go/resources/completions/methods/create/index.md +0 −329 deleted
File Deleted View Diff
1## Create completion
2
3`client.Completions.New(ctx, body) (*Completion, error)`
4
5**post** `/completions`
6
7Creates a completion for the provided prompt and parameters.
8
9Returns a completion object, or a sequence of completion objects if the request is streamed.
10
11### Parameters
12
13- `body CompletionNewParams`
14
15 - `Model param.Field[CompletionNewParamsModel]`
16
17 ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.
18
19 - `string`
20
21 - `CompletionNewParamsModel`
22
23 - `const CompletionNewParamsModelGPT3_5TurboInstruct CompletionNewParamsModel = "gpt-3.5-turbo-instruct"`
24
25 - `const CompletionNewParamsModelDavinci002 CompletionNewParamsModel = "davinci-002"`
26
27 - `const CompletionNewParamsModelBabbage002 CompletionNewParamsModel = "babbage-002"`
28
29 - `Prompt param.Field[CompletionNewParamsPromptUnion]`
30
31 The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.
32
33 Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.
34
35 - `string`
36
37 - `[]string`
38
39 - `[]int64`
40
41 - `[][]int64`
42
43 - `BestOf param.Field[int64]`
44
45 Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed.
46
47 When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.
48
49 **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.
50
51 - `Echo param.Field[bool]`
52
53 Echo back the prompt in addition to the completion
54
55 - `FrequencyPenalty param.Field[float64]`
56
57 Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
58
59 [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
60
61 - `LogitBias param.Field[map[string, int64]]`
62
63 Modify the likelihood of specified tokens appearing in the completion.
64
65 Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
66
67 As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated.
68
69 - `Logprobs param.Field[int64]`
70
71 Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.
72
73 The maximum value for `logprobs` is 5.
74
75 - `MaxTokens param.Field[int64]`
76
77 The maximum number of [tokens](/tokenizer) that can be generated in the completion.
78
79 The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.
80
81 - `N param.Field[int64]`
82
83 How many completions to generate for each prompt.
84
85 **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.
86
87 - `PresencePenalty param.Field[float64]`
88
89 Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
90
91 [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
92
93 - `Seed param.Field[int64]`
94
95 If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.
96
97 Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
98
99 - `Stop param.Field[CompletionNewParamsStopUnion]`
100
101 Not supported with latest reasoning models `o3` and `o4-mini`.
102
103 Up to 4 sequences where the API will stop generating further tokens. The
104 returned text will not contain the stop sequence.
105
106 - `string`
107
108 - `[]string`
109
110 - ``
111
112 - `StreamOptions param.Field[ChatCompletionStreamOptions]`
113
114 Options for streaming response. Only set this when you set `stream: true`.
115
116 - `Suffix param.Field[string]`
117
118 The suffix that comes after a completion of inserted text.
119
120 This parameter is only supported for `gpt-3.5-turbo-instruct`.
121
122 - `Temperature param.Field[float64]`
123
124 What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
125
126 We generally recommend altering this or `top_p` but not both.
127
128 - `TopP param.Field[float64]`
129
130 An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
131
132 We generally recommend altering this or `temperature` but not both.
133
134 - `User param.Field[string]`
135
136 A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
137
138### Returns
139
140- `type Completion struct{…}`
141
142 Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint).
143
144 - `ID string`
145
146 A unique identifier for the completion.
147
148 - `Choices []CompletionChoice`
149
150 The list of completion choices the model generated for the input prompt.
151
152 - `FinishReason CompletionChoiceFinishReason`
153
154 The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
155 `length` if the maximum number of tokens specified in the request was reached,
156 or `content_filter` if content was omitted due to a flag from our content filters.
157
158 - `const CompletionChoiceFinishReasonStop CompletionChoiceFinishReason = "stop"`
159
160 - `const CompletionChoiceFinishReasonLength CompletionChoiceFinishReason = "length"`
161
162 - `const CompletionChoiceFinishReasonContentFilter CompletionChoiceFinishReason = "content_filter"`
163
164 - `Index int64`
165
166 - `Logprobs CompletionChoiceLogprobs`
167
168 - `TextOffset []int64`
169
170 - `TokenLogprobs []float64`
171
172 - `Tokens []string`
173
174 - `TopLogprobs []map[string, float64]`
175
176 - `Text string`
177
178 - `Created int64`
179
180 The Unix timestamp (in seconds) of when the completion was created.
181
182 - `Model string`
183
184 The model used for completion.
185
186 - `Object TextCompletion`
187
188 The object type, which is always "text_completion"
189
190 - `const TextCompletionTextCompletion TextCompletion = "text_completion"`
191
192 - `SystemFingerprint string`
193
194 This fingerprint represents the backend configuration that the model runs with.
195
196 Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
197
198 - `Usage CompletionUsage`
199
200 Usage statistics for the completion request.
201
202 - `CompletionTokens int64`
203
204 Number of tokens in the generated completion.
205
206 - `PromptTokens int64`
207
208 Number of tokens in the prompt.
209
210 - `TotalTokens int64`
211
212 Total number of tokens used in the request (prompt + completion).
213
214 - `CompletionTokensDetails CompletionUsageCompletionTokensDetails`
215
216 Breakdown of tokens used in a completion.
217
218 - `AcceptedPredictionTokens int64`
219
220 When using Predicted Outputs, the number of tokens in the
221 prediction that appeared in the completion.
222
223 - `AudioTokens int64`
224
225 Audio input tokens generated by the model.
226
227 - `ReasoningTokens int64`
228
229 Tokens generated by the model for reasoning.
230
231 - `RejectedPredictionTokens int64`
232
233 When using Predicted Outputs, the number of tokens in the
234 prediction that did not appear in the completion. However, like
235 reasoning tokens, these tokens are still counted in the total
236 completion tokens for purposes of billing, output, and context window
237 limits.
238
239 - `PromptTokensDetails CompletionUsagePromptTokensDetails`
240
241 Breakdown of tokens used in the prompt.
242
243 - `AudioTokens int64`
244
245 Audio input tokens present in the prompt.
246
247 - `CachedTokens int64`
248
249 Cached tokens present in the prompt.
250
251### Example
252
253```go
254package main
255
256import (
257 "context"
258 "fmt"
259
260 "github.com/openai/openai-go"
261 "github.com/openai/openai-go/option"
262)
263
264func main() {
265 client := openai.NewClient(
266 option.WithAPIKey("My API Key"),
267 )
268 completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{
269 Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct,
270 Prompt: openai.CompletionNewParamsPromptUnion{
271 OfString: openai.String("This is a test."),
272 },
273 })
274 if err != nil {
275 panic(err.Error())
276 }
277 fmt.Printf("%+v\n", completion)
278}
279```
280
281#### Response
282
283```json
284{
285 "id": "id",
286 "choices": [
287 {
288 "finish_reason": "stop",
289 "index": 0,
290 "logprobs": {
291 "text_offset": [
292 0
293 ],
294 "token_logprobs": [
295 0
296 ],
297 "tokens": [
298 "string"
299 ],
300 "top_logprobs": [
301 {
302 "foo": 0
303 }
304 ]
305 },
306 "text": "text"
307 }
308 ],
309 "created": 0,
310 "model": "model",
311 "object": "text_completion",
312 "system_fingerprint": "system_fingerprint",
313 "usage": {
314 "completion_tokens": 0,
315 "prompt_tokens": 0,
316 "total_tokens": 0,
317 "completion_tokens_details": {
318 "accepted_prediction_tokens": 0,
319 "audio_tokens": 0,
320 "reasoning_tokens": 0,
321 "rejected_prediction_tokens": 0
322 },
323 "prompt_tokens_details": {
324 "audio_tokens": 0,
325 "cached_tokens": 0
326 }
327 }
328}
329```