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 thread
6
7 4
5**post** `/threads/{thread_id}`
8 6
7Modifies a thread.
9 8
10Thank you to everyone who used the Assistants API. We appreciate everything you built and the feedback you shared along the way.9### Path Parameters
11 10
12Use this guide to migrate your integration to the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses).11- `thread_id: string`
13 12
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`.13### Body Parameters
15 14
16### What's changed?15- `metadata: optional Metadata or null`
17 16
18<table>17 Set of 16 key-value pairs that can be attached to an object. This can be
19 <thead>18 useful for storing additional information about the object in a structured
20 <tr>19 format, and querying for objects via API or the dashboard.
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 Keys are strings with a maximum length of 64 characters. Values are strings
22 with a maximum length of 512 characters.
59 23
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.24- `tool_resources: optional object { code_interpreter, file_search } or null`
61 25
62### Why this is helpful26 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.
63 27
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.28 - `code_interpreter: optional object { file_ids }`
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 29
69### Practical migration steps30 - `file_ids: optional array of string`
70 31
711. Identify each existing Assistant’s _instruction + tool_ bundle.32 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.
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 33
76Think of a prompt as a **versioned behavioral profile** to plug into either Responses or Realtime API.34 `maxItems: 20`
77 35
36 - `file_search: optional object { vector_store_ids }`
78 37
79## From threads to conversations38 - `vector_store_ids: optional array of string`
80 39
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.40 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.
82 41
83### Request example42 `maxItems: 1`
84 43
85#### Python44### Returns
86 45
46- `Thread object { id, created_at, metadata, 2 more }`
87 47
48 Represents a thread that contains [messages](/api/docs/assistants/migration).
88 49
89#### Thread object50 - `id: string`
90 51
91```python52 The identifier, which can be referenced in API endpoints.
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 53
98#### Conversation object54 - `created_at: number`
99 55
100```python56 The Unix timestamp (in seconds) for when the thread was created.
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 57
58 `format: unixtime`
107 59
60 - `metadata: Metadata or null`
108 61
109#### Go62 Set of 16 key-value pairs that can be attached to an object. This can be
63 useful for storing additional information about the object in a structured
64 format, and querying for objects via API or the dashboard.
110 65
66 Keys are strings with a maximum length of 64 characters. Values are strings
67 with a maximum length of 512 characters.
111 68
69 - `object: "thread"`
112 70
113#### Thread object (Go)71 The object type, which is always `thread`.
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
132```go
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 72
73 - `"thread"`
144 74
75 - `tool_resources: object { code_interpreter, file_search } or null`
145 76
146#### JavaScript77 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.
147 78
79 - `code_interpreter: optional object { file_ids }`
148 80
81 - `file_ids: optional array of string`
149 82
150#### Thread object (JavaScript)83 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.
151 84
152```javascript85 `maxItems: 20`
153import OpenAI from "openai";
154 86
155const client = new OpenAI();87 - `file_search: optional object { vector_store_ids }`
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 88
163#### Conversation object (JavaScript)89 - `vector_store_ids: optional array of string`
164 90
165```javascript91 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.
166import OpenAI from "openai";
167 92
168const client = new OpenAI();93 `maxItems: 1`
169 94
170const conversation = await client.conversations.create({95### Example
171 items: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
172 metadata: { user_id: "peter_le_fleur" },
173});
174 96
175console.log(conversation.id);97```http
98curl https://api.openai.com/v1/threads/$THREAD_ID \
99 -H 'Content-Type: application/json' \
100 -H 'OpenAI-Beta: assistants=v2' \
101 -H "Authorization: Bearer $OPENAI_API_KEY" \
102 -d '{}'
176```103```
177 104
178 105#### Response
179
180### Response example
181
182
183
184#### Thread object
185 106
186```json107```json
187{108{
188 "id": "thread_CrXtCzcyEQbkAcXuNmVSKFs1",109 "id": "id",
189 "object": "thread",110 "created_at": 0,
190 "created_at": 1752855924,
191 "metadata": {111 "metadata": {
192 "user_id": "peter_le_fleur"112 "foo": "string"
193 },113 },
194 "tool_resources": {}114 "object": "thread",
195}115 "tool_resources": {
196```116 "code_interpreter": {
197 117 "file_ids": [
198#### Conversation object118 "string"
199 119 ]
200```json120 },
201{121 "file_search": {
202 "id": "conv_68542dc602388199a30af27d040cefd4087a04b576bfeb24",122 "vector_store_ids": [
203 "object": "conversation",123 "string"
204 "created_at": 1752855924,124 ]
205 "metadata": {
206 "user_id": "peter_le_fleur"
207 }125 }
208}
209```
210
211
212
213
214## From runs to responses
215
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.
217
218Responses are designed to be used alone, but you can also use them with prompt and conversation objects for storing context and configuration.
219
220### Request example
221
222#### Python
223
224
225
226#### Run object
227
228```python
229# Replace the illustrative IDs and URLs below with your own resource values.
230import time
231
232from openai import OpenAI
233
234openai = OpenAI()
235thread_id = "thread_123"
236assistant_id = "asst_123"
237
238run = openai.beta.threads.runs.create(
239 thread_id=thread_id,
240 assistant_id=assistant_id,
241)
242
243while run.status in ("queued", "in_progress"):
244 time.sleep(1)
245 run = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
246```
247
248#### Response object
249
250```python
251# Replace the illustrative IDs and URLs below with your own resource values.
252
253from openai import OpenAI
254
255openai = OpenAI()
256conversation_id = "conv_123"
257
258response = openai.responses.create(
259 model="gpt-6-astra",
260 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],
261 conversation=conversation_id,
262)
263```
264
265
266
267#### Go
268
269
270
271#### Run object (Go)
272
273```go
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 }126 }
286}127}
287```128```
288 129
289#### Response object (Go)130### Example
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
304
305
306#### JavaScript
307
308
309
310#### Run object (JavaScript)
311
312```javascript
313import { setTimeout } from "node:timers/promises";
314import OpenAI from "openai";
315
316const client = new OpenAI();
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 131
332#### Response object (JavaScript)132```http
333 133curl https://api.openai.com/v1/threads/thread_abc123 \
334```javascript134 -H "Content-Type: application/json" \
335// Replace the illustrative IDs and URLs below with your own resource values.135 -H "Authorization: Bearer $OPENAI_API_KEY" \
336import OpenAI from "openai";136 -H "OpenAI-Beta: assistants=v2" \
337 137 -d '{
338const client = new OpenAI();138 "metadata": {
339const conversationId = "conv_123";139 "modified": "true",
340 140 "user": "abc123"
341const response = await client.responses.create({
342 model: "gpt-6-astra",
343 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],
344 conversation: conversationId,
345});
346
347console.log(response.output_text);
348```
349
350
351
352### Response example
353
354
355
356#### Run object
357
358```json
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 }141 }
397 },142 }'
398 "temperature": 1.0,
399 "top_p": 1.0,
400 "tool_resources": {},
401 "reasoning_effort": null
402}
403```143```
404 144
405#### Response object145#### Response
406 146
407```json147```json
408{148{
409 "id": "resp_687a7b53036c819baad6012d58b39bcb074adcd9e24850fc",149 "id": "thread_abc123",
410 "created_at": 1752857427,150 "object": "thread",
411 "conversation": {151 "created_at": 1699014083,
412 "id": "conv_689667905b048191b4740501625afd940c7533ace33a2dab"152 "metadata": {
413 },153 "modified": "true",
414 "error": null,154 "user": "abc123"
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
475
476
477
478## Migrating your integration
479
480Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.
481
482### 1. Create prompts from your assistants
483
4841. Identify the most important assistant objects in your application.
4851. Find these in the dashboard and click `Create prompt`.
486
487This will create a prompt object out of each existing assistant object.
488
489Reusable prompt objects are also being deprecated. If you use this migration
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
494### 2. Move new user chats over to conversations and responses
495
496Start new chats with the Conversations API and Responses API. To preserve earlier conversation history, use messages already stored by your application.
497
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.
499
500```python
501# Replace the illustrative IDs and URLs below with your own resource values.
502
503from openai import OpenAI
504
505openai = OpenAI()
506messages = []
507thread_id = "thread_123"
508
509for page in openai.beta.threads.messages.list(
510 thread_id=thread_id, order="asc"
511).iter_pages():
512 messages += page.data
513
514items = []
515for m in messages:
516 item = {"role": m.role}
517 item_content = []
518
519 for content in m.content:
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
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 },155 },
849 })156 "tool_resources": {}
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}157}
863```158```
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```