SPB Git

Repository Public

migrate-to-responses.md 61.5 KB 2,183 lines markdown

1# Migrate to the Responses API23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45The [Responses API](https://developers.openai.com/api/reference/resources/responses) is our new API primitive, an evolution of [Chat Completions](https://developers.openai.com/api/reference/resources/chat) which brings added simplicity and powerful agentic primitives to your integrations.67**While Chat Completions remains supported, Responses is recommended for all new projects.**89## About the Responses API1011The Responses API is a unified interface for building powerful, agent-like applications. It contains:1213- Built-in tools like [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [file search](https://developers.openai.com/api/docs/guides/tools-file-search), [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [code interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter), and [remote MCPs](https://developers.openai.com/api/docs/guides/tools-connectors-mcp).14- Seamless multi-turn interactions that allow you to pass previous responses for higher accuracy reasoning results.15- Native multimodal support for text and images.1617## Responses benefits1819The Responses API contains several benefits over Chat Completions:2021- **Better performance**: Using reasoning models, like GPT-5, with Responses will result in better model intelligence when compared to Chat Completions. Our internal evals reveal a 3% improvement in SWE-bench with same prompt and setup.22- **Agentic by default**: The Responses API is an agentic loop, allowing the model to call multiple tools, like `web_search`, `image_generation`, `file_search`, `code_interpreter`, remote MCP servers, as well as your own custom functions, within the span of one API request.23- **Lower costs**: Results in lower costs due to improved cache utilization (40% to 80% improvement when compared to Chat Completions in internal tests).24- **Stateful context**: Use `store: true` to maintain state from turn to turn, preserving reasoning and tool context from turn-to-turn.25- **Flexible inputs**: Pass a string with input or a list of messages; use instructions for system-level guidance.26- **Encrypted reasoning**: Opt-out of statefulness while still benefiting from advanced reasoning.27- **Future-proof**: Future-proofed for upcoming models.2829303132| Capabilities        | Chat Completions API  | Responses API         |33| ------------------- | --------------------- | --------------------- |34| Text generation     | | |35| Audio               | | Coming soon           |36| Vision              | | |37| Structured Outputs  | | |38| Function calling    | | |39| Web search          | | |40| File search         | | |41| Computer use        | | |42| Code interpreter    | | |43| MCP                 | | |44| Image generation    | | |45| Reasoning summaries | | |4647484950### Examples5152See how the Responses API compares to the Chat Completions API in specific scenarios.5354#### Messages vs. Items5556Both APIs make it easy to generate output from our models. The input to, and result of, a call to Chat completions is an array of _Messages_, while57the Responses API uses _Items_. An Item is a union of many types, representing the range of possibilities58of model actions. A `message` is a type of Item, as is a `function_call` or `function_call_output`. Unlike a Chat Completions Message, where59many concerns are glued together into one object, Items are distinct from one another and better represent the basic unit of model context.6061Additionally, Chat Completions can return multiple parallel generations as `choices`, using the `n` param. In Responses, we've removed this param, leaving only one generation.62636465  Chat Completions API6667```python68from openai import OpenAI6970client = OpenAI()7172completion = client.chat.completions.create(73    model="gpt-6-astra",74    messages=[75        {76            "role": "user",77            "content": "Write a one-sentence bedtime story about a unicorn.",78        }79    ],80)8182print(completion.choices[0].message.content)83```8485```ruby86require "openai"8788client = OpenAI::Client.new89completion = client.chat.completions.create(90  model: "gpt-6-astra",91  messages: [92    {93      role: :user,94      content: "Write a one-sentence bedtime story about a unicorn."95    }96  ]97)98puts(completion.choices.fetch(0).message.content)99```100101  Responses API102103```python104from openai import OpenAI105106client = OpenAI()107108response = client.responses.create(109    model="gpt-6-astra",110    input="Write a one-sentence bedtime story about a unicorn.",111)112113print(response.output_text)114```115116```ruby117require "openai"118119client = OpenAI::Client.new120response = client.responses.create(121  model: "gpt-6-astra",122  input: "Write a one-sentence bedtime story about a unicorn."123)124puts(response.output_text)125```126127128129130When you get a response back from the Responses API, the fields differ slightly.131Instead of a `message`, you receive a typed `response` object with its own `id`.132Responses are stored by default. Chat completions are stored by default for new accounts.133To disable storage when using either API, set `store: false`.134135The objects you receive back from these APIs will differ slightly. In Chat Completions, you receive an array of136`choices`, each containing a `message`. In Responses, you receive an array of Items labeled `output`.137138139140#### Chat Completions API141142```json143{144    "id": "chatcmpl-C9EDpkjH60VPPIB86j2zIhiR8kWiC",145    "object": "chat.completion",146    "created": 1756315657,147    "model": "gpt-5.5",148    "choices": [149      {150        "index": 0,151        "message": {152          "role": "assistant",153          "content": "Under a blanket of starlight, a sleepy unicorn tiptoed through moonlit meadows, gathering dreams like dew to tuck beneath its silver mane until morning.",154          "refusal": null,155          "annotations": []156        },157        "finish_reason": "stop"158      }159    ],160    ...161}162```163164#### Responses API165166```json167{168    "id": "resp_68af4030592c81938ec0a5fbab4a3e9f05438e46b5f69a3b",169    "object": "response",170    "created_at": 1756315696,171    "model": "gpt-5.5",172    "output": [173      {174        "id": "rs_68af4030baa48193b0b43b4c2a176a1a05438e46b5f69a3b",175        "type": "reasoning",176        "content": [],177        "summary": []178      },179      {180        "id": "msg_68af40337e58819392e935fb404414d005438e46b5f69a3b",181        "type": "message",182        "status": "completed",183        "content": [184          {185            "type": "output_text",186            "annotations": [],187            "logprobs": [],188            "text": "Under a quilt of moonlight, a drowsy unicorn wandered through quiet meadows, brushing blossoms with her glowing horn so they sighed soft lullabies that carried every dreamer gently to sleep."189          }190        ],191        "role": "assistant"192      }193    ],194    ...195}196```197198199200### Additional differences201202- Responses are stored by default. Chat completions are stored by default for new accounts. To disable storage in either API, set `store: false`.203- [Reasoning](https://developers.openai.com/api/docs/guides/reasoning) models have a richer experience in the Responses API with [improved tool usage](https://developers.openai.com/api/docs/guides/reasoning#keeping-reasoning-items-in-context). Starting with GPT-5.4, Chat Completions does not support tool calling with `reasoning_effort` values other than `none`.204- Structured Outputs API shape is different. Instead of `response_format`, use `text.format` in Responses. Learn more in the [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs) guide.205- The function-calling API shape is different, both for the function config on the request, and function calls sent back in the response. See the full difference in the [function calling guide](https://developers.openai.com/api/docs/guides/function-calling).206- The Responses SDK has an `output_text` helper, which the Chat Completions SDK does not have.207- In Chat Completions, conversation state must be managed manually. The Responses API has compatibility with the [Conversations API](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses#using-the-conversations-api) for persistent conversations, or the ability to pass a `previous_response_id` to easily chain Responses together.208209## Migrating from Chat Completions210211Treat migration as three related changes: send requests to `/v1/responses`, read output from a typed `output` array, and choose how your application will carry state between turns.212213### 1. Update generation endpoints214215Start by updating your generation endpoints from `post /v1/chat/completions` to `post /v1/responses`.216217If you are not using functions or multimodal inputs, simple message inputs are compatible from one API to the other:218219Reuse simple message input220221```javascript222const context = [223  { role: "system", content: "You are a helpful assistant." },224  { role: "user", content: "Hello!" },225];226227const completion = await client.chat.completions.create({228  model: "gpt-6-astra",229  messages: context,230});231232const response = await client.responses.create({233  model: "gpt-6-astra",234  input: context,235});236```237238```python239context = [240    {"role": "system", "content": "You are a helpful assistant."},241    {"role": "user", "content": "Hello!"},242]243244completion = client.chat.completions.create(model="gpt-6-astra", messages=context)245246response = client.responses.create(model="gpt-6-astra", input=context)247```248249```go250package main251252import (253	"context"254	"fmt"255256	"github.com/openai/openai-go/v3"257	"github.com/openai/openai-go/v3/responses"258)259260func main() {261	client := openai.NewClient()262263	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{264		Model: "gpt-6-astra",265		Messages: []openai.ChatCompletionMessageParamUnion{266			openai.SystemMessage("You are a helpful assistant."),267			openai.UserMessage("Hello!"),268		},269	})270	if err != nil {271		panic(err)272	}273	fmt.Println(completion.Choices[0].Message.Content)274275	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{276		Model: "gpt-6-astra",277		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{278			responses.ResponseInputItemParamOfMessage("You are a helpful assistant.", responses.EasyInputMessageRoleSystem),279			responses.ResponseInputItemParamOfMessage("Hello!", responses.EasyInputMessageRoleUser),280		}},281	})282	if err != nil {283		panic(err)284	}285	fmt.Println(response.OutputText())286}287```288289```java290import com.openai.client.OpenAIClient;291import com.openai.client.okhttp.OpenAIOkHttpClient;292import com.openai.models.chat.completions.ChatCompletionCreateParams;293import com.openai.models.responses.EasyInputMessage;294import com.openai.models.responses.ResponseCreateParams;295import com.openai.models.responses.ResponseInputItem;296import java.util.List;297298var completion =299    client300        .chat()301        .completions()302        .create(303            ChatCompletionCreateParams.builder()304                .model("gpt-6-astra")305                .addSystemMessage("You are a helpful assistant.")306                .addUserMessage("Hello!")307                .build());308completion.choices().stream()309    .flatMap(choice -> choice.message().content().stream())310    .forEach(System.out::println);311312var response =313    client314        .responses()315        .create(316            ResponseCreateParams.builder()317                .model("gpt-6-astra")318                .inputOfResponse(319                    List.of(320                        ResponseInputItem.ofEasyInputMessage(321                            EasyInputMessage.builder()322                                .role(EasyInputMessage.Role.SYSTEM)323                                .content("You are a helpful assistant.")324                                .build()),325                        ResponseInputItem.ofEasyInputMessage(326                            EasyInputMessage.builder()327                                .role(EasyInputMessage.Role.USER)328                                .content("Hello!")329                                .build())))330                .build());331response.output().stream()332    .flatMap(item -> item.message().stream())333    .flatMap(message -> message.content().stream())334    .flatMap(content -> content.outputText().stream())335    .forEach(text -> System.out.println(text.text()));336```337338```csharp339using OpenAI.Chat;340using OpenAI.Responses;341#pragma warning disable OPENAI001342343string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;344string model = "gpt-6-astra";345346ChatClient chat = new(model, key);347348ChatCompletion completion = await chat.CompleteChatAsync(349    [350        new SystemChatMessage("You are a helpful assistant."),351        new UserChatMessage("Hello!"),352    ]353);354Console.WriteLine(completion.Content[0].Text);355356ResponsesClient responses = new(key);357358ResponseResult response = await responses.CreateResponseAsync(359    model,360    [361        ResponseItem.CreateSystemMessageItem("You are a helpful assistant."),362        ResponseItem.CreateUserMessageItem("Hello!"),363    ]364);365Console.WriteLine(response.GetOutputText());366```367368```ruby369require "openai"370371client = OpenAI::Client.new372messages = [373  {374    role: :system,375    content: "You are a helpful assistant."376  },377  {378    role: :user,379    content: "Hello!"380  }381]382383completion = client.chat.completions.create(384  model: "gpt-6-astra",385  messages: messages386)387puts(completion.choices.fetch(0).message.content)388389response = client.responses.create(390  model: "gpt-6-astra",391  input: messages392)393puts(response.output_text)394```395396```bash397INPUT='[398  { "role": "system", "content": "You are a helpful assistant." },399  { "role": "user", "content": "Hello!" }400]'401402curl -s https://api.openai.com/v1/chat/completions \403  -H "Content-Type: application/json" \404  -H "Authorization: Bearer $OPENAI_API_KEY" \405  -d "{406    \"model\": \"gpt-6-astra\",407    \"messages\": $INPUT408  }"409410curl -s https://api.openai.com/v1/responses \411  -H "Content-Type: application/json" \412  -H "Authorization: Bearer $OPENAI_API_KEY" \413  -d "{414    \"model\": \"gpt-6-astra\",415    \"input\": $INPUT416  }"417```418419420421422Chat Completions423424    With Chat Completions, you create a `messages` array and read the model text425    from `completion.choices[0].message.content`.426    Generate text from a model427428```javascript429import OpenAI from "openai";430const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });431432const completion = await client.chat.completions.create({433  model: "gpt-6-astra",434  messages: [435    { role: "system", content: "You are a helpful assistant." },436    { role: "user", content: "Hello!" },437  ],438});439console.log(completion.choices[0].message.content);440```441442```python443from openai import OpenAI444445client = OpenAI()446447completion = client.chat.completions.create(448    model="gpt-6-astra",449    messages=[450        {"role": "system", "content": "You are a helpful assistant."},451        {"role": "user", "content": "Hello!"},452    ],453)454print(completion.choices[0].message.content)455```456457```go458package main459460import (461	"context"462	"fmt"463464	"github.com/openai/openai-go/v3"465)466467func main() {468	client := openai.NewClient()469470	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{471		Model: "gpt-6-astra",472		Messages: []openai.ChatCompletionMessageParamUnion{473			openai.SystemMessage("You are a helpful assistant."),474			openai.UserMessage("Hello!"),475		},476	})477	if err != nil {478		panic(err)479	}480	fmt.Println(completion.Choices[0].Message.Content)481}482```483484```java485import com.openai.client.OpenAIClient;486import com.openai.client.okhttp.OpenAIOkHttpClient;487import com.openai.models.chat.completions.ChatCompletionCreateParams;488489ChatCompletionCreateParams params =490    ChatCompletionCreateParams.builder()491        .model("gpt-6-astra")492        .addSystemMessage("You are a helpful assistant.")493        .addUserMessage("Hello!")494        .build();495496client.chat().completions().create(params).choices().stream()497    .flatMap(choice -> choice.message().content().stream())498    .forEach(System.out::println);499```500501```csharp502using OpenAI.Chat;503504string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;505string model = "gpt-6-astra";506ChatClient client = new(model, key);507508ChatCompletion completion = await client.CompleteChatAsync(509    [510        new SystemChatMessage("You are a helpful assistant."),511        new UserChatMessage("Hello!"),512    ]513);514515Console.WriteLine(completion.Content[0].Text);516```517518```ruby519require "openai"520521client = OpenAI::Client.new522523completion = client.chat.completions.create(524  model: "gpt-6-astra",525  messages: [526    {527      role: :system,528      content: "You are a helpful assistant."529    },530    {531      role: :user,532      content: "Hello!"533    }534  ]535)536537puts(completion.choices.fetch(0).message.content)538```539540```bash541curl https://api.openai.com/v1/chat/completions \542  -H "Content-Type: application/json" \543  -H "Authorization: Bearer $OPENAI_API_KEY" \544  -d '{545      "model": "gpt-6-astra",546      "messages": [547          {"role": "system", "content": "You are a helpful assistant."},548          {"role": "user", "content": "Hello!"}549      ]550  }'551```552553554  555556  557558    559Responses560561    With Responses, you can separate `instructions` and `input` at the top level562    and read generated text from `response.output_text`.563    Generate text from a model564565```javascript566import OpenAI from "openai";567const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });568569const response = await client.responses.create({570  model: "gpt-6-astra",571  instructions: "You are a helpful assistant.",572  input: "Hello!",573});574575console.log(response.output_text);576```577578```python579from openai import OpenAI580581client = OpenAI()582583response = client.responses.create(584    model="gpt-6-astra", instructions="You are a helpful assistant.", input="Hello!"585)586print(response.output_text)587```588589```go590package main591592import (593	"context"594	"fmt"595596	"github.com/openai/openai-go/v3"597	"github.com/openai/openai-go/v3/responses"598)599600func main() {601	client := openai.NewClient()602603	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{604		Model:        "gpt-6-astra",605		Instructions: openai.String("You are a helpful assistant."),606		Input:        responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello!")},607	})608	if err != nil {609		panic(err)610	}611	fmt.Println(response.OutputText())612}613```614615```java616import com.openai.client.OpenAIClient;617import com.openai.client.okhttp.OpenAIOkHttpClient;618import com.openai.models.responses.ResponseCreateParams;619620ResponseCreateParams params =621    ResponseCreateParams.builder()622        .model("gpt-6-astra")623        .input("Hello!")624        .instructions("You are a helpful assistant.")625        .build();626627client.responses().create(params).output().stream()628    .flatMap(item -> item.message().stream())629    .flatMap(message -> message.content().stream())630    .flatMap(content -> content.outputText().stream())631    .forEach(text -> System.out.println(text.text()));632```633634```csharp635using OpenAI.Responses;636#pragma warning disable OPENAI001637638string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;639ResponsesClient client = new(key);640641CreateResponseOptions options = new()642{643    Model = "gpt-6-astra",644    Instructions = "You are a helpful assistant.",645};646options.InputItems.Add(ResponseItem.CreateUserMessageItem("Hello!"));647648ResponseResult response = await client.CreateResponseAsync(options);649650Console.WriteLine(response.GetOutputText());651```652653```ruby654require "openai"655656client = OpenAI::Client.new657658response = client.responses.create(659  model: "gpt-6-astra",660  instructions: "You are a helpful assistant.",661  input: "Hello!"662)663664puts(response.output_text)665```666667```bash668curl https://api.openai.com/v1/responses \669  -H "Content-Type: application/json" \670  -H "Authorization: Bearer $OPENAI_API_KEY" \671  -d '{672      "model": "gpt-6-astra",673      "instructions": "You are a helpful assistant.",674      "input": "Hello!"675  }'676```677678679680### 2. Map Messages to Items681682Chat Completions uses `messages` as both input and output. Responses uses `input` and `output` arrays of typed Items. A `message` is one Item type, alongside Items such as `reasoning`, `function_call`, and `function_call_output`.683684| Chat Completions concept      | Responses mapping                                                                                      |685| ----------------------------- | ------------------------------------------------------------------------------------------------------ |686| `messages[]`                  | `input`, as a string or an array of input Items                                                        |687| System or developer guidance  | Top-level `instructions`, or compatible message Items when you need to preserve an existing transcript |688| User message                  | An input message Item with `role: "user"`                                                              |689| Assistant message             | An output message Item in `response.output`; pass it back in `input` if you manually manage state      |690| Tool or function call         | A `function_call` output Item                                                                          |691| Tool or function result       | A `function_call_output` input Item linked to the call with `call_id`                                  |692| Multiple generations with `n` | Not available in Responses; make separate requests if you need multiple candidate outputs              |693694When you only need the final text, use the SDK `output_text` helper. When your flow uses reasoning, tools, or multimodal output, iterate over `response.output` and handle each Item by its `type`.695696### 3. Update multi-turn conversations697698If you have multi-turn conversations in your application, update your context logic. Responses gives you three common state-management options:699700- Use `previous_response_id` when you want OpenAI to manage prior response context. Resend stable `instructions` on each request, because `previous_response_id` does not carry over the previous response's top-level `instructions`.701- Pass prior `output` Items back into the next request when you need to manage or trim context yourself.702- Use the [Conversations API](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses#using-the-conversations-api) when you need a persistent conversation object.703704705706Chat Completions707708    In Chat Completions, you store the transcript and send the accumulated709    `messages` array on each request.710    Multi-turn conversation711712```javascript713let messages = [714  { role: "system", content: "You are a helpful assistant." },715  { role: "user", content: "What is the capital of France?" },716];717const res1 = await client.chat.completions.create({718  model: "gpt-6-astra",719  messages,720});721722messages = messages.concat([res1.choices[0].message]);723messages.push({ role: "user", content: "And its population?" });724725const res2 = await client.chat.completions.create({726  model: "gpt-6-astra",727  messages,728});729```730731```python732messages = [733    {"role": "system", "content": "You are a helpful assistant."},734    {"role": "user", "content": "What is the capital of France?"},735]736res1 = client.chat.completions.create(model="gpt-6-astra", messages=messages)737738messages += [res1.choices[0].message]739messages += [{"role": "user", "content": "And its population?"}]740741res2 = client.chat.completions.create(model="gpt-6-astra", messages=messages)742```743744```go745package main746747import (748	"context"749	"fmt"750751	"github.com/openai/openai-go/v3"752)753754func main() {755	client := openai.NewClient()756	messages := []openai.ChatCompletionMessageParamUnion{757		openai.SystemMessage("You are a helpful assistant."),758		openai.UserMessage("What is the capital of France?"),759	}760761	first, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})762	if err != nil {763		panic(err)764	}765	messages = append(messages, openai.AssistantMessage(first.Choices[0].Message.Content), openai.UserMessage("And its population?"))766767	second, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})768	if err != nil {769		panic(err)770	}771	fmt.Println(second.Choices[0].Message.Content)772}773```774775```java776import com.openai.client.OpenAIClient;777import com.openai.client.okhttp.OpenAIOkHttpClient;778import com.openai.models.chat.completions.ChatCompletionCreateParams;779780var params =781    ChatCompletionCreateParams.builder()782        .model("gpt-6-astra")783        .addSystemMessage("You are a helpful assistant.")784        .addUserMessage("What is the capital of France?")785        .build();786var first = client.chat().completions().create(params);787788var second =789    client790        .chat()791        .completions()792        .create(793            params.toBuilder()794                .addAssistantMessage(first.choices().get(0).message().content().orElseThrow())795                .addUserMessage("And its population?")796                .build());797second.choices().stream()798    .flatMap(choice -> choice.message().content().stream())799    .forEach(System.out::println);800```801802```csharp803using OpenAI.Chat;804805string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;806string model = "gpt-6-astra";807ChatClient client = new(model, key);808809List<ChatMessage> messages =810[811    new SystemChatMessage("You are a helpful assistant."),812    new UserChatMessage("What is the capital of France?"),813];814ChatCompletion first = await client.CompleteChatAsync(messages);815816messages.Add(new AssistantChatMessage(first));817messages.Add(new UserChatMessage("And its population?"));818ChatCompletion second = await client.CompleteChatAsync(messages);819820Console.WriteLine(second.Content[0].Text);821```822823```ruby824require "openai"825826client = OpenAI::Client.new827messages = [828  {829    role: :system,830    content: "You are a helpful assistant."831  },832  {833    role: :user,834    content: "What is the capital of France?"835  }836]837838first = client.chat.completions.create(839  model: "gpt-6-astra",840  messages: messages841)842messages << {843  role: :assistant,844  content: first.choices.fetch(0).message.content845}846messages << {847  role: :user,848  content: "And its population?"849}850851second = client.chat.completions.create(852  model: "gpt-6-astra",853  messages: messages854)855856puts(second.choices.fetch(0).message.content)857```858859860  861862  863864    865Responses866867    With Responses, you can manually pass outputs from one response into the868    input of another.869    Multi-turn conversation870871```javascript872import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";873874let context = [{ role: "user", content: "What is the capital of France?" }];875876const res1 = await client.responses.create({877  model: "gpt-6-astra",878  input: context,879});880881// Append the first response’s output to context882context = context.concat(toResponseInputItems(res1.output));883884// Add the next user message885context.push({ role: "user", content: "And its population?" });886887const res2 = await client.responses.create({888  model: "gpt-6-astra",889  input: context,890});891```892893```python894context = [{"role": "user", "content": "What is the capital of France?"}]895res1 = client.responses.create(896    model="gpt-6-astra",897    input=context,898)899900# Append the first response's output to context901context += res1.output902903# Add the next user message904context += [{"role": "user", "content": "And its population?"}]905906res2 = client.responses.create(907    model="gpt-6-astra",908    input=context,909)910```911912```go913package main914915import (916	"context"917	"encoding/json"918	"fmt"919920	"github.com/openai/openai-go/v3"921	"github.com/openai/openai-go/v3/responses"922)923924func main() {925	client := openai.NewClient()926	contextItems := responses.ResponseInputParam{927		responses.ResponseInputItemParamOfMessage("What is the capital of France?", responses.EasyInputMessageRoleUser),928	}929	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{930		Model: "gpt-6-astra",931		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},932	})933	if err != nil {934		panic(err)935	}936	contextItems = append(contextItems, outputAsInput(first.Output)...)937	contextItems = append(contextItems, responses.ResponseInputItemParamOfMessage("And its population?", responses.EasyInputMessageRoleUser))938	second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{939		Model: "gpt-6-astra",940		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},941	})942	if err != nil {943		panic(err)944	}945	fmt.Println(second.OutputText())946}947948func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {949	input := make([]responses.ResponseInputItemUnionParam, 0, len(output))950	for _, item := range output {951		var converted responses.ResponseInputItemUnion952		if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {953			panic(err)954		}955		input = append(input, converted.ToParam())956	}957	return input958}959```960961```java962import com.openai.client.OpenAIClient;963import com.openai.client.okhttp.OpenAIOkHttpClient;964import com.openai.core.JsonValue;965import com.openai.models.responses.EasyInputMessage;966import com.openai.models.responses.ResponseCreateParams;967import com.openai.models.responses.ResponseInputItem;968import java.util.ArrayList;969970var history = new ArrayList<ResponseInputItem>();971history.add(972    ResponseInputItem.ofEasyInputMessage(973        EasyInputMessage.builder()974            .role(EasyInputMessage.Role.USER)975            .content("What is the capital of France?")976            .build()));977978var first =979    client980        .responses()981        .create(982            ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build());983first.output().stream()984    .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))985    .forEach(history::add);986history.add(987    ResponseInputItem.ofEasyInputMessage(988        EasyInputMessage.builder()989            .role(EasyInputMessage.Role.USER)990            .content("And its population?")991            .build()));992993client994    .responses()995    .create(ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build())996    .output()997    .stream()998    .flatMap(item -> item.message().stream())999    .flatMap(message -> message.content().stream())1000    .flatMap(content -> content.outputText().stream())1001    .forEach(text -> System.out.println(text.text()));1002```10031004```csharp1005using OpenAI.Responses;1006#pragma warning disable OPENAI00110071008string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1009ResponsesClient client = new(key);10101011List<ResponseItem> history =1012[1013    ResponseItem.CreateUserMessageItem("What is the capital of France?"),1014];10151016ResponseResult first = await client.CreateResponseAsync("gpt-6-astra", history);1017history.AddRange(first.OutputItems);1018history.Add(ResponseItem.CreateUserMessageItem("And its population?"));10191020ResponseResult second = await client.CreateResponseAsync("gpt-6-astra", history);1021Console.WriteLine(second.GetOutputText());1022```10231024```ruby1025require "openai"10261027client = OpenAI::Client.new1028context = [1029  {1030    role: :user,1031    content: "What is the capital of France?"1032  }1033]10341035first = client.responses.create(1036  model: "gpt-6-astra",1037  input: context1038)1039context.concat(first.output)1040context << {1041  role: :user,1042  content: "And its population?"1043}10441045second = client.responses.create(1046  model: "gpt-6-astra",1047  input: context1048)10491050puts(second.output_text)1051```10521053    You can also use `previous_response_id` to reference the previous response1054    and create response chains or forks.1055    Multi-turn conversation10561057```javascript1058const res1 = await client.responses.create({1059  model: "gpt-6-astra",1060  input: "What is the capital of France?",1061  store: true,1062});10631064const res2 = await client.responses.create({1065  model: "gpt-6-astra",1066  input: "And its population?",1067  previous_response_id: res1.id,1068  store: true,1069});1070```10711072```python1073res1 = client.responses.create(1074    model="gpt-6-astra", input="What is the capital of France?", store=True1075)10761077res2 = client.responses.create(1078    model="gpt-6-astra",1079    input="And its population?",1080    previous_response_id=res1.id,1081    store=True,1082)1083```10841085```go1086package main10871088import (1089	"context"1090	"fmt"10911092	"github.com/openai/openai-go/v3"1093	"github.com/openai/openai-go/v3/responses"1094)10951096func main() {1097	client := openai.NewClient()10981099	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1100		Model: "gpt-6-astra",1101		Store: openai.Bool(true),1102		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the capital of France?")},1103	})1104	if err != nil {1105		panic(err)1106	}11071108	second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1109		Model:              "gpt-6-astra",1110		Store:              openai.Bool(true),1111		PreviousResponseID: openai.String(first.ID),1112		Input:              responses.ResponseNewParamsInputUnion{OfString: openai.String("And its population?")},1113	})1114	if err != nil {1115		panic(err)1116	}1117	fmt.Println(second.OutputText())1118}1119```11201121```java1122import com.openai.client.OpenAIClient;1123import com.openai.client.okhttp.OpenAIOkHttpClient;1124import com.openai.models.responses.ResponseCreateParams;11251126var first =1127    client1128        .responses()1129        .create(1130            ResponseCreateParams.builder()1131                .model("gpt-6-astra")1132                .input("What is the capital of France?")1133                .store(true)1134                .build());11351136var second =1137    client1138        .responses()1139        .create(1140            ResponseCreateParams.builder()1141                .model("gpt-6-astra")1142                .input("And its population?")1143                .previousResponseId(first.id())1144                .store(true)1145                .build());1146second.output().stream()1147    .flatMap(item -> item.message().stream())1148    .flatMap(message -> message.content().stream())1149    .flatMap(content -> content.outputText().stream())1150    .forEach(text -> System.out.println(text.text()));1151```11521153```csharp1154using OpenAI.Responses;1155#pragma warning disable OPENAI00111561157string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1158ResponsesClient client = new(key);11591160ResponseResult first = await client.CreateResponseAsync(1161    "gpt-6-astra",1162    "What is the capital of France?"1163);1164ResponseResult second = await client.CreateResponseAsync(1165    "gpt-6-astra",1166    "And its population?",1167    previousResponseId: first.Id1168);11691170Console.WriteLine(second.GetOutputText());1171```11721173```ruby1174require "openai"11751176client = OpenAI::Client.new11771178first = client.responses.create(1179  model: "gpt-6-astra",1180  input: "What is the capital of France?",1181  store: true1182)11831184second = client.responses.create(1185  model: "gpt-6-astra",1186  previous_response_id: first.id,1187  input: "And its population?",1188  store: true1189)11901191puts(second.output_text)1192```1193119411951196Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.11971198### 4. Decide when to use statefulness11991200Responses are stored by default. Chat Completions are stored by default for new accounts. To disable storage in either API, set `store: false`.12011202Some organizations, such as those with Zero Data Retention (ZDR) requirements, cannot use the Responses API in a stateful way due to compliance or data retention policies. To support these cases, OpenAI offers encrypted reasoning items, allowing you to keep your workflow stateless while still benefiting from reasoning items.12031204To disable statefulness but still take advantage of reasoning:12051206- Set `store: false` in the [store field](https://developers.openai.com/api/reference/resources/responses/methods/create#responses_create-store).1207- Preserve and replay every returned reasoning item. Each item includes `encrypted_content` by default when you create a response.12081209The API will then return an encrypted version of the reasoning tokens, which you can pass back in future requests just like regular reasoning items.1210For ZDR organizations, OpenAI enforces `store: false` automatically. When a request includes `encrypted_content`, it is decrypted in memory, used for generating the next response, and then securely discarded. Any new reasoning tokens are immediately encrypted and returned to you, ensuring no intermediate state is persisted.12111212### 5. Update function definitions and outputs12131214There are two minor, but notable, differences in how functions are defined between Chat Completions and Responses.121512161. In Chat Completions, function definitions are externally tagged. In Responses, they are internally tagged.12172. In Chat Completions, functions are non-strict by default. In Responses, omitting `strict` attempts strict mode; if the schema cannot be made compatible, Responses falls back to non-strict, best-effort function calling and returns the resolved tool with `strict: false`. To keep non-strict behavior in Responses explicitly, set `strict: false`.12181219The Responses API function example on the right is functionally equivalent to the Chat Completions example on the left.1220122112221223#### Chat Completions API12241225```json1226{1227    "type": "function",1228    "function": {1229      "name": "get_weather",1230      "description": "Determine weather in my location",1231      "strict": true,1232      "parameters": {1233        "type": "object",1234        "properties": {1235          "location": {1236            "type": "string"1237          }1238        },1239        "additionalProperties": false,1240        "required": [1241          "location"1242        ]1243      }1244    }1245}1246```12471248#### Responses API12491250```json1251{1252    "type": "function",1253    "name": "get_weather",1254    "description": "Determine weather in my location",1255    "parameters": {1256      "type": "object",1257      "properties": {1258        "location": {1259          "type": "string"1260        }1261      },1262      "additionalProperties": false,1263      "required": [1264        "location"1265      ]1266    }1267}1268```1269127012711272#### Follow function-calling best practices12731274In Responses, tool calls and their outputs are two distinct types of Items that are correlated using a `call_id`. See1275the [function calling docs](https://developers.openai.com/api/docs/guides/function-calling#function-tool-example) for more detail on how function calling works in Responses.12761277### 6. Update Structured Outputs definitions12781279In the Responses API, Structured Outputs definitions have moved from `response_format` to `text.format`:1280128112821283Chat Completions12841285    Structured Outputs12861287```javascript1288const completion = await openai.chat.completions.create({1289  model: "gpt-6-astra",1290  messages: [1291    {1292      role: "user",1293      content: "Jane, 54 years old",1294    },1295  ],1296  response_format: {1297    type: "json_schema",1298    json_schema: {1299      name: "person",1300      strict: true,1301      schema: {1302        type: "object",1303        properties: {1304          name: {1305            type: "string",1306            minLength: 1,1307          },1308          age: {1309            type: "number",1310            minimum: 0,1311            maximum: 130,1312          },1313        },1314        required: ["name", "age"],1315        additionalProperties: false,1316      },1317    },1318  },1319  reasoning_effort: "medium",1320});1321```13221323```python1324from openai import OpenAI13251326client = OpenAI()13271328response = client.chat.completions.create(1329    model="gpt-6-astra",1330    messages=[1331        {1332            "role": "user",1333            "content": "Jane, 54 years old",1334        }1335    ],1336    response_format={1337        "type": "json_schema",1338        "json_schema": {1339            "name": "person",1340            "strict": True,1341            "schema": {1342                "type": "object",1343                "properties": {1344                    "name": {"type": "string", "minLength": 1},1345                    "age": {"type": "number", "minimum": 0, "maximum": 130},1346                },1347                "required": ["name", "age"],1348                "additionalProperties": False,1349            },1350        },1351    },1352    reasoning_effort="medium",1353)1354```13551356```go1357package main13581359import (1360	"context"1361	"fmt"13621363	"github.com/openai/openai-go/v3"1364	"github.com/openai/openai-go/v3/shared"1365)13661367func main() {1368	client := openai.NewClient()1369	schema := map[string]any{1370		"type": "object",1371		"properties": map[string]any{1372			"name": map[string]any{"type": "string", "minLength": 1},1373			"age":  map[string]any{"type": "number", "minimum": 0, "maximum": 130},1374		},1375		"required":             []string{"name", "age"},1376		"additionalProperties": false,1377	}13781379	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{1380		Model:           "gpt-6-astra",1381		ReasoningEffort: openai.ReasoningEffortMedium,1382		Messages: []openai.ChatCompletionMessageParamUnion{1383			openai.UserMessage("Jane, 54 years old"),1384		},1385		ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{1386			OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{1387				Name: "person", Strict: openai.Bool(true), Schema: schema,1388			}},1389		},1390	})1391	if err != nil {1392		panic(err)1393	}1394	fmt.Println(completion.Choices[0].Message.Content)1395}1396```13971398```java1399import com.openai.client.OpenAIClient;1400import com.openai.client.okhttp.OpenAIOkHttpClient;1401import com.openai.core.JsonValue;1402import com.openai.models.ReasoningEffort;1403import com.openai.models.chat.completions.ChatCompletionCreateParams;1404import java.util.List;1405import java.util.Map;14061407ChatCompletionCreateParams params =1408    ChatCompletionCreateParams.builder()1409        .model("gpt-6-astra")1410        .reasoningEffort(ReasoningEffort.MEDIUM)1411        .addUserMessage("Jane, 54 years old")1412        .putAdditionalBodyProperty(1413            "response_format",1414            JsonValue.from(1415                Map.of(1416                    "type",1417                    "json_schema",1418                    "json_schema",1419                    Map.of(1420                        "name",1421                        "person",1422                        "strict",1423                        true,1424                        "schema",1425                        Map.of(1426                            "type",1427                            "object",1428                            "properties",1429                            Map.of(1430                                "name",1431                                Map.of("type", "string", "minLength", 1),1432                                "age",1433                                Map.of("type", "number", "minimum", 0, "maximum", 130)),1434                            "required",1435                            List.of("name", "age"),1436                            "additionalProperties",1437                            false)))))1438        .build();14391440client.chat().completions().create(params).choices().stream()1441    .flatMap(choice -> choice.message().content().stream())1442    .forEach(System.out::println);1443```14441445```csharp1446using OpenAI.Chat;1447#pragma warning disable OPENAI00114481449string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1450string model = "gpt-6-astra";1451ChatClient client = new(model, key);14521453BinaryData schema = BinaryData.FromString(1454    """1455    {1456      "type": "object",1457      "properties": {1458        "name": { "type": "string", "minLength": 1 },1459        "age": { "type": "number", "minimum": 0, "maximum": 130 }1460      },1461      "required": ["name", "age"],1462      "additionalProperties": false1463    }1464    """1465);1466ChatCompletionOptions options = new()1467{1468    ReasoningEffortLevel = ChatReasoningEffortLevel.Medium,1469    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(1470        "person",1471        schema,1472        jsonSchemaIsStrict: true1473    ),1474};14751476ChatCompletion completion = await client.CompleteChatAsync(1477    [new UserChatMessage("Jane, 54 years old")],1478    options1479);14801481Console.WriteLine(completion.Content[0].Text);1482```14831484```ruby1485require "openai"14861487client = OpenAI::Client.new1488schema = {1489  type: "object",1490  properties: {1491    name: {1492      type: "string",1493      minLength: 11494    },1495    age: {1496      type: "number",1497      minimum: 0,1498      maximum: 1301499    }1500  },1501  required: ["name", "age"],1502  additionalProperties: false1503}15041505completion = client.chat.completions.create(1506  model: "gpt-6-astra",1507  reasoning_effort: :medium,1508  messages: [1509    {1510      role: :user,1511      content: "Jane, 54 years old"1512    }1513  ],1514  response_format: {1515    type: :json_schema,1516    json_schema: {1517      name: "person",1518      strict: true,1519      schema: schema1520    }1521  }1522)15231524puts(completion.choices.fetch(0).message.content)1525```15261527```bash1528curl https://api.openai.com/v1/chat/completions \1529  -H "Content-Type: application/json" \1530  -H "Authorization: Bearer $OPENAI_API_KEY" \1531  -d '{1532  "model": "gpt-6-astra",1533  "messages": [1534    {1535      "role": "user",1536      "content": "Jane, 54 years old"1537    }1538  ],1539  "response_format": {1540    "type": "json_schema",1541    "json_schema": {1542      "name": "person",1543      "strict": true,1544      "schema": {1545        "type": "object",1546        "properties": {1547          "name": {1548            "type": "string",1549            "minLength": 11550          },1551          "age": {1552            "type": "number",1553            "minimum": 0,1554            "maximum": 1301555          }1556        },1557        "required": [1558          "name",1559          "age"1560        ],1561        "additionalProperties": false1562      }1563    }1564  },1565  "reasoning_effort": "medium"1566}'1567```15681569  15701571  15721573    1574Responses15751576    Structured Outputs15771578```javascript1579const response = await openai.responses.create({1580  model: "gpt-6-astra",1581  input: "Jane, 54 years old",1582  text: {1583    format: {1584      type: "json_schema",1585      name: "person",1586      strict: true,1587      schema: {1588        type: "object",1589        properties: {1590          name: {1591            type: "string",1592            minLength: 1,1593          },1594          age: {1595            type: "number",1596            minimum: 0,1597            maximum: 130,1598          },1599        },1600        required: ["name", "age"],1601        additionalProperties: false,1602      },1603    },1604  },1605});1606```16071608```python1609response = client.responses.create(1610    model="gpt-6-astra",1611    input="Jane, 54 years old",1612    text={1613        "format": {1614            "type": "json_schema",1615            "name": "person",1616            "strict": True,1617            "schema": {1618                "type": "object",1619                "properties": {1620                    "name": {"type": "string", "minLength": 1},1621                    "age": {"type": "number", "minimum": 0, "maximum": 130},1622                },1623                "required": ["name", "age"],1624                "additionalProperties": False,1625            },1626        }1627    },1628)1629```16301631```go1632package main16331634import (1635	"context"1636	"fmt"16371638	"github.com/openai/openai-go/v3"1639	"github.com/openai/openai-go/v3/responses"1640)16411642func main() {1643	client := openai.NewClient()1644	schema := map[string]any{1645		"type": "object",1646		"properties": map[string]any{1647			"name": map[string]any{"type": "string", "minLength": 1},1648			"age":  map[string]any{"type": "number", "minimum": 0, "maximum": 130},1649		},1650		"required":             []string{"name", "age"},1651		"additionalProperties": false,1652	}16531654	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1655		Model: "gpt-6-astra",1656		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Jane, 54 years old")},1657		Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{1658			OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "person", Schema: schema, Strict: openai.Bool(true)},1659		}},1660	})1661	if err != nil {1662		panic(err)1663	}1664	fmt.Println(response.OutputText())1665}1666```16671668```java1669import com.openai.client.OpenAIClient;1670import com.openai.client.okhttp.OpenAIOkHttpClient;1671import com.openai.core.JsonValue;1672import com.openai.models.responses.ResponseCreateParams;1673import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;1674import com.openai.models.responses.ResponseTextConfig;1675import java.util.List;1676import java.util.Map;16771678ResponseCreateParams params =1679    ResponseCreateParams.builder()1680        .model("gpt-6-astra")1681        .input("Jane, 54 years old")1682        .text(1683            ResponseTextConfig.builder()1684                .format(1685                    ResponseFormatTextJsonSchemaConfig.builder()1686                        .name("person")1687                        .strict(true)1688                        .schema(1689                            ResponseFormatTextJsonSchemaConfig.Schema.builder()1690                                .putAdditionalProperty("type", JsonValue.from("object"))1691                                .putAdditionalProperty(1692                                    "properties",1693                                    JsonValue.from(1694                                        Map.of(1695                                            "name",1696                                            Map.of("type", "string", "minLength", 1),1697                                            "age",1698                                            Map.of(1699                                                "type", "number", "minimum", 0, "maximum",1700                                                130))))1701                                .putAdditionalProperty(1702                                    "required", JsonValue.from(List.of("name", "age")))1703                                .putAdditionalProperty(1704                                    "additionalProperties", JsonValue.from(false))1705                                .build())1706                        .build())1707                .build())1708        .build();17091710client.responses().create(params).output().stream()1711    .flatMap(item -> item.message().stream())1712    .flatMap(message -> message.content().stream())1713    .flatMap(content -> content.outputText().stream())1714    .forEach(text -> System.out.println(text.text()));1715```17161717```csharp1718using OpenAI.Responses;1719#pragma warning disable OPENAI00117201721string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1722ResponsesClient client = new(key);17231724BinaryData schema = BinaryData.FromString(1725    """1726    {1727      "type": "object",1728      "properties": {1729        "name": { "type": "string", "minLength": 1 },1730        "age": { "type": "number", "minimum": 0, "maximum": 130 }1731      },1732      "required": ["name", "age"],1733      "additionalProperties": false1734    }1735    """1736);1737CreateResponseOptions options = new()1738{1739    Model = "gpt-6-astra",1740    TextOptions = new ResponseTextOptions1741    {1742        TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(1743            "person",1744            schema,1745            jsonSchemaIsStrict: true1746        ),1747    },1748};1749options.InputItems.Add(1750    ResponseItem.CreateUserMessageItem("Jane, 54 years old")1751);17521753ResponseResult response = await client.CreateResponseAsync(options);17541755Console.WriteLine(response.GetOutputText());1756```17571758```ruby1759require "openai"17601761client = OpenAI::Client.new1762schema = {1763  type: "object",1764  properties: {1765    name: {1766      type: "string",1767      minLength: 11768    },1769    age: {1770      type: "number",1771      minimum: 0,1772      maximum: 1301773    }1774  },1775  required: ["name", "age"],1776  additionalProperties: false1777}17781779response = client.responses.create(1780  model: "gpt-6-astra",1781  input: "Jane, 54 years old",1782  text: {1783    format: {1784      type: :json_schema,1785      name: "person",1786      strict: true,1787      schema: schema1788    }1789  }1790)17911792puts(response.output_text)1793```17941795```bash1796curl https://api.openai.com/v1/responses \1797  -H "Content-Type: application/json" \1798  -H "Authorization: Bearer $OPENAI_API_KEY" \1799  -d '{1800  "model": "gpt-6-astra",1801  "input": "Jane, 54 years old",1802  "text": {1803    "format": {1804      "type": "json_schema",1805      "name": "person",1806      "strict": true,1807      "schema": {1808        "type": "object",1809        "properties": {1810          "name": {1811            "type": "string",1812            "minLength": 11813          },1814          "age": {1815            "type": "number",1816            "minimum": 0,1817            "maximum": 1301818          }1819        },1820        "required": [1821          "name",1822          "age"1823        ],1824        "additionalProperties": false1825      }1826    }1827  }1828}'1829```1830183118321833### 7. Update streaming consumers18341835Chat Completions streaming returns incremental chunks with a `delta` field. Responses streaming uses typed server-sent events. Update stream consumers to branch on each event's `type` and handle the events your UI or orchestration layer needs.18361837For text streaming, listen for events such as:18381839- `response.created`1840- `response.output_text.delta`1841- `response.completed`1842- `error`18431844Function-calling streams can also emit events such as `response.function_call_arguments.delta` and `response.function_call_arguments.done`. See the [streaming Responses guide](https://developers.openai.com/api/docs/guides/streaming-responses?api-mode=responses) and [Responses streaming events reference](https://developers.openai.com/api/reference/resources/responses).18451846### 8. Upgrade to native tools18471848If your application has use cases that would benefit from OpenAI's native [tools](https://developers.openai.com/api/docs/guides/tools), you can update your tool calls to use OpenAI's tools out of the box.1849185018511852Chat Completions18531854    With Chat Completions, you cannot use OpenAI-hosted tools natively and have1855    to write your own tool integration.1856    This example uses GPT-5.6 because GPT-6 Astra requires the Responses API1857    for tool calling.1858    Web search tool18591860```javascript1861async function web_search(query) {1862  const res = await fetch(`https://api.example.com/search?q=${query}`);1863  const data = await res.json();1864  return data.results;1865}18661867const completion = await client.chat.completions.create({1868  model: "gpt-5.6",1869  messages: [1870    { role: "system", content: "You are a helpful assistant." },1871    { role: "user", content: "Who is the current president of France?" },1872  ],1873  functions: [1874    {1875      name: "web_search",1876      description: "Search the web for information",1877      parameters: {1878        type: "object",1879        properties: { query: { type: "string" } },1880        required: ["query"],1881      },1882    },1883  ],1884});1885```18861887```python1888import requests188918901891def web_search(query):1892    r = requests.get(f"https://api.example.com/search?q={query}")1893    return r.json().get("results", [])189418951896completion = client.chat.completions.create(1897    model="gpt-5.6",1898    messages=[1899        {"role": "system", "content": "You are a helpful assistant."},1900        {"role": "user", "content": "Who is the current president of France?"},1901    ],1902    functions=[1903        {1904            "name": "web_search",1905            "description": "Search the web for information",1906            "parameters": {1907                "type": "object",1908                "properties": {"query": {"type": "string"}},1909                "required": ["query"],1910            },1911        }1912    ],1913)1914```19151916```go1917package main19181919import (1920	"context"1921	"fmt"19221923	"github.com/openai/openai-go/v3"1924	"github.com/openai/openai-go/v3/shared"1925)19261927func main() {1928	client := openai.NewClient()1929	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{1930		Model: "gpt-5.6",1931		Messages: []openai.ChatCompletionMessageParamUnion{1932			openai.SystemMessage("You are a helpful assistant."),1933			openai.UserMessage("Who is the current president of France?"),1934		},1935		Functions: []openai.ChatCompletionNewParamsFunction{{1936			Name:        "web_search",1937			Description: openai.String("Search the web for information"),1938			Parameters: map[string]any{1939				"type":       "object",1940				"properties": map[string]any{"query": map[string]any{"type": "string"}},1941				"required":   []string{"query"},1942			},1943		}},1944		ReasoningEffort: shared.ReasoningEffortNone,1945	})1946	if err != nil {1947		panic(err)1948	}1949	fmt.Println(completion.Choices[0].Message)1950}1951```19521953```java1954import com.openai.client.OpenAIClient;1955import com.openai.client.okhttp.OpenAIOkHttpClient;1956import com.openai.core.JsonValue;1957import com.openai.models.FunctionParameters;1958import com.openai.models.ReasoningEffort;1959import com.openai.models.chat.completions.ChatCompletionCreateParams;1960import java.util.List;1961import java.util.Map;19621963ChatCompletionCreateParams params =1964    ChatCompletionCreateParams.builder()1965        .model("gpt-5.6")1966        .reasoningEffort(ReasoningEffort.NONE)1967        .addSystemMessage("You are a helpful assistant.")1968        .addUserMessage("Who is the current president of France?")1969        .addFunction(1970            ChatCompletionCreateParams.Function.builder()1971                .name("web_search")1972                .description("Search the web for information")1973                .parameters(1974                    FunctionParameters.builder()1975                        .putAdditionalProperty("type", JsonValue.from("object"))1976                        .putAdditionalProperty(1977                            "properties",1978                            JsonValue.from(Map.of("query", Map.of("type", "string"))))1979                        .putAdditionalProperty("required", JsonValue.from(List.of("query")))1980                        .build())1981                .build())1982        .build();19831984client.chat().completions().create(params).choices().stream()1985    .map(choice -> choice.message())1986    .forEach(System.out::println);1987```19881989```ruby1990require "openai"19911992client = OpenAI::Client.new19931994completion = client.chat.completions.create(1995  model: "gpt-5.6",1996  reasoning_effort: :none,1997  messages: [1998    {1999      role: :system,2000      content: "You are a helpful assistant."2001    },2002    {2003      role: :user,2004      content: "Who is the current president of France?"2005    }2006  ],2007  functions: [2008    {2009      name: "web_search",2010      description: "Search the web for information",2011      parameters: {2012        type: "object",2013        properties: { query: { type: "string" } },2014        required: ["query"]2015      }2016    }2017  ]2018)20192020puts(completion.choices.fetch(0).message)2021```20222023```bash2024curl https://api.example.com/search \2025  -G \2026  --data-urlencode "q=your+search+term" \2027  --data-urlencode "key=$SEARCH_API_KEY"\2028```20292030  20312032  20332034    2035Responses20362037    With Responses, you can specify the tools that you want the model to use.2038    Web search tool20392040```javascript2041const answer = await client.responses.create({2042  model: "gpt-6-astra",2043  input: "Who is the current president of France?",2044  tools: [{ type: "web_search" }],2045});20462047console.log(answer.output_text);2048```20492050```python2051answer = client.responses.create(2052    model="gpt-6-astra",2053    input="Who is the current president of France?",2054    tools=[{"type": "web_search"}],2055)20562057print(answer.output_text)2058```20592060```go2061package main20622063import (2064	"context"2065	"fmt"20662067	"github.com/openai/openai-go/v3"2068	"github.com/openai/openai-go/v3/responses"2069)20702071func main() {2072	client := openai.NewClient()2073	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2074		Model: "gpt-6-astra",2075		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Who is the current president of France?")},2076		Tools: []responses.ToolUnionParam{2077			responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),2078		},2079	})2080	if err != nil {2081		panic(err)2082	}2083	fmt.Println(response.OutputText())2084}2085```20862087```java2088import com.openai.client.OpenAIClient;2089import com.openai.client.okhttp.OpenAIOkHttpClient;2090import com.openai.models.responses.ResponseCreateParams;2091import com.openai.models.responses.WebSearchTool;20922093ResponseCreateParams params =2094    ResponseCreateParams.builder()2095        .model("gpt-6-astra")2096        .input("Who is the current president of France?")2097        .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())2098        .build();20992100client.responses().create(params).output().stream()2101    .flatMap(item -> item.message().stream())2102    .flatMap(message -> message.content().stream())2103    .flatMap(content -> content.outputText().stream())2104    .forEach(text -> System.out.println(text.text()));2105```21062107```csharp2108using OpenAI.Responses;2109#pragma warning disable OPENAI00121102111string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;2112ResponsesClient client = new(key);21132114CreateResponseOptions options = new() { Model = "gpt-6-astra" };2115options.Tools.Add(ResponseTool.CreateWebSearchTool());2116options.InputItems.Add(2117    ResponseItem.CreateUserMessageItem("Who is the current president of France?")2118);21192120ResponseResult response = await client.CreateResponseAsync(options);2121Console.WriteLine(response.GetOutputText());2122```21232124```ruby2125require "openai"21262127client = OpenAI::Client.new21282129response = client.responses.create(2130  model: "gpt-6-astra",2131  input: "Who is the current president of France?",2132  tools: [{ type: :web_search }]2133)21342135puts(response.output_text)2136```21372138```bash2139curl https://api.openai.com/v1/responses \2140  -H "Content-Type: application/json" \2141  -H "Authorization: Bearer $OPENAI_API_KEY" \2142  -d '{2143    "model": "gpt-6-astra",2144    "input": "Who is the current president of France?",2145    "tools": [{"type": "web_search"}]2146  }'2147```2148214921502151### 9. Check common migration errors21522153Watch for these issues when moving code from Chat Completions to Responses:21542155- Reading `choices[0].message.content` instead of `response.output_text` or `response.output`.2156- Treating every `output` entry as a message. Reasoning, tool, and function calls are separate Item types.2157- Dropping reasoning, function call, or function call output Items when manually carrying context into the next response.2158- Sending a function result without the matching `call_id`.2159- Using `response_format` in a Responses request instead of `text.format`.2160- Reusing Chat Completions streaming chunk handlers without handling typed Responses events.2161- Assuming `previous_response_id` removes billing for prior context. Previous input tokens in the response chain are still billed as input tokens.21622163## Incremental rollout checklist21642165Chat Completions remains supported, so you can migrate one user flow at a time.21662167- [ ] Start with a simple text-generation flow.2168- [ ] Update the endpoint, request body, and output handling.2169- [ ] Decide whether the flow uses `previous_response_id`, manual Item replay, or the Conversations API.2170- [ ] If the flow is stateless or ZDR, add `store: false` and include encrypted reasoning items when reasoning context must continue across turns.2171- [ ] Migrate function definitions and verify function call outputs include the correct `call_id`.2172- [ ] Move Structured Outputs schemas from `response_format` to `text.format`.2173- [ ] Update streaming consumers to handle typed Responses events.2174- [ ] Replace custom orchestration with OpenAI-hosted tools where they fit the workflow.2175- [ ] Compare behavior, latency, token usage, and errors before routing more traffic to Responses.21762177We recommend migrating all flows to the Responses API over time to take advantage of the latest OpenAI features and improvements.21782179## Assistants API21802181Based on developer feedback from the [Assistants API](https://developers.openai.com/api/reference/resources/beta/subresources/assistants) beta, we've incorporated key improvements into the Responses API to make it more flexible, faster, and easier to use. The Responses API represents the future direction for building agents on OpenAI.21822183The Assistants API was officially sunset on August 26, 2026, and is no longer available. Follow the [migration guide](https://developers.openai.com/api/docs/assistants/migration) to update your integration to the Responses API.
Files main
Menu

Theme