SPB Git

Repository Public

reasoning.md 68.6 KB 2,119 lines markdown

1# Reasoning models23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45**Reasoning models** use internal reasoning tokens before producing a response. This helps the model plan, use tools effectively, inspect alternatives, recover from ambiguity, and solve harder multi-step tasks. Reasoning models work especially well for complex problem solving, coding, scientific reasoning, and multi-step agentic workflows. They're also the best models for [Codex CLI](https://github.com/openai/codex), our lightweight coding agent.67Start with `gpt-6-astra` for most reasoning workloads. For lower cost, consider [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra), or [`gpt-5.6-luna`](https://developers.openai.com/api/docs/models/gpt-5.6-luna) for the lowest cost and latency. If you're using a GPT-5.6 model, see [reasoning mode](#reasoning-mode) for its `pro` option.89**Reasoning models work better with the [Responses10  API](https://developers.openai.com/api/docs/guides/migrate-to-responses)**. While the Chat Completions API11  is still supported, you'll get improved model intelligence and performance by12  using Responses.1314## Get started with reasoning1516Call the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) and specify your reasoning model and reasoning effort:1718Using a reasoning model in the Responses API1920```javascript21import OpenAI from "openai";2223const openai = new OpenAI();2425const prompt = `26Write a bash script that takes a matrix represented as a string with27format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.28`;2930const response = await openai.responses.create({31  model: "gpt-6-astra",32  reasoning: { effort: "low" },33  input: [34    {35      role: "user",36      content: prompt,37    },38  ],39});4041console.log(response.output_text);42```4344```python45from openai import OpenAI4647client = OpenAI()4849prompt = """50Write a bash script that takes a matrix represented as a string with51format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.52"""5354response = client.responses.create(55    model="gpt-6-astra",56    reasoning={"effort": "low"},57    input=[{"role": "user", "content": prompt}],58)5960print(response.output_text)61```6263```go64package main6566import (67	"context"68	"fmt"6970	"github.com/openai/openai-go/v3"71	"github.com/openai/openai-go/v3/responses"72)7374func main() {75	client := openai.NewClient()76	prompt := `Write a bash script that takes a matrix represented as a string with77format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`7879	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{80		Model: "gpt-6-astra",81		Reasoning: responses.ReasoningParam{82			Effort: responses.ReasoningEffortLow,83		},84		Input: responses.ResponseNewParamsInputUnion{85			OfString: openai.String(prompt),86		},87	})88	if err != nil {89		panic(err)90	}9192	fmt.Println(response.OutputText())93}94```9596```java97import com.openai.client.OpenAIClient;98import com.openai.client.okhttp.OpenAIOkHttpClient;99import com.openai.models.Reasoning;100import com.openai.models.ReasoningEffort;101import com.openai.models.responses.ResponseCreateParams;102103String prompt =104    """105    Write a bash script that takes a matrix represented as a string with format106    '[1,2],[3,4],[5,6]' and prints the transpose in the same format.107    """108        .strip();109110ResponseCreateParams params =111    ResponseCreateParams.builder()112        .model("gpt-6-astra")113        .input(prompt)114        .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())115        .build();116117client.responses().create(params).output().stream()118    .flatMap(item -> item.message().stream())119    .flatMap(message -> message.content().stream())120    .flatMap(content -> content.outputText().stream())121    .forEach(text -> System.out.println(text.text()));122```123124```csharp125using OpenAI.Responses;126#pragma warning disable OPENAI001127128string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;129ResponsesClient client = new(key);130131string prompt =132    """133    Write a bash script that takes a matrix represented as a string with format134    '[1,2],[3,4],[5,6]' and prints the transpose in the same format.135    """;136CreateResponseOptions options = new()137{138    Model = "gpt-6-astra",139    ReasoningOptions = new ResponseReasoningOptions140    {141        ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,142    },143};144options.InputItems.Add(ResponseItem.CreateUserMessageItem(prompt));145146ResponseResult response = await client.CreateResponseAsync(options);147148Console.WriteLine(response.GetOutputText());149```150151```ruby152require "openai"153154client = OpenAI::Client.new155prompt = <<~PROMPT156  Write a bash script that takes a matrix represented as a string with format157  '[1,2],[3,4],[5,6]' and prints the transpose in the same format.158PROMPT159160response = client.responses.create(161  model: "gpt-6-astra",162  reasoning: { effort: :low },163  input: prompt164)165166puts(response.output_text)167```168169```bash170curl https://api.openai.com/v1/responses \171  -H "Content-Type: application/json" \172  -H "Authorization: Bearer $OPENAI_API_KEY" \173  -d '{174    "model": "gpt-6-astra",175    "reasoning": {"effort": "low"},176    "input": [177      {178        "role": "user",179        "content": "Write a bash script that takes a matrix represented as a string with format \"[1,2],[3,4],[5,6]\" and prints the transpose in the same format."180      }181    ]182  }'183```184185186## Reasoning effort187188The `reasoning.effort` parameter guides the model on how much to think when performing a task.189190Supported values are model-dependent and can include `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Lower effort favors speed and lower token usage, while at higher effort the model thinks more completely to provide higher quality responses. The models also reason adaptively across reasoning efforts, using fewer tokens for simpler tasks and thinking harder for complex tasks.191192[GPT-6 Astra](https://developers.openai.com/api/docs/models/gpt-6-astra) does not support `none` reasoning193  effort. Setting `reasoning.effort` (Responses) or `reasoning_effort` (Chat194  Completions) to `none` returns HTTP 400.195196Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for function197calling. Chat Completions does not support function calling with GPT-6 Astra.198199Defaults are also model-dependent rather than universal. `gpt-5.5` defaults to `medium` reasoning effort. This is the best starting point for `gpt-5.5`’s full balance of quality, reliability and performance.200201| Effort   | Best for                                                                                                                                                                                                                                                                                                                                                             |202| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |203| `none`   | Latency-critical tasks that do not benefit from any reasoning or multi-chained tool calls. For latency-sensitive use cases with `gpt-5.5`, we recommend trying `low` to begin with and then moving to `none` if required.<br /><br />Common use cases include voice, fast information retrieval, and classification.                                                 |204| `low`    | Efficient reasoning with a modest latency increase. Ideal for use cases requiring tool-use, planning, search, or multi-step decision making, while optimizing for speed and cost.<br /><br />Common use cases include data analysis, drafting, execution-oriented coding, and customer support / chat assistant workflows.                                           |205| `medium` | When quality and reliability matter, and the task involves planning, complex reasoning, and judgement. Default configuration for most workloads, and a well-balanced point on the pareto curve of latency, performance and cost.<br /><br />Common use cases include agentic coding, research, working with spreadsheets & slides, and delegating long-horizon work. |206| `high`   | Hard reasoning, complex debugging, deep planning, and high-value tasks where quality and intelligence matters more than latency. Recommended for complex workflows and agentic tasks.<br /><br />Common use cases include agentic coding, long-horizon research, and knowledge work. Depending on the complexity of the task, evaluate both `medium` and `high`.     |207| `xhigh`  | Deep research, asynchronous workflows and agentic tasks that require long runs. Only use when your evals show a clear benefit that justifies the extra latency and cost.<br /><br />Common use cases include security and code review, enterprise productivity, deeper research tasks, and challenging coding workflows.                                             |208| `max`    | Maximum reasoning for your most complex tasks. If you are currently using `xhigh`, evaluate if `max` results in stronger performance                                                                                                                                                                                                                                 |209210For faster time to first visible token in latency-sensitive applications, ask the model to generate a short preamble before continuing with deeper reasoning.211212Some models support only a subset of these values, so check the relevant [model page](https://developers.openai.com/api/docs/models) before choosing a setting.213214## Reasoning mode215216GPT-5.6 models support `standard` and `pro` reasoning modes in the Responses API. `standard` is the default. Set `reasoning.mode` to `pro` for difficult tasks that need more model work and can tolerate higher latency and token usage.217218Reasoning mode and reasoning effort are independent. Mode selects standard or pro execution, while `reasoning.effort` controls how much reasoning the model applies within that mode. If you omit `reasoning.effort`, GPT-5.6 defaults to `medium` in both modes.219220Using pro reasoning mode221222```bash223curl https://api.openai.com/v1/responses \224  -H "Content-Type: application/json" \225  -H "Authorization: Bearer $OPENAI_API_KEY" \226  -d '{227    "model": "gpt-5.6",228    "reasoning": {229      "mode": "pro",230      "effort": "medium"231    },232    "input": "Review this database migration plan and identify potential failure modes."233  }'234```235236237Pro mode aggregates the model work performed to produce the final answer and bills those tokens at the selected model's standard [token rates](https://developers.openai.com/api/docs/pricing). Pro mode performs more model work than standard mode, increasing token usage and cost. Existing Pro model IDs keep their current behavior and pricing.238239## How reasoning works240241Reasoning models introduce **reasoning tokens** in addition to input and output tokens. The models use these reasoning tokens to "think," breaking down the prompt and considering multiple approaches to generating a response. Our reasoning models like `gpt-5.5` and `gpt-5.4` support interleaved thinking, where the model is able to generate visible output tokens before and in between thinking, and is able to think in between tool calls.242243For models released before GPT-5.6, the default behavior in a multi-step conversation is to carry over input and output tokens from each step without rendering reasoning from earlier turns into the next sample. GPT-5.6 models instead default to rendering available reasoning from earlier turns. Use `reasoning.context` to select either behavior on supported models.244245![Reasoning tokens with current-turn context](https://cdn.openai.com/API/docs/images/context-window.png)246247While reasoning tokens are not visible via the API, they still occupy space in248  the model's context window and are billed as [output249  tokens](https://openai.com/api/pricing).250251## Controlling costs252253To manage costs with reasoning models, you can limit the total number of tokens the254model generates, including reasoning tokens, visible output tokens, and non-visible255formatting tokens, by using the256[`max_output_tokens`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-max_output_tokens)257parameter. See [output token counts](https://developers.openai.com/api/docs/guides/token-counting#understand-output-token-counts) for details about how generated tokens are reflected in usage and output limits.258259### Managing the context window260261It's important to ensure there's enough space in the context window for reasoning tokens when creating responses. Depending on the problem's complexity, the models may generate anywhere from a few hundred to tens of thousands of reasoning tokens. The exact number of reasoning tokens used is visible in the [usage object of the response object](https://developers.openai.com/api/reference/resources/responses), under `output_tokens_details`:262263```json264{265  "usage": {266    "input_tokens": 75,267    "input_tokens_details": {268      "cached_tokens": 0269    },270    "output_tokens": 1186,271    "output_tokens_details": {272      "reasoning_tokens": 1024273    },274    "total_tokens": 1261275  }276}277```278279Context window lengths are found on the [model reference page](https://developers.openai.com/api/docs/models), and will differ across model snapshots.280281### Allocating space for reasoning282283If the generated tokens reach the context window limit or the `max_output_tokens` value you've set, you'll receive a response with a `status` of `incomplete` and `incomplete_details` with `reason` set to `max_output_tokens`. This might occur before any visible output tokens are produced, meaning you could incur costs for input and reasoning tokens without receiving a visible response.284285To prevent this, ensure there's sufficient space in the context window or adjust the `max_output_tokens` value to a higher number. OpenAI recommends reserving at least 25,000 tokens for reasoning and outputs when you start experimenting with these models. As you become familiar with the number of reasoning tokens your prompts require, you can adjust this buffer accordingly.286287Handling incomplete responses288289```javascript290import OpenAI from "openai";291292const openai = new OpenAI();293294const prompt = `295Write a bash script that takes a matrix represented as a string with296format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.297`;298299const response = await openai.responses.create({300  model: "gpt-6-astra",301  reasoning: { effort: "medium" },302  input: [303    {304      role: "user",305      content: prompt,306    },307  ],308  max_output_tokens: 300,309});310311if (312  response.status === "incomplete" &&313  response.incomplete_details.reason === "max_output_tokens"314) {315  console.log("Ran out of tokens");316  if (response.output_text?.length > 0) {317    console.log("Partial output:", response.output_text);318  } else {319    console.log("Ran out of tokens during reasoning");320  }321}322```323324```python325from openai import OpenAI326327client = OpenAI()328329prompt = """330Write a bash script that takes a matrix represented as a string with331format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.332"""333334response = client.responses.create(335    model="gpt-6-astra",336    reasoning={"effort": "medium"},337    input=[{"role": "user", "content": prompt}],338    max_output_tokens=300,339)340341if (342    response.status == "incomplete"343    and response.incomplete_details.reason == "max_output_tokens"344):345    print("Ran out of tokens")346    if response.output_text:347        print("Partial output:", response.output_text)348    else:349        print("Ran out of tokens during reasoning")350```351352```go353package main354355import (356	"context"357	"fmt"358359	"github.com/openai/openai-go/v3"360	"github.com/openai/openai-go/v3/responses"361)362363func main() {364	client := openai.NewClient()365	prompt := `Write a bash script that takes a matrix represented as a string with366format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`367368	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{369		Model:           "gpt-6-astra",370		MaxOutputTokens: openai.Int(300),371		Reasoning: responses.ReasoningParam{372			Effort: responses.ReasoningEffortMedium,373		},374		Input: responses.ResponseNewParamsInputUnion{375			OfString: openai.String(prompt),376		},377	})378	if err != nil {379		panic(err)380	}381382	if response.Status == responses.ResponseStatusIncomplete {383		fmt.Println("Ran out of tokens")384		if text := response.OutputText(); text != "" {385			fmt.Println("Partial output:", text)386		}387	}388}389```390391```java392import com.openai.client.OpenAIClient;393import com.openai.client.okhttp.OpenAIOkHttpClient;394import com.openai.models.Reasoning;395import com.openai.models.ReasoningEffort;396import com.openai.models.responses.Response;397import com.openai.models.responses.ResponseCreateParams;398import com.openai.models.responses.ResponseStatus;399400ResponseCreateParams params =401    ResponseCreateParams.builder()402        .model("gpt-6-astra")403        .input(404            "Write a bash script that takes a matrix represented as a string with format "405                + "'[1,2],[3,4],[5,6]' and prints the transpose in the same format.")406        .maxOutputTokens(300)407        .reasoning(Reasoning.builder().effort(ReasoningEffort.MEDIUM).build())408        .build();409410var response = client.responses().create(params);411if (response.status().filter(ResponseStatus.INCOMPLETE::equals).isPresent()412    && response413        .incompleteDetails()414        .flatMap(Response.IncompleteDetails::reason)415        .filter(Response.IncompleteDetails.Reason.MAX_OUTPUT_TOKENS::equals)416        .isPresent()) {417  System.out.println("Ran out of tokens");418  response.output().stream()419      .flatMap(item -> item.message().stream())420      .flatMap(message -> message.content().stream())421      .flatMap(content -> content.outputText().stream())422      .forEach(text -> System.out.println("Partial output: " + text.text()));423}424```425426```csharp427using OpenAI.Responses;428#pragma warning disable OPENAI001429430string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;431ResponsesClient client = new(key);432433CreateResponseOptions options = new()434{435    Model = "gpt-6-astra",436    MaxOutputTokenCount = 300,437    ReasoningOptions = new ResponseReasoningOptions438    {439        ReasoningEffortLevel = ResponseReasoningEffortLevel.Medium,440    },441};442options.InputItems.Add(443    ResponseItem.CreateUserMessageItem("Write a bash script that transposes a matrix.")444);445446ResponseResult response = await client.CreateResponseAsync(options);447if (448    response.Status == ResponseStatus.Incomplete449    && response.IncompleteStatusDetails?.Reason == ResponseIncompleteStatusReason.MaxOutputTokens450)451{452    Console.WriteLine("The response ended before all output tokens were generated.");453    string partialOutput = response.GetOutputText();454    Console.WriteLine(455        string.IsNullOrWhiteSpace(partialOutput)456            ? "Ran out of tokens during reasoning."457            : $"Partial output: {partialOutput}"458    );459}460else if (461    response.Status == ResponseStatus.Incomplete462    && response.IncompleteStatusDetails?.Reason == ResponseIncompleteStatusReason.ContentFilter463)464{465    Console.WriteLine("The response was interrupted by the content filter.");466}467else if (response.Status == ResponseStatus.Completed)468{469    Console.WriteLine(response.GetOutputText());470}471else472{473    throw new InvalidOperationException($"The response ended with status: {response.Status}");474}475```476477```ruby478require "openai"479480client = OpenAI::Client.new481prompt = <<~PROMPT482  Write a bash script that takes a matrix represented as a string with format483  '[1,2],[3,4],[5,6]' and prints the transpose in the same format.484PROMPT485486response = client.responses.create(487  model: "gpt-6-astra",488  max_output_tokens: 300,489  reasoning: { effort: :medium },490  input: prompt491)492493if response.status == OpenAI::Responses::ResponseStatus::INCOMPLETE494  puts("Ran out of tokens")495  puts("Partial output: #{response.output_text}") unless response.output_text.empty?496end497```498499500## Preserve reasoning across calls501502Conversation state and reasoning state serve different purposes. Passing messages across calls gives the model the visible conversation history. On supported models, persisted reasoning also lets the model render compatible reasoning items from earlier turns into its next context.503504Persisted reasoning provides continuity; it does not expose the model's raw reasoning. The reasoning items remain opaque, and the API does not return their reasoning text. Set `reasoning.context` to control which available reasoning items the model can use:505506The [GPT-5.6 model family](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-5.6)507  supports508  `all_turns` and uses it by default. Earlier models default to509  `current_turn`. Omit `reasoning.context` or set it to510  `auto` to use the selected model's default.511512| Value          | Behavior                                                                                                                  |513| -------------- | ------------------------------------------------------------------------------------------------------------------------- |514| `auto`         | Uses the selected model's default. Omitting `reasoning.context` has the same effect as `auto`.                            |515| `current_turn` | Makes reasoning from the active turn available, but does not render reasoning from earlier turns into the next sample.    |516| `all_turns`    | Renders available, compatible reasoning items from earlier turns into the next sample. GPT-5.6 models support this value. |517518The response's `reasoning.context` field contains the effective mode, either `current_turn` or `all_turns`. Check this field on each response to confirm which mode the model used. The setting does not create reasoning items that are not already available.519520`all_turns` has an effect only when the request has access to earlier response items. Use `previous_response_id`, attach the response to a conversation, or manually replay the complete response history. On the first request, `current_turn` and `all_turns` behave the same because no earlier reasoning exists.521522Persisted reasoning can be reused only within the same model family. For example, `gpt-5.6-sol`, `gpt-5.6-terra`, and `gpt-5.6-luna` can reuse each other's reasoning, but reasoning does not carry between the GPT-5.6 and GPT-5.5 families.523524When you switch model families, the API omits incompatible reasoning from the model's context, even when `reasoning.context` is `all_turns`.525526### Continue reasoning with stored responses527528Use `previous_response_id` for the shortest stateful integration:529530Preserve reasoning with a previous response531532```javascript533import OpenAI from "openai";534535const client = new OpenAI();536537const first = await client.responses.create({538  model: "gpt-5.6",539  input: "Inspect this repository and identify the likely bug.",540  reasoning: { context: "current_turn" },541});542543const second = await client.responses.create({544  model: "gpt-5.6",545  previous_response_id: first.id,546  input: "Now patch the bug and explain the change.",547  reasoning: { context: "all_turns" },548});549550console.log(second.output_text);551```552553```python554from openai import OpenAI555556client = OpenAI()557model = "gpt-5.6"558559first = client.responses.create(560    model=model,561    input="Inspect this repository and identify the likely bug.",562    reasoning={"context": "current_turn"},563)564565second = client.responses.create(566    model=model,567    previous_response_id=first.id,568    input="Now patch the bug and explain the change.",569    reasoning={"context": "all_turns"},570)571572print(second.output_text)573```574575```go576package main577578import (579	"context"580	"fmt"581582	"github.com/openai/openai-go/v3"583	"github.com/openai/openai-go/v3/responses"584)585586func main() {587	client := openai.NewClient()588	model := "gpt-5.6"589590	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{591		Model: model,592		Input: responses.ResponseNewParamsInputUnion{593			OfString: openai.String("Inspect this repository and identify the likely bug."),594		},595		Reasoning: responses.ReasoningParam{596			Context: responses.ReasoningContextCurrentTurn,597		},598	})599	if err != nil {600		panic(err)601	}602603	second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{604		Model:              model,605		PreviousResponseID: openai.String(first.ID),606		Input: responses.ResponseNewParamsInputUnion{607			OfString: openai.String("Now patch the bug and explain the change."),608		},609		Reasoning: responses.ReasoningParam{610			Context: responses.ReasoningContextAllTurns,611		},612	})613	if err != nil {614		panic(err)615	}616617	fmt.Println(second.OutputText())618}619```620621```java622import com.openai.client.OpenAIClient;623import com.openai.client.okhttp.OpenAIOkHttpClient;624import com.openai.core.JsonValue;625import com.openai.models.Reasoning;626import com.openai.models.responses.ResponseCreateParams;627628var first =629    client630        .responses()631        .create(632            ResponseCreateParams.builder()633                .model("gpt-5.6")634                .input("Inspect this repository and identify the likely bug.")635                .reasoning(636                    Reasoning.builder()637                        .putAdditionalProperty("context", JsonValue.from("current_turn"))638                        .build())639                .build());640641var second =642    client643        .responses()644        .create(645            ResponseCreateParams.builder()646                .model("gpt-5.6")647                .input("Now patch the bug and explain the change.")648                .previousResponseId(first.id())649                .reasoning(650                    Reasoning.builder()651                        .putAdditionalProperty("context", JsonValue.from("all_turns"))652                        .build())653                .build());654second.output().stream()655    .flatMap(item -> item.message().stream())656    .flatMap(message -> message.content().stream())657    .flatMap(content -> content.outputText().stream())658    .forEach(text -> System.out.println(text.text()));659```660661```ruby662require "openai"663664client = OpenAI::Client.new665666first = client.responses.create(667  model: "gpt-5.6",668  input: "Inspect this repository and identify the likely bug.",669  reasoning: { context: :current_turn }670)671672second = client.responses.create(673  model: "gpt-5.6",674  previous_response_id: first.id,675  input: "Now patch the bug and explain the change.",676  reasoning: { context: :all_turns }677)678679puts(second.output_text)680```681682683Use `current_turn` when replaying older response items that the model no longer needs. Those reasoning items can remain in the API payload for continuity, but the service does not render them into the new sample. This can reduce the rendered context for long-running workflows.684685### Preserve reasoning without stored responses686687When you create a response in stateless mode, reasoning items in the response's `output` array include an `encrypted_content` property by default. Stateless mode applies when `store` is `false` or when your organization uses Zero Data Retention (ZDR). The API still accepts the legacy `reasoning.encrypted_content` value in `include` for compatibility, but doesn't require it.688689The following request returns encrypted reasoning content without specifying `include`:690691```bash692curl https://api.openai.com/v1/responses \693  -H "Content-Type: application/json" \694  -H "Authorization: Bearer $OPENAI_API_KEY" \695  -d '{696    "model": "gpt-6-astra",697    "store": false,698    "reasoning": {"effort": "medium"},699    "input": "What is the weather like today?",700    "tools": [ ... function config here ... ]701  }'702```703704705Reasoning items in the `output` array will include an `encrypted_content` property containing encrypted reasoning tokens that you can pass to future calls.706707To use `all_turns` with `store: false`, preserve every output item, append the next user message, and replay the complete history:708709Preserve reasoning without storing responses710711```javascript712import OpenAI from "openai";713import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";714715const client = new OpenAI();716717const history = [718  {719    role: "user",720    content: "Inspect this repository and identify the likely bug.",721  },722];723724const first = await client.responses.create({725  model: "gpt-5.6",726  store: false,727  input: history,728  reasoning: { context: "current_turn" },729});730731// Keep replayable output, including encrypted reasoning and assistant phase.732history.push(...toResponseInputItems(first.output));733history.push({734  role: "user",735  content: "Now patch the bug and explain the change.",736});737738const second = await client.responses.create({739  model: "gpt-5.6",740  store: false,741  input: history,742  reasoning: { context: "all_turns" },743});744745console.log(second.output_text);746```747748```python749from openai import OpenAI750751client = OpenAI()752model = "gpt-5.6"753754history = [755    {756        "role": "user",757        "content": "Inspect this repository and identify the likely bug.",758    }759]760761first = client.responses.create(762    model=model,763    store=False,764    input=history,765    reasoning={"context": "current_turn"},766)767768# Keep every output item, including encrypted reasoning and assistant phase.769history.extend(item.model_dump() for item in first.output)770history.append(771    {772        "role": "user",773        "content": "Now patch the bug and explain the change.",774    }775)776777second = client.responses.create(778    model=model,779    store=False,780    input=history,781    reasoning={"context": "all_turns"},782)783784print(second.output_text)785```786787```go788package main789790import (791	"context"792	"encoding/json"793	"fmt"794795	"github.com/openai/openai-go/v3"796	"github.com/openai/openai-go/v3/responses"797	"github.com/openai/openai-go/v3/shared"798)799800func main() {801	client := openai.NewClient()802	history := []responses.ResponseInputItemUnionParam{803		responses.ResponseInputItemParamOfMessage("Inspect this repository and identify the likely bug.", responses.EasyInputMessageRoleUser),804	}805	first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{806		Model:     "gpt-5.6",807		Store:     openai.Bool(false),808		Input:     responses.ResponseNewParamsInputUnion{OfInputItemList: history},809		Reasoning: shared.ReasoningParam{Context: shared.ReasoningContextCurrentTurn},810	})811	if err != nil {812		panic(err)813	}814	history = append(history, outputAsInput(first.Output)...)815	history = append(history, responses.ResponseInputItemParamOfMessage(816		"Now patch the bug and explain the change.",817		responses.EasyInputMessageRoleUser,818	))819	second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{820		Model:     "gpt-5.6",821		Store:     openai.Bool(false),822		Input:     responses.ResponseNewParamsInputUnion{OfInputItemList: history},823		Reasoning: shared.ReasoningParam{Context: shared.ReasoningContextAllTurns},824	})825	if err != nil {826		panic(err)827	}828	fmt.Println(second.OutputText())829}830831func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {832	input := make([]responses.ResponseInputItemUnionParam, 0, len(output))833	for _, item := range output {834		var converted responses.ResponseInputItemUnion835		if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {836			panic(err)837		}838		input = append(input, converted.ToParam())839	}840	return input841}842```843844```java845import com.openai.client.OpenAIClient;846import com.openai.client.okhttp.OpenAIOkHttpClient;847import com.openai.core.JsonValue;848import com.openai.models.Reasoning;849import com.openai.models.responses.EasyInputMessage;850import com.openai.models.responses.ResponseCreateParams;851import com.openai.models.responses.ResponseInputItem;852import java.util.ArrayList;853854var history = new ArrayList<ResponseInputItem>();855history.add(856    ResponseInputItem.ofEasyInputMessage(857        EasyInputMessage.builder()858            .role(EasyInputMessage.Role.USER)859            .content("Inspect this repository and identify the likely bug.")860            .build()));861862var first =863    client864        .responses()865        .create(866            ResponseCreateParams.builder()867                .model("gpt-5.6")868                .inputOfResponse(history)869                .store(false)870                .reasoning(871                    Reasoning.builder()872                        .putAdditionalProperty("context", JsonValue.from("current_turn"))873                        .build())874                .build());875first.output().stream()876    .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))877    .forEach(history::add);878history.add(879    ResponseInputItem.ofEasyInputMessage(880        EasyInputMessage.builder()881            .role(EasyInputMessage.Role.USER)882            .content("Now patch the bug and explain the change.")883            .build()));884885client886    .responses()887    .create(888        ResponseCreateParams.builder()889            .model("gpt-5.6")890            .inputOfResponse(history)891            .store(false)892            .reasoning(893                Reasoning.builder()894                    .putAdditionalProperty("context", JsonValue.from("all_turns"))895                    .build())896            .build())897    .output()898    .stream()899    .flatMap(item -> item.message().stream())900    .flatMap(message -> message.content().stream())901    .flatMap(content -> content.outputText().stream())902    .forEach(text -> System.out.println(text.text()));903```904905```ruby906require "openai"907908client = OpenAI::Client.new909history = [910  {911    role: :user,912    content: "Inspect this repository and identify the likely bug."913  }914]915916first = client.responses.create(917  model: "gpt-5.6",918  store: false,919  input: history,920  reasoning: { context: :current_turn }921)922history.concat(first.output)923history << {924  role: :user,925  content: "Now patch the bug and explain the change."926}927928second = client.responses.create(929  model: "gpt-5.6",930  store: false,931  input: history,932  reasoning: { context: :all_turns }933)934935puts(second.output_text)936```937938939### Keeping reasoning items in context940941When doing [function calling](https://developers.openai.com/api/docs/guides/function-calling) with a reasoning model in the [Responses API](https://developers.openai.com/api/reference/resources/responses), we highly recommend you pass back any reasoning items returned with the last function call (in addition to the output of your function). If the model calls multiple functions consecutively, you should pass back all reasoning items, function call items, and function call output items, since the last `user` message. This allows the model to continue its reasoning process to produce better results in the most token-efficient manner.942943The simplest way to do this is to pass in all reasoning items from a previous response into the next one. Our systems will smartly ignore any reasoning items that aren't relevant to your functions, and only retain those in context that are relevant. You can pass reasoning items from previous responses either using the `previous_response_id` parameter, or by manually passing in all the [output](https://developers.openai.com/api/reference/resources/responses#responses/object-output) items from a past response into the [input](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-input) of a new one.944945For advanced use cases where you might be truncating and optimizing parts of the context window before passing them on to the next response, just ensure all items between the last user message and your function call output are passed into the next response untouched. This will ensure that the model has all the context it needs.946947Check out [this guide](https://developers.openai.com/api/docs/guides/conversation-state) to learn more about manual context management.948949## Change reasoning mid-conversation950951Use `configuration_update` to increase reasoning effort for difficult work or reduce it for routine follow-ups. Add the update between responses while leaving the request-level `reasoning.effort` unchanged. This preserves the original prompt prefix for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).952953Configuration updates are supported only by GPT-6 Astra (`gpt-6-astra`) in954  standard, single-agent mode. They change only reasoning effort.955956Add the following item before the next user message in the `input` array of an HTTP Responses request or a WebSocket `response.create` request:957958```json959{960  "type": "configuration_update",961  "reasoning": {962    "effort": "high"963  }964}965```966967For example, if the conversation starts with request-level effort `low`, this update selects `high` for the next response and subsequent responses until another update overrides it.968969Increase reasoning effort for a follow-up970971```javascript972import OpenAI from "openai";973974const client = new OpenAI();975const model = "gpt-6-astra";976977const first = await client.responses.create({978  model,979  reasoning: { effort: "low" },980  input: "Draft a database migration plan.",981});982983const next = await client.responses.create({984  model,985  reasoning: { effort: "low" },986  previous_response_id: first.id,987  input: [988    { type: "configuration_update", reasoning: { effort: "high" } },989    {990      role: "user",991      content: "Analyze the failure modes and propose rollback steps.",992    },993  ],994});995console.log(next.output_text);996```997998```python999from openai import OpenAI10001001client = OpenAI()1002model = "gpt-6-astra"10031004response = client.responses.create(1005    model=model,1006    reasoning={"effort": "low"},1007    input="Draft a database migration plan.",1008    store=True,1009)1010print(response.output_text)10111012response = client.responses.create(1013    model=model,1014    previous_response_id=response.id,1015    reasoning={"effort": "low"},1016    input=[1017        {1018            "type": "configuration_update",1019            "reasoning": {"effort": "high"},1020        },1021        {1022            "role": "user",1023            "content": "Analyze the failure modes and propose rollback steps.",1024        },1025    ],1026    store=True,1027)1028print(response.output_text)1029```10301031```go1032package main10331034import (1035	"context"1036	"fmt"10371038	"github.com/openai/openai-go/v3"1039	"github.com/openai/openai-go/v3/responses"1040	"github.com/openai/openai-go/v3/shared"1041)10421043func main() {1044	client := openai.NewClient()1045	ctx := context.Background()1046	first, err := client.Responses.New(ctx, responses.ResponseNewParams{1047		Store:     openai.Bool(true),1048		Model:     "gpt-6-astra",1049		Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},1050		Input:     responses.ResponseNewParamsInputUnion{OfString: openai.String("Draft a database migration plan.")},1051	})1052	if err != nil {1053		panic(err)1054	}1055	fmt.Println(first.OutputText())1056	response, err := client.Responses.New(ctx, responses.ResponseNewParams{1057		Model:              "gpt-6-astra",1058		PreviousResponseID: openai.String(first.ID),1059		// Keep the original request-level setting; the item updates the conversation.1060		Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},1061		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1062			{OfConfigurationUpdate: &responses.ResponseConfigurationUpdateItemParam{1063				Reasoning: responses.ResponseConfigurationUpdateItemParamReasoning{Effort: shared.ReasoningEffortHigh},1064			}},1065			responses.ResponseInputItemParamOfMessage("Analyze the failure modes and propose rollback steps.", responses.EasyInputMessageRoleUser),1066		}},1067	})1068	if err != nil {1069		panic(err)1070	}1071	fmt.Println(response.OutputText())1072}1073```10741075```java1076import com.openai.models.Reasoning;1077import com.openai.models.ReasoningEffort;1078import com.openai.models.responses.EasyInputMessage;1079import com.openai.models.responses.Response;1080import com.openai.models.responses.ResponseConfigurationUpdateItemParam;1081import com.openai.models.responses.ResponseCreateParams;1082import com.openai.models.responses.ResponseInputItem;1083import java.util.List;10841085Response first =1086    client1087        .responses()1088        .create(1089            ResponseCreateParams.builder()1090                .model("gpt-6-astra")1091                .store(true)1092                .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())1093                .input("Draft a database migration plan.")1094                .build());1095Response response =1096    client1097        .responses()1098        .create(1099            ResponseCreateParams.builder()1100                .model("gpt-6-astra")1101                .previousResponseId(first.id())1102                // Keep the original request-level setting; the item updates the conversation.1103                .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())1104                .inputOfResponse(1105                    List.of(1106                        ResponseInputItem.ofConfigurationUpdate(1107                            ResponseConfigurationUpdateItemParam.builder()1108                                .reasoning(1109                                    ResponseConfigurationUpdateItemParam.Reasoning.builder()1110                                        .effort(ReasoningEffort.HIGH)1111                                        .build())1112                                .build()),1113                        ResponseInputItem.ofEasyInputMessage(1114                            EasyInputMessage.builder()1115                                .role(EasyInputMessage.Role.USER)1116                                .content(1117                                    "Analyze the failure modes and propose rollback steps.")1118                                .build())))1119                .build());1120response.output().stream()1121    .flatMap(item -> item.message().stream())1122    .flatMap(message -> message.content().stream())1123    .flatMap(content -> content.outputText().stream())1124    .forEach(text -> System.out.println(text.text()));1125```11261127```ruby1128require "openai"11291130client = OpenAI::Client.new1131first = client.responses.create(1132  model: "gpt-6-astra",1133  store: true,1134  reasoning: OpenAI::Models::Reasoning.new(effort: :low),1135  input: "Draft a database migration plan."1136)1137puts(first.output_text)1138response = client.responses.create(1139  model: "gpt-6-astra",1140  previous_response_id: first.id,1141  # Keep the original request-level setting; the item updates the conversation.1142  reasoning: OpenAI::Models::Reasoning.new(effort: :low),1143  input: [1144    OpenAI::Models::Responses::ResponseConfigurationUpdateItemParam.new(1145      reasoning: OpenAI::Models::Responses::ResponseConfigurationUpdateItemParam::Reasoning.new(1146        effort: :high1147      )1148    ),1149    OpenAI::Models::Responses::EasyInputMessage.new(1150      role: :user,1151      content: "Analyze the failure modes and propose rollback steps."1152    )1153  ]1154)1155puts(response.output_text)1156```115711581159Preserve updates with `previous_response_id`, or replay them in their original positions when [managing conversation history manually](https://developers.openai.com/api/docs/guides/conversation-state#manually-manage-conversation-state). The response's `reasoning.effort` continues to report the request-level setting, not the effort selected by the update.11601161Do not place two `configuration_update` items directly next to each other in the conversation history; the API rejects adjacent updates.11621163Do not combine configuration updates with automatic compaction or automatic truncation. The standalone `/responses/compact` endpoint also rejects histories containing these updates.11641165You can still explicitly compact history by including a `compaction_trigger` item in a `/responses` request. After compaction, add a fresh `configuration_update` with the desired effort before the next user message.11661167Normal prompt caching requirements still apply. To send user instructions while a response is running, use [Mid-turn steering](https://developers.openai.com/api/docs/guides/steering).11681169## Reasoning summaries11701171While we don't expose the raw reasoning tokens emitted by the model, you can view a summary of the model's reasoning using the `summary` parameter. See our [model documentation](https://developers.openai.com/api/docs/models) to check which reasoning models support summaries.11721173Different models support different reasoning summary settings. For example, our computer use model supports the `concise` summarizer, while o4-mini supports `detailed`. To access the most detailed summarizer available for a model, set the value of this parameter to `auto`. `auto` will be equivalent to `detailed` for most reasoning models today, but there may be more granular settings in the future.11741175Reasoning summary output is part of the `summary` array in the `reasoning` [output item](https://developers.openai.com/api/reference/resources/responses#responses/object-output). This output will not be included unless you explicitly opt in to including reasoning summaries.11761177The example below shows how to make an API request that includes a reasoning summary.11781179Include a reasoning summary with the API response11801181```javascript1182import OpenAI from "openai";1183const openai = new OpenAI();11841185const response = await openai.responses.create({1186  model: "gpt-6-astra",1187  input: "What is the capital of France?",1188  reasoning: {1189    effort: "low",1190    summary: "auto",1191  },1192});11931194console.log(response.output);1195```11961197```python1198from openai import OpenAI11991200client = OpenAI()12011202response = client.responses.create(1203    model="gpt-6-astra",1204    input="What is the capital of France?",1205    reasoning={"effort": "low", "summary": "auto"},1206)12071208print(response.output)1209```12101211```go1212package main12131214import (1215	"context"1216	"fmt"12171218	"github.com/openai/openai-go/v3"1219	"github.com/openai/openai-go/v3/responses"1220)12211222func main() {1223	client := openai.NewClient()12241225	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1226		Model: "gpt-6-astra",1227		Input: responses.ResponseNewParamsInputUnion{1228			OfString: openai.String("What is the capital of France?"),1229		},1230		Reasoning: responses.ReasoningParam{1231			Effort:  responses.ReasoningEffortLow,1232			Summary: responses.ReasoningSummaryAuto,1233		},1234	})1235	if err != nil {1236		panic(err)1237	}12381239	fmt.Println(response.Output)1240}1241```12421243```java1244import com.openai.client.OpenAIClient;1245import com.openai.client.okhttp.OpenAIOkHttpClient;1246import com.openai.models.Reasoning;1247import com.openai.models.ReasoningEffort;1248import com.openai.models.responses.ResponseCreateParams;12491250ResponseCreateParams params =1251    ResponseCreateParams.builder()1252        .model("gpt-6-astra")1253        .input("What is the capital of France?")1254        .reasoning(1255            Reasoning.builder()1256                .effort(ReasoningEffort.LOW)1257                .summary(Reasoning.Summary.AUTO)1258                .build())1259        .build();12601261client.responses().create(params).output().stream()1262    .flatMap(item -> item.reasoning().stream())1263    .flatMap(reasoning -> reasoning.summary().stream())1264    .forEach(summary -> System.out.println(summary.text()));1265```12661267```csharp1268using OpenAI.Responses;1269#pragma warning disable OPENAI00112701271string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1272ResponsesClient client = new(key);12731274CreateResponseOptions options = new()1275{1276    Model = "gpt-6-astra",1277    ReasoningOptions = new ResponseReasoningOptions1278    {1279        ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,1280        ReasoningSummaryVerbosity = ResponseReasoningSummaryVerbosity.Auto,1281    },1282};1283options.InputItems.Add(ResponseItem.CreateUserMessageItem("What is the capital of France?"));12841285ResponseResult response = await client.CreateResponseAsync(options);1286foreach (ReasoningResponseItem reasoning in response.OutputItems.OfType<ReasoningResponseItem>())1287{1288    Console.WriteLine(reasoning.GetSummaryText());1289}1290Console.WriteLine(response.GetOutputText());1291```12921293```ruby1294require "openai"12951296client = OpenAI::Client.new12971298response = client.responses.create(1299  model: "gpt-6-astra",1300  input: "What is the capital of France?",1301  reasoning: {1302    effort: :low,1303    summary: :auto1304  }1305)13061307puts(response.output)1308```13091310```bash1311curl https://api.openai.com/v1/responses \1312  -H "Content-Type: application/json" \1313  -H "Authorization: Bearer $OPENAI_API_KEY" \1314  -d '{1315    "model": "gpt-6-astra",1316    "input": "What is the capital of France?",1317    "reasoning": {1318        "effort": "low",1319        "summary": "auto"1320    }1321  }'1322```132313241325This API request will return an output array with both an assistant message and a summary of the model's reasoning in generating that response.13261327```json1328[1329  {1330    "id": "rs_6876cf02e0bc8192b74af0fb64b715ff06fa2fcced15a5ac",1331    "type": "reasoning",1332    "summary": [1333      {1334        "type": "summary_text",1335        "text": "**Answering a simple question**\n\nI\u2019m looking at a straightforward question: the capital of France is Paris. It\u2019s a well-known fact, and I want to keep it brief and to the point. Paris is known for its history, art, and culture, so it might be nice to add just a hint of that charm. But mostly, I\u2019ll aim to focus on delivering a clear and direct answer, ensuring the user gets what they\u2019re looking for without any extra fluff."1336      }1337    ]1338  },1339  {1340    "id": "msg_6876cf054f58819284ecc1058131305506fa2fcced15a5ac",1341    "type": "message",1342    "status": "completed",1343    "content": [1344      {1345        "type": "output_text",1346        "annotations": [],1347        "logprobs": [],1348        "text": "The capital of France is Paris."1349      }1350    ],1351    "role": "assistant"1352  }1353]1354```13551356Before using summarizers with our latest reasoning models, you may need to1357  complete [organization1358  verification](https://help.openai.com/en/articles/10910291-api-organization-verification)1359  to ensure safe deployment. Get started with verification on the [platform1360  settings page](https://platform.openai.com/settings/organization/general).13611362## `phase` parameter13631364For long-running or tool-heavy flows with GPT-5.5 and GPT-5.4 in the Responses API, use the assistant message `phase` field to avoid early stopping and other misbehavior.1365`phase` is optional at the API level, but OpenAI recommends using it. Use `phase: "commentary"` for intermediate assistant updates, such as preambles before tool calls, and `phase: "final_answer"` for the completed answer. Don't add `phase` to user messages.1366Using `previous_response_id` is usually the simplest path because prior assistant state is preserved. If you replay assistant history manually, preserve each original `phase` value.1367Missing or dropped `phase` can cause preambles to be treated as final answers in those workflows. For model-specific prompt guidance, see [Prompting GPT-5.5](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-5.5#prompting-best-practices).13681369### Round-trip assistant phase values13701371Round-trip assistant phase values13721373```javascript1374import OpenAI from "openai";1375const client = new OpenAI();13761377const response = await client.responses.create({1378  model: "gpt-6-astra",1379  input: [1380    {1381      role: "assistant",1382      phase: "commentary",1383      content:1384        "I’ll inspect the logs and then summarize root cause and remediation.",1385    },1386    {1387      role: "assistant",1388      phase: "final_answer",1389      content: "Root cause: cache invalidation race.",1390    },1391    {1392      role: "user",1393      content: "Great—now give me a rollout-safe fix plan.",1394    },1395  ],1396});13971398console.log(response.output_text);1399```14001401```python1402from openai import OpenAI14031404client = OpenAI()14051406response = client.responses.create(1407    model="gpt-6-astra",1408    input=[1409        {1410            "role": "assistant",1411            "phase": "commentary",1412            "content": "I’ll inspect the logs and then summarize root cause and remediation.",1413        },1414        {1415            "role": "assistant",1416            "phase": "final_answer",1417            "content": "Root cause: cache invalidation race.",1418        },1419        {1420            "role": "user",1421            "content": "Great—now give me a rollout-safe fix plan.",1422        },1423    ],1424)14251426print(response.output_text)1427```14281429```go1430package main14311432import (1433	"context"1434	"fmt"14351436	"github.com/openai/openai-go/v3"1437	"github.com/openai/openai-go/v3/responses"1438)14391440func main() {1441	client := openai.NewClient()1442	commentary := responses.ResponseInputItemParamOfMessage(1443		"I’ll inspect the logs and then summarize root cause and remediation.",1444		responses.EasyInputMessageRoleAssistant,1445	)1446	commentary.OfMessage.Phase = responses.EasyInputMessagePhaseCommentary1447	finalAnswer := responses.ResponseInputItemParamOfMessage(1448		"Root cause: cache invalidation race.",1449		responses.EasyInputMessageRoleAssistant,1450	)1451	finalAnswer.OfMessage.Phase = responses.EasyInputMessagePhaseFinalAnswer1452	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1453		Model: "gpt-6-astra",1454		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1455			commentary,1456			finalAnswer,1457			responses.ResponseInputItemParamOfMessage("Great—now give me a rollout-safe fix plan.", responses.EasyInputMessageRoleUser),1458		}},1459	})1460	if err != nil {1461		panic(err)1462	}1463	fmt.Println(response.OutputText())1464}1465```14661467```java1468import com.openai.client.OpenAIClient;1469import com.openai.client.okhttp.OpenAIOkHttpClient;1470import com.openai.models.responses.EasyInputMessage;1471import com.openai.models.responses.ResponseCreateParams;1472import com.openai.models.responses.ResponseInputItem;1473import java.util.List;14741475ResponseCreateParams params =1476    ResponseCreateParams.builder()1477        .model("gpt-6-astra")1478        .inputOfResponse(1479            List.of(1480                ResponseInputItem.ofEasyInputMessage(1481                    EasyInputMessage.builder()1482                        .role(EasyInputMessage.Role.ASSISTANT)1483                        .phase(EasyInputMessage.Phase.COMMENTARY)1484                        .content(1485                            "I'll inspect the logs and then summarize root cause and remediation.")1486                        .build()),1487                ResponseInputItem.ofEasyInputMessage(1488                    EasyInputMessage.builder()1489                        .role(EasyInputMessage.Role.ASSISTANT)1490                        .phase(EasyInputMessage.Phase.FINAL_ANSWER)1491                        .content("Root cause: cache invalidation race.")1492                        .build()),1493                ResponseInputItem.ofEasyInputMessage(1494                    EasyInputMessage.builder()1495                        .role(EasyInputMessage.Role.USER)1496                        .content("Great—now give me a rollout-safe fix plan.")1497                        .build())))1498        .build();14991500client.responses().create(params).output().stream()1501    .flatMap(item -> item.message().stream())1502    .flatMap(message -> message.content().stream())1503    .flatMap(content -> content.outputText().stream())1504    .forEach(text -> System.out.println(text.text()));1505```15061507```ruby1508require "openai"15091510client = OpenAI::Client.new15111512response = client.responses.create(1513  model: "gpt-6-astra",1514  input: [1515    {1516      role: :assistant,1517      phase: :commentary,1518      content: "I'll inspect the logs and then summarize root cause and remediation."1519    },1520    {1521      role: :assistant,1522      phase: :final_answer,1523      content: "Root cause: cache invalidation race."1524    },1525    {1526      role: :user,1527      content: "Great—now give me a rollout-safe fix plan."1528    }1529  ]1530)15311532puts(response.output_text)1533```153415351536## Advice on prompting15371538Consider these differences when prompting a reasoning model. Reasoning-capable GPT-5 models usually work best when you give them a clear goal, strong constraints, and an explicit output contract without prescribing every intermediate step.15391540- Give the model the task, constraints, and desired output format.1541- Treat `reasoning.effort` as a tuning knob, not the primary way to recover quality.1542- For agentic or research-heavy workflows, define what counts as done and how the model should verify its work.15431544For more information on best practices when using reasoning models, [refer to this guide](https://developers.openai.com/api/docs/guides/reasoning-best-practices).15451546### Prompt examples1547154815491550Coding (refactoring)15511552    15531554OpenAI o-series models are able to implement complex algorithms and produce code. This prompt asks o1 to refactor a React component based on some specific criteria.15551556155715581559  Refactor code15601561```javascript1562import OpenAI from "openai";15631564const openai = new OpenAI();15651566const prompt = `1567Instructions:1568- Given the React component below, change it so that nonfiction books have red1569  text.1570- Return only the code in your reply1571- Do not include any additional formatting, such as markdown code blocks1572- For formatting, use four space tabs, and do not allow any lines of code to1573  exceed 80 columns15741575const books = [1576  { title: 'Dune', category: 'fiction', id: 1 },1577  { title: 'Frankenstein', category: 'fiction', id: 2 },1578  { title: 'Moneyball', category: 'nonfiction', id: 3 },1579];15801581export default function BookList() {1582  const listItems = books.map(book =>1583    <li>1584      {book.title}1585    </li>1586  );15871588  return (1589    <ul>{listItems}</ul>1590  );1591}1592`.trim();15931594const response = await openai.responses.create({1595  model: "gpt-6-astra",1596  input: [1597    {1598      role: "user",1599      content: prompt,1600    },1601  ],1602});16031604console.log(response.output_text);1605```16061607```python1608from openai import OpenAI16091610client = OpenAI()16111612prompt = """1613Instructions:1614- Given the React component below, change it so that nonfiction books have red1615  text.1616- Return only the code in your reply1617- Do not include any additional formatting, such as markdown code blocks1618- For formatting, use four space tabs, and do not allow any lines of code to1619  exceed 80 columns16201621const books = [1622  { title: 'Dune', category: 'fiction', id: 1 },1623  { title: 'Frankenstein', category: 'fiction', id: 2 },1624  { title: 'Moneyball', category: 'nonfiction', id: 3 },1625];16261627export default function BookList() {1628  const listItems = books.map(book =>1629    <li>1630      {book.title}1631    </li>1632  );16331634  return (1635    <ul>{listItems}</ul>1636  );1637}1638"""16391640response = client.responses.create(1641    model="gpt-6-astra",1642    input=[1643        {1644            "role": "user",1645            "content": prompt,1646        }1647    ],1648)16491650print(response.output_text)1651```16521653```go1654package main16551656import (1657	"context"1658	"fmt"16591660	"github.com/openai/openai-go/v3"1661	"github.com/openai/openai-go/v3/responses"1662)16631664func main() {1665	client := openai.NewClient()1666	prompt := `Instructions:1667- Given the React component below, change it so that nonfiction books have red text.1668- Return only the code in your reply.1669- Do not include any additional formatting, such as markdown code blocks.16701671const books = [1672  { title: 'Dune', category: 'fiction', id: 1 },1673  { title: 'Frankenstein', category: 'fiction', id: 2 },1674  { title: 'Moneyball', category: 'nonfiction', id: 3 },1675];`16761677	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1678		Model: "gpt-6-astra",1679		Input: responses.ResponseNewParamsInputUnion{1680			OfString: openai.String(prompt),1681		},1682	})1683	if err != nil {1684		panic(err)1685	}16861687	fmt.Println(response.OutputText())1688}1689```16901691```java1692import com.openai.client.OpenAIClient;1693import com.openai.client.okhttp.OpenAIOkHttpClient;1694import com.openai.models.responses.ResponseCreateParams;16951696String prompt =1697    """1698    Instructions:1699    - Given the React component below, change it so that nonfiction books have red text.1700    - Return only the code in your reply.1701    - Do not include any additional formatting, such as markdown code blocks.17021703    const books = [1704    { title: 'Dune', category: 'fiction', id: 1 },1705    { title: 'Frankenstein', category: 'fiction', id: 2 },1706    { title: 'Moneyball', category: 'nonfiction', id: 3 },1707    ];1708    """1709        .strip();17101711ResponseCreateParams params =1712    ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();17131714client.responses().create(params).output().stream()1715    .flatMap(item -> item.message().stream())1716    .flatMap(message -> message.content().stream())1717    .flatMap(content -> content.outputText().stream())1718    .forEach(text -> System.out.println(text.text()));1719```17201721```csharp1722using OpenAI.Responses;1723#pragma warning disable OPENAI00117241725string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1726ResponsesClient client = new(key);17271728string prompt =1729    """1730    Instructions:1731    - Given the React component below, make nonfiction book titles red.1732    - Return only the updated component code in your reply.1733    - Do not include any additional formatting, such as markdown code blocks.1734    - For formatting, use four space tabs, and do not allow any lines of code to1735      exceed 80 columns.17361737    const books = [1738      { title: 'Dune', category: 'fiction', id: 1 },1739      { title: 'Frankenstein', category: 'fiction', id: 2 },1740      { title: 'Moneyball', category: 'nonfiction', id: 3 },1741    ];17421743    export default function BookList() {1744      const listItems = books.map(book =>1745        <li>1746          {book.title}1747        </li>1748      );17491750      return (1751        <ul>{listItems}</ul>1752      );1753    }1754    """;1755ResponseResult response = await client.CreateResponseAsync(1756    "gpt-6-astra",1757    [ResponseItem.CreateUserMessageItem(prompt)]1758);1759Console.WriteLine(response.GetOutputText());1760```17611762```ruby1763require "openai"17641765client = OpenAI::Client.new1766prompt = <<~PROMPT1767  Instructions:1768  - Given the React component below, change it so that nonfiction books have red text.1769  - Return only the code in your reply.1770  - Do not include any additional formatting, such as markdown code blocks.17711772  const books = [1773    { title: 'Dune', category: 'fiction', id: 1 },1774    { title: 'Frankenstein', category: 'fiction', id: 2 },1775    { title: 'Moneyball', category: 'nonfiction', id: 3 },1776  ];1777PROMPT17781779response = client.responses.create(1780  model: "gpt-6-astra",1781  input: prompt1782)17831784puts(response.output_text)1785```178617871788  17891790  17911792    1793Coding (planning)17941795    17961797OpenAI o-series models are also adept in creating multi-step plans. This example prompt asks o1 to create a filesystem structure for a full solution, along with Python code that implements the desired use case.17981799180018011802  Plan and create a Python project18031804```javascript1805import OpenAI from "openai";18061807const openai = new OpenAI();18081809const prompt = `1810I want to build a Python app that takes user questions and looks1811them up in a database where they are mapped to answers. If there1812is close match, it retrieves the matched answer. If there isn't,1813it asks the user to provide an answer and stores the1814question/answer pair in the database. Make a plan for the directory1815structure you'll need, then return each file in full. Only supply1816your reasoning at the beginning and end, not throughout the code.1817`.trim();18181819const response = await openai.responses.create({1820  model: "gpt-6-astra",1821  input: [1822    {1823      role: "user",1824      content: prompt,1825    },1826  ],1827});18281829console.log(response.output_text);1830```18311832```python1833from openai import OpenAI18341835client = OpenAI()18361837prompt = """1838I want to build a Python app that takes user questions and looks1839them up in a database where they are mapped to answers. If there1840is close match, it retrieves the matched answer. If there isn't,1841it asks the user to provide an answer and stores the1842question/answer pair in the database. Make a plan for the directory1843structure you'll need, then return each file in full. Only supply1844your reasoning at the beginning and end, not throughout the code.1845"""18461847response = client.responses.create(1848    model="gpt-6-astra",1849    input=[1850        {1851            "role": "user",1852            "content": prompt,1853        }1854    ],1855)18561857print(response.output_text)1858```18591860```go1861package main18621863import (1864	"context"1865	"fmt"18661867	"github.com/openai/openai-go/v3"1868	"github.com/openai/openai-go/v3/responses"1869)18701871func main() {1872	client := openai.NewClient()1873	prompt := `I want to build a Python app that takes user questions and looks them up1874in a database where they are mapped to answers. If there is a close match, it1875retrieves the matched answer. If there is not, it asks the user to provide an1876answer and stores the question/answer pair in the database. Make a plan for the1877directory structure you will need, then return each file in full.`18781879	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1880		Model: "gpt-6-astra",1881		Input: responses.ResponseNewParamsInputUnion{1882			OfString: openai.String(prompt),1883		},1884	})1885	if err != nil {1886		panic(err)1887	}18881889	fmt.Println(response.OutputText())1890}1891```18921893```java1894import com.openai.client.OpenAIClient;1895import com.openai.client.okhttp.OpenAIOkHttpClient;1896import com.openai.models.responses.ResponseCreateParams;18971898String prompt =1899    """1900    I want to build a Python app that looks up user questions in a database where1901    they are mapped to answers. If there is a close match, it retrieves the answer.1902    Otherwise, it asks the user for an answer and stores the question and answer.1903    Plan the directory structure, then return each file in full.1904    """1905        .strip();19061907ResponseCreateParams params =1908    ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();19091910client.responses().create(params).output().stream()1911    .flatMap(item -> item.message().stream())1912    .flatMap(message -> message.content().stream())1913    .flatMap(content -> content.outputText().stream())1914    .forEach(text -> System.out.println(text.text()));1915```19161917```csharp1918using OpenAI.Responses;1919#pragma warning disable OPENAI00119201921string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1922ResponsesClient client = new(key);19231924string prompt =1925    """1926    I want to build a Python app that looks up user questions in a database where1927    they are mapped to answers. If there is a close match, it retrieves the answer.1928    Otherwise, it asks the user for an answer and stores the question and answer.1929    Plan the directory structure, then return each file in full.1930    Only supply your reasoning at the beginning and end, not throughout the code.1931    """;1932ResponseResult response = await client.CreateResponseAsync("gpt-6-astra", prompt);19331934Console.WriteLine(response.GetOutputText());1935```19361937```ruby1938require "openai"19391940client = OpenAI::Client.new1941prompt = <<~PROMPT1942  I want to build a Python app that looks up user questions in a database where1943  they are mapped to answers. If there is a close match, it retrieves the answer.1944  Otherwise, it asks the user for an answer and stores the question and answer.1945  Plan the directory structure, then return each file in full.1946PROMPT19471948response = client.responses.create(1949  model: "gpt-6-astra",1950  input: prompt1951)19521953puts(response.output_text)1954```195519561957  19581959  19601961    1962STEM Research19631964    19651966OpenAI o-series models have shown excellent performance in STEM research. Prompts asking for support of basic research tasks should show strong results.19671968196919701971  Ask questions related to basic scientific research19721973```javascript1974import OpenAI from "openai";19751976const openai = new OpenAI();19771978const prompt = `1979What are three compounds we should consider investigating to1980advance research into new antibiotics? Why should we consider1981them?1982`;19831984const response = await openai.responses.create({1985  model: "gpt-6-astra",1986  input: [1987    {1988      role: "user",1989      content: prompt,1990    },1991  ],1992});19931994console.log(response.output_text);1995```19961997```python1998from openai import OpenAI19992000client = OpenAI()20012002prompt = """2003What are three compounds we should consider investigating to2004advance research into new antibiotics? Why should we consider2005them?2006"""20072008response = client.responses.create(2009    model="gpt-6-astra", input=[{"role": "user", "content": prompt}]2010)20112012print(response.output_text)2013```20142015```go2016package main20172018import (2019	"context"2020	"fmt"20212022	"github.com/openai/openai-go/v3"2023	"github.com/openai/openai-go/v3/responses"2024)20252026func main() {2027	client := openai.NewClient()2028	prompt := `What are three compounds we should consider investigating to advance2029research into new antibiotics? Why should we consider them?`20302031	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2032		Model: "gpt-6-astra",2033		Input: responses.ResponseNewParamsInputUnion{2034			OfString: openai.String(prompt),2035		},2036	})2037	if err != nil {2038		panic(err)2039	}20402041	fmt.Println(response.OutputText())2042}2043```20442045```java2046import com.openai.client.OpenAIClient;2047import com.openai.client.okhttp.OpenAIOkHttpClient;2048import com.openai.models.responses.ResponseCreateParams;20492050String prompt =2051    """2052    What are three compounds we should consider investigating to advance research2053    into new antibiotics? Why should we consider them?2054    """2055        .strip();20562057ResponseCreateParams params =2058    ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();20592060client.responses().create(params).output().stream()2061    .flatMap(item -> item.message().stream())2062    .flatMap(message -> message.content().stream())2063    .flatMap(content -> content.outputText().stream())2064    .forEach(text -> System.out.println(text.text()));2065```20662067```csharp2068using OpenAI.Responses;2069#pragma warning disable OPENAI00120702071string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;2072ResponsesClient client = new(key);20732074string prompt =2075    """2076    What are three compounds we should investigate to advance research into2077    new antibiotics? Why should we consider them?2078    """;2079ResponseResult response = await client.CreateResponseAsync(2080    "gpt-6-astra",2081    [ResponseItem.CreateUserMessageItem(prompt)]2082);2083Console.WriteLine(response.GetOutputText());2084```20852086```ruby2087require "openai"20882089client = OpenAI::Client.new2090prompt = <<~PROMPT2091  What are three compounds we should consider investigating to advance research2092  into new antibiotics? Why should we consider them?2093PROMPT20942095response = client.responses.create(2096  model: "gpt-6-astra",2097  input: prompt2098)20992100puts(response.output_text)2101```2102210321042105## Use case examples21062107Some examples of using reasoning models for real-world use cases can be found in [the cookbook](https://developers.openai.com/cookbook).21082109[Using reasoning for data validation2110211121122113      Evaluate a synthetic medical data set for discrepancies.](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_data_validation)21142115[Using reasoning for routine generation2116211721182119      Use help center articles to generate actions that an agent could perform.](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_routine_generation)
Files main
Menu

Theme