1# Assistants migration guide
2
3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.1> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.
4 2
5The Assistants API was officially sunset on August 26, 2026, and is no longer available. Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for new integrations.3## Modify assistant
6 4
5**post** `/assistants/{assistant_id}`
7 6
7Modifies an assistant.
8 8
9### Path Parameters
9 10
10Thank you to everyone who used the Assistants API. We appreciate everything you built and the feedback you shared along the way.11- `assistant_id: string`
11 12
12Use this guide to migrate your integration to the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses).13### Body Parameters
13 14
14Responses are simpler—send input items and get output items back. With the Responses API, you also get better performance and new features like [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [MCP](https://developers.openai.com/api/docs/guides/tools-connectors-mcp), and [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use). This change also lets you manage conversations instead of passing back `previous_response_id`.15- `description: optional string or null`
15 16
16### What's changed?17 The description of the assistant. The maximum length is 512 characters.
17 18
18<table>19 `maxLength: 512`
19 <thead>
20 <tr>
21 <th>Before</th>
22 <th>Now</th>
23 <th>Why?</th>
24 </tr>
25 </thead>
26 <tbody>
27 <tr>
28 <td>`Assistants`</td>
29 <td>`Prompts`</td>
30 <td>
31 Prompts hold configuration (model, tools, instructions) and are easier
32 to version and update
33 </td>
34 </tr>
35 <tr>
36 <td>`Threads`</td>
37 <td>`Conversations`</td>
38 <td>Streams of items instead of just messages</td>
39 </tr>
40 <tr>
41 <td>`Runs`</td>
42 <td>`Responses`</td>
43 <td>
44 Responses send input items or use a conversation object and receive
45 output items; tool call loops are explicitly managed
46 </td>
47 </tr>
48 <tr>
49 <td>`Run steps`</td>
50 <td>`Items`</td>
51 <td>
52 Generalized objects—can be messages, tool calls, outputs, and more
53 </td>
54 </tr>
55 </tbody>
56</table>
57 20
58## From assistants to prompts21- `instructions: optional string or null`
59 22
60Assistants were persistent API objects that bundled model choice, instructions, and tool declarations—created and managed entirely through the API. Their replacement, prompts, can only be created in the dashboard, where you can version them as you develop your product.23 The system instructions that the assistant uses. The maximum length is 256,000 characters.
61 24
62### Why this is helpful25 `maxLength: 256000`
63 26
64- **Portability and versioning**: You can snapshot, review, diff, and roll back prompt specs. You can also version a prompt, so your code can just point the latest version.27- `metadata: optional Metadata or null`
65- **Separation of concerns**: Your application code now handles orchestration (history pruning, tool loop, retries) while your prompt focuses on high‑level behavior and constraints (system guidance, tool availability, structured output schema, temperature defaults).
66- **Realtime compatibility**: The same prompt configuration can be reused when you connect through the Realtime API, giving you a single definition of behavior across chat, streaming, and low‑latency interactive sessions.
67- **Tool and output consistency**: Using prompts, every Responses or Realtime session you start inherits a consistent contract because prompts encapsulate tool schemas and structured output expectations.
68 28
69### Practical migration steps29 Set of 16 key-value pairs that can be attached to an object. This can be
30 useful for storing additional information about the object in a structured
31 format, and querying for objects via API or the dashboard.
70 32
711. Identify each existing Assistant’s _instruction + tool_ bundle.33 Keys are strings with a maximum length of 64 characters. Values are strings
722. In the dashboard, recreate that bundle as a named prompt.34 with a maximum length of 512 characters.
733. Store the prompt ID (or its exported spec) in source control so application code can refer to a stable identifier.
744. During rollout, run A/B tests by swapping prompt IDs—no need to create or delete assistant objects programmatically.
75 35
76Think of a prompt as a **versioned behavioral profile** to plug into either Responses or Realtime API.36- `model: optional string or "gpt-5" or "gpt-5-mini" or "gpt-5-nano" or 39 more`
77 37
38 ID of the model to use. You can use the [List models](/api/reference/resources/models/methods/list) API to see all of your available models, or see our [Model overview](/api/docs/models) for descriptions of them.
78 39
79## From threads to conversations40 - `string`
80 41
81A thread was a collection of messages stored server-side. Threads could _only_ store messages. Conversations store items, which can include messages, tool calls, tool outputs, and other data.42 - `AssistantSupportedModels = "gpt-5" or "gpt-5-mini" or "gpt-5-nano" or 39 more`
82 43
83### Request example44 ID of the model to use. You can use the [List models](/api/reference/resources/models/methods/list) API to see all of your available models, or see our [Model overview](/api/docs/models) for descriptions of them.
84 45
85#### Python46 - `"gpt-5"`
86 47
48 - `"gpt-5-mini"`
87 49
50 - `"gpt-5-nano"`
88 51
89#### Thread object52 - `"gpt-5-2025-08-07"`
90 53
91```python54 - `"gpt-5-mini-2025-08-07"`
92thread = openai.beta.threads.create(
93 messages=[{"role": "user", "content": "what are the 5 Ds of dodgeball?"}],
94 metadata={"user_id": "peter_le_fleur"},
95)
96```
97 55
98#### Conversation object56 - `"gpt-5-nano-2025-08-07"`
99 57
100```python58 - `"gpt-4.1"`
101conversation = openai.conversations.create(
102 items=[{"role": "user", "content": "what are the 5 Ds of dodgeball?"}],
103 metadata={"user_id": "peter_le_fleur"},
104)
105```
106 59
60 - `"gpt-4.1-mini"`
107 61
62 - `"gpt-4.1-nano"`
108 63
109#### Go64 - `"gpt-4.1-2025-04-14"`
110 65
66 - `"gpt-4.1-mini-2025-04-14"`
111 67
68 - `"gpt-4.1-nano-2025-04-14"`
112 69
113#### Thread object (Go)70 - `"o3-mini"`
114 71
115```go72 - `"o3-mini-2025-01-31"`
116thread, err := client.Beta.Threads.New(context.Background(), openai.BetaThreadNewParams{
117 Messages: []openai.BetaThreadNewParamsMessage{{
118 Role: "user",
119 Content: openai.BetaThreadNewParamsMessageContentUnion{
120 OfString: openai.String("what are the 5 Ds of dodgeball?"),
121 },
122 }},
123 Metadata: shared.Metadata{"user_id": "peter_le_fleur"},
124})
125if err != nil {
126 panic(err)
127}
128```
129 73
130#### Conversation object (Go)74 - `"o1"`
131 75
132```go76 - `"o1-2024-12-17"`
133conversation, err := client.Conversations.New(context.Background(), conversations.ConversationNewParams{
134 Items: []responses.ResponseInputItemUnionParam{
135 responses.ResponseInputItemParamOfMessage("what are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),
136 },
137 Metadata: shared.Metadata{"user_id": "peter_le_fleur"},
138})
139if err != nil {
140 panic(err)
141}
142```
143 77
78 - `"gpt-4o"`
144 79
80 - `"gpt-4o-2024-11-20"`
145 81
146#### JavaScript82 - `"gpt-4o-2024-08-06"`
147 83
84 - `"gpt-4o-2024-05-13"`
148 85
86 - `"gpt-4o-mini"`
149 87
150#### Thread object (JavaScript)88 - `"gpt-4o-mini-2024-07-18"`
151 89
152```javascript90 - `"gpt-4.5-preview"`
153import OpenAI from "openai";
154 91
155const client = new OpenAI();92 - `"gpt-4.5-preview-2025-02-27"`
156const thread = await client.beta.threads.create({
157 messages: [{ role: "user", content: "what are the 5 Ds of dodgeball?" }],
158 metadata: { user_id: "peter_le_fleur" },
159});
160console.log(thread.id);
161```
162 93
163#### Conversation object (JavaScript)94 - `"gpt-4-turbo"`
164 95
165```javascript96 - `"gpt-4-turbo-2024-04-09"`
166import OpenAI from "openai";
167 97
168const client = new OpenAI();98 - `"gpt-4-0125-preview"`
169 99
170const conversation = await client.conversations.create({100 - `"gpt-4-turbo-preview"`
171 items: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
172 metadata: { user_id: "peter_le_fleur" },
173});
174 101
175console.log(conversation.id);102 - `"gpt-4-1106-preview"`
176```
177 103
104 - `"gpt-4-vision-preview"`
178 105
106 - `"gpt-4"`
179 107
180### Response example108 - `"gpt-4-0314"`
181 109
110 - `"gpt-4-0613"`
182 111
112 - `"gpt-4-32k"`
183 113
184#### Thread object114 - `"gpt-4-32k-0314"`
185 115
186```json116 - `"gpt-4-32k-0613"`
187{
188 "id": "thread_CrXtCzcyEQbkAcXuNmVSKFs1",
189 "object": "thread",
190 "created_at": 1752855924,
191 "metadata": {
192 "user_id": "peter_le_fleur"
193 },
194 "tool_resources": {}
195}
196```
197 117
198#### Conversation object118 - `"gpt-3.5-turbo"`
199 119
200```json120 - `"gpt-3.5-turbo-16k"`
201{
202 "id": "conv_68542dc602388199a30af27d040cefd4087a04b576bfeb24",
203 "object": "conversation",
204 "created_at": 1752855924,
205 "metadata": {
206 "user_id": "peter_le_fleur"
207 }
208}
209```
210 121
122 - `"gpt-3.5-turbo-0613"`
211 123
124 - `"gpt-3.5-turbo-1106"`
212 125
126 - `"gpt-3.5-turbo-0125"`
213 127
214## From runs to responses128 - `"gpt-3.5-turbo-16k-0613"`
215 129
216Runs were asynchronous processes that executed against threads. See the example below. Responses are simpler: provide a set of input items to execute, and get a list of output items back.130- `name: optional string or null`
217 131
218Responses are designed to be used alone, but you can also use them with prompt and conversation objects for storing context and configuration.132 The name of the assistant. The maximum length is 256 characters.
219 133
220### Request example134 `maxLength: 256`
221 135
222#### Python136- `reasoning_effort: optional ReasoningEffort or null`
223 137
138 Constrains effort on reasoning for reasoning models. Currently supported
139 values are `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`.
140 Reducing reasoning effort can result in faster responses and fewer tokens
141 used on reasoning in a response. Not all reasoning models support every
142 value. See the
143 [reasoning guide](/api/docs/guides/reasoning)
144 for model-specific support.
224 145
146 - `"none"`
225 147
226#### Run object148 - `"minimal"`
227 149
228```python150 - `"low"`
229# Replace the illustrative IDs and URLs below with your own resource values.
230import time
231 151
232from openai import OpenAI152 - `"medium"`
233 153
234openai = OpenAI()154 - `"high"`
235thread_id = "thread_123"
236assistant_id = "asst_123"
237 155
238run = openai.beta.threads.runs.create(156 - `"xhigh"`
239 thread_id=thread_id,
240 assistant_id=assistant_id,
241)
242 157
243while run.status in ("queued", "in_progress"):158 - `"max"`
244 time.sleep(1)
245 run = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
246```
247 159
248#### Response object160- `response_format: optional AssistantResponseFormatOption or null`
249 161
250```python162 Specifies the format that the model must output. Compatible with [GPT-4o](/api/docs/models/gpt-4o), [GPT-4 Turbo](/api/docs/models/gpt-4-turbo), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
251# Replace the illustrative IDs and URLs below with your own resource values.
252 163
253from openai import OpenAI164 Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/api/docs/guides/structured-outputs).
254 165
255openai = OpenAI()166 Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON.
256conversation_id = "conv_123"
257 167
258response = openai.responses.create(168 **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.
259 model="gpt-6-astra",
260 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],
261 conversation=conversation_id,
262)
263```
264 169
170 - `"auto"`
265 171
172 `auto` is the default value
266 173
267#### Go174 - `"auto"`
268 175
176 - `ResponseFormatText object { type }`
269 177
178 Default response format. Used to generate text responses.
270 179
271#### Run object (Go)180 - `type: "text"`
272 181
273```go182 The type of response format being defined. Always `text`.
274run, err := client.Beta.Threads.Runs.New(context.Background(), "thread_abc123", openai.BetaThreadRunNewParams{
275 AssistantID: "asst_abc123",
276})
277if err != nil {
278 panic(err)
279}
280for run.Status == openai.RunStatusQueued || run.Status == openai.RunStatusInProgress {
281 time.Sleep(time.Second)
282 run, err = client.Beta.Threads.Runs.Get(context.Background(), "thread_abc123", run.ID)
283 if err != nil {
284 panic(err)
285 }
286}
287```
288 183
289#### Response object (Go)184 - `"text"`
290
291```go
292_, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
293 Model: "gpt-6-astra",
294 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
295 responses.ResponseInputItemParamOfMessage("What are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),
296 }},
297 Conversation: responses.ResponseNewParamsConversationUnion{OfString: openai.String("conv_abc123")},
298})
299if err != nil {
300 panic(err)
301}
302```
303 185
186 - `ResponseFormatJSONObject object { type }`
304 187
188 JSON object response format. An older method of generating JSON responses.
189 Using `json_schema` is recommended for models that support it. Note that the
190 model will not generate JSON without a system or user message instructing it
191 to do so.
305 192
306#### JavaScript193 - `type: "json_object"`
307 194
195 The type of response format being defined. Always `json_object`.
308 196
197 - `"json_object"`
309 198
310#### Run object (JavaScript)199 - `ResponseFormatJSONSchema object { json_schema, type }`
311 200
312```javascript201 JSON Schema response format. Used to generate structured JSON responses.
313import { setTimeout } from "node:timers/promises";202 Learn more about [Structured Outputs](/api/docs/guides/structured-outputs).
314import OpenAI from "openai";
315 203
316const client = new OpenAI();204 - `json_schema: object { name, description, schema, strict }`
317// Replace these illustrative IDs with your own resources.
318const threadId = "thread_123";
319const assistantId = "asst_123";
320let run = await client.beta.threads.runs.create(threadId, {
321 assistant_id: assistantId,
322});
323while (run.status === "queued" || run.status === "in_progress") {
324 await setTimeout(1000);
325 run = await client.beta.threads.runs.retrieve(run.id, {
326 thread_id: threadId,
327 });
328}
329console.log(run.status);
330```
331 205
332#### Response object (JavaScript)206 Structured Outputs configuration options, including a JSON Schema.
333 207
334```javascript208 - `name: string`
335// Replace the illustrative IDs and URLs below with your own resource values.
336import OpenAI from "openai";
337 209
338const client = new OpenAI();210 The name of the response format. Must be a-z, A-Z, 0-9, or contain
339const conversationId = "conv_123";211 underscores and dashes, with a maximum length of 64.
340 212
341const response = await client.responses.create({213 - `description: optional string`
342 model: "gpt-6-astra",
343 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
344 conversation: conversationId,
345});
346 214
347console.log(response.output_text);215 A description of what the response format is for, used by the model to
348```216 determine how to respond in the format.
349 217
218 - `schema: optional map[unknown]`
350 219
220 The schema for the response format, described as a JSON Schema object.
221 Learn how to build JSON schemas [here](https://json-schema.org/).
351 222
352### Response example223 - `strict: optional boolean or null`
353 224
225 Whether to enable strict schema adherence when generating the output.
226 If set to true, the model will always follow the exact schema defined
227 in the `schema` field. Only a subset of JSON Schema is supported when
228 `strict` is `true`. To learn more, read the [Structured Outputs
229 guide](/api/docs/guides/structured-outputs).
354 230
231 - `type: "json_schema"`
355 232
356#### Run object233 The type of response format being defined. Always `json_schema`.
357 234
358```json235 - `"json_schema"`
359{
360 "id": "run_FKIpcs5ECSwuCmehBqsqkORj",
361 "assistant_id": "asst_8fVY45hU3IM6creFkVi5MBKB",
362 "cancelled_at": null,
363 "completed_at": 1752857327,
364 "created_at": 1752857322,
365 "expires_at": null,
366 "failed_at": null,
367 "incomplete_details": null,
368 "instructions": null,
369 "last_error": null,
370 "max_completion_tokens": null,
371 "max_prompt_tokens": null,
372 "metadata": {},
373 "model": "gpt-4.1",
374 "object": "thread.run",
375 "parallel_tool_calls": true,
376 "required_action": null,
377 "response_format": "auto",
378 "started_at": 1752857324,
379 "status": "completed",
380 "thread_id": "thread_CrXtCzcyEQbkAcXuNmVSKFs1",
381 "tool_choice": "auto",
382 "tools": [],
383 "truncation_strategy": {
384 "type": "auto",
385 "last_messages": null
386 },
387 "usage": {
388 "completion_tokens": 130,
389 "prompt_tokens": 34,
390 "total_tokens": 164,
391 "prompt_token_details": {
392 "cached_tokens": 0
393 },
394 "completion_tokens_details": {
395 "reasoning_tokens": 0
396 }
397 },
398 "temperature": 1.0,
399 "top_p": 1.0,
400 "tool_resources": {},
401 "reasoning_effort": null
402}
403```
404 236
405#### Response object237- `temperature: optional number or null`
406 238
407```json239 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.
408{
409 "id": "resp_687a7b53036c819baad6012d58b39bcb074adcd9e24850fc",
410 "created_at": 1752857427,
411 "conversation": {
412 "id": "conv_689667905b048191b4740501625afd940c7533ace33a2dab"
413 },
414 "error": null,
415 "incomplete_details": null,
416 "instructions": null,
417 "metadata": {},
418 "model": "gpt-5.5",
419 "object": "response",
420 "output": [
421 {
422 "id": "msg_687a7b542948819ba79e77e14791ef83074adcd9e24850fc",
423 "content": [
424 {
425 "annotations": [],
426 "text": "The \"5 Ds of Dodgeball\" are a humorous set of rules made famous by the 2004 comedy film **\"Dodgeball: A True Underdog Story.\"** In the movie, dodgeball coach Patches O’Houlihan teaches these basics to his team. The **5 Ds** are:\n\n1. **Dodge**\n2. **Duck**\n3. **Dip**\n4. **Dive**\n5. **Dodge** (yes, dodge is listed twice for emphasis!)\n\nIn summary: \n> **“If you can dodge a wrench, you can dodge a ball!”**\n\nThese 5 Ds are not official competitive rules, but have become a fun and memorable pop culture reference for the sport of dodgeball.",
427 "type": "output_text",
428 "logprobs": []
429 }
430 ],
431 "role": "assistant",
432 "status": "completed",
433 "type": "message"
434 }
435 ],
436 "parallel_tool_calls": true,
437 "temperature": 1.0,
438 "tool_choice": "auto",
439 "tools": [],
440 "top_p": 1.0,
441 "background": false,
442 "max_output_tokens": null,
443 "previous_response_id": null,
444 "reasoning": {
445 "effort": null,
446 "generate_summary": null,
447 "summary": null
448 },
449 "service_tier": "scale",
450 "status": "completed",
451 "text": {
452 "format": {
453 "type": "text"
454 }
455 },
456 "truncation": "disabled",
457 "usage": {
458 "input_tokens": 17,
459 "input_tokens_details": {
460 "cached_tokens": 0
461 },
462 "output_tokens": 150,
463 "output_tokens_details": {
464 "reasoning_tokens": 0
465 },
466 "total_tokens": 167
467 },
468 "user": null,
469 "max_tool_calls": null,
470 "store": true,
471 "top_logprobs": 0
472}
473```
474 240
241 `minimum: 0`, `maximum: 2`
475 242
243- `tool_resources: optional object { code_interpreter, file_search } or null`
476 244
245 A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.
477 246
478## Migrating your integration247 - `code_interpreter: optional object { file_ids }`
479 248
480Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.249 - `file_ids: optional array of string`
481 250
482### 1. Create prompts from your assistants251 Overrides the list of [file](/api/reference/resources/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.
483 252
4841. Identify the most important assistant objects in your application.253 `maxItems: 20`
4851. Find these in the dashboard and click `Create prompt`.
486 254
487This will create a prompt object out of each existing assistant object.255 - `file_search: optional object { vector_store_ids }`
488 256
489Reusable prompt objects are also being deprecated. If you use this migration257 - `vector_store_ids: optional array of string`
490 path, review the [prompts deprecation
491 timeline](https://developers.openai.com/api/docs/deprecations#2026-06-03-reusable-prompts) before adopting
492 prompt objects in a long-lived integration.
493 258
494### 2. Move new user chats over to conversations and responses259 Overrides the [vector store](/api/reference/resources/vector_stores) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.
495 260
496Start new chats with the Conversations API and Responses API. To preserve earlier conversation history, use messages already stored by your application.261 `maxItems: 1`
497 262
498The example below shows how thread history could be migrated before the sunset. The Assistants API call that retrieves thread messages no longer works; use your stored messages instead.263- `tools: optional array of CodeInterpreterTool or FileSearchTool or FunctionTool`
499 264
500```python265 A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.
501# Replace the illustrative IDs and URLs below with your own resource values.
502 266
503from openai import OpenAI267 `maxItems: 128`
504 268
505openai = OpenAI()269 - `CodeInterpreterTool object { type }`
506messages = []
507thread_id = "thread_123"
508 270
509for page in openai.beta.threads.messages.list(271 - `type: "code_interpreter"`
510 thread_id=thread_id, order="asc"
511).iter_pages():
512 messages += page.data
513 272
514items = []273 The type of tool being defined: `code_interpreter`
515for m in messages:
516 item = {"role": m.role}
517 item_content = []
518 274
519 for content in m.content:275 - `"code_interpreter"`
520 match content.type:
521 case "text":
522 item_content_type = "input_text" if m.role == "user" else "output_text"
523 item_content += [
524 {"type": item_content_type, "text": content.text.value}
525 ]
526 case "image_url":
527 item_content += [
528 {
529 "type": "input_image",
530 "image_url": content.image_url.url,
531 "detail": content.image_url.detail,
532 }
533 ]
534 276
535 item |= {"content": item_content}277 - `FileSearchTool object { type, file_search }`
536 items.append(item)
537 278
538# create a conversation with your converted items279 - `type: "file_search"`
539conversation = openai.conversations.create(items=items)
540```
541 280
542```ruby281 The type of tool being defined: `file_search`
543# Replace the illustrative IDs and URLs below with your own resource values.
544require "openai"
545
546client = OpenAI::Client.new
547thread_id = "thread_123"
548messages = client.beta.threads.messages.list(thread_id, order: :asc)
549items = []
550messages.auto_paging_each do |message|
551 content = message.content.filter_map do |part|
552 case part
553 when OpenAI::Models::Beta::Threads::TextContentBlock
554 type = if message.role == OpenAI::Models::Beta::Threads::Message::Role::USER
555 :input_text
556 else
557 :output_text
558 end
559 {
560 type: type,
561 text: part.text.value
562 }
563 when OpenAI::Models::Beta::Threads::ImageURLContentBlock
564 {
565 type: :input_image,
566 image_url: part.image_url.url,
567 detail: part.image_url.detail
568 }
569 end
570 end
571 items << {
572 role: message.role,
573 content: content
574 }
575end
576conversation = client.conversations.create(
577 items: items
578)
579puts(conversation.id)
580```
581 282
283 - `"file_search"`
582 284
583## Comparing full examples285 - `file_search: optional object { max_num_results, ranking_options }`
584 286
585Here are a few examples of integrations using both the Assistants API and the Responses API so you can see how they compare.287 Overrides for the file search tool.
586 288
587### User chat app289 - `max_num_results: optional number`
588 290
291 The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.
589 292
293 Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/api/docs/guides/tools-file-search#retrieval-customization) for more information.
590 294
591Assistants API295 `minimum: 1`, `maximum: 50`
592 296
593```python297 - `ranking_options: optional object { score_threshold, ranker }`
594# Replace the illustrative IDs and URLs below with your own resource values.
595threads_by_session: dict[str, str] = {}
596 298
299 The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0.
597 300
598@app.post("/messages")301 See the [file search tool documentation](/api/docs/guides/tools-file-search#retrieval-customization) for more information.
599async def message(message: Message):
600 thread_id = threads_by_session.get(message.session_id)
601 if thread_id is None:
602 thread_id = openai.beta.threads.create().id
603 threads_by_session[message.session_id] = thread_id
604 302
605 openai.beta.threads.messages.create(303 - `score_threshold: number`
606 thread_id=thread_id,
607 role="user",
608 content=message.content,
609 )
610 304
611 example_assistant_id = "asst_123"305 The score threshold for the file search. All values must be a floating point number between 0 and 1.
612 run = openai.beta.threads.runs.create(
613 assistant_id=example_assistant_id,
614 thread_id=thread_id,
615 )
616 while run.status in ("queued", "in_progress"):
617 await asyncio.sleep(1)
618 run = openai.beta.threads.runs.retrieve(
619 thread_id=thread_id,
620 run_id=run.id,
621 )
622 306
623 messages = openai.beta.threads.messages.list(307 `minimum: 0`, `maximum: 1`
624 order="desc",
625 limit=1,
626 thread_id=thread_id,
627 )
628 308
629 return {"content": messages.data[0].content}309 - `ranker: optional "auto" or "default_2024_08_21"`
630```
631 310
632```ruby311 The ranker to use for the file search. If not specified will use the `auto` ranker.
633# Replace the illustrative IDs and URLs below with your own resource values.
634require "openai"
635
636client = OpenAI::Client.new
637assistant_id = "asst_123"
638threads_by_session = {}
639
640handle_message = lambda do |session_id:, content:|
641 thread_id = threads_by_session[session_id]
642 unless thread_id
643 thread_id = client.beta.threads.create.id
644 threads_by_session[session_id] = thread_id
645 end
646
647 client.beta.threads.messages.create(
648 thread_id,
649 role: :user,
650 content: content
651 )
652 run = client.beta.threads.runs.create(
653 thread_id,
654 assistant_id: assistant_id
655 )
656 while [:queued, :in_progress].include?(run.status)
657 sleep(1)
658 run = client.beta.threads.runs.retrieve(run.id, thread_id: thread_id)
659 end
660
661 messages = client.beta.threads.messages.list(
662 thread_id,
663 order: :desc,
664 limit: 1
665 )
666 { content: messages.data&.first&.content }
667end
668
669puts(
670 handle_message.call(
671 session_id: "example-session",
672 content: "What are the five Ds of dodgeball?"
673 )
674)
675```
676 312
313 - `"auto"`
677 314
315 - `"default_2024_08_21"`
678 316
317 - `FunctionTool object { function, type }`
679 318
319 - `function: FunctionDefinition`
680 320
321 - `name: string`
681 322
323 The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
682 324
683Responses API325 - `description: optional string`
684 326
685```javascript327 A description of what the function does, used by the model to choose when and how to call the function.
686// Replace the illustrative IDs and URLs below with your own resource values.
687import express from "express";
688import OpenAI from "openai";
689 328
690const app = express();329 - `parameters: optional FunctionParameters`
691const client = new OpenAI();
692const conversationsBySession = new Map();
693 330
694app.use(express.json());331 The parameters the functions accepts, described as a JSON Schema object. See the [guide](/api/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.
695 332
696app.post("/messages", async (request, response) => {333 Omitting `parameters` defines a function with an empty parameter list.
697 const { content, session_id: sessionId } = request.body ?? {};
698 if (
699 typeof content !== "string" ||
700 !content.trim() ||
701 typeof sessionId !== "string" ||
702 !sessionId.trim()
703 ) {
704 response.status(400).json({
705 error: "content and session_id must be non-empty strings.",
706 });
707 return;
708 }
709 334
710 let conversationIdPromise = conversationsBySession.get(sessionId);335 - `strict: optional boolean or null`
711
712 if (!conversationIdPromise) {
713 conversationIdPromise = client.conversations
714 .create()
715 .then((conversation) => conversation.id)
716 .catch((error) => {
717 conversationsBySession.delete(sessionId);
718 throw error;
719 });
720 conversationsBySession.set(sessionId, conversationIdPromise);
721 }
722 const conversationId = await conversationIdPromise;
723 336
724 const promptId = "pmpt_123";337 Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](/api/docs/guides/function-calling).
725 338
726 const result = await client.responses.create({339 - `type: "function"`
727 prompt: { id: promptId },
728 input: [{ role: "user", content }],
729 conversation: conversationId,
730 });
731 340
732 response.json({ content: result.output_text });341 The type of tool being defined: `function`
733});
734 342
735app.listen(Number(process.env.OPENAI_EXAMPLE_PORT ?? 8000), "127.0.0.1");343 - `"function"`
736```344
345- `top_p: optional number or null`
346
347 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.
348
349 We generally recommend altering this or temperature but not both.
350
351 `minimum: 0`, `maximum: 1`
352
353### Returns
354
355- `Assistant object { id, created_at, description, 10 more }`
356
357 Represents an `assistant` that can call the model and use tools.
358
359 - `id: string`
360
361 The identifier, which can be referenced in API endpoints.
362
363 - `created_at: number`
364
365 The Unix timestamp (in seconds) for when the assistant was created.
366
367 `format: unixtime`
368
369 - `description: string or null`
370
371 The description of the assistant. The maximum length is 512 characters.
372
373 `maxLength: 512`
374
375 - `instructions: string or null`
376
377 The system instructions that the assistant uses. The maximum length is 256,000 characters.
378
379 `maxLength: 256000`
380
381 - `metadata: Metadata or null`
382
383 Set of 16 key-value pairs that can be attached to an object. This can be
384 useful for storing additional information about the object in a structured
385 format, and querying for objects via API or the dashboard.
386
387 Keys are strings with a maximum length of 64 characters. Values are strings
388 with a maximum length of 512 characters.
389
390 - `model: string`
391
392 ID of the model to use. You can use the [List models](/api/reference/resources/models/methods/list) API to see all of your available models, or see our [Model overview](/api/docs/models) for descriptions of them.
393
394 - `name: string or null`
395
396 The name of the assistant. The maximum length is 256 characters.
397
398 `maxLength: 256`
399
400 - `object: "assistant"`
401
402 The object type, which is always `assistant`.
403
404 - `"assistant"`
405
406 - `tools: array of CodeInterpreterTool or FileSearchTool or FunctionTool`
407
408 A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.
409
410 `maxItems: 128`
411
412 - `CodeInterpreterTool object { type }`
413
414 - `type: "code_interpreter"`
415
416 The type of tool being defined: `code_interpreter`
737 417
738```python418 - `"code_interpreter"`
739# Replace the illustrative IDs and URLs below with your own resource values.
740conversations_by_session: dict[str, str] = {}
741 419
420 - `FileSearchTool object { type, file_search }`
742 421
743@app.post("/messages")422 - `type: "file_search"`
744async def message(message: Message):
745 conversation_id = conversations_by_session.get(message.session_id)
746 if conversation_id is None:
747 conversation_id = openai.conversations.create().id
748 conversations_by_session[message.session_id] = conversation_id
749 423
750 example_prompt_id = "pmpt_123"424 The type of tool being defined: `file_search`
751 response = openai.responses.create(
752 prompt={"id": example_prompt_id},
753 input=[{"role": "user", "content": message.content}],
754 conversation=conversation_id,
755 )
756 425
757 return {"content": response.output_text}426 - `"file_search"`
427
428 - `file_search: optional object { max_num_results, ranking_options }`
429
430 Overrides for the file search tool.
431
432 - `max_num_results: optional number`
433
434 The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.
435
436 Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/api/docs/guides/tools-file-search#retrieval-customization) for more information.
437
438 `minimum: 1`, `maximum: 50`
439
440 - `ranking_options: optional object { score_threshold, ranker }`
441
442 The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0.
443
444 See the [file search tool documentation](/api/docs/guides/tools-file-search#retrieval-customization) for more information.
445
446 - `score_threshold: number`
447
448 The score threshold for the file search. All values must be a floating point number between 0 and 1.
449
450 `minimum: 0`, `maximum: 1`
451
452 - `ranker: optional "auto" or "default_2024_08_21"`
453
454 The ranker to use for the file search. If not specified will use the `auto` ranker.
455
456 - `"auto"`
457
458 - `"default_2024_08_21"`
459
460 - `FunctionTool object { function, type }`
461
462 - `function: FunctionDefinition`
463
464 - `name: string`
465
466 The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
467
468 - `description: optional string`
469
470 A description of what the function does, used by the model to choose when and how to call the function.
471
472 - `parameters: optional FunctionParameters`
473
474 The parameters the functions accepts, described as a JSON Schema object. See the [guide](/api/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.
475
476 Omitting `parameters` defines a function with an empty parameter list.
477
478 - `strict: optional boolean or null`
479
480 Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](/api/docs/guides/function-calling).
481
482 - `type: "function"`
483
484 The type of tool being defined: `function`
485
486 - `"function"`
487
488 - `response_format: optional AssistantResponseFormatOption or null`
489
490 Specifies the format that the model must output. Compatible with [GPT-4o](/api/docs/models/gpt-4o), [GPT-4 Turbo](/api/docs/models/gpt-4-turbo), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
491
492 Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/api/docs/guides/structured-outputs).
493
494 Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON.
495
496 **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.
497
498 - `"auto"`
499
500 `auto` is the default value
501
502 - `"auto"`
503
504 - `ResponseFormatText object { type }`
505
506 Default response format. Used to generate text responses.
507
508 - `type: "text"`
509
510 The type of response format being defined. Always `text`.
511
512 - `"text"`
513
514 - `ResponseFormatJSONObject object { type }`
515
516 JSON object response format. An older method of generating JSON responses.
517 Using `json_schema` is recommended for models that support it. Note that the
518 model will not generate JSON without a system or user message instructing it
519 to do so.
520
521 - `type: "json_object"`
522
523 The type of response format being defined. Always `json_object`.
524
525 - `"json_object"`
526
527 - `ResponseFormatJSONSchema object { json_schema, type }`
528
529 JSON Schema response format. Used to generate structured JSON responses.
530 Learn more about [Structured Outputs](/api/docs/guides/structured-outputs).
531
532 - `json_schema: object { name, description, schema, strict }`
533
534 Structured Outputs configuration options, including a JSON Schema.
535
536 - `name: string`
537
538 The name of the response format. Must be a-z, A-Z, 0-9, or contain
539 underscores and dashes, with a maximum length of 64.
540
541 - `description: optional string`
542
543 A description of what the response format is for, used by the model to
544 determine how to respond in the format.
545
546 - `schema: optional map[unknown]`
547
548 The schema for the response format, described as a JSON Schema object.
549 Learn how to build JSON schemas [here](https://json-schema.org/).
550
551 - `strict: optional boolean or null`
552
553 Whether to enable strict schema adherence when generating the output.
554 If set to true, the model will always follow the exact schema defined
555 in the `schema` field. Only a subset of JSON Schema is supported when
556 `strict` is `true`. To learn more, read the [Structured Outputs
557 guide](/api/docs/guides/structured-outputs).
558
559 - `type: "json_schema"`
560
561 The type of response format being defined. Always `json_schema`.
562
563 - `"json_schema"`
564
565 - `temperature: optional number or null`
566
567 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.
568
569 `minimum: 0`, `maximum: 2`
570
571 - `tool_resources: optional object { code_interpreter, file_search } or null`
572
573 A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.
574
575 - `code_interpreter: optional object { file_ids }`
576
577 - `file_ids: optional array of string`
578
579 A list of [file](/api/reference/resources/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.
580
581 `maxItems: 20`
582
583 - `file_search: optional object { vector_store_ids }`
584
585 - `vector_store_ids: optional array of string`
586
587 The ID of the [vector store](/api/reference/resources/vector_stores) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.
588
589 `maxItems: 1`
590
591 - `top_p: optional number or null`
592
593 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.
594
595 We generally recommend altering this or temperature but not both.
596
597 `minimum: 0`, `maximum: 1`
598
599### Example
600
601```http
602curl https://api.openai.com/v1/assistants/$ASSISTANT_ID \
603 -H 'Content-Type: application/json' \
604 -H 'OpenAI-Beta: assistants=v2' \
605 -H "Authorization: Bearer $OPENAI_API_KEY" \
606 -d '{
607 "temperature": 1,
608 "top_p": 1
609 }'
758```610```
759 611
760```go612#### Response
761func main() {
762 client := openai.NewClient()
763 server := &http.Server{
764 Addr: "127.0.0.1:8000",
765 Handler: newChatHandler(client),
766 ReadHeaderTimeout: 5 * time.Second,
767 }
768 log.Fatal(server.ListenAndServe())
769}
770 613
771func newChatHandler(client openai.Client) http.Handler {614```json
772 var mutex sync.Mutex615{
773 type sessionConversation struct {616 "id": "id",
774 ready chan struct{}617 "created_at": 0,
775 id string618 "description": "description",
776 err error619 "instructions": "instructions",
777 responseSlot chan struct{}620 "metadata": {
778 }621 "foo": "string"
779 conversationsBySession := map[string]*sessionConversation{}
780 mux := http.NewServeMux()
781 mux.HandleFunc("POST /messages", func(w http.ResponseWriter, r *http.Request) {
782 var message struct {
783 Content string `json:"content"`
784 SessionID string `json:"session_id"`
785 }
786 if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&message); err != nil || strings.TrimSpace(message.Content) == "" || strings.TrimSpace(message.SessionID) == "" {
787 http.Error(w, "content and session_id must be non-empty strings", 400)
788 return
789 }
790 // A demo session map. Bind session IDs to authenticated users in your application.
791 mutex.Lock()
792 session, exists := conversationsBySession[message.SessionID]
793 if !exists {
794 session = &sessionConversation{ready: make(chan struct{}), responseSlot: make(chan struct{}, 1)}
795 conversationsBySession[message.SessionID] = session
796 }
797 mutex.Unlock()
798 if !exists {
799 go func() {
800 // Creation belongs to the shared session, not the first HTTP request.
801 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
802 defer cancel()
803 conversation, err := client.Conversations.New(ctx, conversations.ConversationNewParams{})
804 session.err = err
805 if err == nil {
806 session.id = conversation.ID
807 }
808 mutex.Lock()
809 if err != nil {
810 delete(conversationsBySession, message.SessionID)
811 }
812 close(session.ready)
813 mutex.Unlock()
814 }()
815 }
816 select {
817 case <-r.Context().Done():
818 http.Error(w, "Request cancelled", http.StatusRequestTimeout)
819 return
820 case <-session.ready:
821 }
822 if session.err != nil {
823 http.Error(w, "Could not create conversation", http.StatusInternalServerError)
824 return
825 }
826 // Serialize responses within this conversation; waiting requests can cancel.
827 select {
828 case session.responseSlot <- struct{}{}:
829 defer func() { <-session.responseSlot }()
830 case <-r.Context().Done():
831 http.Error(w, "Request cancelled", http.StatusRequestTimeout)
832 return
833 }
834 if r.Context().Err() != nil {
835 http.Error(w, "Request cancelled", http.StatusRequestTimeout)
836 return
837 }
838 // Replace this illustrative stored prompt ID with your prompt.
839 result, err := client.Responses.New(r.Context(), responses.ResponseNewParams{
840 Prompt: responses.ResponsePromptParam{
841 ID: "pmpt_123",
842 },
843 Input: responses.ResponseNewParamsInputUnion{
844 OfString: openai.String(message.Content),
845 },
846 Conversation: responses.ResponseNewParamsConversationUnion{
847 OfString: openai.String(session.id),
848 },622 },
849 })623 "model": "model",
850 if err != nil || result.Status != responses.ResponseStatusCompleted {624 "name": "name",
851 http.Error(w, "Could not create response", 500)625 "object": "assistant",
852 return626 "tools": [
627 {
628 "type": "code_interpreter"
853 }629 }
854 w.Header().Set("Content-Type", "application/json")630 ],
855 if err := json.NewEncoder(w).Encode(map[string]string{631 "response_format": "auto",
856 "content": result.OutputText(),632 "temperature": 1,
857 }); err != nil {633 "tool_resources": {
858 log.Print(err)634 "code_interpreter": {
635 "file_ids": [
636 "string"
637 ]
638 },
639 "file_search": {
640 "vector_store_ids": [
641 "string"
642 ]
859 }643 }
860 })644 },
861 return mux645 "top_p": 1
862}646}
863```647```
864 648
865```ruby649### Example
866# Replace the illustrative IDs and URLs below with your own resource values.650
867require "openai"651```http
868 652curl https://api.openai.com/v1/assistants/asst_abc123 \
869client = OpenAI::Client.new653 -H "Content-Type: application/json" \
870conversations_by_session = {}654 -H "Authorization: Bearer $OPENAI_API_KEY" \
655 -H "OpenAI-Beta: assistants=v2" \
656 -d '{
657 "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.",
658 "tools": [{"type": "file_search"}],
659 "model": "gpt-4.1"
660 }'
661```
871 662
872handle_message = lambda do |session_id:, content:|663#### Response
873 conversation_id = conversations_by_session[session_id]
874 unless conversation_id
875 conversation_id = client.conversations.create.id
876 conversations_by_session[session_id] = conversation_id
877 end
878 664
879 response = client.responses.create(665```json
880 prompt: { id: "pmpt_123" },666{
881 input: [667 "id": "asst_123",
668 "object": "assistant",
669 "created_at": 1699009709,
670 "name": "HR Helper",
671 "description": null,
672 "model": "gpt-4.1",
673 "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.",
674 "tools": [
882 {675 {
883 role: :user,676 "type": "file_search"
884 content: content
885 }677 }
886 ],678 ],
887 conversation: conversation_id679 "tool_resources": {
888 )680 "file_search": {
889 { content: response.output_text }681 "vector_store_ids": []
890end682 }
891 683 },
892puts(684 "metadata": {},
893 handle_message.call(685 "top_p": 1.0,
894 session_id: "example-session",686 "temperature": 1.0,
895 content: "What are the five Ds of dodgeball?"687 "response_format": "auto"
896 )688}
897)
898```689```