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## Create thread
6
7
8
9
10Thank you to everyone who used the Assistants API. We appreciate everything you built and the feedback you shared along the way.
11 4
12Use this guide to migrate your integration to the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses).5**post** `/threads`
13 6
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`.7Create a thread.
15 8
16### What's changed?9### Body Parameters
17 10
18<table>11- `messages: optional array of object { content, role, attachments, metadata }`
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 12
58## From assistants to prompts13 A list of [messages](/api/docs/assistants/migration) to start the thread with.
59 14
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.15 - `content: string or array of ImageFileContentBlock or ImageURLContentBlock or TextContentBlockParam`
61 16
62### Why this is helpful17 The text contents of the message.
63 18
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.19 - `TextContent = string`
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 20
69### Practical migration steps21 The text contents of the message.
70 22
711. Identify each existing Assistant’s _instruction + tool_ bundle.23 - `ArrayOfContentParts = array of ImageFileContentBlock or ImageURLContentBlock or TextContentBlockParam`
722. In the dashboard, recreate that bundle as a named prompt.
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 24
76Think of a prompt as a **versioned behavioral profile** to plug into either Responses or Realtime API.25 An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/api/docs/models).
77 26
27 - `ImageFileContentBlock object { image_file, type }`
78 28
79## From threads to conversations29 References an image [File](/api/reference/resources/files) in the content of a message.
80 30
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.31 - `image_file: ImageFile`
82 32
83### Request example33 - `file_id: string`
84 34
85#### Python35 The [File](/api/reference/resources/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.
86 36
37 - `detail: optional "auto" or "low" or "high"`
87 38
39 Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.
88 40
89#### Thread object41 - `"auto"`
90 42
91```python43 - `"low"`
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
98#### Conversation object
99
100```python
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 44
45 - `"high"`
107 46
47 - `type: "image_file"`
108 48
109#### Go49 Always `image_file`.
110
111
112
113#### Thread object (Go)
114
115```go
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
130#### Conversation object (Go)
131 50
132```go51 - `"image_file"`
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 52
53 - `ImageURLContentBlock object { image_url, type }`
144 54
55 References an image URL in the content of a message.
145 56
146#### JavaScript57 - `image_url: ImageURL`
147 58
59 - `url: string`
148 60
61 The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.
149 62
150#### Thread object (JavaScript)63 `format: uri`
151 64
152```javascript65 - `detail: optional "auto" or "low" or "high"`
153import OpenAI from "openai";
154 66
155const client = new OpenAI();67 Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`
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 68
163#### Conversation object (JavaScript)69 - `"auto"`
164 70
165```javascript71 - `"low"`
166import OpenAI from "openai";
167 72
168const client = new OpenAI();73 - `"high"`
169 74
170const conversation = await client.conversations.create({75 - `type: "image_url"`
171 items: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
172 metadata: { user_id: "peter_le_fleur" },
173});
174 76
175console.log(conversation.id);77 The type of the content part.
176```
177 78
79 - `"image_url"`
178 80
81 - `TextContentBlockParam object { text, type }`
179 82
180### Response example83 The text content that is part of a message.
181 84
85 - `text: string`
182 86
87 Text content to be sent to the model
183 88
184#### Thread object89 - `type: "text"`
185 90
186```json91 Always `text`.
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 92
198#### Conversation object93 - `"text"`
199 94
200```json95 - `role: "user" or "assistant"`
201{
202 "id": "conv_68542dc602388199a30af27d040cefd4087a04b576bfeb24",
203 "object": "conversation",
204 "created_at": 1752855924,
205 "metadata": {
206 "user_id": "peter_le_fleur"
207 }
208}
209```
210 96
97 The role of the entity that is creating the message. Allowed values include:
211 98
99 - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.
100 - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.
212 101
102 - `"user"`
213 103
214## From runs to responses104 - `"assistant"`
215 105
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.106 - `attachments: optional array of object { file_id, tools } or null`
217 107
218Responses are designed to be used alone, but you can also use them with prompt and conversation objects for storing context and configuration.108 A list of files attached to the message, and the tools they should be added to.
219 109
220### Request example110 - `file_id: optional string`
221 111
222#### Python112 The ID of the file to attach to the message.
223 113
114 - `tools: optional array of CodeInterpreterTool or FileSearchTool { type }`
224 115
116 The tools to add this file to.
225 117
226#### Run object118 - `CodeInterpreterTool object { type }`
227 119
228```python120 - `type: "code_interpreter"`
229# Replace the illustrative IDs and URLs below with your own resource values.
230import time
231 121
232from openai import OpenAI122 The type of tool being defined: `code_interpreter`
233 123
234openai = OpenAI()124 - `"code_interpreter"`
235thread_id = "thread_123"
236assistant_id = "asst_123"
237 125
238run = openai.beta.threads.runs.create(126 - `FileSearchTool object { type }`
239 thread_id=thread_id,
240 assistant_id=assistant_id,
241)
242 127
243while run.status in ("queued", "in_progress"):128 - `type: "file_search"`
244 time.sleep(1)
245 run = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
246```
247 129
248#### Response object130 The type of tool being defined: `file_search`
249 131
250```python132 - `"file_search"`
251# Replace the illustrative IDs and URLs below with your own resource values.
252 133
253from openai import OpenAI134 - `metadata: optional Metadata or null`
254 135
255openai = OpenAI()136 Set of 16 key-value pairs that can be attached to an object. This can be
256conversation_id = "conv_123"137 useful for storing additional information about the object in a structured
138 format, and querying for objects via API or the dashboard.
257 139
258response = openai.responses.create(140 Keys are strings with a maximum length of 64 characters. Values are strings
259 model="gpt-6-astra",141 with a maximum length of 512 characters.
260 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],
261 conversation=conversation_id,
262)
263```
264 142
143- `metadata: optional Metadata or null`
265 144
145 Set of 16 key-value pairs that can be attached to an object. This can be
146 useful for storing additional information about the object in a structured
147 format, and querying for objects via API or the dashboard.
266 148
267#### Go149 Keys are strings with a maximum length of 64 characters. Values are strings
150 with a maximum length of 512 characters.
268 151
152- `tool_resources: optional object { code_interpreter, file_search } or null`
269 153
154 A set of resources that are made available to the assistant's tools in this thread. 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.
270 155
271#### Run object (Go)156 - `code_interpreter: optional object { file_ids }`
272 157
273```go158 - `file_ids: optional array of string`
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 159
289#### Response object (Go)160 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.
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 161
162 `maxItems: 20`
304 163
164 - `file_search: optional object { vector_store_ids, vector_stores }`
305 165
306#### JavaScript166 - `vector_store_ids: optional array of string`
307 167
168 The [vector store](/api/reference/resources/vector_stores) attached to this thread. There can be a maximum of 1 vector store attached to the thread.
308 169
170 `maxItems: 1`
309 171
310#### Run object (JavaScript)172 - `vector_stores: optional array of object { chunking_strategy, file_ids, metadata }`
311 173
312```javascript174 A helper to create a [vector store](/api/reference/resources/vector_stores) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.
313import { setTimeout } from "node:timers/promises";
314import OpenAI from "openai";
315 175
316const client = new OpenAI();176 `maxItems: 1`
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 177
332#### Response object (JavaScript)178 - `chunking_strategy: optional Auto { type } or Static { static, type }`
333 179
334```javascript180 The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.
335// Replace the illustrative IDs and URLs below with your own resource values.
336import OpenAI from "openai";
337 181
338const client = new OpenAI();182 - `Auto object { type }`
339const conversationId = "conv_123";
340 183
341const response = await client.responses.create({184 The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`.
342 model: "gpt-6-astra",
343 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
344 conversation: conversationId,
345});
346 185
347console.log(response.output_text);186 - `type: "auto"`
348```
349 187
188 Always `auto`.
350 189
190 - `"auto"`
351 191
352### Response example192 - `Static object { static, type }`
353 193
194 - `static: object { chunk_overlap_tokens, max_chunk_size_tokens }`
354 195
196 - `chunk_overlap_tokens: number`
355 197
356#### Run object198 The number of tokens that overlap between chunks. The default value is `400`.
357 199
358```json200 Note that the overlap must not exceed half of `max_chunk_size_tokens`.
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 201
405#### Response object202 - `max_chunk_size_tokens: number`
406 203
407```json204 The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.
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 205
206 `minimum: 100`, `maximum: 4096`
475 207
208 - `type: "static"`
476 209
210 Always `static`.
477 211
478## Migrating your integration212 - `"static"`
479 213
480Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.214 - `file_ids: optional array of string`
481 215
482### 1. Create prompts from your assistants216 A list of [file](/api/reference/resources/files) IDs to add to the vector store. For vector stores created before Nov 2025, there can be a maximum of 10,000 files in a vector store. For vector stores created starting in Nov 2025, the limit is 100,000,000 files.
483 217
4841. Identify the most important assistant objects in your application.218 `maxItems: 100000000`
4851. Find these in the dashboard and click `Create prompt`.
486 219
487This will create a prompt object out of each existing assistant object.220 - `metadata: optional Metadata or null`
488 221
489Reusable prompt objects are also being deprecated. If you use this migration222 Set of 16 key-value pairs that can be attached to an object. This can be
490 path, review the [prompts deprecation223 useful for storing additional information about the object in a structured
491 timeline](https://developers.openai.com/api/docs/deprecations#2026-06-03-reusable-prompts) before adopting224 format, and querying for objects via API or the dashboard.
492 prompt objects in a long-lived integration.
493 225
494### 2. Move new user chats over to conversations and responses226 Keys are strings with a maximum length of 64 characters. Values are strings
227 with a maximum length of 512 characters.
495 228
496Start new chats with the Conversations API and Responses API. To preserve earlier conversation history, use messages already stored by your application.229### Returns
497 230
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.231- `Thread object { id, created_at, metadata, 2 more }`
499 232
500```python233 Represents a thread that contains [messages](/api/docs/assistants/migration).
501# Replace the illustrative IDs and URLs below with your own resource values.
502 234
503from openai import OpenAI235 - `id: string`
504 236
505openai = OpenAI()237 The identifier, which can be referenced in API endpoints.
506messages = []
507thread_id = "thread_123"
508 238
509for page in openai.beta.threads.messages.list(239 - `created_at: number`
510 thread_id=thread_id, order="asc"
511).iter_pages():
512 messages += page.data
513 240
514items = []241 The Unix timestamp (in seconds) for when the thread was created.
515for m in messages:
516 item = {"role": m.role}
517 item_content = []
518 242
519 for content in m.content:243 `format: unixtime`
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 244
535 item |= {"content": item_content}245 - `metadata: Metadata or null`
536 items.append(item)
537 246
538# create a conversation with your converted items247 Set of 16 key-value pairs that can be attached to an object. This can be
539conversation = openai.conversations.create(items=items)248 useful for storing additional information about the object in a structured
540```249 format, and querying for objects via API or the dashboard.
541 250
542```ruby251 Keys are strings with a maximum length of 64 characters. Values are strings
543# Replace the illustrative IDs and URLs below with your own resource values.252 with a maximum length of 512 characters.
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 253
254 - `object: "thread"`
582 255
583## Comparing full examples256 The object type, which is always `thread`.
584 257
585Here are a few examples of integrations using both the Assistants API and the Responses API so you can see how they compare.258 - `"thread"`
586 259
587### User chat app260 - `tool_resources: object { code_interpreter, file_search } or null`
588 261
262 A set of resources that are made available to the assistant's tools in this thread. 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.
589 263
264 - `code_interpreter: optional object { file_ids }`
590 265
591Assistants API266 - `file_ids: optional array of string`
592 267
593```python268 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.
594# Replace the illustrative IDs and URLs below with your own resource values.
595threads_by_session: dict[str, str] = {}
596 269
270 `maxItems: 20`
597 271
598@app.post("/messages")272 - `file_search: optional object { vector_store_ids }`
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 273
605 openai.beta.threads.messages.create(274 - `vector_store_ids: optional array of string`
606 thread_id=thread_id,
607 role="user",
608 content=message.content,
609 )
610 275
611 example_assistant_id = "asst_123"276 The [vector store](/api/reference/resources/vector_stores) attached to this thread. There can be a maximum of 1 vector store attached to the thread.
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 277
623 messages = openai.beta.threads.messages.list(278 `maxItems: 1`
624 order="desc",
625 limit=1,
626 thread_id=thread_id,
627 )
628 279
629 return {"content": messages.data[0].content}280### Example
630```
631 281
632```ruby282```http
633# Replace the illustrative IDs and URLs below with your own resource values.283curl https://api.openai.com/v1/threads \
634require "openai"284 -X POST \
635 285 -H 'OpenAI-Beta: assistants=v2' \
636client = OpenAI::Client.new286 -H "Authorization: Bearer $OPENAI_API_KEY"
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```287```
676 288
289#### Response
677 290
678 291```json
679 292{
680 293 "id": "id",
681 294 "created_at": 0,
682 295 "metadata": {
683Responses API296 "foo": "string"
684 297 },
685```javascript298 "object": "thread",
686// Replace the illustrative IDs and URLs below with your own resource values.299 "tool_resources": {
687import express from "express";300 "code_interpreter": {
688import OpenAI from "openai";301 "file_ids": [
689 302 "string"
690const app = express();303 ]
691const client = new OpenAI();304 },
692const conversationsBySession = new Map();305 "file_search": {
693 306 "vector_store_ids": [
694app.use(express.json());307 "string"
695 308 ]
696app.post("/messages", async (request, response) => {
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 }309 }
709
710 let conversationIdPromise = conversationsBySession.get(sessionId);
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 }310 }
722 const conversationId = await conversationIdPromise;311}
723
724 const promptId = "pmpt_123";
725
726 const result = await client.responses.create({
727 prompt: { id: promptId },
728 input: [{ role: "user", content }],
729 conversation: conversationId,
730 });
731
732 response.json({ content: result.output_text });
733});
734
735app.listen(Number(process.env.OPENAI_EXAMPLE_PORT ?? 8000), "127.0.0.1");
736```312```
737 313
738```python314### Empty
739# Replace the illustrative IDs and URLs below with your own resource values.
740conversations_by_session: dict[str, str] = {}
741 315
316```http
317curl https://api.openai.com/v1/threads \
318 -H "Content-Type: application/json" \
319 -H "Authorization: Bearer $OPENAI_API_KEY" \
320 -H "OpenAI-Beta: assistants=v2" \
321 -d ''
322```
742 323
743@app.post("/messages")324#### Response
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 325
750 example_prompt_id = "pmpt_123"326```json
751 response = openai.responses.create(327{
752 prompt={"id": example_prompt_id},328 "id": "thread_abc123",
753 input=[{"role": "user", "content": message.content}],329 "object": "thread",
754 conversation=conversation_id,330 "created_at": 1699012949,
755 )331 "metadata": {},
332 "tool_resources": {}
333}
334```
756 335
757 return {"content": response.output_text}336### Messages
337
338```http
339curl https://api.openai.com/v1/threads \
340-H "Content-Type: application/json" \
341-H "Authorization: Bearer $OPENAI_API_KEY" \
342-H "OpenAI-Beta: assistants=v2" \
343-d '{
344 "messages": [{
345 "role": "user",
346 "content": "Hello, what is AI?"
347 }, {
348 "role": "user",
349 "content": "How does AI work? Explain it in simple terms."
350 }]
351 }'
758```352```
759 353
760```go354#### 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 355
771func newChatHandler(client openai.Client) http.Handler {356```json
772 var mutex sync.Mutex357{
773 type sessionConversation struct {358 "id": "thread_abc123",
774 ready chan struct{}359 "object": "thread",
775 id string360 "created_at": 1699014083,
776 err error361 "metadata": {},
777 responseSlot chan struct{}362 "tool_resources": {}
778 }
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 },
849 })
850 if err != nil || result.Status != responses.ResponseStatusCompleted {
851 http.Error(w, "Could not create response", 500)
852 return
853 }
854 w.Header().Set("Content-Type", "application/json")
855 if err := json.NewEncoder(w).Encode(map[string]string{
856 "content": result.OutputText(),
857 }); err != nil {
858 log.Print(err)
859 }
860 })
861 return mux
862}363}
863```364```
864
865```ruby
866# Replace the illustrative IDs and URLs below with your own resource values.
867require "openai"
868
869client = OpenAI::Client.new
870conversations_by_session = {}
871
872handle_message = lambda do |session_id:, content:|
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
879 response = client.responses.create(
880 prompt: { id: "pmpt_123" },
881 input: [
882 {
883 role: :user,
884 content: content
885 }
886 ],
887 conversation: conversation_id
888 )
889 { content: response.output_text }
890end
891
892puts(
893 handle_message.call(
894 session_id: "example-session",
895 content: "What are the five Ds of dodgeball?"
896 )
897)
898```