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## Retrieve assistant
6 4
5**get** `/assistants/{assistant_id}`
7 6
7Retrieves 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### Returns
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- `Assistant object { id, created_at, description, 10 more }`
15 16
16### What's changed?17 Represents an `assistant` that can call the model and use tools.
17 18
18<table>19 - `id: string`
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 The identifier, which can be referenced in API endpoints.
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 - `created_at: number`
61 24
62### Why this is helpful25 The Unix timestamp (in seconds) for when the assistant was created.
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 `format: unixtime`
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 - `description: string or null`
70 30
711. Identify each existing Assistant’s _instruction + tool_ bundle.31 The description of the assistant. The maximum length is 512 characters.
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 32
76Think of a prompt as a **versioned behavioral profile** to plug into either Responses or Realtime API.33 `maxLength: 512`
77 34
35 - `instructions: string or null`
78 36
79## From threads to conversations37 The system instructions that the assistant uses. The maximum length is 256,000 characters.
80 38
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.39 `maxLength: 256000`
82 40
83### Request example41 - `metadata: Metadata or null`
84 42
85#### Python43 Set of 16 key-value pairs that can be attached to an object. This can be
44 useful for storing additional information about the object in a structured
45 format, and querying for objects via API or the dashboard.
86 46
47 Keys are strings with a maximum length of 64 characters. Values are strings
48 with a maximum length of 512 characters.
87 49
50 - `model: string`
88 51
89#### Thread object52 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.
90 53
91```python54 - `name: string or null`
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 The name of the assistant. The maximum length is 256 characters.
99 57
100```python58 `maxLength: 256`
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 - `object: "assistant"`
107 61
62 The object type, which is always `assistant`.
108 63
109#### Go64 - `"assistant"`
110 65
66 - `tools: array of CodeInterpreterTool or FileSearchTool or FunctionTool`
111 67
68 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`.
112 69
113#### Thread object (Go)70 `maxItems: 128`
114 71
115```go72 - `CodeInterpreterTool object { type }`
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 - `type: "code_interpreter"`
131 75
132```go76 The type of tool being defined: `code_interpreter`
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 - `"code_interpreter"`
144 79
80 - `FileSearchTool object { type, file_search }`
145 81
146#### JavaScript82 - `type: "file_search"`
147 83
84 The type of tool being defined: `file_search`
148 85
86 - `"file_search"`
149 87
150#### Thread object (JavaScript)88 - `file_search: optional object { max_num_results, ranking_options }`
151 89
152```javascript90 Overrides for the file search tool.
153import OpenAI from "openai";
154 91
155const client = new OpenAI();92 - `max_num_results: optional number`
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 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.
164 95
165```javascript96 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.
166import OpenAI from "openai";
167 97
168const client = new OpenAI();98 `minimum: 1`, `maximum: 50`
169 99
170const conversation = await client.conversations.create({100 - `ranking_options: optional object { score_threshold, ranker }`
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 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.
176```
177 103
104 See the [file search tool documentation](/api/docs/guides/tools-file-search#retrieval-customization) for more information.
178 105
106 - `score_threshold: number`
179 107
180### Response example108 The score threshold for the file search. All values must be a floating point number between 0 and 1.
181 109
110 `minimum: 0`, `maximum: 1`
182 111
112 - `ranker: optional "auto" or "default_2024_08_21"`
183 113
184#### Thread object114 The ranker to use for the file search. If not specified will use the `auto` ranker.
185 115
186```json116 - `"auto"`
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 - `"default_2024_08_21"`
199 119
200```json120 - `FunctionTool object { function, type }`
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 - `function: FunctionDefinition`
211 123
124 - `name: string`
212 125
126 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.
213 127
214## From runs to responses128 - `description: optional string`
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 A description of what the function does, used by the model to choose when and how to call the function.
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 - `parameters: optional FunctionParameters`
219 133
220### Request example134 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.
221 135
222#### Python136 Omitting `parameters` defines a function with an empty parameter list.
223 137
138 - `strict: optional boolean or null`
224 139
140 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).
225 141
226#### Run object142 - `type: "function"`
227 143
228```python144 The type of tool being defined: `function`
229# Replace the illustrative IDs and URLs below with your own resource values.
230import time
231 145
232from openai import OpenAI146 - `"function"`
233 147
234openai = OpenAI()148 - `response_format: optional AssistantResponseFormatOption or null`
235thread_id = "thread_123"
236assistant_id = "asst_123"
237 149
238run = openai.beta.threads.runs.create(150 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`.
239 thread_id=thread_id,
240 assistant_id=assistant_id,
241)
242 151
243while run.status in ("queued", "in_progress"):152 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).
244 time.sleep(1)
245 run = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
246```
247 153
248#### Response object154 Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON.
249 155
250```python156 **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.
251# Replace the illustrative IDs and URLs below with your own resource values.
252 157
253from openai import OpenAI158 - `"auto"`
254 159
255openai = OpenAI()160 `auto` is the default value
256conversation_id = "conv_123"
257 161
258response = openai.responses.create(162 - `"auto"`
259 model="gpt-6-astra",
260 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],
261 conversation=conversation_id,
262)
263```
264 163
164 - `ResponseFormatText object { type }`
265 165
166 Default response format. Used to generate text responses.
266 167
267#### Go168 - `type: "text"`
268 169
170 The type of response format being defined. Always `text`.
269 171
172 - `"text"`
270 173
271#### Run object (Go)174 - `ResponseFormatJSONObject object { type }`
272 175
273```go176 JSON object response format. An older method of generating JSON responses.
274run, err := client.Beta.Threads.Runs.New(context.Background(), "thread_abc123", openai.BetaThreadRunNewParams{177 Using `json_schema` is recommended for models that support it. Note that the
275 AssistantID: "asst_abc123",178 model will not generate JSON without a system or user message instructing it
276})179 to do so.
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 180
289#### Response object (Go)181 - `type: "json_object"`
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 182
183 The type of response format being defined. Always `json_object`.
304 184
185 - `"json_object"`
305 186
306#### JavaScript187 - `ResponseFormatJSONSchema object { json_schema, type }`
307 188
189 JSON Schema response format. Used to generate structured JSON responses.
190 Learn more about [Structured Outputs](/api/docs/guides/structured-outputs).
308 191
192 - `json_schema: object { name, description, schema, strict }`
309 193
310#### Run object (JavaScript)194 Structured Outputs configuration options, including a JSON Schema.
311 195
312```javascript196 - `name: string`
313import { setTimeout } from "node:timers/promises";
314import OpenAI from "openai";
315 197
316const client = new OpenAI();198 The name of the response format. Must be a-z, A-Z, 0-9, or contain
317// Replace these illustrative IDs with your own resources.199 underscores and dashes, with a maximum length of 64.
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 200
332#### Response object (JavaScript)201 - `description: optional string`
333 202
334```javascript203 A description of what the response format is for, used by the model to
335// Replace the illustrative IDs and URLs below with your own resource values.204 determine how to respond in the format.
336import OpenAI from "openai";
337 205
338const client = new OpenAI();206 - `schema: optional map[unknown]`
339const conversationId = "conv_123";
340 207
341const response = await client.responses.create({208 The schema for the response format, described as a JSON Schema object.
342 model: "gpt-6-astra",209 Learn how to build JSON schemas [here](https://json-schema.org/).
343 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
344 conversation: conversationId,
345});
346 210
347console.log(response.output_text);211 - `strict: optional boolean or null`
348```
349 212
213 Whether to enable strict schema adherence when generating the output.
214 If set to true, the model will always follow the exact schema defined
215 in the `schema` field. Only a subset of JSON Schema is supported when
216 `strict` is `true`. To learn more, read the [Structured Outputs
217 guide](/api/docs/guides/structured-outputs).
350 218
219 - `type: "json_schema"`
351 220
352### Response example221 The type of response format being defined. Always `json_schema`.
353 222
223 - `"json_schema"`
354 224
225 - `temperature: optional number or null`
355 226
356#### Run object227 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.
357 228
358```json229 `minimum: 0`, `maximum: 2`
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 230
405#### Response object231 - `tool_resources: optional object { code_interpreter, file_search } or null`
406
407```json
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 232
233 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.
475 234
235 - `code_interpreter: optional object { file_ids }`
476 236
237 - `file_ids: optional array of string`
477 238
478## Migrating your integration239 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.
479 240
480Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.241 `maxItems: 20`
481 242
482### 1. Create prompts from your assistants243 - `file_search: optional object { vector_store_ids }`
483 244
4841. Identify the most important assistant objects in your application.245 - `vector_store_ids: optional array of string`
4851. Find these in the dashboard and click `Create prompt`.
486 246
487This will create a prompt object out of each existing assistant object.247 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.
488 248
489Reusable prompt objects are also being deprecated. If you use this migration249 `maxItems: 1`
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 250
494### 2. Move new user chats over to conversations and responses251 - `top_p: optional number or null`
495 252
496Start new chats with the Conversations API and Responses API. To preserve earlier conversation history, use messages already stored by your application.253 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.
497 254
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.255 We generally recommend altering this or temperature but not both.
499 256
500```python257 `minimum: 0`, `maximum: 1`
501# Replace the illustrative IDs and URLs below with your own resource values.
502 258
503from openai import OpenAI259### Example
504 260
505openai = OpenAI()261```http
506messages = []262curl https://api.openai.com/v1/assistants/$ASSISTANT_ID \
507thread_id = "thread_123"263 -H 'OpenAI-Beta: assistants=v2' \
508 264 -H "Authorization: Bearer $OPENAI_API_KEY"
509for page in openai.beta.threads.messages.list(265```
510 thread_id=thread_id, order="asc"
511).iter_pages():
512 messages += page.data
513 266
514items = []267#### Response
515for m in messages:
516 item = {"role": m.role}
517 item_content = []
518 268
519 for content in m.content:269```json
520 match content.type:270{
521 case "text":271 "id": "id",
522 item_content_type = "input_text" if m.role == "user" else "output_text"272 "created_at": 0,
523 item_content += [273 "description": "description",
524 {"type": item_content_type, "text": content.text.value}274 "instructions": "instructions",
525 ]275 "metadata": {
526 case "image_url":276 "foo": "string"
527 item_content += [277 },
278 "model": "model",
279 "name": "name",
280 "object": "assistant",
281 "tools": [
528 {282 {
529 "type": "input_image",283 "type": "code_interpreter"
530 "image_url": content.image_url.url,
531 "detail": content.image_url.detail,
532 }284 }
285 ],
286 "response_format": "auto",
287 "temperature": 1,
288 "tool_resources": {
289 "code_interpreter": {
290 "file_ids": [
291 "string"
533 ]292 ]
534
535 item |= {"content": item_content}
536 items.append(item)
537
538# create a conversation with your converted items
539conversation = openai.conversations.create(items=items)
540```
541
542```ruby
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
582
583## Comparing full examples
584
585Here are a few examples of integrations using both the Assistants API and the Responses API so you can see how they compare.
586
587### User chat app
588
589
590
591Assistants API
592
593```python
594# Replace the illustrative IDs and URLs below with your own resource values.
595threads_by_session: dict[str, str] = {}
596
597
598@app.post("/messages")
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
605 openai.beta.threads.messages.create(
606 thread_id=thread_id,
607 role="user",
608 content=message.content,
609 )
610
611 example_assistant_id = "asst_123"
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
623 messages = openai.beta.threads.messages.list(
624 order="desc",
625 limit=1,
626 thread_id=thread_id,
627 )
628
629 return {"content": messages.data[0].content}
630```
631
632```ruby
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
677
678
679
680
681
682
683Responses API
684
685```javascript
686// Replace the illustrative IDs and URLs below with your own resource values.
687import express from "express";
688import OpenAI from "openai";
689
690const app = express();
691const client = new OpenAI();
692const conversationsBySession = new Map();
693
694app.use(express.json());
695
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 }
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 }
722 const conversationId = await conversationIdPromise;
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```
737
738```python
739# Replace the illustrative IDs and URLs below with your own resource values.
740conversations_by_session: dict[str, str] = {}
741
742
743@app.post("/messages")
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
750 example_prompt_id = "pmpt_123"
751 response = openai.responses.create(
752 prompt={"id": example_prompt_id},
753 input=[{"role": "user", "content": message.content}],
754 conversation=conversation_id,
755 )
756
757 return {"content": response.output_text}
758```
759
760```go
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
771func newChatHandler(client openai.Client) http.Handler {
772 var mutex sync.Mutex
773 type sessionConversation struct {
774 ready chan struct{}
775 id string
776 err error
777 responseSlot chan struct{}
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 },293 },
849 })294 "file_search": {
850 if err != nil || result.Status != responses.ResponseStatusCompleted {295 "vector_store_ids": [
851 http.Error(w, "Could not create response", 500)296 "string"
852 return297 ]
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 }298 }
860 })299 },
861 return mux300 "top_p": 1
862}301}
863```302```
864 303
865```ruby304### Example
866# Replace the illustrative IDs and URLs below with your own resource values.
867require "openai"
868 305
869client = OpenAI::Client.new306```http
870conversations_by_session = {}307curl https://api.openai.com/v1/assistants/asst_abc123 \
308 -H "Content-Type: application/json" \
309 -H "Authorization: Bearer $OPENAI_API_KEY" \
310 -H "OpenAI-Beta: assistants=v2"
311```
871 312
872handle_message = lambda do |session_id:, content:|313#### 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 314
879 response = client.responses.create(315```json
880 prompt: { id: "pmpt_123" },316{
881 input: [317 "id": "asst_abc123",
318 "object": "assistant",
319 "created_at": 1699009709,
320 "name": "HR Helper",
321 "description": null,
322 "model": "gpt-4.1",
323 "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.",
324 "tools": [
882 {325 {
883 role: :user,326 "type": "file_search"
884 content: content
885 }327 }
886 ],328 ],
887 conversation: conversation_id329 "metadata": {},
888 )330 "top_p": 1.0,
889 { content: response.output_text }331 "temperature": 1.0,
890end332 "response_format": "auto"
891 333}
892puts(
893 handle_message.call(
894 session_id: "example-session",
895 content: "What are the five Ds of dodgeball?"
896 )
897)
898```334```