SpyBara
Go Premium

Documentation 2026-11-16 23:00 UTC to 2026-11-17 22:57 UTC

106 files changed +5,112 −1,687. View all changes and history on the product overview
2026
Thu 26 22:58 Wed 25 23:57 Tue 24 23:00 Mon 23 23:58 Sat 21 23:57 Fri 20 23:59 Thu 19 22:59 Wed 18 22:59 Tue 17 22:57 Mon 16 23:00 Fri 13 23:58 Thu 12 22:57 Wed 11 23:57 Tue 10 23:02 Mon 9 23:02 Sun 8 22:59 Sat 7 22:59 Fri 6 23:00 Thu 5 23:00 Wed 4 22:58 Tue 3 22:58 Mon 2 23:58 Sun 1 23:00
Details

258conversation_id = "conv_123"258conversation_id = "conv_123"

259 259 

260response = openai.responses.create(260response = openai.responses.create(

261 model="gpt-6-astra",261 model="gpt-6.2-astra",

262 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],262 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],

263 conversation=conversation_id,263 conversation=conversation_id,

264)264)


292 292 

293```go293```go

294_, err := client.Responses.New(context.Background(), responses.ResponseNewParams{294_, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

295 Model: "gpt-6-astra",295 Model: "gpt-6.2-astra",

296 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{296 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

297 responses.ResponseInputItemParamOfMessage("What are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),297 responses.ResponseInputItemParamOfMessage("What are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),

298 }},298 }},


341const conversationId = "conv_123";341const conversationId = "conv_123";

342 342 

343const response = await client.responses.create({343const response = await client.responses.create({

344 model: "gpt-6-astra",344 model: "gpt-6.2-astra",

345 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],345 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],

346 conversation: conversationId,346 conversation: conversationId,

347});347});

concepts.md +1 −1

Details

8 8 

9## Text generation models9## Text generation models

10 10 

11OpenAI's text generation models (often referred to as generative pre-trained transformers or "GPT" models for short), like [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) and [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra), have been trained to understand natural and formal language. These models allow text outputs in response to their inputs. The inputs to these models are also referred to as "prompts." Designing a prompt is essentially how you "program" a model, usually by providing instructions or some examples of how to successfully complete a task. GPT models can be used across a great variety of tasks including content or code generation, summarization, conversation, creative writing, and more. Read more in our introductory [text generation guide](https://developers.openai.com/api/docs/guides/text) and in our [prompt engineering guide](https://developers.openai.com/api/docs/guides/prompt-engineering).11OpenAI's text generation models (often referred to as generative pre-trained transformers or "GPT" models for short), like [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra), have been trained to understand natural and formal language. These models allow text outputs in response to their inputs. The inputs to these models are also referred to as "prompts." Designing a prompt is essentially how you "program" a model, usually by providing instructions or some examples of how to successfully complete a task. GPT models can be used across a great variety of tasks including content or code generation, summarization, conversation, creative writing, and more. Read more in our introductory [text generation guide](https://developers.openai.com/api/docs/guides/text) and in our [prompt engineering guide](https://developers.openai.com/api/docs/guides/prompt-engineering).

12 12 

13## Embeddings13## Embeddings

14 14 

Details

28As a rough rule of thumb, 1 token is approximately 4 characters or 0.75 words for English text.28As a rough rule of thumb, 1 token is approximately 4 characters or 0.75 words for English text.

29 29 

30Check out our 30Check out our

31 [Tokenizer tool](https://platform.openai.com/tokenizer) 31 [tokenizer tool](https://platform.openai.com/tokenizer)

32 to test specific strings and see how they are translated into tokens.32 to test specific strings and see how they are translated into tokens.

33 33 

34For example, the string `"ChatGPT is great!"` is encoded into six tokens: `["Chat", "G", "PT", " is", " great", "!"]`.34For example, the string `"ChatGPT is great!"` is encoded into six tokens: `["Chat", "G", "PT", " is", " great", "!"]`.


51 51 

52This local counter applies only to text messages for that historical snapshot. Message formatting varies by model.52This local counter applies only to text messages for that historical snapshot. Message formatting varies by model.

53 53 

54Count chat message tokens

55 

54```python56```python

55import tiktoken57import tiktoken

56 58 


76 )78 )

77```79```

78 80 

81```ruby

82require "tiktoken_ruby"

83 

84def num_tokens_from_messages(messages, model = "gpt-3.5-turbo-0613")

85 raise ArgumentError, "Token counting only supports gpt-3.5-turbo-0613" unless model == "gpt-3.5-turbo-0613"

86 

87 encoding = Tiktoken.get_encoding("cl100k_base")

88 messages.sum do |message|

89 3 + message.sum { |key, value| encoding.encode(value).length + ((key.to_s == "name") ? 1 : 0) }

90 end + 3

91end

92```

93 

79 94 

80Count the example messages locally:95Count the example messages locally:

81 96 

97Count tokens in an example prompt

98 

82```python99```python

83messages = [100messages = [

84 {101 {


117# 129 prompt tokens counted.134# 129 prompt tokens counted.

118```135```

119 136 

137```ruby

138require "json"

139 

140messages = JSON.parse(<<~MESSAGES)

141 [

142 {

143 "role": "system",

144 "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."

145 },

146 {

147 "role": "system",

148 "name": "example_user",

149 "content": "New synergies will help drive top-line growth."

150 },

151 {

152 "role": "system",

153 "name": "example_assistant",

154 "content": "Things working well together will increase revenue."

155 },

156 {

157 "role": "system",

158 "name": "example_user",

159 "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."

160 },

161 {

162 "role": "system",

163 "name": "example_assistant",

164 "content": "Let's talk later when we're less busy about how to do better."

165 },

166 {

167 "role": "user",

168 "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."

169 }

170 ]

171MESSAGES

172model = "gpt-3.5-turbo-0613"

173puts("#{num_tokens_from_messages(messages, model)} prompt tokens counted.")

174```

175 

176 

177 

178Read the prompt token count from `response.usage`:

120 179 

121The following historical example shows how to read the API's prompt token count. It cannot run against the retired model:180Read API prompt token usage

122 181 

123```typescript182```typescript

124import OpenAI from "openai";183import OpenAI from "openai";


126const client = new OpenAI();185const client = new OpenAI();

127 186 

128const response = await client.chat.completions.create({187const response = await client.chat.completions.create({

129 model,188 model: "gpt-6.2-astra",

130 messages,189 messages: [

131 temperature: 0,190 { role: "user", content: "Translate this sentence into plain English." },

191 ],

132});192});

133 193 

134if (!response.usage)194if (!response.usage)


143client = OpenAI()203client = OpenAI()

144 204 

145response = client.chat.completions.create(205response = client.chat.completions.create(

146 model=model,206 model="gpt-6.2-astra",

147 messages=messages,207 messages=[

148 temperature=0,208 {"role": "user", "content": "Translate this sentence into plain English."}

209 ],

149)210)

150 211 

212if response.usage is None:

213 raise RuntimeError("The response did not include token usage")

151print(f"{response.usage.prompt_tokens} prompt tokens used.")214print(f"{response.usage.prompt_tokens} prompt tokens used.")

152```215```

153 216 


158 221 

159ChatCompletionCreateParams params =222ChatCompletionCreateParams params =

160 ChatCompletionCreateParams.builder()223 ChatCompletionCreateParams.builder()

161 .model("gpt-3.5-turbo-0613")224 .model("gpt-6.2-astra")

162 .addUserMessage("Translate this sentence into plain English.")225 .addUserMessage("Translate this sentence into plain English.")

163 .temperature(0)

164 .build();226 .build();

165 227 

166var completion = client.chat().completions().create(params);228var completion = client.chat().completions().create(params);


169System.out.println(usage.promptTokens() + " prompt tokens used.");231System.out.println(usage.promptTokens() + " prompt tokens used.");

170```232```

171 233 

234```ruby

235require "openai"

236 

237client = OpenAI::Client.new

238response = client.chat.completions.create(

239 model: "gpt-6.2-astra",

240 messages: [

241 {

242 role: :user,

243 content: "Translate this sentence into plain English."

244 }

245 ]

246)

247usage = response.usage or raise "The response did not include token usage"

248puts "#{usage.prompt_tokens} prompt tokens used."

249```

172 250 

173 251 

174To see how many tokens are in a text string without making an API call, use OpenAI’s [tiktoken](https://github.com/openai/tiktoken) Python library. Example code can be found in the OpenAI Cookbook’s guide on [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).252To see how many tokens are in a text string without making an API call, use OpenAI’s [tiktoken](https://github.com/openai/tiktoken) Python library. Example code can be found in the OpenAI Cookbook’s guide on [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).


187 265 

188 266 

189 267 

190They work by directly modifying the logits (un-normalized log-probabilities) with an additive contribution.268They work by directly modifying the raw token scores (un-normalized log-probabilities) with an additive contribution.

269 

270Set frequency and presence penalties

191 271 

192```python272```python

193mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence273mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence


200 280 

201Where:281Where:

202 282 

203- `mu[j]` is the logits of the j-th token283- `mu[j]` is the raw score of the j-th token

204- `c[j]` is how often that token was sampled prior to the current position284- `c[j]` is how often that token was sampled prior to the current position

205- The presence penalty subtracts `alpha_presence` if `c[j] > 0` and 0 otherwise285- The presence penalty subtracts `alpha_presence` if `c[j] > 0` and 0 otherwise

206- `alpha_frequency` is the frequency penalty coefficient286- `alpha_frequency` is the frequency penalty coefficient

Details

97 raise FileNotFoundError(f"No artifact for {path!r} in turn {turn_id}")97 raise FileNotFoundError(f"No artifact for {path!r} in turn {turn_id}")

98```98```

99 99 

100```ruby

101require "openai"

102 

103def download_artifact(client, session_id, turn_id, path, destination)

104 client.beta.agents.sessions.artifacts.list(session_id).auto_paging_each do |artifact|

105 next unless artifact.turn_id == turn_id && artifact.path == path

106 

107 content = client.beta.agents.sessions.artifacts.content(artifact.id, session_id: session_id)

108 begin

109 File.open(destination, "wb") { |file| IO.copy_stream(content, file) }

110 ensure

111 content.close

112 end

113 return destination

114 end

115 raise Errno::ENOENT, "No artifact for #{path.inspect} in turn #{turn_id}"

116end

117 

118download_artifact(OpenAI::Client.new, "sess_123", "turn_123", "/workspace/outputs/report.pdf", "report.pdf")

119```

120 

100 121 

101 122 

102 123 

Details

90 90 

91Use stdio to let the executor start a server process. Install the server and its dependencies in the environment first.91Use stdio to let the executor start a server process. Install the server and its dependencies in the environment first.

92 92 

93For this customer lookup example, install the MCP SDK:93 

94 

95 

96For the Python version of this customer lookup example, install the MCP SDK:

94 97 

95```bash98```bash

96python3 -m venv /workspace/mcp-demo99python3 -m venv /workspace/mcp-demo

97/workspace/mcp-demo/bin/python -m pip install 'mcp==1.26.0'100/workspace/mcp-demo/bin/python -m pip install 'mcp==1.26.0'

98```101```

99 102 

100Save the server as `/workspace/lookup_mcp.py`:103 

104 

105 

106 

107 

108 

109Save the Python server as `/workspace/lookup_mcp.py`.

110 

111 

112 

113 

114 

115 

116 

117For Ruby, install the `mcp` gem at version `1.10.0` and save the Ruby server as `/workspace/lookup_mcp.rb`. The Ruby example is tested with Ruby 3.3.

118 

119 

120 

101 121 

102Run a customer lookup MCP server122Run a customer lookup MCP server

103 123 


121 server.run(transport=transport)141 server.run(transport=transport)

122```142```

123 143 

144```ruby

145require "mcp"

146require "json"

147 

148class GetCustomer < MCP::Tool

149 tool_name "get_customer"

150 description "Look up a customer in the example data."

151 input_schema(type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"])

152 

153 def self.call(customer_id:, server_context:)

154 customers = {

155 "123" => {

156 name: "Example Customer",

157 plan: "pro"

158 }

159 }

160 result = { customer: customers[customer_id] }

161 MCP::Tool::Response.new(

162 [

163 {

164 type: "text",

165 text: JSON.generate(result)

166 }

167 ], structured_content: result

168 )

169 end

170end

171 

172server = MCP::Server.new(name: "customer-lookup", version: "1.0.0", tools: [GetCustomer])

173# Use `ruby main.rb http` for the HTTP endpoint at /mcp; default to stdio.

174if ARGV.first == "http"

175 require "rackup"

176 require "rackup/handler/webrick"

177 transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true)

178 app = Rack::URLMap.new("/mcp" => transport)

179 Rackup::Handler::WEBrick.run(app, Host: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "8765")))

180else

181 MCP::Server::Transports::StdioTransport.new(server).open

182end

183```

184 

185 

186Add the server to `agent.tools`.

187 

188 

189 

190 

191The following configuration starts the Python server.

192 

193 

194 

195 

196 

197 

198 

199For Ruby, set `transport.command` to the absolute path of your Ruby executable and `transport.args` to `["/workspace/lookup_mcp.rb", "stdio"]`. Install the gem for that Ruby runtime. The `stdio` argument selects the script's transport:

200 

201 

124 202 

125Add the server to `agent.tools`. The `stdio` argument selects the script's transport:

126 203 

127```json204```json

128{205{

Details

170 170 

171This helper packages your folder and creates a session. Pass your API client and the path to `docs-helper`. OpenAI extracts and registers the plugin automatically.171This helper packages your folder and creates a session. Pass your API client and the path to `docs-helper`. OpenAI extracts and registers the plugin automatically.

172 172 

173 

174 

175 

176The Ruby helper requires the `openai` and `rubyzip` gems. Install them with `gem install openai rubyzip` and set `OPENAI_API_KEY` before creating the client.

177 

178 

179 

180 

173Upload a plugin folder181Upload a plugin folder

174 182 

175```python183```python


212 )220 )

213```221```

214 222 

223```ruby

224require "openai"

225require "json"

226require "base64"

227require "tmpdir"

228require "fileutils"

229require "zip"

230 

231def upload_plugin(client, plugin_directory)

232 plugin_directory = File.expand_path(plugin_directory)

233 manifest = JSON.parse(File.read(File.join(plugin_directory, ".codex-plugin/plugin.json")))

234 Dir.mktmpdir do |temporary|

235 archive = File.join(temporary, "plugin.zip")

236 Zip::File.open(archive, create: true) do |zip|

237 Dir.glob("**/*", File::FNM_DOTMATCH, base: plugin_directory).sort.each do |relative|

238 source = File.join(plugin_directory, relative)

239 next unless File.file?(source)

240 

241 zip.add(File.join(File.basename(plugin_directory), relative), source)

242 end

243 end

244 client.beta.agents.sessions.create(

245 agent: { model: "gpt-6-astra" },

246 environment: {

247 type: :openai_hosted,

248 plugins: [

249 {

250 type: :inline,

251 name: manifest.fetch("name"),

252 description: manifest.fetch("description"),

253 source: {

254 type: :base64,

255 media_type: "application/zip",

256 data: Base64.strict_encode64(File.binread(archive))

257 }

258 }

259 ]

260 }

261 )

262 end

263end

264```

265 

215 266 

216## Reuse a hosted plugin setup267## Reuse a hosted plugin setup

217 268 

Details

43const agent = new Agent({43const agent = new Agent({

44 name: "Weather bot",44 name: "Weather bot",

45 instructions: "You are a helpful weather bot.",45 instructions: "You are a helpful weather bot.",

46 model: "gpt-6-astra",46 model: "gpt-6.2-astra",

47 tools: [getWeather],47 tools: [getWeather],

48});48});

49```49```


61agent = Agent(61agent = Agent(

62 name="Weather bot",62 name="Weather bot",

63 instructions="You are a helpful weather bot.",63 instructions="You are a helpful weather bot.",

64 model="gpt-6-astra",64 model="gpt-6.2-astra",

65 tools=[get_weather],65 tools=[get_weather],

66)66)

67```67```

Details

20const fastAgent = new Agent({20const fastAgent = new Agent({

21 name: "Fast support agent",21 name: "Fast support agent",

22 instructions: "Handle routine support questions.",22 instructions: "Handle routine support questions.",

23 model: "gpt-5.6-terra",23 model: "gpt-6.1-terra",

24});24});

25 25 

26const generalAgent = new Agent({26const generalAgent = new Agent({


29});29});

30 30 

31const runner = new Runner({31const runner = new Runner({

32 model: "gpt-6-astra",32 model: "gpt-6.2-astra",

33});33});

34 34 

35await runner.run(fastAgent, "Summarize ticket 123.");35await runner.run(fastAgent, "Summarize ticket 123.");


49fast_agent = Agent(49fast_agent = Agent(

50 name="Fast support agent",50 name="Fast support agent",

51 instructions="Handle routine support questions.",51 instructions="Handle routine support questions.",

52 model="gpt-5.6-terra",52 model="gpt-6.1-terra",

53)53)

54 54 

55general_agent = Agent(55general_agent = Agent(


64 result = await Runner.run(64 result = await Runner.run(

65 general_agent,65 general_agent,

66 "Investigate the billing issue on account 456.",66 "Investigate the billing issue on account 456.",

67 run_config=RunConfig(model="gpt-6-astra"),67 run_config=RunConfig(model="gpt-6.2-astra"),

68 )68 )

69 print(result.final_output)69 print(result.final_output)

70 70 


74```74```

75 75 

76 76 

77For most new SDK workflows, start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) and move to a smaller variant only when latency or cost matters enough to justify it. Use the platform-wide [Model guidance](https://developers.openai.com/api/docs/guides/latest-model) page for current model-selection advice.77For most new SDK workflows, start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and move to a smaller variant only when latency or cost matters enough to justify it. Use the platform-wide [Model guidance](https://developers.openai.com/api/docs/guides/latest-model) page for current model-selection advice.

78 78 

79## Choose the simplest default strategy79## Choose the simplest default strategy

80 80 

Details

36const agent = new Agent({36const agent = new Agent({

37 name: "History tutor",37 name: "History tutor",

38 instructions: "You answer history questions clearly and concisely.",38 instructions: "You answer history questions clearly and concisely.",

39 model: "gpt-6-astra",39 model: "gpt-6.2-astra",

40});40});

41 41 

42const result = await run(agent, "When did the Roman Empire fall?");42const result = await run(agent, "When did the Roman Empire fall?");


51agent = Agent(51agent = Agent(

52 name="History tutor",52 name="History tutor",

53 instructions="You answer history questions clearly and concisely.",53 instructions="You answer history questions clearly and concisely.",

54 model="gpt-6-astra",54 model="gpt-6.2-astra",

55)55)

56 56 

57 57 

Details

314 314 

315const agent = new SandboxAgent({315const agent = new SandboxAgent({

316 name: "Renewal Packet Analyst",316 name: "Renewal Packet Analyst",

317 model: "gpt-6-astra",317 model: "gpt-6.2-astra",

318 instructions:318 instructions:

319 "Review the workspace before answering. Keep the response concise, " +319 "Review the workspace before answering. Keep the response concise, " +

320 "business-focused, and cite the file names that support each conclusion.",320 "business-focused, and cite the file names that support each conclusion.",


366 366 

367agent = SandboxAgent(367agent = SandboxAgent(

368 name="Renewal Packet Analyst",368 name="Renewal Packet Analyst",

369 model="gpt-6-astra",369 model="gpt-6.2-astra",

370 instructions=(370 instructions=(

371 "Review the workspace before answering. Keep the response concise, "371 "Review the workspace before answering. Keep the response concise, "

372 "business-focused, and cite the file names that support each conclusion."372 "business-focused, and cite the file names that support each conclusion."


412 412 

413const agent = new SandboxAgent({413const agent = new SandboxAgent({

414 name: "Workspace reviewer",414 name: "Workspace reviewer",

415 model: "gpt-6-astra",415 model: "gpt-6.2-astra",

416 instructions: "Inspect the sandbox workspace before answering.",416 instructions: "Inspect the sandbox workspace before answering.",

417});417});

418 418 


515});515});

516const agent = new SandboxAgent({516const agent = new SandboxAgent({

517 name: "Workspace builder",517 name: "Workspace builder",

518 model: "gpt-6-astra",518 model: "gpt-6.2-astra",

519 instructions: "Inspect the sandbox workspace before answering.",519 instructions: "Inspect the sandbox workspace before answering.",

520});520});

521 521 

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Agents like [Codex](https://openai.com/index/introducing-codex/) and [Deep Research](https://openai.com/index/introducing-deep-research/) show that reasoning models can take several minutes to solve complex problems. Background mode enables you to execute long-running tasks on models like GPT-5.2 and GPT-5.2 Pro reliably, without having to worry about timeouts or other connectivity issues.5Use background mode to run long-running Responses API requests asynchronously,

6including multi-step agent runs. An agent run is the full workflow your

7application manages: it sends an initial request and can use the result to

8decide what to do next, such as running a tool and sending its output in a

9follow-up request. For independent requests you can submit together up front,

10use the [Batch API](https://developers.openai.com/api/docs/guides/batch).

6 11 

7Background mode kicks off these tasks asynchronously, and developers can poll response objects to check status over time. To start response generation in the background, make an API request with `background` set to `true`:12## Choose a completion window

8 13 

9Background requests from Zero Data Retention (ZDR) projects run with14Set `background_options.completion_window` based on how soon you need the

10 `store=false`. Response data is temporarily stored to disk for roughly 1015initial response. For `2h` and `8h`, the API targets completion within the

11 minutes to enable asynchronous execution and polling.16selected window after it accepts the request.

12 17 

13For projects using [Modified Abuse18| Window | When to use it | Model token discount |

14Monitoring](https://developers.openai.com/api/docs/guides/your-data#modified-abuse-monitoring), including19| ------------------- | ------------------------------------------------------------------------- | -------------------- |

15enhanced Modified Abuse Monitoring, foreground requests follow standard20| `soonest` (default) | Generate an on-demand report while someone waits for the result. | None |

16retention when `store` is omitted or set to `true`. Background responses are21| `2h` | Analyze the morning’s support tickets before an afternoon triage meeting. | 30% below Standard |

17retained after the polling period only when `store=true` is explicitly provided.22| `8h` | Review a batch of documents overnight for the next morning. | 40% below Standard |

18If `store` is omitted or set to `false` for a background request, the response23 

19is deleted after roughly 10 minutes.24For an overnight document review, start with an `8h` request. If the first

25response asks your application to look up a document, run the tool and send its

26result in a [follow-up request](#run-a-workflow-with-follow-up-requests). Reuse

27the window, continuation ID, model, and project to qualify for higher queue

28priority.

29 

30The completion target starts when the API accepts the initial request and

31applies to that response. The discount applies to model token rates on each

32eligible request, including follow-ups. In this example, both requests qualify for the 40% discount.

33 

34## Start a background request

35 

36Set `background` to `true` and save the response ID returned by the API. Use a

37webhook to learn when the request finishes and retrieve the response by ID.

38This example uses the default completion window (`soonest`).

20 39 

21Generate a response in the background40Generate a response in the background

22 41 


25-H "Content-Type: application/json" \44-H "Content-Type: application/json" \

26-H "Authorization: Bearer $OPENAI_API_KEY" \45-H "Authorization: Bearer $OPENAI_API_KEY" \

27-d '{46-d '{

28 "model": "gpt-6-astra",47 "model": "gpt-6.2-astra",

29 "input": "Write a very long novel about otters in space.",48 "input": "Write a very long novel about otters in space.",

30 "background": true49 "background": true

31}'50}'


36const client = new OpenAI();55const client = new OpenAI();

37 56 

38const resp = await client.responses.create({57const resp = await client.responses.create({

39 model: "gpt-6-astra",58 model: "gpt-6.2-astra",

40 input: "Write a very long novel about otters in space.",59 input: "Write a very long novel about otters in space.",

41 background: true,60 background: true,

42});61});


50client = OpenAI()69client = OpenAI()

51 70 

52resp = client.responses.create(71resp = client.responses.create(

53 model="gpt-6-astra",72 model="gpt-6.2-astra",

54 input="Write a very long novel about otters in space.",73 input="Write a very long novel about otters in space.",

55 background=True,74 background=True,

56)75)


73 client := openai.NewClient()92 client := openai.NewClient()

74 93 

75 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{94 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

76 Model: "gpt-6-astra",95 Model: "gpt-6.2-astra",

77 Background: openai.Bool(true),96 Background: openai.Bool(true),

78 Input: responses.ResponseNewParamsInputUnion{97 Input: responses.ResponseNewParamsInputUnion{

79 OfString: openai.String("Write a very long novel about otters in space."),98 OfString: openai.String("Write a very long novel about otters in space."),


94 113 

95ResponseCreateParams params =114ResponseCreateParams params =

96 ResponseCreateParams.builder()115 ResponseCreateParams.builder()

97 .model("gpt-6-astra")116 .model("gpt-6.2-astra")

98 .input("Write a detailed market analysis.")117 .input("Write a detailed market analysis.")

99 .background(true)118 .background(true)

100 .build();119 .build();


112 131 

113CreateResponseOptions options = new()132CreateResponseOptions options = new()

114{133{

115 Model = "gpt-6-astra",134 Model = "gpt-6.2-astra",

116 BackgroundModeEnabled = true,135 BackgroundModeEnabled = true,

117};136};

118options.InputItems.Add(137options.InputItems.Add(


128 147 

129client = OpenAI::Client.new148client = OpenAI::Client.new

130response = client.responses.create(149response = client.responses.create(

131 model: "gpt-6-astra",150 model: "gpt-6.2-astra",

132 input: "Write a detailed market analysis.",151 input: "Write a detailed market analysis.",

133 background: true152 background: true

134)153)


137```156```

138 157 

139 158 

159Background mode temporarily stores response data even when you set `store` to

160 `false` or use Zero Data Retention. The API uses this data to run the request

161 and make the result available for retrieval. The API encrypts temporarily

162 stored request content at rest for all completion windows (`soonest`, `2h`,

163 and `8h`). See [Data controls](https://developers.openai.com/api/docs/guides/your-data#v1responses) for

164 details on temporary storage.

165 

166## Receive results with webhooks

167 

1681. [Create a webhook endpoint](https://developers.openai.com/api/docs/guides/webhooks#creating-webhook-endpoints)

169 for the project that sends your background requests. Subscribe to

170 [`response.completed`](https://developers.openai.com/api/reference/resources/webhooks)

171 and to the events for failed, incomplete, or canceled responses you want to

172 handle.

1732. [Verify the signature](https://developers.openai.com/api/docs/guides/webhooks#verifying-webhook-signatures)

174 on incoming events. Hand off any longer work to a background worker and

175 return a `2xx` response as soon as you accept the event.

1763. For `response.completed`, use `event.data.id` to

177 [retrieve the response](https://developers.openai.com/api/reference/resources/responses/methods/retrieve). Handle other

178 terminal events according to your application's workflow.

179 

180The [webhooks guide](https://developers.openai.com/api/docs/guides/webhooks) includes a server example that

181verifies the signature and retrieves the completed response. If you can't receive

182webhooks, [poll the response](#polling-background-responses) using its ID.

183 

184After the API accepts a `2h` or `8h` request, it automatically retries eligible

185capacity errors. While the response is `queued` or `in_progress`, wait for a

186webhook or poll using the same response ID.

187 

188## Use discounted completion windows

189 

190Discounted completion windows are in public beta on GPT-6.2 Astra, GPT-6.2

191 Sol, GPT-6.1 Terra, and GPT-6 Luna.

192 

193Requests with `2h` or `8h` completion windows share the

194[Batch/Background Rate Limit](https://developers.openai.com/api/docs/guides/rate-limits#how-do-these-rate-limits-work)

195with Batch API jobs. The API counts input tokens at submission. Requests with the

196default `soonest` window use the regular request and token limits.

197 

198If your application can wait for the initial response, use a two-hour or eight-hour

199completion window. Set `background` to `true` and set

200`background_options.completion_window` to `2h` or `8h`. Leave `stream` unset or

201set it to `false`. See

202[completion window pricing](https://developers.openai.com/api/docs/pricing#background-completion-windows).

203 

204Discounted windows require Standard processing. Set `service_tier` to `default`

205to select Standard. With `auto`, the request qualifies only if the API selects

206Standard.

207 

208Standard requests outside the discounted completion windows can’t reuse prompt

209cache entries created by `2h` or `8h` background requests, even when the prompt

210is identical.

211 

212For a single overnight document review, send an `8h` request to

213[`POST /v1/responses`](https://developers.openai.com/api/reference/resources/responses/methods/create) with

214`gpt-6.1-terra` and the document contents in `input`. Leave

215`background_options.continuation_id` unset if you only need one response.

216 

217For the default completion window, omit `background_options.completion_window`

218or set it to `soonest`.

219 

220### Run a workflow with follow-up requests

221 

222Use the same API project for both requests in the overnight document review.

223 

2241. Ask `gpt-6.1-terra` to look up a document by ID and review it for missing

225 approvals in a [create response request](https://developers.openai.com/api/reference/resources/responses/methods/create). Set

226 `background` to `true`, `service_tier` to `default`, and

227 `background_options.completion_window` to `8h`. Set

228 `background_options.continuation_id` to a unique ID your application

229 chooses for this run. Include a [function tool](https://developers.openai.com/api/docs/guides/function-calling#defining-functions)

230 that retrieves a document by ID. Save the response ID returned by the API.

2312. When you receive a `response.completed` webhook,

232 [deduplicate deliveries](https://developers.openai.com/api/docs/guides/webhooks#handling-webhook-requests-on-a-server)

233 using the `webhook-id` header. Check that `event.data.id` matches the saved

234 response ID before proceeding. Retrieve the response and run the document

235 lookup requested by its `function_call` output item. If your app may need to

236 continue after the response expires, save the original input and the full

237 response `output` while you can still retrieve it.

2383. Create a follow-up response with the same model, service tier, background

239 setting, completion window, and continuation ID. Set

240 `previous_response_id` to `event.data.id` to carry forward conversation

241 history if the prior response is still available. In `input`, send a

242 `function_call_output` item with the original function call's `call_id` and

243 the retrieved document as its `output`.

244 

245Reuse `continuation_id` to make follow-ups eligible for higher queue priority.

246Start times depend on scheduling. If the prior response expires, omit

247`previous_response_id` and

248[pass the conversation history in `input`](https://developers.openai.com/api/docs/guides/conversation-state#manually-manage-conversation-state).

249Replay the original input and every item in the saved response `output` in

250order, including any encrypted reasoning items and the original function call.

251Then append the new `function_call_output` item.

252 

140## Polling background responses253## Polling background responses

141 254 

142To check the status of background requests, use the GET endpoint for Responses. Keep polling while the request is in the queued or in_progress state. When it leaves these states, it has reached a final (terminal) state.255As an alternative to webhooks, use the response ID to check the request's status

256with the [retrieve endpoint](https://developers.openai.com/api/reference/resources/responses/methods/retrieve). Keep polling

257while the status is `queued` or `in_progress`. When the status changes to a

258terminal state, stop polling.

143 259 

144Retrieve a response executing in the background260Retrieve a response executing in the background

145 261 


154const client = new OpenAI();270const client = new OpenAI();

155 271 

156let resp = await client.responses.create({272let resp = await client.responses.create({

157 model: "gpt-6-astra",273 model: "gpt-6.2-astra",

158 input: "Write a very long novel about otters in space.",274 input: "Write a very long novel about otters in space.",

159 background: true,275 background: true,

160});276});


175client = OpenAI()291client = OpenAI()

176 292 

177resp = client.responses.create(293resp = client.responses.create(

178 model="gpt-6-astra",294 model="gpt-6.2-astra",

179 input="Write a very long novel about otters in space.",295 input="Write a very long novel about otters in space.",

180 background=True,296 background=True,

181)297)


204 client := openai.NewClient()320 client := openai.NewClient()

205 321 

206 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{322 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

207 Model: "gpt-6-astra",323 Model: "gpt-6.2-astra",

208 Background: openai.Bool(true),324 Background: openai.Bool(true),

209 Input: responses.ResponseNewParamsInputUnion{325 Input: responses.ResponseNewParamsInputUnion{

210 OfString: openai.String("Write a very long novel about otters in space."),326 OfString: openai.String("Write a very long novel about otters in space."),


235 351 

236ResponseCreateParams params =352ResponseCreateParams params =

237 ResponseCreateParams.builder()353 ResponseCreateParams.builder()

238 .model("gpt-6-astra")354 .model("gpt-6.2-astra")

239 .input("Write a very long novel about otters in space.")355 .input("Write a very long novel about otters in space.")

240 .background(true)356 .background(true)

241 .build();357 .build();


264 380 

265CreateResponseOptions options = new()381CreateResponseOptions options = new()

266{382{

267 Model = "gpt-6-astra",383 Model = "gpt-6.2-astra",

268 BackgroundModeEnabled = true,384 BackgroundModeEnabled = true,

269};385};

270options.InputItems.Add(386options.InputItems.Add(


290 406 

291client = OpenAI::Client.new407client = OpenAI::Client.new

292response = client.responses.create(408response = client.responses.create(

293 model: "gpt-6-astra",409 model: "gpt-6.2-astra",

294 input: "Write a very long novel about otters in space.",410 input: "Write a very long novel about otters in space.",

295 background: true411 background: true

296)412)


397```513```

398 514 

399 515 

400Cancelling twice is idempotent - subsequent calls simply return the final `Response` object.516Canceling twice is idempotent. Later calls return the final `Response` object.

517For a synchronous response, close the connection instead.

401 518 

402## Streaming a background response519## Streaming a background response

403 520 

404You can create a background Response and start streaming events from it right away. This may be helpful if you expect the client to drop the stream and want the option of picking it back up later. To do this, create a Response with both `background` and `stream` set to `true`. You will want to keep track of a "cursor" corresponding to the `sequence_number` you receive in each streaming event.521To stream a background response, use the default completion window (`soonest`)

522and set `stream: true` when you create it. For `2h` and `8h` requests, omit

523`stream` or set it to `false`.

405 524 

406Currently, the time to first token you receive from a background response is525If the connection drops, resume the stream by passing the last event's

407 higher than what you receive from a synchronous one. We are working to reduce526`sequence_number` as `starting_after`. You can't stream a response later if

408 this latency gap in the coming weeks.527it was created without streaming.

528 

529Time to first token can be higher for a background response than for a

530 synchronous response.

409 531 

410Generate and stream a background response532Generate and stream a background response

411 533 


414-H "Content-Type: application/json" \536-H "Content-Type: application/json" \

415-H "Authorization: Bearer $OPENAI_API_KEY" \537-H "Authorization: Bearer $OPENAI_API_KEY" \

416-d '{538-d '{

417 "model": "gpt-6-astra",539 "model": "gpt-6.2-astra",

418 "input": "Write a very long novel about otters in space.",540 "input": "Write a very long novel about otters in space.",

419 "background": true,541 "background": true,

420 "stream": true542 "stream": true

421}'543}'

422 544 

423// To resume:545# To resume:

424curl "https://api.openai.com/v1/responses/resp_123?stream=true&starting_after=42" \546curl "https://api.openai.com/v1/responses/resp_123?stream=true&starting_after=42" \

425-H "Content-Type: application/json" \547-H "Content-Type: application/json" \

426-H "Authorization: Bearer $OPENAI_API_KEY"548-H "Authorization: Bearer $OPENAI_API_KEY"


431const client = new OpenAI();553const client = new OpenAI();

432 554 

433const stream = await client.responses.create({555const stream = await client.responses.create({

434 model: "gpt-6-astra",556 model: "gpt-6.2-astra",

435 input: "Write a very long novel about otters in space.",557 input: "Write a very long novel about otters in space.",

436 background: true,558 background: true,

437 stream: true,559 stream: true,


461 583 

462# Fire off an async response but also start streaming immediately584# Fire off an async response but also start streaming immediately

463stream = client.responses.create(585stream = client.responses.create(

464 model="gpt-6-astra",586 model="gpt-6.2-astra",

465 input="Write a very long novel about otters in space.",587 input="Write a very long novel about otters in space.",

466 background=True,588 background=True,

467 stream=True,589 stream=True,


500 client := openai.NewClient()622 client := openai.NewClient()

501 623 

502 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{624 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

503 Model: "gpt-6-astra",625 Model: "gpt-6.2-astra",

504 Background: openai.Bool(true),626 Background: openai.Bool(true),

505 Input: responses.ResponseNewParamsInputUnion{627 Input: responses.ResponseNewParamsInputUnion{

506 OfString: openai.String("Write a very long novel about otters in space."),628 OfString: openai.String("Write a very long novel about otters in space."),


554 676 

555ResponseCreateParams params =677ResponseCreateParams params =

556 ResponseCreateParams.builder()678 ResponseCreateParams.builder()

557 .model("gpt-6-astra")679 .model("gpt-6.2-astra")

558 .input("Write a very long novel about otters in space.")680 .input("Write a very long novel about otters in space.")

559 .background(true)681 .background(true)

560 .build();682 .build();


655 777 

656CreateResponseOptions options = new()778CreateResponseOptions options = new()

657{779{

658 Model = "gpt-6-astra",780 Model = "gpt-6.2-astra",

659 BackgroundModeEnabled = true,781 BackgroundModeEnabled = true,

660 StreamingEnabled = true,782 StreamingEnabled = true,

661};783};


737# An uncapped background novel can run beyond the SDK's default ten minutes.859# An uncapped background novel can run beyond the SDK's default ten minutes.

738client = OpenAI::Client.new(timeout: 30 * 60)860client = OpenAI::Client.new(timeout: 30 * 60)

739stream = client.responses.stream(861stream = client.responses.stream(

740 model: "gpt-6-astra",862 model: "gpt-6.2-astra",

741 input: "Write a very long novel about otters in space.",863 input: "Write a very long novel about otters in space.",

742 background: true864 background: true

743)865)


764# puts(event.type)886# puts(event.type)

765# end887# end

766```888```

767 

768 

769## Limits

770 

7711. Background requests can use `store=false`, but response data is temporarily

772 stored to support asynchronous execution and polling.

7732. To cancel a synchronous response, terminate the connection

7743. You can only start a new stream from a background response if you created it with `stream=true`.

guides/batch.md +5 −5

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Learn how to use OpenAI's Batch API to send asynchronous groups of requests with 50% lower costs, a separate pool of significantly higher rate limits, and a clear 24-hour turnaround time. The service is ideal for processing jobs that don't require immediate responses. You can also [explore the API reference directly here](https://developers.openai.com/api/reference/resources/batches).5Learn how to use OpenAI's Batch API to send asynchronous groups of requests with 50% lower costs, a queued-token limit separate from per-minute limits, and a clear 24-hour turnaround time. The service is ideal for processing jobs that don't require immediate responses. You can also [explore the API reference directly here](https://developers.openai.com/api/reference/resources/batches).

6 6 

7## Overview7## Overview

8 8 


637 637 

638## Model availability638## Model availability

639 639 

640Most models support the Batch API. Check the [model reference](https://developers.openai.com/api/docs/models) for your model. GPT-6 Sol and Luna support EU data residency with Standard, Flex, and Batch processing. See [data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency).640Most models support the Batch API. Check the [model reference](https://developers.openai.com/api/docs/models) for your model. GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Batch processing. GPT-6 Sol and Luna support EU data residency with Standard, Flex, and Batch processing. See [data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency).

641 641 

642GPT-Image-2.5 supports batch image generation and editing with `gpt-image-2.5-flare` and `gpt-image-2.5-sunburst`, including their `2026-09-08` snapshots. Use `/v1/images/generations` or `/v1/images/edits` and see [image generation pricing](https://developers.openai.com/api/docs/pricing?multimodal-image-pricing=batch#image-generation) for Batch rates.642GPT-Image-2.5 supports batch image generation and editing with `gpt-image-2.5-flare` and `gpt-image-2.5-sunburst`, including their `2026-09-08` snapshots. Use `/v1/images/generations` or `/v1/images/edits` and see [image generation pricing](https://developers.openai.com/api/docs/pricing?multimodal-image-pricing=batch#image-generation) for Batch rates.

643 643 

644## Rate limits644## Rate limits

645 645 

646Batch API rate limits are separate from existing per-model rate limits. The Batch API has three types of rate limits:646The Batch API has three types of limits:

647 647 

6481. **Per-batch limits:** A single batch may include up to 50,000 requests, and a batch input file can be up to 200 MB in size. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch.6481. **Per-batch limits:** A single batch may include up to 50,000 requests, and a batch input file can be up to 200 MB in size. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch.

6492. **Queued prompt tokens per model:** Each model has a maximum number of prompt tokens that can be queued for batch processing. You can find these limits on the [Platform Settings page](https://platform.openai.com/settings/organization/limits).6492. **Queued input tokens per model:** Batch API jobs share the [Batch/Background Rate Limit](https://developers.openai.com/api/docs/guides/rate-limits#how-do-these-rate-limits-work) with Background mode requests using `2h` or `8h` completion windows. The API counts input tokens at submission. You can find your limits in [Settings > Organization > Limits](https://platform.openai.com/settings/organization/limits).

6503. **Batch creation rate limit:** You can create up to 2,000 batches per hour. If you need to submit more requests, increase the number of requests per batch.6503. **Batch creation rate limit:** You can create up to 2,000 batches per hour. If you need to submit more requests, increase the number of requests per batch.

651 651 

652The Batch API currently has no output-token limit. Because Batch API rate limits are a new, separate pool, **using the Batch API will not consume tokens from your standard per-model rate limits**, thereby offering you a convenient way to increase the number of requests and processed tokens you can use when querying our API.652The Batch API currently has no output-token limit. Batch API jobs don't count toward standard per-model request or token rate limits.

653 653 

654## Batch expiration654## Batch expiration

655 655 

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Writing, reviewing, editing, and answering questions about code is one of the primary use cases for OpenAI models today. This guide walks through your options for code generation with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) and Codex.5Writing, reviewing, editing, and answering questions about code is one of the primary use cases for OpenAI models today. This guide walks through your options for code generation with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and Codex.

6 6 

7## Get started7## Get started

8 8 


23 23 

24## Integrate with coding models24## Integrate with coding models

25 25 

26For most API-based code generation, start with **`gpt-6-astra`**. It handles both general-purpose work and coding, which makes it a strong default when your application needs to write code, reason about requirements, inspect docs, and handle broader workflows in one place.26For most API-based code generation, start with **`gpt-6.2-astra`**. It handles both general-purpose work and coding, which makes it a strong default when your application needs to write code, reason about requirements, inspect docs, and handle broader workflows in one place.

27 27 

28This example shows how you can use the [Responses API](https://developers.openai.com/api/reference/resources/responses) for a code generation use case:28This example shows how you can use the [Responses API](https://developers.openai.com/api/reference/resources/responses) for a code generation use case:

29 29 


34const openai = new OpenAI();34const openai = new OpenAI();

35 35 

36const result = await openai.responses.create({36const result = await openai.responses.create({

37 model: "gpt-6-astra",37 model: "gpt-6.2-astra",

38 input: `Find the null pointer exception in this code:38 input: `Find the null pointer exception in this code:

39 39 

40def display_name(user):40def display_name(user):


54client = OpenAI()54client = OpenAI()

55 55 

56result = client.responses.create(56result = client.responses.create(

57 model="gpt-6-astra",57 model="gpt-6.2-astra",

58 input="""Find the null pointer exception in this code:58 input="""Find the null pointer exception in this code:

59 59 

60def display_name(user):60def display_name(user):


83func main() {83func main() {

84 client := openai.NewClient()84 client := openai.NewClient()

85 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{85 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

86 Model: "gpt-6-astra",86 Model: "gpt-6.2-astra",

87 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(`Find the null pointer exception in this code:87 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(`Find the null pointer exception in this code:

88 88 

89def display_name(user):89def display_name(user):


116 116 

117ResponseCreateParams params =117ResponseCreateParams params =

118 ResponseCreateParams.builder()118 ResponseCreateParams.builder()

119 .model("gpt-6-astra")119 .model("gpt-6.2-astra")

120 .input("Find the null pointer exception in this code:\n\n" + code)120 .input("Find the null pointer exception in this code:\n\n" + code)

121 .reasoning(Reasoning.builder().effort(ReasoningEffort.HIGH).build())121 .reasoning(Reasoning.builder().effort(ReasoningEffort.HIGH).build())

122 .build();122 .build();


137 137 

138CreateResponseOptions options = new()138CreateResponseOptions options = new()

139{139{

140 Model = "gpt-6-astra",140 Model = "gpt-6.2-astra",

141 ReasoningOptions = new ResponseReasoningOptions141 ReasoningOptions = new ResponseReasoningOptions

142 {142 {

143 ReasoningEffortLevel = ResponseReasoningEffortLevel.High,143 ReasoningEffortLevel = ResponseReasoningEffortLevel.High,


172PYTHON172PYTHON

173 173 

174response = client.responses.create(174response = client.responses.create(

175 model: "gpt-6-astra",175 model: "gpt-6.2-astra",

176 input: "Find the null pointer exception in this code:\n\n#{code}",176 input: "Find the null pointer exception in this code:\n\n#{code}",

177 reasoning: { effort: :high }177 reasoning: { effort: :high }

178)178)


185 -H "Content-Type: application/json" \185 -H "Content-Type: application/json" \

186 -H "Authorization: Bearer $OPENAI_API_KEY" \186 -H "Authorization: Bearer $OPENAI_API_KEY" \

187 -d '{187 -d '{

188 "model": "gpt-6-astra",188 "model": "gpt-6.2-astra",

189 "input": "Find the null pointer exception in this code:\n\ndef display_name(user):\n return user.profile.name\n\nprint(display_name(None))\n",189 "input": "Find the null pointer exception in this code:\n\ndef display_name(user):\n return user.profile.name\n\nprint(display_name(None))\n",

190 "reasoning": { "effort": "high" }190 "reasoning": { "effort": "high" }

191 }'191 }'


194 194 

195## Frontend development195## Frontend development

196 196 

197For frontend work, start with `gpt-6.1-sol` or `gpt-6-astra` in Codex or the Responses API.197For frontend work, start with `gpt-6.1-sol` or `gpt-6.2-astra` in Codex or the Responses API.

198 198 

199The historical GPT-5 gallery shows applications generated from a single prompt. Use the prompts as starting points and evaluate the results with the model you plan to deploy.199The historical GPT-5 gallery shows applications generated from a single prompt. Use the prompts as starting points and evaluate the results with the model you plan to deploy.

200 200 


202 202 

203- Visit the [ChatGPT docs](https://developers.openai.com/codex) to learn what you can do with Codex, set up Codex in whichever interface you choose, or find more details.203- Visit the [ChatGPT docs](https://developers.openai.com/codex) to learn what you can do with Codex, set up Codex in whichever interface you choose, or find more details.

204- Read [Model guidance](https://developers.openai.com/api/docs/guides/latest-model) for model selection, features, migration guidance, and prompting patterns that work well on coding and agentic tasks.204- Read [Model guidance](https://developers.openai.com/api/docs/guides/latest-model) for model selection, features, migration guidance, and prompting patterns that work well on coding and agentic tasks.

205- Compare [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) and [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol) on the model pages.205- Compare [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol) on the model pages.

Details

9 9 

10Compaction helps you balance quality, cost, and latency as conversations grow.10Compaction helps you balance quality, cost, and latency as conversations grow.

11For guidance on preserving reasoning when changing conversation history, see11For guidance on preserving reasoning when changing conversation history, see

12[Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/preserved-reasoning).12[Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged).

13 13 

14## Server-side compaction14## Server-side compaction

15 15 


32using `previous_response_id`, pass only the new user message each turn. In both32using `previous_response_id`, pass only the new user message each turn. In both

33cases, the compaction item carries context needed for the next window.33cases, the compaction item carries context needed for the next window.

34 34 

35When the conversation contains earlier `configuration_update` items, the API

36emits one fresh `configuration_update` immediately after the `compaction` item.

37It carries the latest explicitly set value for each updated field:

38`reasoning.effort` and `text.format`. For example, a format-only update preserves

39an earlier effort change. If the conversation has no configuration updates, the

40API omits this item.

41 

42Replay the returned output items in order, including the fresh update when present.

43 

35Latency tip: After appending output items to the previous input items, you can44Latency tip: After appending output items to the previous input items, you can

36drop items that came before the most recent compaction item to keep requests45drop items that came before the most recent compaction item to keep requests

37smaller and reduce long-tail latency. The latest compaction item carries the46smaller and reduce long-tail latency. The latest compaction item carries the

38necessary context to continue the conversation. If you use47necessary context to continue the conversation. If you use

39`previous_response_id` chaining, do not manually prune.48`previous_response_id` chaining, do not manually prune.

40 49 

50### Developer-added tools

51 

52A developer can [add tools mid-conversation](https://developers.openai.com/api/docs/guides/prompt-caching#manage-tools-with-append-only-updates)

53with an `additional_tools` input item. Automatic compaction saves these

54declarations in order inside the encrypted `compaction` item. For example, if

55you added a function named `lookup_ticket`, the model can call it as soon as

56generation continues, or on a later turn when you replay the item or use

57`previous_response_id`. The declarations survive repeated automatic compaction.

58 

59A tool declaration alone adds no extra item to `response.output`. If you also

60changed the reasoning effort or output format, replay the `compaction` item

61and the following `configuration_update` in order. To change a tool's schema

62later, append a new `additional_tools` item for that tool. Supply tools you

63defined only in the request-level `tools` array again on turns that need them.

64 

65- **Tool selection.** You can select restored functions, custom tools, and tools

66 in a namespace. Naming an unavailable function in `tool_choice` returns HTTP 400.

67- **Client tool search.** Restored client tool search can discover a function with

68 `defer_loading: true`. Answer the `tool_search_call` with a `tool_search_output`

69 using the same `call_id`. Client tool search alone cannot satisfy

70 `tool_choice: "required"`.

71- **Hosted MCP servers.** Automatic compaction saves the `server_label`. Supply

72 the current endpoint and credentials under that label on the next request.

73 

41## User journey74## User journey

42 75 

431. Call `/responses` as usual, but include `context_management` with761. Call `/responses` as usual, but include `context_management` with


277```310```

278 311 

279 312 

313## Request compaction with an explicit trigger

314 

315To compact now, append `{"type": "compaction_trigger"}` as the last input item

316in a `POST /v1/responses` request. Leave earlier `configuration_update` items in

317place. Their settings apply while the model produces the summary. The API

318returns a `compaction` item without a fresh `configuration_update`.

319 

320To keep your settings, append one fresh `configuration_update` after the

321summary and before the next user message. Include the latest value of each

322field you changed. With `previous_response_id`, the summary is already in

323stored history, so send the new update followed by the user message.

324 

325The explicit trigger's compaction item doesn't carry earlier `additional_tools`

326declarations. If you resume from that item, supply the tools you need in the

327request's `tools` array or append a new developer `additional_tools` item

328before the user message.

329 

330### Example user flow

331 

332```typescript

333import OpenAI from "openai";

334import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

335 

336const client = new OpenAI();

337const model = "gpt-6-astra";

338const lookupTicket: OpenAI.Responses.FunctionTool = {

339 type: "function",

340 name: "lookup_ticket",

341 description: "Look up a ticket by ID.",

342 parameters: {

343 type: "object",

344 properties: { id: { type: "string" } },

345 required: ["id"],

346 additionalProperties: false,

347 },

348 strict: true,

349};

350const reasoning = { effort: "high" } as const;

351const text = {

352 format: {

353 type: "json_schema",

354 name: "trip_destination",

355 strict: true,

356 schema: {

357 type: "object",

358 properties: { city: { type: "string" } },

359 required: ["city"],

360 additionalProperties: false,

361 },

362 },

363} as const;

364 

365const compacted = await client.responses.create({

366 model,

367 reasoning: { effort: "low" },

368 input: [

369 { role: "user", content: "Plan a trip to Kyoto." },

370 { type: "additional_tools", role: "developer", tools: [lookupTicket] },

371 { type: "configuration_update", reasoning },

372 { type: "configuration_update", text },

373 { type: "compaction_trigger" },

374 ],

375 store: false,

376});

377 

378const response = await client.responses.create({

379 model,

380 reasoning: { effort: "low" },

381 tools: [lookupTicket],

382 input: [

383 ...toResponseInputItems(compacted.output),

384 { type: "configuration_update", reasoning, text },

385 { role: "user", content: "Which city is my trip to?" },

386 ],

387 store: false,

388});

389console.log(response.output_text);

390```

391 

392```python

393from openai import OpenAI

394 

395client = OpenAI()

396model = "gpt-6-astra"

397lookup_ticket = {

398 "type": "function",

399 "name": "lookup_ticket",

400 "description": "Look up a ticket by ID.",

401 "parameters": {

402 "type": "object",

403 "properties": {"id": {"type": "string"}},

404 "required": ["id"],

405 "additionalProperties": False,

406 },

407 "strict": True,

408}

409reasoning = {"effort": "high"}

410text = {

411 "format": {

412 "type": "json_schema",

413 "name": "trip_destination",

414 "strict": True,

415 "schema": {

416 "type": "object",

417 "properties": {"city": {"type": "string"}},

418 "required": ["city"],

419 "additionalProperties": False,

420 },

421 }

422}

423compacted = client.responses.create(

424 model=model,

425 reasoning={"effort": "low"},

426 input=[

427 {"role": "user", "content": "Plan a trip to Kyoto."},

428 {"type": "additional_tools", "role": "developer", "tools": [lookup_ticket]},

429 {"type": "configuration_update", "reasoning": reasoning},

430 {"type": "configuration_update", "text": text},

431 {"type": "compaction_trigger"},

432 ],

433 store=False,

434)

435response = client.responses.create(

436 model=model,

437 reasoning={"effort": "low"},

438 tools=[lookup_ticket],

439 input=[

440 *compacted.output,

441 {"type": "configuration_update", "reasoning": reasoning, "text": text},

442 {"role": "user", "content": "Which city is my trip to?"},

443 ],

444 store=False,

445)

446print(response.output_text)

447```

448 

449```go

450package main

451 

452import (

453 "context"

454 "encoding/json"

455 "fmt"

456 

457 "github.com/openai/openai-go/v3"

458 "github.com/openai/openai-go/v3/responses"

459 "github.com/openai/openai-go/v3/shared"

460)

461 

462func main() {

463 client := openai.NewClient()

464 ctx := context.Background()

465 model := shared.ResponsesModel("gpt-6-astra")

466 lookupTicket := responses.ToolUnionParam{OfFunction: &responses.FunctionToolParam{

467 Name: "lookup_ticket", Description: openai.String("Look up a ticket by ID."),

468 Parameters: map[string]any{

469 "type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}},

470 "required": []string{"id"}, "additionalProperties": false,

471 },

472 Strict: openai.Bool(true),

473 }}

474 reasoning := responses.ResponseConfigurationUpdateItemParamReasoning{Effort: shared.ReasoningEffortHigh}

475 text := responses.ResponseConfigurationUpdateItemParamText{

476 Format: responses.ResponseConfigurationUpdateItemParamTextFormatUnion{OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{

477 Name: "trip_destination", Strict: openai.Bool(true),

478 Schema: map[string]any{

479 "type": "object", "properties": map[string]any{"city": map[string]any{"type": "string"}},

480 "required": []string{"city"}, "additionalProperties": false,

481 },

482 }},

483 }

484 compacted, err := client.Responses.New(ctx, responses.ResponseNewParams{

485 Model: model, Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},

486 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

487 responses.ResponseInputItemParamOfMessage("Plan a trip to Kyoto.", responses.EasyInputMessageRoleUser),

488 responses.ResponseInputItemParamOfAdditionalTools([]responses.ToolUnionParam{lookupTicket}),

489 {OfConfigurationUpdate: &responses.ResponseConfigurationUpdateItemParam{Reasoning: reasoning}},

490 {OfConfigurationUpdate: &responses.ResponseConfigurationUpdateItemParam{Text: text}},

491 {OfCompactionTrigger: &responses.ResponseInputItemCompactionTriggerParam{}},

492 }},

493 Store: openai.Bool(false),

494 })

495 if err != nil {

496 panic(err)

497 }

498 nextInput := outputAsInput(compacted.Output)

499 nextInput = append(nextInput,

500 responses.ResponseInputItemUnionParam{OfConfigurationUpdate: &responses.ResponseConfigurationUpdateItemParam{Reasoning: reasoning, Text: text}},

501 responses.ResponseInputItemParamOfMessage("Which city is my trip to?", responses.EasyInputMessageRoleUser),

502 )

503 response, err := client.Responses.New(ctx, responses.ResponseNewParams{

504 Model: model, Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},

505 Tools: []responses.ToolUnionParam{lookupTicket},

506 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput},

507 Store: openai.Bool(false),

508 })

509 if err != nil {

510 panic(err)

511 }

512 fmt.Println(response.OutputText())

513}

514 

515func outputAsInput(output []responses.ResponseOutputItemUnion) responses.ResponseInputParam {

516 input := make(responses.ResponseInputParam, 0, len(output))

517 for _, item := range output {

518 var converted responses.ResponseInputItemUnion

519 if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {

520 panic(err)

521 }

522 input = append(input, converted.ToParam())

523 }

524 return input

525}

526```

527 

528```java

529import com.openai.core.JsonValue;

530import com.openai.models.Reasoning;

531import com.openai.models.ReasoningEffort;

532import com.openai.models.responses.EasyInputMessage;

533import com.openai.models.responses.FunctionTool;

534import com.openai.models.responses.ResponseConfigurationUpdateItemParam;

535import com.openai.models.responses.ResponseCreateParams;

536import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

537import com.openai.models.responses.ResponseInputItem;

538import java.util.ArrayList;

539import java.util.List;

540import java.util.Map;

541 

542String model = "gpt-6-astra";

543var tool =

544 FunctionTool.builder()

545 .name("lookup_ticket")

546 .description("Look up a ticket by ID.")

547 .parameters(

548 JsonValue.from(

549 Map.of(

550 "type",

551 "object",

552 "properties",

553 Map.of("id", Map.of("type", "string")),

554 "required",

555 List.of("id"),

556 "additionalProperties",

557 false))

558 .convert(FunctionTool.Parameters.class))

559 .strict(true)

560 .build();

561var reasoning =

562 ResponseConfigurationUpdateItemParam.Reasoning.builder()

563 .effort(ReasoningEffort.HIGH)

564 .build();

565var format =

566 ResponseFormatTextJsonSchemaConfig.builder()

567 .name("trip_destination")

568 .strict(true)

569 .schema(

570 JsonValue.from(

571 Map.of(

572 "type",

573 "object",

574 "properties",

575 Map.of("city", Map.of("type", "string")),

576 "required",

577 List.of("city"),

578 "additionalProperties",

579 false))

580 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

581 .build();

582var text = ResponseConfigurationUpdateItemParam.Text.builder().format(format).build();

583var compacted =

584 client

585 .responses()

586 .create(

587 ResponseCreateParams.builder()

588 .model(model)

589 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

590 .inputOfResponse(

591 List.of(

592 ResponseInputItem.ofEasyInputMessage(

593 EasyInputMessage.builder()

594 .role(EasyInputMessage.Role.USER)

595 .content("Plan a trip to Kyoto.")

596 .build()),

597 ResponseInputItem.ofAdditionalTools(

598 ResponseInputItem.AdditionalTools.builder().addTool(tool).build()),

599 ResponseInputItem.ofConfigurationUpdate(

600 ResponseConfigurationUpdateItemParam.builder()

601 .reasoning(reasoning)

602 .build()),

603 ResponseInputItem.ofConfigurationUpdate(

604 ResponseConfigurationUpdateItemParam.builder().text(text).build()),

605 ResponseInputItem.ofCompactionTrigger()))

606 .store(false)

607 .build());

608var input = new ArrayList<ResponseInputItem>();

609for (var item : compacted.output())

610 input.add(JsonValue.from(item).convert(ResponseInputItem.class));

611input.add(

612 ResponseInputItem.ofConfigurationUpdate(

613 ResponseConfigurationUpdateItemParam.builder()

614 .reasoning(reasoning)

615 .text(text)

616 .build()));

617input.add(

618 ResponseInputItem.ofEasyInputMessage(

619 EasyInputMessage.builder()

620 .role(EasyInputMessage.Role.USER)

621 .content("Which city is my trip to?")

622 .build()));

623var response =

624 client

625 .responses()

626 .create(

627 ResponseCreateParams.builder()

628 .model(model)

629 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

630 .addTool(tool)

631 .inputOfResponse(input)

632 .store(false)

633 .build());

634response.output().stream()

635 .flatMap(item -> item.message().stream())

636 .flatMap(message -> message.content().stream())

637 .flatMap(content -> content.outputText().stream())

638 .forEach(value -> System.out.println(value.text()));

639```

640 

641```ruby

642require "openai"

643 

644client = OpenAI::Client.new

645model = "gpt-6-astra"

646lookup_ticket = {

647 type: :function,

648 

649 name: "lookup_ticket",

650 

651 description: "Look up a ticket by ID.",

652 parameters: {

653 type: "object",

654 

655 properties: { id: { type: "string" } },

656 required: ["id"],

657 

658 additionalProperties: false

659 },

660 strict: true

661}

662reasoning = { effort: :high }

663text = {

664 format: {

665 type: :json_schema,

666 

667 name: "trip_destination",

668 

669 strict: true,

670 schema: {

671 type: "object",

672 properties: { city: { type: "string" } },

673 required: ["city"],

674 additionalProperties: false

675 }

676 }

677}

678compacted = client.responses.create(

679 model: model, reasoning: { effort: :low },

680 input: [

681 {

682 role: :user,

683 content: "Plan a trip to Kyoto."

684 },

685 {

686 type: :additional_tools,

687 role: :developer,

688 tools: [lookup_ticket]

689 },

690 {

691 type: :configuration_update,

692 reasoning: reasoning

693 },

694 {

695 type: :configuration_update,

696 text: text

697 },

698 { type: :compaction_trigger }

699 ],

700 store: false

701)

702response = client.responses.create(

703 model: model, reasoning: { effort: :low }, tools: [lookup_ticket],

704 input: [

705 *compacted.output,

706 {

707 type: :configuration_update,

708 reasoning: reasoning,

709 text: text

710 },

711 {

712 role: :user,

713 content: "Which city is my trip to?"

714 }

715 ],

716 store: false

717)

718puts(response.output_text)

719```

720 

721 

280## Standalone compact endpoint722## Standalone compact endpoint

281 723 

282For explicit control, use the724For explicit control, use the


325];767];

326 768 

327const compacted = await client.responses.compact({769const compacted = await client.responses.compact({

328 model: "gpt-6-astra",770 model: "gpt-6.2-astra",

329 input: conversation,771 input: conversation,

330});772});

331 773 


335];777];

336 778 

337const response = await client.responses.create({779const response = await client.responses.create({

338 model: "gpt-6-astra",780 model: "gpt-6.2-astra",

339 input: nextInput,781 input: nextInput,

340 store: false,782 store: false,

341});783});


349 791 

350# 1) Compact the current window792# 1) Compact the current window

351compacted = client.responses.compact(793compacted = client.responses.compact(

352 model="gpt-6-astra",794 model="gpt-6.2-astra",

353 input=long_input_items_array,795 input=long_input_items_array,

354)796)

355 797 


364]806]

365 807 

366next_response = client.responses.create(808next_response = client.responses.create(

367 model="gpt-6-astra",809 model="gpt-6.2-astra",

368 input=next_input,810 input=next_input,

369 store=False, # Keep the flow ZDR-friendly811 store=False, # Keep the flow ZDR-friendly

370)812)


390 responses.ResponseInputItemParamOfMessage("Plan a trip to Kyoto.", responses.EasyInputMessageRoleUser),832 responses.ResponseInputItemParamOfMessage("Plan a trip to Kyoto.", responses.EasyInputMessageRoleUser),

391 }833 }

392 compacted, err := client.Responses.Compact(context.Background(), responses.ResponseCompactParams{834 compacted, err := client.Responses.Compact(context.Background(), responses.ResponseCompactParams{

393 Model: "gpt-6-astra",835 Model: "gpt-6.2-astra",

394 Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: longInputItems},836 Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: longInputItems},

395 })837 })

396 if err != nil {838 if err != nil {


404 responses.ResponseInputItemParamOfMessage(scanner.Text(), responses.EasyInputMessageRoleUser),846 responses.ResponseInputItemParamOfMessage(scanner.Text(), responses.EasyInputMessageRoleUser),

405 )847 )

406 nextResponse, err := client.Responses.New(context.Background(), responses.ResponseNewParams{848 nextResponse, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

407 Model: "gpt-6-astra",849 Model: "gpt-6.2-astra",

408 Store: openai.Bool(false),850 Store: openai.Bool(false),

409 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput},851 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput},

410 })852 })


442 .responses()884 .responses()

443 .compact(885 .compact(

444 ResponseCompactParams.builder()886 ResponseCompactParams.builder()

445 .model("gpt-6-astra")887 .model("gpt-6.2-astra")

446 .input("Plan a trip to Kyoto.")888 .input("Plan a trip to Kyoto.")

447 .build());889 .build());

448var input = new ArrayList<ResponseInputItem>();890var input = new ArrayList<ResponseInputItem>();


470 .responses()912 .responses()

471 .create(913 .create(

472 ResponseCreateParams.builder()914 ResponseCreateParams.builder()

473 .model("gpt-6-astra")915 .model("gpt-6.2-astra")

474 .inputOfResponse(input)916 .inputOfResponse(input)

475 .store(false)917 .store(false)

476 .build())918 .build())


493 }935 }

494]936]

495compaction = client.responses.compact(937compaction = client.responses.compact(

496 model: "gpt-6-astra",938 model: "gpt-6.2-astra",

497 input: long_input939 input: long_input

498)940)

499next_input = [941next_input = [


505 }947 }

506]948]

507response = client.responses.create(949response = client.responses.create(

508 model: "gpt-6-astra",950 model: "gpt-6.2-astra",

509 input: next_input,951 input: next_input,

510 store: false952 store: false

511)953)

512puts(response.output_text)954puts(response.output_text)

513```955```

956 

957 

958### Continue with configuration updates and tools

959 

960`POST /v1/responses/compact` rejects histories containing

961`configuration_update` items, including updates inherited through

962`previous_response_id`. If your history contains updates:

963 

9641. Start from your full history of input and output items. Save the latest

965 explicit `reasoning.effort` and `text.format` separately. Send the remaining

966 items to the compact endpoint in their original order, omitting only the

967 configuration updates.

9682. Keep the entire returned window. Append one fresh `configuration_update`

969 with the fields you saved, then append the next user message. Keep the

970 original request-level settings on the next `/v1/responses` call.

9713. If you previously added tools with `additional_tools`, supply the definitions

972 the next turn needs in `tools`, or append a new developer declaration before

973 the user message. The standalone summary doesn't restore these tools.

974 

975In this example, the conversation started with low effort and plain text. One

976update raised effort to high and a later update supplied a JSON schema.

977`compactAndContinue` restores both in a single item. Pass the tools needed for

978the next turn in `nextTools`.

979 

980```typescript

981import OpenAI from "openai";

982import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

983 

984const client = new OpenAI();

985 

986async function compactAndContinue(

987 model: string,

988 history: OpenAI.Responses.ResponseInput,

989 nextMessage: string,

990 nextTools: OpenAI.Responses.Tool[]

991) {

992 const input: OpenAI.Responses.ResponseInput = [];

993 const latest: OpenAI.Responses.ResponseConfigurationUpdateItemParam = {

994 type: "configuration_update",

995 };

996 for (const item of history) {

997 if (item.type === "configuration_update") {

998 if (item.reasoning?.effort != null) latest.reasoning = item.reasoning;

999 if (item.text?.format) latest.text = item.text;

1000 } else {

1001 input.push(item);

1002 }

1003 }

1004 

1005 const compacted = await client.responses.compact({ model, input });

1006 const nextInput = toResponseInputItems(compacted.output);

1007 if (latest.reasoning || latest.text) nextInput.push(latest);

1008 nextInput.push({ role: "user", content: nextMessage });

1009 

1010 return client.responses.create({

1011 model,

1012 reasoning: { effort: "low" },

1013 tools: nextTools,

1014 input: nextInput,

1015 store: false,

1016 });

1017}

1018```

1019 

1020```python

1021from openai import OpenAI

1022 

1023client = OpenAI()

1024 

1025 

1026def compact_and_continue(model, history, next_message, next_tools):

1027 compact_input = []

1028 latest = {"type": "configuration_update"}

1029 for item in history:

1030 data = item if isinstance(item, dict) else item.model_dump(exclude_unset=True)

1031 if data.get("type") == "configuration_update":

1032 if (data.get("reasoning") or {}).get("effort") is not None:

1033 latest["reasoning"] = data["reasoning"]

1034 if (data.get("text") or {}).get("format") is not None:

1035 latest["text"] = data["text"]

1036 else:

1037 compact_input.append(item)

1038 

1039 compacted = client.responses.compact(model=model, input=compact_input)

1040 next_input = list(compacted.output)

1041 if len(latest) > 1:

1042 next_input.append(latest)

1043 next_input.append({"role": "user", "content": next_message})

1044 return client.responses.create(

1045 model=model,

1046 reasoning={"effort": "low"},

1047 tools=next_tools,

1048 input=next_input,

1049 store=False,

1050 )

1051```

1052 

1053```go

1054func compactAndContinue(

1055 ctx context.Context,

1056 client *openai.Client,

1057 model string,

1058 history responses.ResponseInputParam,

1059 nextMessage string,

1060 nextTools []responses.ToolUnionParam,

1061) (*responses.Response, error) {

1062 input := responses.ResponseInputParam{}

1063 latest := responses.ResponseConfigurationUpdateItemParam{}

1064 for _, item := range history {

1065 if _, overridden := item.Overrides(); overridden {

1066 raw, err := json.Marshal(item)

1067 if err != nil {

1068 return nil, err

1069 }

1070 var normalized responses.ResponseInputItemUnionParam

1071 if err := json.Unmarshal(raw, &normalized); err != nil {

1072 return nil, err

1073 }

1074 if normalized.OfConfigurationUpdate != nil {

1075 item = normalized

1076 }

1077 }

1078 if update := item.OfConfigurationUpdate; update != nil {

1079 if update.Reasoning.Effort != "" {

1080 latest.Reasoning = update.Reasoning

1081 }

1082 if update.Text.Format.OfText != nil || update.Text.Format.OfJSONSchema != nil {

1083 latest.Text = update.Text

1084 }

1085 } else {

1086 input = append(input, item)

1087 }

1088 }

1089 

1090 compacted, err := client.Responses.Compact(ctx, responses.ResponseCompactParams{

1091 Model: responses.ResponseCompactParamsModel(model),

1092 Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: input},

1093 })

1094 if err != nil {

1095 return nil, err

1096 }

1097 nextInput := outputAsInput(compacted.Output)

1098 if latest.Reasoning.Effort != "" || latest.Text.Format.OfText != nil || latest.Text.Format.OfJSONSchema != nil {

1099 nextInput = append(nextInput, responses.ResponseInputItemUnionParam{OfConfigurationUpdate: &latest})

1100 }

1101 nextInput = append(nextInput, responses.ResponseInputItemParamOfMessage(nextMessage, responses.EasyInputMessageRoleUser))

1102 

1103 return client.Responses.New(ctx, responses.ResponseNewParams{

1104 Model: shared.ResponsesModel(model),

1105 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},

1106 Tools: nextTools,

1107 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput},

1108 Store: openai.Bool(false),

1109 })

1110}

1111 

1112func outputAsInput(output []responses.ResponseOutputItemUnion) responses.ResponseInputParam {

1113 input := make(responses.ResponseInputParam, 0, len(output))

1114 for _, item := range output {

1115 var converted responses.ResponseInputItemUnion

1116 if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {

1117 panic(err)

1118 }

1119 input = append(input, converted.ToParam())

1120 }

1121 return input

1122}

1123```

1124 

1125```java

1126import com.openai.client.OpenAIClient;

1127import com.openai.core.JsonValue;

1128import com.openai.models.Reasoning;

1129import com.openai.models.ReasoningEffort;

1130import com.openai.models.responses.EasyInputMessage;

1131import com.openai.models.responses.FunctionTool;

1132import com.openai.models.responses.Response;

1133import com.openai.models.responses.ResponseCompactParams;

1134import com.openai.models.responses.ResponseConfigurationUpdateItemParam;

1135import com.openai.models.responses.ResponseCreateParams;

1136import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

1137import com.openai.models.responses.ResponseInputItem;

1138import com.openai.models.responses.Tool;

1139import java.util.ArrayList;

1140import java.util.List;

1141import java.util.Map;

1142 

1143static Response compactAndContinue(

1144 OpenAIClient client,

1145 String model,

1146 List<ResponseInputItem> history,

1147 String nextMessage,

1148 List<Tool> nextTools) {

1149 var input = new ArrayList<ResponseInputItem>();

1150 var latest = ResponseConfigurationUpdateItemParam.builder();

1151 boolean hasUpdate = false;

1152 for (var item : history) {

1153 if (item.configurationUpdate().isPresent()) {

1154 var update = item.configurationUpdate().get();

1155 if (update.reasoning().isPresent() && update.reasoning().get().effort().isPresent()) {

1156 latest.reasoning(update.reasoning().get());

1157 hasUpdate = true;

1158 }

1159 if (update.text().isPresent()) {

1160 latest.text(update.text().get());

1161 hasUpdate = true;

1162 }

1163 } else {

1164 input.add(item);

1165 }

1166 }

1167 var compacted =

1168 client

1169 .responses()

1170 .compact(

1171 ResponseCompactParams.builder()

1172 .model(model)

1173 .inputOfResponseInputItems(input)

1174 .build());

1175 var nextInput = new ArrayList<ResponseInputItem>();

1176 for (var item : compacted.output()) {

1177 nextInput.add(JsonValue.from(item).convert(ResponseInputItem.class));

1178 }

1179 if (hasUpdate) nextInput.add(ResponseInputItem.ofConfigurationUpdate(latest.build()));

1180 nextInput.add(

1181 ResponseInputItem.ofEasyInputMessage(

1182 EasyInputMessage.builder()

1183 .role(EasyInputMessage.Role.USER)

1184 .content(nextMessage)

1185 .build()));

1186 return client

1187 .responses()

1188 .create(

1189 ResponseCreateParams.builder()

1190 .model(model)

1191 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

1192 .tools(nextTools)

1193 .inputOfResponse(nextInput)

1194 .store(false)

1195 .build());

1196}

1197```

1198 

1199```ruby

1200require "openai"

1201 

1202client = OpenAI::Client.new

1203 

1204def compact_and_continue(client, model, history, next_message, next_tools)

1205 input = []

1206 latest = { type: :configuration_update }

1207 history.each do |item|

1208 if item[:type].to_s == "configuration_update"

1209 latest[:reasoning] = item[:reasoning] unless item[:reasoning]&.[](:effort).nil?

1210 latest[:text] = item[:text] unless item[:text]&.[](:format).nil?

1211 else

1212 input << item

1213 end

1214 end

1215 

1216 compacted = client.responses.compact(model: model, input: input)

1217 next_input = compacted.output.dup

1218 next_input << latest if latest.size > 1

1219 next_input << {

1220 role: :user,

1221 content: next_message

1222 }

1223 client.responses.create(

1224 model: model, reasoning: { effort: :low }, tools: next_tools, input: next_input, store: false

1225 )

1226end

1227```

Details

206 206 

207Likewise, the completions API can be used to simulate a chat between a user and an assistant by formatting the input [accordingly](https://platform.openai.com/playground/p/default-chat?model=gpt-3.5-turbo-instruct).207Likewise, the completions API can be used to simulate a chat between a user and an assistant by formatting the input [accordingly](https://platform.openai.com/playground/p/default-chat?model=gpt-3.5-turbo-instruct).

208 208 

209The difference between these APIs is the underlying models that are available in each. The Chat Completions API supports current GPT models like [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) and lower-cost options like [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra).209The difference between these APIs is the underlying models that are available in each. The Chat Completions API supports current GPT models like [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and lower-cost options like [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra).

Details

25const openai = new OpenAI();25const openai = new OpenAI();

26 26 

27const response = await openai.responses.create({27const response = await openai.responses.create({

28 model: "gpt-6-astra",28 model: "gpt-6.2-astra",

29 input: [29 input: [

30 { role: "user", content: "knock knock." },30 { role: "user", content: "knock knock." },

31 { role: "assistant", content: "Who's there?" },31 { role: "assistant", content: "Who's there?" },


42client = OpenAI()42client = OpenAI()

43 43 

44response = client.responses.create(44response = client.responses.create(

45 model="gpt-6-astra",45 model="gpt-6.2-astra",

46 input=[46 input=[

47 {"role": "user", "content": "knock knock."},47 {"role": "user", "content": "knock knock."},

48 {"role": "assistant", "content": "Who's there?"},48 {"role": "assistant", "content": "Who's there?"},


68 client := openai.NewClient()68 client := openai.NewClient()

69 69 

70 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{70 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

71 Model: "gpt-6-astra",71 Model: "gpt-6.2-astra",

72 Input: responses.ResponseNewParamsInputUnion{72 Input: responses.ResponseNewParamsInputUnion{

73 OfInputItemList: responses.ResponseInputParam{73 OfInputItemList: responses.ResponseInputParam{

74 responses.ResponseInputItemParamOfMessage("Knock knock.", responses.EasyInputMessageRoleUser),74 responses.ResponseInputItemParamOfMessage("Knock knock.", responses.EasyInputMessageRoleUser),


95 95 

96ResponseCreateParams params =96ResponseCreateParams params =

97 ResponseCreateParams.builder()97 ResponseCreateParams.builder()

98 .model("gpt-6-astra")98 .model("gpt-6.2-astra")

99 .inputOfResponse(99 .inputOfResponse(

100 List.of(100 List.of(

101 ResponseInputItem.ofEasyInputMessage(101 ResponseInputItem.ofEasyInputMessage(


130ResponsesClient client = new(key);130ResponsesClient client = new(key);

131 131 

132ResponseResult response = await client.CreateResponseAsync(132ResponseResult response = await client.CreateResponseAsync(

133 "gpt-6-astra",133 "gpt-6.2-astra",

134 [134 [

135 ResponseItem.CreateUserMessageItem("Knock knock."),135 ResponseItem.CreateUserMessageItem("Knock knock."),

136 ResponseItem.CreateAssistantMessageItem("Who's there?"),136 ResponseItem.CreateAssistantMessageItem("Who's there?"),


147client = OpenAI::Client.new147client = OpenAI::Client.new

148 148 

149response = client.responses.create(149response = client.responses.create(

150 model: "gpt-6-astra",150 model: "gpt-6.2-astra",

151 input: [151 input: [

152 {152 {

153 role: :user,153 role: :user,


175 175 

176For stateless reasoning-model requests, preserve every item in the response's `output` array. The Responses API returns encrypted reasoning items by default. Replaying the complete output keeps reasoning items and assistant `phase` values intact. Models that support persisted reasoning can use `reasoning.context: "all_turns"` to render the available reasoning from earlier turns into the next sample. See [preserve reasoning across calls](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls).176For stateless reasoning-model requests, preserve every item in the response's `output` array. The Responses API returns encrypted reasoning items by default. Replaying the complete output keeps reasoning items and assistant `phase` values intact. Models that support persisted reasoning can use `reasoning.context: "all_turns"` to render the available reasoning from earlier turns into the next sample. See [preserve reasoning across calls](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls).

177 177 

178When replaying reasoning items, preserve the history that produced them. See [Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/preserved-reasoning) for details on how edits to conversation history affect reasoning.178When replaying reasoning items, preserve the history that produced them. See [Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) for details on how edits to conversation history affect reasoning.

179 179 

180In the following example, we ask the model to tell a joke, followed by a request for another joke. Appending previous responses to new requests in this way helps ensure conversations feel natural and retain the context of previous interactions.180In the following example, we ask the model to tell a joke, followed by a request for another joke. Appending previous responses to new requests in this way helps ensure conversations feel natural and retain the context of previous interactions.

181 181 


198];198];

199 199 

200const response = await openai.responses.create({200const response = await openai.responses.create({

201 model: "gpt-6-astra",201 model: "gpt-6.2-astra",

202 input: history,202 input: history,

203 store: false,203 store: false,

204});204});


214});214});

215 215 

216const secondResponse = await openai.responses.create({216const secondResponse = await openai.responses.create({

217 model: "gpt-6-astra",217 model: "gpt-6.2-astra",

218 input: history,218 input: history,

219 store: false,219 store: false,

220});220});


230history = [{"role": "user", "content": "tell me a joke"}]230history = [{"role": "user", "content": "tell me a joke"}]

231 231 

232response = client.responses.create(232response = client.responses.create(

233 model="gpt-6-astra",233 model="gpt-6.2-astra",

234 input=history,234 input=history,

235 store=False,235 store=False,

236)236)


243history.append({"role": "user", "content": "tell me another"})243history.append({"role": "user", "content": "tell me another"})

244 244 

245second_response = client.responses.create(245second_response = client.responses.create(

246 model="gpt-6-astra",246 model="gpt-6.2-astra",

247 input=history,247 input=history,

248 store=False,248 store=False,

249)249)


269 responses.ResponseInputItemParamOfMessage("tell me a joke", responses.EasyInputMessageRoleUser),269 responses.ResponseInputItemParamOfMessage("tell me a joke", responses.EasyInputMessageRoleUser),

270 }270 }

271 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{271 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

272 Model: "gpt-6-astra",272 Model: "gpt-6.2-astra",

273 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},273 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},

274 Store: openai.Bool(false),274 Store: openai.Bool(false),

275 })275 })


281 history = append(history, outputAsInput(first.Output)...)281 history = append(history, outputAsInput(first.Output)...)

282 history = append(history, responses.ResponseInputItemParamOfMessage("tell me another", responses.EasyInputMessageRoleUser))282 history = append(history, responses.ResponseInputItemParamOfMessage("tell me another", responses.EasyInputMessageRoleUser))

283 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{283 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

284 Model: "gpt-6-astra",284 Model: "gpt-6.2-astra",

285 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},285 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},

286 Store: openai.Bool(false),286 Store: openai.Bool(false),

287 })287 })


326 .responses()326 .responses()

327 .create(327 .create(

328 ResponseCreateParams.builder()328 ResponseCreateParams.builder()

329 .model("gpt-6-astra")329 .model("gpt-6.2-astra")

330 .inputOfResponse(history)330 .inputOfResponse(history)

331 .store(false)331 .store(false)

332 .build());332 .build());


349 .responses()349 .responses()

350 .create(350 .create(

351 ResponseCreateParams.builder()351 ResponseCreateParams.builder()

352 .model("gpt-6-astra")352 .model("gpt-6.2-astra")

353 .inputOfResponse(history)353 .inputOfResponse(history)

354 .store(false)354 .store(false)

355 .build())355 .build())


373 ResponseItem.CreateUserMessageItem("Tell me a joke."),373 ResponseItem.CreateUserMessageItem("Tell me a joke."),

374];374];

375 375 

376CreateResponseOptions options = new("gpt-6-astra", history)376CreateResponseOptions options = new("gpt-6.2-astra", history)

377{377{

378 StoredOutputEnabled = false,378 StoredOutputEnabled = false,

379 IncludedProperties =379 IncludedProperties =


387history.AddRange(first.OutputItems);387history.AddRange(first.OutputItems);

388history.Add(ResponseItem.CreateUserMessageItem("Tell me another."));388history.Add(ResponseItem.CreateUserMessageItem("Tell me another."));

389 389 

390options = new("gpt-6-astra", history)390options = new("gpt-6.2-astra", history)

391{391{

392 StoredOutputEnabled = false,392 StoredOutputEnabled = false,

393 IncludedProperties =393 IncludedProperties =


411]411]

412 412 

413first = client.responses.create(413first = client.responses.create(

414 model: "gpt-6-astra",414 model: "gpt-6.2-astra",

415 input: history,415 input: history,

416 store: false416 store: false

417)417)


424}424}

425 425 

426second = client.responses.create(426second = client.responses.create(

427 model: "gpt-6-astra",427 model: "gpt-6.2-astra",

428 input: history,428 input: history,

429 store: false429 store: false

430)430)


484 484 

485```typescript485```typescript

486const response = await client.responses.create({486const response = await client.responses.create({

487 model: "gpt-6-astra",487 model: "gpt-6.2-astra",

488 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],488 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],

489 conversation: conversation.id,489 conversation: conversation.id,

490});490});


494 494 

495```python495```python

496response = openai.responses.create(496response = openai.responses.create(

497 model="gpt-6-astra",497 model="gpt-6.2-astra",

498 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],498 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],

499 conversation=conversation.id,499 conversation=conversation.id,

500)500)


502 502 

503```go503```go

504response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{504response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

505 Model: "gpt-6-astra",505 Model: "gpt-6.2-astra",

506 Conversation: responses.ResponseNewParamsConversationUnion{506 Conversation: responses.ResponseNewParamsConversationUnion{

507 OfString: openai.String(conversation.ID),507 OfString: openai.String(conversation.ID),

508 },508 },


528 .responses()528 .responses()

529 .create(529 .create(

530 ResponseCreateParams.builder()530 ResponseCreateParams.builder()

531 .model("gpt-6-astra")531 .model("gpt-6.2-astra")

532 .conversation(conversation.id())532 .conversation(conversation.id())

533 .input("What are the five Ds of dodgeball?")533 .input("What are the five Ds of dodgeball?")

534 .build());534 .build());


542 542 

543```ruby543```ruby

544response = client.responses.create(544response = client.responses.create(

545 model: "gpt-6-astra",545 model: "gpt-6.2-astra",

546 conversation: conversation.id,546 conversation: conversation.id,

547 input: "What are the five Ds of dodgeball?"547 input: "What are the five Ds of dodgeball?"

548)548)


563const openai = new OpenAI();563const openai = new OpenAI();

564 564 

565const response = await openai.responses.create({565const response = await openai.responses.create({

566 model: "gpt-6-astra",566 model: "gpt-6.2-astra",

567 input: "tell me a joke",567 input: "tell me a joke",

568 store: true,568 store: true,

569});569});


571console.log(response.output_text);571console.log(response.output_text);

572 572 

573const secondResponse = await openai.responses.create({573const secondResponse = await openai.responses.create({

574 model: "gpt-6-astra",574 model: "gpt-6.2-astra",

575 previous_response_id: response.id,575 previous_response_id: response.id,

576 input: [{ role: "user", content: "explain why this is funny." }],576 input: [{ role: "user", content: "explain why this is funny." }],

577 store: true,577 store: true,


586client = OpenAI()586client = OpenAI()

587 587 

588response = client.responses.create(588response = client.responses.create(

589 model="gpt-6-astra",589 model="gpt-6.2-astra",

590 input="tell me a joke",590 input="tell me a joke",

591)591)

592print(response.output_text)592print(response.output_text)

593 593 

594second_response = client.responses.create(594second_response = client.responses.create(

595 model="gpt-6-astra",595 model="gpt-6.2-astra",

596 previous_response_id=response.id,596 previous_response_id=response.id,

597 input=[{"role": "user", "content": "explain why this is funny."}],597 input=[{"role": "user", "content": "explain why this is funny."}],

598)598)


614 client := openai.NewClient()614 client := openai.NewClient()

615 615 

616 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{616 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

617 Model: "gpt-6-astra",617 Model: "gpt-6.2-astra",

618 Input: responses.ResponseNewParamsInputUnion{618 Input: responses.ResponseNewParamsInputUnion{

619 OfString: openai.String("Tell me a joke."),619 OfString: openai.String("Tell me a joke."),

620 },620 },


625 fmt.Println(first.OutputText())625 fmt.Println(first.OutputText())

626 626 

627 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{627 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

628 Model: "gpt-6-astra",628 Model: "gpt-6.2-astra",

629 PreviousResponseID: openai.String(first.ID),629 PreviousResponseID: openai.String(first.ID),

630 Input: responses.ResponseNewParamsInputUnion{630 Input: responses.ResponseNewParamsInputUnion{

631 OfString: openai.String("Explain why this is funny."),631 OfString: openai.String("Explain why this is funny."),


647 client647 client

648 .responses()648 .responses()

649 .create(649 .create(

650 ResponseCreateParams.builder().model("gpt-6-astra").input("Tell me a joke.").build());650 ResponseCreateParams.builder().model("gpt-6.2-astra").input("Tell me a joke.").build());

651 651 

652first.output().stream()652first.output().stream()

653 .flatMap(item -> item.message().stream())653 .flatMap(item -> item.message().stream())


660 .responses()660 .responses()

661 .create(661 .create(

662 ResponseCreateParams.builder()662 ResponseCreateParams.builder()

663 .model("gpt-6-astra")663 .model("gpt-6.2-astra")

664 .input("Explain why this is funny.")664 .input("Explain why this is funny.")

665 .previousResponseId(first.id())665 .previousResponseId(first.id())

666 .build());666 .build());


679ResponsesClient client = new(key);679ResponsesClient client = new(key);

680 680 

681ResponseResult first = await client.CreateResponseAsync(681ResponseResult first = await client.CreateResponseAsync(

682 "gpt-6-astra",682 "gpt-6.2-astra",

683 "Tell me a joke."683 "Tell me a joke."

684);684);

685Console.WriteLine(first.GetOutputText());685Console.WriteLine(first.GetOutputText());

686 686 

687ResponseResult second = await client.CreateResponseAsync(687ResponseResult second = await client.CreateResponseAsync(

688 "gpt-6-astra",688 "gpt-6.2-astra",

689 "Explain why this is funny.",689 "Explain why this is funny.",

690 previousResponseId: first.Id690 previousResponseId: first.Id

691);691);


698client = OpenAI::Client.new698client = OpenAI::Client.new

699 699 

700first = client.responses.create(700first = client.responses.create(

701 model: "gpt-6-astra",701 model: "gpt-6.2-astra",

702 input: "Tell me a joke."702 input: "Tell me a joke."

703)703)

704puts(first.output_text)704puts(first.output_text)

705 705 

706second = client.responses.create(706second = client.responses.create(

707 model: "gpt-6-astra",707 model: "gpt-6.2-astra",

708 previous_response_id: first.id,708 previous_response_id: first.id,

709 input: "Explain why this is funny."709 input: "Explain why this is funny."

710)710)

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5There are several ways to reduce costs when using OpenAI models. Cost and latency are typically interconnected; reducing tokens and requests generally leads to faster processing. OpenAI's Batch API and flex processing are additional ways to lower costs.5Reducing tokens and requests can lower costs and shorten response times. For workloads that can wait, you can also lower costs with the Batch API, discounted background completion windows, or Flex processing.

6 6 

7## Cost and latency7## Cost and latency

8 8 


20 20 

21[Get started with the Batch API →](https://developers.openai.com/api/docs/guides/batch)21[Get started with the Batch API →](https://developers.openai.com/api/docs/guides/batch)

22 22 

23## Background completion windows

24 

25Choose a discounted completion window for a Responses API workflow that can wait for its initial response. Use the same continuation ID across related requests to make follow-ups eligible for higher scheduling priority. See [how to choose a completion window](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows).

26 

23## Flex processing27## Flex processing

24 28 

25Get significantly lower costs for Chat Completions or Responses requests in exchange for slower response times and occasional resource unavailability. Ieal for non-production or lower-priority tasks such as model evaluations, data enrichment, or asynchronous workloads.29Get significantly lower costs for Chat Completions or Responses requests in exchange for slower response times and occasional resource unavailability. Ideal for non-production or lower-priority tasks such as model evaluations, data enrichment, or asynchronous workloads.

26 30 

27[Get started with flex processing →](https://developers.openai.com/api/docs/guides/flex-processing)31[Get started with flex processing →](https://developers.openai.com/api/docs/guides/flex-processing)

guides/csam-classifier.md +102 −0 created

Details

1# CSAM classifier

2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 

5The OpenAI CSAM Image Classifier helps reviewers prioritize images that may contain child sexual abuse material (CSAM), including AI-generated material.

6 

7The classifier is available to approved organizations at no cost. .

8 

9## How it works

10 

11The classifier takes one image as input and returns signals for two categories: potential CSAM and potential AI-generated CSAM. To use the classifier, set the model to `omni-moderation-csam-latest`.

12 

13For general moderation, use `omni-moderation-latest`. It can flag sexual content in images, but its `sexual/minors` category applies only to text.

14 

15## Classify an image

16 

17Follow your organization's approved input-handling process. Do not submit known CSAM.

18 

19- Set `OPENAI_API_KEY` to an API key for an approved organization.

20- Send a standalone [Create moderation](https://developers.openai.com/api/reference/resources/moderations/methods/create) request (`POST /v1/moderations`).

21- Send exactly one still image of up to 20 MB (20,000,000 bytes) in the `input` array with `type: "image_url"`. Set `image_url.url` to an HTTP or HTTPS image URL or a base64-encoded image data URL. The classifier doesn't support text classification.

22 

23The following example sends an image of soap to the classifier.

24 

25Classify an image

26 

27```bash

28curl https://api.openai.com/v1/moderations \

29 -X POST \

30 -H "Content-Type: application/json" \

31 -H "Authorization: Bearer $OPENAI_API_KEY" \

32 -d '{

33 "model": "omni-moderation-csam-latest",

34 "input": [

35 {

36 "type": "image_url",

37 "image_url": {

38 "url": "https://cdn.openai.com/API/docs/images/soap.png"

39 }

40 }

41 ]

42 }'

43```

44 

45 

46Here’s an example response:

47 

48```json

49{

50 "id": "modr_example",

51 "model": "omni-moderation-csam-latest",

52 "results": [

53 {

54 "flagged": false,

55 "categories": {

56 "likely-csam": false,

57 "likely-csam/gen-ai": false

58 },

59 "category_scores": {

60 "likely-csam": 0.12,

61 "likely-csam/gen-ai": 0.01

62 },

63 "category_applied_input_types": {

64 "likely-csam": ["image"],

65 "likely-csam/gen-ai": ["image"]

66 }

67 }

68 ]

69}

70```

71 

72## Interpret the result

73 

74Read the classification result at `results[0]`. Start with `flagged`, then check the individual category flags.

75 

76| Response field | Description |

77| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

78| `flagged` | Whether the classifier flagged the image. |

79| `categories` | A boolean flag for each category, based on its configured decision threshold. |

80| `category_scores` | A score from 0 to 1 for each category, with no units. Higher scores signal a stronger match within the same category and model snapshot. Do not interpret these scores as calibrated probabilities or assume `0.5` is a universal threshold. |

81| `category_applied_input_types` | The input types evaluated for each category. Each value is `["image"]`. |

82 

83### Understand the categories

84 

85| Category | Signal |

86| -------------------- | --------------------------------------- |

87| `likely-csam` | Signal for potential CSAM. |

88| `likely-csam/gen-ai` | Signal for potential AI-generated CSAM. |

89 

90A category flag doesn't establish that an image is CSAM, and the classifier doesn't automatically report content to authorities. Follow your organization's review, escalation, and reporting processes. See the [CSAM guidance](https://developers.openai.com/api/docs/guides/csam-guidance) for recommendations on handling flagged content.

91 

92## Troubleshoot a request

93 

94If a request fails, check that you selected `omni-moderation-csam-latest`, used an API key for an approved organization, and sent one image within the size limit.

95 

96The classifier doesn't support [inline moderation](https://developers.openai.com/api/docs/guides/moderation#moderate-generated-content) or the [Batch API](https://developers.openai.com/api/docs/guides/batch).

97 

98For rate-limit errors, consult your organization's limits and the [rate-limit guidance](https://developers.openai.com/api/docs/guides/rate-limits).

99 

100## Access

101 

102To request access, submit the .

Details

115 115 

116 116 

117assistant_agent = Agent[AgentContext](117assistant_agent = Agent[AgentContext](

118 model="gpt-6-astra",118 model="gpt-6.2-astra",

119 name="Assistant",119 name="Assistant",

120 instructions="You are a helpful assistant",120 instructions="You are a helpful assistant",

121 tools=[add_to_todo_list],121 tools=[add_to_todo_list],

Details

62 62 

63# No processing constraint.63# No processing constraint.

64response = client.responses.create(64response = client.responses.create(

65 model="gpt-5.6-terra",65 model="gpt-6.1-terra",

66 input="Reply with OK.",66 input="Reply with OK.",

67)67)

68print(response.output_text)68print(response.output_text)


71response = client.with_options(71response = client.with_options(

72 base_url="https://us.api.openai.com/v1",72 base_url="https://us.api.openai.com/v1",

73).responses.create(73).responses.create(

74 model="gpt-5.6-terra",74 model="gpt-6.1-terra",

75 input="Reply with OK.",75 input="Reply with OK.",

76)76)

77print(response.output_text)77print(response.output_text)


80response = client.with_options(80response = client.with_options(

81 base_url="https://eu.api.openai.com/v1",81 base_url="https://eu.api.openai.com/v1",

82).responses.create(82).responses.create(

83 model="gpt-5.6-terra",83 model="gpt-6.1-terra",

84 input="Reply with OK.",84 input="Reply with OK.",

85)85)

86print(response.output_text)86print(response.output_text)


92client = OpenAI::Client.new92client = OpenAI::Client.new

93 93 

94response = client.responses.create(94response = client.responses.create(

95 model: "gpt-5.6-terra",95 model: "gpt-6.1-terra",

96 input: "Reply with OK."96 input: "Reply with OK."

97)97)

98puts(response.output_text)98puts(response.output_text)

99 99 

100response = client.with_options(data_residency: :us).responses.create(100response = client.with_options(data_residency: :us).responses.create(

101 model: "gpt-5.6-terra",101 model: "gpt-6.1-terra",

102 input: "Reply with OK."102 input: "Reply with OK."

103)103)

104puts(response.output_text)104puts(response.output_text)

105 105 

106# EU processing requires a key from an EU-region project.106# EU processing requires a key from an EU-region project.

107response = client.with_options(data_residency: :eu, api_key: ENV.fetch("OPENAI_EU_API_KEY"), organization: nil, project: nil).responses.create(107response = client.with_options(data_residency: :eu, api_key: ENV.fetch("OPENAI_EU_API_KEY"), organization: nil, project: nil).responses.create(

108 model: "gpt-5.6-terra",108 model: "gpt-6.1-terra",

109 input: "Reply with OK."109 input: "Reply with OK."

110)110)

111puts(response.output_text)111puts(response.output_text)


120 120 

121In Australia, India, and Japan, `gpt-6-luna` supports regional processing. These regions support Standard pay-as-you-go only. Use a project in the selected region. The Responses and Chat Completions APIs support text and image inputs and text output. Hosted tools are unavailable for regional processing in these three regions.121In Australia, India, and Japan, `gpt-6-luna` supports regional processing. These regions support Standard pay-as-you-go only. Use a project in the selected region. The Responses and Chat Completions APIs support text and image inputs and text output. Hosted tools are unavailable for regional processing in these three regions.

122 122 

123GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Standard, Fast, and Batch processing. Both models support [Ultrafast](https://developers.openai.com/api/docs/guides/ultrafast-mode) with US data residency only.

124 

123Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol, GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support EU data residency with Standard, Flex, and Batch processing. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only.125Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol, GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support EU data residency with Standard, Flex, and Batch processing. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only.

124 126 

125### Support by region127### Support by region


133| Australia\* | `au.api.openai.com` | Yes | Yes | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |135| Australia\* | `au.api.openai.com` | Yes | Yes | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |

134| Canada\* | `ca.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |136| Canada\* | `ca.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |

135| Japan\* | `jp.api.openai.com` | Yes | Yes | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |137| Japan\* | `jp.api.openai.com` | Yes | Yes | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |

136| India\* | `in.api.openai.com` | Yes | Yes | [Contact sales](https://openai.com/contact-sales/) to access this region | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |138| India\* | `in.api.openai.com` | Yes | Yes | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | `/v1/chat/completions` (`gpt-6-luna`)<br />`/v1/responses` (`gpt-6-luna`) |

137| Singapore\* | `sg.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |139| Singapore\* | `sg.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |

138| South Korea\* | `kr.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |140| South Korea\* | `kr.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |

139| United Kingdom\* | `gb.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |141| United Kingdom\* | `gb.api.openai.com` | Yes | No | — | Text, Audio, Voice, Image | `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech`<br />`/v1/batches`<br />`/v1/chat/completions`<br />`/v1/decisions`<br />`/v1/embeddings`<br />`/v1/files`<br />`/v1/fine_tuning/jobs`<br />`/v1/images/edits`<br />`/v1/images/generations`<br />`/v1/moderations`<br />`/v1/responses`<br />`/v1/responses File Search`<br />`/v1/responses Web Search`<br />`/v1/vector_stores`<br />`Code Interpreter tool`<br />`File Search`<br />`File Uploads`<br />`Remote MCP server tool`<br />`Scale Tier`<br />`Structured Outputs (excluding schema)`<br />`Supported input modalities` | None |


144### API Endpoint, tool and model support146### API Endpoint, tool and model support

145 147 

146| Endpoint or feature | Service | Storage regions | Processing regions | Supported models and snapshots | Regional processing snapshot exceptions | Notes |148| Endpoint or feature | Service | Storage regions | Processing regions | Supported models and snapshots | Regional processing snapshot exceptions | Notes |

147| -------------------------------------------------------------------- | ---------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |149| -------------------------------------------------------------------- | ---------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

148| `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech` | Audio | All listed regions | United States, Europe (EEA + Switzerland) | `tts-1`, `whisper-1`, `gpt-4o-tts`, `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `gpt-transcribe` | None | — |150| `/v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech` | Audio | All listed regions | United States, Europe (EEA + Switzerland) | `tts-1`, `whisper-1`, `gpt-4o-tts`, `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `gpt-transcribe` | None | — |

149| `/v1/batches` | Batches | All listed regions | United States, Europe (EEA + Switzerland) | `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.5-pro-2026-04-23`, `gpt-5.4-pro-2026-03-05`, `gpt-5.2-pro-2025-12-11`, `gpt-5-pro-2025-10-06`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5-2025-08-07`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-pro`, `o1-pro-2025-03-19`, `o3-mini-2025-01-31`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | None | GPT-6.1 Sol, GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support EU data residency with Standard, Flex, and Batch processing. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |151| `/v1/batches` | Batches | All listed regions | United States, Europe (EEA + Switzerland) | `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.5-pro-2026-04-23`, `gpt-5.4-pro-2026-03-05`, `gpt-5.2-pro-2025-12-11`, `gpt-5-pro-2025-10-06`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5-2025-08-07`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-pro`, `o1-pro-2025-03-19`, `o3-mini-2025-01-31`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | None | GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Batch processing. GPT-6.1 Sol, GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support EU data residency with Standard, Flex, and Batch processing. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |

150| `/v1/chat/completions` | Chat Completions | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates, Australia, India, Japan | `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-2025-08-07`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-mini-2025-01-31`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | United Arab Emirates: `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.2-2025-12-11`<br />Australia, India, Japan: `gpt-6-luna` | Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |152| `/v1/chat/completions` | Chat Completions | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates, Australia, India, Japan | `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-2025-08-07`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-mini-2025-01-31`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | United Arab Emirates: `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.2-2025-12-11`<br />Australia, India, Japan: `gpt-6-luna` | GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Standard and Fast processing. Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |

151| `/v1/decisions` | Decisions | All listed regions | United States, Europe (EEA + Switzerland) | `gpt-6-luna` | None | Available in all supported API regions. Regional processing is supported in the United States and Europe (EEA + Switzerland). Prompt caching is subject to the retention limitations below. |153| `/v1/decisions` | Decisions | All listed regions | United States, Europe (EEA + Switzerland) | `gpt-6-luna` | None | Available in all supported API regions. Regional processing is supported in the United States and Europe (EEA + Switzerland). Prompt caching is subject to the retention limitations below. |

152| `/v1/embeddings` | Embeddings | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates | `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002` | United Arab Emirates: `text-embedding-3-large` | — |154| `/v1/embeddings` | Embeddings | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates | `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002` | United Arab Emirates: `text-embedding-3-large` | — |

153| `/v1/evals` | Evals | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | Service-level support | None | — |155| `/v1/evals` | Evals | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | Service-level support | None | — |


161| `/v1/realtime` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime`, `gpt-realtime-1.5`, `gpt-realtime-mini`, `gpt-realtime-2`, `gpt-realtime-2.1`, `gpt-realtime-2.1-mini` | None | — |163| `/v1/realtime` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime`, `gpt-realtime-1.5`, `gpt-realtime-mini`, `gpt-realtime-2`, `gpt-realtime-2.1`, `gpt-realtime-2.1-mini` | None | — |

162| `/v1/realtime/transcription_sessions` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime-whisper`, `gpt-live-transcribe`, `gpt-transcribe` | None | — |164| `/v1/realtime/transcription_sessions` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime-whisper`, `gpt-live-transcribe`, `gpt-transcribe` | None | — |

163| `/v1/realtime/translations` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime-translate` | None | — |165| `/v1/realtime/translations` | Realtime | United States, Europe (EEA + Switzerland) | United States, Europe (EEA + Switzerland) | `gpt-realtime-translate` | None | — |

164| `/v1/responses` | Responses | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates, Australia, India, Japan | `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.5-pro-2026-04-23`, `gpt-5.4-pro-2026-03-05`, `gpt-5.2-pro-2025-12-11`, `gpt-5-pro-2025-10-06`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5-2025-08-07`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-pro`, `o1-pro-2025-03-19`, `o3-mini-2025-01-31`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | United Arab Emirates: `gpt-5.5-pro-2026-04-23`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.2-2025-12-11`<br />Australia, India, Japan: `gpt-6-luna` | Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |166| `/v1/responses` | Responses | All listed regions | United States, Europe (EEA + Switzerland), United Arab Emirates, Australia, India, Japan | `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.5-pro-2026-04-23`, `gpt-5.4-pro-2026-03-05`, `gpt-5.2-pro-2025-12-11`, `gpt-5-pro-2025-10-06`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.4-2026-03-05`, `gpt-5-2025-08-07`, `gpt-5.4-mini-2026-03-17`, `gpt-5.4-nano-2026-03-17`, `gpt-5.2-2025-12-11`, `gpt-5.1-2025-11-13`, `gpt-5-mini-2025-08-07`, `gpt-5-nano-2025-08-07`, `gpt-4.1-2025-04-14`, `gpt-4.1-mini-2025-04-14`, `gpt-4.1-nano-2025-04-14`, `o3-2025-04-16`, `o4-mini-2025-04-16`, `o1-pro`, `o1-pro-2025-03-19`, `o3-mini-2025-01-31`, `o1-2024-12-17`, `gpt-4o-2024-11-20`, `gpt-4o-2024-08-06`, `gpt-4o-mini-2024-07-18`, `gpt-4-turbo-2024-04-09`, `gpt-4-0613`, `gpt-3.5-turbo-0125` | United Arab Emirates: `gpt-5.5-pro-2026-04-23`, `gpt-5.6-luna`, `gpt-5.5-2026-04-23`, `gpt-5.2-2025-12-11`<br />Australia, India, Japan: `gpt-6-luna` | GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Standard and Fast processing. Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. GPT-6.1 Sol and GPT-6.1 Terra support only US and EU data residency. |

165| `/v1/responses File Search` | Responses | All listed regions | United States, Europe (EEA + Switzerland) | Service-level support | None | — |167| `/v1/responses File Search` | Responses | All listed regions | United States, Europe (EEA + Switzerland) | Service-level support | None | — |

166| `/v1/responses Web Search` | Responses | All listed regions | United States, Europe (EEA + Switzerland) | Service-level support | None | — |168| `/v1/responses Web Search` | Responses | All listed regions | United States, Europe (EEA + Switzerland) | Service-level support | None | — |

167| `/v1/vector_stores` | Vector stores | All listed regions | None | Service-level support | None | — |169| `/v1/vector_stores` | Vector stores | All listed regions | None | Service-level support | None | — |

Details

274 -H "Authorization: Bearer $OPENAI_API_KEY" \274 -H "Authorization: Bearer $OPENAI_API_KEY" \

275 -H "Content-Type: application/json" \275 -H "Content-Type: application/json" \

276 -d '{276 -d '{

277 "model": "gpt-6.1-sol",277 "model": "gpt-6.2-sol",

278 "instructions": "The car has handled the cabin controls. Use the tools for the rest of the request, then briefly tell the driver what happened based on the results.",278 "instructions": "The car has handled the cabin controls. Use the tools for the rest of the request, then briefly tell the driver what happened based on the results.",

279 "input": "Driver: My windshield is foggy, so please defog it, navigate to San Francisco, and find me some good restaurants there.\nCabin results: Windshield defogger confirmed on. Temperature unchanged.",279 "input": "Driver: My windshield is foggy, so please defog it, navigate to San Francisco, and find me some good restaurants there.\nCabin results: Windshield defogger confirmed on. Temperature unchanged.",

280 "tools": [280 "tools": [

Details

101].join("\n");101].join("\n");

102 102 

103const response = await openai.responses.create({103const response = await openai.responses.create({

104 model: "gpt-6-astra",104 model: "gpt-6.2-astra",

105 reasoning: { effort: "xhigh", mode: "pro" },105 reasoning: { effort: "xhigh", mode: "pro" },

106 input: prompt,106 input: prompt,

107});107});


124"""124"""

125 125 

126response = client.responses.create(126response = client.responses.create(

127 model="gpt-6-astra",127 model="gpt-6.2-astra",

128 reasoning={"effort": "xhigh", "mode": "pro"},128 reasoning={"effort": "xhigh", "mode": "pro"},

129 input=prompt,129 input=prompt,

130)130)


158 reasoning := shared.ReasoningParam{Effort: shared.ReasoningEffortXhigh}158 reasoning := shared.ReasoningParam{Effort: shared.ReasoningEffortXhigh}

159 reasoning.SetExtraFields(map[string]any{"mode": "pro"})159 reasoning.SetExtraFields(map[string]any{"mode": "pro"})

160 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{160 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

161 Model: "gpt-6-astra",161 Model: "gpt-6.2-astra",

162 Reasoning: reasoning,162 Reasoning: reasoning,

163 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(prompt)},163 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(prompt)},

164 })164 })


179 179 

180ResponseCreateParams params =180ResponseCreateParams params =

181 ResponseCreateParams.builder()181 ResponseCreateParams.builder()

182 .model("gpt-6-astra")182 .model("gpt-6.2-astra")

183 .input(183 .input(

184 "Our CI job started failing after a dependency bump. Error: TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'. Identify the likeliest root cause and the smallest safe fix.")184 "Our CI job started failing after a dependency bump. Error: TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'. Identify the likeliest root cause and the smallest safe fix.")

185 .reasoning(185 .reasoning(


210PROMPT210PROMPT

211 211 

212response = client.responses.create(212response = client.responses.create(

213 model: "gpt-6-astra",213 model: "gpt-6.2-astra",

214 reasoning: {214 reasoning: {

215 effort: :xhigh,215 effort: :xhigh,

216 mode: :pro216 mode: :pro


270].join("\n");270].join("\n");

271 271 

272const response = await openai.responses.create({272const response = await openai.responses.create({

273 model: "gpt-6-astra",273 model: "gpt-6.2-astra",

274 text: { verbosity: "low" },274 text: { verbosity: "low" },

275 input: incident,275 input: incident,

276});276});


284client = OpenAI()284client = OpenAI()

285 285 

286response = client.responses.create(286response = client.responses.create(

287 model="gpt-6-astra",287 model="gpt-6.2-astra",

288 text={"verbosity": "low"},288 text={"verbosity": "low"},

289 input="""289 input="""

290 Summarize this incident for the next on-call engineer.290 Summarize this incident for the next on-call engineer.


320 "- likely trigger: cache stampede after deploy",320 "- likely trigger: cache stampede after deploy",

321 }, "\n")321 }, "\n")

322 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{322 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

323 Model: "gpt-6-astra",323 Model: "gpt-6.2-astra",

324 Text: responses.ResponseTextConfigParam{Verbosity: "low"},324 Text: responses.ResponseTextConfigParam{Verbosity: "low"},

325 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(incident)},325 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(incident)},

326 })326 })


339 339 

340ResponseCreateParams params =340ResponseCreateParams params =

341 ResponseCreateParams.builder()341 ResponseCreateParams.builder()

342 .model("gpt-6-astra")342 .model("gpt-6.2-astra")

343 .input(343 .input(

344 "Summarize this incident for the next on-call engineer: checkout latency spiked from 220 ms to 4.8 s, only us-east-1 was affected, rollback is complete, and the likely trigger was a cache stampede.")344 "Summarize this incident for the next on-call engineer: checkout latency spiked from 220 ms to 4.8 s, only us-east-1 was affected, rollback is complete, and the likely trigger was a cache stampede.")

345 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())345 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())


365INCIDENT365INCIDENT

366 366 

367response = client.responses.create(367response = client.responses.create(

368 model: "gpt-6-astra",368 model: "gpt-6.2-astra",

369 text: { verbosity: :low },369 text: { verbosity: :low },

370 input: incident370 input: incident

371)371)


504};504};

505 505 

506const response = await openai.responses.create({506const response = await openai.responses.create({

507 model: "gpt-6-astra",507 model: "gpt-6.2-astra",

508 input:508 input:

509 "Find the right billing tool and explain why invoice INV-1043 still " +509 "Find the right billing tool and explain why invoice INV-1043 still " +

510 "shows overdue after a payment yesterday.",510 "shows overdue after a payment yesterday.",


566}566}

567 567 

568response = client.responses.create(568response = client.responses.create(

569 model="gpt-6-astra",569 model="gpt-6.2-astra",

570 input=(570 input=(

571 "Find the right billing tool and explain why invoice INV-1043 still "571 "Find the right billing tool and explain why invoice INV-1043 still "

572 "shows overdue after a payment yesterday."572 "shows overdue after a payment yesterday."


606 )606 )

607 toolSearch := responses.ToolUnionParam{OfToolSearch: &responses.ToolSearchToolParam{}}607 toolSearch := responses.ToolUnionParam{OfToolSearch: &responses.ToolSearchToolParam{}}

608 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{608 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

609 Model: "gpt-6-astra",609 Model: "gpt-6.2-astra",

610 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(610 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(

611 "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",611 "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",

612 )},612 )},


650 650 

651ResponseCreateParams params =651ResponseCreateParams params =

652 ResponseCreateParams.builder()652 ResponseCreateParams.builder()

653 .model("gpt-6-astra")653 .model("gpt-6.2-astra")

654 .input(654 .input(

655 "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.")655 "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.")

656 .addTool(656 .addTool(


746)746)

747 747 

748response = client.responses.create(748response = client.responses.create(

749 model: "gpt-6-astra",749 model: "gpt-6.2-astra",

750 input: "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",750 input: "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",

751 tools: [billing, crm, { type: :tool_search }]751 tools: [billing, crm, { type: :tool_search }]

752)752)


887const longWindow = sessionItems;887const longWindow = sessionItems;

888 888 

889const compacted = await openai.responses.compact({889const compacted = await openai.responses.compact({

890 model: "gpt-6-astra",890 model: "gpt-6.2-astra",

891 input: longWindow,891 input: longWindow,

892});892});

893 893 

894const nextResponse = await openai.responses.create({894const nextResponse = await openai.responses.create({

895 model: "gpt-6-astra",895 model: "gpt-6.2-astra",

896 store: false,896 store: false,

897 input: [897 input: [

898 // Preserve replayable compacted items.898 // Preserve replayable compacted items.


920long_window = session_items920long_window = session_items

921 921 

922compacted = client.responses.compact(922compacted = client.responses.compact(

923 model="gpt-6-astra",923 model="gpt-6.2-astra",

924 input=long_window,924 input=long_window,

925)925)

926 926 

927next_response = client.responses.create(927next_response = client.responses.create(

928 model="gpt-6-astra",928 model="gpt-6.2-astra",

929 store=False,929 store=False,

930 input=[930 input=[

931 *compacted.output, # Use compact output as-is.931 *compacted.output, # Use compact output as-is.


961 responses.ResponseInputItemParamOfMessage("Find the cache invalidation bug in this debugging session.", responses.EasyInputMessageRoleUser),961 responses.ResponseInputItemParamOfMessage("Find the cache invalidation bug in this debugging session.", responses.EasyInputMessageRoleUser),

962 }962 }

963 compacted, err := client.Responses.Compact(context.Background(), responses.ResponseCompactParams{963 compacted, err := client.Responses.Compact(context.Background(), responses.ResponseCompactParams{

964 Model: "gpt-6-astra",964 Model: "gpt-6.2-astra",

965 Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: longWindow},965 Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: longWindow},

966 })966 })

967 if err != nil {967 if err != nil {


974 ),974 ),

975 )975 )

976 nextResponse, err := client.Responses.New(context.Background(), responses.ResponseNewParams{976 nextResponse, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

977 Model: "gpt-6-astra",977 Model: "gpt-6.2-astra",

978 Store: openai.Bool(false),978 Store: openai.Bool(false),

979 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},979 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},

980 })980 })


1012 .responses()1012 .responses()

1013 .compact(1013 .compact(

1014 ResponseCompactParams.builder()1014 ResponseCompactParams.builder()

1015 .model("gpt-6-astra")1015 .model("gpt-6.2-astra")

1016 .input("Find the cache invalidation bug in this debugging session.")1016 .input("Find the cache invalidation bug in this debugging session.")

1017 .build());1017 .build());

1018var input = new ArrayList<ResponseInputItem>();1018var input = new ArrayList<ResponseInputItem>();


1041 .responses()1041 .responses()

1042 .create(1042 .create(

1043 ResponseCreateParams.builder()1043 ResponseCreateParams.builder()

1044 .model("gpt-6-astra")1044 .model("gpt-6.2-astra")

1045 .inputOfResponse(input)1045 .inputOfResponse(input)

1046 .store(false)1046 .store(false)

1047 .build())1047 .build())


1065]1065]

1066 1066 

1067compacted = client.responses.compact(1067compacted = client.responses.compact(

1068 model: "gpt-6-astra",1068 model: "gpt-6.2-astra",

1069 input: long_window1069 input: long_window

1070)1070)

1071input = compacted.output.dup1071input = compacted.output.dup


1075}1075}

1076 1076 

1077response = client.responses.create(1077response = client.responses.create(

1078 model: "gpt-6-astra",1078 model: "gpt-6.2-astra",

1079 store: false,1079 store: false,

1080 input: input1080 input: input

1081)1081)


1141].join("\n");1141].join("\n");

1142 1142 

1143const response = await openai.responses.create({1143const response = await openai.responses.create({

1144 model: "gpt-6-astra",1144 model: "gpt-6.2-astra",

1145 prompt_cache_key: "tenant-acme-support-agent",1145 prompt_cache_key: "tenant-acme-support-agent",

1146 instructions,1146 instructions,

1147 input: "Summarize the current escalation for the on-call lead.",1147 input: "Summarize the current escalation for the on-call lead.",


1162"""1162"""

1163 1163 

1164response = client.responses.create(1164response = client.responses.create(

1165 model="gpt-6-astra",1165 model="gpt-6.2-astra",

1166 prompt_cache_key="tenant-acme-support-agent",1166 prompt_cache_key="tenant-acme-support-agent",

1167 instructions=instructions,1167 instructions=instructions,

1168 input="Summarize the current escalation for the on-call lead.",1168 input="Summarize the current escalation for the on-call lead.",


1191 "Use the same tone, safety rules, and tool plan for each ticket.",1191 "Use the same tone, safety rules, and tool plan for each ticket.",

1192 }, "\n")1192 }, "\n")

1193 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1193 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1194 Model: "gpt-6-astra",1194 Model: "gpt-6.2-astra",

1195 PromptCacheKey: openai.String("tenant-acme-support-agent"),1195 PromptCacheKey: openai.String("tenant-acme-support-agent"),

1196 Instructions: openai.String(instructions),1196 Instructions: openai.String(instructions),

1197 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Summarize the current escalation for the on-call lead.")},1197 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Summarize the current escalation for the on-call lead.")},


1210 1210 

1211ResponseCreateParams params =1211ResponseCreateParams params =

1212 ResponseCreateParams.builder()1212 ResponseCreateParams.builder()

1213 .model("gpt-6-astra")1213 .model("gpt-6.2-astra")

1214 .instructions(1214 .instructions(

1215 "You are the support agent for Acme.\n"1215 "You are the support agent for Acme.\n"

1216 + "Follow the Acme support policy and escalation rubric.\n"1216 + "Follow the Acme support policy and escalation rubric.\n"


1235 1235 

1236CreateResponseOptions options = new()1236CreateResponseOptions options = new()

1237{1237{

1238 Model = "gpt-6-astra",1238 Model = "gpt-6.2-astra",

1239 PromptCacheKey = "tenant-acme-support-agent",1239 PromptCacheKey = "tenant-acme-support-agent",

1240 Instructions = "Follow the Acme support policy and escalation rubric.",1240 Instructions = "Follow the Acme support policy and escalation rubric.",

1241};1241};


1258INSTRUCTIONS1258INSTRUCTIONS

1259 1259 

1260response = client.responses.create(1260response = client.responses.create(

1261 model: "gpt-6-astra",1261 model: "gpt-6.2-astra",

1262 prompt_cache_key: "tenant-acme-support-agent",1262 prompt_cache_key: "tenant-acme-support-agent",

1263 instructions: instructions,1263 instructions: instructions,

1264 input: "Summarize the current escalation for the on-call lead."1264 input: "Summarize the current escalation for the on-call lead."


1309];1309];

1310 1310 

1311const first = await openai.responses.create({1311const first = await openai.responses.create({

1312 model: "gpt-6-astra",1312 model: "gpt-6.2-astra",

1313 store: false,1313 store: false,

1314 reasoning: { effort: "medium", context: "current_turn" },1314 reasoning: { effort: "medium", context: "current_turn" },

1315 input: history,1315 input: history,


1322});1322});

1323 1323 

1324const second = await openai.responses.create({1324const second = await openai.responses.create({

1325 model: "gpt-6-astra",1325 model: "gpt-6.2-astra",

1326 store: false,1326 store: false,

1327 reasoning: { effort: "medium", context: "all_turns" },1327 reasoning: { effort: "medium", context: "all_turns" },

1328 input: history,1328 input: history,


1344]1344]

1345 1345 

1346first = client.responses.create(1346first = client.responses.create(

1347 model="gpt-6-astra",1347 model="gpt-6.2-astra",

1348 store=False,1348 store=False,

1349 reasoning={"effort": "medium", "context": "current_turn"},1349 reasoning={"effort": "medium", "context": "current_turn"},

1350 input=history,1350 input=history,


1359)1359)

1360 1360 

1361second = client.responses.create(1361second = client.responses.create(

1362 model="gpt-6-astra",1362 model="gpt-6.2-astra",

1363 store=False,1363 store=False,

1364 reasoning={"effort": "medium", "context": "all_turns"},1364 reasoning={"effort": "medium", "context": "all_turns"},

1365 input=history,1365 input=history,


1387 responses.ResponseInputItemParamOfMessage("Investigate why invoice INV-1043 has mismatched tax totals.", responses.EasyInputMessageRoleUser),1387 responses.ResponseInputItemParamOfMessage("Investigate why invoice INV-1043 has mismatched tax totals.", responses.EasyInputMessageRoleUser),

1388 }1388 }

1389 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1389 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1390 Model: "gpt-6-astra",1390 Model: "gpt-6.2-astra",

1391 Store: openai.Bool(false),1391 Store: openai.Bool(false),

1392 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextCurrentTurn},1392 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextCurrentTurn},

1393 Include: []responses.ResponseIncludable{responses.ResponseIncludableReasoningEncryptedContent},1393 Include: []responses.ResponseIncludable{responses.ResponseIncludableReasoningEncryptedContent},


1402 responses.EasyInputMessageRoleUser,1402 responses.EasyInputMessageRoleUser,

1403 ))1403 ))

1404 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1404 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1405 Model: "gpt-6-astra",1405 Model: "gpt-6.2-astra",

1406 Store: openai.Bool(false),1406 Store: openai.Bool(false),

1407 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextAllTurns},1407 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextAllTurns},

1408 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},1408 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},


1450 .responses()1450 .responses()

1451 .create(1451 .create(

1452 ResponseCreateParams.builder()1452 ResponseCreateParams.builder()

1453 .model("gpt-6-astra")1453 .model("gpt-6.2-astra")

1454 .inputOfResponse(history)1454 .inputOfResponse(history)

1455 .store(false)1455 .store(false)

1456 .reasoning(1456 .reasoning(


1474 .responses()1474 .responses()

1475 .create(1475 .create(

1476 ResponseCreateParams.builder()1476 ResponseCreateParams.builder()

1477 .model("gpt-6-astra")1477 .model("gpt-6.2-astra")

1478 .inputOfResponse(history)1478 .inputOfResponse(history)

1479 .store(false)1479 .store(false)

1480 .reasoning(1480 .reasoning(


1503]1503]

1504 1504 

1505first = client.responses.create(1505first = client.responses.create(

1506 model: "gpt-6-astra",1506 model: "gpt-6.2-astra",

1507 store: false,1507 store: false,

1508 reasoning: {1508 reasoning: {

1509 effort: :medium,1509 effort: :medium,


1519}1519}

1520 1520 

1521second = client.responses.create(1521second = client.responses.create(

1522 model: "gpt-6-astra",1522 model: "gpt-6.2-astra",

1523 store: false,1523 store: false,

1524 reasoning: {1524 reasoning: {

1525 effort: :medium,1525 effort: :medium,


1599const logBundleFileId = "file_123";1599const logBundleFileId = "file_123";

1600 1600 

1601let job = await openai.responses.create({1601let job = await openai.responses.create({

1602 model: "gpt-6-astra",1602 model: "gpt-6.2-astra",

1603 background: true,1603 background: true,

1604 store: false,1604 store: false,

1605 input: "Analyze this large log bundle and cluster the primary failure modes.",1605 input: "Analyze this large log bundle and cluster the primary failure modes.",


1631log_bundle_file_id = "file_123"1631log_bundle_file_id = "file_123"

1632 1632 

1633job = client.responses.create(1633job = client.responses.create(

1634 model="gpt-6-astra",1634 model="gpt-6.2-astra",

1635 background=True,1635 background=True,

1636 store=False,1636 store=False,

1637 input="Analyze this large log bundle and cluster the primary failure modes.",1637 input="Analyze this large log bundle and cluster the primary failure modes.",


1671 FileIDs: []string{"file_abc123"},1671 FileIDs: []string{"file_abc123"},

1672 })1672 })

1673 job, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1673 job, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1674 Model: "gpt-6-astra",1674 Model: "gpt-6.2-astra",

1675 Background: openai.Bool(true),1675 Background: openai.Bool(true),

1676 Store: openai.Bool(false),1676 Store: openai.Bool(false),

1677 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Analyze this large log bundle and cluster the primary failure modes.")},1677 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Analyze this large log bundle and cluster the primary failure modes.")},


1702 1702 

1703ResponseCreateParams params =1703ResponseCreateParams params =

1704 ResponseCreateParams.builder()1704 ResponseCreateParams.builder()

1705 .model("gpt-6-astra")1705 .model("gpt-6.2-astra")

1706 .input("Analyze this large log bundle and cluster the primary failure modes.")1706 .input("Analyze this large log bundle and cluster the primary failure modes.")

1707 .background(true)1707 .background(true)

1708 .store(false)1708 .store(false)


1736client = OpenAI::Client.new1736client = OpenAI::Client.new

1737 1737 

1738job = client.responses.create(1738job = client.responses.create(

1739 model: "gpt-6-astra",1739 model: "gpt-6.2-astra",

1740 background: true,1740 background: true,

1741 store: false,1741 store: false,

1742 input: "Analyze this large log bundle and cluster the primary failure modes.",1742 input: "Analyze this large log bundle and cluster the primary failure modes.",


1842try {1842try {

1843 ws.send({1843 ws.send({

1844 type: "response.create",1844 type: "response.create",

1845 model: "gpt-6-astra",1845 model: "gpt-6.2-astra",

1846 store: false,1846 store: false,

1847 input: [1847 input: [

1848 {1848 {


1919with client.responses.connect() as connection:1919with client.responses.connect() as connection:

1920 # Use the same typed parameters as client.responses.create(...).1920 # Use the same typed parameters as client.responses.create(...).

1921 connection.response.create(1921 connection.response.create(

1922 model="gpt-6-astra",1922 model="gpt-6.2-astra",

1923 store=False,1923 store=False,

1924 input=[1924 input=[

1925 {1925 {


1984}1984}

1985defer conn.Close()1985defer conn.Close()

1986if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{1986if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{

1987 Model: "gpt-6-astra",1987 Model: "gpt-6.2-astra",

1988 Store: openai.Bool(false),1988 Store: openai.Bool(false),

1989 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{1989 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{

1990 OfString: openai.String("Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause."),1990 OfString: openai.String("Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause."),


2038 conn.send(2038 conn.send(

2039 ResponsesClientEvent.ofResponseCreate(2039 ResponsesClientEvent.ofResponseCreate(

2040 ResponsesClientEvent.ResponseCreate.builder()2040 ResponsesClientEvent.ResponseCreate.builder()

2041 .model("gpt-6-astra")2041 .model("gpt-6.2-astra")

2042 .store(false)2042 .store(false)

2043 .input(2043 .input(

2044 "Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause.")2044 "Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause.")


2098 task.with_timeout(120) do2098 task.with_timeout(120) do

2099 client.responses.connect(request_options: { timeout: 10 }) do |connection|2099 client.responses.connect(request_options: { timeout: 10 }) do |connection|

2100 connection.response.create(2100 connection.response.create(

2101 stream_id: "main", model: "gpt-6-astra", store: false,2101 stream_id: "main", model: "gpt-6.2-astra", store: false,

2102 input: [2102 input: [

2103 {2103 {

2104 role: "user",2104 role: "user",

Details

19 19 

20## How to get embeddings20## How to get embeddings

21 21 

22To get an embedding, send your text string to the [embeddings API endpoint](https://developers.openai.com/api/reference/resources/embeddings) along with the embedding model name (e.g., `text-embedding-3-small`):22To get an embedding, send your text string to the [embeddings API endpoint](https://developers.openai.com/api/reference/resources/embeddings) along with the embedding model name (for example, `text-embedding-3-small`):

23 23 

24Example: Getting embeddings24Example: Getting embeddings

25 25 


154```154```

155 155 

156 156 

157By default, the length of the embedding vector is `1536` for `text-embedding-3-small` or `3072` for `text-embedding-3-large`. To reduce the embedding's dimensions without losing its concept-representing properties, pass in the [dimensions parameter](https://developers.openai.com/api/reference/resources/embeddings/methods/create#embeddings-create-dimensions). Find more detail on embedding dimensions in the [embedding use case section](#use-cases).157By default, the length of the embedding vector is `1536` for `text-embedding-3-small` or `3072` for `text-embedding-3-large`. To reduce the dimensions of an embedding without losing its ability to represent concepts, pass in the [dimensions parameter](https://developers.openai.com/api/reference/resources/embeddings/methods/create#embeddings-create-dimensions). Find more detail on embedding dimensions in the [embedding use case section](#use-cases).

158 158 

159## Embedding models159## Embedding models

160 160 


180 180 

181 181 

182| Product Id | User Id | Score | Summary | Text |182| Product Id | User Id | Score | Summary | Text |

183| ---------- | -------------- | ----- | --------------------- | ------------------------------------------------- |183| ---------- | -------------- | ----- | --------------------- | ----------------------------------------------- |

184| B001E4KFG0 | A3SGXH7AUHU8GW | 5 | Good Quality Dog Food | I have bought several of the Vitality canned... |184| B001E4KFG0 | A3SGXH7AUHU8GW | 5 | Good Quality Dog Food | I have bought several of the Vitality canned… |

185| B00813GRG4 | A1D87F6ZCVE5NK | 1 | Not as Advertised | Product arrived labeled as Jumbo Salted Peanut... |185| B00813GRG4 | A1D87F6ZCVE5NK | 1 | Not as Advertised | Product arrived labeled as Jumbo Salted Peanut… |

186 186 

187 187 

188 188 

189 189 

190Below, we combine the review summary and review text into a single combined text. The model encodes this combined text and output a single vector embedding.190Below, we combine the review summary and review text into a single combined text. The model encodes this combined text and outputs a single vector embedding.

191 191 

192 192 

193Get_embeddings_from_dataset.ipynb193Get_embeddings_from_dataset.ipynb

194 For Ruby, save the review CSV as `data/fine_food_reviews_1k.csv` or set `REVIEWS_CSV` to its path. Keep the `Summary`, `Text`, `Score`, `UserId`, and `ProductId` columns; the saved embeddings retain them for the analysis steps.

195 

196 

197 

198 

199Create review embeddings

200 

194```typescript201```typescript

195import { mkdir, writeFile } from "node:fs/promises";202import { mkdir, writeFile } from "node:fs/promises";

196import OpenAI from "openai";203import OpenAI from "openai";


378require "openai"385require "openai"

379 386 

380client = OpenAI::Client.new387client = OpenAI::Client.new

381reviews = ["A rich cup of coffee.", "A bright herbal tea."]388table = CSV.read(ENV.fetch("REVIEWS_CSV", "data/fine_food_reviews_1k.csv"))

382 389headers = table.shift or raise ArgumentError, "Review CSV is empty"

383response = client.embeddings.create(390reviews = table.map { |fields| headers.zip(fields).to_h }

384 model: "text-embedding-3-small",391combined = reviews.map { |row| "#{row.fetch("Summary")} #{row.fetch("Text")}".tr("\n", " ") }

385 input: reviews.map { |review| review.tr("\n", " ") }392response = client.embeddings.create(model: "text-embedding-3-small", input: combined)

386)

387 393 

388FileUtils.mkdir_p("output")394FileUtils.mkdir_p("output")

389CSV.open("output/embedded_1k_reviews.csv", "w") do |csv|395CSV.open("output/embedded_1k_reviews.csv", "w") do |csv|

390 csv << ["combined", "ada_embedding"]396 csv << headers + ["combined", "ada_embedding"]

391 response.data.each do |embedding|397 response.data.each do |embedding|

392 csv << [reviews.fetch(embedding.index), JSON.generate(embedding.embedding)]398 row = reviews.fetch(embedding.index)

399 

400 csv << headers.map { |header| row.fetch(header) } + [combined.fetch(embedding.index), JSON.generate(embedding.embedding)]

393 end401 end

394end402end

395```403```

396 404 

397 405 

406 

407 

408 

409For Ruby, use Ruby 3.3 and install the [sample project dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile). Append the loading and analysis snippets to the same Ruby file; run the split before either forest example. The metrics below come from the linked Python notebooks and depend on the dataset and implementation.

410 

411 

412 

413 

398To load the data from a saved file, you can run the following:414To load the data from a saved file, you can run the following:

399 415 

416Load saved embeddings

417 

400```python418```python

401from ast import literal_eval419from ast import literal_eval

402import pandas as pd420import pandas as pd


405df["ada_embedding"] = df.ada_embedding.apply(literal_eval).apply(np.array)423df["ada_embedding"] = df.ada_embedding.apply(literal_eval).apply(np.array)

406```424```

407 425 

426```ruby

427# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

428require "csv"

429require "json"

430 

431rows = CSV.read("output/embedded_1k_reviews.csv", headers: true).map do |row|

432 row.to_h.merge("ada_embedding" => JSON.parse(row.fetch("ada_embedding")))

433end

434# standard:enable Lint/UselessAssignment

435```

436 

408 437 

409 438 

410 439 


414 443 

415Using larger embeddings, for example storing them in a vector store for retrieval, generally costs more and consumes more compute, memory and storage than using smaller embeddings.444Using larger embeddings, for example storing them in a vector store for retrieval, generally costs more and consumes more compute, memory and storage than using smaller embeddings.

416 445 

417Both of our new embedding models were trained [with a technique](https://arxiv.org/abs/2205.13147) that allows developers to trade-off performance and cost of using embeddings. Specifically, developers can shorten embeddings (i.e. remove some numbers from the end of the sequence) without the embedding losing its concept-representing properties by passing in the [`dimensions` API parameter](https://developers.openai.com/api/reference/resources/embeddings/methods/create#embeddings-create-dimensions). For example, on the MTEB benchmark, a `text-embedding-3-large` embedding can be shortened to a size of 256 while still outperforming an unshortened `text-embedding-ada-002` embedding with a size of 1536. You can read more about how changing the dimensions impacts performance in our [embeddings v3 launch blog post](https://openai.com/blog/new-embedding-models-and-api-updates#:~:text=Native%20support%20for%20shortening%20embeddings).446Both of our new embedding models were trained [with a technique](https://arxiv.org/abs/2205.13147) that allows developers to trade-off performance and cost of using embeddings. Specifically, developers can shorten embeddings (that is, remove some numbers from the end of the sequence) without the embedding losing its concept-representing properties by passing in the [`dimensions` API parameter](https://developers.openai.com/api/reference/resources/embeddings/methods/create#embeddings-create-dimensions). For example, on the MTEB benchmark, a `text-embedding-3-large` embedding can be shortened to a size of 256 while still outperforming a full-length `text-embedding-ada-002` embedding with a size of 1536. You can read more about how changing the dimensions impacts performance in our [embeddings v3 launch blog post](https://openai.com/blog/new-embedding-models-and-api-updates#:~:text=Native%20support%20for%20shortening%20embeddings).

418 447 

419In general, using the `dimensions` parameter when creating the embedding is the suggested approach. In certain cases, you may need to change the embedding dimension after you generate it. When you change the dimension manually, you need to be sure to normalize the dimensions of the embedding as is shown below.448In general, using the `dimensions` parameter when creating the embedding is the suggested approach. In certain cases, you may need to change the embedding dimension after you generate it. When you change the dimension manually, you need to be sure to normalize the dimensions of the embedding as is shown below.

420 449 

450Reduce embedding dimensions

451 

421```typescript452```typescript

422import OpenAI from "openai";453import OpenAI from "openai";

423 454 


531```562```

532 563 

533 564 

534Dynamically changing the dimensions enables very flexible usage. For example, when using a vector data store that only supports embeddings up to 1024 dimensions long, developers can now still use our best embedding model `text-embedding-3-large` and specify a value of 1024 for the `dimensions` API parameter, which will shorten the embedding down from 3072 dimensions, trading off some accuracy in exchange for the smaller vector size.565Dynamically changing the dimensions enables flexible usage. For example, when using a vector data store that only supports embeddings up to 1024 dimensions long, developers can now still use our best embedding model `text-embedding-3-large` and specify a value of 1024 for the `dimensions` API parameter, which will shorten the embedding down from 3072 dimensions, trading off some accuracy in exchange for the smaller vector size.

535 566 

536 567 

537 568 


551 582 

552 583 

553 584 

554There are many common cases where the model is not trained on data which contains key facts and information you want to make accessible when generating responses to a user query. One way of solving this, as shown below, is to put additional information into the context window of the model. This is effective in many use cases but leads to higher token costs. In this notebook, we explore the tradeoff between this approach and embeddings bases search.585In many common cases, the model is not trained on data which contains key facts and information you want to make accessible when generating responses to a user query. One way of solving this, as shown below, is to put additional information into the context window of the model. This is effective in many use cases but leads to higher token costs. In this notebook, we explore the tradeoff between this approach and embeddings bases search.

586 

587Answer a question with retrieved context

555 588 

556```typescript589```typescript

557import OpenAI from "openai";590import OpenAI from "openai";


731 764 

732To retrieve the most relevant documents we use the cosine similarity between the embedding vectors of the query and each document, and return the highest scored documents.765To retrieve the most relevant documents we use the cosine similarity between the embedding vectors of the query and each document, and return the highest scored documents.

733 766 

767Search reviews by similarity

768 

734```typescript769```typescript

735import OpenAI from "openai";770import OpenAI from "openai";

736 771 


993 1028 

994To perform a code search, we embed the query in natural language using the same model. Then we calculate cosine similarity between the resulting query embedding and each of the function embeddings. The highest cosine similarity results are most relevant.1029To perform a code search, we embed the query in natural language using the same model. Then we calculate cosine similarity between the resulting query embedding and each of the function embeddings. The highest cosine similarity results are most relevant.

995 1030 

1031Search function source code

1032 

996```typescript1033```typescript

997import OpenAI from "openai";1034import OpenAI from "openai";

998 1035 


1254 1291 

1255Because shorter distances between embedding vectors represent greater similarity, embeddings can be useful for recommendation.1292Because shorter distances between embedding vectors represent greater similarity, embeddings can be useful for recommendation.

1256 1293 

1257Below, we illustrate a basic recommender. It takes in a list of strings and one 'source' string, computes their embeddings, and then returns a ranking of the strings, ranked from most similar to least similar. As a concrete example, the linked notebook below applies a version of this function to the [AG news dataset](http://groups.di.unipi.it/~gulli/AG_corpus_of_news_articles.html) (sampled down to 2,000 news article descriptions) to return the top 5 most similar articles to any given source article.1294Below, we illustrate a basic recommendation function. It takes in a list of strings and one 'source' string, computes their embeddings, and then returns a ranking of the strings, ranked from most similar to least similar. As a concrete example, the linked notebook below applies a version of this function to the [AG news dataset](http://groups.di.unipi.it/~gulli/AG_corpus_of_news_articles.html) (sampled down to 2,000 news article descriptions) to return the top 5 most similar articles to any given source article.

1295 

1296Recommend similar strings

1258 1297 

1259```typescript1298```typescript

1260import OpenAI from "openai";1299import OpenAI from "openai";


1539 1578 

1540The visualization seems to have produced roughly 3 clusters, one of which has mostly negative reviews.1579The visualization seems to have produced roughly 3 clusters, one of which has mostly negative reviews.

1541 1580 

1581Visualize embeddings with t-SNE

1582 

1542```python1583```python

1543from ast import literal_eval1584from ast import literal_eval

1544import numpy as np1585import numpy as np


1566plt.title("Amazon ratings visualized in language using t-SNE")1607plt.title("Amazon ratings visualized in language using t-SNE")

1567```1608```

1568 1609 

1610```ruby

1611require "csv"

1612require "json"

1613require "rumale/manifold"

1614require "chunky_png"

1615 

1616rows = CSV.read("output/embedded_1k_reviews.csv", headers: true).map do |row|

1617 row.to_h.merge("ada_embedding" => JSON.parse(row.fetch("ada_embedding")))

1618end

1619matrix = Numo::DFloat.asarray(rows.map { |row| row.fetch("ada_embedding") })

1620tsne = Rumale::Manifold::TSNE.new(n_components: 2, perplexity: 15, random_seed: 42, init: "random")

1621points = tsne.fit_transform(matrix).to_a

1622color_indices = rows.map { |row| Integer(row.fetch("Score")) - 1 }

1623palette = ["#ff0000", "#ff8c00", "#ffd700", "#40e0d0", "#006400"]

1624 

1625plot = ChunkyPNG::Image.new(600, 400, ChunkyPNG::Color::WHITE)

1626x_min, x_max = points.map(&:first).minmax

1627y_min, y_max = points.map(&:last).minmax

1628plotted = points.map(&:dup)

1629plotted.each_with_index do |(x, y), index|

1630 pixel_x = 20 + ((x - x_min) / [x_max - x_min, Float::EPSILON].max * 560).round

1631 pixel_y = 380 - ((y - y_min) / [y_max - y_min, Float::EPSILON].max * 360).round

1632 color = ChunkyPNG::Color.from_hex(palette.fetch(color_indices.fetch(index)))

1633 plot.circle(pixel_x, pixel_y, 3, color, color)

1634end

1635plot.save("local-plot.png")

1636```

1637 

1569 1638 

1570 1639 

1571 1640 


1587 1656 

1588An embedding can be used as a general free-text feature encoder within a machine learning model. Incorporating embeddings will improve the performance of any machine learning model, if some of the relevant inputs are free text. An embedding can also be used as a categorical feature encoder within a ML model. This adds most value if the names of categorical variables are meaningful and numerous, such as job titles. Similarity embeddings generally perform better than search embeddings for this task.1657An embedding can be used as a general free-text feature encoder within a machine learning model. Incorporating embeddings will improve the performance of any machine learning model, if some of the relevant inputs are free text. An embedding can also be used as a categorical feature encoder within a ML model. This adds most value if the names of categorical variables are meaningful and numerous, such as job titles. Similarity embeddings generally perform better than search embeddings for this task.

1589 1658 

1590We observed that generally the embedding representation is very rich and information dense. For example, reducing the dimensionality of the inputs using SVD or PCA, even by 10%, generally results in worse downstream performance on specific tasks.1659We observed that generally the embedding representation is rich and information dense. For example, reducing the dimensionality of the inputs using SVD or PCA, even by 10%, generally results in worse downstream performance on specific tasks.

1591 1660 

1592This code splits the data into a training set and a testing set, which will be used by the following two use cases, namely regression and classification.1661This code splits the data into a training set and a testing set, which will be used by the following two use cases, namely regression and classification.

1593 1662 

1663Split the dataset for training and testing

1664 

1594```python1665```python

1595from sklearn.model_selection import train_test_split1666from sklearn.model_selection import train_test_split

1596 1667 


1599)1670)

1600```1671```

1601 1672 

1673```ruby

1674vectors = rows.map { |row| row.fetch("ada_embedding") }

1675scores = rows.map { |row| Integer(row.fetch("Score")) }

1676 

1677indices = (0...vectors.length).to_a.shuffle(random: Random.new(42))

1678test_size = (vectors.length * 0.2).ceil

1679test_indices = indices.take(test_size)

1680train_indices = indices.drop(test_size)

1681x_train = train_indices.map { |index| vectors.fetch(index) }

1682holdout_vectors = test_indices.map { |index| vectors.fetch(index) }

1683y_train = train_indices.map { |index| scores.fetch(index) }

1684holdout_scores = test_indices.map { |index| scores.fetch(index) }

1685```

1686 

1602 1687 

1603#### Regression using the embedding features1688#### Regression using the embedding features

1604 1689 

1605Embeddings present an elegant way of predicting a numerical value. In this example we predict the reviewer’s star rating, based on the text of their review. Because the semantic information contained within embeddings is high, the prediction is decent even with very few reviews.1690Embeddings present an elegant way of predicting a numerical value. In this example we predict the reviewer’s star rating, based on the text of their review. Because the semantic information contained within embeddings is high, the prediction is decent even with few reviews.

1606 1691 

1607We assume the score is a continuous variable between 1 and 5, and allow the algorithm to predict any floating point value. The ML algorithm minimizes the distance of the predicted value to the true score, and achieves a mean absolute error of 0.39, which means that on average the prediction is off by less than half a star.1692We assume the score is a continuous variable between 1 and 5, and allow the algorithm to predict any floating point value. The ML algorithm minimizes the distance of the predicted value to the true score, and achieves a mean absolute error of 0.39, which means that on average the prediction is off by less than half a star.

1608 1693 

1694Predict review scores

1695 

1609```python1696```python

1610from sklearn.ensemble import RandomForestRegressor1697from sklearn.ensemble import RandomForestRegressor

1611 1698 


1614preds = rfr.predict(X_test)1701preds = rfr.predict(X_test)

1615```1702```

1616 1703 

1704```ruby

1705require "rumale/ensemble"

1706 

1707x_train = Numo::DFloat.asarray(x_train)

1708y_train = Numo::DFloat.asarray(y_train)

1709holdout_vectors = Numo::DFloat.asarray(holdout_vectors)

1710 

1711forest = Rumale::Ensemble::RandomForestRegressor.new(n_estimators: 100, random_seed: 42)

1712forest.fit(x_train, y_train)

1713predictions = forest.predict(holdout_vectors)

1714```

1715 

1617 1716 

1618 1717 

1619 1718 


1637 1736 

1638After the training, the model learns to predict 1 and 5-star reviews much better than the more nuanced reviews (2-4 stars), likely due to more extreme sentiment expression.1737After the training, the model learns to predict 1 and 5-star reviews much better than the more nuanced reviews (2-4 stars), likely due to more extreme sentiment expression.

1639 1738 

1739Classify review scores

1740 

1640```python1741```python

1641from sklearn.ensemble import RandomForestClassifier1742from sklearn.ensemble import RandomForestClassifier

1642from sklearn.metrics import classification_report, accuracy_score1743from sklearn.metrics import classification_report, accuracy_score


1646preds = clf.predict(X_test)1747preds = clf.predict(X_test)

1647```1748```

1648 1749 

1750```ruby

1751require "rumale/ensemble"

1752 

1753x_train = Numo::DFloat.asarray(x_train)

1754y_train = Numo::Int32.asarray(y_train)

1755holdout_vectors = Numo::DFloat.asarray(holdout_vectors)

1756 

1757forest = Rumale::Ensemble::RandomForestClassifier.new(n_estimators: 100, random_seed: 42)

1758forest.fit(x_train, y_train)

1759predictions = forest.predict(holdout_vectors)

1760```

1761 

1649 1762 

1650 1763 

1651 1764 


1667 1780 

1668We can use embeddings for zero shot classification without any labeled training data. For each class, we embed the class name or a short description of the class. To classify some new text in a zero-shot manner, we compare its embedding to all class embeddings and predict the class with the highest similarity.1781We can use embeddings for zero shot classification without any labeled training data. For each class, we embed the class name or a short description of the class. To classify some new text in a zero-shot manner, we compare its embedding to all class embeddings and predict the class with the highest similarity.

1669 1782 

1783Classify text without training examples

1784 

1670```typescript1785```typescript

1671import OpenAI from "openai";1786import OpenAI from "openai";

1672 1787 


1876 1991 

1877We evaluate the usefulness of these embeddings on a separate test set, where we plot similarity of the user and product embedding as a function of the rating. Interestingly, based on this approach, even before the user receives the product we can predict better than random whether they would like the product.1992We evaluate the usefulness of these embeddings on a separate test set, where we plot similarity of the user and product embedding as a function of the rating. Interestingly, based on this approach, even before the user receives the product we can predict better than random whether they would like the product.

1878 1993 

1994Average user and product embeddings

1995 

1879```python1996```python

1880user_embeddings = df.groupby("UserId").ada_embedding.apply(np.mean)1997user_embeddings = df.groupby("UserId").ada_embedding.apply(np.mean)

1881prod_embeddings = df.groupby("ProductId").ada_embedding.apply(np.mean)1998prod_embeddings = df.groupby("ProductId").ada_embedding.apply(np.mean)

1882```1999```

1883 2000 

2001```ruby

2002vectors = rows.map { |row| row.fetch("ada_embedding") }

2003user_ids = rows.map { |row| row.fetch("UserId") }

2004product_ids = rows.map { |row| row.fetch("ProductId") }

2005 

2006def average_embeddings(ids, vectors)

2007 ids.zip(vectors).group_by(&:first).transform_values do |rows|

2008 rows.map(&:last).transpose.map { |dimension| dimension.sum / dimension.length.to_f }

2009 end

2010end

2011 

2012user_embeddings = average_embeddings(user_ids, vectors)

2013product_embeddings = average_embeddings(product_ids, vectors)

2014```

2015 

1884 2016 

1885 2017 

1886 2018 


1904 2036 

1905In this example, we discover four distinct clusters: one focusing on dog food, one on negative reviews, and two on positive reviews.2037In this example, we discover four distinct clusters: one focusing on dog food, one on negative reviews, and two on positive reviews.

1906 2038 

2039Cluster embeddings

2040 

1907```python2041```python

1908import numpy as np2042import numpy as np

1909from sklearn.cluster import KMeans2043from sklearn.cluster import KMeans


1916df["Cluster"] = kmeans.labels_2050df["Cluster"] = kmeans.labels_

1917```2051```

1918 2052 

2053```ruby

2054require "rumale/clustering"

2055 

2056vectors = rows.map { |row| row.fetch("ada_embedding") }

2057 

2058matrix = Numo::DFloat.asarray(vectors)

2059kmeans = Rumale::Clustering::KMeans.new(n_clusters: 4, init: "k-means++", random_seed: 42)

2060labels = kmeans.fit_predict(matrix)

2061```

2062 

1919 2063 

1920 2064 

1921 2065 


1929 2073 

1930Example code:2074Example code:

1931 2075 

2076Count tokens before embedding

2077 

1932```python2078```python

1933import tiktoken2079import tiktoken

1934 2080 


1943num_tokens_from_string("tiktoken is great!", "cl100k_base")2089num_tokens_from_string("tiktoken is great!", "cl100k_base")

1944```2090```

1945 2091 

2092```ruby

2093require "tiktoken_ruby"

2094 

2095def num_tokens_from_string(string, encoding_name)

2096 Tiktoken.get_encoding(encoding_name).encode(string).length

2097end

2098 

2099puts(num_tokens_from_string("tiktoken is great!", "cl100k_base"))

2100```

2101 

1946 2102 

1947For third-generation embedding models like `text-embedding-3-small`, use the `cl100k_base` encoding.2103For third-generation embedding models like `text-embedding-3-small`, use the `cl100k_base` encoding.

1948 2104 

Details

380 380 

381try {381try {

382 const response = await client.responses.create({382 const response = await client.responses.create({

383 model: "gpt-6-astra",383 model: "gpt-6.2-astra",

384 input: "Hello world",384 input: "Hello world",

385 });385 });

386 console.log(response.output_text);386 console.log(response.output_text);


404client = OpenAI()404client = OpenAI()

405 405 

406try:406try:

407 response = client.responses.create(model="gpt-6-astra", input="Hello world")407 response = client.responses.create(model="gpt-6.2-astra", input="Hello world")

408except openai.APIConnectionError as e:408except openai.APIConnectionError as e:

409 print(f"Failed to connect to OpenAI API: {e}")409 print(f"Failed to connect to OpenAI API: {e}")

410except openai.RateLimitError as e:410except openai.RateLimitError as e:


430func main() {430func main() {

431 client := openai.NewClient()431 client := openai.NewClient()

432 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{432 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

433 Model: "gpt-6-astra",433 Model: "gpt-6.2-astra",

434 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello world")},434 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello world")},

435 })435 })

436 if err != nil {436 if err != nil {


457 client457 client

458 .responses()458 .responses()

459 .create(459 .create(

460 ResponseCreateParams.builder().model("gpt-6-astra").input("Say hello.").build());460 ResponseCreateParams.builder().model("gpt-6.2-astra").input("Say hello.").build());

461 461 

462 response.output().stream()462 response.output().stream()

463 .flatMap(item -> item.message().stream())463 .flatMap(item -> item.message().stream())


474 474 

475client = OpenAI::Client.new475client = OpenAI::Client.new

476begin476begin

477 response = client.responses.create(model: "gpt-6-astra", input: "Say hello.")477 response = client.responses.create(model: "gpt-6.2-astra", input: "Say hello.")

478 puts(response.output_text)478 puts(response.output_text)

479rescue OpenAI::Errors::APIError => error479rescue OpenAI::Errors::APIError => error

480 warn(error.message)480 warn(error.message)

guides/evals.md +12 −12

Details

47const ticket = "My monitor won't turn on - help!";47const ticket = "My monitor won't turn on - help!";

48 48 

49const response = await client.responses.create({49const response = await client.responses.create({

50 model: "gpt-6-astra",50 model: "gpt-6.2-astra",

51 input: [51 input: [

52 { role: "developer", content: instructions },52 { role: "developer", content: instructions },

53 { role: "user", content: ticket },53 { role: "user", content: ticket },


71ticket = "My monitor won't turn on - help!"71ticket = "My monitor won't turn on - help!"

72 72 

73response = client.responses.create(73response = client.responses.create(

74 model="gpt-6-astra",74 model="gpt-6.2-astra",

75 input=[75 input=[

76 {"role": "developer", "content": instructions},76 {"role": "developer", "content": instructions},

77 {"role": "user", "content": ticket},77 {"role": "user", "content": ticket},


96 client := openai.NewClient()96 client := openai.NewClient()

97 instructions := "You are an expert in categorizing IT support tickets. Given the support ticket below, categorize the request into one of \"Hardware\", \"Software\", or \"Other\". Respond with only one of those words."97 instructions := "You are an expert in categorizing IT support tickets. Given the support ticket below, categorize the request into one of \"Hardware\", \"Software\", or \"Other\". Respond with only one of those words."

98 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{98 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

99 Model: "gpt-6-astra",99 Model: "gpt-6.2-astra",

100 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{100 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

101 responses.ResponseInputItemParamOfMessage(instructions, responses.EasyInputMessageRoleDeveloper),101 responses.ResponseInputItemParamOfMessage(instructions, responses.EasyInputMessageRoleDeveloper),

102 responses.ResponseInputItemParamOfMessage("My monitor won't turn on - help!", responses.EasyInputMessageRoleUser),102 responses.ResponseInputItemParamOfMessage("My monitor won't turn on - help!", responses.EasyInputMessageRoleUser),


119 119 

120ResponseCreateParams params =120ResponseCreateParams params =

121 ResponseCreateParams.builder()121 ResponseCreateParams.builder()

122 .model("gpt-6-astra")122 .model("gpt-6.2-astra")

123 .inputOfResponse(123 .inputOfResponse(

124 List.of(124 List.of(

125 ResponseInputItem.ofEasyInputMessage(125 ResponseInputItem.ofEasyInputMessage(


150ResponsesClient client = new(key);150ResponsesClient client = new(key);

151 151 

152ResponseResult response = await client.CreateResponseAsync(152ResponseResult response = await client.CreateResponseAsync(

153 "gpt-6-astra",153 "gpt-6.2-astra",

154 [154 [

155 ResponseItem.CreateDeveloperMessageItem(155 ResponseItem.CreateDeveloperMessageItem(

156 "Categorize the IT support ticket as Hardware, Software, or Other. Respond with only one of those words."156 "Categorize the IT support ticket as Hardware, Software, or Other. Respond with only one of those words."


172 Respond with only one of those words.172 Respond with only one of those words.

173INSTRUCTIONS173INSTRUCTIONS

174response = client.responses.create(174response = client.responses.create(

175 model: "gpt-6-astra",175 model: "gpt-6.2-astra",

176 input: [176 input: [

177 {177 {

178 role: :developer,178 role: :developer,


192 -H "Authorization: Bearer $OPENAI_API_KEY" \192 -H "Authorization: Bearer $OPENAI_API_KEY" \

193 -H "Content-Type: application/json" \193 -H "Content-Type: application/json" \

194 -d '{194 -d '{

195 "model": "gpt-6-astra",195 "model": "gpt-6.2-astra",

196 "input": [196 "input": [

197 {197 {

198 "role": "developer",198 "role": "developer",


621 name: "Categorization text run",621 name: "Categorization text run",

622 data_source: {622 data_source: {

623 type: "responses",623 type: "responses",

624 model: "gpt-6-astra",624 model: "gpt-6.2-astra",

625 sampling_params: { reasoning_effort: "low" },625 sampling_params: { reasoning_effort: "low" },

626 input_messages: {626 input_messages: {

627 type: "template",627 type: "template",


651 name="Categorization text run",651 name="Categorization text run",

652 data_source={652 data_source={

653 "type": "responses",653 "type": "responses",

654 "model": "gpt-6-astra",654 "model": "gpt-6.2-astra",

655 "input_messages": {655 "input_messages": {

656 "type": "template",656 "type": "template",

657 "template": [657 "template": [


688 .type(688 .type(

689 RunCreateParams.DataSource.CreateEvalResponsesRunDataSource.Type689 RunCreateParams.DataSource.CreateEvalResponsesRunDataSource.Type

690 .RESPONSES)690 .RESPONSES)

691 .model("gpt-6-astra")691 .model("gpt-6.2-astra")

692 .samplingParams(692 .samplingParams(

693 RunCreateParams.DataSource.CreateEvalResponsesRunDataSource693 RunCreateParams.DataSource.CreateEvalResponsesRunDataSource

694 .SamplingParams.builder()694 .SamplingParams.builder()


749 }749 }

750 ]750 ]

751 },751 },

752 model: "gpt-6-astra",752 model: "gpt-6.2-astra",

753 sampling_params: { reasoning_effort: :low }753 sampling_params: { reasoning_effort: :low }

754 }754 }

755)755)


764 "name": "Categorization text run",764 "name": "Categorization text run",

765 "data_source": {765 "data_source": {

766 "type": "responses",766 "type": "responses",

767 "model": "gpt-6-astra",767 "model": "gpt-6.2-astra",

768 "input_messages": {768 "input_messages": {

769 "type": "template",769 "type": "template",

770 "template": [770 "template": [

Details

109 Set up continuous evaluation (CE) to run evals on every change, monitor your app to identify new cases of nondeterminism, and grow the eval set over time.109 Set up continuous evaluation (CE) to run evals on every change, monitor your app to identify new cases of nondeterminism, and grow the eval set over time.

110 110 

111When creating an eval dataset, 111When creating an eval dataset,

112 [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) 112 [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra)

113 is useful for collecting eval examples and edge cases. Consider using it to113 is useful for collecting eval examples and edge cases. Consider using it to

114 help you generate a diverse set of test data across various scenarios. Ensure114 help you generate a diverse set of test data across various scenarios. Ensure

115 your test data includes typical cases, edge cases, and adversarial cases. Use115 your test data includes typical cases, edge cases, and adversarial cases. Use


421 421 

422### LLM-as-a-judge and model graders422### LLM-as-a-judge and model graders

423 423 

424Using models to judge output is cheaper to run and more scalable than human evaluation. Start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) when you need a strong LLM judge, then validate agreement against your human labels before optimizing for cost or latency.424Using models to judge output is cheaper to run and more scalable than human evaluation. Start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) when you need a strong LLM judge, then validate agreement against your human labels before optimizing for cost or latency.

425 425 

426- **Examples**:426- **Examples**:

427 - Pairwise comparison: Present the judge model with two responses and ask it to determine which one is better based on specific criteria427 - Pairwise comparison: Present the judge model with two responses and ask it to determine which one is better based on specific criteria


430- **Challenges**: Position bias (response order), verbosity bias (preferring longer responses)430- **Challenges**: Position bias (response order), verbosity bias (preferring longer responses)

431- **Recommendations**:431- **Recommendations**:

432 - Use pairwise comparison or pass/fail for more reliability432 - Use pairwise comparison or pass/fail for more reliability

433 - Use the most capable model to grade if you can. Start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra), then validate whether a specialized reasoning model performs better for your rubric or reference-answer set433 - Use the most capable model to grade if you can. Start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra), then validate whether a specialized reasoning model performs better for your rubric or reference-answer set

434 - Control for response lengths as LLMs bias towards longer responses in general434 - Control for response lengths as LLMs bias towards longer responses in general

435 - Add reasoning and chain-of-thought as reasoning before scoring improves eval performance435 - Add reasoning and chain-of-thought as reasoning before scoring improves eval performance

436 - Once the LLM judge reaches a point where it's faster, cheaper, and consistently agrees with human annotations, scale up436 - Once the LLM judge reaches a point where it's faster, cheaper, and consistently agrees with human annotations, scale up

Details

4 4 

5Fast mode delivers up to 2.5× faster speeds and more consistent latency with pay-as-you-go pricing. Use it for user-facing applications with regular traffic where latency matters.5Fast mode delivers up to 2.5× faster speeds and more consistent latency with pay-as-you-go pricing. Use it for user-facing applications with regular traffic where latency matters.

6 6 

7For faster speeds with GPT-6 Astra or GPT-6.1 Sol, see [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode).7For faster speeds with GPT-6.2 Astra, GPT-6.2 Sol, GPT-6 Astra, or GPT-6.1 Sol, see [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode).

8 8 

9Priority processing was renamed Fast mode on July 30, 2026. We also increased9Priority processing was renamed Fast mode on July 30, 2026. We also increased

10 the speed at which Fast mode operates for `gpt-5.6-sol` to make it up to 2.5×10 the speed at which Fast mode operates for `gpt-5.6-sol` to make it up to 2.5×


25const openai = new OpenAI();25const openai = new OpenAI();

26 26 

27const response = await openai.responses.create({27const response = await openai.responses.create({

28 model: "gpt-6.1-sol",28 model: "gpt-6.2-sol",

29 input: "What does 'fit check for my napalm era' mean?",29 input: "What does 'fit check for my napalm era' mean?",

30 service_tier: "fast",30 service_tier: "fast",

31});31});


39client = OpenAI()39client = OpenAI()

40 40 

41response = client.responses.create(41response = client.responses.create(

42 model="gpt-6.1-sol",42 model="gpt-6.2-sol",

43 input="What does 'fit check for my napalm era' mean?",43 input="What does 'fit check for my napalm era' mean?",

44 service_tier="fast",44 service_tier="fast",

45)45)


60func main() {60func main() {

61 client := openai.NewClient()61 client := openai.NewClient()

62 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{62 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

63 Model: "gpt-6.1-sol",63 Model: "gpt-6.2-sol",

64 ServiceTier: "fast",64 ServiceTier: "fast",

65 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What does 'fit check for my napalm era' mean?")},65 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What does 'fit check for my napalm era' mean?")},

66 })66 })


78 78 

79ResponseCreateParams params =79ResponseCreateParams params =

80 ResponseCreateParams.builder()80 ResponseCreateParams.builder()

81 .model("gpt-6.1-sol")81 .model("gpt-6.2-sol")

82 .input("What does 'fit check for my napalm era' mean?")82 .input("What does 'fit check for my napalm era' mean?")

83 .serviceTier(ResponseCreateParams.ServiceTier.of("fast"))83 .serviceTier(ResponseCreateParams.ServiceTier.of("fast"))

84 .build();84 .build();


96client = OpenAI::Client.new96client = OpenAI::Client.new

97 97 

98response = client.responses.create(98response = client.responses.create(

99 model: "gpt-6.1-sol",99 model: "gpt-6.2-sol",

100 service_tier: :fast,100 service_tier: :fast,

101 input: "What does 'fit check for my napalm era' mean?"101 input: "What does 'fit check for my napalm era' mean?"

102)102)


109 -H "Authorization: Bearer $OPENAI_API_KEY" \109 -H "Authorization: Bearer $OPENAI_API_KEY" \

110 -H "Content-Type: application/json" \110 -H "Content-Type: application/json" \

111 -d '{111 -d '{

112 "model": "gpt-6.1-sol",112 "model": "gpt-6.2-sol",

113 "input": "What does 'fit check for my napalm era' mean?",113 "input": "What does 'fit check for my napalm era' mean?",

114 "service_tier": "fast"114 "service_tier": "fast"

115 }'115 }'


178 178 

179### Is Fast mode compatible with data residency, Zero Data Retention, and a BAA?179### Is Fast mode compatible with data residency, Zero Data Retention, and a BAA?

180 180 

181Fast mode is compatible with data residency, Zero Data Retention, and a Business Associate Agreement (BAA), subject to model-specific availability. Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. Existing endpoint, tool, eligibility, and contractual requirements still apply. See the [Your data guide](https://developers.openai.com/api/docs/guides/your-data) for details.181Fast mode is compatible with data residency, Zero Data Retention, and a Business Associate Agreement (BAA), subject to model-specific availability. GPT-6.2 Astra and GPT-6.2 Sol support US and EU data residency with Fast mode. Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna. Fast mode is not available with EU data residency for GPT-6 Astra or GPT-6 Sol. Existing endpoint, tool, eligibility, and contractual requirements still apply. See the [Data residency guide](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency) for details.

Details

108const client = new OpenAI();108const client = new OpenAI();

109 109 

110const response = await client.responses.create({110const response = await client.responses.create({

111 model: "gpt-6-astra",111 model: "gpt-6.2-astra",

112 input: [112 input: [

113 {113 {

114 role: "user",114 role: "user",


135client = OpenAI()135client = OpenAI()

136 136 

137response = client.responses.create(137response = client.responses.create(

138 model="gpt-6-astra",138 model="gpt-6.2-astra",

139 input=[139 input=[

140 {140 {

141 "role": "user",141 "role": "user",


171 client := openai.NewClient()171 client := openai.NewClient()

172 172 

173 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{173 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

174 Model: "gpt-6-astra",174 Model: "gpt-6.2-astra",

175 Input: responses.ResponseNewParamsInputUnion{175 Input: responses.ResponseNewParamsInputUnion{

176 OfInputItemList: responses.ResponseInputParam{176 OfInputItemList: responses.ResponseInputParam{

177 responses.ResponseInputItemParamOfMessage(177 responses.ResponseInputItemParamOfMessage(


210 210 

211ResponseCreateParams params =211ResponseCreateParams params =

212 ResponseCreateParams.builder()212 ResponseCreateParams.builder()

213 .model("gpt-6-astra")213 .model("gpt-6.2-astra")

214 .inputOfResponse(214 .inputOfResponse(

215 List.of(215 List.of(

216 ResponseInputItem.ofMessage(216 ResponseInputItem.ofMessage(


245);245);

246 246 

247ResponseResult response = await client.CreateResponseAsync(247ResponseResult response = await client.CreateResponseAsync(

248 "gpt-6-astra",248 "gpt-6.2-astra",

249 [249 [

250 ResponseItem.CreateUserMessageItem(250 ResponseItem.CreateUserMessageItem(

251 [251 [


267openai = OpenAI::Client.new267openai = OpenAI::Client.new

268 268 

269response = openai.responses.create(269response = openai.responses.create(

270 model: "gpt-6-astra",270 model: "gpt-6.2-astra",

271 input: [271 input: [

272 {272 {

273 role: "user",273 role: "user",


293 -H "Content-Type: application/json" \293 -H "Content-Type: application/json" \

294 -H "Authorization: Bearer $OPENAI_API_KEY" \294 -H "Authorization: Bearer $OPENAI_API_KEY" \

295 -d '{295 -d '{

296 "model": "gpt-6-astra",296 "model": "gpt-6.2-astra",

297 "input": [297 "input": [

298 {298 {

299 "role": "user",299 "role": "user",


336});336});

337 337 

338const response = await client.responses.create({338const response = await client.responses.create({

339 model: "gpt-6-astra",339 model: "gpt-6.2-astra",

340 input: [340 input: [

341 {341 {

342 role: "user",342 role: "user",


365file = client.files.create(file=open("draconomicon.pdf", "rb"), purpose="user_data")365file = client.files.create(file=open("draconomicon.pdf", "rb"), purpose="user_data")

366 366 

367response = client.responses.create(367response = client.responses.create(

368 model="gpt-6-astra",368 model="gpt-6.2-astra",

369 input=[369 input=[

370 {370 {

371 "role": "user",371 "role": "user",


416 }416 }

417 417 

418 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{418 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

419 Model: "gpt-6-astra",419 Model: "gpt-6.2-astra",

420 Input: responses.ResponseNewParamsInputUnion{420 Input: responses.ResponseNewParamsInputUnion{

421 OfInputItemList: responses.ResponseInputParam{421 OfInputItemList: responses.ResponseInputParam{

422 responses.ResponseInputItemParamOfMessage(422 responses.ResponseInputItemParamOfMessage(


468 .responses()468 .responses()

469 .create(469 .create(

470 ResponseCreateParams.builder()470 ResponseCreateParams.builder()

471 .model("gpt-6-astra")471 .model("gpt-6.2-astra")

472 .inputOfResponse(472 .inputOfResponse(

473 List.of(473 List.of(

474 ResponseInputItem.ofMessage(474 ResponseInputItem.ofMessage(


502);502);

503 503 

504ResponseResult response = await client.CreateResponseAsync(504ResponseResult response = await client.CreateResponseAsync(

505 "gpt-6-astra",505 "gpt-6.2-astra",

506 [506 [

507 ResponseItem.CreateUserMessageItem(507 ResponseItem.CreateUserMessageItem(

508 [508 [


530)530)

531 531 

532response = openai.responses.create(532response = openai.responses.create(

533 model: "gpt-6-astra",533 model: "gpt-6.2-astra",

534 input: [534 input: [

535 {535 {

536 role: "user",536 role: "user",


561 -H "Content-Type: application/json" \561 -H "Content-Type: application/json" \

562 -H "Authorization: Bearer $OPENAI_API_KEY" \562 -H "Authorization: Bearer $OPENAI_API_KEY" \

563 -d '{563 -d '{

564 "model": "gpt-6-astra",564 "model": "gpt-6.2-astra",

565 "input": [565 "input": [

566 {566 {

567 "role": "user",567 "role": "user",


602const base64String = data.toString("base64");602const base64String = data.toString("base64");

603 603 

604const response = await client.responses.create({604const response = await client.responses.create({

605 model: "gpt-6-astra",605 model: "gpt-6.2-astra",

606 input: [606 input: [

607 {607 {

608 role: "user",608 role: "user",


636base64_string = base64.b64encode(data).decode("utf-8")636base64_string = base64.b64encode(data).decode("utf-8")

637 637 

638response = client.responses.create(638response = client.responses.create(

639 model="gpt-6-astra",639 model="gpt-6.2-astra",

640 input=[640 input=[

641 {641 {

642 "role": "user",642 "role": "user",


681 fileData := "data:application/pdf;base64," + base64.StdEncoding.EncodeToString(data)681 fileData := "data:application/pdf;base64," + base64.StdEncoding.EncodeToString(data)

682 682 

683 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{683 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

684 Model: "gpt-6-astra",684 Model: "gpt-6.2-astra",

685 Input: responses.ResponseNewParamsInputUnion{685 Input: responses.ResponseNewParamsInputUnion{

686 OfInputItemList: responses.ResponseInputParam{686 OfInputItemList: responses.ResponseInputParam{

687 responses.ResponseInputItemParamOfMessage(687 responses.ResponseInputItemParamOfMessage(


726 .encodeToString(Files.readAllBytes(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"))));726 .encodeToString(Files.readAllBytes(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"))));

727ResponseCreateParams params =727ResponseCreateParams params =

728 ResponseCreateParams.builder()728 ResponseCreateParams.builder()

729 .model("gpt-6-astra")729 .model("gpt-6.2-astra")

730 .inputOfResponse(730 .inputOfResponse(

731 List.of(731 List.of(

732 ResponseInputItem.ofMessage(732 ResponseInputItem.ofMessage(


757 757 

758BinaryData fileBytes = BinaryData.FromBytes(await File.ReadAllBytesAsync("draconomicon.pdf"));758BinaryData fileBytes = BinaryData.FromBytes(await File.ReadAllBytesAsync("draconomicon.pdf"));

759ResponseResult response = await client.CreateResponseAsync(759ResponseResult response = await client.CreateResponseAsync(

760 "gpt-6-astra",760 "gpt-6.2-astra",

761 [761 [

762 ResponseItem.CreateUserMessageItem(762 ResponseItem.CreateUserMessageItem(

763 [763 [


784client = OpenAI::Client.new784client = OpenAI::Client.new

785pdf_data = Base64.strict_encode64(File.binread("draconomicon.pdf"))785pdf_data = Base64.strict_encode64(File.binread("draconomicon.pdf"))

786response = client.responses.create(786response = client.responses.create(

787 model: "gpt-6-astra",787 model: "gpt-6.2-astra",

788 input: [788 input: [

789 {789 {

790 role: :user,790 role: :user,


811 -H "Content-Type: application/json" \811 -H "Content-Type: application/json" \

812 -H "Authorization: Bearer $OPENAI_API_KEY" \812 -H "Authorization: Bearer $OPENAI_API_KEY" \

813 -d '{813 -d '{

814 "model": "gpt-6-astra",814 "model": "gpt-6.2-astra",

815 "input": [815 "input": [

816 {816 {

817 "role": "user",817 "role": "user",

Details

9Flex processing is in beta with limited model availability. Supported models9Flex processing is in beta with limited model availability. Supported models

10 are listed on the [pricing page](https://developers.openai.com/api/docs/pricing?latest-pricing=flex).10 are listed on the [pricing page](https://developers.openai.com/api/docs/pricing?latest-pricing=flex).

11 11 

12For asynchronous Responses API workflows that can wait longer for the initial response, see [discounted background completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows). These windows use Standard processing.

13 

12## API usage14## API usage

13 15 

14To use Flex processing, set the `service_tier` parameter to `flex` in your API request:16To use Flex processing, set the `service_tier` parameter to `flex` in your API request:


24 26 

25const response = await client.responses.create(27const response = await client.responses.create(

26 {28 {

27 model: "gpt-6-astra",29 model: "gpt-6.1-sol",

28 instructions: "List and describe all the metaphors used in this book.",30 instructions: "List and describe all the metaphors used in this book.",

29 input: "<very long text of book here>",31 input: "<very long text of book here>",

30 service_tier: "flex",32 service_tier: "flex",


45 47 

46# you can override the max timeout per request as well48# you can override the max timeout per request as well

47response = client.with_options(timeout=900.0).responses.create(49response = client.with_options(timeout=900.0).responses.create(

48 model="gpt-6-astra",50 model="gpt-6.1-sol",

49 instructions="List and describe all the metaphors used in this book.",51 instructions="List and describe all the metaphors used in this book.",

50 input="<very long text of book here>",52 input="<very long text of book here>",

51 service_tier="flex",53 service_tier="flex",


70func main() {72func main() {

71 client := openai.NewClient(option.WithRequestTimeout(15 * time.Minute))73 client := openai.NewClient(option.WithRequestTimeout(15 * time.Minute))

72 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{74 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

73 Model: "gpt-6-astra",75 Model: "gpt-6.1-sol",

74 Instructions: openai.String("List and describe all the metaphors used in this book."),76 Instructions: openai.String("List and describe all the metaphors used in this book."),

75 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("<very long text of book here>")},77 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("<very long text of book here>")},

76 ServiceTier: responses.ResponseNewParamsServiceTierFlex,78 ServiceTier: responses.ResponseNewParamsServiceTierFlex,


92 94 

93ResponseCreateParams params =95ResponseCreateParams params =

94 ResponseCreateParams.builder()96 ResponseCreateParams.builder()

95 .model("gpt-6-astra")97 .model("gpt-6.1-sol")

96 .input("<very long text of book here>")98 .input("<very long text of book here>")

97 .instructions("List and describe all the metaphors used in this book.")99 .instructions("List and describe all the metaphors used in this book.")

98 .serviceTier(ResponseCreateParams.ServiceTier.FLEX)100 .serviceTier(ResponseCreateParams.ServiceTier.FLEX)


116 118 

117CreateResponseOptions options = new()119CreateResponseOptions options = new()

118{120{

119 Model = "gpt-6-astra",121 Model = "gpt-6.1-sol",

120 Instructions = "List and describe all the metaphors used in this book.",122 Instructions = "List and describe all the metaphors used in this book.",

121 ServiceTier = ResponseServiceTier.Flex,123 ServiceTier = ResponseServiceTier.Flex,

122};124};


133client = OpenAI::Client.new(timeout: 900.0)135client = OpenAI::Client.new(timeout: 900.0)

134 136 

135response = client.responses.create(137response = client.responses.create(

136 model: "gpt-6-astra",138 model: "gpt-6.1-sol",

137 service_tier: :flex,139 service_tier: :flex,

138 instructions: "List and describe all the metaphors used in this book.",140 instructions: "List and describe all the metaphors used in this book.",

139 input: "<very long text of book here>"141 input: "<very long text of book here>"


147 -H "Authorization: Bearer $OPENAI_API_KEY" \149 -H "Authorization: Bearer $OPENAI_API_KEY" \

148 -H "Content-Type: application/json" \150 -H "Content-Type: application/json" \

149 -d '{151 -d '{

150 "model": "gpt-6-astra",152 "model": "${sampleParameters.model}",

151 "instructions": "List and describe all the metaphors used in this book.",153 "instructions": "List and describe all the metaphors used in this book.",

152 "input": "<very long text of book here>",154 "input": "<very long text of book here>",

153 "service_tier": "flex"155 "service_tier": "flex"

Details

154 154 

155// 2. Prompt the model with tools defined155// 2. Prompt the model with tools defined

156let response = await openai.responses.create({156let response = await openai.responses.create({

157 model: "gpt-6-astra",157 model: "gpt-6.2-astra",

158 tools,158 tools,

159 input,159 input,

160});160});


183console.log(JSON.stringify(input, null, 2));183console.log(JSON.stringify(input, null, 2));

184 184 

185response = await openai.responses.create({185response = await openai.responses.create({

186 model: "gpt-6-astra",186 model: "gpt-6.2-astra",

187 instructions: "Respond only with a horoscope generated by a tool.",187 instructions: "Respond only with a horoscope generated by a tool.",

188 tools,188 tools,

189 input,189 input,


231 231 

232# 2. Prompt the model with tools defined232# 2. Prompt the model with tools defined

233response = client.responses.create(233response = client.responses.create(

234 model="gpt-6-astra",234 model="gpt-6.2-astra",

235 tools=tools,235 tools=tools,

236 input=input_list,236 input=input_list,

237)237)


256 )256 )

257 257 

258response = client.responses.create(258response = client.responses.create(

259 model="gpt-6-astra",259 model="gpt-6.2-astra",

260 instructions="Respond only with a horoscope generated by a tool.",260 instructions="Respond only with a horoscope generated by a tool.",

261 tools=tools,261 tools=tools,

262 input=input_list,262 input=input_list,


282 client := openai.NewClient()282 client := openai.NewClient()

283 tool := horoscopeResponseTool()283 tool := horoscopeResponseTool()

284 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{284 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

285 Model: "gpt-6-astra",285 Model: "gpt-6.2-astra",

286 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is my horoscope? I am an Aquarius.")},286 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is my horoscope? I am an Aquarius.")},

287 Tools: []responses.ToolUnionParam{tool},287 Tools: []responses.ToolUnionParam{tool},

288 })288 })


313 }313 }

314 314 

315 response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{315 response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{

316 Model: "gpt-6-astra",316 Model: "gpt-6.2-astra",

317 PreviousResponseID: openai.String(response.ID),317 PreviousResponseID: openai.String(response.ID),

318 Instructions: openai.String("Respond only with a horoscope generated by a tool."),318 Instructions: openai.String("Respond only with a horoscope generated by a tool."),

319 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{functionOutput}},319 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{functionOutput}},


381 .responses()381 .responses()

382 .create(382 .create(

383 ResponseCreateParams.builder()383 ResponseCreateParams.builder()

384 .model("gpt-6-astra")384 .model("gpt-6.2-astra")

385 .input("What is my horoscope? I am an Aquarius.")385 .input("What is my horoscope? I am an Aquarius.")

386 .addTool(horoscope)386 .addTool(horoscope)

387 .build());387 .build());


398String sign = functionCall.arguments(HoroscopeArguments.class).sign();398String sign = functionCall.arguments(HoroscopeArguments.class).sign();

399ResponseCreateParams followUp =399ResponseCreateParams followUp =

400 ResponseCreateParams.builder()400 ResponseCreateParams.builder()

401 .model("gpt-6-astra")401 .model("gpt-6.2-astra")

402 .instructions("Respond only with a horoscope generated by a tool.")402 .instructions("Respond only with a horoscope generated by a tool.")

403 .previousResponseId(firstResponse.id())403 .previousResponseId(firstResponse.id())

404 .inputOfResponse(404 .inputOfResponse(


439]439]

440 440 

441first_response = client.responses.create(441first_response = client.responses.create(

442 model: "gpt-6-astra",442 model: "gpt-6.2-astra",

443 input: "What is my horoscope? I am an Aquarius.",443 input: "What is my horoscope? I am an Aquarius.",

444 tools: tools444 tools: tools

445)445)


454arguments = JSON.parse(function_call.arguments, symbolize_names: true)454arguments = JSON.parse(function_call.arguments, symbolize_names: true)

455sign = arguments.fetch(:sign)455sign = arguments.fetch(:sign)

456response = client.responses.create(456response = client.responses.create(

457 model: "gpt-6-astra",457 model: "gpt-6.2-astra",

458 previous_response_id: first_response.id,458 previous_response_id: first_response.id,

459 input: [459 input: [

460 {460 {


475 returned in model responses with tool calls must also be passed back with tool475 returned in model responses with tool calls must also be passed back with tool

476 call outputs. For guidance on preserving the history that produced those476 call outputs. For guidance on preserving the history that produced those

477 items, see [Best practices for prefix477 items, see [Best practices for prefix

478 changes](https://developers.openai.com/api/docs/guides/preserved-reasoning).478 changes](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged).

479 479 

480## Defining functions480## Defining functions

481 481 


908 908 

909```typescript909```typescript

910const response = await openai.responses.create({910const response = await openai.responses.create({

911 model: "gpt-6-astra",911 model: "gpt-6.2-astra",

912 input,912 input,

913 tools,913 tools,

914});914});


916 916 

917```python917```python

918response = client.responses.create(918response = client.responses.create(

919 model="gpt-6-astra",919 model="gpt-6.2-astra",

920 input=input_messages,920 input=input_messages,

921 tools=responses_tools,921 tools=responses_tools,

922)922)


924 924 

925```go925```go

926response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{926response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{

927 Model: "gpt-6-astra",927 Model: "gpt-6.2-astra",

928 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},928 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},

929 Tools: tools,929 Tools: tools,

930})930})


962 962 

963ResponseCreateParams params =963ResponseCreateParams params =

964 ResponseCreateParams.builder()964 ResponseCreateParams.builder()

965 .model("gpt-6-astra")965 .model("gpt-6.2-astra")

966 .inputOfResponse(966 .inputOfResponse(

967 List.of(967 List.of(

968 ResponseInputItem.ofEasyInputMessage(968 ResponseInputItem.ofEasyInputMessage(


1027 }1027 }

1028]1028]

1029response = client.responses.create(1029response = client.responses.create(

1030 model: "gpt-6-astra",1030 model: "gpt-6.2-astra",

1031 input: input,1031 input: input,

1032 tools: tools1032 tools: tools

1033)1033)


1233];1233];

1234 1234 

1235const stream = await openai.responses.create({1235const stream = await openai.responses.create({

1236 model: "gpt-6-astra",1236 model: "gpt-6.2-astra",

1237 input: [{ role: "user", content: "What's the weather like in Paris today?" }],1237 input: [{ role: "user", content: "What's the weather like in Paris today?" }],

1238 tools,1238 tools,

1239 tool_choice: "required",1239 tool_choice: "required",


1272]1272]

1273 1273 

1274stream = client.responses.create(1274stream = client.responses.create(

1275 model="gpt-6-astra",1275 model="gpt-6.2-astra",

1276 input=[{"role": "user", "content": "What's the weather like in Paris today?"}],1276 input=[{"role": "user", "content": "What's the weather like in Paris today?"}],

1277 tools=tools,1277 tools=tools,

1278 stream=True,1278 stream=True,


1305 }1305 }

1306 tool := responses.ToolParamOfFunction("get_weather", parameters, true)1306 tool := responses.ToolParamOfFunction("get_weather", parameters, true)

1307 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{1307 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

1308 Model: "gpt-6-astra",1308 Model: "gpt-6.2-astra",

1309 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What's the weather like in Paris today?")},1309 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What's the weather like in Paris today?")},

1310 Tools: []responses.ToolUnionParam{tool},1310 Tools: []responses.ToolUnionParam{tool},

1311 })1311 })


1345 .build();1345 .build();

1346ResponseCreateParams params =1346ResponseCreateParams params =

1347 ResponseCreateParams.builder()1347 ResponseCreateParams.builder()

1348 .model("gpt-6-astra")1348 .model("gpt-6.2-astra")

1349 .input("What is the weather in Paris?")1349 .input("What is the weather in Paris?")

1350 .addTool(weather)1350 .addTool(weather)

1351 .build();1351 .build();


1360 1360 

1361client = OpenAI::Client.new1361client = OpenAI::Client.new

1362stream = client.responses.stream(1362stream = client.responses.stream(

1363 model: "gpt-6-astra",1363 model: "gpt-6.2-astra",

1364 input: "What is the weather in Paris?",1364 input: "What is the weather in Paris?",

1365 tools: [1365 tools: [

1366 {1366 {


1482 }1482 }

1483 tool := responses.ToolParamOfFunction("get_weather", parameters, true)1483 tool := responses.ToolParamOfFunction("get_weather", parameters, true)

1484 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{1484 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

1485 Model: "gpt-6-astra",1485 Model: "gpt-6.2-astra",

1486 Input: responses.ResponseNewParamsInputUnion{1486 Input: responses.ResponseNewParamsInputUnion{

1487 OfString: openai.String("What's the weather like in Paris today?"),1487 OfString: openai.String("What's the weather like in Paris today?"),

1488 },1488 },


1540 .build();1540 .build();

1541ResponseCreateParams params =1541ResponseCreateParams params =

1542 ResponseCreateParams.builder()1542 ResponseCreateParams.builder()

1543 .model("gpt-6-astra")1543 .model("gpt-6.2-astra")

1544 .input("What is the weather in Paris?")1544 .input("What is the weather in Paris?")

1545 .addTool(weather)1545 .addTool(weather)

1546 .build();1546 .build();


1578 1578 

1579client = OpenAI::Client.new1579client = OpenAI::Client.new

1580stream = client.responses.stream(1580stream = client.responses.stream(

1581 model: "gpt-6-astra",1581 model: "gpt-6.2-astra",

1582 input: "What is the weather in Paris?",1582 input: "What is the weather in Paris?",

1583 tools: [1583 tools: [

1584 {1584 {


1649const client = new OpenAI();1649const client = new OpenAI();

1650 1650 

1651const response = await client.responses.create({1651const response = await client.responses.create({

1652 model: "gpt-6-astra",1652 model: "gpt-6.2-astra",

1653 input: "Use the code_exec tool to print hello world to the console.",1653 input: "Use the code_exec tool to print hello world to the console.",

1654 tools: [1654 tools: [

1655 {1655 {


1669client = OpenAI()1669client = OpenAI()

1670 1670 

1671response = client.responses.create(1671response = client.responses.create(

1672 model="gpt-6-astra",1672 model="gpt-6.2-astra",

1673 input="Use the code_exec tool to print hello world to the console.",1673 input="Use the code_exec tool to print hello world to the console.",

1674 tools=[1674 tools=[

1675 {1675 {


1699 tool.OfCustom.Description = openai.String("Executes arbitrary Python code.")1699 tool.OfCustom.Description = openai.String("Executes arbitrary Python code.")

1700 1700 

1701 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1701 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1702 Model: "gpt-6-astra",1702 Model: "gpt-6.2-astra",

1703 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the code_exec tool to print hello world to the console.")},1703 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the code_exec tool to print hello world to the console.")},

1704 Tools: []responses.ToolUnionParam{tool},1704 Tools: []responses.ToolUnionParam{tool},

1705 })1705 })


1718 1718 

1719ResponseCreateParams params =1719ResponseCreateParams params =

1720 ResponseCreateParams.builder()1720 ResponseCreateParams.builder()

1721 .model("gpt-6-astra")1721 .model("gpt-6.2-astra")

1722 .input("Use code_exec to print hello world.")1722 .input("Use code_exec to print hello world.")

1723 .addTool(1723 .addTool(

1724 CustomTool.builder()1724 CustomTool.builder()


1735 1735 

1736client = OpenAI::Client.new1736client = OpenAI::Client.new

1737response = client.responses.create(1737response = client.responses.create(

1738 model: "gpt-6-astra",1738 model: "gpt-6.2-astra",

1739 input: "Use code_exec to print hello world.",1739 input: "Use code_exec to print hello world.",

1740 tools: [1740 tools: [

1741 {1741 {


1799`;1799`;

1800 1800 

1801const response = await client.responses.create({1801const response = await client.responses.create({

1802 model: "gpt-6-astra",1802 model: "gpt-6.2-astra",

1803 input: "Use the math_exp tool to add four plus four.",1803 input: "Use the math_exp tool to add four plus four.",

1804 tools: [1804 tools: [

1805 {1805 {


1837"""1837"""

1838 1838 

1839response = client.responses.create(1839response = client.responses.create(

1840 model="gpt-6-astra",1840 model="gpt-6.2-astra",

1841 input="Use the math_exp tool to add four plus four.",1841 input="Use the math_exp tool to add four plus four.",

1842 tools=[1842 tools=[

1843 {1843 {


1884 tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "lark")1884 tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "lark")

1885 1885 

1886 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1886 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1887 Model: "gpt-6-astra",1887 Model: "gpt-6.2-astra",

1888 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the math_exp tool to add four plus four.")},1888 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the math_exp tool to add four plus four.")},

1889 Tools: []responses.ToolUnionParam{tool},1889 Tools: []responses.ToolUnionParam{tool},

1890 })1890 })


1914 1914 

1915ResponseCreateParams params =1915ResponseCreateParams params =

1916 ResponseCreateParams.builder()1916 ResponseCreateParams.builder()

1917 .model("gpt-6-astra")1917 .model("gpt-6.2-astra")

1918 .input("Use math_exp to add four plus four.")1918 .input("Use math_exp to add four plus four.")

1919 .addTool(1919 .addTool(

1920 CustomTool.builder()1920 CustomTool.builder()


1944 %import common.INT1944 %import common.INT

1945LARK1945LARK

1946response = client.responses.create(1946response = client.responses.create(

1947 model: "gpt-6-astra",1947 model: "gpt-6.2-astra",

1948 input: "Use math_exp to add four plus four.",1948 input: "Use math_exp to add four plus four.",

1949 tools: [1949 tools: [

1950 {1950 {


2084 "^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\\s+(?P<day>\\d{1,2})(?:st|nd|rd|th)?\\s+(?P<year>\\d{4})\\s+at\\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$";2084 "^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\\s+(?P<day>\\d{1,2})(?:st|nd|rd|th)?\\s+(?P<year>\\d{4})\\s+at\\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$";

2085 2085 

2086const response = await client.responses.create({2086const response = await client.responses.create({

2087 model: "gpt-6-astra",2087 model: "gpt-6.2-astra",

2088 input:2088 input:

2089 "Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",2089 "Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",

2090 tools: [2090 tools: [


2112grammar = r"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$"2112grammar = r"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$"

2113 2113 

2114response = client.responses.create(2114response = client.responses.create(

2115 model="gpt-6-astra",2115 model="gpt-6.2-astra",

2116 input="Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",2116 input="Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",

2117 tools=[2117 tools=[

2118 {2118 {


2150 tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "regex")2150 tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "regex")

2151 2151 

2152 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2152 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2153 Model: "gpt-6-astra",2153 Model: "gpt-6.2-astra",

2154 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.")},2154 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.")},

2155 Tools: []responses.ToolUnionParam{tool},2155 Tools: []responses.ToolUnionParam{tool},

2156 })2156 })


2174 2174 

2175ResponseCreateParams params =2175ResponseCreateParams params =

2176 ResponseCreateParams.builder()2176 ResponseCreateParams.builder()

2177 .model("gpt-6-astra")2177 .model("gpt-6.2-astra")

2178 .input("Use timestamp to save August 7th 2025 at 10AM.")2178 .input("Use timestamp to save August 7th 2025 at 10AM.")

2179 .addTool(2179 .addTool(

2180 CustomTool.builder()2180 CustomTool.builder()


2197client = OpenAI::Client.new2197client = OpenAI::Client.new

2198grammar = "^(January|February|March|April|May|June|July|August|September|October|November|December) \\d{1,2}(st|nd|rd|th)? \\d{4} at (0?[1-9]|1[0-2])(AM|PM)$"2198grammar = "^(January|February|March|April|May|June|July|August|September|October|November|December) \\d{1,2}(st|nd|rd|th)? \\d{4} at (0?[1-9]|1[0-2])(AM|PM)$"

2199response = client.responses.create(2199response = client.responses.create(

2200 model: "gpt-6-astra",2200 model: "gpt-6.2-astra",

2201 input: "Use timestamp to save August 7th 2025 at 10AM.",2201 input: "Use timestamp to save August 7th 2025 at 10AM.",

2202 tools: [2202 tools: [

2203 {2203 {

Details

141 141 

142Here’s a full runnable code sample:142Here’s a full runnable code sample:

143 143 

144Run a score model grader

145 

144```python146```python

145import os147import os

146import requests148import requests


296 298 

297The python source code must contain a grade function that takes in exactly two arguments and returns a float value as a grade.299The python source code must contain a grade function that takes in exactly two arguments and returns a float value as a grade.

298 300 

301Define a Python grading function

302 

299```python303```python

300from typing import Any304from typing import Any

301 305 


327}331}

328```332```

329 333 

330Here's a working example. For Ruby, save the `grade` function shown above, including its import, as `grader.py`. Place `grader.py` in the directory where you run the example. The supplied function returns `1.0`; replace its body with your grading logic.334Here's a working example.

335 

336 

337 

338 

339For Ruby, save the `grade` function shown above, including its import, as `grader.py`. Place `grader.py` in the directory where you run the example. The supplied function returns `1.0`; replace its body with your grading logic.

340 

341 

342 

343 

344Run a Python grader through the API

331 345 

332```python346```python

333import os347import os


395**Tip:**409**Tip:**

396If you don't want to manually put your grading function in a string, you can also load it from a Python file using `importlib` and `inspect`. For example, if your grader function is in a file named `grader.py`, you can do:410If you don't want to manually put your grading function in a string, you can also load it from a Python file using `importlib` and `inspect`. For example, if your grader function is in a file named `grader.py`, you can do:

397 411 

412Load a grader from a Python file

413 

398```python414```python

399import importlib415import importlib

400import inspect416import inspect


403grader = {"type": "python", "source": inspect.getsource(grader_module)}419grader = {"type": "python", "source": inspect.getsource(grader_module)}

404```420```

405 421 

422```ruby

423# The grader executes in the service's Python runtime; Ruby packages its source.

424grader = {

425 type: :python,

426 source: File.read("grader.py")

427}

428```

429 

406 430 

407This will automatically use the entire source code of your `grader.py` file as the grader which can be helpful for longer graders.431This will automatically use the entire source code of your `grader.py` file as the grader which can be helpful for longer graders.

408 432 

Details

289const openai = new OpenAI();289const openai = new OpenAI();

290 290 

291const response = await openai.responses.create({291const response = await openai.responses.create({

292 model: "gpt-6-astra",292 model: "gpt-6.2-astra",

293 input:293 input:

294 "Generate an image of gray tabby cat hugging an otter with an orange scarf",294 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

295 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],295 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


315client = OpenAI()315client = OpenAI()

316 316 

317response = client.responses.create(317response = client.responses.create(

318 model="gpt-6-astra",318 model="gpt-6.2-astra",

319 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",319 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

320 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],320 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

321)321)


348func main() {348func main() {

349 client := openai.NewClient()349 client := openai.NewClient()

350 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{350 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

351 Model: "gpt-6-astra",351 Model: "gpt-6.2-astra",

352 Input: responses.ResponseNewParamsInputUnion{352 Input: responses.ResponseNewParamsInputUnion{

353 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),353 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

354 },354 },


389 389 

390ResponseCreateParams params =390ResponseCreateParams params =

391 ResponseCreateParams.builder()391 ResponseCreateParams.builder()

392 .model("gpt-6-astra")392 .model("gpt-6.2-astra")

393 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")393 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

394 .addTool(Tool.ImageGeneration.builder().build())394 .addTool(Tool.ImageGeneration.builder().build())

395 .build();395 .build();


411string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;411string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

412ResponsesClient client = new(key);412ResponsesClient client = new(key);

413 413 

414CreateResponseOptions options = new() { Model = "gpt-6-astra" };414CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

415options.InputItems.Add(415options.InputItems.Add(

416 ResponseItem.CreateUserMessageItem(416 ResponseItem.CreateUserMessageItem(

417 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."417 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."


433 433 

434client = OpenAI::Client.new434client = OpenAI::Client.new

435response = client.responses.create(435response = client.responses.create(

436 model: "gpt-6-astra",436 model: "gpt-6.2-astra",

437 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",437 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

438 tools: [438 tools: [

439 {439 {


470const openai = new OpenAI();470const openai = new OpenAI();

471 471 

472const response = await openai.responses.create({472const response = await openai.responses.create({

473 model: "gpt-6-astra",473 model: "gpt-6.2-astra",

474 input:474 input:

475 "Generate an image of gray tabby cat hugging an otter with an orange scarf",475 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

476 tools: [476 tools: [


498client = OpenAI()498client = OpenAI()

499 499 

500response = client.responses.create(500response = client.responses.create(

501 model="gpt-6-astra",501 model="gpt-6.2-astra",

502 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",502 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

503 tools=[503 tools=[

504 {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}504 {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}


533func main() {533func main() {

534 client := openai.NewClient()534 client := openai.NewClient()

535 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{535 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

536 Model: "gpt-6-astra",536 Model: "gpt-6.2-astra",

537 Input: responses.ResponseNewParamsInputUnion{537 Input: responses.ResponseNewParamsInputUnion{

538 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),538 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

539 },539 },


571 571 

572ResponseCreateParams params =572ResponseCreateParams params =

573 ResponseCreateParams.builder()573 ResponseCreateParams.builder()

574 .model("gpt-6-astra")574 .model("gpt-6.2-astra")

575 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")575 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

576 .addTool(576 .addTool(

577 Tool.ImageGeneration.builder().action(Tool.ImageGeneration.Action.GENERATE).build())577 Tool.ImageGeneration.builder().action(Tool.ImageGeneration.Action.GENERATE).build())


595string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;595string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

596ResponsesClient client = new(key);596ResponsesClient client = new(key);

597 597 

598CreateResponseOptions options = new() { Model = "gpt-6-astra" };598CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

599options.InputItems.Add(599options.InputItems.Add(

600 ResponseItem.CreateUserMessageItem(600 ResponseItem.CreateUserMessageItem(

601 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."601 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."


622 622 

623client = OpenAI::Client.new623client = OpenAI::Client.new

624response = client.responses.create(624response = client.responses.create(

625 model: "gpt-6-astra",625 model: "gpt-6.2-astra",

626 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",626 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

627 tools: [627 tools: [

628 {628 {


660const openai = new OpenAI();660const openai = new OpenAI();

661 661 

662const response = await openai.responses.create({662const response = await openai.responses.create({

663 model: "gpt-6-astra",663 model: "gpt-6.2-astra",

664 input:664 input:

665 "Generate an image of gray tabby cat hugging an otter with an orange scarf",665 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

666 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],666 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


680// Follow up680// Follow up

681 681 

682const response_fwup = await openai.responses.create({682const response_fwup = await openai.responses.create({

683 model: "gpt-6-astra",683 model: "gpt-6.2-astra",

684 previous_response_id: response.id,684 previous_response_id: response.id,

685 input: "Now make it look realistic",685 input: "Now make it look realistic",

686 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],686 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


708client = OpenAI()708client = OpenAI()

709 709 

710response = client.responses.create(710response = client.responses.create(

711 model="gpt-6-astra",711 model="gpt-6.2-astra",

712 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",712 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

713 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],713 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

714)714)


729# Follow up729# Follow up

730 730 

731response_fwup = client.responses.create(731response_fwup = client.responses.create(

732 model="gpt-6-astra",732 model="gpt-6.2-astra",

733 previous_response_id=response.id,733 previous_response_id=response.id,

734 input="Now make it look realistic",734 input="Now make it look realistic",

735 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],735 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],


762func main() {762func main() {

763 client := openai.NewClient()763 client := openai.NewClient()

764 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{764 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

765 Model: "gpt-6-astra",765 Model: "gpt-6.2-astra",

766 Input: responses.ResponseNewParamsInputUnion{766 Input: responses.ResponseNewParamsInputUnion{

767 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),767 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

768 },768 },


774 saveFirstGeneratedImage(first, "cat_and_otter.png")774 saveFirstGeneratedImage(first, "cat_and_otter.png")

775 775 

776 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{776 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

777 Model: "gpt-6-astra",777 Model: "gpt-6.2-astra",

778 PreviousResponseID: openai.String(first.ID),778 PreviousResponseID: openai.String(first.ID),

779 Input: responses.ResponseNewParamsInputUnion{779 Input: responses.ResponseNewParamsInputUnion{

780 OfString: openai.String("Now make it look realistic"),780 OfString: openai.String("Now make it look realistic"),


819 .responses()819 .responses()

820 .create(820 .create(

821 ResponseCreateParams.builder()821 ResponseCreateParams.builder()

822 .model("gpt-6-astra")822 .model("gpt-6.2-astra")

823 .input(823 .input(

824 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")824 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

825 .addTool(Tool.ImageGeneration.builder().build())825 .addTool(Tool.ImageGeneration.builder().build())


842 .responses()842 .responses()

843 .create(843 .create(

844 ResponseCreateParams.builder()844 ResponseCreateParams.builder()

845 .model("gpt-6-astra")845 .model("gpt-6.2-astra")

846 .input("Now make it look realistic.")846 .input("Now make it look realistic.")

847 .previousResponseId(first.id())847 .previousResponseId(first.id())

848 .addTool(Tool.ImageGeneration.builder().build())848 .addTool(Tool.ImageGeneration.builder().build())


869string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;869string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

870ResponsesClient client = new(key);870ResponsesClient client = new(key);

871 871 

872CreateResponseOptions options = new() { Model = "gpt-6-astra" };872CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

873options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));873options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

874options.InputItems.Add(874options.InputItems.Add(

875 ResponseItem.CreateUserMessageItem(875 ResponseItem.CreateUserMessageItem(


885 885 

886CreateResponseOptions followUp = new()886CreateResponseOptions followUp = new()

887{887{

888 Model = "gpt-6-astra",888 Model = "gpt-6.2-astra",

889 PreviousResponseId = first.Id,889 PreviousResponseId = first.Id,

890};890};

891followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));891followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));


907 907 

908client = OpenAI::Client.new908client = OpenAI::Client.new

909first = client.responses.create(909first = client.responses.create(

910 model: "gpt-6-astra",910 model: "gpt-6.2-astra",

911 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",911 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

912 tools: [912 tools: [

913 {913 {


928File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))928File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))

929 929 

930follow_up = client.responses.create(930follow_up = client.responses.create(

931 model: "gpt-6-astra",931 model: "gpt-6.2-astra",

932 input: "Now make it look realistic.",932 input: "Now make it look realistic.",

933 previous_response_id: first.id,933 previous_response_id: first.id,

934 tools: [934 tools: [


964const openai = new OpenAI();964const openai = new OpenAI();

965 965 

966const response = await openai.responses.create({966const response = await openai.responses.create({

967 model: "gpt-6-astra",967 model: "gpt-6.2-astra",

968 input:968 input:

969 "Generate an image of gray tabby cat hugging an otter with an orange scarf",969 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

970 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],970 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


986// Follow up986// Follow up

987 987 

988const response_fwup = await openai.responses.create({988const response_fwup = await openai.responses.create({

989 model: "gpt-6-astra",989 model: "gpt-6.2-astra",

990 input: [990 input: [

991 {991 {

992 role: "user",992 role: "user",


1020import base641020import base64

1021 1021 

1022response = openai.responses.create(1022response = openai.responses.create(

1023 model="gpt-6-astra",1023 model="gpt-6.2-astra",

1024 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",1024 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

1025 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],1025 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

1026)1026)


1041# Follow up1041# Follow up

1042 1042 

1043response_fwup = openai.responses.create(1043response_fwup = openai.responses.create(

1044 model="gpt-6-astra",1044 model="gpt-6.2-astra",

1045 input=[1045 input=[

1046 {1046 {

1047 "role": "user",1047 "role": "user",


1083func main() {1083func main() {

1084 client := openai.NewClient()1084 client := openai.NewClient()

1085 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1085 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1086 Model: "gpt-6-astra",1086 Model: "gpt-6.2-astra",

1087 Input: responses.ResponseNewParamsInputUnion{1087 Input: responses.ResponseNewParamsInputUnion{

1088 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),1088 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

1089 },1089 },


1101 ))1101 ))

1102 1102 

1103 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1103 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1104 Model: "gpt-6-astra",1104 Model: "gpt-6.2-astra",

1105 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},1105 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},

1106 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},1106 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},

1107 })1107 })


1161 .responses()1161 .responses()

1162 .create(1162 .create(

1163 ResponseCreateParams.builder()1163 ResponseCreateParams.builder()

1164 .model("gpt-6-astra")1164 .model("gpt-6.2-astra")

1165 .input(1165 .input(

1166 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")1166 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

1167 .addTool(Tool.ImageGeneration.builder().build())1167 .addTool(Tool.ImageGeneration.builder().build())


1184 .responses()1184 .responses()

1185 .create(1185 .create(

1186 ResponseCreateParams.builder()1186 ResponseCreateParams.builder()

1187 .model("gpt-6-astra")1187 .model("gpt-6.2-astra")

1188 .inputOfResponse(1188 .inputOfResponse(

1189 List.of(1189 List.of(

1190 ResponseInputItem.ofMessage(1190 ResponseInputItem.ofMessage(


1219string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1219string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1220ResponsesClient client = new(key);1220ResponsesClient client = new(key);

1221 1221 

1222CreateResponseOptions options = new() { Model = "gpt-6-astra" };1222CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1223options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));1223options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

1224options.InputItems.Add(1224options.InputItems.Add(

1225 ResponseItem.CreateUserMessageItem(1225 ResponseItem.CreateUserMessageItem(


1233 .First();1233 .First();

1234await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());1234await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());

1235 1235 

1236CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };1236CreateResponseOptions followUp = new() { Model = "gpt-6.2-astra" };

1237followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));1237followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

1238followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));1238followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));

1239followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));1239followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));


1254 1254 

1255client = OpenAI::Client.new1255client = OpenAI::Client.new

1256first = client.responses.create(1256first = client.responses.create(

1257 model: "gpt-6-astra",1257 model: "gpt-6.2-astra",

1258 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",1258 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

1259 tools: [1259 tools: [

1260 {1260 {


1275File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))1275File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))

1276 1276 

1277follow_up = client.responses.create(1277follow_up = client.responses.create(

1278 model: "gpt-6-astra",1278 model: "gpt-6.2-astra",

1279 input: [1279 input: [

1280 {1280 {

1281 role: :user,1281 role: :user,


1379}1379}

1380 1380 

1381const stream = await openai.responses.create({1381const stream = await openai.responses.create({

1382 model: "gpt-6-astra",1382 model: "gpt-6.2-astra",

1383 input:1383 input:

1384 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1384 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",

1385 stream: true,1385 stream: true,


1418 1418 

1419 1419 

1420stream = client.responses.create(1420stream = client.responses.create(

1421 model="gpt-6-astra",1421 model="gpt-6.2-astra",

1422 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1422 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",

1423 stream=True,1423 stream=True,

1424 tools=[1424 tools=[


1457func main() {1457func main() {

1458 client := openai.NewClient()1458 client := openai.NewClient()

1459 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{1459 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

1460 Model: "gpt-6-astra",1460 Model: "gpt-6.2-astra",

1461 Input: responses.ResponseNewParamsInputUnion{1461 Input: responses.ResponseNewParamsInputUnion{

1462 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),1462 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),

1463 },1463 },


1507 1507 

1508ResponseCreateParams params =1508ResponseCreateParams params =

1509 ResponseCreateParams.builder()1509 ResponseCreateParams.builder()

1510 .model("gpt-6-astra")1510 .model("gpt-6.2-astra")

1511 .input("Generate an image of a river made of white owl feathers.")1511 .input("Generate an image of a river made of white owl feathers.")

1512 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())1512 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())

1513 .build();1513 .build();


1547 1547 

1548client = OpenAI::Client.new1548client = OpenAI::Client.new

1549stream = client.responses.stream(1549stream = client.responses.stream(

1550 model: "gpt-6-astra",1550 model: "gpt-6.2-astra",

1551 input: "Generate an image of a river made of white owl feathers.",1551 input: "Generate an image of a river made of white owl feathers.",

1552 tools: [1552 tools: [

1553 {1553 {


1984const fileId2 = await createFile("fixtures/incense-kit.png");1984const fileId2 = await createFile("fixtures/incense-kit.png");

1985 1985 

1986const response = await openai.responses.create({1986const response = await openai.responses.create({

1987 model: "gpt-6-astra",1987 model: "gpt-6.2-astra",

1988 input: [1988 input: [

1989 {1989 {

1990 role: "user",1990 role: "user",


2057file_id2 = create_file("incense-kit.png")2057file_id2 = create_file("incense-kit.png")

2058 2058 

2059response = client.responses.create(2059response = client.responses.create(

2060 model="gpt-6-astra",2060 model="gpt-6.2-astra",

2061 input=[2061 input=[

2062 {2062 {

2063 "role": "user",2063 "role": "user",


2117 incenseKitID := uploadImage(client, "incense-kit.png")2117 incenseKitID := uploadImage(client, "incense-kit.png")

2118 2118 

2119 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2119 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2120 Model: "gpt-6-astra",2120 Model: "gpt-6.2-astra",

2121 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2121 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

2122 responses.ResponseInputItemParamOfMessage(2122 responses.ResponseInputItemParamOfMessage(

2123 responses.ResponseInputMessageContentListParam{2123 responses.ResponseInputMessageContentListParam{


2244 .responses()2244 .responses()

2245 .create(2245 .create(

2246 ResponseCreateParams.builder()2246 ResponseCreateParams.builder()

2247 .model("gpt-6-astra")2247 .model("gpt-6.2-astra")

2248 .inputOfResponse(List.of(input))2248 .inputOfResponse(List.of(input))

2249 .addTool(Tool.ImageGeneration.builder().build())2249 .addTool(Tool.ImageGeneration.builder().build())

2250 .build());2250 .build());


2279 containing all the items in the reference pictures.2279 containing all the items in the reference pictures.

2280PROMPT2280PROMPT

2281response = client.responses.create(2281response = client.responses.create(

2282 model: "gpt-6-astra",2282 model: "gpt-6.2-astra",

2283 input: [2283 input: [

2284 {2284 {

2285 role: :user,2285 role: :user,


2634}2634}

2635```2635```

2636 2636 

2637```ruby

2638require "openai"

2639require "pathname"

2640require "base64"

2641 

2642client = OpenAI::Client.new

2643result = client.images.edit(

2644 model: "gpt-image-2.6-flare",

2645 image: OpenAI::FilePart.new(Pathname("kitchen.webp"), content_type: "image/webp"),

2646 markup: OpenAI::FilePart.new(Pathname("markup-vase-overlay-gpt-image-2-6.png"), content_type: "image/png"),

2647 quality: :medium,

2648 prompt: "Recolor the striped vase inside the red circle to solid cobalt blue ceramic. " \

2649 "Keep its shape, the dried stems, and the rest of the kitchen unchanged. " \

2650 "Remove the red circle from the finished photo."

2651)

2652image = result.data&.first or raise "No image returned"

2653encoded = image.b64_json or raise "No image data returned"

2654File.binwrite("vase.png", Base64.strict_decode64(encoded))

2655```

2656 

2637```bash2657```bash

2638set -euo pipefail2658set -euo pipefail

2639 2659 


2715const maskId = await createFile("fixtures/mask.png");2735const maskId = await createFile("fixtures/mask.png");

2716 2736 

2717const response = await openai.responses.create({2737const response = await openai.responses.create({

2718 model: "gpt-6-astra",2738 model: "gpt-6.2-astra",

2719 input: [2739 input: [

2720 {2740 {

2721 role: "user",2741 role: "user",


2772maskId = create_file("mask.png")2792maskId = create_file("mask.png")

2773 2793 

2774response = client.responses.create(2794response = client.responses.create(

2775 model="gpt-6-astra",2795 model="gpt-6.2-astra",

2776 input=[2796 input=[

2777 {2797 {

2778 "role": "user",2798 "role": "user",


2829 imageID := uploadImage(client, "sunlit_lounge.png")2849 imageID := uploadImage(client, "sunlit_lounge.png")

2830 maskID := uploadImage(client, "mask.png")2850 maskID := uploadImage(client, "mask.png")

2831 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2851 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2832 Model: "gpt-6-astra",2852 Model: "gpt-6.2-astra",

2833 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2853 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

2834 responses.ResponseInputItemParamOfMessage(2854 responses.ResponseInputItemParamOfMessage(

2835 responses.ResponseInputMessageContentListParam{2855 responses.ResponseInputMessageContentListParam{


2920 .responses()2940 .responses()

2921 .create(2941 .create(

2922 ResponseCreateParams.builder()2942 ResponseCreateParams.builder()

2923 .model("gpt-6-astra")2943 .model("gpt-6.2-astra")

2924 .inputOfResponse(2944 .inputOfResponse(

2925 List.of(2945 List.of(

2926 ResponseInputItem.ofMessage(2946 ResponseInputItem.ofMessage(


2960image = client.files.create(file: Pathname("sunlit_lounge.png"), purpose: :vision)2980image = client.files.create(file: Pathname("sunlit_lounge.png"), purpose: :vision)

2961mask = client.files.create(file: Pathname("mask.png"), purpose: :vision)2981mask = client.files.create(file: Pathname("mask.png"), purpose: :vision)

2962response = client.responses.create(2982response = client.responses.create(

2963 model: "gpt-6-astra",2983 model: "gpt-6.2-astra",

2964 input: [2984 input: [

2965 {2985 {

2966 role: :user,2986 role: :user,


3268}3288}

3269```3289```

3270 3290 

3291```ruby

3292require "chunky_png"

3293 

3294mask = ChunkyPNG::Image.from_file("mask.png")

3295mask.pixels.map! do |pixel|

3296 gray = (0.299 * ChunkyPNG::Color.r(pixel) + 0.587 * ChunkyPNG::Color.g(pixel) + 0.114 * ChunkyPNG::Color.b(pixel)).round

3297 ChunkyPNG::Color.rgba(gray, gray, gray, gray)

3298end

3299mask.save("mask_alpha.png", color_mode: ChunkyPNG::COLOR_TRUECOLOR_ALPHA)

3300```

3301 

3271 3302 

3272## Customize Image Output3303## Customize Image Output

3273 3304 

Details

38const openai = new OpenAI();38const openai = new OpenAI();

39 39 

40const response = await openai.responses.create({40const response = await openai.responses.create({

41 model: "gpt-6-astra",41 model: "gpt-6.2-astra",

42 input:42 input:

43 "Generate an image of gray tabby cat hugging an otter with an orange scarf",43 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

44 tools: [{ type: "image_generation" }],44 tools: [{ type: "image_generation" }],


64client = OpenAI()64client = OpenAI()

65 65 

66response = client.responses.create(66response = client.responses.create(

67 model="gpt-6-astra",67 model="gpt-6.2-astra",

68 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",68 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

69 tools=[{"type": "image_generation"}],69 tools=[{"type": "image_generation"}],

70)70)


98 client := openai.NewClient()98 client := openai.NewClient()

99 99 

100 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{100 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

101 Model: "gpt-6-astra",101 Model: "gpt-6.2-astra",

102 Input: responses.ResponseNewParamsInputUnion{102 Input: responses.ResponseNewParamsInputUnion{

103 OfString: openai.String("Generate an image of a gray tabby cat hugging an otter with an orange scarf."),103 OfString: openai.String("Generate an image of a gray tabby cat hugging an otter with an orange scarf."),

104 },104 },


140 140 

141ResponseCreateParams params =141ResponseCreateParams params =

142 ResponseCreateParams.builder()142 ResponseCreateParams.builder()

143 .model("gpt-6-astra")143 .model("gpt-6.2-astra")

144 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")144 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

145 .addTool(Tool.ImageGeneration.builder().build())145 .addTool(Tool.ImageGeneration.builder().build())

146 .build();146 .build();


163 163 

164CreateResponseOptions options = new()164CreateResponseOptions options = new()

165{165{

166 Model = "gpt-6-astra",166 Model = "gpt-6.2-astra",

167};167};

168options.InputItems.Add(168options.InputItems.Add(

169 ResponseItem.CreateUserMessageItem(169 ResponseItem.CreateUserMessageItem(


191 191 

192client = OpenAI::Client.new192client = OpenAI::Client.new

193response = client.responses.create(193response = client.responses.create(

194 model: "gpt-6-astra",194 model: "gpt-6.2-astra",

195 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",195 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

196 tools: [{ type: :image_generation }]196 tools: [{ type: :image_generation }]

197)197)


211 211 

212```bash212```bash

213openai responses create \213openai responses create \

214 --model gpt-6-astra \214 --model gpt-6.2-astra \

215 --raw-output \215 --raw-output \

216 --transform 'output.#(type=="image_generation_call").result' <<'YAML' | base64 --decode > cat_and_otter.png216 --transform 'output.#(type=="image_generation_call").result' <<'YAML' | base64 --decode > cat_and_otter.png

217tools:217tools:


259const openai = new OpenAI();259const openai = new OpenAI();

260 260 

261const response = await openai.responses.create({261const response = await openai.responses.create({

262 model: "gpt-6-astra",262 model: "gpt-6.2-astra",

263 input: [263 input: [

264 {264 {

265 role: "user",265 role: "user",


285client = OpenAI()285client = OpenAI()

286 286 

287response = client.responses.create(287response = client.responses.create(

288 model="gpt-6-astra",288 model="gpt-6.2-astra",

289 input=[289 input=[

290 {290 {

291 "role": "user",291 "role": "user",


318 client := openai.NewClient()318 client := openai.NewClient()

319 319 

320 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{320 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

321 Model: "gpt-6-astra",321 Model: "gpt-6.2-astra",

322 Input: responses.ResponseNewParamsInputUnion{322 Input: responses.ResponseNewParamsInputUnion{

323 OfInputItemList: responses.ResponseInputParam{323 OfInputItemList: responses.ResponseInputParam{

324 responses.ResponseInputItemParamOfMessage(324 responses.ResponseInputItemParamOfMessage(


365 365 

366ResponseCreateParams params =366ResponseCreateParams params =

367 ResponseCreateParams.builder()367 ResponseCreateParams.builder()

368 .model("gpt-6-astra")368 .model("gpt-6.2-astra")

369 .inputOfResponse(List.of(imageInput))369 .inputOfResponse(List.of(imageInput))

370 .build();370 .build();

371 371 


388);388);

389 389 

390ResponseResult response = await client.CreateResponseAsync(390ResponseResult response = await client.CreateResponseAsync(

391 "gpt-6-astra",391 "gpt-6.2-astra",

392 [392 [

393 ResponseItem.CreateUserMessageItem(393 ResponseItem.CreateUserMessageItem(

394 [394 [


408client = OpenAI::Client.new408client = OpenAI::Client.new

409 409 

410response = client.responses.create(410response = client.responses.create(

411 model: "gpt-6-astra",411 model: "gpt-6.2-astra",

412 input: [412 input: [

413 {413 {

414 role: :user,414 role: :user,


435 -H "Content-Type: application/json" \435 -H "Content-Type: application/json" \

436 -H "Authorization: Bearer $OPENAI_API_KEY" \436 -H "Authorization: Bearer $OPENAI_API_KEY" \

437 -d '{437 -d '{

438 "model": "gpt-6-astra",438 "model": "gpt-6.2-astra",

439 "input": [439 "input": [

440 {440 {

441 "role": "user",441 "role": "user",


453 453 

454```bash454```bash

455openai responses create \455openai responses create \

456 --model gpt-6-astra \456 --model gpt-6.2-astra \

457 --raw-output \457 --raw-output \

458 --transform 'output.#(type=="message").content.0.text' <<'YAML'458 --transform 'output.#(type=="message").content.0.text' <<'YAML'

459input:459input:


485const base64Image = fs.readFileSync(imagePath, "base64");485const base64Image = fs.readFileSync(imagePath, "base64");

486 486 

487const response = await openai.responses.create({487const response = await openai.responses.create({

488 model: "gpt-6-astra",488 model: "gpt-6.2-astra",

489 input: [489 input: [

490 {490 {

491 role: "user",491 role: "user",


525 525 

526 526 

527response = client.responses.create(527response = client.responses.create(

528 model="gpt-6-astra",528 model="gpt-6.2-astra",

529 input=[529 input=[

530 {530 {

531 "role": "user",531 "role": "user",


565 imageURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)565 imageURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)

566 566 

567 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{567 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

568 Model: "gpt-6-astra",568 Model: "gpt-6.2-astra",

569 Input: responses.ResponseNewParamsInputUnion{569 Input: responses.ResponseNewParamsInputUnion{

570 OfInputItemList: responses.ResponseInputParam{570 OfInputItemList: responses.ResponseInputParam{

571 responses.ResponseInputItemParamOfMessage(571 responses.ResponseInputItemParamOfMessage(


620 620 

621ResponseCreateParams params =621ResponseCreateParams params =

622 ResponseCreateParams.builder()622 ResponseCreateParams.builder()

623 .model("gpt-6-astra")623 .model("gpt-6.2-astra")

624 .inputOfResponse(List.of(imageInput))624 .inputOfResponse(List.of(imageInput))

625 .build();625 .build();

626 626 


649BinaryData imageData = BinaryData.FromStream(stream, "image/png");649BinaryData imageData = BinaryData.FromStream(stream, "image/png");

650 650 

651ResponseResult response1 = await client.CreateResponseAsync(651ResponseResult response1 = await client.CreateResponseAsync(

652 "gpt-6-astra",652 "gpt-6.2-astra",

653 [653 [

654 ResponseItem.CreateUserMessageItem(654 ResponseItem.CreateUserMessageItem(

655 [655 [


667imageData = BinaryData.FromBytes(bytes, "image/png");667imageData = BinaryData.FromBytes(bytes, "image/png");

668 668 

669ResponseResult response2 = await client.CreateResponseAsync(669ResponseResult response2 = await client.CreateResponseAsync(

670 "gpt-6-astra",670 "gpt-6.2-astra",

671 [671 [

672 ResponseItem.CreateUserMessageItem(672 ResponseItem.CreateUserMessageItem(

673 [673 [


689image = Base64.strict_encode64(File.binread("image.png"))689image = Base64.strict_encode64(File.binread("image.png"))

690 690 

691response = client.responses.create(691response = client.responses.create(

692 model: "gpt-6-astra",692 model: "gpt-6.2-astra",

693 input: [693 input: [

694 {694 {

695 role: :user,695 role: :user,


740const fileId = await createFile("fixtures/example.jpg");740const fileId = await createFile("fixtures/example.jpg");

741 741 

742const response = await openai.responses.create({742const response = await openai.responses.create({

743 model: "gpt-6-astra",743 model: "gpt-6.2-astra",

744 input: [744 input: [

745 {745 {

746 role: "user",746 role: "user",


779file_id = create_file("path_to_your_image.jpg")779file_id = create_file("path_to_your_image.jpg")

780 780 

781response = client.responses.create(781response = client.responses.create(

782 model="gpt-6-astra",782 model="gpt-6.2-astra",

783 input=[783 input=[

784 {784 {

785 "role": "user",785 "role": "user",


826 }826 }

827 827 

828 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{828 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

829 Model: "gpt-6-astra",829 Model: "gpt-6.2-astra",

830 Input: responses.ResponseNewParamsInputUnion{830 Input: responses.ResponseNewParamsInputUnion{

831 OfInputItemList: responses.ResponseInputParam{831 OfInputItemList: responses.ResponseInputParam{

832 responses.ResponseInputItemParamOfMessage(832 responses.ResponseInputItemParamOfMessage(


875 .responses()875 .responses()

876 .create(876 .create(

877 ResponseCreateParams.builder()877 ResponseCreateParams.builder()

878 .model("gpt-6-astra")878 .model("gpt-6.2-astra")

879 .inputOfResponse(879 .inputOfResponse(

880 List.of(880 List.of(

881 ResponseInputItem.ofMessage(881 ResponseInputItem.ofMessage(


923);923);

924 924 

925ResponseResult response = await client.CreateResponseAsync(925ResponseResult response = await client.CreateResponseAsync(

926 "gpt-6-astra",926 "gpt-6.2-astra",

927 [927 [

928 ResponseItem.CreateUserMessageItem(928 ResponseItem.CreateUserMessageItem(

929 [929 [


948)948)

949 949 

950response = client.responses.create(950response = client.responses.create(

951 model: "gpt-6-astra",951 model: "gpt-6.2-astra",

952 input: [952 input: [

953 {953 {

954 role: :user,954 role: :user,

Details

Previously: guides/preserved-reasoning.md

24| Changing structured output schemas | Instead of changing the `text.format` parameter in the Responses API, append a [`configuration_update` item](https://developers.openai.com/api/docs/guides/structured-outputs#change-the-response-format-mid-conversation) with the new schema to the input items list. Keep the original request-level setting the same. |24| Changing structured output schemas | Instead of changing the `text.format` parameter in the Responses API, append a [`configuration_update` item](https://developers.openai.com/api/docs/guides/structured-outputs#change-the-response-format-mid-conversation) with the new schema to the input items list. Keep the original request-level setting the same. |

25| Changing the tools available to the agent | Instead of changing the `tools` parameter in the Responses API, use an [`additional_tools` item](https://developers.openai.com/api/docs/guides/prompt-caching#manage-tools-with-append-only-updates) to add tools, or `tool_choice` with `allowed_tools` to restrict which tools the model can call on a turn. Keep existing tool definitions in order. Append `additional_tools` with the `developer` role and a `tools` array, and replay it in its original position. |25| Changing the tools available to the agent | Instead of changing the `tools` parameter in the Responses API, use an [`additional_tools` item](https://developers.openai.com/api/docs/guides/prompt-caching#manage-tools-with-append-only-updates) to add tools, or `tool_choice` with `allowed_tools` to restrict which tools the model can call on a turn. Keep existing tool definitions in order. Append `additional_tools` with the `developer` role and a `tools` array, and replay it in its original position. |

26| Updating developer instructions | Instead of editing the original developer message, append a new `developer` message asking the model to ignore older instructions and follow the new ones you provide. For instructions scoped to a single turn, place an [explicit cache breakpoint](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works) immediately before the latest developer message so the reusable prefix ends before that message. |26| Updating developer instructions | Instead of editing the original developer message, append a new `developer` message asking the model to ignore older instructions and follow the new ones you provide. For instructions scoped to a single turn, place an [explicit cache breakpoint](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works) immediately before the latest developer message so the reusable prefix ends before that message. |

27| Compaction | Compaction changes the prefix, so cache misses are difficult to avoid in these cases.<br /><br />**OpenAI compaction:** If you use [OpenAI compaction](https://developers.openai.com/api/docs/guides/compaction) via `/responses/compact` or `context_management`, our systems retain subsequent reasoning items despite the prefix being changed. An OpenAI compaction item can appear anywhere in context. When calling `/responses/compact`, omit `instructions` and pass the returned window to the next request in its original order. If your history contains `configuration_update` items, follow the [configuration-update compaction requirements](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation).<br /><br />**Custom compaction:** If you use a different or home-grown compaction strategy, place the compacted item at the end of the model’s context, instead of before recent turns. Alternatively, you can accept the trade-off and have the reasoning items from the original history that follow it dropped. |27| Compaction | Compaction changes the prefix, so cache misses are difficult to avoid in these cases.<br /><br />**OpenAI compaction:** If you use [OpenAI compaction](https://developers.openai.com/api/docs/guides/compaction) via `/responses/compact` or `context_management`, our systems retain subsequent reasoning items despite the prefix being changed. An OpenAI compaction item can appear anywhere in context. When calling `/responses/compact`, omit `instructions` and pass the returned window to the next request in its original order. `context_management` carries forward configuration updates and developer-added tools. For explicit compaction, [restore them on the next request](https://developers.openai.com/api/docs/guides/compaction).<br /><br />**Custom compaction:** If you use a different or home-grown compaction strategy, place the compacted item at the end of the model’s context, instead of before recent turns. Alternatively, you can accept the trade-off and have the reasoning items from the original history that follow it dropped. |

28| Shortening past tool outputs or downsizing past files / images | Some integrations truncate past items, such as tool outputs, files, or images, instead of using compaction. These modifications change the prefix. We strongly recommend either using compaction, or shortening long tool outputs and downsizing images or files before they’re sent to the model for the first time. |28| Shortening past tool outputs or downsizing past files / images | Some integrations truncate past items, such as tool outputs, files, or images, instead of using compaction. These modifications change the prefix. We strongly recommend either using compaction, or shortening long tool outputs and downsizing images or files before they’re sent to the model for the first time. |

29 29 

30## Auditing your integration for prefix changes30## Auditing your integration for prefix changes

Details

43 43 

44A long prompt can delay the first token, especially when much of the input is new. Filter search results for relevance, strip markup you don't need, and send only the context required to answer accurately.44A long prompt can delay the first token, especially when much of the input is new. Filter search results for relevance, strip markup you don't need, and send only the context required to answer accurately.

45 45 

46For repeated inputs, put stable instructions, examples, and tool definitions first. In multi-turn conversations, [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/preserved-reasoning) and append new messages and tool results. [Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) can reuse an eligible exact prefix match. In the Responses API, inspect `usage.input_tokens_details.cached_tokens` and compare TTFT for requests with and without cache hits.46For repeated inputs, put stable instructions, examples, and tool definitions first. In multi-turn conversations, [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) and append new messages and tool results. [Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) can reuse an eligible exact prefix match. In the Responses API, inspect `usage.input_tokens_details.cached_tokens` and compare TTFT for requests with and without cache hits.

47 47 

48## Make fewer requests48## Make fewer requests

49 49 

Details

1---1---

2latestModelInfo:2latestModelInfo:

3 model: gpt-6-astra3 model: gpt-6.2-astra

4 migrationGuide: /api/docs/guides/latest-model/gpt-6-astra.md#migration-quickstart4 migrationGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#migration-quickstart

5 promptingGuide: /api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices5 promptingGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#prompting-best-practices

6---6---

7 7 

8# Using GPT-68# Using GPT-6.2

9 9 

10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

11 11 

12<a id="gpt-6-astra-gpt-6-astra"></a>12<a id="gpt-6.2-astra-gpt-62-astra-and-gpt-62-sol"></a>

13<a id="gpt-61-sol"></a>

14<a id="gpt-6.1-sol"></a>

15<a id="gpt-6-astra-gpt-61-sol"></a>

16<a id="gpt-61-terra"></a>

17<a id="gpt-6.1-terra"></a>

18<a id="gpt-6-astra-gpt-61-terra"></a>

19 13 

20Use GPT-6 Astra for the most demanding work, GPT-6.1 Sol for complex work at14Use [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra) for the most demanding tasks or [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol) for complex work at lower cost.

21lower cost, GPT-6.1 Terra for visual reasoning and writing, or GPT-6 Luna for

22focused, high-volume tasks. See [Model selection](https://developers.openai.com/api/docs/guides/model-selection)

23for a comparison.

24 

25<a id="gpt-6-astra-what-is-new" className="scroll-mt-[110px]"></a>

26 15 

27## What's new16## What's new

28 17 

29- **Async tool calling:** Supported models can continue reasoning, call other tools, or answer independent parts of a request while your application runs a tool. Set `async: true` on a function or custom tool and return its result when ready using the original `call_id`. Your application executes the tool and manages pending work. See [Async tool calling](https://developers.openai.com/api/docs/guides/async-tool-calling) for compatibility and examples.18Starting with GPT-6.2, the API will drop reasoning items when it detects mid-conversation changes to the conversation history (prefix edits), model downgrade, end user, or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to instructions or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

30- **Mid-turn steering:** Send additional user instructions while GPT-6 is working, such as a correction or a change in requirements. Over a WebSocket connection, the Responses API preserves completed work and includes the update in a continuation. See [Mid-turn steering](https://developers.openai.com/api/docs/guides/steering) for the event flow and tool-result handling.

31- **Change reasoning mid-conversation while preserving cache:** Add a `configuration_update` input item to increase reasoning effort for difficult work or reduce it for routine follow-ups without rewriting the original prompt prefix. The updated reasoning effort applies until another `configuration_update` input item overrides it. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility.

32- **Multi-agent and persisted reasoning on GPT-6.1 Sol:** Use the [Responses Multi-agent beta](https://developers.openai.com/api/docs/guides/responses-multi-agent) to delegate work to subagents. Set [`reasoning.context` to `all_turns`](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls) to reuse compatible reasoning from earlier turns.

33- **Misalignment monitoring:** As part of our [strengthened safeguards](https://openai.com/index/path-to-astra/) for GPT-6 Astra, our systems asynchronously monitor for misalignment and trigger alerts when necessary. See [Misalignment monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring) for more information.

34 

35GPT-6 also supports the existing API capabilities available with GPT-5.6, including [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [streaming](https://developers.openai.com/api/docs/guides/streaming-responses), [Programmatic Tool Calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling), [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [compaction](https://developers.openai.com/api/docs/guides/compaction), and [pro mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode).

36 

37## Limitations

38 

39- GPT-6 Astra and GPT-6.1 Sol do not support the `none` reasoning effort; GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna do.

40- Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. See [data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency).

41 19 

42<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>20<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

43 21 

44## Prompting best practices22## Prompting best practices

45 23 

46Use the following prompts as a starting point across the GPT-6 model family. They address behavior observed with GPT-6 Astra; evaluate them with your chosen model and workload.24Use the following prompts as a starting point across the GPT-6.2 model family. The examples address behaviors we’ve seen when working with GPT-6.2 Astra and Sol. If you recognize one in your own application, try the prompt in that section.

47 25 

48### GPT-6 Astra behavior26### GPT-6.2 Astra behavior

49 27 

50- [Initiative and follow-through](#initiative-and-follow-through): The model is designed to be a more effective collaborator and is thus more likely to ask the user a question when additional input could materially change the result. This can cause it to stop when the user may expect it to make reasonable assumptions and persist.28- **[Writing style](#writing-style).** The model’s writing tends to be more concise and direct by default. When migrating, revisit instructions like “be concise” in your system prompt.

51- [Instruction following](#instruction-following): GPT-6 Astra is stronger at general instruction following than our previous models, giving you greater control over its behavior. It can be more sensitive to instructions contained in skills and other files, such as `AGENTS.md`. We **strongly recommend** auditing skills and other files accessible to your model for instructions that could influence its behavior.29- **[Task completion](#task-completion).** When the user’s intent is unclear, the model may propose a next step and wait for confirmation. For longer tasks, give it room to make reasonable assumptions and keep working.

52- [Personality and writing style](#personality-and-writing-style): The model tends toward detailed, formatted responses and may use recurring phrases across sessions. Specify the writing style and structure your application needs.30- **[Coding style](#coding-style).** The model tends to write more efficient, high-quality code than its predecessors. Describe any project conventions that should guide how it writes or edits code.

53- [Subagent delegation](#subagent-delegation): The model may delegate less often than desired for your workflow. Specify when and how much it should use subagents for parallel work.31- **[Frontend design](#frontend-design).** If the interface needs a particular look, specify the imagery and typography it should use.

54- [Testing and verification](#testing-and-verification): For coding tasks, the model tends to be thorough in testing before considering a task complete. For smaller tasks, this can result in broader tests than the task requires.

55 32 

56### Initiative and follow-through33<a id="gpt-6.2-astra-prompt-patterns-for-api-applications"></a>

34<a id="gpt-6.2-astra-personality-and-writing-style"></a>

57 35 

58GPT-6 Astra is generally better than GPT-5.6 Sol and earlier models at staying coherent during long tasks. It is also more likely to ask for clarification where earlier models would make assumptions.36### Writing style

59 37 

60To encourage more autonomous work, start with this prompt:38GPT-6.2 Astra is more concise and direct by default than earlier models. Its tone can be tuned to suit the application, from a professional colleague to a more conversational assistant.

61 39 

62```text40Use the following prompt if you want to use the model as a collaborator and thought partner for day to day work.

63You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.

64 41 

65When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.42```text

43Write using terminology the user and sources use. Keep technical details and use domain-specific language when they make the explanation more precise. Use the active voice and keep closely related details together. Cover the key points up front, and avoid references that the reader can only make sense of later in the response. Give the user enough context to follow your reasoning.

66```44```

67 45 

68When the user’s intent is unclear, the model is more likely to ask the user for clarification to proceed. Prompt the model to follow through if the user’s prompt implies authorization:46Prompt the model to adapt to the audience it is drafting material for, such as writing in documents, emails, messages and external posts.

69 47 

70```text48```text

71When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.49When drafting a message or any other material on behalf of the user to be sent to an external audience, consider who will read it and tailor the content to that intended audience. The intended audience likely does not have the same context as the user, so ensure that you provide the background information or reasoning required for the audience to understand the content. When reviewing or editing existing content, preserve the author’s content and wording, and follow the user's instruction carefully for what edits they want.

72```50```

73 51 

74Prompt the model to ask for approval only after preparing a concrete, reviewable result. This avoids blocking the task before the model has done the work it can, and often leads to quicker task completion.52During longer tasks, the model can carry shorthand from its reasoning or from other agents into its final answer. Remind it to write a self-contained response that’s clear to someone who hasn’t followed the progress updates.

75 53 

76```text54```text

77Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.55Treat your final answer as the user's first look at your work, and not as a continuation of intermediate commentary. The final answer must always be fully self-contained: users should never need to read earlier commentary updates for context, since they are collapsed when the final answer is shown to the user.

78 56 

79Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.57Write the final answer and all other human-facing material anew for the intended reader. Do not copy or closely paraphrase your reasoning or adopt its writing style. Do not carry over working shorthand, jargon, or abbreviations from your reasoning, tool calls, or instructions to subagents and automations.

80```58```

81 59 

82The model also likes to ask non-blocking questions as it’s working by default, so adjust these prompts to match the level of autonomy your application needs.60<a id="gpt-6.2-astra-initiative-and-follow-through"></a>

61<a id="gpt-6.2-astra-subagent-delegation"></a>

83 62 

84### Instruction following63### Task completion

85 64 

86GPT-6 Astra is better able to follow longer instructions, but can also be more sensitive to information in context. For example, unclear or conflicting guidance in a skill file may cause the model to pause and block work early. Make the priority of user instructions and skills explicit.65For work that can proceed without supervision, specify the outcome the model should complete and which decisions need the user’s input.

87 66 

88```text67```text

89The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.68Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. If your final response before ending the turn is a suggested next step, a plan, a request to the user for a routine decision, instructions for a task to execute, or similar handoff to the user, take these steps yourself to make progress towards what the user asked for. Make sure that you have authorization to do so, and flag any assumptions or decisions you maketo the user.

90```

91 

92Asking the model to identify the skill and instruction that caused it to pause or change direction can also be effective in providing transparency into model behavior.

93 69 

94```text70Only stop to clarify with the user if there is significant change in task scope, you are concretely blocked, have a decision that the user needs to resolve, or before irreversible or destructive actions.

95If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.

96```71```

97 72 

98Use this prompt to find silent and conflicting guidance when your application loads many skills and instruction files such as `AGENTS.md`.73<a id="gpt-6.2-astra-testing-and-verification"></a>

74<a id="gpt-6.2-astra-ask-for-an-exhaustive-pass"></a>

99 75 

100### Personality and writing style76Ask the model to verify that it has completed the requested work. Higher reasoning effort can help it persist through the final checks on complex or long-running tasks. In the Responses API, set the level with `reasoning.effort`. [Reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort)

101 

102GPT-6 Astra tends to use lists, tables and Markdown to make responses scannable. If your application needs prose with less formatting, specify that preference.

103 77 

104```text78```text

105Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.79Bias towards action, and persist until you've completed the task the user asked for. Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. Make sure that you have accounted for every part of the user's request, and persist until you've delivered a result that fully satisfies the user's goal. If a task requires sustained work, do all the necessary work until the intended outcome is completely fulfilled.

106 80 

107Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.81Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, creating draft PRs etc) unless they are clearly destructive or irreversible. Before ending a turn or calling your work complete, check that your work fully satisfies what the user asked for. If any steps remain or any part of the result still needs verification, follow through on this work before finishing.

108```82```

109 83 

110For technical communication, the following prompt helps strike a balance between using clear, coherent language while remaining domain appropriate:84<a id="gpt-6.2-astra-instruction-following"></a>

85<a id="gpt-6.2-astra-intent-understanding"></a>

86<a id="gpt-6.2-astra-interpreting-ambiguous-requests"></a>

111 87 

112```text88When a detail is unclear, give the model room to state what it’s assuming and continue with the task.

113Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.

114```

115 

116To reduce jargon and stock phrases in writing, start with this prompt:

117 89 

118```text90```text

119Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".91Make reasonable, reversible assumptions to carry work forward and state them if it progresses the task within scope. Do not second guess yourself, stop after describing what you could do, offer to do the work, or provide a partial answer unless there is no way you can proceed.

120 

121State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.

122```92```

123 93 

124### Subagent delegation94With an async tool such as `request_user_input_async` in your application, GPT-6.2 can ask the user for clarification and continue work that doesn’t depend on the answer. [Add an async question tool](https://developers.openai.com/api/docs/guides/async-tool-calling#add-a-tool-to-ask-the-user-for-input)

125 95 

126GPT-6 Astra is trained to be able to divide and delegate work to subagents that work in parallel. If you are implementing a multi-agent system in your harness, use the following prompt to tune how much GPT-6 Astra should delegate work:96<a id="gpt-6.2-astra-code-changes"></a>

127 97 

128```text98### Coding style

129If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.

130```

131 99 

132Messages between agents may contain grammar or spacing errors. Use this prompt to make inter-agent messages easier to read:100Describe the codebase’s conventions and any behavior that existing callers rely on. For example, specify when to reuse existing logic, how narrowly to scope a change, and when to add a test for behavior the existing suite doesn’t cover.

133 101 

134```text102```text

135Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.103Above all, be thorough in producing high-quality, correct code that completely fulfills the user's task. Keep the code easy to read and verify that the user-requested outcome works as they intend. Follow these instructions when coding:

104 

105(a) Reuse existing logic in the user's repo when you can. You should reuse existing classes, methods, representations, and APIs in the codebase as long as they preserve correctness. Before consolidating or removing code, preserve the behavior its callers rely on unless the task requires changing it.

106(b) Skip new tests unless requested, required by the repo, or needed to catch a specific regression existing tests would miss.

107(c) Make sure that code is human readable. Do not use fewer lines, shorter variable names, minified formatting, or dense one-liners as substitutes for simplicity. Ensure that comments and variable names are readable and understandable to a human. Code-golfed expressions count as overly complex when they encode many branches, conditions, or hidden assumptions.

108(d) Avoid unnecessary indirection and abstraction. Helper functions, utility functions, and class abstractions can add cognitive complexity even when they do not add branches.

136```109```

137 110 

138The model tends to respond well to prompting for how and when it should delegate work to subagents, so tune this behavior to fit with your harness and multi-agent implementation.111<a id="gpt-6.2-astra-visual-review"></a>

112<a id="gpt-6.2-astra-visual-work-and-frontend-design"></a>

139 113 

140### Testing and verification114### Frontend design

141 115 

142For coding tasks, calibrate how much testing and verification a change requires. This can help avoid unnecessary tests or repeated checks for small changes.116If the application depends on a specific visual style, describe it in the prompt. Specify the kinds of images it should use and the typography it should follow, including a particular typeface when that matters. Keep interface copy focused on what people need to know or do.

143 117 

144```text118```text

145Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.119When generating webpages or apps with a frontend user interface, follow these instructions:

146 120 

147Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.121- When choosing visuals, generally prefer realistic images from ImageGen or image search that suit the project's style and purpose. Use SVGs when the user specifically asks for them.

122- Include a text element only when it provides information the user needs, helps them navigate or act, or fulfills an explicit content request. Remove decorative numbering, filler badges, redundant headings, and explanatory copy that merely restates what the surrounding interface already makes clear, while preserving necessary labels, instructions, and status feedback.

148```123```

149 124 

150## Migration quickstart125For visual work, share a reference from your design software, or give GPT-6.2 access to the [image generation tool](https://developers.openai.com/api/docs/guides/tools-image-generation) and ask it to create one with GPT Image. A reference can enrich your prompt with details that are hard to describe in words. Once it captures the look you want, ask the model to build the asset, render it, and refine it against the reference.

151 126 

152### Migrate with Codex127## Migration quickstart

153 128 

154Codex can apply the recommended changes in this guide with the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).129<a id="gpt-6.2-astra-migrate-with-codex"></a>

155 130 

156```text131To migrate an API application to GPT-6.2 Astra with a coding agent, use the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).

157$openai-docs migrate this project to the GPT-6 model family

158```

159 132 

160To use this skill in other coding agents, download it from the [Codex repository](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).133<a id="gpt-6.2-astra-choose-a-reasoning-effort"></a>

134<a id="gpt-6.2-astra-zdr-data-residency-and-service-tiers"></a>

135<a id="gpt-6.2-astra-limitations"></a>

136<a id="gpt-6.2-astra-data-residency-and-service-tiers"></a>

161 137 

162### Update API and model parameters138### Update API and model parameters

163 139 

164Set `model` to `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, or `gpt-6-luna`, then review the compatibility checks below.140Set `model` to `gpt-6.2-astra` or `gpt-6.2-sol`, then check the following:

165 

166If you're switching from `gpt-6-sol` to `gpt-6.1-sol`, use `low` if your

167current reasoning effort is `none`. Move any Chat Completions requests that

168call functions to the Responses API.

169 

170When moving from GPT-5.6 Terra to GPT-6.1 Terra, compare both models on

171representative images and workflows at the same reasoning effort.

172 141 

173- **Reasoning effort:** Preserve your current effective [reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort) where supported. GPT-6 Astra and GPT-6.1 Sol do not support `none`; use `low` instead. GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support `none`. If your existing request uses `minimal`, start with `low` and compare results on representative tasks. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.142- **Reasoning effort:** Start with `medium` for a new integration. If you currently use `none` or `minimal`, use `low` instead. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.

174- **Tool calling:** Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6 Astra, GPT-6.1 Sol, and GPT-6.1 Terra support Chat Completions, but tool calling requires Responses. GPT-6 Sol and GPT-6 Luna support function calling in Chat Completions only with `reasoning_effort: "none"`. Use Responses for reasoning with tools.143- **Tool calling:** Use the [**Responses API**](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6.2 Astra and GPT-6.2 Sol support Chat Completions, but tool calling requires Responses.

175- **Unsupported parameters:** When reasoning effort is not `none`, remove `temperature`, `top_p`, and `top_logprobs`. For Chat Completions, also remove `logprobs`. For Responses, remove `message.output_text.logprobs` from `include`.144- **Unsupported parameters:** When migrating Chat Completions requests, omit `temperature`, `top_p`, `logprobs`, and `top_logprobs`. For Responses requests, omit `temperature`, `top_p`, and `top_logprobs` and remove `message.output_text.logprobs` from `include`.

176- **Data residency:** Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. Fast mode for GPT-6 Astra does not include a latency SLA. See [Fast mode compatibility](https://developers.openai.com/api/docs/guides/fast-mode#is-fast-mode-compatible-with-data-residency-zero-data-retention-and-a-baa).145- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [**prompt caching changes**](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.

177- **Changing reasoning effort:** If your application changes effort between responses, use `configuration_update` items in standard, single-agent requests. Keep request-level `reasoning.effort` unchanged to preserve the prompt prefix for caching. Check the [compatibility limits](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) before adopting this feature.146- **Zero Data Retention:** GPT-6.2 Astra and Sol support Zero Data Retention (ZDR) for approved organizations on eligible endpoints and features. With ZDR enabled, the Responses API treats `store` as `false`. For multi-turn work, pass the prior output items back in order, including encrypted reasoning items. See [Zero Data Retention](https://developers.openai.com/api/docs/guides/your-data#zero-data-retention) for eligibility and endpoint behavior.

178- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [prompt caching changes](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.147- **Service tiers and regions:** Both models support US and EU data residency with Standard, Fast, and Batch processing. Ultrafast supports US data residency only. See [data residency](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency) and [pricing](https://developers.openai.com/api/docs/pricing#text-tokens).

179- **Unnecessary approval pauses:** If you run into issues where the model keeps asking for approval before proceeding, use the [initiative and follow-through guidance](#initiative-and-follow-through) to prompt for more autonomous execution. See the rest of [Prompting best practices](#prompting-best-practices) for guidance on instruction following, writing style, subagent delegation, and testing.148- **Prompting:** See [**Prompting best practices**](#prompting-best-practices) for guidance.

Details

70client = OpenAI()70client = OpenAI()

71 71 

72completion = client.chat.completions.create(72completion = client.chat.completions.create(

73 model="gpt-6-astra",73 model="gpt-6.2-astra",

74 messages=[74 messages=[

75 {75 {

76 "role": "user",76 "role": "user",


87 87 

88client = OpenAI::Client.new88client = OpenAI::Client.new

89completion = client.chat.completions.create(89completion = client.chat.completions.create(

90 model: "gpt-6-astra",90 model: "gpt-6.2-astra",

91 messages: [91 messages: [

92 {92 {

93 role: :user,93 role: :user,


106client = OpenAI()106client = OpenAI()

107 107 

108response = client.responses.create(108response = client.responses.create(

109 model="gpt-6-astra",109 model="gpt-6.2-astra",

110 input="Write a one-sentence bedtime story about a unicorn.",110 input="Write a one-sentence bedtime story about a unicorn.",

111)111)

112 112 


118 118 

119client = OpenAI::Client.new119client = OpenAI::Client.new

120response = client.responses.create(120response = client.responses.create(

121 model: "gpt-6-astra",121 model: "gpt-6.2-astra",

122 input: "Write a one-sentence bedtime story about a unicorn."122 input: "Write a one-sentence bedtime story about a unicorn."

123)123)

124puts(response.output_text)124puts(response.output_text)


225];225];

226 226 

227const completion = await client.chat.completions.create({227const completion = await client.chat.completions.create({

228 model: "gpt-6-astra",228 model: "gpt-6.2-astra",

229 messages: context,229 messages: context,

230});230});

231 231 

232const response = await client.responses.create({232const response = await client.responses.create({

233 model: "gpt-6-astra",233 model: "gpt-6.2-astra",

234 input: context,234 input: context,

235});235});

236```236```


241 {"role": "user", "content": "Hello!"},241 {"role": "user", "content": "Hello!"},

242]242]

243 243 

244completion = client.chat.completions.create(model="gpt-6-astra", messages=context)244completion = client.chat.completions.create(model="gpt-6.2-astra", messages=context)

245 245 

246response = client.responses.create(model="gpt-6-astra", input=context)246response = client.responses.create(model="gpt-6.2-astra", input=context)

247```247```

248 248 

249```go249```go


261 client := openai.NewClient()261 client := openai.NewClient()

262 262 

263 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{263 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

264 Model: "gpt-6-astra",264 Model: "gpt-6.2-astra",

265 Messages: []openai.ChatCompletionMessageParamUnion{265 Messages: []openai.ChatCompletionMessageParamUnion{

266 openai.SystemMessage("You are a helpful assistant."),266 openai.SystemMessage("You are a helpful assistant."),

267 openai.UserMessage("Hello!"),267 openai.UserMessage("Hello!"),


273 fmt.Println(completion.Choices[0].Message.Content)273 fmt.Println(completion.Choices[0].Message.Content)

274 274 

275 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{275 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

276 Model: "gpt-6-astra",276 Model: "gpt-6.2-astra",

277 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{277 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

278 responses.ResponseInputItemParamOfMessage("You are a helpful assistant.", responses.EasyInputMessageRoleSystem),278 responses.ResponseInputItemParamOfMessage("You are a helpful assistant.", responses.EasyInputMessageRoleSystem),

279 responses.ResponseInputItemParamOfMessage("Hello!", responses.EasyInputMessageRoleUser),279 responses.ResponseInputItemParamOfMessage("Hello!", responses.EasyInputMessageRoleUser),


301 .completions()301 .completions()

302 .create(302 .create(

303 ChatCompletionCreateParams.builder()303 ChatCompletionCreateParams.builder()

304 .model("gpt-6-astra")304 .model("gpt-6.2-astra")

305 .addSystemMessage("You are a helpful assistant.")305 .addSystemMessage("You are a helpful assistant.")

306 .addUserMessage("Hello!")306 .addUserMessage("Hello!")

307 .build());307 .build());


314 .responses()314 .responses()

315 .create(315 .create(

316 ResponseCreateParams.builder()316 ResponseCreateParams.builder()

317 .model("gpt-6-astra")317 .model("gpt-6.2-astra")

318 .inputOfResponse(318 .inputOfResponse(

319 List.of(319 List.of(

320 ResponseInputItem.ofEasyInputMessage(320 ResponseInputItem.ofEasyInputMessage(


341#pragma warning disable OPENAI001341#pragma warning disable OPENAI001

342 342 

343string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;343string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

344string model = "gpt-6-astra";344string model = "gpt-6.2-astra";

345 345 

346ChatClient chat = new(model, key);346ChatClient chat = new(model, key);

347 347 


381]381]

382 382 

383completion = client.chat.completions.create(383completion = client.chat.completions.create(

384 model: "gpt-6-astra",384 model: "gpt-6.2-astra",

385 messages: messages385 messages: messages

386)386)

387puts(completion.choices.fetch(0).message.content)387puts(completion.choices.fetch(0).message.content)

388 388 

389response = client.responses.create(389response = client.responses.create(

390 model: "gpt-6-astra",390 model: "gpt-6.2-astra",

391 input: messages391 input: messages

392)392)

393puts(response.output_text)393puts(response.output_text)


403 -H "Content-Type: application/json" \403 -H "Content-Type: application/json" \

404 -H "Authorization: Bearer $OPENAI_API_KEY" \404 -H "Authorization: Bearer $OPENAI_API_KEY" \

405 -d "{405 -d "{

406 \"model\": \"gpt-6-astra\",406 \"model\": \"gpt-6.2-astra\",

407 \"messages\": $INPUT407 \"messages\": $INPUT

408 }"408 }"

409 409 


411 -H "Content-Type: application/json" \411 -H "Content-Type: application/json" \

412 -H "Authorization: Bearer $OPENAI_API_KEY" \412 -H "Authorization: Bearer $OPENAI_API_KEY" \

413 -d "{413 -d "{

414 \"model\": \"gpt-6-astra\",414 \"model\": \"gpt-6.2-astra\",

415 \"input\": $INPUT415 \"input\": $INPUT

416 }"416 }"

417```417```


430const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });430const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

431 431 

432const completion = await client.chat.completions.create({432const completion = await client.chat.completions.create({

433 model: "gpt-6-astra",433 model: "gpt-6.2-astra",

434 messages: [434 messages: [

435 { role: "system", content: "You are a helpful assistant." },435 { role: "system", content: "You are a helpful assistant." },

436 { role: "user", content: "Hello!" },436 { role: "user", content: "Hello!" },


445client = OpenAI()445client = OpenAI()

446 446 

447completion = client.chat.completions.create(447completion = client.chat.completions.create(

448 model="gpt-6-astra",448 model="gpt-6.2-astra",

449 messages=[449 messages=[

450 {"role": "system", "content": "You are a helpful assistant."},450 {"role": "system", "content": "You are a helpful assistant."},

451 {"role": "user", "content": "Hello!"},451 {"role": "user", "content": "Hello!"},


468 client := openai.NewClient()468 client := openai.NewClient()

469 469 

470 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{470 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

471 Model: "gpt-6-astra",471 Model: "gpt-6.2-astra",

472 Messages: []openai.ChatCompletionMessageParamUnion{472 Messages: []openai.ChatCompletionMessageParamUnion{

473 openai.SystemMessage("You are a helpful assistant."),473 openai.SystemMessage("You are a helpful assistant."),

474 openai.UserMessage("Hello!"),474 openai.UserMessage("Hello!"),


488 488 

489ChatCompletionCreateParams params =489ChatCompletionCreateParams params =

490 ChatCompletionCreateParams.builder()490 ChatCompletionCreateParams.builder()

491 .model("gpt-6-astra")491 .model("gpt-6.2-astra")

492 .addSystemMessage("You are a helpful assistant.")492 .addSystemMessage("You are a helpful assistant.")

493 .addUserMessage("Hello!")493 .addUserMessage("Hello!")

494 .build();494 .build();


502using OpenAI.Chat;502using OpenAI.Chat;

503 503 

504string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;504string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

505string model = "gpt-6-astra";505string model = "gpt-6.2-astra";

506ChatClient client = new(model, key);506ChatClient client = new(model, key);

507 507 

508ChatCompletion completion = await client.CompleteChatAsync(508ChatCompletion completion = await client.CompleteChatAsync(


521client = OpenAI::Client.new521client = OpenAI::Client.new

522 522 

523completion = client.chat.completions.create(523completion = client.chat.completions.create(

524 model: "gpt-6-astra",524 model: "gpt-6.2-astra",

525 messages: [525 messages: [

526 {526 {

527 role: :system,527 role: :system,


542 -H "Content-Type: application/json" \542 -H "Content-Type: application/json" \

543 -H "Authorization: Bearer $OPENAI_API_KEY" \543 -H "Authorization: Bearer $OPENAI_API_KEY" \

544 -d '{544 -d '{

545 "model": "gpt-6-astra",545 "model": "gpt-6.2-astra",

546 "messages": [546 "messages": [

547 {"role": "system", "content": "You are a helpful assistant."},547 {"role": "system", "content": "You are a helpful assistant."},

548 {"role": "user", "content": "Hello!"}548 {"role": "user", "content": "Hello!"}


567const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });567const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

568 568 

569const response = await client.responses.create({569const response = await client.responses.create({

570 model: "gpt-6-astra",570 model: "gpt-6.2-astra",

571 instructions: "You are a helpful assistant.",571 instructions: "You are a helpful assistant.",

572 input: "Hello!",572 input: "Hello!",

573});573});


581client = OpenAI()581client = OpenAI()

582 582 

583response = client.responses.create(583response = client.responses.create(

584 model="gpt-6-astra", instructions="You are a helpful assistant.", input="Hello!"584 model="gpt-6.2-astra", instructions="You are a helpful assistant.", input="Hello!"

585)585)

586print(response.output_text)586print(response.output_text)

587```587```


601 client := openai.NewClient()601 client := openai.NewClient()

602 602 

603 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{603 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

604 Model: "gpt-6-astra",604 Model: "gpt-6.2-astra",

605 Instructions: openai.String("You are a helpful assistant."),605 Instructions: openai.String("You are a helpful assistant."),

606 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello!")},606 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello!")},

607 })607 })


619 619 

620ResponseCreateParams params =620ResponseCreateParams params =

621 ResponseCreateParams.builder()621 ResponseCreateParams.builder()

622 .model("gpt-6-astra")622 .model("gpt-6.2-astra")

623 .input("Hello!")623 .input("Hello!")

624 .instructions("You are a helpful assistant.")624 .instructions("You are a helpful assistant.")

625 .build();625 .build();


640 640 

641CreateResponseOptions options = new()641CreateResponseOptions options = new()

642{642{

643 Model = "gpt-6-astra",643 Model = "gpt-6.2-astra",

644 Instructions = "You are a helpful assistant.",644 Instructions = "You are a helpful assistant.",

645};645};

646options.InputItems.Add(ResponseItem.CreateUserMessageItem("Hello!"));646options.InputItems.Add(ResponseItem.CreateUserMessageItem("Hello!"));


656client = OpenAI::Client.new656client = OpenAI::Client.new

657 657 

658response = client.responses.create(658response = client.responses.create(

659 model: "gpt-6-astra",659 model: "gpt-6.2-astra",

660 instructions: "You are a helpful assistant.",660 instructions: "You are a helpful assistant.",

661 input: "Hello!"661 input: "Hello!"

662)662)


669 -H "Content-Type: application/json" \669 -H "Content-Type: application/json" \

670 -H "Authorization: Bearer $OPENAI_API_KEY" \670 -H "Authorization: Bearer $OPENAI_API_KEY" \

671 -d '{671 -d '{

672 "model": "gpt-6-astra",672 "model": "gpt-6.2-astra",

673 "instructions": "You are a helpful assistant.",673 "instructions": "You are a helpful assistant.",

674 "input": "Hello!"674 "input": "Hello!"

675 }'675 }'


715 { role: "user", content: "What is the capital of France?" },715 { role: "user", content: "What is the capital of France?" },

716];716];

717const res1 = await client.chat.completions.create({717const res1 = await client.chat.completions.create({

718 model: "gpt-6-astra",718 model: "gpt-6.2-astra",

719 messages,719 messages,

720});720});

721 721 


723messages.push({ role: "user", content: "And its population?" });723messages.push({ role: "user", content: "And its population?" });

724 724 

725const res2 = await client.chat.completions.create({725const res2 = await client.chat.completions.create({

726 model: "gpt-6-astra",726 model: "gpt-6.2-astra",

727 messages,727 messages,

728});728});

729```729```


733 {"role": "system", "content": "You are a helpful assistant."},733 {"role": "system", "content": "You are a helpful assistant."},

734 {"role": "user", "content": "What is the capital of France?"},734 {"role": "user", "content": "What is the capital of France?"},

735]735]

736res1 = client.chat.completions.create(model="gpt-6-astra", messages=messages)736res1 = client.chat.completions.create(model="gpt-6.2-astra", messages=messages)

737 737 

738messages += [res1.choices[0].message]738messages += [res1.choices[0].message]

739messages += [{"role": "user", "content": "And its population?"}]739messages += [{"role": "user", "content": "And its population?"}]

740 740 

741res2 = client.chat.completions.create(model="gpt-6-astra", messages=messages)741res2 = client.chat.completions.create(model="gpt-6.2-astra", messages=messages)

742```742```

743 743 

744```go744```go


758 openai.UserMessage("What is the capital of France?"),758 openai.UserMessage("What is the capital of France?"),

759 }759 }

760 760 

761 first, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})761 first, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6.2-astra", Messages: messages})

762 if err != nil {762 if err != nil {

763 panic(err)763 panic(err)

764 }764 }

765 messages = append(messages, openai.AssistantMessage(first.Choices[0].Message.Content), openai.UserMessage("And its population?"))765 messages = append(messages, openai.AssistantMessage(first.Choices[0].Message.Content), openai.UserMessage("And its population?"))

766 766 

767 second, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})767 second, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6.2-astra", Messages: messages})

768 if err != nil {768 if err != nil {

769 panic(err)769 panic(err)

770 }770 }


779 779 

780var params =780var params =

781 ChatCompletionCreateParams.builder()781 ChatCompletionCreateParams.builder()

782 .model("gpt-6-astra")782 .model("gpt-6.2-astra")

783 .addSystemMessage("You are a helpful assistant.")783 .addSystemMessage("You are a helpful assistant.")

784 .addUserMessage("What is the capital of France?")784 .addUserMessage("What is the capital of France?")

785 .build();785 .build();


803using OpenAI.Chat;803using OpenAI.Chat;

804 804 

805string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;805string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

806string model = "gpt-6-astra";806string model = "gpt-6.2-astra";

807ChatClient client = new(model, key);807ChatClient client = new(model, key);

808 808 

809List<ChatMessage> messages =809List<ChatMessage> messages =


836]836]

837 837 

838first = client.chat.completions.create(838first = client.chat.completions.create(

839 model: "gpt-6-astra",839 model: "gpt-6.2-astra",

840 messages: messages840 messages: messages

841)841)

842messages << {842messages << {


849}849}

850 850 

851second = client.chat.completions.create(851second = client.chat.completions.create(

852 model: "gpt-6-astra",852 model: "gpt-6.2-astra",

853 messages: messages853 messages: messages

854)854)

855 855 


876];876];

877 877 

878const res1 = await client.responses.create({878const res1 = await client.responses.create({

879 model: "gpt-6-astra",879 model: "gpt-6.2-astra",

880 input: context,880 input: context,

881});881});

882 882 


887context.push({ role: "user", content: "And its population?" });887context.push({ role: "user", content: "And its population?" });

888 888 

889const res2 = await client.responses.create({889const res2 = await client.responses.create({

890 model: "gpt-6-astra",890 model: "gpt-6.2-astra",

891 input: context,891 input: context,

892});892});

893```893```


895```python895```python

896context = [{"role": "user", "content": "What is the capital of France?"}]896context = [{"role": "user", "content": "What is the capital of France?"}]

897res1 = client.responses.create(897res1 = client.responses.create(

898 model="gpt-6-astra",898 model="gpt-6.2-astra",

899 input=context,899 input=context,

900)900)

901 901 


906context += [{"role": "user", "content": "And its population?"}]906context += [{"role": "user", "content": "And its population?"}]

907 907 

908res2 = client.responses.create(908res2 = client.responses.create(

909 model="gpt-6-astra",909 model="gpt-6.2-astra",

910 input=context,910 input=context,

911)911)

912```912```


929 responses.ResponseInputItemParamOfMessage("What is the capital of France?", responses.EasyInputMessageRoleUser),929 responses.ResponseInputItemParamOfMessage("What is the capital of France?", responses.EasyInputMessageRoleUser),

930 }930 }

931 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{931 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

932 Model: "gpt-6-astra",932 Model: "gpt-6.2-astra",

933 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},933 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},

934 })934 })

935 if err != nil {935 if err != nil {


938 contextItems = append(contextItems, outputAsInput(first.Output)...)938 contextItems = append(contextItems, outputAsInput(first.Output)...)

939 contextItems = append(contextItems, responses.ResponseInputItemParamOfMessage("And its population?", responses.EasyInputMessageRoleUser))939 contextItems = append(contextItems, responses.ResponseInputItemParamOfMessage("And its population?", responses.EasyInputMessageRoleUser))

940 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{940 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

941 Model: "gpt-6-astra",941 Model: "gpt-6.2-astra",

942 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},942 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},

943 })943 })

944 if err != nil {944 if err != nil {


981 client981 client

982 .responses()982 .responses()

983 .create(983 .create(

984 ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build());984 ResponseCreateParams.builder().model("gpt-6.2-astra").inputOfResponse(history).build());

985first.output().stream()985first.output().stream()

986 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))986 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

987 .forEach(history::add);987 .forEach(history::add);


994 994 

995client995client

996 .responses()996 .responses()

997 .create(ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build())997 .create(ResponseCreateParams.builder().model("gpt-6.2-astra").inputOfResponse(history).build())

998 .output()998 .output()

999 .stream()999 .stream()

1000 .flatMap(item -> item.message().stream())1000 .flatMap(item -> item.message().stream())


1015 ResponseItem.CreateUserMessageItem("What is the capital of France?"),1015 ResponseItem.CreateUserMessageItem("What is the capital of France?"),

1016];1016];

1017 1017 

1018ResponseResult first = await client.CreateResponseAsync("gpt-6-astra", history);1018ResponseResult first = await client.CreateResponseAsync("gpt-6.2-astra", history);

1019history.AddRange(first.OutputItems);1019history.AddRange(first.OutputItems);

1020history.Add(ResponseItem.CreateUserMessageItem("And its population?"));1020history.Add(ResponseItem.CreateUserMessageItem("And its population?"));

1021 1021 

1022ResponseResult second = await client.CreateResponseAsync("gpt-6-astra", history);1022ResponseResult second = await client.CreateResponseAsync("gpt-6.2-astra", history);

1023Console.WriteLine(second.GetOutputText());1023Console.WriteLine(second.GetOutputText());

1024```1024```

1025 1025 


1035]1035]

1036 1036 

1037first = client.responses.create(1037first = client.responses.create(

1038 model: "gpt-6-astra",1038 model: "gpt-6.2-astra",

1039 input: context1039 input: context

1040)1040)

1041context.concat(first.output)1041context.concat(first.output)


1045}1045}

1046 1046 

1047second = client.responses.create(1047second = client.responses.create(

1048 model: "gpt-6-astra",1048 model: "gpt-6.2-astra",

1049 input: context1049 input: context

1050)1050)

1051 1051 


1058 1058 

1059```typescript1059```typescript

1060const res1 = await client.responses.create({1060const res1 = await client.responses.create({

1061 model: "gpt-6-astra",1061 model: "gpt-6.2-astra",

1062 input: "What is the capital of France?",1062 input: "What is the capital of France?",

1063 store: true,1063 store: true,

1064});1064});

1065 1065 

1066const res2 = await client.responses.create({1066const res2 = await client.responses.create({

1067 model: "gpt-6-astra",1067 model: "gpt-6.2-astra",

1068 input: "And its population?",1068 input: "And its population?",

1069 previous_response_id: res1.id,1069 previous_response_id: res1.id,

1070 store: true,1070 store: true,


1073 1073 

1074```python1074```python

1075res1 = client.responses.create(1075res1 = client.responses.create(

1076 model="gpt-6-astra", input="What is the capital of France?", store=True1076 model="gpt-6.2-astra", input="What is the capital of France?", store=True

1077)1077)

1078 1078 

1079res2 = client.responses.create(1079res2 = client.responses.create(

1080 model="gpt-6-astra",1080 model="gpt-6.2-astra",

1081 input="And its population?",1081 input="And its population?",

1082 previous_response_id=res1.id,1082 previous_response_id=res1.id,

1083 store=True,1083 store=True,


1099 client := openai.NewClient()1099 client := openai.NewClient()

1100 1100 

1101 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1101 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1102 Model: "gpt-6-astra",1102 Model: "gpt-6.2-astra",

1103 Store: openai.Bool(true),1103 Store: openai.Bool(true),

1104 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the capital of France?")},1104 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the capital of France?")},

1105 })1105 })


1108 }1108 }

1109 1109 

1110 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1110 second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1111 Model: "gpt-6-astra",1111 Model: "gpt-6.2-astra",

1112 Store: openai.Bool(true),1112 Store: openai.Bool(true),

1113 PreviousResponseID: openai.String(first.ID),1113 PreviousResponseID: openai.String(first.ID),

1114 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("And its population?")},1114 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("And its population?")},


1130 .responses()1130 .responses()

1131 .create(1131 .create(

1132 ResponseCreateParams.builder()1132 ResponseCreateParams.builder()

1133 .model("gpt-6-astra")1133 .model("gpt-6.2-astra")

1134 .input("What is the capital of France?")1134 .input("What is the capital of France?")

1135 .store(true)1135 .store(true)

1136 .build());1136 .build());


1140 .responses()1140 .responses()

1141 .create(1141 .create(

1142 ResponseCreateParams.builder()1142 ResponseCreateParams.builder()

1143 .model("gpt-6-astra")1143 .model("gpt-6.2-astra")

1144 .input("And its population?")1144 .input("And its population?")

1145 .previousResponseId(first.id())1145 .previousResponseId(first.id())

1146 .store(true)1146 .store(true)


1160ResponsesClient client = new(key);1160ResponsesClient client = new(key);

1161 1161 

1162ResponseResult first = await client.CreateResponseAsync(1162ResponseResult first = await client.CreateResponseAsync(

1163 "gpt-6-astra",1163 "gpt-6.2-astra",

1164 "What is the capital of France?"1164 "What is the capital of France?"

1165);1165);

1166ResponseResult second = await client.CreateResponseAsync(1166ResponseResult second = await client.CreateResponseAsync(

1167 "gpt-6-astra",1167 "gpt-6.2-astra",

1168 "And its population?",1168 "And its population?",

1169 previousResponseId: first.Id1169 previousResponseId: first.Id

1170);1170);


1178client = OpenAI::Client.new1178client = OpenAI::Client.new

1179 1179 

1180first = client.responses.create(1180first = client.responses.create(

1181 model: "gpt-6-astra",1181 model: "gpt-6.2-astra",

1182 input: "What is the capital of France?",1182 input: "What is the capital of France?",

1183 store: true1183 store: true

1184)1184)

1185 1185 

1186second = client.responses.create(1186second = client.responses.create(

1187 model: "gpt-6-astra",1187 model: "gpt-6.2-astra",

1188 previous_response_id: first.id,1188 previous_response_id: first.id,

1189 input: "And its population?",1189 input: "And its population?",

1190 store: true1190 store: true


1290 1290 

1291```typescript1291```typescript

1292const completion = await openai.chat.completions.create({1292const completion = await openai.chat.completions.create({

1293 model: "gpt-6-astra",1293 model: "gpt-6.2-astra",

1294 messages: [1294 messages: [

1295 {1295 {

1296 role: "user",1296 role: "user",


1330client = OpenAI()1330client = OpenAI()

1331 1331 

1332response = client.chat.completions.create(1332response = client.chat.completions.create(

1333 model="gpt-6-astra",1333 model="gpt-6.2-astra",

1334 messages=[1334 messages=[

1335 {1335 {

1336 "role": "user",1336 "role": "user",


1381 }1381 }

1382 1382 

1383 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{1383 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

1384 Model: "gpt-6-astra",1384 Model: "gpt-6.2-astra",

1385 ReasoningEffort: openai.ReasoningEffortMedium,1385 ReasoningEffort: openai.ReasoningEffortMedium,

1386 Messages: []openai.ChatCompletionMessageParamUnion{1386 Messages: []openai.ChatCompletionMessageParamUnion{

1387 openai.UserMessage("Jane, 54 years old"),1387 openai.UserMessage("Jane, 54 years old"),


1410 1410 

1411ChatCompletionCreateParams params =1411ChatCompletionCreateParams params =

1412 ChatCompletionCreateParams.builder()1412 ChatCompletionCreateParams.builder()

1413 .model("gpt-6-astra")1413 .model("gpt-6.2-astra")

1414 .reasoningEffort(ReasoningEffort.MEDIUM)1414 .reasoningEffort(ReasoningEffort.MEDIUM)

1415 .addUserMessage("Jane, 54 years old")1415 .addUserMessage("Jane, 54 years old")

1416 .putAdditionalBodyProperty(1416 .putAdditionalBodyProperty(


1451#pragma warning disable OPENAI0011451#pragma warning disable OPENAI001

1452 1452 

1453string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1453string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1454string model = "gpt-6-astra";1454string model = "gpt-6.2-astra";

1455ChatClient client = new(model, key);1455ChatClient client = new(model, key);

1456 1456 

1457BinaryData schema = BinaryData.FromString(1457BinaryData schema = BinaryData.FromString(


1507}1507}

1508 1508 

1509completion = client.chat.completions.create(1509completion = client.chat.completions.create(

1510 model: "gpt-6-astra",1510 model: "gpt-6.2-astra",

1511 reasoning_effort: :medium,1511 reasoning_effort: :medium,

1512 messages: [1512 messages: [

1513 {1513 {


1533 -H "Content-Type: application/json" \1533 -H "Content-Type: application/json" \

1534 -H "Authorization: Bearer $OPENAI_API_KEY" \1534 -H "Authorization: Bearer $OPENAI_API_KEY" \

1535 -d '{1535 -d '{

1536 "model": "gpt-6-astra",1536 "model": "gpt-6.2-astra",

1537 "messages": [1537 "messages": [

1538 {1538 {

1539 "role": "user",1539 "role": "user",


1581 1581 

1582```typescript1582```typescript

1583const response = await openai.responses.create({1583const response = await openai.responses.create({

1584 model: "gpt-6-astra",1584 model: "gpt-6.2-astra",

1585 input: "Jane, 54 years old",1585 input: "Jane, 54 years old",

1586 text: {1586 text: {

1587 format: {1587 format: {


1611 1611 

1612```python1612```python

1613response = client.responses.create(1613response = client.responses.create(

1614 model="gpt-6-astra",1614 model="gpt-6.2-astra",

1615 input="Jane, 54 years old",1615 input="Jane, 54 years old",

1616 text={1616 text={

1617 "format": {1617 "format": {


1656 }1656 }

1657 1657 

1658 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1658 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1659 Model: "gpt-6-astra",1659 Model: "gpt-6.2-astra",

1660 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Jane, 54 years old")},1660 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Jane, 54 years old")},

1661 Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{1661 Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{

1662 OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "person", Schema: schema, Strict: openai.Bool(true)},1662 OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "person", Schema: schema, Strict: openai.Bool(true)},


1681 1681 

1682ResponseCreateParams params =1682ResponseCreateParams params =

1683 ResponseCreateParams.builder()1683 ResponseCreateParams.builder()

1684 .model("gpt-6-astra")1684 .model("gpt-6.2-astra")

1685 .input("Jane, 54 years old")1685 .input("Jane, 54 years old")

1686 .text(1686 .text(

1687 ResponseTextConfig.builder()1687 ResponseTextConfig.builder()


1740);1740);

1741CreateResponseOptions options = new()1741CreateResponseOptions options = new()

1742{1742{

1743 Model = "gpt-6-astra",1743 Model = "gpt-6.2-astra",

1744 TextOptions = new ResponseTextOptions1744 TextOptions = new ResponseTextOptions

1745 {1745 {

1746 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(1746 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


1781}1781}

1782 1782 

1783response = client.responses.create(1783response = client.responses.create(

1784 model: "gpt-6-astra",1784 model: "gpt-6.2-astra",

1785 input: "Jane, 54 years old",1785 input: "Jane, 54 years old",

1786 text: {1786 text: {

1787 format: {1787 format: {


1801 -H "Content-Type: application/json" \1801 -H "Content-Type: application/json" \

1802 -H "Authorization: Bearer $OPENAI_API_KEY" \1802 -H "Authorization: Bearer $OPENAI_API_KEY" \

1803 -d '{1803 -d '{

1804 "model": "gpt-6-astra",1804 "model": "gpt-6.2-astra",

1805 "input": "Jane, 54 years old",1805 "input": "Jane, 54 years old",

1806 "text": {1806 "text": {

1807 "format": {1807 "format": {


2046 2046 

2047```typescript2047```typescript

2048const answer = await client.responses.create({2048const answer = await client.responses.create({

2049 model: "gpt-6-astra",2049 model: "gpt-6.2-astra",

2050 input: "Who is the current president of France?",2050 input: "Who is the current president of France?",

2051 tools: [{ type: "web_search" }],2051 tools: [{ type: "web_search" }],

2052});2052});


2056 2056 

2057```python2057```python

2058answer = client.responses.create(2058answer = client.responses.create(

2059 model="gpt-6-astra",2059 model="gpt-6.2-astra",

2060 input="Who is the current president of France?",2060 input="Who is the current president of France?",

2061 tools=[{"type": "web_search"}],2061 tools=[{"type": "web_search"}],

2062)2062)


2078func main() {2078func main() {

2079 client := openai.NewClient()2079 client := openai.NewClient()

2080 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2080 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2081 Model: "gpt-6-astra",2081 Model: "gpt-6.2-astra",

2082 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Who is the current president of France?")},2082 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Who is the current president of France?")},

2083 Tools: []responses.ToolUnionParam{2083 Tools: []responses.ToolUnionParam{

2084 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),2084 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),


2099 2099 

2100ResponseCreateParams params =2100ResponseCreateParams params =

2101 ResponseCreateParams.builder()2101 ResponseCreateParams.builder()

2102 .model("gpt-6-astra")2102 .model("gpt-6.2-astra")

2103 .input("Who is the current president of France?")2103 .input("Who is the current president of France?")

2104 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())2104 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

2105 .build();2105 .build();


2118string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;2118string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

2119ResponsesClient client = new(key);2119ResponsesClient client = new(key);

2120 2120 

2121CreateResponseOptions options = new() { Model = "gpt-6-astra" };2121CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

2122options.Tools.Add(ResponseTool.CreateWebSearchTool());2122options.Tools.Add(ResponseTool.CreateWebSearchTool());

2123options.InputItems.Add(2123options.InputItems.Add(

2124 ResponseItem.CreateUserMessageItem("Who is the current president of France?")2124 ResponseItem.CreateUserMessageItem("Who is the current president of France?")


2134client = OpenAI::Client.new2134client = OpenAI::Client.new

2135 2135 

2136response = client.responses.create(2136response = client.responses.create(

2137 model: "gpt-6-astra",2137 model: "gpt-6.2-astra",

2138 input: "Who is the current president of France?",2138 input: "Who is the current president of France?",

2139 tools: [{ type: :web_search }]2139 tools: [{ type: :web_search }]

2140)2140)


2147 -H "Content-Type: application/json" \2147 -H "Content-Type: application/json" \

2148 -H "Authorization: Bearer $OPENAI_API_KEY" \2148 -H "Authorization: Bearer $OPENAI_API_KEY" \

2149 -d '{2149 -d '{

2150 "model": "gpt-6-astra",2150 "model": "gpt-6.2-astra",

2151 "input": "Who is the current president of France?",2151 "input": "Who is the current president of France?",

2152 "tools": [{"type": "web_search"}]2152 "tools": [{"type": "web_search"}]

2153 }'2153 }'

Details

1---1---

2latestModelInfo:2latestModelInfo:

3 model: gpt-6-astra3 model: gpt-6.2-astra

4 migrationGuide: /api/docs/guides/latest-model/gpt-6-astra.md#migration-quickstart4 migrationGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#migration-quickstart

5 promptingGuide: /api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices5 promptingGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#prompting-best-practices

6---6---

7 7 

8# Using GPT-68# Using GPT-6.2

9 9 

10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

11 11 

12<a id="gpt-6-astra-gpt-6-astra"></a>12<a id="gpt-6.2-astra-gpt-62-astra-and-gpt-62-sol"></a>

13<a id="gpt-61-sol"></a>

14<a id="gpt-6.1-sol"></a>

15<a id="gpt-6-astra-gpt-61-sol"></a>

16<a id="gpt-61-terra"></a>

17<a id="gpt-6.1-terra"></a>

18<a id="gpt-6-astra-gpt-61-terra"></a>

19 13 

20Use GPT-6 Astra for the most demanding work, GPT-6.1 Sol for complex work at14Use [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra) for the most demanding tasks or [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol) for complex work at lower cost.

21lower cost, GPT-6.1 Terra for visual reasoning and writing, or GPT-6 Luna for

22focused, high-volume tasks. See [Model selection](https://developers.openai.com/api/docs/guides/model-selection)

23for a comparison.

24 

25<a id="gpt-6-astra-what-is-new" className="scroll-mt-[110px]"></a>

26 15 

27## What's new16## What's new

28 17 

29- **Async tool calling:** Supported models can continue reasoning, call other tools, or answer independent parts of a request while your application runs a tool. Set `async: true` on a function or custom tool and return its result when ready using the original `call_id`. Your application executes the tool and manages pending work. See [Async tool calling](https://developers.openai.com/api/docs/guides/async-tool-calling) for compatibility and examples.18Starting with GPT-6.2, the API will drop reasoning items when it detects mid-conversation changes to the conversation history (prefix edits), model downgrade, end user, or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to instructions or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

30- **Mid-turn steering:** Send additional user instructions while GPT-6 is working, such as a correction or a change in requirements. Over a WebSocket connection, the Responses API preserves completed work and includes the update in a continuation. See [Mid-turn steering](https://developers.openai.com/api/docs/guides/steering) for the event flow and tool-result handling.

31- **Change reasoning mid-conversation while preserving cache:** Add a `configuration_update` input item to increase reasoning effort for difficult work or reduce it for routine follow-ups without rewriting the original prompt prefix. The updated reasoning effort applies until another `configuration_update` input item overrides it. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility.

32- **Multi-agent and persisted reasoning on GPT-6.1 Sol:** Use the [Responses Multi-agent beta](https://developers.openai.com/api/docs/guides/responses-multi-agent) to delegate work to subagents. Set [`reasoning.context` to `all_turns`](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls) to reuse compatible reasoning from earlier turns.

33- **Misalignment monitoring:** As part of our [strengthened safeguards](https://openai.com/index/path-to-astra/) for GPT-6 Astra, our systems asynchronously monitor for misalignment and trigger alerts when necessary. See [Misalignment monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring) for more information.

34 

35GPT-6 also supports the existing API capabilities available with GPT-5.6, including [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [streaming](https://developers.openai.com/api/docs/guides/streaming-responses), [Programmatic Tool Calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling), [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [compaction](https://developers.openai.com/api/docs/guides/compaction), and [pro mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode).

36 

37## Limitations

38 

39- GPT-6 Astra and GPT-6.1 Sol do not support the `none` reasoning effort; GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna do.

40- Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. See [data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency).

41 19 

42<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>20<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

43 21 

44## Prompting best practices22## Prompting best practices

45 23 

46Use the following prompts as a starting point across the GPT-6 model family. They address behavior observed with GPT-6 Astra; evaluate them with your chosen model and workload.24Use the following prompts as a starting point across the GPT-6.2 model family. The examples address behaviors we’ve seen when working with GPT-6.2 Astra and Sol. If you recognize one in your own application, try the prompt in that section.

47 25 

48### GPT-6 Astra behavior26### GPT-6.2 Astra behavior

49 27 

50- [Initiative and follow-through](#initiative-and-follow-through): The model is designed to be a more effective collaborator and is thus more likely to ask the user a question when additional input could materially change the result. This can cause it to stop when the user may expect it to make reasonable assumptions and persist.28- **[Writing style](#writing-style).** The model’s writing tends to be more concise and direct by default. When migrating, revisit instructions like “be concise” in your system prompt.

51- [Instruction following](#instruction-following): GPT-6 Astra is stronger at general instruction following than our previous models, giving you greater control over its behavior. It can be more sensitive to instructions contained in skills and other files, such as `AGENTS.md`. We **strongly recommend** auditing skills and other files accessible to your model for instructions that could influence its behavior.29- **[Task completion](#task-completion).** When the user’s intent is unclear, the model may propose a next step and wait for confirmation. For longer tasks, give it room to make reasonable assumptions and keep working.

52- [Personality and writing style](#personality-and-writing-style): The model tends toward detailed, formatted responses and may use recurring phrases across sessions. Specify the writing style and structure your application needs.30- **[Coding style](#coding-style).** The model tends to write more efficient, high-quality code than its predecessors. Describe any project conventions that should guide how it writes or edits code.

53- [Subagent delegation](#subagent-delegation): The model may delegate less often than desired for your workflow. Specify when and how much it should use subagents for parallel work.31- **[Frontend design](#frontend-design).** If the interface needs a particular look, specify the imagery and typography it should use.

54- [Testing and verification](#testing-and-verification): For coding tasks, the model tends to be thorough in testing before considering a task complete. For smaller tasks, this can result in broader tests than the task requires.

55 32 

56### Initiative and follow-through33<a id="gpt-6.2-astra-prompt-patterns-for-api-applications"></a>

34<a id="gpt-6.2-astra-personality-and-writing-style"></a>

57 35 

58GPT-6 Astra is generally better than GPT-5.6 Sol and earlier models at staying coherent during long tasks. It is also more likely to ask for clarification where earlier models would make assumptions.36### Writing style

59 37 

60To encourage more autonomous work, start with this prompt:38GPT-6.2 Astra is more concise and direct by default than earlier models. Its tone can be tuned to suit the application, from a professional colleague to a more conversational assistant.

61 39 

62```text40Use the following prompt if you want to use the model as a collaborator and thought partner for day to day work.

63You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.

64 41 

65When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.42```text

43Write using terminology the user and sources use. Keep technical details and use domain-specific language when they make the explanation more precise. Use the active voice and keep closely related details together. Cover the key points up front, and avoid references that the reader can only make sense of later in the response. Give the user enough context to follow your reasoning.

66```44```

67 45 

68When the user’s intent is unclear, the model is more likely to ask the user for clarification to proceed. Prompt the model to follow through if the user’s prompt implies authorization:46Prompt the model to adapt to the audience it is drafting material for, such as writing in documents, emails, messages and external posts.

69 47 

70```text48```text

71When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.49When drafting a message or any other material on behalf of the user to be sent to an external audience, consider who will read it and tailor the content to that intended audience. The intended audience likely does not have the same context as the user, so ensure that you provide the background information or reasoning required for the audience to understand the content. When reviewing or editing existing content, preserve the author’s content and wording, and follow the user's instruction carefully for what edits they want.

72```50```

73 51 

74Prompt the model to ask for approval only after preparing a concrete, reviewable result. This avoids blocking the task before the model has done the work it can, and often leads to quicker task completion.52During longer tasks, the model can carry shorthand from its reasoning or from other agents into its final answer. Remind it to write a self-contained response that’s clear to someone who hasn’t followed the progress updates.

75 53 

76```text54```text

77Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.55Treat your final answer as the user's first look at your work, and not as a continuation of intermediate commentary. The final answer must always be fully self-contained: users should never need to read earlier commentary updates for context, since they are collapsed when the final answer is shown to the user.

78 56 

79Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.57Write the final answer and all other human-facing material anew for the intended reader. Do not copy or closely paraphrase your reasoning or adopt its writing style. Do not carry over working shorthand, jargon, or abbreviations from your reasoning, tool calls, or instructions to subagents and automations.

80```58```

81 59 

82The model also likes to ask non-blocking questions as it’s working by default, so adjust these prompts to match the level of autonomy your application needs.60<a id="gpt-6.2-astra-initiative-and-follow-through"></a>

61<a id="gpt-6.2-astra-subagent-delegation"></a>

83 62 

84### Instruction following63### Task completion

85 64 

86GPT-6 Astra is better able to follow longer instructions, but can also be more sensitive to information in context. For example, unclear or conflicting guidance in a skill file may cause the model to pause and block work early. Make the priority of user instructions and skills explicit.65For work that can proceed without supervision, specify the outcome the model should complete and which decisions need the user’s input.

87 66 

88```text67```text

89The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.68Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. If your final response before ending the turn is a suggested next step, a plan, a request to the user for a routine decision, instructions for a task to execute, or similar handoff to the user, take these steps yourself to make progress towards what the user asked for. Make sure that you have authorization to do so, and flag any assumptions or decisions you maketo the user.

90```

91 

92Asking the model to identify the skill and instruction that caused it to pause or change direction can also be effective in providing transparency into model behavior.

93 69 

94```text70Only stop to clarify with the user if there is significant change in task scope, you are concretely blocked, have a decision that the user needs to resolve, or before irreversible or destructive actions.

95If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.

96```71```

97 72 

98Use this prompt to find silent and conflicting guidance when your application loads many skills and instruction files such as `AGENTS.md`.73<a id="gpt-6.2-astra-testing-and-verification"></a>

74<a id="gpt-6.2-astra-ask-for-an-exhaustive-pass"></a>

99 75 

100### Personality and writing style76Ask the model to verify that it has completed the requested work. Higher reasoning effort can help it persist through the final checks on complex or long-running tasks. In the Responses API, set the level with `reasoning.effort`. [Reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort)

101 

102GPT-6 Astra tends to use lists, tables and Markdown to make responses scannable. If your application needs prose with less formatting, specify that preference.

103 77 

104```text78```text

105Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.79Bias towards action, and persist until you've completed the task the user asked for. Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. Make sure that you have accounted for every part of the user's request, and persist until you've delivered a result that fully satisfies the user's goal. If a task requires sustained work, do all the necessary work until the intended outcome is completely fulfilled.

106 80 

107Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.81Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, creating draft PRs etc) unless they are clearly destructive or irreversible. Before ending a turn or calling your work complete, check that your work fully satisfies what the user asked for. If any steps remain or any part of the result still needs verification, follow through on this work before finishing.

108```82```

109 83 

110For technical communication, the following prompt helps strike a balance between using clear, coherent language while remaining domain appropriate:84<a id="gpt-6.2-astra-instruction-following"></a>

85<a id="gpt-6.2-astra-intent-understanding"></a>

86<a id="gpt-6.2-astra-interpreting-ambiguous-requests"></a>

111 87 

112```text88When a detail is unclear, give the model room to state what it’s assuming and continue with the task.

113Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.

114```

115 

116To reduce jargon and stock phrases in writing, start with this prompt:

117 89 

118```text90```text

119Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".91Make reasonable, reversible assumptions to carry work forward and state them if it progresses the task within scope. Do not second guess yourself, stop after describing what you could do, offer to do the work, or provide a partial answer unless there is no way you can proceed.

120 

121State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.

122```92```

123 93 

124### Subagent delegation94With an async tool such as `request_user_input_async` in your application, GPT-6.2 can ask the user for clarification and continue work that doesn’t depend on the answer. [Add an async question tool](https://developers.openai.com/api/docs/guides/async-tool-calling#add-a-tool-to-ask-the-user-for-input)

125 95 

126GPT-6 Astra is trained to be able to divide and delegate work to subagents that work in parallel. If you are implementing a multi-agent system in your harness, use the following prompt to tune how much GPT-6 Astra should delegate work:96<a id="gpt-6.2-astra-code-changes"></a>

127 97 

128```text98### Coding style

129If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.

130```

131 99 

132Messages between agents may contain grammar or spacing errors. Use this prompt to make inter-agent messages easier to read:100Describe the codebase’s conventions and any behavior that existing callers rely on. For example, specify when to reuse existing logic, how narrowly to scope a change, and when to add a test for behavior the existing suite doesn’t cover.

133 101 

134```text102```text

135Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.103Above all, be thorough in producing high-quality, correct code that completely fulfills the user's task. Keep the code easy to read and verify that the user-requested outcome works as they intend. Follow these instructions when coding:

104 

105(a) Reuse existing logic in the user's repo when you can. You should reuse existing classes, methods, representations, and APIs in the codebase as long as they preserve correctness. Before consolidating or removing code, preserve the behavior its callers rely on unless the task requires changing it.

106(b) Skip new tests unless requested, required by the repo, or needed to catch a specific regression existing tests would miss.

107(c) Make sure that code is human readable. Do not use fewer lines, shorter variable names, minified formatting, or dense one-liners as substitutes for simplicity. Ensure that comments and variable names are readable and understandable to a human. Code-golfed expressions count as overly complex when they encode many branches, conditions, or hidden assumptions.

108(d) Avoid unnecessary indirection and abstraction. Helper functions, utility functions, and class abstractions can add cognitive complexity even when they do not add branches.

136```109```

137 110 

138The model tends to respond well to prompting for how and when it should delegate work to subagents, so tune this behavior to fit with your harness and multi-agent implementation.111<a id="gpt-6.2-astra-visual-review"></a>

112<a id="gpt-6.2-astra-visual-work-and-frontend-design"></a>

139 113 

140### Testing and verification114### Frontend design

141 115 

142For coding tasks, calibrate how much testing and verification a change requires. This can help avoid unnecessary tests or repeated checks for small changes.116If the application depends on a specific visual style, describe it in the prompt. Specify the kinds of images it should use and the typography it should follow, including a particular typeface when that matters. Keep interface copy focused on what people need to know or do.

143 117 

144```text118```text

145Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.119When generating webpages or apps with a frontend user interface, follow these instructions:

146 120 

147Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.121- When choosing visuals, generally prefer realistic images from ImageGen or image search that suit the project's style and purpose. Use SVGs when the user specifically asks for them.

122- Include a text element only when it provides information the user needs, helps them navigate or act, or fulfills an explicit content request. Remove decorative numbering, filler badges, redundant headings, and explanatory copy that merely restates what the surrounding interface already makes clear, while preserving necessary labels, instructions, and status feedback.

148```123```

149 124 

150## Migration quickstart125For visual work, share a reference from your design software, or give GPT-6.2 access to the [image generation tool](https://developers.openai.com/api/docs/guides/tools-image-generation) and ask it to create one with GPT Image. A reference can enrich your prompt with details that are hard to describe in words. Once it captures the look you want, ask the model to build the asset, render it, and refine it against the reference.

151 126 

152### Migrate with Codex127## Migration quickstart

153 128 

154Codex can apply the recommended changes in this guide with the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).129<a id="gpt-6.2-astra-migrate-with-codex"></a>

155 130 

156```text131To migrate an API application to GPT-6.2 Astra with a coding agent, use the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).

157$openai-docs migrate this project to the GPT-6 model family

158```

159 132 

160To use this skill in other coding agents, download it from the [Codex repository](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).133<a id="gpt-6.2-astra-choose-a-reasoning-effort"></a>

134<a id="gpt-6.2-astra-zdr-data-residency-and-service-tiers"></a>

135<a id="gpt-6.2-astra-limitations"></a>

136<a id="gpt-6.2-astra-data-residency-and-service-tiers"></a>

161 137 

162### Update API and model parameters138### Update API and model parameters

163 139 

164Set `model` to `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, or `gpt-6-luna`, then review the compatibility checks below.140Set `model` to `gpt-6.2-astra` or `gpt-6.2-sol`, then check the following:

165 

166If you're switching from `gpt-6-sol` to `gpt-6.1-sol`, use `low` if your

167current reasoning effort is `none`. Move any Chat Completions requests that

168call functions to the Responses API.

169 

170When moving from GPT-5.6 Terra to GPT-6.1 Terra, compare both models on

171representative images and workflows at the same reasoning effort.

172 141 

173- **Reasoning effort:** Preserve your current effective [reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort) where supported. GPT-6 Astra and GPT-6.1 Sol do not support `none`; use `low` instead. GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support `none`. If your existing request uses `minimal`, start with `low` and compare results on representative tasks. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.142- **Reasoning effort:** Start with `medium` for a new integration. If you currently use `none` or `minimal`, use `low` instead. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.

174- **Tool calling:** Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6 Astra, GPT-6.1 Sol, and GPT-6.1 Terra support Chat Completions, but tool calling requires Responses. GPT-6 Sol and GPT-6 Luna support function calling in Chat Completions only with `reasoning_effort: "none"`. Use Responses for reasoning with tools.143- **Tool calling:** Use the [**Responses API**](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6.2 Astra and GPT-6.2 Sol support Chat Completions, but tool calling requires Responses.

175- **Unsupported parameters:** When reasoning effort is not `none`, remove `temperature`, `top_p`, and `top_logprobs`. For Chat Completions, also remove `logprobs`. For Responses, remove `message.output_text.logprobs` from `include`.144- **Unsupported parameters:** When migrating Chat Completions requests, omit `temperature`, `top_p`, `logprobs`, and `top_logprobs`. For Responses requests, omit `temperature`, `top_p`, and `top_logprobs` and remove `message.output_text.logprobs` from `include`.

176- **Data residency:** Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. Fast mode for GPT-6 Astra does not include a latency SLA. See [Fast mode compatibility](https://developers.openai.com/api/docs/guides/fast-mode#is-fast-mode-compatible-with-data-residency-zero-data-retention-and-a-baa).145- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [**prompt caching changes**](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.

177- **Changing reasoning effort:** If your application changes effort between responses, use `configuration_update` items in standard, single-agent requests. Keep request-level `reasoning.effort` unchanged to preserve the prompt prefix for caching. Check the [compatibility limits](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) before adopting this feature.146- **Zero Data Retention:** GPT-6.2 Astra and Sol support Zero Data Retention (ZDR) for approved organizations on eligible endpoints and features. With ZDR enabled, the Responses API treats `store` as `false`. For multi-turn work, pass the prior output items back in order, including encrypted reasoning items. See [Zero Data Retention](https://developers.openai.com/api/docs/guides/your-data#zero-data-retention) for eligibility and endpoint behavior.

178- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [prompt caching changes](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.147- **Service tiers and regions:** Both models support US and EU data residency with Standard, Fast, and Batch processing. Ultrafast supports US data residency only. See [data residency](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency) and [pricing](https://developers.openai.com/api/docs/pricing#text-tokens).

179- **Unnecessary approval pauses:** If you run into issues where the model keeps asking for approval before proceeding, use the [initiative and follow-through guidance](#initiative-and-follow-through) to prompt for more autonomous execution. See the rest of [Prompting best practices](#prompting-best-practices) for guidance on instruction following, writing style, subagent delegation, and testing.148- **Prompting:** See [**Prompting best practices**](#prompting-best-practices) for guidance.

Details

46With evals in place, you can effectively iterate on [prompts](https://developers.openai.com/api/docs/guides/text). The prompt engineering process may be all you need in order to get great results for your use case. Different models may require different prompting techniques, but there are several best practices you can apply across the board to get better results.46With evals in place, you can effectively iterate on [prompts](https://developers.openai.com/api/docs/guides/text). The prompt engineering process may be all you need in order to get great results for your use case. Different models may require different prompting techniques, but there are several best practices you can apply across the board to get better results.

47 47 

48- **Include relevant context** - in your instructions, include text or image content that the model will need to generate a response from outside its training data. This could include data from private databases or current, up-to-the-minute information.48- **Include relevant context** - in your instructions, include text or image content that the model will need to generate a response from outside its training data. This could include data from private databases or current, up-to-the-minute information.

49- **Provide clear instructions** - your prompt should contain clear goals about what kind of output you want. Start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) for new work, and use [reasoning model guidance](https://developers.openai.com/api/docs/guides/reasoning) to tune outcome-level instructions, reasoning effort, and verbosity.49- **Provide clear instructions** - your prompt should contain clear goals about what kind of output you want. Start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) for new work, and use [reasoning model guidance](https://developers.openai.com/api/docs/guides/reasoning) to tune outcome-level instructions, reasoning effort, and verbosity.

50- **Provide example outputs** - give the model a few examples of correct output for a given prompt (a process called few-shot learning). The model can extrapolate from these examples how it should respond for other prompts.50- **Provide example outputs** - give the model a few examples of correct output for a given prompt (a process called few-shot learning). The model can extrapolate from these examples how it should respond for other prompts.

51 51 

52[Learn about prompt engineering](https://developers.openai.com/api/docs/guides/text)52[Learn about prompt engineering](https://developers.openai.com/api/docs/guides/text)

Details

10 10 

11## Find the right model for your workflow11## Find the right model for your workflow

12 12 

13Choose your work and task and get a recommendation.13Choose a task and a priority to see a suggested model and reasoning effort.

14 14 

15### When to consider GPT-6.1 Terra15## How to think about models and reasoning effort

16 16 

17Try [GPT-6.1 Terra](https://developers.openai.com/api/docs/models/gpt-6.1-terra) for concise writing based on

18supplied material, computer-use tasks with a defined outcome, and scoped code

19fixes. Provide clear inputs, requirements, and a way to verify the result, such as

20checking saved records or running regression tests.

21 17 

22Compare it with GPT-6.1 Sol on the same inputs and reasoning effort. For writing,

23judge audience fit, voice, and useful detail as well as accuracy and length. For

24computer use, check the saved result and the accuracy of the completion report.

25 18 

26### When to consider GPT-6.1 Sol19 To reduce costs or latency, start with the lightest setting that meets your

20 acceptance criteria. Compare the API cost per completed task, including

21 retries.

27 22 

28Consider GPT-6.1 Sol for complex projects where cost matters, such as

29creating a board presentation from financial results or building a website

30from a product brief. Compare it with Astra on the same task to assess the

31tradeoff between quality and cost.

32 23 

33See the [API model page](https://developers.openai.com/api/docs/models/gpt-6.1-sol) for specifications

34and API pricing, or [Codex and ChatGPT Work availability](https://developers.openai.com/codex/models#gpt-6.1-sol)

35for access through your ChatGPT plan.

36 24 

37## How to think about models and reasoning effort

38 25 

39 26 

271. **GPT-6 Luna · Low**

40 28 

41 Luna is the most cost-efficient model, while Astra is our state-of-the-art,29 Making small edits to files and extracting fields when the expected result is clear.

42 most powerful model. If cost and latency aren't a concern, you can default to

43 Astra. To reduce costs or latency, use the guidance below to choose a model

44 and reasoning effort for your needs.

45 30 

312. **GPT-6 Luna · Extra high**

46 32 

33 Finding updates across apps, prioritizing follow-ups, and solving problems with clear constraints.

47 34 

353. **GPT-6.1 Terra · Medium**

48 36 

37 Navigating desktop apps, updating records, and making focused fixes you can verify.

49 38 

501. **Luna · Low**394. **GPT-6.2 Sol · Medium**

51 40 

52 Fine-grained edits, well-scoped problem-solving, and simple data extraction.41 Fixing bugs and adding features in an existing codebase, or drafting documents for review.

53 42 

542. **Luna · Extra high**435. **GPT-6.2 Sol · Extra high**

55 44 

56 Finding current context across multiple apps, prioritizing work, and solving problems with clear constraints.45 Working through multistep tasks that need testing and revision along the way.

57 46 

583. **GPT-6.1 Sol · Medium**476. **GPT-6.2 Astra · Low**

59 48 

60 Complex technical work and coordinated deliverables you expect to revise.49 Turning a clear brief into polished work that's ready to use.

61 50 

624. **GPT-6.1 Sol · Extra high**517. **GPT-6.2 Astra · Medium**

63 52 

64 Polished deliverables, connected visual systems, and decisions built from conflicting evidence.53 Planning and carrying out complex projects, adjusting the approach as new information comes in.

65 54 

665. **Astra · Low**558. **GPT-6.2 Astra · Extra high**

67 56 

68 Concise writing and content adaptation that preserve facts and nuance.57 Solving open-ended problems that require weighing trade-offs and testing assumptions.

69 58 

706. **Astra · Medium**59**Model strengths**

71 60 

72 Ambitious projects that need broad context, reliable interactions, and complete results.61Farther from the center means a stronger fit for that type of work. The ratings are high-level estimates based on benchmarks, independently run task examples, and user feedback.

73 62 

747. **Astra · Extra high**63Models ordered by estimated fit for each type of work

75 64 

76 Demanding analysis and complex deliverables with exacting requirements.65| Type of work | Models from strongest fit to weakest fit |

66| --- | --- |

67| 3D and design | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

68| Software engineering | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

69| Data analysis | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

70| Creating deliverables | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

71| Computer use | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

72| Research decisions | GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna |

77 73 

78### Experiment74### Experiment

79 75 

Details

37const client = new OpenAI();37const client = new OpenAI();

38 38 

39const response = await client.responses.create({39const response = await client.responses.create({

40 model: "gpt-6-astra",40 model: "gpt-6.2-astra",

41 input: [41 input: [

42 {42 {

43 role: "user",43 role: "user",


71client = OpenAI()71client = OpenAI()

72 72 

73response = client.responses.create(73response = client.responses.create(

74 model="gpt-6-astra",74 model="gpt-6.2-astra",

75 input=[75 input=[

76 {76 {

77 "role": "user",77 "role": "user",


111 client := openai.NewClient()111 client := openai.NewClient()

112 112 

113 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{113 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

114 Model: "gpt-6-astra",114 Model: "gpt-6.2-astra",

115 Input: responses.ResponseNewParamsInputUnion{115 Input: responses.ResponseNewParamsInputUnion{

116 OfString: openai.String("A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative."),116 OfString: openai.String("A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative."),

117 },117 },


153 153 

154ResponseCreateParams params =154ResponseCreateParams params =

155 ResponseCreateParams.builder()155 ResponseCreateParams.builder()

156 .model("gpt-6-astra")156 .model("gpt-6.2-astra")

157 .input(157 .input(

158 "A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative.")158 "A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative.")

159 .putAdditionalBodyProperty(159 .putAdditionalBodyProperty(


195client = OpenAI::Client.new195client = OpenAI::Client.new

196 196 

197response = client.responses.create(197response = client.responses.create(

198 model: "gpt-6-astra",198 model: "gpt-6.2-astra",

199 input: "A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative.",199 input: "A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative.",

200 moderation: { model: "omni-moderation-latest" }200 moderation: { model: "omni-moderation-latest" }

201)201)

Details

20export default User;20export default User;

21```21```

22 22 

23```ruby

24class User

25 attr_accessor :first_name, :last_name, :username

26 

27 def initialize

28 @first_name = ""

29 @last_name = ""

30 @username = ""

31 end

32end

33```

34 

23 35 

24Most of the file will be unchanged, except for line 4 above. If you use the current text of the code file as your prediction, you can regenerate the entire file with lower latency. These time savings add up quickly for larger files.36Most of the file will be unchanged, except for line 4 above. If you use the current text of the code file as your prediction, you can regenerate the entire file with lower latency. These time savings add up quickly for larger files.

25 37 


601});613});

602```614```

603 615 

616```ruby

617require "webrick"

618 

619server = WEBrick::HTTPServer.new(Port: Integer(ENV.fetch("PORT", "3000")), BindAddress: "127.0.0.1")

620# Build your client first and place its static files in dist/.

621static_files = WEBrick::HTTPServlet::FileHandler.new(server, File.expand_path("dist"))

622server.mount_proc("/") do |request, response|

623 response["Content-Type"] = "text/plain"

624 if !%w[GET HEAD].include?(request.request_method)

625 response.status = 404

626 response.body = "404 Not Found"

627 elsif request.path == "/api"

628 response.body = "Hello Hono!"

629 else

630 begin

631 static_files.service(request, response)

632 rescue WEBrick::HTTPStatus::NotFound

633 response.status = 404

634 response.body = "404 Not Found"

635 end

636 end

637end

638trap("INT") { server.shutdown }

639trap("TERM") { server.shutdown }

640server.start

641```

642 

604 643 

605You could prompt the model to regenerate the file with a prompt like:644You could prompt the model to regenerate the file with a prompt like:

606 645 


645});684});

646```685```

647 686 

687```ruby

688require "webrick"

689 

690server = WEBrick::HTTPServer.new(Port: Integer(ENV.fetch("PORT", "3000")), BindAddress: "127.0.0.1")

691# Build your client first and place its static files in dist/.

692static_files = WEBrick::HTTPServlet::FileHandler.new(server, File.expand_path("dist"))

693server.mount_proc("/") do |request, response|

694 response["Content-Type"] = "text/plain"

695 if !%w[GET HEAD].include?(request.request_method)

696 response.status = 404

697 response.body = "404 Not Found"

698 elsif request.path == "/api"

699 response.body = "Hello Hono!"

700 elsif request.path == "/hello"

701 response.body = "hello world"

702 else

703 begin

704 static_files.service(request, response)

705 rescue WEBrick::HTTPStatus::NotFound

706 response.status = 404

707 response.body = "404 Not Found"

708 end

709 end

710end

711trap("INT") { server.shutdown }

712trap("TERM") { server.shutdown }

713server.start

714```

715 

648 716 

649An abridged model response without the `choices` field would still show accepted prediction tokens, even though the prediction text appeared both before and after the new content added to the response:717An abridged model response without the `choices` field would still show accepted prediction tokens, even though the prediction text appeared both before and after the new content added to the response:

650 718 

Details

576Define group OpenAICSGProduction as ocid1.group.oc1..aaaaaaaanuot5i5kooasr6qh6qo4ohqljrrxx3javkl2tkedb7ljsluq62sa576Define group OpenAICSGProduction as ocid1.group.oc1..aaaaaaaanuot5i5kooasr6qh6qo4ohqljrrxx3javkl2tkedb7ljsluq62sa

577Admit group OpenAICSGProduction of tenancy OpenAICSG to {OBJECTSTORAGE_NAMESPACE_READ} in tenancy577Admit group OpenAICSGProduction of tenancy OpenAICSG to {OBJECTSTORAGE_NAMESPACE_READ} in tenancy

578Admit group OpenAICSGProduction of tenancy OpenAICSG to {BUCKET_READ} in tenancy where target.bucket.name = 'CUSTOMER_BUCKET_NAME'578Admit group OpenAICSGProduction of tenancy OpenAICSG to {BUCKET_READ} in tenancy where target.bucket.name = 'CUSTOMER_BUCKET_NAME'

579Admit group OpenAICSGProduction of tenancy OpenAICSG to {OBJECT_READ, OBJECT_CREATE, OBJECT_OVERWRITE} in tenancy where all {target.bucket.name = 'CUSTOMER_BUCKET_NAME', target.object.name = 'openai/CUSTOMER_ORG_ID/CUSTOMER_PROJECT_ID/*'}579Admit group OpenAICSGProduction of tenancy OpenAICSG to {OBJECT_READ, OBJECT_CREATE, OBJECT_OVERWRITE, OBJECT_DELETE} in tenancy where all {target.bucket.name = 'CUSTOMER_BUCKET_NAME', target.object.name = 'openai/CUSTOMER_ORG_ID/CUSTOMER_PROJECT_ID/*'}

580Allow service objectstorage-CUSTOMER_OCI_REGION to {BUCKET_INSPECT, BUCKET_READ, OBJECT_INSPECT, OBJECT_DELETE} in tenancy where target.bucket.name = 'CUSTOMER_BUCKET_NAME'580Allow service objectstorage-CUSTOMER_OCI_REGION to {BUCKET_INSPECT, BUCKET_READ, OBJECT_INSPECT, OBJECT_DELETE} in tenancy where target.bucket.name = 'CUSTOMER_BUCKET_NAME'

581```581```

582 582 

Details

123 123 

124#### Model124#### Model

125 125 

126Our API offers different models with varying levels of complexity and generality. The most capable models, such as `gpt-6-astra`, can generate more complex and diverse completions, but they also take longer to process your query.126Our API offers different models with varying levels of complexity and generality. The most capable models, such as `gpt-6.2-astra`, can generate more complex and diverse completions, but they also take longer to process your query.

127Models such as `gpt-5.6-terra` and `gpt-5.6-luna` can generate faster and cheaper Responses, while `gpt-6-astra` is a stronger default when you want more headroom on complex tasks. You can choose the model that best suits your use case and the trade-off between speed, cost, and quality.127Models such as `gpt-6.1-terra` and `gpt-6-luna` can generate faster and cheaper Responses, while `gpt-6.2-astra` is a stronger default when you want more headroom on complex tasks. You can choose the model that best suits your use case and the trade-off between speed, cost, and quality.

128 128 

129#### Number of completion tokens129#### Number of completion tokens

130 130 

Details

76 76 

77 77 

78 78 

79For GPT-5.6 and later, cache writes cost 1.25× the standard, uncached input-token rate for the default 30-minute lifetime. In the Responses API, you can choose a [12-hour minimum lifetime](#cache-lifetime) at a write rate of 2.5× ordinary input. Subsequent reads cost 0.1× the ordinary input rate on most of these models and 0.05× on [GPT-6.1 Sol](https://developers.openai.com/api/docs/models/gpt-6.1-sol) and [GPT-6.1 Terra](https://developers.openai.com/api/docs/models/gpt-6.1-terra), regardless of the selected lifetime.79For GPT-5.6 and later, cache writes cost 1.25× the standard, uncached input-token rate for the default 30-minute lifetime. In the Responses API, you can choose a [12-hour minimum lifetime](#cache-lifetime) at a write rate of 2.5× ordinary input. Subsequent reads cost 0.1× the ordinary input rate on most of these models and 0.05× on [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra), [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol), [GPT-6.1 Sol](https://developers.openai.com/api/docs/models/gpt-6.1-sol), and [GPT-6.1 Terra](https://developers.openai.com/api/docs/models/gpt-6.1-terra), regardless of the selected lifetime.

80 80 

81At the 0.1× read rate with 30-minute writes, writing a prefix once and fully reusing it once costs 1.35× its ordinary input cost, compared with 2× for processing it twice without caching. Across ten requests, one write and nine full reads cost 2.15× at that rate, compared with 10× without caching.81At the 0.1× read rate with 30-minute writes, writing a prefix once and fully reusing it once costs 1.35× its ordinary input cost, compared with 2× for processing it twice without caching. Across ten requests, one write and nine full reads cost 2.15× at that rate, compared with 10× without caching.

82 82 


166 166 

167```json167```json

168{168{

169 "model": "gpt-6.1-sol",169 "model": "gpt-6.2-sol",

170 "prompt_cache_options": { "mode": "explicit", "ttl": "30m" },170 "prompt_cache_options": { "mode": "explicit", "ttl": "30m" },

171 "input": [171 "input": [

172 {172 {


296## Summary of model differences296## Summary of model differences

297 297 

298| Behavior | GPT-5.6 and later | GPT-5.5 and GPT-5.5 Pro | Other earlier models |298| Behavior | GPT-5.6 and later | GPT-5.5 and GPT-5.5 Pro | Other earlier models |

299| -------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------- |299| -------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------------------------------------- |

300| Implicit breakpoints | At the end of the latest eligible message. | Spaced at regular 2,048-token intervals. | Spaced at regular, model-dependent intervals. |300| Implicit breakpoints | At the end of the latest eligible message. | Spaced at regular 2,048-token intervals. | Spaced at regular, model-dependent intervals. |

301| Explicit breakpoints | Supported | Not supported | Not supported |301| Explicit breakpoints | Supported | Not supported | Not supported |

302| `prompt_cache_key` | Optional for separate cache accounting | Use a stable key to optimize cache routing | Use a stable key to optimize cache routing |302| `prompt_cache_key` | Optional for separate cache accounting | Use a stable key to optimize cache routing | Use a stable key to optimize cache routing |

303| Minimum cacheable prefix | 1,024 visible input tokens | Varies by request settings | Varies by request settings |303| Minimum cacheable prefix | 1,024 visible input tokens | Varies by request settings | Varies by request settings |

304| Cached-token reporting | Exact eligible boundary, excluding hidden tokens | Excludes hidden tokens and rounds down to a multiple of 128 | Excludes hidden tokens and rounds down to a multiple of 128 |304| Cached-token reporting | Exact eligible boundary, excluding hidden tokens | Excludes hidden tokens and rounds down to a multiple of 128 | Excludes hidden tokens and rounds down to a multiple of 128 |

305| Cache read charge | 0.1× uncached input (0.05× for GPT-6.1 Sol and GPT-6.1 Terra) | Model-dependent cached-input rate | Model-dependent cached-input rate |305| Cache read charge | 0.1× uncached input (0.05× for GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol, and GPT-6.1 Terra) | Model-dependent cached-input rate | Model-dependent cached-input rate |

306| Cache write charge | 1.25× for `"30m"`; 2.5× for `"12h"` in the Responses API | No additional cache-write charge | No additional cache-write charge |306| Cache write charge | 1.25× for `"30m"`; 2.5× for `"12h"` in the Responses API | No additional cache-write charge | No additional cache-write charge |

307| Cache lifetime control | `prompt_cache_options.ttl` | `prompt_cache_retention` | `prompt_cache_retention` |307| Cache lifetime control | `prompt_cache_options.ttl` | `prompt_cache_retention` | `prompt_cache_retention` |

308| Supported retention values | `"30m"` (default), or `"12h"` in the Responses API | `"24h"` only | `"in_memory"` or `"24h"`<sup>[\*](#extended-retention-models)</sup> |308| Supported retention values | `"30m"` (default), or `"12h"` in the Responses API | `"24h"` only | `"in_memory"` or `"24h"`<sup>[\*](#extended-retention-models)</sup> |


344 344 

345- **Keep the prefix stable.** Put stable developer instructions and shared reference material first. If developer instructions or shared material contain timestamps, user-specific content, or other dynamic content, place those at the end rather than the beginning, or move them into later conversation messages.345- **Keep the prefix stable.** Put stable developer instructions and shared reference material first. If developer instructions or shared material contain timestamps, user-specific content, or other dynamic content, place those at the end rather than the beginning, or move them into later conversation messages.

346- **Preserve conversation history.** Append new messages rather than rewriting earlier turns. Summarization, [compaction](#compaction-can-reduce-cache-reuse), or context truncation can change the prefix and reset cache reuse.346- **Preserve conversation history.** Append new messages rather than rewriting earlier turns. Summarization, [compaction](#compaction-can-reduce-cache-reuse), or context truncation can change the prefix and reset cache reuse.

347- **Change reasoning effort without rewriting the prefix.** On GPT-6 models, append a `configuration_update` input item to change reasoning effort between responses while keeping request-level `reasoning.effort` unchanged. This preserves the original prefix for cache reuse. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility limits.347- **Change reasoning effort without rewriting the prefix.** On supported models, append a `configuration_update` input item to change reasoning effort between responses while keeping request-level `reasoning.effort` unchanged. This preserves the original prefix for cache reuse. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility limits.

348 348 

349Keep changing content after the breakpoint349Keep changing content after the breakpoint

350 350 

351```json351```json

352{352{

353 "model": "gpt-6.1-sol",353 "model": "gpt-6.2-sol",

354 "reasoning": { "effort": "low", "context": "all_turns" },354 "reasoning": { "effort": "low", "context": "all_turns" },

355 "text": { "verbosity": "medium" },355 "text": { "verbosity": "medium" },

356 "prompt_cache_options": { "mode": "explicit" },356 "prompt_cache_options": { "mode": "explicit" },


477 477 

478```json478```json

479{479{

480 "model": "gpt-6.1-sol",480 "model": "gpt-6.2-sol",

481 "input": [481 "input": [

482 {482 {

483 "role": "developer",483 "role": "developer",


495 495 

496```json496```json

497{497{

498 "model": "gpt-6.1-sol",498 "model": "gpt-6.2-sol",

499 "input": [499 "input": [

500 {500 {

501 "role": "developer",501 "role": "developer",


794 794 

795```json795```json

796{796{

797 "model": "gpt-6.1-sol",797 "model": "gpt-6.2-sol",

798 "reasoning": { "effort": "medium", "context": "all_turns" },798 "reasoning": { "effort": "medium", "context": "all_turns" },

799 "text": { "verbosity": "low" },799 "text": { "verbosity": "low" },

800 "prompt_cache_options": { "mode": "explicit" },800 "prompt_cache_options": { "mode": "explicit" },


845 845 

846```json846```json

847{847{

848 "model": "gpt-6.1-sol",848 "model": "gpt-6.2-sol",

849 "reasoning": { "effort": "medium", "context": "all_turns" },849 "reasoning": { "effort": "medium", "context": "all_turns" },

850 "text": { "verbosity": "medium" },850 "text": { "verbosity": "medium" },

851 "prompt_cache_key": "agent_123_v1:user_456",851 "prompt_cache_key": "agent_123_v1:user_456",


914 914 

915```json915```json

916{916{

917 "model": "gpt-6.1-sol",917 "model": "gpt-6.2-sol",

918 "reasoning": { "effort": "medium", "context": "all_turns" },918 "reasoning": { "effort": "medium", "context": "all_turns" },

919 "text": { "verbosity": "low" },919 "text": { "verbosity": "low" },

920 "prompt_cache_options": { "mode": "implicit" },920 "prompt_cache_options": { "mode": "implicit" },


932 932 

933```json933```json

934{934{

935 "model": "gpt-6.1-sol",935 "model": "gpt-6.2-sol",

936 "reasoning": { "effort": "medium", "context": "all_turns" },936 "reasoning": { "effort": "medium", "context": "all_turns" },

937 "text": { "verbosity": "low" },937 "text": { "verbosity": "low" },

938 "prompt_cache_options": { "mode": "explicit" },938 "prompt_cache_options": { "mode": "explicit" },

Details

56 print(diagnostics.cache_missed_tokens)56 print(diagnostics.cache_missed_tokens)

57```57```

58 58 

59```ruby

60require "openai"

61 

62client = OpenAI::Client.new

63policy = File.read("support-policy.txt") # At least 1,024 tokens.

64 

65first = client.responses.create(

66 model: "gpt-6-astra",

67 instructions: policy,

68 input: "Reply with exactly OK.",

69 tools: [

70 {

71 type: :function,

72 name: "get_time"

73 }

74 ]

75)

76 

77second = client.responses.create(

78 model: "gpt-6-astra",

79 instructions: policy,

80 input: "Reply with exactly OK.",

81 tools: [

82 {

83 type: :function,

84 name: "get_date"

85 }

86 ],

87 prompt_cache_options: { comparison_response_id: first.id }

88)

89 

90diagnostics = second.prompt_cache_diagnostics

91if diagnostics.is_a?(OpenAI::Models::Responses::Response::PromptCacheDiagnostics::CacheMiss)

92 puts(diagnostics.reason)

93 puts(diagnostics.comparison_reusable_tokens)

94 puts(diagnostics.cache_missed_tokens)

95end

96```

97 

59 98 

60If the tool change causes a miss, the result may look like this. Token counts vary with the input.99If the tool change causes a miss, the result may look like this. Token counts vary with the input.

61 100 

Details

15const client = new OpenAI();15const client = new OpenAI();

16 16 

17const response = await client.responses.create({17const response = await client.responses.create({

18 model: "gpt-6-astra",18 model: "gpt-6.2-astra",

19 input: "Write a one-sentence bedtime story about a unicorn.",19 input: "Write a one-sentence bedtime story about a unicorn.",

20});20});

21 21 


28client = OpenAI()28client = OpenAI()

29 29 

30response = client.responses.create(30response = client.responses.create(

31 model="gpt-6-astra",31 model="gpt-6.2-astra",

32 input="Write a one-sentence bedtime story about a unicorn.",32 input="Write a one-sentence bedtime story about a unicorn.",

33)33)

34 34 


50 client := openai.NewClient()50 client := openai.NewClient()

51 51 

52 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{52 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

53 Model: "gpt-6-astra",53 Model: "gpt-6.2-astra",

54 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},54 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

55 })55 })

56 if err != nil {56 if err != nil {


72 OpenAIClient client = OpenAIOkHttpClient.fromEnv();72 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

73 73 

74 ResponseCreateParams params =74 ResponseCreateParams params =

75 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();75 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();

76 76 

77 Response response = client.responses().create(params);77 Response response = client.responses().create(params);

78 response.output().stream()78 response.output().stream()


92ResponsesClient client = new(key);92ResponsesClient client = new(key);

93 93 

94ResponseResult response = await client.CreateResponseAsync(94ResponseResult response = await client.CreateResponseAsync(

95 "gpt-6-astra",95 "gpt-6.2-astra",

96 "Say 'this is a test.'"96 "Say 'this is a test.'"

97);97);

98 98 


105openai = OpenAI::Client.new105openai = OpenAI::Client.new

106 106 

107response = openai.responses.create(107response = openai.responses.create(

108 model: "gpt-6-astra",108 model: "gpt-6.2-astra",

109 input: "Write a one-sentence bedtime story about a unicorn."109 input: "Write a one-sentence bedtime story about a unicorn."

110)110)

111 111 


114 114 

115```bash115```bash

116openai responses create \116openai responses create \

117 --model "gpt-6-astra" \117 --model "gpt-6.2-astra" \

118 --input "Write a one-sentence bedtime story about a unicorn." \118 --input "Write a one-sentence bedtime story about a unicorn." \

119 --raw-output \119 --raw-output \

120 --transform 'output.#(type=="message").content.0.text'120 --transform 'output.#(type=="message").content.0.text'


125 -H "Content-Type: application/json" \125 -H "Content-Type: application/json" \

126 -H "Authorization: Bearer $OPENAI_API_KEY" \126 -H "Authorization: Bearer $OPENAI_API_KEY" \

127 -d '{127 -d '{

128 "model": "gpt-6-astra",128 "model": "gpt-6.2-astra",

129 "input": "Write a one-sentence bedtime story about a unicorn."129 "input": "Write a one-sentence bedtime story about a unicorn."

130 }'130 }'

131```131```


169- **GPT models** are fast, cost-efficient, and highly intelligent, but benefit from more explicit instructions around how to accomplish tasks.169- **GPT models** are fast, cost-efficient, and highly intelligent, but benefit from more explicit instructions around how to accomplish tasks.

170- **Large and small (mini or nano) models** offer trade-offs for speed, cost, and intelligence. Large models are more effective at understanding prompts and solving problems across domains, while small models are generally faster and cheaper to use.170- **Large and small (mini or nano) models** offer trade-offs for speed, cost, and intelligence. Large models are more effective at understanding prompts and solving problems across domains, while small models are generally faster and cheaper to use.

171 171 

172When in doubt, [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) offers a strong default for general-purpose text generation and prompt iteration.172When in doubt, [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) offers a strong default for general-purpose text generation and prompt iteration.

173 173 

174## Prompt engineering174## Prompt engineering

175 175 


199const client = new OpenAI();199const client = new OpenAI();

200 200 

201const response = await client.responses.create({201const response = await client.responses.create({

202 model: "gpt-6-astra",202 model: "gpt-6.2-astra",

203 reasoning: { effort: "low" },203 reasoning: { effort: "low" },

204 instructions: "Talk like a pirate.",204 instructions: "Talk like a pirate.",

205 input: "Are semicolons optional in JavaScript?",205 input: "Are semicolons optional in JavaScript?",


214client = OpenAI()214client = OpenAI()

215 215 

216response = client.responses.create(216response = client.responses.create(

217 model="gpt-6-astra",217 model="gpt-6.2-astra",

218 reasoning={"effort": "low"},218 reasoning={"effort": "low"},

219 instructions="Talk like a pirate.",219 instructions="Talk like a pirate.",

220 input="Are semicolons optional in JavaScript?",220 input="Are semicolons optional in JavaScript?",


238 client := openai.NewClient()238 client := openai.NewClient()

239 239 

240 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{240 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

241 Model: "gpt-6-astra",241 Model: "gpt-6.2-astra",

242 Instructions: openai.String("Talk like a pirate."),242 Instructions: openai.String("Talk like a pirate."),

243 Reasoning: responses.ReasoningParam{243 Reasoning: responses.ReasoningParam{

244 Effort: responses.ReasoningEffortLow,244 Effort: responses.ReasoningEffortLow,


268 268 

269ResponseCreateParams params =269ResponseCreateParams params =

270 ResponseCreateParams.builder()270 ResponseCreateParams.builder()

271 .model("gpt-6-astra")271 .model("gpt-6.2-astra")

272 .input(semicolonsPrompt)272 .input(semicolonsPrompt)

273 .instructions(semicolonsDevMsg)273 .instructions(semicolonsDevMsg)

274 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())274 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())


290 290 

291CreateResponseOptions options = new()291CreateResponseOptions options = new()

292{292{

293 Model = "gpt-6-astra",293 Model = "gpt-6.2-astra",

294 Instructions = "Talk like a pirate.",294 Instructions = "Talk like a pirate.",

295 ReasoningOptions = new ResponseReasoningOptions295 ReasoningOptions = new ResponseReasoningOptions

296 {296 {


311 311 

312client = OpenAI::Client.new312client = OpenAI::Client.new

313response = client.responses.create(313response = client.responses.create(

314 model: "gpt-6-astra",314 model: "gpt-6.2-astra",

315 instructions: "Talk like a pirate.",315 instructions: "Talk like a pirate.",

316 reasoning: { effort: :low },316 reasoning: { effort: :low },

317 input: "Are semicolons optional in JavaScript?"317 input: "Are semicolons optional in JavaScript?"


325 -H "Content-Type: application/json" \325 -H "Content-Type: application/json" \

326 -H "Authorization: Bearer $OPENAI_API_KEY" \326 -H "Authorization: Bearer $OPENAI_API_KEY" \

327 -d '{327 -d '{

328 "model": "gpt-6-astra",328 "model": "gpt-6.2-astra",

329 "reasoning": {"effort": "low"},329 "reasoning": {"effort": "low"},

330 "instructions": "Talk like a pirate.",330 "instructions": "Talk like a pirate.",

331 "input": "Are semicolons optional in JavaScript?"331 "input": "Are semicolons optional in JavaScript?"


342const client = new OpenAI();342const client = new OpenAI();

343 343 

344const response = await client.responses.create({344const response = await client.responses.create({

345 model: "gpt-6-astra",345 model: "gpt-6.2-astra",

346 reasoning: { effort: "low" },346 reasoning: { effort: "low" },

347 input: [347 input: [

348 {348 {


365client = OpenAI()365client = OpenAI()

366 366 

367response = client.responses.create(367response = client.responses.create(

368 model="gpt-6-astra",368 model="gpt-6.2-astra",

369 reasoning={"effort": "low"},369 reasoning={"effort": "low"},

370 input=[370 input=[

371 {"role": "developer", "content": "Talk like a pirate."},371 {"role": "developer", "content": "Talk like a pirate."},


391 client := openai.NewClient()391 client := openai.NewClient()

392 392 

393 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{393 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

394 Model: "gpt-6-astra",394 Model: "gpt-6.2-astra",

395 Reasoning: responses.ReasoningParam{395 Reasoning: responses.ReasoningParam{

396 Effort: responses.ReasoningEffortLow,396 Effort: responses.ReasoningEffortLow,

397 },397 },


432 432 

433ResponseCreateParams params =433ResponseCreateParams params =

434 ResponseCreateParams.builder()434 ResponseCreateParams.builder()

435 .model("gpt-6-astra")435 .model("gpt-6.2-astra")

436 .input(436 .input(

437 ResponseCreateParams.Input.ofResponse(437 ResponseCreateParams.Input.ofResponse(

438 List.of(438 List.of(


465 465 

466CreateResponseOptions options = new()466CreateResponseOptions options = new()

467{467{

468 Model = "gpt-6-astra",468 Model = "gpt-6.2-astra",

469 ReasoningOptions = new ResponseReasoningOptions469 ReasoningOptions = new ResponseReasoningOptions

470 {470 {

471 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,471 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,


488 488 

489client = OpenAI::Client.new489client = OpenAI::Client.new

490response = client.responses.create(490response = client.responses.create(

491 model: "gpt-6-astra",491 model: "gpt-6.2-astra",

492 reasoning: { effort: :low },492 reasoning: { effort: :low },

493 input: [493 input: [

494 {494 {


510 -H "Content-Type: application/json" \510 -H "Content-Type: application/json" \

511 -H "Authorization: Bearer $OPENAI_API_KEY" \511 -H "Authorization: Bearer $OPENAI_API_KEY" \

512 -d '{512 -d '{

513 "model": "gpt-6-astra",513 "model": "gpt-6.2-astra",

514 "reasoning": {"effort": "low"},514 "reasoning": {"effort": "low"},

515 "input": [515 "input": [

516 {516 {


630const instructions = await fs.readFile("fixtures/prompt.txt", "utf-8");630const instructions = await fs.readFile("fixtures/prompt.txt", "utf-8");

631 631 

632const response = await client.responses.create({632const response = await client.responses.create({

633 model: "gpt-6-astra",633 model: "gpt-6.2-astra",

634 instructions,634 instructions,

635 input: "How would I declare a variable for a last name?",635 input: "How would I declare a variable for a last name?",

636});636});


647 instructions = f.read()647 instructions = f.read()

648 648 

649response = client.responses.create(649response = client.responses.create(

650 model="gpt-6-astra",650 model="gpt-6.2-astra",

651 instructions=instructions,651 instructions=instructions,

652 input="How would I declare a variable for a last name?",652 input="How would I declare a variable for a last name?",

653)653)


676 }676 }

677 677 

678 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{678 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

679 Model: "gpt-6-astra",679 Model: "gpt-6.2-astra",

680 Instructions: openai.String(string(instructions)),680 Instructions: openai.String(string(instructions)),

681 Input: responses.ResponseNewParamsInputUnion{681 Input: responses.ResponseNewParamsInputUnion{

682 OfString: openai.String("How would I declare a variable for a last name?"),682 OfString: openai.String("How would I declare a variable for a last name?"),


697 697 

698ResponseCreateParams params =698ResponseCreateParams params =

699 ResponseCreateParams.builder()699 ResponseCreateParams.builder()

700 .model("gpt-6-astra")700 .model("gpt-6.2-astra")

701 .instructions(701 .instructions(

702 "You are a coding assistant. Answer with concise JavaScript examples and use semicolons.")702 "You are a coding assistant. Answer with concise JavaScript examples and use semicolons.")

703 .input("How would I declare a variable for a last name?")703 .input("How would I declare a variable for a last name?")


720string instructions = await File.ReadAllTextAsync("prompt.txt");720string instructions = await File.ReadAllTextAsync("prompt.txt");

721CreateResponseOptions options = new()721CreateResponseOptions options = new()

722{722{

723 Model = "gpt-6-astra",723 Model = "gpt-6.2-astra",

724 Instructions = instructions,724 Instructions = instructions,

725};725};

726options.InputItems.Add(726options.InputItems.Add(


737client = OpenAI::Client.new737client = OpenAI::Client.new

738instructions = File.read(File.join(__dir__, "prompt.txt"))738instructions = File.read(File.join(__dir__, "prompt.txt"))

739response = client.responses.create(739response = client.responses.create(

740 model: "gpt-6-astra",740 model: "gpt-6.2-astra",

741 instructions: instructions,741 instructions: instructions,

742 input: "How would I declare a variable for a last name?"742 input: "How would I declare a variable for a last name?"

743)743)


750 -H "Authorization: Bearer $OPENAI_API_KEY" \750 -H "Authorization: Bearer $OPENAI_API_KEY" \

751 -H "Content-Type: application/json" \751 -H "Content-Type: application/json" \

752 -d '{752 -d '{

753 "model": "gpt-6-astra",753 "model": "gpt-6.2-astra",

754 "instructions": "'"$(< prompt.txt)"'",754 "instructions": "'"$(< prompt.txt)"'",

755 "input": "How would I declare a variable for a last name?"755 "input": "How would I declare a variable for a last name?"

756 }'756 }'


829 829 

830## Prompting current models830## Prompting current models

831 831 

832GPT models like [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) benefit from precise instructions that explicitly provide the logic and data required to complete the task in the prompt. To get the most out of the latest model, start with the current prompting guide.832GPT models like [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) benefit from precise instructions that explicitly provide the logic and data required to complete the task in the prompt. To get the most out of the latest model, start with the current prompting guide.

833 833 

834[](https://developers.openai.com/api/docs/guides/latest-model)834[](https://developers.openai.com/api/docs/guides/latest-model)

835 835 


852 852 

853#### Coding853#### Coding

854 854 

855Prompting `gpt-6-astra` for coding tasks is most effective when following a few best practices: define the agent's role, enforce structured tool use with examples, require thorough testing for correctness, and set Markdown standards for clean output.855Prompting `gpt-6.2-astra` for coding tasks is most effective when following a few best practices: define the agent's role, enforce structured tool use with examples, require thorough testing for correctness, and set Markdown standards for clean output.

856 856 

857**Explicit role and workflow guidance**857**Explicit role and workflow guidance**

858Frame the model as a software engineering agent with well-defined responsibilities. Provide clear instructions for using tools like `functions.run` for code tasks, and specify when not to use certain modes—for example, avoid interactive execution unless necessary.858Frame the model as a software engineering agent with well-defined responsibilities. Provide clear instructions for using tools like `functions.run` for code tasks, and specify when not to use certain modes—for example, avoid interactive execution unless necessary.


878 878 

879 879 

880 880 

881[GPT-6 Astra](https://developers.openai.com/api/docs/models/gpt-6-astra)881[GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra)

882performs well at building front ends from scratch as well as contributing to882performs well at building front ends from scratch as well as contributing to

883large, established codebases. To get the best results, we recommend using the883large, established codebases. To get the best results, we recommend using the

884following libraries:884following libraries:


924 924 

925 925 

926 926 

927For agentic and long-running tasks with `gpt-6-astra`, ask the model to plan the work from start to finish, explain major tool calls before making them, and track progress with a task list tool.927For agentic and long-running tasks with `gpt-6.2-astra`, ask the model to plan the work from start to finish, explain major tool calls before making them, and track progress with a task list tool.

928 928 

929**Planning and persistence**929**Planning and persistence**

930Instruct the model to resolve the full query before yielding control, decomposing it into sub-tasks and reflecting after each tool call to confirm completeness.930Instruct the model to resolve the full query before yielding control, decomposing it into sub-tasks and reflecting after each tool call to confirm completeness.

Details

78 78 

79async function generatePrompt(taskOrPrompt: string) {79async function generatePrompt(taskOrPrompt: string) {

80 const completion = await client.chat.completions.create({80 const completion = await client.chat.completions.create({

81 model: "gpt-6-astra",81 model: "gpt-6.2-astra",

82 messages: [82 messages: [

83 { role: "system", content: metaPrompt },83 { role: "system", content: metaPrompt },

84 {84 {


150 150 

151def generate_prompt(task_or_prompt: str):151def generate_prompt(task_or_prompt: str):

152 completion = client.chat.completions.create(152 completion = client.chat.completions.create(

153 model="gpt-6-astra",153 model="gpt-6.2-astra",

154 messages=[154 messages=[

155 {155 {

156 "role": "system",156 "role": "system",


227 "\n" +227 "\n" +

228 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"228 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"

229 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{229 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

230 Model: "gpt-6-astra",230 Model: "gpt-6.2-astra",

231 Messages: []openai.ChatCompletionMessageParamUnion{231 Messages: []openai.ChatCompletionMessageParamUnion{

232 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),232 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

233 }})233 }})


294 294 

295ChatCompletionCreateParams params =295ChatCompletionCreateParams params =

296 ChatCompletionCreateParams.builder()296 ChatCompletionCreateParams.builder()

297 .model("gpt-6-astra")297 .model("gpt-6.2-astra")

298 .addSystemMessage(metaPrompt)298 .addSystemMessage(metaPrompt)

299 .addUserMessage(299 .addUserMessage(

300 "Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")300 "Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")


309using OpenAI.Chat;309using OpenAI.Chat;

310 310 

311string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;311string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

312string model = "gpt-6-astra";312string model = "gpt-6.2-astra";

313ChatClient client = new(model, key);313ChatClient client = new(model, key);

314 314 

315string metaPrompt = """"315string metaPrompt = """"


414 414 

415def generate_prompt(client, meta_prompt, task_or_prompt)415def generate_prompt(client, meta_prompt, task_or_prompt)

416 completion = client.chat.completions.create(416 completion = client.chat.completions.create(

417 model: "gpt-6-astra",417 model: "gpt-6.2-astra",

418 messages: [418 messages: [

419 {419 {

420 role: :system,420 role: :system,


484 484 

485async function generatePrompt(taskOrPrompt: string) {485async function generatePrompt(taskOrPrompt: string) {

486 const completion = await client.chat.completions.create({486 const completion = await client.chat.completions.create({

487 model: "gpt-6-astra",487 model: "gpt-6.2-astra",

488 messages: [488 messages: [

489 { role: "system", content: metaPrompt },489 { role: "system", content: metaPrompt },

490 {490 {


547 547 

548def generate_prompt(task_or_prompt: str):548def generate_prompt(task_or_prompt: str):

549 completion = client.chat.completions.create(549 completion = client.chat.completions.create(

550 model="gpt-6-astra",550 model="gpt-6.2-astra",

551 messages=[551 messages=[

552 {552 {

553 "role": "system",553 "role": "system",


615 "\n" +615 "\n" +

616 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"616 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"

617 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{617 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

618 Model: "gpt-6-astra",618 Model: "gpt-6.2-astra",

619 Messages: []openai.ChatCompletionMessageParamUnion{619 Messages: []openai.ChatCompletionMessageParamUnion{

620 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),620 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

621 }})621 }})


673 673 

674ChatCompletionCreateParams params =674ChatCompletionCreateParams params =

675 ChatCompletionCreateParams.builder()675 ChatCompletionCreateParams.builder()

676 .model("gpt-6-astra")676 .model("gpt-6.2-astra")

677 .addSystemMessage(metaPrompt)677 .addSystemMessage(metaPrompt)

678 .addUserMessage(678 .addUserMessage(

679 "Task, Goal, or Current Prompt:\n"679 "Task, Goal, or Current Prompt:\n"


689using OpenAI.Chat;689using OpenAI.Chat;

690 690 

691string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;691string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

692string model = "gpt-6-astra";692string model = "gpt-6.2-astra";

693ChatClient client = new(model, key);693ChatClient client = new(model, key);

694 694 

695string metaPrompt = """"695string metaPrompt = """"


776 776 

777def generate_prompt(client, meta_prompt, task_or_prompt)777def generate_prompt(client, meta_prompt, task_or_prompt)

778 completion = client.chat.completions.create(778 completion = client.chat.completions.create(

779 model: "gpt-6-astra",779 model: "gpt-6.2-astra",

780 messages: [780 messages: [

781 {781 {

782 role: :system,782 role: :system,


877 877 

878async function generatePrompt(taskOrPrompt: string) {878async function generatePrompt(taskOrPrompt: string) {

879 const completion = await client.chat.completions.create({879 const completion = await client.chat.completions.create({

880 model: "gpt-6-astra",880 model: "gpt-6.2-astra",

881 messages: [881 messages: [

882 { role: "system", content: metaPrompt },882 { role: "system", content: metaPrompt },

883 {883 {


968 968 

969def generate_prompt(task_or_prompt: str):969def generate_prompt(task_or_prompt: str):

970 completion = client.chat.completions.create(970 completion = client.chat.completions.create(

971 model="gpt-6-astra",971 model="gpt-6.2-astra",

972 messages=[972 messages=[

973 {973 {

974 "role": "system",974 "role": "system",


1064 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +1064 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +

1065 "[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"1065 "[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"

1066 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{1066 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

1067 Model: "gpt-6-astra",1067 Model: "gpt-6.2-astra",

1068 Messages: []openai.ChatCompletionMessageParamUnion{1068 Messages: []openai.ChatCompletionMessageParamUnion{

1069 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),1069 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

1070 }})1070 }})


1150 1150 

1151ChatCompletionCreateParams params =1151ChatCompletionCreateParams params =

1152 ChatCompletionCreateParams.builder()1152 ChatCompletionCreateParams.builder()

1153 .model("gpt-6-astra")1153 .model("gpt-6.2-astra")

1154 .addSystemMessage(metaPrompt)1154 .addSystemMessage(metaPrompt)

1155 .addUserMessage(1155 .addUserMessage(

1156 "Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")1156 "Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")


1165using OpenAI.Chat;1165using OpenAI.Chat;

1166 1166 

1167string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1167string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1168string model = "gpt-6-astra";1168string model = "gpt-6.2-astra";

1169ChatClient client = new(model, key);1169ChatClient client = new(model, key);

1170 1170 

1171string metaPrompt = """"1171string metaPrompt = """"


1308 1308 

1309def generate_prompt(client, meta_prompt, task_or_prompt)1309def generate_prompt(client, meta_prompt, task_or_prompt)

1310 completion = client.chat.completions.create(1310 completion = client.chat.completions.create(

1311 model: "gpt-6-astra",1311 model: "gpt-6.2-astra",

1312 messages: [1312 messages: [

1313 {1313 {

1314 role: :system,1314 role: :system,


1397 1397 

1398async function generatePrompt(taskOrPrompt: string) {1398async function generatePrompt(taskOrPrompt: string) {

1399 const completion = await client.chat.completions.create({1399 const completion = await client.chat.completions.create({

1400 model: "gpt-6-astra",1400 model: "gpt-6.2-astra",

1401 messages: [1401 messages: [

1402 { role: "system", content: metaPrompt },1402 { role: "system", content: metaPrompt },

1403 {1403 {


1481 1481 

1482def generate_prompt(task_or_prompt: str):1482def generate_prompt(task_or_prompt: str):

1483 completion = client.chat.completions.create(1483 completion = client.chat.completions.create(

1484 model="gpt-6-astra",1484 model="gpt-6.2-astra",

1485 messages=[1485 messages=[

1486 {1486 {

1487 "role": "system",1487 "role": "system",


1568 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +1568 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +

1569 "[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"1569 "[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"

1570 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{1570 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

1571 Model: "gpt-6-astra",1571 Model: "gpt-6.2-astra",

1572 Messages: []openai.ChatCompletionMessageParamUnion{1572 Messages: []openai.ChatCompletionMessageParamUnion{

1573 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),1573 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

1574 }})1574 }})


1645 1645 

1646ChatCompletionCreateParams params =1646ChatCompletionCreateParams params =

1647 ChatCompletionCreateParams.builder()1647 ChatCompletionCreateParams.builder()

1648 .model("gpt-6-astra")1648 .model("gpt-6.2-astra")

1649 .addSystemMessage(metaPrompt)1649 .addSystemMessage(metaPrompt)

1650 .addUserMessage(1650 .addUserMessage(

1651 "Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")1651 "Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")


1660using OpenAI.Chat;1660using OpenAI.Chat;

1661 1661 

1662string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1662string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1663string model = "gpt-6-astra";1663string model = "gpt-6.2-astra";

1664ChatClient client = new(model, key);1664ChatClient client = new(model, key);

1665 1665 

1666string metaPrompt = """"1666string metaPrompt = """"


1785 1785 

1786def generate_prompt(client, meta_prompt, task_or_prompt)1786def generate_prompt(client, meta_prompt, task_or_prompt)

1787 completion = client.chat.completions.create(1787 completion = client.chat.completions.create(

1788 model: "gpt-6-astra",1788 model: "gpt-6.2-astra",

1789 messages: [1789 messages: [

1790 {1790 {

1791 role: :system,1791 role: :system,


2094 2094 

2095async function generateSchema(description: string) {2095async function generateSchema(description: string) {

2096 const completion = await client.chat.completions.create({2096 const completion = await client.chat.completions.create({

2097 model: "gpt-5.6-terra",2097 model: "gpt-6.1-terra",

2098 response_format: { type: "json_schema", json_schema: metaSchema },2098 response_format: { type: "json_schema", json_schema: metaSchema },

2099 messages: [2099 messages: [

2100 { role: "system", content: metaPrompt },2100 { role: "system", content: metaPrompt },


2354 # Generation is non-strict. Validate locally and allow one correction.2354 # Generation is non-strict. Validate locally and allow one correction.

2355 for attempt in range(2):2355 for attempt in range(2):

2356 completion = client.chat.completions.create(2356 completion = client.chat.completions.create(

2357 model="gpt-5.6-terra",2357 model="gpt-6.1-terra",

2358 response_format={"type": "json_schema", "json_schema": META_SCHEMA},2358 response_format={"type": "json_schema", "json_schema": META_SCHEMA},

2359 messages=messages,2359 messages=messages,

2360 )2360 )


2765 return err2765 return err

2766 }2766 }

2767 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{2767 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

2768 Model: "gpt-5.6-terra",2768 Model: "gpt-6.1-terra",

2769 Messages: []openai.ChatCompletionMessageParamUnion{2769 Messages: []openai.ChatCompletionMessageParamUnion{

2770 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),2770 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),

2771 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "metaschema", Schema: schema}}}})2771 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "metaschema", Schema: schema}}}})


3029 3029 

3030ChatCompletionCreateParams params =3030ChatCompletionCreateParams params =

3031 ChatCompletionCreateParams.builder()3031 ChatCompletionCreateParams.builder()

3032 .model("gpt-5.6-terra")3032 .model("gpt-6.1-terra")

3033 .addSystemMessage(metaPrompt)3033 .addSystemMessage(metaPrompt)

3034 .addUserMessage("Description:\nDescribe a calendar event.")3034 .addUserMessage("Description:\nDescribe a calendar event.")

3035 .putAdditionalBodyProperty(3035 .putAdditionalBodyProperty(


3047using OpenAI.Chat;3047using OpenAI.Chat;

3048 3048 

3049string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;3049string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

3050string model = "gpt-5.6-terra";3050string model = "gpt-6.1-terra";

3051ChatClient client = new(model, key);3051ChatClient client = new(model, key);

3052 3052 

3053string metaPrompt = """"3053string metaPrompt = """"


3662 3662 

3663client = OpenAI::Client.new3663client = OpenAI::Client.new

3664completion = client.chat.completions.create(3664completion = client.chat.completions.create(

3665 model: "gpt-5.6-terra",3665 model: "gpt-6.1-terra",

3666 response_format: {3666 response_format: {

3667 type: :json_schema,3667 type: :json_schema,

3668 json_schema: META_SCHEMA3668 json_schema: META_SCHEMA


3907 3907 

3908async function generateFunctionSchema(description: string) {3908async function generateFunctionSchema(description: string) {

3909 const completion = await client.chat.completions.create({3909 const completion = await client.chat.completions.create({

3910 model: "gpt-5.6-terra",3910 model: "gpt-6.1-terra",

3911 response_format: { type: "json_schema", json_schema: metaSchema },3911 response_format: { type: "json_schema", json_schema: metaSchema },

3912 messages: [3912 messages: [

3913 { role: "system", content: metaPrompt },3913 { role: "system", content: metaPrompt },


4126 4126 

4127def generate_function_schema(description: str):4127def generate_function_schema(description: str):

4128 completion = client.chat.completions.create(4128 completion = client.chat.completions.create(

4129 model="gpt-5.6-terra",4129 model="gpt-6.1-terra",

4130 response_format={"type": "json_schema", "json_schema": META_SCHEMA},4130 response_format={"type": "json_schema", "json_schema": META_SCHEMA},

4131 messages=[4131 messages=[

4132 {4132 {


4383 return err4383 return err

4384 }4384 }

4385 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{4385 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

4386 Model: "gpt-5.6-terra",4386 Model: "gpt-6.1-terra",

4387 Messages: []openai.ChatCompletionMessageParamUnion{4387 Messages: []openai.ChatCompletionMessageParamUnion{

4388 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),4388 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),

4389 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "function-metaschema", Schema: schema}}}})4389 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "function-metaschema", Schema: schema}}}})


4602 4602 

4603ChatCompletionCreateParams params =4603ChatCompletionCreateParams params =

4604 ChatCompletionCreateParams.builder()4604 ChatCompletionCreateParams.builder()

4605 .model("gpt-5.6-terra")4605 .model("gpt-6.1-terra")

4606 .addSystemMessage(metaPrompt)4606 .addSystemMessage(metaPrompt)

4607 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")4607 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")

4608 .putAdditionalBodyProperty(4608 .putAdditionalBodyProperty(


4625using OpenAI.Chat;4625using OpenAI.Chat;

4626 4626 

4627string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;4627string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

4628string model = "gpt-5.6-terra";4628string model = "gpt-6.1-terra";

4629ChatClient client = new(model, key);4629ChatClient client = new(model, key);

4630 4630 

4631string metaPrompt = """"4631string metaPrompt = """"


5061 5061 

5062client = OpenAI::Client.new5062client = OpenAI::Client.new

5063completion = client.chat.completions.create(5063completion = client.chat.completions.create(

5064 model: "gpt-5.6-terra",5064 model: "gpt-6.1-terra",

5065 response_format: {5065 response_format: {

5066 type: :json_schema,5066 type: :json_schema,

5067 json_schema: META_SCHEMA5067 json_schema: META_SCHEMA

Details

1---1---

2latestModelInfo:2latestModelInfo:

3 model: gpt-6-astra3 model: gpt-6.2-astra

4 migrationGuide: /api/docs/guides/latest-model/gpt-6-astra.md#migration-quickstart4 migrationGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#migration-quickstart

5 promptingGuide: /api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices5 promptingGuide: /api/docs/guides/latest-model/gpt-6.2-astra.md#prompting-best-practices

6---6---

7 7 

8# Using GPT-68# Using GPT-6.2

9 9 

10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.10> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

11 11 

12<a id="gpt-6-astra-gpt-6-astra"></a>12<a id="gpt-6.2-astra-gpt-62-astra-and-gpt-62-sol"></a>

13<a id="gpt-61-sol"></a>

14<a id="gpt-6.1-sol"></a>

15<a id="gpt-6-astra-gpt-61-sol"></a>

16<a id="gpt-61-terra"></a>

17<a id="gpt-6.1-terra"></a>

18<a id="gpt-6-astra-gpt-61-terra"></a>

19 13 

20Use GPT-6 Astra for the most demanding work, GPT-6.1 Sol for complex work at14Use [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra) for the most demanding tasks or [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol) for complex work at lower cost.

21lower cost, GPT-6.1 Terra for visual reasoning and writing, or GPT-6 Luna for

22focused, high-volume tasks. See [Model selection](https://developers.openai.com/api/docs/guides/model-selection)

23for a comparison.

24 

25<a id="gpt-6-astra-what-is-new" className="scroll-mt-[110px]"></a>

26 15 

27## What's new16## What's new

28 17 

29- **Async tool calling:** Supported models can continue reasoning, call other tools, or answer independent parts of a request while your application runs a tool. Set `async: true` on a function or custom tool and return its result when ready using the original `call_id`. Your application executes the tool and manages pending work. See [Async tool calling](https://developers.openai.com/api/docs/guides/async-tool-calling) for compatibility and examples.18Starting with GPT-6.2, the API will drop reasoning items when it detects mid-conversation changes to the conversation history (prefix edits), model downgrade, end user, or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to instructions or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

30- **Mid-turn steering:** Send additional user instructions while GPT-6 is working, such as a correction or a change in requirements. Over a WebSocket connection, the Responses API preserves completed work and includes the update in a continuation. See [Mid-turn steering](https://developers.openai.com/api/docs/guides/steering) for the event flow and tool-result handling.

31- **Change reasoning mid-conversation while preserving cache:** Add a `configuration_update` input item to increase reasoning effort for difficult work or reduce it for routine follow-ups without rewriting the original prompt prefix. The updated reasoning effort applies until another `configuration_update` input item overrides it. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility.

32- **Multi-agent and persisted reasoning on GPT-6.1 Sol:** Use the [Responses Multi-agent beta](https://developers.openai.com/api/docs/guides/responses-multi-agent) to delegate work to subagents. Set [`reasoning.context` to `all_turns`](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls) to reuse compatible reasoning from earlier turns.

33- **Misalignment monitoring:** As part of our [strengthened safeguards](https://openai.com/index/path-to-astra/) for GPT-6 Astra, our systems asynchronously monitor for misalignment and trigger alerts when necessary. See [Misalignment monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring) for more information.

34 

35GPT-6 also supports the existing API capabilities available with GPT-5.6, including [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [streaming](https://developers.openai.com/api/docs/guides/streaming-responses), [Programmatic Tool Calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling), [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [compaction](https://developers.openai.com/api/docs/guides/compaction), and [pro mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode).

36 

37## Limitations

38 

39- GPT-6 Astra and GPT-6.1 Sol do not support the `none` reasoning effort; GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna do.

40- Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. See [data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency).

41 19 

42<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>20<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

43 21 

44## Prompting best practices22## Prompting best practices

45 23 

46Use the following prompts as a starting point across the GPT-6 model family. They address behavior observed with GPT-6 Astra; evaluate them with your chosen model and workload.24Use the following prompts as a starting point across the GPT-6.2 model family. The examples address behaviors we’ve seen when working with GPT-6.2 Astra and Sol. If you recognize one in your own application, try the prompt in that section.

47 25 

48### GPT-6 Astra behavior26### GPT-6.2 Astra behavior

49 27 

50- [Initiative and follow-through](#initiative-and-follow-through): The model is designed to be a more effective collaborator and is thus more likely to ask the user a question when additional input could materially change the result. This can cause it to stop when the user may expect it to make reasonable assumptions and persist.28- **[Writing style](#writing-style).** The model’s writing tends to be more concise and direct by default. When migrating, revisit instructions like “be concise” in your system prompt.

51- [Instruction following](#instruction-following): GPT-6 Astra is stronger at general instruction following than our previous models, giving you greater control over its behavior. It can be more sensitive to instructions contained in skills and other files, such as `AGENTS.md`. We **strongly recommend** auditing skills and other files accessible to your model for instructions that could influence its behavior.29- **[Task completion](#task-completion).** When the user’s intent is unclear, the model may propose a next step and wait for confirmation. For longer tasks, give it room to make reasonable assumptions and keep working.

52- [Personality and writing style](#personality-and-writing-style): The model tends toward detailed, formatted responses and may use recurring phrases across sessions. Specify the writing style and structure your application needs.30- **[Coding style](#coding-style).** The model tends to write more efficient, high-quality code than its predecessors. Describe any project conventions that should guide how it writes or edits code.

53- [Subagent delegation](#subagent-delegation): The model may delegate less often than desired for your workflow. Specify when and how much it should use subagents for parallel work.31- **[Frontend design](#frontend-design).** If the interface needs a particular look, specify the imagery and typography it should use.

54- [Testing and verification](#testing-and-verification): For coding tasks, the model tends to be thorough in testing before considering a task complete. For smaller tasks, this can result in broader tests than the task requires.

55 32 

56### Initiative and follow-through33<a id="gpt-6.2-astra-prompt-patterns-for-api-applications"></a>

34<a id="gpt-6.2-astra-personality-and-writing-style"></a>

57 35 

58GPT-6 Astra is generally better than GPT-5.6 Sol and earlier models at staying coherent during long tasks. It is also more likely to ask for clarification where earlier models would make assumptions.36### Writing style

59 37 

60To encourage more autonomous work, start with this prompt:38GPT-6.2 Astra is more concise and direct by default than earlier models. Its tone can be tuned to suit the application, from a professional colleague to a more conversational assistant.

61 39 

62```text40Use the following prompt if you want to use the model as a collaborator and thought partner for day to day work.

63You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.

64 41 

65When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.42```text

43Write using terminology the user and sources use. Keep technical details and use domain-specific language when they make the explanation more precise. Use the active voice and keep closely related details together. Cover the key points up front, and avoid references that the reader can only make sense of later in the response. Give the user enough context to follow your reasoning.

66```44```

67 45 

68When the user’s intent is unclear, the model is more likely to ask the user for clarification to proceed. Prompt the model to follow through if the user’s prompt implies authorization:46Prompt the model to adapt to the audience it is drafting material for, such as writing in documents, emails, messages and external posts.

69 47 

70```text48```text

71When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.49When drafting a message or any other material on behalf of the user to be sent to an external audience, consider who will read it and tailor the content to that intended audience. The intended audience likely does not have the same context as the user, so ensure that you provide the background information or reasoning required for the audience to understand the content. When reviewing or editing existing content, preserve the author’s content and wording, and follow the user's instruction carefully for what edits they want.

72```50```

73 51 

74Prompt the model to ask for approval only after preparing a concrete, reviewable result. This avoids blocking the task before the model has done the work it can, and often leads to quicker task completion.52During longer tasks, the model can carry shorthand from its reasoning or from other agents into its final answer. Remind it to write a self-contained response that’s clear to someone who hasn’t followed the progress updates.

75 53 

76```text54```text

77Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.55Treat your final answer as the user's first look at your work, and not as a continuation of intermediate commentary. The final answer must always be fully self-contained: users should never need to read earlier commentary updates for context, since they are collapsed when the final answer is shown to the user.

78 56 

79Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.57Write the final answer and all other human-facing material anew for the intended reader. Do not copy or closely paraphrase your reasoning or adopt its writing style. Do not carry over working shorthand, jargon, or abbreviations from your reasoning, tool calls, or instructions to subagents and automations.

80```58```

81 59 

82The model also likes to ask non-blocking questions as it’s working by default, so adjust these prompts to match the level of autonomy your application needs.60<a id="gpt-6.2-astra-initiative-and-follow-through"></a>

61<a id="gpt-6.2-astra-subagent-delegation"></a>

83 62 

84### Instruction following63### Task completion

85 64 

86GPT-6 Astra is better able to follow longer instructions, but can also be more sensitive to information in context. For example, unclear or conflicting guidance in a skill file may cause the model to pause and block work early. Make the priority of user instructions and skills explicit.65For work that can proceed without supervision, specify the outcome the model should complete and which decisions need the user’s input.

87 66 

88```text67```text

89The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.68Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. If your final response before ending the turn is a suggested next step, a plan, a request to the user for a routine decision, instructions for a task to execute, or similar handoff to the user, take these steps yourself to make progress towards what the user asked for. Make sure that you have authorization to do so, and flag any assumptions or decisions you maketo the user.

90```

91 

92Asking the model to identify the skill and instruction that caused it to pause or change direction can also be effective in providing transparency into model behavior.

93 69 

94```text70Only stop to clarify with the user if there is significant change in task scope, you are concretely blocked, have a decision that the user needs to resolve, or before irreversible or destructive actions.

95If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.

96```71```

97 72 

98Use this prompt to find silent and conflicting guidance when your application loads many skills and instruction files such as `AGENTS.md`.73<a id="gpt-6.2-astra-testing-and-verification"></a>

74<a id="gpt-6.2-astra-ask-for-an-exhaustive-pass"></a>

99 75 

100### Personality and writing style76Ask the model to verify that it has completed the requested work. Higher reasoning effort can help it persist through the final checks on complex or long-running tasks. In the Responses API, set the level with `reasoning.effort`. [Reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort)

101 

102GPT-6 Astra tends to use lists, tables and Markdown to make responses scannable. If your application needs prose with less formatting, specify that preference.

103 77 

104```text78```text

105Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.79Bias towards action, and persist until you've completed the task the user asked for. Avoid stopping to end the turn while the task is incomplete or if there is an authorized next step you can take, and instead take the next steps within task scope to progress the user's request. Make sure that you have accounted for every part of the user's request, and persist until you've delivered a result that fully satisfies the user's goal. If a task requires sustained work, do all the necessary work until the intended outcome is completely fulfilled.

106 80 

107Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.81Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, creating draft PRs etc) unless they are clearly destructive or irreversible. Before ending a turn or calling your work complete, check that your work fully satisfies what the user asked for. If any steps remain or any part of the result still needs verification, follow through on this work before finishing.

108```82```

109 83 

110For technical communication, the following prompt helps strike a balance between using clear, coherent language while remaining domain appropriate:84<a id="gpt-6.2-astra-instruction-following"></a>

85<a id="gpt-6.2-astra-intent-understanding"></a>

86<a id="gpt-6.2-astra-interpreting-ambiguous-requests"></a>

111 87 

112```text88When a detail is unclear, give the model room to state what it’s assuming and continue with the task.

113Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.

114```

115 

116To reduce jargon and stock phrases in writing, start with this prompt:

117 89 

118```text90```text

119Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".91Make reasonable, reversible assumptions to carry work forward and state them if it progresses the task within scope. Do not second guess yourself, stop after describing what you could do, offer to do the work, or provide a partial answer unless there is no way you can proceed.

120 

121State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.

122```92```

123 93 

124### Subagent delegation94With an async tool such as `request_user_input_async` in your application, GPT-6.2 can ask the user for clarification and continue work that doesn’t depend on the answer. [Add an async question tool](https://developers.openai.com/api/docs/guides/async-tool-calling#add-a-tool-to-ask-the-user-for-input)

125 95 

126GPT-6 Astra is trained to be able to divide and delegate work to subagents that work in parallel. If you are implementing a multi-agent system in your harness, use the following prompt to tune how much GPT-6 Astra should delegate work:96<a id="gpt-6.2-astra-code-changes"></a>

127 97 

128```text98### Coding style

129If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.

130```

131 99 

132Messages between agents may contain grammar or spacing errors. Use this prompt to make inter-agent messages easier to read:100Describe the codebase’s conventions and any behavior that existing callers rely on. For example, specify when to reuse existing logic, how narrowly to scope a change, and when to add a test for behavior the existing suite doesn’t cover.

133 101 

134```text102```text

135Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.103Above all, be thorough in producing high-quality, correct code that completely fulfills the user's task. Keep the code easy to read and verify that the user-requested outcome works as they intend. Follow these instructions when coding:

104 

105(a) Reuse existing logic in the user's repo when you can. You should reuse existing classes, methods, representations, and APIs in the codebase as long as they preserve correctness. Before consolidating or removing code, preserve the behavior its callers rely on unless the task requires changing it.

106(b) Skip new tests unless requested, required by the repo, or needed to catch a specific regression existing tests would miss.

107(c) Make sure that code is human readable. Do not use fewer lines, shorter variable names, minified formatting, or dense one-liners as substitutes for simplicity. Ensure that comments and variable names are readable and understandable to a human. Code-golfed expressions count as overly complex when they encode many branches, conditions, or hidden assumptions.

108(d) Avoid unnecessary indirection and abstraction. Helper functions, utility functions, and class abstractions can add cognitive complexity even when they do not add branches.

136```109```

137 110 

138The model tends to respond well to prompting for how and when it should delegate work to subagents, so tune this behavior to fit with your harness and multi-agent implementation.111<a id="gpt-6.2-astra-visual-review"></a>

112<a id="gpt-6.2-astra-visual-work-and-frontend-design"></a>

139 113 

140### Testing and verification114### Frontend design

141 115 

142For coding tasks, calibrate how much testing and verification a change requires. This can help avoid unnecessary tests or repeated checks for small changes.116If the application depends on a specific visual style, describe it in the prompt. Specify the kinds of images it should use and the typography it should follow, including a particular typeface when that matters. Keep interface copy focused on what people need to know or do.

143 117 

144```text118```text

145Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.119When generating webpages or apps with a frontend user interface, follow these instructions:

146 120 

147Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.121- When choosing visuals, generally prefer realistic images from ImageGen or image search that suit the project's style and purpose. Use SVGs when the user specifically asks for them.

122- Include a text element only when it provides information the user needs, helps them navigate or act, or fulfills an explicit content request. Remove decorative numbering, filler badges, redundant headings, and explanatory copy that merely restates what the surrounding interface already makes clear, while preserving necessary labels, instructions, and status feedback.

148```123```

149 124 

150## Migration quickstart125For visual work, share a reference from your design software, or give GPT-6.2 access to the [image generation tool](https://developers.openai.com/api/docs/guides/tools-image-generation) and ask it to create one with GPT Image. A reference can enrich your prompt with details that are hard to describe in words. Once it captures the look you want, ask the model to build the asset, render it, and refine it against the reference.

151 126 

152### Migrate with Codex127## Migration quickstart

153 128 

154Codex can apply the recommended changes in this guide with the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).129<a id="gpt-6.2-astra-migrate-with-codex"></a>

155 130 

156```text131To migrate an API application to GPT-6.2 Astra with a coding agent, use the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).

157$openai-docs migrate this project to the GPT-6 model family

158```

159 132 

160To use this skill in other coding agents, download it from the [Codex repository](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).133<a id="gpt-6.2-astra-choose-a-reasoning-effort"></a>

134<a id="gpt-6.2-astra-zdr-data-residency-and-service-tiers"></a>

135<a id="gpt-6.2-astra-limitations"></a>

136<a id="gpt-6.2-astra-data-residency-and-service-tiers"></a>

161 137 

162### Update API and model parameters138### Update API and model parameters

163 139 

164Set `model` to `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, or `gpt-6-luna`, then review the compatibility checks below.140Set `model` to `gpt-6.2-astra` or `gpt-6.2-sol`, then check the following:

165 

166If you're switching from `gpt-6-sol` to `gpt-6.1-sol`, use `low` if your

167current reasoning effort is `none`. Move any Chat Completions requests that

168call functions to the Responses API.

169 

170When moving from GPT-5.6 Terra to GPT-6.1 Terra, compare both models on

171representative images and workflows at the same reasoning effort.

172 141 

173- **Reasoning effort:** Preserve your current effective [reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort) where supported. GPT-6 Astra and GPT-6.1 Sol do not support `none`; use `low` instead. GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support `none`. If your existing request uses `minimal`, start with `low` and compare results on representative tasks. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.142- **Reasoning effort:** Start with `medium` for a new integration. If you currently use `none` or `minimal`, use `low` instead. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.

174- **Tool calling:** Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6 Astra, GPT-6.1 Sol, and GPT-6.1 Terra support Chat Completions, but tool calling requires Responses. GPT-6 Sol and GPT-6 Luna support function calling in Chat Completions only with `reasoning_effort: "none"`. Use Responses for reasoning with tools.143- **Tool calling:** Use the [**Responses API**](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6.2 Astra and GPT-6.2 Sol support Chat Completions, but tool calling requires Responses.

175- **Unsupported parameters:** When reasoning effort is not `none`, remove `temperature`, `top_p`, and `top_logprobs`. For Chat Completions, also remove `logprobs`. For Responses, remove `message.output_text.logprobs` from `include`.144- **Unsupported parameters:** When migrating Chat Completions requests, omit `temperature`, `top_p`, `logprobs`, and `top_logprobs`. For Responses requests, omit `temperature`, `top_p`, and `top_logprobs` and remove `message.output_text.logprobs` from `include`.

176- **Data residency:** Fast mode supports EU data residency for GPT-6.1 Sol, GPT-6.1 Terra, and GPT-6 Luna, but not GPT-6 Astra or GPT-6 Sol. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only. Fast mode for GPT-6 Astra does not include a latency SLA. See [Fast mode compatibility](https://developers.openai.com/api/docs/guides/fast-mode#is-fast-mode-compatible-with-data-residency-zero-data-retention-and-a-baa).145- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [**prompt caching changes**](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.

177- **Changing reasoning effort:** If your application changes effort between responses, use `configuration_update` items in standard, single-agent requests. Keep request-level `reasoning.effort` unchanged to preserve the prompt prefix for caching. Check the [compatibility limits](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) before adopting this feature.146- **Zero Data Retention:** GPT-6.2 Astra and Sol support Zero Data Retention (ZDR) for approved organizations on eligible endpoints and features. With ZDR enabled, the Responses API treats `store` as `false`. For multi-turn work, pass the prior output items back in order, including encrypted reasoning items. See [Zero Data Retention](https://developers.openai.com/api/docs/guides/your-data#zero-data-retention) for eligibility and endpoint behavior.

178- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [prompt caching changes](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.147- **Service tiers and regions:** Both models support US and EU data residency with Standard, Fast, and Batch processing. Ultrafast supports US data residency only. See [data residency](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency) and [pricing](https://developers.openai.com/api/docs/pricing#text-tokens).

179- **Unnecessary approval pauses:** If you run into issues where the model keeps asking for approval before proceeding, use the [initiative and follow-through guidance](#initiative-and-follow-through) to prompt for more autonomous execution. See the rest of [Prompting best practices](#prompting-best-practices) for guidance on instruction following, writing style, subagent delegation, and testing.148- **Prompting:** See [**Prompting best practices**](#prompting-best-practices) for guidance.

Details

158const client = new OpenAI();158const client = new OpenAI();

159 159 

160const response = await client.responses.create({160const response = await client.responses.create({

161 model: "gpt-6-astra",161 model: "gpt-6.2-astra",

162 input: [162 input: [

163 {163 {

164 role: "system",164 role: "system",


182client = OpenAI()182client = OpenAI()

183 183 

184response = client.responses.create(184response = client.responses.create(

185 model="gpt-6-astra",185 model="gpt-6.2-astra",

186 input=[186 input=[

187 {187 {

188 "role": "system",188 "role": "system",


212func main() {212func main() {

213 client := openai.NewClient()213 client := openai.NewClient()

214 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{214 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

215 Model: "gpt-6-astra",215 Model: "gpt-6.2-astra",

216 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{216 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

217 responses.ResponseInputItemParamOfMessage("You are a helpful support assistant. Be concise, accurate, and friendly.", responses.EasyInputMessageRoleSystem),217 responses.ResponseInputItemParamOfMessage("You are a helpful support assistant. Be concise, accurate, and friendly.", responses.EasyInputMessageRoleSystem),

218 responses.ResponseInputItemParamOfMessage("Customer name: Acme. Issue: billing question. Write a response to the customer.", responses.EasyInputMessageRoleUser),218 responses.ResponseInputItemParamOfMessage("Customer name: Acme. Issue: billing question. Write a response to the customer.", responses.EasyInputMessageRoleUser),


235 235 

236ResponseCreateParams params =236ResponseCreateParams params =

237 ResponseCreateParams.builder()237 ResponseCreateParams.builder()

238 .model("gpt-6-astra")238 .model("gpt-6.2-astra")

239 .inputOfResponse(239 .inputOfResponse(

240 List.of(240 List.of(

241 ResponseInputItem.ofEasyInputMessage(241 ResponseInputItem.ofEasyInputMessage(


267ResponsesClient client = new(key);267ResponsesClient client = new(key);

268 268 

269ResponseResult response = await client.CreateResponseAsync(269ResponseResult response = await client.CreateResponseAsync(

270 "gpt-6-astra",270 "gpt-6.2-astra",

271 [271 [

272 ResponseItem.CreateSystemMessageItem(272 ResponseItem.CreateSystemMessageItem(

273 "You are a helpful support assistant. Be concise, accurate, and friendly."273 "You are a helpful support assistant. Be concise, accurate, and friendly."


287client = OpenAI::Client.new287client = OpenAI::Client.new

288 288 

289response = client.responses.create(289response = client.responses.create(

290 model: "gpt-6-astra",290 model: "gpt-6.2-astra",

291 input: [291 input: [

292 {292 {

293 role: :system,293 role: :system,


308 -H "Content-Type: application/json" \308 -H "Content-Type: application/json" \

309 -H "Authorization: Bearer $OPENAI_API_KEY" \309 -H "Authorization: Bearer $OPENAI_API_KEY" \

310 -d '{310 -d '{

311 "model": "gpt-6-astra",311 "model": "gpt-6.2-astra",

312 "input": [312 "input": [

313 {313 {

314 "role": "system",314 "role": "system",


371}371}

372 372 

373const response = await client.responses.create({373const response = await client.responses.create({

374 model: "gpt-6-astra",374 model: "gpt-6.2-astra",

375 input: buildSupportPrompt({375 input: buildSupportPrompt({

376 customerName: "Acme",376 customerName: "Acme",

377 issue: "billing question",377 issue: "billing question",


399 399 

400 400 

401response = client.responses.create(401response = client.responses.create(

402 model="gpt-6-astra",402 model="gpt-6.2-astra",

403 input=build_support_prompt(403 input=build_support_prompt(

404 customer_name="Acme",404 customer_name="Acme",

405 issue="billing question",405 issue="billing question",


421func main() {421func main() {

422 client := openai.NewClient()422 client := openai.NewClient()

423 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{423 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

424 Model: "gpt-6-astra",424 Model: "gpt-6.2-astra",

425 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: buildSupportPrompt("Acme", "billing question")},425 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: buildSupportPrompt("Acme", "billing question")},

426 })426 })

427 if err != nil {427 if err != nil {


468 468 

469ResponseCreateParams params =469ResponseCreateParams params =

470 ResponseCreateParams.builder()470 ResponseCreateParams.builder()

471 .model("gpt-6-astra")471 .model("gpt-6.2-astra")

472 .inputOfResponse(buildSupportPrompt("Acme", "billing question"))472 .inputOfResponse(buildSupportPrompt("Acme", "billing question"))

473 .build();473 .build();

474 474 


497];497];

498 498 

499ResponseResult response = await client.CreateResponseAsync(499ResponseResult response = await client.CreateResponseAsync(

500 "gpt-6-astra",500 "gpt-6.2-astra",

501 BuildSupportPrompt("Acme", "billing question")501 BuildSupportPrompt("Acme", "billing question")

502);502);

503Console.WriteLine(response.GetOutputText());503Console.WriteLine(response.GetOutputText());


522client = OpenAI::Client.new522client = OpenAI::Client.new

523 523 

524response = client.responses.create(524response = client.responses.create(

525 model: "gpt-6-astra",525 model: "gpt-6.2-astra",

526 input: build_support_prompt("Acme", "billing question")526 input: build_support_prompt("Acme", "billing question")

527)527)

528 528 

Details

11 11 

12Your cloud key-management service decrypts a small recovery capsule. Your application uses the recovered secret to decrypt the record locally. Your private key stays in your cloud key-management service.12Your cloud key-management service decrypts a small recovery capsule. Your application uses the recovered secret to decrypt the record locally. Your private key stays in your cloud key-management service.

13 13 

14The [appendix](#appendix-format-and-decryption-reference) shows the record bundle and a Python example.14The [appendix](#appendix-format-and-decryption-reference) shows the record bundle and local decryption examples.

15 15 

16## Before you start16## Before you start

17 17 


57 57 

58### 4. Decrypt and verify the content58### 4. Decrypt and verify the content

59 59 

60Use the [Python example](#python-example) to check the capsule's binding to the record and decrypt the content locally.60Use the [decryption examples](#decryption-examples) to check the capsule's binding to the record and decrypt the content locally.

61 61 

62Return content only after all checks and AES-GCM authentication succeed.62Return content only after all checks and AES-GCM authentication succeed.

63 63 


72| `customer_access` is `null` | The record wasn't written with PSP decryption enabled for a recovery key. Selecting a key doesn't enable PSP decryption for that record. |72| `customer_access` is `null` | The record wasn't written with PSP decryption enabled for a recovery key. Selecting a key doesn't enable PSP decryption for that record. |

73| KMS access denied or key unavailable | Check your decrypt permission and the availability of the original cloud key and version. |73| KMS access denied or key unavailable | Check your decrypt permission and the availability of the original cloud key and version. |

74| Fingerprint or binding mismatch | Check the intended record and original registration. Don't modify authenticated fields or substitute another key. |74| Fingerprint or binding mismatch | Check the intended record and original registration. Don't modify authenticated fields or substitute another key. |

75| AES-GCM authentication fails | Check the inputs to the [Python example](#python-example). Don't return partial plaintext. |75| AES-GCM authentication fails | Check the inputs to the [decryption examples](#decryption-examples). Don't return partial plaintext. |

76 76 

77## Related guides77## Related guides

78 78 


81 81 

82## Appendix: Format and decryption reference82## Appendix: Format and decryption reference

83 83 

84This appendix covers **bundle version 1, protected-record version `v4`**. Use the Python example below to implement local decryption without OpenAI libraries.84This appendix covers **bundle version 1, protected-record version `v4`**. Use the examples below to implement local decryption without OpenAI libraries.

85 85 

86### Bundle format86### Bundle format

87 87 


115 115 

116`encrypted_cot` contains encrypted chain-of-thought content. This content cannot be decrypted with your customer recovery key. The array may be empty.116`encrypted_cot` contains encrypted chain-of-thought content. This content cannot be decrypted with your customer recovery key. The array may be empty.

117 117 

118### Python example118 

119 

120 

121### Decryption examples

119 122 

120Use the example below after decrypting any separate EKM storage envelope and the recovery capsule with the original cloud key. It checks the key fingerprint, capsule binding, recovered scalar, and runtime thumbprint before authenticating and decrypting the payload.123Use the example below after decrypting any separate EKM storage envelope and the recovery capsule with the original cloud key. It checks the key fingerprint, capsule binding, recovered scalar, and runtime thumbprint before authenticating and decrypting the payload.

121 124 

122Install `pyhpke`, `cryptography`, and `rfc8785` in your Python environment. Pass these inputs to `recover_record`:125 

126 

127 

128For Python, install `pyhpke`, `cryptography`, and `rfc8785`.

129 

130 

131 

132 

133 

134 

135 

136For Ruby, install `hpke` and `json-canonicalization` with the OpenSSL Ruby bindings.

137 

138 

139 

140 

141Pass these inputs to `recover_record`:

123 142 

124- `bundle_json`: The inner record bundle as UTF-8 JSON bytes.143- `bundle_json`: The inner record bundle as UTF-8 JSON bytes.

125- `capsule`: The bytes returned by your cloud key-management service.144- `capsule`: The bytes returned by your cloud key-management service.


273 return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), encoded)292 return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), encoded)

274```293```

275 294 

295```ruby

296require "base64"

297require "digest"

298require "json"

299require "json/canonicalization"

300require "openssl"

301require "hpke"

302 

303def require_valid(condition, message)

304 raise ArgumentError, message unless condition

305end

306 

307def b64url(bytes)

308 Base64.urlsafe_encode64(bytes, padding: false)

309end

310 

311def decode64(value)

312 require_valid(value.is_a?(String), "Expected base64url text")

313 bytes = Base64.strict_decode64(value.tr("-_", "+/") + "=" * (-value.length % 4))

314 require_valid(b64url(bytes) == value, "Noncanonical base64url")

315 bytes

316end

317 

318def equal_bytes?(left, right)

319 left.bytesize == right.bytesize && OpenSSL.fixed_length_secure_compare(left, right)

320end

321 

322def recovery_point(kem, value)

323 encoded = decode64(value)

324 require_valid(encoded.bytesize == 65 && encoded.getbyte(0) == 4, "Invalid P-256 encoding")

325 key = kem.deserialize_public_key(encoded)

326 require_valid(key.check_key, "Invalid P-256 point")

327 [key, encoded]

328rescue OpenSSL::PKey::PKeyError

329 raise ArgumentError, "Invalid P-256 point"

330end

331 

332# Recover from exact inner bundle bytes and an already decrypted capsule.

333# No cloud calls occur here; the RSA private key stays in the cloud.

334def recover_record(bundle_json, capsule, original_key_id, original_public_key_pem)

335 bundle = JSON.parse(bundle_json, allow_duplicate_key: false)

336 require_valid(

337 bundle["bundle_version"].is_a?(Integer) && bundle["bundle_version"] == 1,

338 "Unsupported bundle version"

339 )

340 record = bundle.fetch("protected_record")

341 access = bundle.fetch("customer_access")

342 require_valid(access.is_a?(Hash), "Customer recovery is unavailable")

343 require_valid(

344 record["version"] == "v4" &&

345 record["algorithm"] == "HPKE-v1-DHKEM_P256_HKDF_SHA256-EXPORT_ONLY-AES256_GCM" &&

346 access["version"].is_a?(Integer) && access["version"] == 1 &&

347 access["algorithm"] == "RSA-OAEP-256" && access["customer_key_id"] == original_key_id,

348 "Wrong schema or original key"

349 )

350 

351 public_key = OpenSSL::PKey.read(original_public_key_pem)

352 require_valid(public_key.is_a?(OpenSSL::PKey::RSA) && !public_key.private?, "Expected an RSA public key")

353 require_valid(public_key.n.num_bits == 3072, "Expected RSA-3072")

354 require_valid(

355 decode64(access.fetch("recovery_secret")).bytesize == 384,

356 "Wrong RSA ciphertext length"

357 )

358 fingerprint = Digest::SHA256.digest(public_key.public_to_der)

359 require_valid(equal_bytes?(decode64(access.fetch("customer_public_key_fingerprint")), fingerprint), "Wrong key")

360 

361 suite = HPKE.new(HPKE::DHKEM_P256_HKDF_SHA256, HPKE::HKDF_SHA256, HPKE::EXPORT_ONLY)

362 runtime, encoded = recovery_point(suite.kem, record.fetch("safety_review_runtime_public_key"))

363 jwk = {

364 "crv" => "P-256",

365 

366 "kty" => "EC",

367 

368 "x" => b64url(encoded.byteslice(1, 32)),

369 "y" => b64url(encoded.byteslice(33, 32))

370 }

371 require_valid(record["key_thumbprint"] == b64url(Digest::SHA256.digest(jwk.to_json_c14n)), "Wrong runtime key")

372 nonce = decode64(record.fetch("nonce"))

373 ciphertext = decode64(record.fetch("ciphertext"))

374 require_valid(nonce.bytesize == 12 && ciphertext.bytesize >= 16, "Invalid AES-GCM encoding")

375 

376 binding_input = {

377 "purpose" => "OpenAI-PSP-v4/customer-recovery-binding",

378 

379 "bundle_version" => 1,

380 "record" => record,

381 

382 "recovery_header" => access.except("recovery_secret")

383 }

384 binding = Digest::SHA256.digest(binding_input.to_json_c14n)

385 require_valid(

386 capsule.is_a?(String) && capsule.bytesize == 72 &&

387 capsule.byteslice(0, 8) == "PSPv4\x00\x00\x01".b && equal_bytes?(capsule.byteslice(40, 32), binding),

388 "Invalid recovery capsule binding"

389 )

390 secret = capsule.byteslice(8, 32)

391 scalar = OpenSSL::BN.new(secret, 2).to_i

392 order = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551

393 require_valid(scalar >= 1 && scalar < order, "Invalid P-256 private scalar")

394 

395 # Restore the recovered key on this one KEM instance. The library performs

396 # the complete HPKE encapsulation and key schedule, without generating a new

397 # ephemeral key that would differ from the original encryption operation.

398 ephemeral = suite.kem.create_key_pair_from_secret(secret)

399 suite.kem.define_singleton_method(:generate_key_pair) { ephemeral }

400 sender = suite.setup_base_s(runtime, "OpenAI-PSP-v4/HPKE-export")

401 require_valid(sender.fetch(:enc) == decode64(record.fetch("encrypted_dek")), "Wrong recovered scalar")

402 aad = record.except("ciphertext").to_json_c14n

403 key = sender.fetch(:context_s).export("OpenAI-PSP-v4/payload-key" + Digest::SHA256.digest(aad), 32)

404 

405 cipher = OpenSSL::Cipher.new("aes-256-gcm")

406 cipher.decrypt

407 cipher.key = key

408 cipher.iv = nonce

409 cipher.auth_tag = ciphertext.byteslice(-16, 16)

410 cipher.auth_data = aad

411 encrypted_body = ciphertext.byteslice(0, ciphertext.bytesize - 16)

412 plaintext = encrypted_body.empty? ? "".b : cipher.update(encrypted_body)

413 plaintext << cipher.final

414 plaintext.force_encoding(Encoding::UTF_8)

415 require_valid(plaintext.valid_encoding?, "Recovered plaintext is not UTF-8")

416 plaintext

417end

418```

419 

276 420 

277### Recovered content421### Recovered content

278 422 

Details

22 22 

23Rate limits use metrics such as **RPM** (requests per minute), **RPD** (requests per day), **TPM** (tokens per minute), **TPD** (tokens per day), **IPM** (images per minute), and audio minutes per minute for some streaming audio models. Rate limits can be hit across any of the options depending on what occurs first. For example, you might send 20 requests with only 100 tokens to the ChatCompletions endpoint and that would fill your limit (if your RPM was 20), even if you didn't send 150k tokens (if your TPM limit was 150k) within those 20 requests.23Rate limits use metrics such as **RPM** (requests per minute), **RPD** (requests per day), **TPM** (tokens per minute), **TPD** (tokens per day), **IPM** (images per minute), and audio minutes per minute for some streaming audio models. Rate limits can be hit across any of the options depending on what occurs first. For example, you might send 20 requests with only 100 tokens to the ChatCompletions endpoint and that would fill your limit (if your RPM was 20), even if you didn't send 150k tokens (if your TPM limit was 150k) within those 20 requests.

24 24 

25[Batch API](https://developers.openai.com/api/reference/resources/batches/methods/create) queue limits are calculated based on the total number of input tokens queued for a given model. Tokens from pending batch jobs are counted against your queue limit. Once a batch job is completed, its tokens are no longer counted against that model's limit.25The **Batch/Background Rate Limit** caps the total input tokens queued for a model. It applies to [Batch API](https://developers.openai.com/api/docs/guides/batch) jobs and [Background mode](https://developers.openai.com/api/docs/guides/background) requests with `2h` or `8h` completion windows. The API counts input tokens at submission. Once a batch job completes, its tokens no longer count toward the limit. Background requests with the default `soonest` window use the regular request and token limits.

26 26 

27Other important things worth noting:27Other important things worth noting:

28 28 


253print(response.output_text)253print(response.output_text)

254```254```

255 255 

256```ruby

257require "openai"

258require "retriable"

259 

260client = OpenAI::Client.new(max_retries: 0)

261response = Retriable.retriable(on: OpenAI::Errors::RateLimitError, tries: 6, base_interval: 1, max_interval: 60, multiplier: 2) do

262 client.responses.create(

263 model: "gpt-6-luna",

264 input: "Say hello in one sentence.",

265 reasoning: { effort: :low },

266 max_output_tokens: 1024

267 )

268end

269puts(response.output_text)

270```

271 

256 272 

257Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about273Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about

258its reliability or security.274its reliability or security.


293print(response.output_text)309print(response.output_text)

294```310```

295 311 

312```ruby

313require "openai"

314require "retryable"

315 

316client = OpenAI::Client.new(max_retries: 0)

317response = Retryable.retryable(on: OpenAI::Errors::RateLimitError, tries: 6, sleep: ->(attempt) { rand * (2**attempt) }) do

318 client.responses.create(

319 model: "gpt-6-luna",

320 input: "Say hello in one sentence.",

321 reasoning: { effort: :low },

322 max_output_tokens: 1024

323 )

324end

325puts(response.output_text)

326```

327 

296 328 

297Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.329Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.

298 330 


379print(response.output_text)411print(response.output_text)

380```412```

381 413 

414```ruby

415require "openai"

416 

417client = OpenAI::Client.new(max_retries: 0)

418 

419def retry_with_exponential_backoff(initial_delay: 1, exponential_base: 2, jitter: true, max_retries: 10)

420 retries = 0

421 delay = initial_delay

422 begin

423 yield

424 rescue OpenAI::Errors::RateLimitError

425 raise if retries >= max_retries

426 

427 retries += 1

428 delay *= exponential_base * (1 + (jitter ? rand : 0))

429 sleep(delay)

430 retry

431 end

432end

433 

434response = retry_with_exponential_backoff do

435 client.responses.create(

436 model: "gpt-6-luna",

437 input: "Say hello in one sentence.",

438 reasoning: { effort: :low },

439 max_output_tokens: 1024

440 )

441end

442puts(response.output_text)

443```

444 

382Again, OpenAI makes no guarantees on the security or efficiency of this solution but it can be a good starting place for your own solution.445Again, OpenAI makes no guarantees on the security or efficiency of this solution but it can be a good starting place for your own solution.

383 446 

384 447 

Details

156}156}

157```157```

158 158 

159```ruby

160require "openai"

161require "base64"

162 

163client = OpenAI::Client.new

164client.realtime.connect_transcription do |connection|

165 connection.session.update(

166 type: :transcription,

167 audio: {

168 input: {

169 format: {

170 type: "audio/pcm",

171 rate: 24000

172 },

173 transcription: { model: "gpt-live-transcribe" },

174 

175 turn_detection: nil

176 }

177 }

178 )

179 updated = connection.find do |event|

180 raise event.error.message if event.is_a?(OpenAI::Realtime::RealtimeErrorEvent)

181 

182 event.is_a?(OpenAI::Realtime::SessionUpdatedEvent)

183 end

184 raise "Connection closed before transcription configuration" unless updated

185 

186 # speech.pcm contains mono PCM16 audio sampled at 24 kHz.

187 raise "Expected nonempty PCM16 audio" unless File.size("speech.pcm").positive? && File.size("speech.pcm").even?

188 

189 File.open("speech.pcm", "rb") do |input|

190 while (chunk = input.read(9600))

191 connection.input_audio_buffer.append(audio: Base64.strict_encode64(chunk))

192 end

193 end

194 connection.input_audio_buffer.commit

195 state = {}

196 completed = connection.find do |event|

197 case event

198 when OpenAI::Realtime::InputAudioBufferCommittedEvent

199 state[:item_id] = event.item_id

200 when OpenAI::Realtime::ConversationItemInputAudioTranscriptionDeltaEvent

201 warn "Partial transcript (#{event.item_id}): #{event.delta}" if state[:item_id] && event.item_id == state[:item_id]

202 when OpenAI::Realtime::ConversationItemInputAudioTranscriptionCompletedEvent

203 if state[:item_id] && event.item_id == state[:item_id]

204 puts "Final transcript: #{event.transcript}"

205 next true

206 end

207 when OpenAI::Realtime::ConversationItemInputAudioTranscriptionFailedEvent

208 raise "Transcription failed" if state[:item_id] && event.item_id == state[:item_id]

209 when OpenAI::Realtime::RealtimeErrorEvent

210 raise event.error.message

211 end

212 false

213 end

214 raise "Connection closed before the committed item's final transcript" unless completed

215end

216```

217 

159 218 

160## Add transcription context219## Add transcription context

161 220 

Details

123 123 

124Connect to the dedicated translation endpoint and select the model in the URL:124Connect to the dedicated translation endpoint and select the model in the URL:

125 125 

126Before running this example, install `ws` for Node.js, `websocket-client` and `sounddevice` for Python, or `async-websocket` for Ruby (`gem install async-websocket`). For Java, add the Maven dependency `com.openai:openai-java:4.75.1`.126 

127 

128 

129Before running this example, install `ws` for Node.js.

130 

131 

132 

133 

134 

135 

136 

137Before running this example, install `websocket-client` and `sounddevice` for Python.

138 

139 

140 

141 

142 

143 

144 

145Before running this example, install `openai` version 0.121.0 and `async-websocket` for Ruby (`gem install openai -v 0.121.0` and `gem install async-websocket`).

146 

147 

148 

149 

150 

151 

152 

153Before running this example, add the Maven dependency `com.openai:openai-java:4.75.1`.

154 

155 

156 

157 

158 

159 

127 160 

128The Java examples cover connection setup, language configuration, and audio input separately. They don't show a complete translation workflow: the Java SDK supports receiving events and finishing a session, but this guide doesn't include Java examples for those steps. Use the Node.js or Python examples to follow the complete workflow below.161The Java examples cover connection setup, language configuration, and audio input separately. They don't show a complete translation workflow: the Java SDK supports receiving events and finishing a session, but this guide doesn't include Java examples for those steps. Use the Node.js or Python examples to follow the complete workflow below.

129 162 


212```248```

213 249 

214```ruby250```ruby

215require "async"251require "openai"

216require "async/http/endpoint"252require "base64"

217require "async/websocket/client"253 

218require "json"254client = OpenAI::Client.new

219 255client.realtime.connect_translation(

220endpoint = Async::HTTP::Endpoint.parse("wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate", timeout: 10, alpn_protocols: ["http/1.1"])256 model: "gpt-realtime-translate",

221headers = {257 request_options: { extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" } }

222 "Authorization" => "Bearer #{ENV.fetch("OPENAI_API_KEY")}",258) do |session|

223 "OpenAI-Safety-Identifier" => "hashed-user-id"259 created = session.receive

224}260 unless created.is_a?(OpenAI::Realtime::RealtimeTranslationSessionCreatedEvent)

225Sync do |task|261 raise "Connection closed before session creation"

226 task.with_timeout(120) do

227 Async::WebSocket::Client.connect(endpoint, headers: headers) do |connection|

228 message = connection.read or raise "Connection closed before session creation"

229 event = JSON.parse(message.to_str)

230 raise "Expected session.created: #{event}" unless event["type"] == "session.created"

231 

232 puts(event.fetch("type"))

233 end

234 end262 end

263 

264 puts created.type

265 # Insert the configuration, audio, listener, and closing steps here.

235end266end

236```267```

237 268 

238 269 

239For Ruby, insert the following configuration and audio-append snippets inside the `Async::WebSocket::Client.connect` block, after the session-created check and before the block ends. Keep the connection open while sending audio and receiving translation events.270 

271 

272 

273For Ruby, insert the configuration, audio-append, listener, and closing snippets below inside the same `client.realtime.connect_translation` block, after the session-created check. The listener snippet defines the event handler. The closing snippet calls that handler while `session.finish` drains the existing connection through `session.closed`. Keep all four steps inside the block so they use the configured Spanish session.

274 

275 

276 

277 

278 

279 

240 280 

241The Java connection example closes the socket when its `try` block ends. The Java configuration and audio-input examples require an open `TranslationConnection`; keep it open while sending audio and receiving output. Before leaving the block, finish the session and drain its events through `session.closed` as described in [Close a WebSocket session](#close-a-websocket-session).281The Java connection example closes the socket when its `try` block ends. The Java configuration and audio-input examples require an open `TranslationConnection`; keep it open while sending audio and receiving output. Before leaving the block, finish the session and drain its events through `session.closed` as described in [Close a WebSocket session](#close-a-websocket-session).

242 282 


316```359```

317 360 

318```ruby361```ruby

319connection.write(JSON.generate(type: "session.update", session: { audio: { output: { language: "es" } } }))362session.send_event(type: "session.update", session: { audio: { output: { language: "es" } } })

320connection.flush363updated = session.receive

364unless updated.is_a?(OpenAI::Realtime::RealtimeTranslationSessionUpdatedEvent)

365 raise "Connection closed before session update"

366end

367 

368puts updated.type

321```369```

322 370 

323 371 


373```421```

374 422 

375```ruby423```ruby

376require "base64"424# speech.pcm contains nonempty mono PCM16 audio sampled at 24 kHz.

425raise "Expected nonempty PCM16 audio" unless File.size("speech.pcm").positive? && File.size("speech.pcm").even?

377 426 

378File.open("speech.pcm", "rb") do |audio|427File.open("speech.pcm", "rb") do |input|

379 while (chunk = audio.read(4_800))428 while (chunk = input.read(4800))

380 connection.write(JSON.generate(type: "session.input_audio_buffer.append", audio: Base64.strict_encode64(chunk)))429 session.send_event(type: "session.input_audio_buffer.append", audio: Base64.strict_encode64(chunk))

381 connection.flush

382 end430 end

383end431end

384```432```


486}534}

487```535```

488 536 

537```ruby

538handle_translation_event = lambda do |event, output|

539 case event

540 when OpenAI::Realtime::RealtimeErrorEvent

541 raise "Translation error: #{event.error.message}"

542 when OpenAI::Realtime::RealtimeTranslationOutputTranscriptDeltaEvent

543 print event.delta

544 $stdout.flush

545 when OpenAI::Realtime::RealtimeTranslationOutputAudioDeltaEvent

546 pcm = Base64.strict_decode64(event.delta)

547 output.write(pcm)

548 warn "Received audio bytes: #{pcm.bytesize}"

549 end

550end

551```

552 

489 553 

490In Go, run `listen` concurrently while sending audio. It closes the transport after receiving `session.closed`.554In Go, run `listen` concurrently while sending audio. It closes the transport after receiving `session.closed`.

491 555 


647}711}

648```712```

649 713 

714```ruby

715# Finish the existing session and consume its trailing output through session.closed.

716File.open("translated.pcm", "wb") do |output|

717 session.finish(timeout: 15) do |event|

718 handle_translation_event.call(event, output)

719 end

720end

721# translated.pcm is ready for your application's 24 kHz PCM16 audio player.

722```

723 

650 724 

651## Build listen-along translation725## Build listen-along translation

652 726 

Details

251}251}

252```252```

253 253 

254```ruby

255require "openai"

256require "webrick"

257require "json"

258require "uri"

259 

260client = OpenAI::Client.new(max_retries: 0)

261server = WEBrick::HTTPServer.new(

262 BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "3000")),

263 Logger: WEBrick::Log.new($stderr), AccessLog: []

264)

265server.mount_proc("/session") do |request, response|

266 unless request.request_method == "POST" && request.path == "/session"

267 response.status = 405

268 next

269 end

270 begin

271 options = { extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" } }

272 # Forward the data-channel ID negotiated by the WARP client.

273 dcid = URI.decode_www_form(request.query_string.to_s).to_h["dcid"]

274 options[:extra_query] = { dcid: dcid } if dcid

275 upstream = client.realtime.calls.create(

276 sdp: request.body.to_s,

277 session: {

278 type: :realtime,

279 model: "gpt-realtime-2.1",

280 audio: { output: { voice: :marin } }

281 },

282 request_options: options

283 )

284 response.status = upstream.status

285 response["Content-Type"] = "application/sdp"

286 # Resolve against the API origin before WEBrick normalizes Location headers.

287 location = upstream.headers["location"]

288 response["Location"] = URI.join(client.base_url.to_s, location).to_s if location

289 response.body = upstream.body.to_a.join

290 rescue OpenAI::Errors::APIError => error

291 response.status = error.status || 502

292 response["Content-Type"] = "application/json"

293 response.body = JSON.generate(error.body)

294 rescue

295 response.status = 500

296 response["Content-Type"] = "application/json"

297 response.body = JSON.generate(error: "Failed to create session")

298 end

299end

300trap("INT") { server.shutdown }

301trap("TERM") { server.shutdown }

302server.start

303```

304 

254 305 

255### Connect from your browser306### Connect from your browser

256 307 

Details

4 4 

5**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.5**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.

6 6 

7Start 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 or GPT-6 model, see [reasoning mode](#reasoning-mode) for its `pro` option.7Start with `gpt-6.2-astra` for most reasoning workloads. For lower cost, consider [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra), or [`gpt-6-luna`](https://developers.openai.com/api/docs/models/gpt-6-luna) for the lowest cost and latency. If you're using a GPT-5.6 or GPT-6 model, see [reasoning mode](#reasoning-mode) for its `pro` option.

8 8 

9**Reasoning models work better with the [Responses9**Reasoning models work better with the [Responses

10 API](https://developers.openai.com/api/docs/guides/migrate-to-responses)**. While the Chat Completions API10 API](https://developers.openai.com/api/docs/guides/migrate-to-responses)**. While the Chat Completions API


28`;28`;

29 29 

30const response = await openai.responses.create({30const response = await openai.responses.create({

31 model: "gpt-6-astra",31 model: "gpt-6.2-astra",

32 reasoning: { effort: "low" },32 reasoning: { effort: "low" },

33 input: [33 input: [

34 {34 {


52"""52"""

53 53 

54response = client.responses.create(54response = client.responses.create(

55 model="gpt-6-astra",55 model="gpt-6.2-astra",

56 reasoning={"effort": "low"},56 reasoning={"effort": "low"},

57 input=[{"role": "user", "content": prompt}],57 input=[{"role": "user", "content": prompt}],

58)58)


77format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`77format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`

78 78 

79 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{79 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

80 Model: "gpt-6-astra",80 Model: "gpt-6.2-astra",

81 Reasoning: responses.ReasoningParam{81 Reasoning: responses.ReasoningParam{

82 Effort: responses.ReasoningEffortLow,82 Effort: responses.ReasoningEffortLow,

83 },83 },


109 109 

110ResponseCreateParams params =110ResponseCreateParams params =

111 ResponseCreateParams.builder()111 ResponseCreateParams.builder()

112 .model("gpt-6-astra")112 .model("gpt-6.2-astra")

113 .input(prompt)113 .input(prompt)

114 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())114 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

115 .build();115 .build();


135 """;135 """;

136CreateResponseOptions options = new()136CreateResponseOptions options = new()

137{137{

138 Model = "gpt-6-astra",138 Model = "gpt-6.2-astra",

139 ReasoningOptions = new ResponseReasoningOptions139 ReasoningOptions = new ResponseReasoningOptions

140 {140 {

141 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,141 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,


158PROMPT158PROMPT

159 159 

160response = client.responses.create(160response = client.responses.create(

161 model: "gpt-6-astra",161 model: "gpt-6.2-astra",

162 reasoning: { effort: :low },162 reasoning: { effort: :low },

163 input: prompt163 input: prompt

164)164)


171 -H "Content-Type: application/json" \171 -H "Content-Type: application/json" \

172 -H "Authorization: Bearer $OPENAI_API_KEY" \172 -H "Authorization: Bearer $OPENAI_API_KEY" \

173 -d '{173 -d '{

174 "model": "gpt-6-astra",174 "model": "gpt-6.2-astra",

175 "reasoning": {"effort": "low"},175 "reasoning": {"effort": "low"},

176 "input": [176 "input": [

177 {177 {


194 Completions) to `none` returns HTTP 400. [GPT-6.1 Sol](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra#gpt-61-sol)194 Completions) to `none` returns HTTP 400. [GPT-6.1 Sol](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra#gpt-61-sol)

195 does not support `none` or `minimal` and defaults to `medium`.195 does not support `none` or `minimal` and defaults to `medium`.

196 196 

197[GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra) and [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol) reject requests that set `reasoning.effort` (Responses) or `reasoning_effort` (Chat Completions) to `none`.

198 

197Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for function199Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for function

198calling. Chat Completions does not support function calling with GPT-6 Astra or200calling. Chat Completions does not support function calling with GPT-6 Astra or

199GPT-6.1 Sol.201GPT-6.1 Sol.


226 -H "Content-Type: application/json" \228 -H "Content-Type: application/json" \

227 -H "Authorization: Bearer $OPENAI_API_KEY" \229 -H "Authorization: Bearer $OPENAI_API_KEY" \

228 -d '{230 -d '{

229 "model": "gpt-6.1-sol",231 "model": "gpt-6.2-sol",

230 "reasoning": {232 "reasoning": {

231 "mode": "pro",233 "mode": "pro",

232 "effort": "medium"234 "effort": "medium"


300`;302`;

301 303 

302const response = await openai.responses.create({304const response = await openai.responses.create({

303 model: "gpt-6-astra",305 model: "gpt-6.2-astra",

304 reasoning: { effort: "medium" },306 reasoning: { effort: "medium" },

305 input: [307 input: [

306 {308 {


335"""337"""

336 338 

337response = client.responses.create(339response = client.responses.create(

338 model="gpt-6-astra",340 model="gpt-6.2-astra",

339 reasoning={"effort": "medium"},341 reasoning={"effort": "medium"},

340 input=[{"role": "user", "content": prompt}],342 input=[{"role": "user", "content": prompt}],

341 max_output_tokens=300,343 max_output_tokens=300,


369format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`371format '[1,2],[3,4],[5,6]' and prints the transpose in the same format.`

370 372 

371 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{373 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

372 Model: "gpt-6-astra",374 Model: "gpt-6.2-astra",

373 MaxOutputTokens: openai.Int(300),375 MaxOutputTokens: openai.Int(300),

374 Reasoning: responses.ReasoningParam{376 Reasoning: responses.ReasoningParam{

375 Effort: responses.ReasoningEffortMedium,377 Effort: responses.ReasoningEffortMedium,


402 404 

403ResponseCreateParams params =405ResponseCreateParams params =

404 ResponseCreateParams.builder()406 ResponseCreateParams.builder()

405 .model("gpt-6-astra")407 .model("gpt-6.2-astra")

406 .input(408 .input(

407 "Write a bash script that takes a matrix represented as a string with format "409 "Write a bash script that takes a matrix represented as a string with format "

408 + "'[1,2],[3,4],[5,6]' and prints the transpose in the same format.")410 + "'[1,2],[3,4],[5,6]' and prints the transpose in the same format.")


435 437 

436CreateResponseOptions options = new()438CreateResponseOptions options = new()

437{439{

438 Model = "gpt-6-astra",440 Model = "gpt-6.2-astra",

439 MaxOutputTokenCount = 300,441 MaxOutputTokenCount = 300,

440 ReasoningOptions = new ResponseReasoningOptions442 ReasoningOptions = new ResponseReasoningOptions

441 {443 {


487PROMPT489PROMPT

488 490 

489response = client.responses.create(491response = client.responses.create(

490 model: "gpt-6-astra",492 model: "gpt-6.2-astra",

491 max_output_tokens: 300,493 max_output_tokens: 300,

492 reasoning: { effort: :medium },494 reasoning: { effort: :medium },

493 input: prompt495 input: prompt


696 -H "Content-Type: application/json" \698 -H "Content-Type: application/json" \

697 -H "Authorization: Bearer $OPENAI_API_KEY" \699 -H "Authorization: Bearer $OPENAI_API_KEY" \

698 -d '{700 -d '{

699 "model": "gpt-6-astra",701 "model": "gpt-6.2-astra",

700 "store": false,702 "store": false,

701 "reasoning": {"effort": "medium"},703 "reasoning": {"effort": "medium"},

702 "input": "What is the weather like today?",704 "input": "What is the weather like today?",


945 947 

946You can carry reasoning items forward using `previous_response_id`. If you manage conversation history yourself, include the original input and all [output](https://developers.openai.com/api/reference/resources/responses#responses/object-output) items from each response in the [input](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-input) of the next request. Keep those items in their original order and append new items.948You can carry reasoning items forward using `previous_response_id`. If you manage conversation history yourself, include the original input and all [output](https://developers.openai.com/api/reference/resources/responses#responses/object-output) items from each response in the [input](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-input) of the next request. Keep those items in their original order and append new items.

947 949 

948For newer frontier models, changes to the history preceding a reasoning item can cause the API to drop that reasoning. See [Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/preserved-reasoning) for guidance on changing instructions and tool outputs, and managing long conversations.950For newer frontier models, changes to the history preceding a reasoning item can cause the API to drop that reasoning. See [Keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) for guidance on changing instructions and tool outputs, and managing long conversations.

949 951 

950## Change reasoning mid-conversation952## Change reasoning mid-conversation

951 953 


1162 1164 

1163You can set `reasoning.effort` and [`text.format`](https://developers.openai.com/api/docs/guides/structured-outputs?api-mode=responses#change-the-response-format-mid-conversation) in the same `configuration_update` item. An update to either setting alone preserves the other.1165You can set `reasoning.effort` and [`text.format`](https://developers.openai.com/api/docs/guides/structured-outputs?api-mode=responses#change-the-response-format-mid-conversation) in the same `configuration_update` item. An update to either setting alone preserves the other.

1164 1166 

1165Do not combine configuration updates with automatic compaction or automatic truncation. The standalone `/responses/compact` endpoint also rejects histories containing these updates.1167You can combine configuration updates with automatic compaction through `context_management`. If earlier updates exist, the API emits a fresh update after the compaction item with the latest effort and output format. Automatic truncation and the standalone `/responses/compact` endpoint still reject histories containing updates. See the [Compaction guide](https://developers.openai.com/api/docs/guides/compaction#continue-with-configuration-updates-and-tools) for how to prepare a standalone request.

1166 1168 

1167You can still explicitly compact history by including a `compaction_trigger` item in a `/responses` request. After compaction, add a fresh `configuration_update` before the next user message. Restate each setting you changed, including the format if you changed it.1169You can still explicitly compact history by including a `compaction_trigger` item in a `/responses` request. After compaction, add a fresh `configuration_update` before the next user message. Restate each setting you changed, including the format if you changed it.

1168 1170 

1169Normal 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).1171Normal 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).

1170 1172 

1173## Reasoning item removal across requests

1174 

1175The API removes reasoning items if you switch model families, downgrade to a less capable model, or switch organizations or users mid-conversation as one of our safeguards against distillation. Starting with 6.2, reasoning items with a `safety_identifier` change or a modified conversation history (the prefix) will also be removed.

1176 

1177You can use `input_transformations` in the response to diagnose unintended removal:

1178 

1179| Reason | When the API removes the item |

1180| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1181| `prefix_mismatch` | On GPT-6.2 and later, you insert or edit content before the reasoning item. For example, rewriting an earlier tool result changes the prefix. Deleting whole items without editing the remaining items, or appending new items after the reasoning item, does not by itself trigger this reason. |

1182| `end_user_mismatch` | On GPT-6.2 and later, the `safety_identifier` on the request that created the item differs from the one on the request that reuses it. This includes supplying an identifier on only one of the two requests. Using the same identifier on both requests, or omitting it from both, passes this check. |

1183| `model_mismatch` | You switch model families or move to a less capable model within the same family. Moving to a more capable model within the same family preserves compatible reasoning if the other checks pass. |

1184| `organization_mismatch` | You reuse an item from another organization, or from a different workspace under a different user. |

1185| `turn_boundary` | The item comes from an earlier turn and the model uses only current-turn reasoning. Models released before GPT-5.6 use current-turn reasoning by default. On supported models, `reasoning.context` controls whether earlier turns are eligible. |

1186 

1171## Reasoning summaries1187## Reasoning summaries

1172 1188 

1173While 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.1189While 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.


1185const openai = new OpenAI();1201const openai = new OpenAI();

1186 1202 

1187const response = await openai.responses.create({1203const response = await openai.responses.create({

1188 model: "gpt-6-astra",1204 model: "gpt-6.2-astra",

1189 input: "What is the capital of France?",1205 input: "What is the capital of France?",

1190 reasoning: {1206 reasoning: {

1191 effort: "low",1207 effort: "low",


1202client = OpenAI()1218client = OpenAI()

1203 1219 

1204response = client.responses.create(1220response = client.responses.create(

1205 model="gpt-6-astra",1221 model="gpt-6.2-astra",

1206 input="What is the capital of France?",1222 input="What is the capital of France?",

1207 reasoning={"effort": "low", "summary": "auto"},1223 reasoning={"effort": "low", "summary": "auto"},

1208)1224)


1225 client := openai.NewClient()1241 client := openai.NewClient()

1226 1242 

1227 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1243 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1228 Model: "gpt-6-astra",1244 Model: "gpt-6.2-astra",

1229 Input: responses.ResponseNewParamsInputUnion{1245 Input: responses.ResponseNewParamsInputUnion{

1230 OfString: openai.String("What is the capital of France?"),1246 OfString: openai.String("What is the capital of France?"),

1231 },1247 },


1251 1267 

1252ResponseCreateParams params =1268ResponseCreateParams params =

1253 ResponseCreateParams.builder()1269 ResponseCreateParams.builder()

1254 .model("gpt-6-astra")1270 .model("gpt-6.2-astra")

1255 .input("What is the capital of France?")1271 .input("What is the capital of France?")

1256 .reasoning(1272 .reasoning(

1257 Reasoning.builder()1273 Reasoning.builder()


1275 1291 

1276CreateResponseOptions options = new()1292CreateResponseOptions options = new()

1277{1293{

1278 Model = "gpt-6-astra",1294 Model = "gpt-6.2-astra",

1279 ReasoningOptions = new ResponseReasoningOptions1295 ReasoningOptions = new ResponseReasoningOptions

1280 {1296 {

1281 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,1297 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,


1298client = OpenAI::Client.new1314client = OpenAI::Client.new

1299 1315 

1300response = client.responses.create(1316response = client.responses.create(

1301 model: "gpt-6-astra",1317 model: "gpt-6.2-astra",

1302 input: "What is the capital of France?",1318 input: "What is the capital of France?",

1303 reasoning: {1319 reasoning: {

1304 effort: :low,1320 effort: :low,


1314 -H "Content-Type: application/json" \1330 -H "Content-Type: application/json" \

1315 -H "Authorization: Bearer $OPENAI_API_KEY" \1331 -H "Authorization: Bearer $OPENAI_API_KEY" \

1316 -d '{1332 -d '{

1317 "model": "gpt-6-astra",1333 "model": "gpt-6.2-astra",

1318 "input": "What is the capital of France?",1334 "input": "What is the capital of France?",

1319 "reasoning": {1335 "reasoning": {

1320 "effort": "low",1336 "effort": "low",


1378const client = new OpenAI();1394const client = new OpenAI();

1379 1395 

1380const response = await client.responses.create({1396const response = await client.responses.create({

1381 model: "gpt-6-astra",1397 model: "gpt-6.2-astra",

1382 input: [1398 input: [

1383 {1399 {

1384 role: "assistant",1400 role: "assistant",


1407client = OpenAI()1423client = OpenAI()

1408 1424 

1409response = client.responses.create(1425response = client.responses.create(

1410 model="gpt-6-astra",1426 model="gpt-6.2-astra",

1411 input=[1427 input=[

1412 {1428 {

1413 "role": "assistant",1429 "role": "assistant",


1453 )1469 )

1454 finalAnswer.OfMessage.Phase = responses.EasyInputMessagePhaseFinalAnswer1470 finalAnswer.OfMessage.Phase = responses.EasyInputMessagePhaseFinalAnswer

1455 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1471 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1456 Model: "gpt-6-astra",1472 Model: "gpt-6.2-astra",

1457 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1473 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

1458 commentary,1474 commentary,

1459 finalAnswer,1475 finalAnswer,


1477 1493 

1478ResponseCreateParams params =1494ResponseCreateParams params =

1479 ResponseCreateParams.builder()1495 ResponseCreateParams.builder()

1480 .model("gpt-6-astra")1496 .model("gpt-6.2-astra")

1481 .inputOfResponse(1497 .inputOfResponse(

1482 List.of(1498 List.of(

1483 ResponseInputItem.ofEasyInputMessage(1499 ResponseInputItem.ofEasyInputMessage(


1513client = OpenAI::Client.new1529client = OpenAI::Client.new

1514 1530 

1515response = client.responses.create(1531response = client.responses.create(

1516 model: "gpt-6-astra",1532 model: "gpt-6.2-astra",

1517 input: [1533 input: [

1518 {1534 {

1519 role: :assistant,1535 role: :assistant,


1595`.trim();1611`.trim();

1596 1612 

1597const response = await openai.responses.create({1613const response = await openai.responses.create({

1598 model: "gpt-6-astra",1614 model: "gpt-6.2-astra",

1599 input: [1615 input: [

1600 {1616 {

1601 role: "user",1617 role: "user",


1642"""1658"""

1643 1659 

1644response = client.responses.create(1660response = client.responses.create(

1645 model="gpt-6-astra",1661 model="gpt-6.2-astra",

1646 input=[1662 input=[

1647 {1663 {

1648 "role": "user",1664 "role": "user",


1680];`1696];`

1681 1697 

1682 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1698 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1683 Model: "gpt-6-astra",1699 Model: "gpt-6.2-astra",

1684 Input: responses.ResponseNewParamsInputUnion{1700 Input: responses.ResponseNewParamsInputUnion{

1685 OfString: openai.String(prompt),1701 OfString: openai.String(prompt),

1686 },1702 },


1715 .strip();1731 .strip();

1716 1732 

1717ResponseCreateParams params =1733ResponseCreateParams params =

1718 ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();1734 ResponseCreateParams.builder().model("gpt-6.2-astra").input(prompt).build();

1719 1735 

1720client.responses().create(params).output().stream()1736client.responses().create(params).output().stream()

1721 .flatMap(item -> item.message().stream())1737 .flatMap(item -> item.message().stream())


1760 }1776 }

1761 """;1777 """;

1762ResponseResult response = await client.CreateResponseAsync(1778ResponseResult response = await client.CreateResponseAsync(

1763 "gpt-6-astra",1779 "gpt-6.2-astra",

1764 [ResponseItem.CreateUserMessageItem(prompt)]1780 [ResponseItem.CreateUserMessageItem(prompt)]

1765);1781);

1766Console.WriteLine(response.GetOutputText());1782Console.WriteLine(response.GetOutputText());


1785PROMPT1801PROMPT

1786 1802 

1787response = client.responses.create(1803response = client.responses.create(

1788 model: "gpt-6-astra",1804 model: "gpt-6.2-astra",

1789 input: prompt1805 input: prompt

1790)1806)

1791 1807 


1826`.trim();1842`.trim();

1827 1843 

1828const response = await openai.responses.create({1844const response = await openai.responses.create({

1829 model: "gpt-6-astra",1845 model: "gpt-6.2-astra",

1830 input: [1846 input: [

1831 {1847 {

1832 role: "user",1848 role: "user",


1855"""1871"""

1856 1872 

1857response = client.responses.create(1873response = client.responses.create(

1858 model="gpt-6-astra",1874 model="gpt-6.2-astra",

1859 input=[1875 input=[

1860 {1876 {

1861 "role": "user",1877 "role": "user",


1888directory structure you will need, then return each file in full.`1904directory structure you will need, then return each file in full.`

1889 1905 

1890 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1906 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1891 Model: "gpt-6-astra",1907 Model: "gpt-6.2-astra",

1892 Input: responses.ResponseNewParamsInputUnion{1908 Input: responses.ResponseNewParamsInputUnion{

1893 OfString: openai.String(prompt),1909 OfString: openai.String(prompt),

1894 },1910 },


1917 .strip();1933 .strip();

1918 1934 

1919ResponseCreateParams params =1935ResponseCreateParams params =

1920 ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();1936 ResponseCreateParams.builder().model("gpt-6.2-astra").input(prompt).build();

1921 1937 

1922client.responses().create(params).output().stream()1938client.responses().create(params).output().stream()

1923 .flatMap(item -> item.message().stream())1939 .flatMap(item -> item.message().stream())


1942 Plan the directory structure, then return each file in full.1958 Plan the directory structure, then return each file in full.

1943 Only supply your reasoning at the beginning and end, not throughout the code.1959 Only supply your reasoning at the beginning and end, not throughout the code.

1944 """;1960 """;

1945ResponseResult response = await client.CreateResponseAsync("gpt-6-astra", prompt);1961ResponseResult response = await client.CreateResponseAsync("gpt-6.2-astra", prompt);

1946 1962 

1947Console.WriteLine(response.GetOutputText());1963Console.WriteLine(response.GetOutputText());

1948```1964```


1960PROMPT1976PROMPT

1961 1977 

1962response = client.responses.create(1978response = client.responses.create(

1963 model: "gpt-6-astra",1979 model: "gpt-6.2-astra",

1964 input: prompt1980 input: prompt

1965)1981)

1966 1982 


1997`;2013`;

1998 2014 

1999const response = await openai.responses.create({2015const response = await openai.responses.create({

2000 model: "gpt-6-astra",2016 model: "gpt-6.2-astra",

2001 input: [2017 input: [

2002 {2018 {

2003 role: "user",2019 role: "user",


2022"""2038"""

2023 2039 

2024response = client.responses.create(2040response = client.responses.create(

2025 model="gpt-6-astra", input=[{"role": "user", "content": prompt}]2041 model="gpt-6.2-astra", input=[{"role": "user", "content": prompt}]

2026)2042)

2027 2043 

2028print(response.output_text)2044print(response.output_text)


2046research into new antibiotics? Why should we consider them?`2062research into new antibiotics? Why should we consider them?`

2047 2063 

2048 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2064 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2049 Model: "gpt-6-astra",2065 Model: "gpt-6.2-astra",

2050 Input: responses.ResponseNewParamsInputUnion{2066 Input: responses.ResponseNewParamsInputUnion{

2051 OfString: openai.String(prompt),2067 OfString: openai.String(prompt),

2052 },2068 },


2073 .strip();2089 .strip();

2074 2090 

2075ResponseCreateParams params =2091ResponseCreateParams params =

2076 ResponseCreateParams.builder().model("gpt-6-astra").input(prompt).build();2092 ResponseCreateParams.builder().model("gpt-6.2-astra").input(prompt).build();

2077 2093 

2078client.responses().create(params).output().stream()2094client.responses().create(params).output().stream()

2079 .flatMap(item -> item.message().stream())2095 .flatMap(item -> item.message().stream())


2096 new antibiotics? Why should we consider them?2112 new antibiotics? Why should we consider them?

2097 """;2113 """;

2098ResponseResult response = await client.CreateResponseAsync(2114ResponseResult response = await client.CreateResponseAsync(

2099 "gpt-6-astra",2115 "gpt-6.2-astra",

2100 [ResponseItem.CreateUserMessageItem(prompt)]2116 [ResponseItem.CreateUserMessageItem(prompt)]

2101);2117);

2102Console.WriteLine(response.GetOutputText());2118Console.WriteLine(response.GetOutputText());


2113PROMPT2129PROMPT

2114 2130 

2115response = client.responses.create(2131response = client.responses.create(

2116 model: "gpt-6-astra",2132 model: "gpt-6.2-astra",

2117 input: prompt2133 input: prompt

2118)2134)

2119 2135 

Details

6 6 

7Multi-agent lets a model spin up and coordinate subagents in parallel, synthesizing their work to provide a final response. This is especially effective for applications with complex tasks that benefit from parallel work delegation, such as codebase exploration, documentation, and implementation.7Multi-agent lets a model spin up and coordinate subagents in parallel, synthesizing their work to provide a final response. This is especially effective for applications with complex tasks that benefit from parallel work delegation, such as codebase exploration, documentation, and implementation.

8 8 

9Multi-agent is available as a beta feature with [GPT-6.1 Sol](https://developers.openai.com/api/docs/models/gpt-6.1-sol) and all GPT-5.6 models. Check the model page before enabling Multi-agent in your application.9Multi-agent is available in beta with [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra), [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol), [GPT-6.1 Sol](https://developers.openai.com/api/docs/models/gpt-6.1-sol), and all GPT-5.6 models. Check the model page before enabling Multi-agent in your application.

10 10 

11## When to use Multi-agent11## When to use Multi-agent

12 12 


53 53 

54async function reviewPullRequest(diff: string) {54async function reviewPullRequest(diff: string) {

55 const response = await client.beta.responses.create({55 const response = await client.beta.responses.create({

56 model: "gpt-6.1-sol",56 model: "gpt-6.2-sol",

57 input:57 input:

58 "Review the pull-request diff below with three agents: one for " +58 "Review the pull-request diff below with three agents: one for " +

59 "correctness, one for security, and one for missing tests. " +59 "correctness, one for security, and one for missing tests. " +


89 89 

90def review_pull_request(diff: str) -> str:90def review_pull_request(diff: str) -> str:

91 response = client.beta.responses.create(91 response = client.beta.responses.create(

92 model="gpt-6.1-sol",92 model="gpt-6.2-sol",

93 input=(93 input=(

94 "Review the pull-request diff below with three agents: one for "94 "Review the pull-request diff below with three agents: one for "

95 "correctness, one for security, and one for missing tests. "95 "correctness, one for security, and one for missing tests. "


118 )118 )

119```119```

120 120 

121```ruby

122def review_pull_request(client, diff)

123 response = client.beta.responses.create(

124 model: "gpt-6.2-sol",

125 input: "Review the pull-request diff below with three agents: one for " \

126 "correctness, one for security, and one for missing tests. " \

127 "Reconcile duplicate or conflicting findings, then return a " \

128 "prioritized review with file and line references.\n\n<diff>\n#{diff}\n</diff>",

129 multi_agent: {

130 enabled: true,

131 max_concurrent_subagents: 3

132 },

133 betas: ["responses_multi_agent=v1"]

134 )

135 

136 response.output.filter_map do |item|

137 next unless item.type == :message && item.agent&.agent_name == "/root" && item.phase == :final_answer

138 

139 item.content.filter_map { |part| part.text if part.type == :output_text }.join

140 end.join

141end

142```

143 

121 144 

122`max_concurrent_subagents` sets the maximum number of subagents that can be active simultaneously across the entire agent tree. It includes all descendants—children, grandchildren, and deeper subagents—but excludes the root agent.145`max_concurrent_subagents` sets the maximum number of subagents that can be active simultaneously across the entire agent tree. It includes all descendants—children, grandchildren, and deeper subagents—but excludes the root agent.

123 146 


248 const itemAgents = new Map();271 const itemAgents = new Map();

249 272 

250 const stream = await client.beta.responses.create({273 const stream = await client.beta.responses.create({

251 model: "gpt-6.1-sol",274 model: "gpt-6.2-sol",

252 // Replay Beta output unchanged, including agent metadata. The SDK input275 // Replay Beta output unchanged, including agent metadata. The SDK input

253 // union is narrower than the agent_message content returned by the API.276 // union is narrower than the agent_message content returned by the API.

254 input: history as OpenAI.Beta.Responses.BetaResponseInput,277 input: history as OpenAI.Beta.Responses.BetaResponseInput,


370 pending_calls = []393 pending_calls = []

371 item_agents: dict[int, str] = {}394 item_agents: dict[int, str] = {}

372 395 

373 stream = client.beta.responses.create(396 completed = False

374 model="gpt-6.1-sol",397 with client.beta.responses.create(

398 model="gpt-6.2-sol",

399 instructions=(

400 "After launching both subagents, call get_proposal for alpha yourself "

401 "before waiting for their findings. Use that direct result to check the final comparison."

402 ),

375 input=history,403 input=history,

376 tools=tools,404 tools=tools,

377 store=False,405 store=False,


381 },409 },

382 stream=True,410 stream=True,

383 betas=["responses_multi_agent=v1"],411 betas=["responses_multi_agent=v1"],

384 )412 ) as stream:

385 for event in stream:413 for event in stream:

386 if event.type == "response.output_item.added":414 if event.type == "response.output_item.added":

387 item_agents[event.output_index] = agent_name(event.item)415 item_agents[event.output_index] = agent_name(event.item)


398 pending_calls.append(event.item)426 pending_calls.append(event.item)

399 elif event.type == "response.completed":427 elif event.type == "response.completed":

400 print(f"\nUsage: {event.response.usage}", file=sys.stderr)428 print(f"\nUsage: {event.response.usage}", file=sys.stderr)

401 break429 completed = True

402 elif event.type in {430 elif event.type in {

403 "error",431 "error",

404 "response.failed",432 "response.failed",


406 }:434 }:

407 raise RuntimeError(event)435 raise RuntimeError(event)

408 436 

437 if not completed:

438 raise RuntimeError("Stream ended without a completed response")

439 

409 history.extend(output_items)440 history.extend(output_items)

410 441 

411 for call in pending_calls:442 for call in pending_calls:


421 break452 break

422```453```

423 454 

455```ruby

456require "openai"

457require "json"

458 

459client = OpenAI::Client.new

460proposals = {

461 "alpha" => {

462 estimated_weeks: 6,

463 risk: "medium"

464 },

465 "beta" => {

466 estimated_weeks: 8,

467 risk: "low"

468 }

469}

470tools = [

471 {

472 type: :function,

473 

474 name: "get_proposal",

475 description: "Return details for a proposal that the agents should compare.",

476 parameters: {

477 type: "object",

478 

479 properties: {

480 proposal: {

481 type: "string",

482 enum: ["alpha", "beta"]

483 }

484 },

485 required: ["proposal"],

486 

487 additionalProperties: false

488 },

489 strict: true

490 }

491]

492history = [

493 {

494 role: :user,

495 

496 content: "Use two subagents, one for proposal alpha and one for proposal beta. " \

497 "Have each call get_proposal, then compare their findings."

498 }

499]

500 

501loop do

502 output_items = []

503 pending_calls = []

504 item_agents = {}

505 state = { completed: false }

506 stream = client.beta.responses.stream_raw(

507 model: "gpt-6.2-sol", input: history, tools: tools, store: false,

508 instructions: "After launching both subagents, call get_proposal for alpha yourself " \

509 "before waiting for their findings. Use that direct result to check the final comparison.",

510 multi_agent: {

511 enabled: true,

512 max_concurrent_subagents: 3

513 },

514 betas: ["responses_multi_agent=v1"]

515 )

516 begin

517 stream.each do |event|

518 case event

519 when OpenAI::Models::Beta::BetaResponseOutputItemAddedEvent

520 item_agents[event.output_index] = event.item.agent&.agent_name || "/root"

521 when OpenAI::Models::Beta::BetaResponseTextDeltaEvent

522 agent = item_agents.fetch(event.output_index, "/root")

523 if agent == "/root"

524 $stdout.print(event.delta)

525 $stdout.flush

526 else

527 $stderr.print("[#{agent}] #{event.delta}")

528 $stderr.flush

529 end

530 when OpenAI::Models::Beta::BetaResponseOutputItemDoneEvent

531 output_items << event.item

532 pending_calls << event.item if event.item.is_a?(OpenAI::Models::Beta::BetaResponseFunctionToolCall)

533 when OpenAI::Models::Beta::BetaResponseCompletedEvent

534 state[:completed] = true

535 warn("\nUsage: #{event.response.usage.to_json}")

536 when OpenAI::Models::Beta::BetaResponseErrorEvent,

537 OpenAI::Models::Beta::BetaResponseFailedEvent,

538 OpenAI::Models::Beta::BetaResponseIncompleteEvent

539 raise "Multi-agent response failed: #{event.type}"

540 end

541 end

542 ensure

543 stream.close

544 end

545 raise "Stream ended without a completed response" unless state[:completed]

546 

547 # Preserve every output item, including subagent calls, for the next turn.

548 history.concat(output_items)

549 pending_calls.each do |call|

550 raise "Unknown tool: #{call.name}" unless call.name == "get_proposal"

551 

552 proposal = JSON.parse(call.arguments).fetch("proposal")

553 history << {

554 type: :function_call_output,

555 

556 call_id: call.call_id,

557 output: JSON.generate(proposals.fetch(proposal))

558 }

559 end

560 break if pending_calls.empty?

561end

562```

563 

424 564 

425If one or more agents call developer-defined functions, execute every pending call and create a continuation request containing their outputs.565If one or more agents call developer-defined functions, execute every pending call and create a continuation request containing their outputs.

426 566 


533 while (pendingInput.length > 0) {673 while (pendingInput.length > 0) {

534 ws.send({674 ws.send({

535 type: "response.create",675 type: "response.create",

536 model: "gpt-6.1-sol",676 model: "gpt-6.2-sol",

537 store: true,677 store: true,

538 multi_agent: {678 multi_agent: {

539 enabled: true,679 enabled: true,


680 while pending_input:820 while pending_input:

681 request = {821 request = {

682 "type": "response.create",822 "type": "response.create",

683 "model": "gpt-6.1-sol",823 "model": "gpt-6.2-sol",

684 "store": True,824 "store": True,

685 "multi_agent": {"enabled": True},825 "multi_agent": {"enabled": True},

686 "tools": tools,826 "tools": tools,


782 )922 )

783```923```

784 924 

925```ruby

926require "async"

927require "async/http/endpoint"

928require "async/websocket/client"

929require "json"

930 

931PROPOSALS = {

932 "alpha" => {

933 estimated_weeks: 6,

934 risk: "medium"

935 },

936 "beta" => {

937 estimated_weeks: 8,

938 risk: "low"

939 }

940}.freeze

941 

942def process_tool_call(name, arguments)

943 raise "Unknown tool: #{name}" unless name == "get_proposal"

944 

945 JSON.generate(PROPOSALS.fetch(JSON.parse(arguments).fetch("proposal")))

946end

947 

948def run_multi_agent(connection, tools)

949 state = {

950 previous: nil,

951 input: [

952 {

953 role: "user",

954 content: $stdin.readline.chomp

955 }

956 ]

957 }

958 until state[:input].empty?

959 request = {

960 type: "response.create",

961 

962 model: "gpt-6.2-sol",

963 

964 store: true,

965 multi_agent: { enabled: true },

966 

967 tools: tools,

968 

969 input: state[:input]

970 }

971 request[:previous_response_id] = state[:previous] if state[:previous]

972 connection.write(JSON.generate(request))

973 connection.flush

974 round = {

975 response_id: nil,

976 completed: nil,

977 pending: 0,

978 retry: []

979 }

980 while (message = connection.read)

981 event = JSON.parse(message.to_str)

982 case event.fetch("type")

983 when "response.created"

984 round[:response_id] = event.fetch("response").fetch("id")

985 when "response.output_item.done"

986 item = event.fetch("item")

987 if item["type"] == "function_call"

988 raise "Function call arrived before response creation" unless round[:response_id]

989 

990 output = {

991 type: "function_call_output",

992 

993 call_id: item.fetch("call_id"),

994 output: process_tool_call(item.fetch("name"), item.fetch("arguments"))

995 }

996 round[:pending] += 1

997 connection.write(JSON.generate(type: "response.inject", response_id: round[:response_id], input: [output]))

998 connection.flush

999 end

1000 when "response.inject.created", "response.inject.failed"

1001 unless event.fetch("response_id") == round[:response_id] && round[:pending].positive?

1002 raise "Unexpected injection acknowledgement"

1003 end

1004 

1005 round[:pending] -= 1

1006 if event["type"] == "response.inject.failed"

1007 raise "Injection failed: #{event.fetch("error")}" unless event.fetch("error").fetch("code") == "response_already_completed"

1008 

1009 round[:retry].concat(event.fetch("input"))

1010 end

1011 when "response.completed"

1012 round[:completed] = event.fetch("response")

1013 when "error", "response.failed", "response.incomplete"

1014 raise "Multi-agent response failed: #{event}"

1015 end

1016 break if round[:completed] && round[:pending].zero?

1017 end

1018 raise "Connection closed before response completion" unless round[:completed]

1019 raise "Connection closed with unacknowledged results" unless round[:pending].zero?

1020 return round[:completed] if round[:retry].empty?

1021 

1022 state[:previous] = round[:completed].fetch("id")

1023 state[:input] = round[:retry]

1024 end

1025 raise "No response was created"

1026end

1027 

1028tools = [

1029 {

1030 type: "function",

1031 

1032 name: "get_proposal",

1033 description: "Return details for a proposal that the agents should compare.",

1034 parameters: {

1035 type: "object",

1036 

1037 properties: {

1038 proposal: {

1039 type: "string",

1040 enum: ["alpha", "beta"]

1041 }

1042 },

1043 required: ["proposal"],

1044 

1045 additionalProperties: false

1046 },

1047 strict: true

1048 }

1049]

1050base = ENV.fetch("OPENAI_BASE_URL", "https://api.openai.com/v1").sub(%r{/+\z}, "")

1051endpoint = Async::HTTP::Endpoint.parse("#{base.sub(/\Ahttp/, "ws")}/responses?beta=true", timeout: 30, alpn_protocols: ["http/1.1"])

1052headers = {

1053 "Authorization" => "Bearer #{ENV.fetch("OPENAI_API_KEY")}",

1054 "OpenAI-Beta" => "responses_multi_agent=v1"

1055}

1056Sync do |task|

1057 task.with_timeout(240) do

1058 Async::WebSocket::Client.connect(endpoint, headers: headers) do |connection|

1059 response = run_multi_agent(connection, tools)

1060 text = response.fetch("output").select do |item|

1061 item["type"] == "message" && item.dig("agent", "agent_name") == "/root" && item["phase"] == "final_answer"

1062 end.flat_map { |item| item.fetch("content") }.select { |part| part["type"] == "output_text" }.map { |part| part.fetch("text") }.join

1063 puts text

1064 end

1065 end

1066end

1067```

1068 

785 1069 

786After sending a `response.inject` event, keep reading from the WebSocket and handle the acknowledgement:1070After sending a `response.inject` event, keep reading from the WebSocket and handle the acknowledgement:

787 1071 

Details

2037 .join("\n");2037 .join("\n");

2038 2038 

2039const completion = await client.chat.completions.create({2039const completion = await client.chat.completions.create({

2040 model: "gpt-6-astra",2040 model: "gpt-6.2-astra",

2041 messages: [2041 messages: [

2042 {2042 {

2043 role: "developer",2043 role: "developer",


2061"\n".join("\n".join(c.text for c in result.content) for result in results.data)2061"\n".join("\n".join(c.text for c in result.content) for result in results.data)

2062 2062 

2063completion = client.chat.completions.create(2063completion = client.chat.completions.create(

2064 model="gpt-6-astra",2064 model="gpt-6.2-astra",

2065 messages=[2065 messages=[

2066 {2066 {

2067 "role": "developer",2067 "role": "developer",


2099 }2099 }

2100 2100 

2101 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{2101 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

2102 Model: "gpt-6-astra",2102 Model: "gpt-6.2-astra",

2103 Messages: []openai.ChatCompletionMessageParamUnion{2103 Messages: []openai.ChatCompletionMessageParamUnion{

2104 openai.DeveloperMessage("Produce a concise answer to the query based on the provided sources."),2104 openai.DeveloperMessage("Produce a concise answer to the query based on the provided sources."),

2105 openai.UserMessage(fmt.Sprintf("Sources: %s\n\nQuery: %q", formatResults(results.Data), userQuery)),2105 openai.UserMessage(fmt.Sprintf("Sources: %s\n\nQuery: %q", formatResults(results.Data), userQuery)),


2161 .completions()2161 .completions()

2162 .create(2162 .create(

2163 ChatCompletionCreateParams.builder()2163 ChatCompletionCreateParams.builder()

2164 .model("gpt-6-astra")2164 .model("gpt-6.2-astra")

2165 .addDeveloperMessage(2165 .addDeveloperMessage(

2166 "Answer the query concisely using only the provided sources.")2166 "Answer the query concisely using only the provided sources.")

2167 .addUserMessage(2167 .addUserMessage(


2185end.join2185end.join

2186 2186 

2187completion = client.chat.completions.create(2187completion = client.chat.completions.create(

2188 model: "gpt-6-astra",2188 model: "gpt-6.2-astra",

2189 messages: [2189 messages: [

2190 {2190 {

2191 role: :developer,2191 role: :developer,

Details

70const client = new OpenAI();70const client = new OpenAI();

71 71 

72const response = await client.chat.completions.create({72const response = await client.chat.completions.create({

73 model: "gpt-6-astra",73 model: "gpt-6.2-astra",

74 messages: [{ role: "user", content: "This is a test" }],74 messages: [{ role: "user", content: "This is a test" }],

75 max_completion_tokens: 5,75 max_completion_tokens: 5,

76 safety_identifier: "user_123456",76 safety_identifier: "user_123456",


85client = OpenAI()85client = OpenAI()

86 86 

87response = client.chat.completions.create(87response = client.chat.completions.create(

88 model="gpt-6-astra",88 model="gpt-6.2-astra",

89 messages=[{"role": "user", "content": "This is a test"}],89 messages=[{"role": "user", "content": "This is a test"}],

90 max_completion_tokens=5,90 max_completion_tokens=5,

91 safety_identifier="user_123456",91 safety_identifier="user_123456",


105func main() {105func main() {

106 client := openai.NewClient()106 client := openai.NewClient()

107 response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{107 response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

108 Model: "gpt-6-astra",108 Model: "gpt-6.2-astra",

109 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("This is a test")},109 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("This is a test")},

110 MaxCompletionTokens: openai.Int(5),110 MaxCompletionTokens: openai.Int(5),

111 SafetyIdentifier: openai.String("user_123456"),111 SafetyIdentifier: openai.String("user_123456"),


124 124 

125ChatCompletionCreateParams params =125ChatCompletionCreateParams params =

126 ChatCompletionCreateParams.builder()126 ChatCompletionCreateParams.builder()

127 .model("gpt-6-astra")127 .model("gpt-6.2-astra")

128 .addUserMessage("Help me plan a study schedule.")128 .addUserMessage("Help me plan a study schedule.")

129 .safetyIdentifier("user_1234")129 .safetyIdentifier("user_1234")

130 .build();130 .build();


139 139 

140client = OpenAI::Client.new140client = OpenAI::Client.new

141completion = client.chat.completions.create(141completion = client.chat.completions.create(

142 model: "gpt-6-astra",142 model: "gpt-6.2-astra",

143 messages: [143 messages: [

144 {144 {

145 role: :user,145 role: :user,


157-H "Content-Type: application/json" \157-H "Content-Type: application/json" \

158-H "Authorization: Bearer $OPENAI_API_KEY" \158-H "Authorization: Bearer $OPENAI_API_KEY" \

159-d '{159-d '{

160"model": "gpt-6-astra",160"model": "gpt-6.2-astra",

161"messages": [161"messages": [

162{"role": "user", "content": "This is a test"}162{"role": "user", "content": "This is a test"}

163],163],

Details

39const client = new OpenAI();39const client = new OpenAI();

40 40 

41const response = await client.responses.create({41const response = await client.responses.create({

42 model: "gpt-5.6-terra",42 model: "gpt-6.1-terra",

43 input: "This is a test",43 input: "This is a test",

44 safety_identifier: "user_123456",44 safety_identifier: "user_123456",

45});45});


53client = OpenAI()53client = OpenAI()

54 54 

55response = client.responses.create(55response = client.responses.create(

56 model="gpt-5.6-terra",56 model="gpt-6.1-terra",

57 input="This is a test",57 input="This is a test",

58 safety_identifier="user_123456",58 safety_identifier="user_123456",

59)59)


73func main() {73func main() {

74 client := openai.NewClient()74 client := openai.NewClient()

75 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{75 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

76 Model: "gpt-5.6-terra",76 Model: "gpt-6.1-terra",

77 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("This is a test")},77 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("This is a test")},

78 SafetyIdentifier: openai.String("user_123456"),78 SafetyIdentifier: openai.String("user_123456"),

79 })79 })


91 91 

92ResponseCreateParams params =92ResponseCreateParams params =

93 ResponseCreateParams.builder()93 ResponseCreateParams.builder()

94 .model("gpt-5.6-terra")94 .model("gpt-6.1-terra")

95 .input("Help me plan a study schedule.")95 .input("Help me plan a study schedule.")

96 .safetyIdentifier("user_1234")96 .safetyIdentifier("user_1234")

97 .build();97 .build();


108 108 

109client = OpenAI::Client.new109client = OpenAI::Client.new

110response = client.responses.create(110response = client.responses.create(

111 model: "gpt-5.6-terra",111 model: "gpt-6.1-terra",

112 input: "Help me plan a study schedule.",112 input: "Help me plan a study schedule.",

113 safety_identifier: "user_1234"113 safety_identifier: "user_1234"

114)114)


121-H "Content-Type: application/json" \121-H "Content-Type: application/json" \

122-H "Authorization: Bearer $OPENAI_API_KEY" \122-H "Authorization: Bearer $OPENAI_API_KEY" \

123-d '{123-d '{

124"model": "gpt-5.6-terra",124"model": "gpt-6.1-terra",

125"input": "This is a test",125"input": "This is a test",

126"safety_identifier": "user_123456"126"safety_identifier": "user_123456"

127}'127}'


142const client = new OpenAI();142const client = new OpenAI();

143 143 

144const response = await client.chat.completions.create({144const response = await client.chat.completions.create({

145 model: "gpt-5.6-terra",145 model: "gpt-6.1-terra",

146 messages: [{ role: "user", content: "This is a test" }],146 messages: [{ role: "user", content: "This is a test" }],

147 safety_identifier: "user_123456",147 safety_identifier: "user_123456",

148});148});


156client = OpenAI()156client = OpenAI()

157 157 

158response = client.chat.completions.create(158response = client.chat.completions.create(

159 model="gpt-5.6-terra",159 model="gpt-6.1-terra",

160 messages=[{"role": "user", "content": "This is a test"}],160 messages=[{"role": "user", "content": "This is a test"}],

161 safety_identifier="user_123456",161 safety_identifier="user_123456",

162)162)


175func main() {175func main() {

176 client := openai.NewClient()176 client := openai.NewClient()

177 response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{177 response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

178 Model: "gpt-5.6-terra",178 Model: "gpt-6.1-terra",

179 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("This is a test")},179 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("This is a test")},

180 SafetyIdentifier: openai.String("user_123456"),180 SafetyIdentifier: openai.String("user_123456"),

181 })181 })


193 193 

194ChatCompletionCreateParams params =194ChatCompletionCreateParams params =

195 ChatCompletionCreateParams.builder()195 ChatCompletionCreateParams.builder()

196 .model("gpt-5.6-terra")196 .model("gpt-6.1-terra")

197 .addUserMessage("Help me plan a study schedule.")197 .addUserMessage("Help me plan a study schedule.")

198 .safetyIdentifier("user_1234")198 .safetyIdentifier("user_1234")

199 .build();199 .build();


208 208 

209client = OpenAI::Client.new209client = OpenAI::Client.new

210completion = client.chat.completions.create(210completion = client.chat.completions.create(

211 model: "gpt-5.6-terra",211 model: "gpt-6.1-terra",

212 messages: [212 messages: [

213 {213 {

214 role: :user,214 role: :user,


226-H "Content-Type: application/json" \226-H "Content-Type: application/json" \

227-H "Authorization: Bearer $OPENAI_API_KEY" \227-H "Authorization: Bearer $OPENAI_API_KEY" \

228-d '{228-d '{

229"model": "gpt-5.6-terra",229"model": "gpt-6.1-terra",

230"messages": [230"messages": [

231{"role": "user", "content": "This is a test"}231{"role": "user", "content": "This is a test"}

232],232],

Details

198 -H "Content-Type: application/json" \198 -H "Content-Type: application/json" \

199 -H "Authorization: Bearer $OPENAI_API_KEY" \199 -H "Authorization: Bearer $OPENAI_API_KEY" \

200 -d '{200 -d '{

201 "model": "gpt-6-astra",201 "model": "gpt-6.2-astra",

202 "input": "Use the private MCP server to answer my request.",202 "input": "Use the private MCP server to answer my request.",

203 "tools": [203 "tools": [

204 {204 {

Details

710 710 

711The Transcriptions API accepts files up to 25 MB. For larger recordings, use a compressed audio format or split the file into chunks of 25 MB or less. Avoid splitting in the middle of a sentence, which can remove context and reduce accuracy.711The Transcriptions API accepts files up to 25 MB. For larger recordings, use a compressed audio format or split the file into chunks of 25 MB or less. Avoid splitting in the middle of a sentence, which can remove context and reduce accuracy.

712 712 

713One way to handle this is to use the [PyDub open source Python package](https://github.com/jiaaro/pydub) to split the audio:713 

714 

715 

716The Python example uses the [`pydub`](https://github.com/jiaaro/pydub) package to split the audio.

717 

718 

719 

720 

721 

722 

723 

724The Ruby example calls `ffmpeg`.

725 

726 

727 

728 

729Split a long audio file

714 730 

715```python731```python

716from pydub import AudioSegment732from pydub import AudioSegment


725first_10_minutes.export("good_morning_10.wav", format="wav")741first_10_minutes.export("good_morning_10.wav", format="wav")

726```742```

727 743 

744```ruby

745# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

746require "open3"

747require "json"

748 

749def audio_duration_ms(path)

750 output, status = Open3.capture2("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", path)

751 raise "Unable to inspect audio duration" unless status.success?

752 

753 (Float(JSON.parse(output).fetch("format").fetch("duration")) * 1000).round

754end

755 

756input_ms = audio_duration_ms("good_morning.wav")

757# Keep the first ten minutes with the original PCM samples and encoding.

758_output, error, status = Open3.capture3(

759 "ffmpeg", "-v", "error", "-y", "-i", "good_morning.wav",

760 "-t", "600", "-c:a", "pcm_s16le", "-flags:a", "+bitexact", "-fflags", "+bitexact", "-map_metadata", "-1",

761 "good_morning_10.wav"

762)

763raise "Audio trimming failed: #{error}" unless status.success?

764```

765 

728 766 

729_OpenAI makes no guarantees about the usability or security of third-party software like PyDub._767_OpenAI makes no guarantees about the usability or security of third-party tools such as `pydub` and `ffmpeg`._

730 768 

731## Prompting769## Prompting

732 770 

Details

16const client = new OpenAI();16const client = new OpenAI();

17 17 

18const stream = await client.responses.create({18const stream = await client.responses.create({

19 model: "gpt-6-astra",19 model: "gpt-6.2-astra",

20 input: [20 input: [

21 {21 {

22 role: "user",22 role: "user",


37client = OpenAI()37client = OpenAI()

38 38 

39stream = client.responses.create(39stream = client.responses.create(

40 model="gpt-6-astra",40 model="gpt-6.2-astra",

41 input=[41 input=[

42 {42 {

43 "role": "user",43 "role": "user",


65func main() {65func main() {

66 client := openai.NewClient()66 client := openai.NewClient()

67 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{67 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

68 Model: "gpt-6-astra",68 Model: "gpt-6.2-astra",

69 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},69 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},

70 })70 })

71 for stream.Next() {71 for stream.Next() {


86 86 

87ResponseCreateParams params =87ResponseCreateParams params =

88 ResponseCreateParams.builder()88 ResponseCreateParams.builder()

89 .model("gpt-6-astra")89 .model("gpt-6.2-astra")

90 .input("Say 'double bubble bath' ten times fast.")90 .input("Say 'double bubble bath' ten times fast.")

91 .build();91 .build();

92 92 


103ResponsesClient client = new(key);103ResponsesClient client = new(key);

104 104 

105var responses = client.CreateResponseStreamingAsync(105var responses = client.CreateResponseStreamingAsync(

106 "gpt-6-astra",106 "gpt-6.2-astra",

107 "Say 'double bubble bath' ten times fast."107 "Say 'double bubble bath' ten times fast."

108);108);

109 109 


122openai = OpenAI::Client.new122openai = OpenAI::Client.new

123 123 

124stream = openai.responses.stream(124stream = openai.responses.stream(

125 model: "gpt-6-astra",125 model: "gpt-6.2-astra",

126 input: [126 input: [

127 {127 {

128 role: "user",128 role: "user",

Details

34});34});

35 35 

36const response = await openai.responses.parse({36const response = await openai.responses.parse({

37 model: "gpt-6-astra",37 model: "gpt-6.2-astra",

38 input: [38 input: [

39 { role: "system", content: "Extract the event information." },39 { role: "system", content: "Extract the event information." },

40 {40 {


64 64 

65 65 

66response = client.responses.parse(66response = client.responses.parse(

67 model="gpt-6-astra",67 model="gpt-6.2-astra",

68 input=[68 input=[

69 {"role": "system", "content": "Extract the event information."},69 {"role": "system", "content": "Extract the event information."},

70 {70 {


103 }103 }

104 104 

105 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{105 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

106 Model: "gpt-6-astra",106 Model: "gpt-6.2-astra",

107 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{107 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

108 responses.ResponseInputItemParamOfMessage(108 responses.ResponseInputItemParamOfMessage(

109 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("Extract the event information.")},109 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("Extract the event information.")},


154 154 

155ResponseCreateParams params =155ResponseCreateParams params =

156 ResponseCreateParams.builder()156 ResponseCreateParams.builder()

157 .model("gpt-6-astra")157 .model("gpt-6.2-astra")

158 .inputOfResponse(158 .inputOfResponse(

159 List.of(159 List.of(

160 ResponseInputItem.ofEasyInputMessage(160 ResponseInputItem.ofEasyInputMessage(


213);213);

214CreateResponseOptions options = new()214CreateResponseOptions options = new()

215{215{

216 Model = "gpt-6-astra",216 Model = "gpt-6.2-astra",

217 TextOptions = new ResponseTextOptions217 TextOptions = new ResponseTextOptions

218 {218 {

219 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(219 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


252schema = OpenAI::StructuredOutput.from_sorbet(CalendarEvent)252schema = OpenAI::StructuredOutput.from_sorbet(CalendarEvent)

253 253 

254response = client.responses.create(254response = client.responses.create(

255 model: "gpt-6-astra",255 model: "gpt-6.2-astra",

256 input: [256 input: [

257 {257 {

258 role: :system,258 role: :system,


280 280 

281### Supported models281### Supported models

282 282 

283Structured Outputs is available in our [latest large language models](https://developers.openai.com/api/docs/models), starting with GPT-4o. For new projects, start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra). Older models like `gpt-4-turbo` and earlier may use [JSON mode](#json-mode) instead.283Structured Outputs is available in our [latest large language models](https://developers.openai.com/api/docs/models), starting with GPT-4o. For new projects, start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra). Older models like `gpt-4-turbo` and earlier may use [JSON mode](#json-mode) instead.

284 284 

285 285 

286 286 


382});382});

383 383 

384const response = await openai.responses.parse({384const response = await openai.responses.parse({

385 model: "gpt-6-astra",385 model: "gpt-6.2-astra",

386 input: [386 input: [

387 {387 {

388 role: "system",388 role: "system",


417 417 

418 418 

419response = client.responses.parse(419response = client.responses.parse(

420 model="gpt-6-astra",420 model="gpt-6.2-astra",

421 input=[421 input=[

422 {422 {

423 "role": "system",423 "role": "system",


464 }464 }

465 465 

466 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{466 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

467 Model: "gpt-6-astra",467 Model: "gpt-6.2-astra",

468 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{468 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

469 responses.ResponseInputItemParamOfMessage(469 responses.ResponseInputItemParamOfMessage(

470 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},470 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},


529 529 

530ResponseCreateParams params =530ResponseCreateParams params =

531 ResponseCreateParams.builder()531 ResponseCreateParams.builder()

532 .model("gpt-6-astra")532 .model("gpt-6.2-astra")

533 .inputOfResponse(533 .inputOfResponse(

534 List.of(534 List.of(

535 ResponseInputItem.ofEasyInputMessage(535 ResponseInputItem.ofEasyInputMessage(


597);597);

598CreateResponseOptions options = new()598CreateResponseOptions options = new()

599{599{

600 Model = "gpt-6-astra",600 Model = "gpt-6.2-astra",

601 TextOptions = new ResponseTextOptions601 TextOptions = new ResponseTextOptions

602 {602 {

603 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(603 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


642}642}

643 643 

644response = client.responses.create(644response = client.responses.create(

645 model: "gpt-6-astra",645 model: "gpt-6.2-astra",

646 input: [646 input: [

647 {647 {

648 role: :system,648 role: :system,


671 -H "Authorization: Bearer $OPENAI_API_KEY" \671 -H "Authorization: Bearer $OPENAI_API_KEY" \

672 -H "Content-Type: application/json" \672 -H "Content-Type: application/json" \

673 -d '{673 -d '{

674 "model": "gpt-6-astra",674 "model": "gpt-6.2-astra",

675 "input": [675 "input": [

676 {676 {

677 "role": "system",677 "role": "system",


777});777});

778 778 

779const response = await openai.responses.parse({779const response = await openai.responses.parse({

780 model: "gpt-6-astra",780 model: "gpt-6.2-astra",

781 input: [781 input: [

782 {782 {

783 role: "system",783 role: "system",


809 809 

810 810 

811response = client.responses.parse(811response = client.responses.parse(

812 model="gpt-6-astra",812 model="gpt-6.2-astra",

813 input=[813 input=[

814 {814 {

815 "role": "system",815 "role": "system",


865 }865 }

866 866 

867 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{867 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

868 Model: "gpt-6-astra",868 Model: "gpt-6.2-astra",

869 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{869 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

870 responses.ResponseInputItemParamOfMessage(870 responses.ResponseInputItemParamOfMessage(

871 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are an expert at structured data extraction. You will be given unstructured text from a research paper and should convert it into the given structure.")},871 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are an expert at structured data extraction. You will be given unstructured text from a research paper and should convert it into the given structure.")},


917 917 

918ResponseCreateParams params =918ResponseCreateParams params =

919 ResponseCreateParams.builder()919 ResponseCreateParams.builder()

920 .model("gpt-6-astra")920 .model("gpt-6.2-astra")

921 .inputOfResponse(921 .inputOfResponse(

922 List.of(922 List.of(

923 ResponseInputItem.ofEasyInputMessage(923 ResponseInputItem.ofEasyInputMessage(


985);985);

986CreateResponseOptions options = new()986CreateResponseOptions options = new()

987{987{

988 Model = "gpt-6-astra",988 Model = "gpt-6.2-astra",

989 TextOptions = new ResponseTextOptions989 TextOptions = new ResponseTextOptions

990 {990 {

991 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(991 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


1044}1044}

1045 1045 

1046response = client.responses.create(1046response = client.responses.create(

1047 model: "gpt-6-astra",1047 model: "gpt-6.2-astra",

1048 input: [1048 input: [

1049 {1049 {

1050 role: :system,1050 role: :system,


1073 -H "Authorization: Bearer $OPENAI_API_KEY" \1073 -H "Authorization: Bearer $OPENAI_API_KEY" \

1074 -H "Content-Type: application/json" \1074 -H "Content-Type: application/json" \

1075 -d '{1075 -d '{

1076 "model": "gpt-6-astra",1076 "model": "gpt-6.2-astra",

1077 "input": [1077 "input": [

1078 {1078 {

1079 "role": "system",1079 "role": "system",


1179);1179);

1180 1180 

1181const response = await openai.responses.parse({1181const response = await openai.responses.parse({

1182 model: "gpt-6-astra",1182 model: "gpt-6.2-astra",

1183 max_output_tokens: 4096,1183 max_output_tokens: 4096,

1184 input: [1184 input: [

1185 {1185 {


1242 1242 

1243 1243 

1244response = client.responses.parse(1244response = client.responses.parse(

1245 model="gpt-6-astra",1245 model="gpt-6.2-astra",

1246 input=[1246 input=[

1247 {1247 {

1248 "role": "system",1248 "role": "system",


1282 }1282 }

1283 1283 

1284 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1284 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1285 Model: "gpt-6-astra",1285 Model: "gpt-6.2-astra",

1286 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1286 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

1287 responses.ResponseInputItemParamOfMessage(1287 responses.ResponseInputItemParamOfMessage(

1288 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a UI generator AI. Convert the user input into a UI.")},1288 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a UI generator AI. Convert the user input into a UI.")},


1351 1351 

1352ResponseCreateParams params =1352ResponseCreateParams params =

1353 ResponseCreateParams.builder()1353 ResponseCreateParams.builder()

1354 .model("gpt-6-astra")1354 .model("gpt-6.2-astra")

1355 .inputOfResponse(1355 .inputOfResponse(

1356 List.of(1356 List.of(

1357 ResponseInputItem.ofEasyInputMessage(1357 ResponseInputItem.ofEasyInputMessage(


1436);1436);

1437CreateResponseOptions options = new()1437CreateResponseOptions options = new()

1438{1438{

1439 Model = "gpt-6-astra",1439 Model = "gpt-6.2-astra",

1440 MaxOutputTokenCount = 4096,1440 MaxOutputTokenCount = 4096,

1441 TextOptions = new ResponseTextOptions1441 TextOptions = new ResponseTextOptions

1442 {1442 {


1501}1501}

1502 1502 

1503response = client.responses.create(1503response = client.responses.create(

1504 model: "gpt-6-astra",1504 model: "gpt-6.2-astra",

1505 input: [1505 input: [

1506 {1506 {

1507 role: :system,1507 role: :system,


1531 -H "Authorization: Bearer $OPENAI_API_KEY" \1531 -H "Authorization: Bearer $OPENAI_API_KEY" \

1532 -H "Content-Type: application/json" \1532 -H "Content-Type: application/json" \

1533 -d '{1533 -d '{

1534 "model": "gpt-6-astra",1534 "model": "gpt-6.2-astra",

1535 "input": [1535 "input": [

1536 {1536 {

1537 "role": "system",1537 "role": "system",


1705});1705});

1706 1706 

1707const response = await openai.responses.parse({1707const response = await openai.responses.parse({

1708 model: "gpt-6-astra",1708 model: "gpt-6.2-astra",

1709 input: [1709 input: [

1710 {1710 {

1711 role: "system",1711 role: "system",


1747 1747 

1748 1748 

1749response = client.responses.parse(1749response = client.responses.parse(

1750 model="gpt-6-astra",1750 model="gpt-6.2-astra",

1751 input=[1751 input=[

1752 {1752 {

1753 "role": "system",1753 "role": "system",


1776 client := openai.NewClient()1776 client := openai.NewClient()

1777 schema := contentComplianceSchema()1777 schema := contentComplianceSchema()

1778 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1778 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1779 Model: "gpt-6-astra",1779 Model: "gpt-6.2-astra",

1780 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1780 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

1781 responses.ResponseInputItemParamOfMessage("Determine if the user input violates specific guidelines and explain if they do.", responses.EasyInputMessageRoleSystem),1781 responses.ResponseInputItemParamOfMessage("Determine if the user input violates specific guidelines and explain if they do.", responses.EasyInputMessageRoleSystem),

1782 responses.ResponseInputItemParamOfMessage("How do I prepare for a job interview?", responses.EasyInputMessageRoleUser),1782 responses.ResponseInputItemParamOfMessage("How do I prepare for a job interview?", responses.EasyInputMessageRoleUser),


1848 1848 

1849ResponseCreateParams params =1849ResponseCreateParams params =

1850 ResponseCreateParams.builder()1850 ResponseCreateParams.builder()

1851 .model("gpt-6-astra")1851 .model("gpt-6.2-astra")

1852 .inputOfResponse(1852 .inputOfResponse(

1853 List.of(1853 List.of(

1854 ResponseInputItem.ofEasyInputMessage(1854 ResponseInputItem.ofEasyInputMessage(


1910);1910);

1911CreateResponseOptions options = new()1911CreateResponseOptions options = new()

1912{1912{

1913 Model = "gpt-6-astra",1913 Model = "gpt-6.2-astra",

1914 TextOptions = new ResponseTextOptions1914 TextOptions = new ResponseTextOptions

1915 {1915 {

1916 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(1916 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


1954}1954}

1955 1955 

1956response = client.responses.create(1956response = client.responses.create(

1957 model: "gpt-6-astra",1957 model: "gpt-6.2-astra",

1958 input: [1958 input: [

1959 {1959 {

1960 role: :system,1960 role: :system,


1984 -H "Authorization: Bearer $OPENAI_API_KEY" \1984 -H "Authorization: Bearer $OPENAI_API_KEY" \

1985 -H "Content-Type: application/json" \1985 -H "Content-Type: application/json" \

1986 -d '{1986 -d '{

1987 "model": "gpt-6-astra",1987 "model": "gpt-6.2-astra",

1988 "input": [1988 "input": [

1989 {1989 {

1990 "role": "system",1990 "role": "system",


2096 2096 

2097```typescript2097```typescript

2098const response = await openai.responses.create({2098const response = await openai.responses.create({

2099 model: "gpt-6-astra",2099 model: "gpt-6.2-astra",

2100 input: [2100 input: [

2101 {2101 {

2102 role: "system",2102 role: "system",


2139 2139 

2140```python2140```python

2141response = client.responses.create(2141response = client.responses.create(

2142 model="gpt-6-astra",2142 model="gpt-6.2-astra",

2143 input=[2143 input=[

2144 {2144 {

2145 "role": "system",2145 "role": "system",


2193func main() {2193func main() {

2194 client := openai.NewClient()2194 client := openai.NewClient()

2195 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2195 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2196 Model: "gpt-6-astra",2196 Model: "gpt-6.2-astra",

2197 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2197 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

2198 responses.ResponseInputItemParamOfMessage(2198 responses.ResponseInputItemParamOfMessage(

2199 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},2199 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},


2269 2269 

2270ResponseCreateParams params =2270ResponseCreateParams params =

2271 ResponseCreateParams.builder()2271 ResponseCreateParams.builder()

2272 .model("gpt-6-astra")2272 .model("gpt-6.2-astra")

2273 .inputOfResponse(2273 .inputOfResponse(

2274 List.of(2274 List.of(

2275 ResponseInputItem.ofEasyInputMessage(2275 ResponseInputItem.ofEasyInputMessage(


2337);2337);

2338CreateResponseOptions options = new()2338CreateResponseOptions options = new()

2339{2339{

2340 Model = "gpt-6-astra",2340 Model = "gpt-6.2-astra",

2341 TextOptions = new ResponseTextOptions2341 TextOptions = new ResponseTextOptions

2342 {2342 {

2343 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(2343 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


2381}2381}

2382 2382 

2383response = client.responses.create(2383response = client.responses.create(

2384 model: "gpt-6-astra",2384 model: "gpt-6.2-astra",

2385 input: [2385 input: [

2386 {2386 {

2387 role: :system,2387 role: :system,


2410 -H "Authorization: Bearer $OPENAI_API_KEY" \2410 -H "Authorization: Bearer $OPENAI_API_KEY" \

2411 -H "Content-Type: application/json" \2411 -H "Content-Type: application/json" \

2412 -d '{2412 -d '{

2413 "model": "gpt-6-astra",2413 "model": "gpt-6.2-astra",

2414 "input": [2414 "input": [

2415 {2415 {

2416 "role": "system",2416 "role": "system",


2477```typescript2477```typescript

2478try {2478try {

2479 const response = await openai.responses.create({2479 const response = await openai.responses.create({

2480 model: "gpt-6-astra",2480 model: "gpt-6.2-astra",

2481 input: [2481 input: [

2482 {2482 {

2483 role: "system",2483 role: "system",


2557```python2557```python

2558try:2558try:

2559 response = client.responses.create(2559 response = client.responses.create(

2560 model="gpt-6-astra",2560 model="gpt-6.2-astra",

2561 input=[2561 input=[

2562 {2562 {

2563 "role": "system",2563 "role": "system",


2633func main() {2633func main() {

2634 client := openai.NewClient()2634 client := openai.NewClient()

2635 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{2635 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

2636 Model: "gpt-6-astra",2636 Model: "gpt-6.2-astra",

2637 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{2637 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

2638 responses.ResponseInputItemParamOfMessage(2638 responses.ResponseInputItemParamOfMessage(

2639 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},2639 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},


2702 2702 

2703ResponseCreateParams params =2703ResponseCreateParams params =

2704 ResponseCreateParams.builder()2704 ResponseCreateParams.builder()

2705 .model("gpt-6-astra")2705 .model("gpt-6.2-astra")

2706 .inputOfResponse(2706 .inputOfResponse(

2707 List.of(2707 List.of(

2708 ResponseInputItem.ofEasyInputMessage(2708 ResponseInputItem.ofEasyInputMessage(


2816);2816);

2817CreateResponseOptions options = new()2817CreateResponseOptions options = new()

2818{2818{

2819 Model = "gpt-6-astra",2819 Model = "gpt-6.2-astra",

2820 MaxOutputTokenCount = 300,2820 MaxOutputTokenCount = 300,

2821 TextOptions = new ResponseTextOptions2821 TextOptions = new ResponseTextOptions

2822 {2822 {


2881}2881}

2882 2882 

2883response = client.responses.create(2883response = client.responses.create(

2884 model: "gpt-6-astra",2884 model: "gpt-6.2-astra",

2885 input: [2885 input: [

2886 {2886 {

2887 role: :system,2887 role: :system,


3245});3245});

3246 3246 

3247const response = await openai.responses.parse({3247const response = await openai.responses.parse({

3248 model: "gpt-6-astra",3248 model: "gpt-6.2-astra",

3249 input: [3249 input: [

3250 {3250 {

3251 role: "system",3251 role: "system",


3292 3292 

3293 3293 

3294response = client.responses.parse(3294response = client.responses.parse(

3295 model="gpt-6-astra",3295 model="gpt-6.2-astra",

3296 input=[3296 input=[

3297 {3297 {

3298 "role": "system",3298 "role": "system",


3333func main() {3333func main() {

3334 client := openai.NewClient()3334 client := openai.NewClient()

3335 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{3335 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

3336 Model: "gpt-6-astra",3336 Model: "gpt-6.2-astra",

3337 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{3337 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

3338 responses.ResponseInputItemParamOfMessage(3338 responses.ResponseInputItemParamOfMessage(

3339 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},3339 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful math tutor. Guide the user through the solution step by step.")},


3421 3421 

3422ResponseCreateParams params =3422ResponseCreateParams params =

3423 ResponseCreateParams.builder()3423 ResponseCreateParams.builder()

3424 .model("gpt-6-astra")3424 .model("gpt-6.2-astra")

3425 .inputOfResponse(3425 .inputOfResponse(

3426 List.of(3426 List.of(

3427 ResponseInputItem.ofEasyInputMessage(3427 ResponseInputItem.ofEasyInputMessage(


3494);3494);

3495CreateResponseOptions options = new()3495CreateResponseOptions options = new()

3496{3496{

3497 Model = "gpt-6-astra",3497 Model = "gpt-6.2-astra",

3498 TextOptions = new ResponseTextOptions3498 TextOptions = new ResponseTextOptions

3499 {3499 {

3500 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(3500 TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(


3545}3545}

3546 3546 

3547response = client.responses.create(3547response = client.responses.create(

3548 model: "gpt-6-astra",3548 model: "gpt-6.2-astra",

3549 input: [3549 input: [

3550 {3550 {

3551 role: :system,3551 role: :system,


3677const openai = new OpenAI();3677const openai = new OpenAI();

3678const stream = openai.responses3678const stream = openai.responses

3679 .stream({3679 .stream({

3680 model: "gpt-6-astra",3680 model: "gpt-6.2-astra",

3681 input: [3681 input: [

3682 { role: "user", content: "What's the weather like in Paris today?" },3682 { role: "user", content: "What's the weather like in Paris today?" },

3683 ],3683 ],


3717client = OpenAI()3717client = OpenAI()

3718 3718 

3719with client.responses.stream(3719with client.responses.stream(

3720 model="gpt-6-astra",3720 model="gpt-6.2-astra",

3721 input=[3721 input=[

3722 {"role": "system", "content": "Extract entities from the input text"},3722 {"role": "system", "content": "Extract entities from the input text"},

3723 {3723 {


3765 3765 

3766ResponseCreateParams params =3766ResponseCreateParams params =

3767 ResponseCreateParams.builder()3767 ResponseCreateParams.builder()

3768 .model("gpt-6-astra")3768 .model("gpt-6.2-astra")

3769 .inputOfResponse(3769 .inputOfResponse(

3770 List.of(3770 List.of(

3771 ResponseInputItem.ofEasyInputMessage(3771 ResponseInputItem.ofEasyInputMessage(


3863}3863}

3864 3864 

3865stream = client.responses.stream(3865stream = client.responses.stream(

3866 model: "gpt-6-astra",3866 model: "gpt-6.2-astra",

3867 input: [3867 input: [

3868 {3868 {

3869 role: :system,3869 role: :system,


4072const json = zodResponseFormat(finalSchema, "final_schema");4072const json = zodResponseFormat(finalSchema, "final_schema");

4073```4073```

4074 4074 

4075```ruby

4076require "openai"

4077require "json"

4078 

4079# A discriminated union is allowed inside an object, but not at the root.

4080root_union = {

4081 anyOf: [

4082 {

4083 type: "object",

4084 

4085 properties: {

4086 status: {

4087 type: "string",

4088 enum: ["success"]

4089 },

4090 value: { type: "string" }

4091 },

4092 required: ["status", "value"],

4093 

4094 additionalProperties: false

4095 },

4096 {

4097 type: "object",

4098 

4099 properties: {

4100 status: {

4101 type: "string",

4102 enum: ["error"]

4103 },

4104 error: { type: "string" }

4105 },

4106 required: ["status", "error"],

4107 

4108 additionalProperties: false

4109 }

4110 ]

4111}

4112client = OpenAI::Client.new

4113begin

4114 client.responses.create(

4115 model: "gpt-6.2-astra", input: "Return a successful result.", store: false,

4116 text: {

4117 format: {

4118 type: :json_schema,

4119 name: "result",

4120 strict: true,

4121 schema: root_union

4122 }

4123 }

4124 )

4125 raise "Expected the API to reject the root union"

4126rescue OpenAI::Errors::BadRequestError => error

4127 raise unless error.code == "invalid_json_schema"

4128 

4129 puts JSON.generate(status: error.status, code: error.code)

4130end

4131```

4132 

4075 4133 

4076#### All fields must be `required`4134#### All fields must be `required`

4077 4135 


4443 4501 

4444try {4502try {

4445 const response = await openai.responses.create({4503 const response = await openai.responses.create({

4446 model: "gpt-6-astra",4504 model: "gpt-6.2-astra",

4447 input: [4505 input: [

4448 {4506 {

4449 role: "system",4507 role: "system",


4506 4564 

4507try:4565try:

4508 response = client.responses.create(4566 response = client.responses.create(

4509 model="gpt-6-astra",4567 model="gpt-6.2-astra",

4510 input=[4568 input=[

4511 {4569 {

4512 "role": "system",4570 "role": "system",


4571func main() {4629func main() {

4572 client := openai.NewClient()4630 client := openai.NewClient()

4573 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{4631 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

4574 Model: "gpt-6-astra",4632 Model: "gpt-6.2-astra",

4575 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{4633 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

4576 responses.ResponseInputItemParamOfMessage(4634 responses.ResponseInputItemParamOfMessage(

4577 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful assistant designed to output JSON.")},4635 responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("You are a helpful assistant designed to output JSON.")},


4629 4687 

4630ResponseCreateParams params =4688ResponseCreateParams params =

4631 ResponseCreateParams.builder()4689 ResponseCreateParams.builder()

4632 .model("gpt-6-astra")4690 .model("gpt-6.2-astra")

4633 .inputOfResponse(4691 .inputOfResponse(

4634 List.of(4692 List.of(

4635 ResponseInputItem.ofEasyInputMessage(4693 ResponseInputItem.ofEasyInputMessage(


4688 4746 

4689CreateResponseOptions options = new()4747CreateResponseOptions options = new()

4690{4748{

4691 Model = "gpt-6-astra",4749 Model = "gpt-6.2-astra",

4692 TextOptions = new ResponseTextOptions4750 TextOptions = new ResponseTextOptions

4693 {4751 {

4694 TextFormat = ResponseTextFormat.CreateJsonObjectFormat(),4752 TextFormat = ResponseTextFormat.CreateJsonObjectFormat(),


4734 4792 

4735client = OpenAI::Client.new4793client = OpenAI::Client.new

4736response = client.responses.create(4794response = client.responses.create(

4737 model: "gpt-6-astra",4795 model: "gpt-6.2-astra",

4738 input: [4796 input: [

4739 {4797 {

4740 role: :system,4798 role: :system,

guides/text.md +23 −23

Details

13const client = new OpenAI();13const client = new OpenAI();

14 14 

15const response = await client.responses.create({15const response = await client.responses.create({

16 model: "gpt-6-astra",16 model: "gpt-6.2-astra",

17 input: "Write a one-sentence bedtime story about a unicorn.",17 input: "Write a one-sentence bedtime story about a unicorn.",

18});18});

19 19 


26client = OpenAI()26client = OpenAI()

27 27 

28response = client.responses.create(28response = client.responses.create(

29 model="gpt-6-astra",29 model="gpt-6.2-astra",

30 input="Write a one-sentence bedtime story about a unicorn.",30 input="Write a one-sentence bedtime story about a unicorn.",

31)31)

32 32 


48 client := openai.NewClient()48 client := openai.NewClient()

49 49 

50 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{50 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

51 Model: "gpt-6-astra",51 Model: "gpt-6.2-astra",

52 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},52 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

53 })53 })

54 if err != nil {54 if err != nil {


70 OpenAIClient client = OpenAIOkHttpClient.fromEnv();70 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

71 71 

72 ResponseCreateParams params =72 ResponseCreateParams params =

73 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();73 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();

74 74 

75 Response response = client.responses().create(params);75 Response response = client.responses().create(params);

76 response.output().stream()76 response.output().stream()


90ResponsesClient client = new(key);90ResponsesClient client = new(key);

91 91 

92ResponseResult response = await client.CreateResponseAsync(92ResponseResult response = await client.CreateResponseAsync(

93 "gpt-6-astra",93 "gpt-6.2-astra",

94 "Say 'this is a test.'"94 "Say 'this is a test.'"

95);95);

96 96 


103openai = OpenAI::Client.new103openai = OpenAI::Client.new

104 104 

105response = openai.responses.create(105response = openai.responses.create(

106 model: "gpt-6-astra",106 model: "gpt-6.2-astra",

107 input: "Write a one-sentence bedtime story about a unicorn."107 input: "Write a one-sentence bedtime story about a unicorn."

108)108)

109 109 


112 112 

113```bash113```bash

114openai responses create \114openai responses create \

115 --model "gpt-6-astra" \115 --model "gpt-6.2-astra" \

116 --input "Write a one-sentence bedtime story about a unicorn." \116 --input "Write a one-sentence bedtime story about a unicorn." \

117 --raw-output \117 --raw-output \

118 --transform 'output.#(type=="message").content.0.text'118 --transform 'output.#(type=="message").content.0.text'


123 -H "Content-Type: application/json" \123 -H "Content-Type: application/json" \

124 -H "Authorization: Bearer $OPENAI_API_KEY" \124 -H "Authorization: Bearer $OPENAI_API_KEY" \

125 -d '{125 -d '{

126 "model": "gpt-6-astra",126 "model": "gpt-6.2-astra",

127 "input": "Write a one-sentence bedtime story about a unicorn."127 "input": "Write a one-sentence bedtime story about a unicorn."

128 }'128 }'

129```129```


170 170 

171## Choosing models and APIs171## Choosing models and APIs

172 172 

173OpenAI has many different [models](https://developers.openai.com/api/docs/models) and several APIs to choose from. [Reasoning models](https://developers.openai.com/api/docs/guides/reasoning), like [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra), behave differently from chat models and respond better to different prompts. One important note is that reasoning models perform better and demonstrate higher intelligence when used with the Responses API.173OpenAI has many different [models](https://developers.openai.com/api/docs/models) and several APIs to choose from. [Reasoning models](https://developers.openai.com/api/docs/guides/reasoning), like [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra), behave differently from chat models and respond better to different prompts. One important note is that reasoning models perform better and demonstrate higher intelligence when used with the Responses API.

174 174 

175If you're building any text generation app, we recommend using the Responses API over the older Chat Completions API. And if you're using a reasoning model, it's especially useful to [migrate to Responses](https://developers.openai.com/api/docs/guides/migrate-to-responses).175If you're building any text generation app, we recommend using the Responses API over the older Chat Completions API. And if you're using a reasoning model, it's especially useful to [migrate to Responses](https://developers.openai.com/api/docs/guides/migrate-to-responses).

176 176 


187const client = new OpenAI();187const client = new OpenAI();

188 188 

189const response = await client.responses.create({189const response = await client.responses.create({

190 model: "gpt-6-astra",190 model: "gpt-6.2-astra",

191 reasoning: { effort: "low" },191 reasoning: { effort: "low" },

192 instructions: "Talk like a pirate.",192 instructions: "Talk like a pirate.",

193 input: "Are semicolons optional in JavaScript?",193 input: "Are semicolons optional in JavaScript?",


202client = OpenAI()202client = OpenAI()

203 203 

204response = client.responses.create(204response = client.responses.create(

205 model="gpt-6-astra",205 model="gpt-6.2-astra",

206 reasoning={"effort": "low"},206 reasoning={"effort": "low"},

207 instructions="Talk like a pirate.",207 instructions="Talk like a pirate.",

208 input="Are semicolons optional in JavaScript?",208 input="Are semicolons optional in JavaScript?",


226 client := openai.NewClient()226 client := openai.NewClient()

227 227 

228 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{228 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

229 Model: "gpt-6-astra",229 Model: "gpt-6.2-astra",

230 Instructions: openai.String("Talk like a pirate."),230 Instructions: openai.String("Talk like a pirate."),

231 Reasoning: responses.ReasoningParam{231 Reasoning: responses.ReasoningParam{

232 Effort: responses.ReasoningEffortLow,232 Effort: responses.ReasoningEffortLow,


256 256 

257ResponseCreateParams params =257ResponseCreateParams params =

258 ResponseCreateParams.builder()258 ResponseCreateParams.builder()

259 .model("gpt-6-astra")259 .model("gpt-6.2-astra")

260 .input(semicolonsPrompt)260 .input(semicolonsPrompt)

261 .instructions(semicolonsDevMsg)261 .instructions(semicolonsDevMsg)

262 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())262 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())


278 278 

279CreateResponseOptions options = new()279CreateResponseOptions options = new()

280{280{

281 Model = "gpt-6-astra",281 Model = "gpt-6.2-astra",

282 Instructions = "Talk like a pirate.",282 Instructions = "Talk like a pirate.",

283 ReasoningOptions = new ResponseReasoningOptions283 ReasoningOptions = new ResponseReasoningOptions

284 {284 {


299 299 

300client = OpenAI::Client.new300client = OpenAI::Client.new

301response = client.responses.create(301response = client.responses.create(

302 model: "gpt-6-astra",302 model: "gpt-6.2-astra",

303 instructions: "Talk like a pirate.",303 instructions: "Talk like a pirate.",

304 reasoning: { effort: :low },304 reasoning: { effort: :low },

305 input: "Are semicolons optional in JavaScript?"305 input: "Are semicolons optional in JavaScript?"


313 -H "Content-Type: application/json" \313 -H "Content-Type: application/json" \

314 -H "Authorization: Bearer $OPENAI_API_KEY" \314 -H "Authorization: Bearer $OPENAI_API_KEY" \

315 -d '{315 -d '{

316 "model": "gpt-6-astra",316 "model": "gpt-6.2-astra",

317 "reasoning": {"effort": "low"},317 "reasoning": {"effort": "low"},

318 "instructions": "Talk like a pirate.",318 "instructions": "Talk like a pirate.",

319 "input": "Are semicolons optional in JavaScript?"319 "input": "Are semicolons optional in JavaScript?"


330const client = new OpenAI();330const client = new OpenAI();

331 331 

332const response = await client.responses.create({332const response = await client.responses.create({

333 model: "gpt-6-astra",333 model: "gpt-6.2-astra",

334 reasoning: { effort: "low" },334 reasoning: { effort: "low" },

335 input: [335 input: [

336 {336 {


353client = OpenAI()353client = OpenAI()

354 354 

355response = client.responses.create(355response = client.responses.create(

356 model="gpt-6-astra",356 model="gpt-6.2-astra",

357 reasoning={"effort": "low"},357 reasoning={"effort": "low"},

358 input=[358 input=[

359 {"role": "developer", "content": "Talk like a pirate."},359 {"role": "developer", "content": "Talk like a pirate."},


379 client := openai.NewClient()379 client := openai.NewClient()

380 380 

381 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{381 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

382 Model: "gpt-6-astra",382 Model: "gpt-6.2-astra",

383 Reasoning: responses.ReasoningParam{383 Reasoning: responses.ReasoningParam{

384 Effort: responses.ReasoningEffortLow,384 Effort: responses.ReasoningEffortLow,

385 },385 },


420 420 

421ResponseCreateParams params =421ResponseCreateParams params =

422 ResponseCreateParams.builder()422 ResponseCreateParams.builder()

423 .model("gpt-6-astra")423 .model("gpt-6.2-astra")

424 .input(424 .input(

425 ResponseCreateParams.Input.ofResponse(425 ResponseCreateParams.Input.ofResponse(

426 List.of(426 List.of(


453 453 

454CreateResponseOptions options = new()454CreateResponseOptions options = new()

455{455{

456 Model = "gpt-6-astra",456 Model = "gpt-6.2-astra",

457 ReasoningOptions = new ResponseReasoningOptions457 ReasoningOptions = new ResponseReasoningOptions

458 {458 {

459 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,459 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,


476 476 

477client = OpenAI::Client.new477client = OpenAI::Client.new

478response = client.responses.create(478response = client.responses.create(

479 model: "gpt-6-astra",479 model: "gpt-6.2-astra",

480 reasoning: { effort: :low },480 reasoning: { effort: :low },

481 input: [481 input: [

482 {482 {


498 -H "Content-Type: application/json" \498 -H "Content-Type: application/json" \

499 -H "Authorization: Bearer $OPENAI_API_KEY" \499 -H "Authorization: Bearer $OPENAI_API_KEY" \

500 -d '{500 -d '{

501 "model": "gpt-6-astra",501 "model": "gpt-6.2-astra",

502 "reasoning": {"effort": "low"},502 "reasoning": {"effort": "low"},

503 "input": [503 "input": [

504 {504 {

Details

33const client = new OpenAI();33const client = new OpenAI();

34 34 

35const response = await client.responses.inputTokens.count({35const response = await client.responses.inputTokens.count({

36 model: "gpt-6-astra",36 model: "gpt-6.2-astra",

37 input: "Tell me a joke.",37 input: "Tell me a joke.",

38});38});

39 39 


46client = OpenAI()46client = OpenAI()

47 47 

48response = client.responses.input_tokens.count(48response = client.responses.input_tokens.count(

49 model="gpt-6-astra", input="Tell me a joke."49 model="gpt-6.2-astra", input="Tell me a joke."

50)50)

51print(response.input_tokens)51print(response.input_tokens)

52```52```


65func main() {65func main() {

66 client := openai.NewClient()66 client := openai.NewClient()

67 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{67 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{

68 Model: openai.String("gpt-6-astra"),68 Model: openai.String("gpt-6.2-astra"),

69 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Tell me a joke.")},69 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Tell me a joke.")},

70 })70 })

71 if err != nil {71 if err != nil {


86 .inputTokens()86 .inputTokens()

87 .count(87 .count(

88 InputTokenCountParams.builder()88 InputTokenCountParams.builder()

89 .model("gpt-6-astra")89 .model("gpt-6.2-astra")

90 .input("Tell me a joke.")90 .input("Tell me a joke.")

91 .build());91 .build());

92 92 


99client = OpenAI::Client.new99client = OpenAI::Client.new

100 100 

101count = client.responses.input_tokens.count(101count = client.responses.input_tokens.count(

102 model: "gpt-6-astra",102 model: "gpt-6.2-astra",

103 input: "Tell me a joke."103 input: "Tell me a joke."

104)104)

105 105 


111 -H "Authorization: Bearer $OPENAI_API_KEY" \111 -H "Authorization: Bearer $OPENAI_API_KEY" \

112 -H "Content-Type: application/json" \112 -H "Content-Type: application/json" \

113 -d '{113 -d '{

114 "model": "gpt-6-astra",114 "model": "gpt-6.2-astra",

115 "input": "Tell me a joke."115 "input": "Tell me a joke."

116 }'116 }'

117```117```

118 118 

119```bash119```bash

120openai responses:input-tokens count \120openai responses:input-tokens count \

121 --model gpt-6-astra \121 --model gpt-6.2-astra \

122 --input "Tell me a joke." \122 --input "Tell me a joke." \

123 --raw-output \123 --raw-output \

124 --transform input_tokens124 --transform input_tokens


135const client = new OpenAI();135const client = new OpenAI();

136 136 

137const response = await client.responses.inputTokens.count({137const response = await client.responses.inputTokens.count({

138 model: "gpt-6-astra",138 model: "gpt-6.2-astra",

139 input: [139 input: [

140 { role: "user", content: "What is 2 + 2?" },140 { role: "user", content: "What is 2 + 2?" },

141 { role: "assistant", content: "2 + 2 equals 4." },141 { role: "assistant", content: "2 + 2 equals 4." },


152client = OpenAI()152client = OpenAI()

153 153 

154response = client.responses.input_tokens.count(154response = client.responses.input_tokens.count(

155 model="gpt-6-astra",155 model="gpt-6.2-astra",

156 input=[156 input=[

157 {"role": "user", "content": "What is 2 + 2?"},157 {"role": "user", "content": "What is 2 + 2?"},

158 {"role": "assistant", "content": "2 + 2 equals 4."},158 {"role": "assistant", "content": "2 + 2 equals 4."},


181 responses.ResponseInputItemParamOfMessage("What about 3 + 3?", responses.EasyInputMessageRoleUser),181 responses.ResponseInputItemParamOfMessage("What about 3 + 3?", responses.EasyInputMessageRoleUser),

182 }182 }

183 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{183 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{

184 Model: openai.String("gpt-6-astra"),184 Model: openai.String("gpt-6.2-astra"),

185 Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},185 Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},

186 })186 })

187 if err != nil {187 if err != nil {


205 .inputTokens()205 .inputTokens()

206 .count(206 .count(

207 InputTokenCountParams.builder()207 InputTokenCountParams.builder()

208 .model("gpt-6-astra")208 .model("gpt-6.2-astra")

209 .inputOfResponseInputItems(209 .inputOfResponseInputItems(

210 List.of(210 List.of(

211 ResponseInputItem.ofEasyInputMessage(211 ResponseInputItem.ofEasyInputMessage(


248]248]

249 249 

250count = client.responses.input_tokens.count(250count = client.responses.input_tokens.count(

251 model: "gpt-6-astra",251 model: "gpt-6.2-astra",

252 input: conversation252 input: conversation

253)253)

254 254 


260 -H "Authorization: Bearer $OPENAI_API_KEY" \260 -H "Authorization: Bearer $OPENAI_API_KEY" \

261 -H "Content-Type: application/json" \261 -H "Content-Type: application/json" \

262 -d '{262 -d '{

263 "model": "gpt-6-astra",263 "model": "gpt-6.2-astra",

264 "input": [264 "input": [

265 {"role": "user", "content": "What is 2 + 2?"},265 {"role": "user", "content": "What is 2 + 2?"},

266 {"role": "assistant", "content": "2 + 2 equals 4."},266 {"role": "assistant", "content": "2 + 2 equals 4."},


273openai responses:input-tokens count \273openai responses:input-tokens count \

274 --raw-output \274 --raw-output \

275 --transform input_tokens <<'YAML'275 --transform input_tokens <<'YAML'

276model: gpt-6-astra276model: gpt-6.2-astra

277input:277input:

278 - role: user278 - role: user

279 content: What is 2 + 2?279 content: What is 2 + 2?


295const client = new OpenAI();295const client = new OpenAI();

296 296 

297const response = await client.responses.inputTokens.count({297const response = await client.responses.inputTokens.count({

298 model: "gpt-6-astra",298 model: "gpt-6.2-astra",

299 instructions: "You are a helpful assistant that explains concepts simply.",299 instructions: "You are a helpful assistant that explains concepts simply.",

300 input: "Explain quantum computing in one sentence.",300 input: "Explain quantum computing in one sentence.",

301});301});


309client = OpenAI()309client = OpenAI()

310 310 

311response = client.responses.input_tokens.count(311response = client.responses.input_tokens.count(

312 model="gpt-6-astra",312 model="gpt-6.2-astra",

313 instructions="You are a helpful assistant that explains concepts simply.",313 instructions="You are a helpful assistant that explains concepts simply.",

314 input="Explain quantum computing in one sentence.",314 input="Explain quantum computing in one sentence.",

315)315)


330func main() {330func main() {

331 client := openai.NewClient()331 client := openai.NewClient()

332 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{332 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{

333 Model: openai.String("gpt-6-astra"),333 Model: openai.String("gpt-6.2-astra"),

334 Instructions: openai.String("You are a helpful assistant that explains concepts simply."),334 Instructions: openai.String("You are a helpful assistant that explains concepts simply."),

335 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Explain quantum computing in one sentence.")},335 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Explain quantum computing in one sentence.")},

336 })336 })


352 .inputTokens()352 .inputTokens()

353 .count(353 .count(

354 InputTokenCountParams.builder()354 InputTokenCountParams.builder()

355 .model("gpt-6-astra")355 .model("gpt-6.2-astra")

356 .input("Explain quantum computing in one sentence.")356 .input("Explain quantum computing in one sentence.")

357 .instructions("You are a helpful assistant that explains concepts simply.")357 .instructions("You are a helpful assistant that explains concepts simply.")

358 .build());358 .build());


366client = OpenAI::Client.new366client = OpenAI::Client.new

367 367 

368count = client.responses.input_tokens.count(368count = client.responses.input_tokens.count(

369 model: "gpt-6-astra",369 model: "gpt-6.2-astra",

370 instructions: "You are a helpful assistant that explains concepts simply.",370 instructions: "You are a helpful assistant that explains concepts simply.",

371 input: "Explain quantum computing in one sentence."371 input: "Explain quantum computing in one sentence."

372)372)


379 -H "Authorization: Bearer $OPENAI_API_KEY" \379 -H "Authorization: Bearer $OPENAI_API_KEY" \

380 -H "Content-Type: application/json" \380 -H "Content-Type: application/json" \

381 -d '{381 -d '{

382 "model": "gpt-6-astra",382 "model": "gpt-6.2-astra",

383 "instructions": "You are a helpful assistant that explains concepts simply.",383 "instructions": "You are a helpful assistant that explains concepts simply.",

384 "input": "Explain quantum computing in one sentence."384 "input": "Explain quantum computing in one sentence."

385 }'385 }'


389openai responses:input-tokens count \389openai responses:input-tokens count \

390 --raw-output \390 --raw-output \

391 --transform input_tokens <<'YAML'391 --transform input_tokens <<'YAML'

392model: gpt-6-astra392model: gpt-6.2-astra

393instructions: You are a helpful assistant that explains concepts simply.393instructions: You are a helpful assistant that explains concepts simply.

394input: Explain quantum computing in one sentence.394input: Explain quantum computing in one sentence.

395YAML395YAML


408const client = new OpenAI();408const client = new OpenAI();

409 409 

410const response = await client.responses.inputTokens.count({410const response = await client.responses.inputTokens.count({

411 model: "gpt-6-astra",411 model: "gpt-6.2-astra",

412 input: [412 input: [

413 {413 {

414 role: "user",414 role: "user",


434 434 

435# Use file_id from uploaded file, or image_url for a URL435# Use file_id from uploaded file, or image_url for a URL

436response = client.responses.input_tokens.count(436response = client.responses.input_tokens.count(

437 model="gpt-6-astra",437 model="gpt-6.2-astra",

438 input=[438 input=[

439 {439 {

440 "role": "user",440 "role": "user",


474 ),474 ),

475 }475 }

476 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{476 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{

477 Model: openai.String("gpt-6-astra"),477 Model: openai.String("gpt-6.2-astra"),

478 Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},478 Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},

479 })479 })

480 if err != nil {480 if err != nil {


498 .inputTokens()498 .inputTokens()

499 .count(499 .count(

500 InputTokenCountParams.builder()500 InputTokenCountParams.builder()

501 .model("gpt-6-astra")501 .model("gpt-6.2-astra")

502 .inputOfResponseInputItems(502 .inputOfResponseInputItems(

503 List.of(503 List.of(

504 ResponseInputItem.ofMessage(504 ResponseInputItem.ofMessage(


523client = OpenAI::Client.new523client = OpenAI::Client.new

524 524 

525count = client.responses.input_tokens.count(525count = client.responses.input_tokens.count(

526 model: "gpt-6-astra",526 model: "gpt-6.2-astra",

527 input: [527 input: [

528 {528 {

529 role: :user,529 role: :user,


550 -H "Authorization: Bearer $OPENAI_API_KEY" \550 -H "Authorization: Bearer $OPENAI_API_KEY" \

551 -H "Content-Type: application/json" \551 -H "Content-Type: application/json" \

552 -d '{552 -d '{

553 "model": "gpt-6-astra",553 "model": "gpt-6.2-astra",

554 "input": [{554 "input": [{

555 "role": "user",555 "role": "user",

556 "content": [556 "content": [


565openai responses:input-tokens count \565openai responses:input-tokens count \

566 --raw-output \566 --raw-output \

567 --transform input_tokens <<'YAML'567 --transform input_tokens <<'YAML'

568model: gpt-6-astra568model: gpt-6.2-astra

569input:569input:

570 - role: user570 - role: user

571 content:571 content:


591const client = new OpenAI();591const client = new OpenAI();

592 592 

593const response = await client.responses.inputTokens.count({593const response = await client.responses.inputTokens.count({

594 model: "gpt-6-astra",594 model: "gpt-6.2-astra",

595 tools: [595 tools: [

596 {596 {

597 type: "function",597 type: "function",


618client = OpenAI()618client = OpenAI()

619 619 

620response = client.responses.input_tokens.count(620response = client.responses.input_tokens.count(

621 model="gpt-6-astra",621 model="gpt-6.2-astra",

622 tools=[622 tools=[

623 {623 {

624 "type": "function",624 "type": "function",


660 tool := responses.ToolParamOfFunction("get_weather", parameters, true)660 tool := responses.ToolParamOfFunction("get_weather", parameters, true)

661 tool.OfFunction.Description = openai.String("Get the current weather in a location")661 tool.OfFunction.Description = openai.String("Get the current weather in a location")

662 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{662 count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{

663 Model: openai.String("gpt-6-astra"),663 Model: openai.String("gpt-6.2-astra"),

664 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("What is the weather in San Francisco?")},664 Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("What is the weather in San Francisco?")},

665 Tools: []responses.ToolUnionParam{tool},665 Tools: []responses.ToolUnionParam{tool},

666 })666 })


686 .inputTokens()686 .inputTokens()

687 .count(687 .count(

688 InputTokenCountParams.builder()688 InputTokenCountParams.builder()

689 .model("gpt-6-astra")689 .model("gpt-6.2-astra")

690 .input("What is the weather in San Francisco?")690 .input("What is the weather in San Francisco?")

691 .addTool(691 .addTool(

692 FunctionTool.builder()692 FunctionTool.builder()


717client = OpenAI::Client.new717client = OpenAI::Client.new

718 718 

719count = client.responses.input_tokens.count(719count = client.responses.input_tokens.count(

720 model: "gpt-6-astra",720 model: "gpt-6.2-astra",

721 input: "What is the weather in San Francisco?",721 input: "What is the weather in San Francisco?",

722 tools: [722 tools: [

723 {723 {


743 -H "Authorization: Bearer $OPENAI_API_KEY" \743 -H "Authorization: Bearer $OPENAI_API_KEY" \

744 -H "Content-Type: application/json" \744 -H "Content-Type: application/json" \

745 -d '{745 -d '{

746 "model": "gpt-6-astra",746 "model": "gpt-6.2-astra",

747 "tools": [{747 "tools": [{

748 "type": "function",748 "type": "function",

749 "name": "get_weather",749 "name": "get_weather",


762openai responses:input-tokens count \762openai responses:input-tokens count \

763 --raw-output \763 --raw-output \

764 --transform input_tokens <<'YAML'764 --transform input_tokens <<'YAML'

765model: gpt-6-astra765model: gpt-6.2-astra

766tools:766tools:

767 - type: function767 - type: function

768 name: get_weather768 name: get_weather

guides/tools.md +33 −33

Details

17const client = new OpenAI();17const client = new OpenAI();

18 18 

19const response = await client.responses.create({19const response = await client.responses.create({

20 model: "gpt-6-astra",20 model: "gpt-6.2-astra",

21 tools: [{ type: "web_search" }],21 tools: [{ type: "web_search" }],

22 input: "What was a positive news story from today?",22 input: "What was a positive news story from today?",

23});23});


31client = OpenAI()31client = OpenAI()

32 32 

33response = client.responses.create(33response = client.responses.create(

34 model="gpt-6-astra",34 model="gpt-6.2-astra",

35 tools=[{"type": "web_search"}],35 tools=[{"type": "web_search"}],

36 input="What was a positive news story from today?",36 input="What was a positive news story from today?",

37)37)


53func main() {53func main() {

54 client := openai.NewClient()54 client := openai.NewClient()

55 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{55 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

56 Model: "gpt-6-astra",56 Model: "gpt-6.2-astra",

57 Tools: []responses.ToolUnionParam{57 Tools: []responses.ToolUnionParam{

58 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),58 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),

59 },59 },


74 74 

75ResponseCreateParams params =75ResponseCreateParams params =

76 ResponseCreateParams.builder()76 ResponseCreateParams.builder()

77 .model("gpt-6-astra")77 .model("gpt-6.2-astra")

78 .input("What was a positive news story from today?")78 .input("What was a positive news story from today?")

79 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())79 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

80 .build();80 .build();


93string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;93string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

94ResponsesClient client = new(key);94ResponsesClient client = new(key);

95 95 

96CreateResponseOptions options = new() { Model = "gpt-6-astra" };96CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

97options.Tools.Add(ResponseTool.CreateWebSearchTool());97options.Tools.Add(ResponseTool.CreateWebSearchTool());

98options.InputItems.Add(98options.InputItems.Add(

99 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")99 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")


110openai = OpenAI::Client.new110openai = OpenAI::Client.new

111 111 

112response = openai.responses.create(112response = openai.responses.create(

113 model: "gpt-6-astra",113 model: "gpt-6.2-astra",

114 tools: [{ type: "web_search" }],114 tools: [{ type: "web_search" }],

115 input: "What was a positive news story from today?"115 input: "What was a positive news story from today?"

116)116)


123 -H "Content-Type: application/json" \123 -H "Content-Type: application/json" \

124 -H "Authorization: Bearer $OPENAI_API_KEY" \124 -H "Authorization: Bearer $OPENAI_API_KEY" \

125 -d '{125 -d '{

126 "model": "gpt-6-astra",126 "model": "gpt-6.2-astra",

127 "tools": [{"type": "web_search"}],127 "tools": [{"type": "web_search"}],

128 "input": "what was a positive news story from today?"128 "input": "what was a positive news story from today?"

129}'129}'


131 131 

132```bash132```bash

133openai responses create \133openai responses create \

134 --model gpt-6-astra \134 --model gpt-6.2-astra \

135 --raw-output \135 --raw-output \

136 --transform 'output.#(type=="message").content.0.text' <<'YAML'136 --transform 'output.#(type=="message").content.0.text' <<'YAML'

137tools:137tools:


154const openai = new OpenAI();154const openai = new OpenAI();

155 155 

156const response = await openai.responses.create({156const response = await openai.responses.create({

157 model: "gpt-6-astra",157 model: "gpt-6.2-astra",

158 input: "What is deep research by OpenAI?",158 input: "What is deep research by OpenAI?",

159 tools: [159 tools: [

160 {160 {


172client = OpenAI()172client = OpenAI()

173 173 

174response = client.responses.create(174response = client.responses.create(

175 model="gpt-6-astra",175 model="gpt-6.2-astra",

176 input="What is deep research by OpenAI?",176 input="What is deep research by OpenAI?",

177 tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],177 tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],

178)178)


193func main() {193func main() {

194 client := openai.NewClient()194 client := openai.NewClient()

195 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{195 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

196 Model: "gpt-6-astra",196 Model: "gpt-6.2-astra",

197 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},197 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},

198 Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},198 Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},

199 })199 })


214 214 

215ResponseCreateParams params =215ResponseCreateParams params =

216 ResponseCreateParams.builder()216 ResponseCreateParams.builder()

217 .model("gpt-6-astra")217 .model("gpt-6.2-astra")

218 .input("What is deep research by OpenAI?")218 .input("What is deep research by OpenAI?")

219 .addFileSearchTool(List.of(vectorStoreId))219 .addFileSearchTool(List.of(vectorStoreId))

220 .build();220 .build();


234string vectorStoreId = "<vector_store_id>";234string vectorStoreId = "<vector_store_id>";

235ResponsesClient client = new(key);235ResponsesClient client = new(key);

236 236 

237CreateResponseOptions options = new() { Model = "gpt-6-astra" };237CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

238options.Tools.Add(238options.Tools.Add(

239 ResponseTool.CreateFileSearchTool([vectorStoreId])239 ResponseTool.CreateFileSearchTool([vectorStoreId])

240);240);


253openai = OpenAI::Client.new253openai = OpenAI::Client.new

254 254 

255response = openai.responses.create(255response = openai.responses.create(

256 model: "gpt-6-astra",256 model: "gpt-6.2-astra",

257 input: "What is deep research by OpenAI?",257 input: "What is deep research by OpenAI?",

258 tools: [258 tools: [

259 {259 {


318};318};

319 319 

320const response = await client.responses.create({320const response = await client.responses.create({

321 model: "gpt-6-astra",321 model: "gpt-6.2-astra",

322 input: "List open orders for customer CUST-12345.",322 input: "List open orders for customer CUST-12345.",

323 // highlight-start:subtle323 // highlight-start:subtle

324 tools: [crmNamespace, { type: "tool_search" }],324 tools: [crmNamespace, { type: "tool_search" }],


372}372}

373 373 

374response = client.responses.create(374response = client.responses.create(

375 model="gpt-6-astra",375 model="gpt-6.2-astra",

376 input="List open orders for customer CUST-12345.",376 input="List open orders for customer CUST-12345.",

377 tools=[377 tools=[

378 crm_namespace,378 crm_namespace,


418 },418 },

419 )419 )

420 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{420 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

421 Model: "gpt-6-astra",421 Model: "gpt-6.2-astra",

422 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List open orders for customer CUST-12345.")},422 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List open orders for customer CUST-12345.")},

423 Tools: []responses.ToolUnionParam{namespace, {OfToolSearch: &responses.ToolSearchToolParam{}}},423 Tools: []responses.ToolUnionParam{namespace, {OfToolSearch: &responses.ToolSearchToolParam{}}},

424 ParallelToolCalls: openai.Bool(false),424 ParallelToolCalls: openai.Bool(false),


442 442 

443ResponseCreateParams params =443ResponseCreateParams params =

444 ResponseCreateParams.builder()444 ResponseCreateParams.builder()

445 .model("gpt-6-astra")445 .model("gpt-6.2-astra")

446 .input("List open orders for customer CUST-12345.")446 .input("List open orders for customer CUST-12345.")

447 .parallelToolCalls(false)447 .parallelToolCalls(false)

448 .addTool(448 .addTool(


502 additionalProperties: false502 additionalProperties: false

503}503}

504response = client.responses.create(504response = client.responses.create(

505 model: "gpt-6-astra",505 model: "gpt-6.2-astra",

506 input: "List open orders for customer CUST-12345.",506 input: "List open orders for customer CUST-12345.",

507 parallel_tool_calls: false,507 parallel_tool_calls: false,

508 tools: [508 tools: [


567];567];

568 568 

569const response = await client.responses.create({569const response = await client.responses.create({

570 model: "gpt-6-astra",570 model: "gpt-6.2-astra",

571 input: [571 input: [

572 { role: "user", content: "What is the weather like in Paris today?" },572 { role: "user", content: "What is the weather like in Paris today?" },

573 ],573 ],


603]603]

604 604 

605response = client.responses.create(605response = client.responses.create(

606 model="gpt-6-astra",606 model="gpt-6.2-astra",

607 input=[607 input=[

608 {"role": "user", "content": "What is the weather like in Paris today?"},608 {"role": "user", "content": "What is the weather like in Paris today?"},

609 ],609 ],


641 tool.OfFunction.Description = openai.String("Get current temperature for a given location.")641 tool.OfFunction.Description = openai.String("Get current temperature for a given location.")

642 642 

643 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{643 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

644 Model: "gpt-6-astra",644 Model: "gpt-6.2-astra",

645 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{645 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

646 responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),646 responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),

647 }},647 }},


665 665 

666ResponseCreateParams params =666ResponseCreateParams params =

667 ResponseCreateParams.builder()667 ResponseCreateParams.builder()

668 .model("gpt-6-astra")668 .model("gpt-6.2-astra")

669 .input("What is the weather like in Paris today?")669 .input("What is the weather like in Paris today?")

670 .addTool(670 .addTool(

671 FunctionTool.builder()671 FunctionTool.builder()


700string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;700string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

701ResponsesClient client = new(key);701ResponsesClient client = new(key);

702 702 

703CreateResponseOptions options = new() { Model = "gpt-6-astra" };703CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

704options.Tools.Add(704options.Tools.Add(

705 ResponseTool.CreateFunctionTool(705 ResponseTool.CreateFunctionTool(

706 functionName: "get_weather",706 functionName: "get_weather",


779]779]

780 780 

781response = openai.responses.create(781response = openai.responses.create(

782 model: "gpt-6-astra",782 model: "gpt-6.2-astra",

783 input: [783 input: [

784 {784 {

785 role: "user",785 role: "user",


797 -H "Authorization: Bearer $OPENAI_API_KEY" \797 -H "Authorization: Bearer $OPENAI_API_KEY" \

798 -H "Content-Type: application/json" \798 -H "Content-Type: application/json" \

799 -d '{799 -d '{

800 "model": "gpt-6-astra",800 "model": "gpt-6.2-astra",

801 "input": [801 "input": [

802 {"role": "user", "content": "What is the weather like in Paris today?"}802 {"role": "user", "content": "What is the weather like in Paris today?"}

803 ],803 ],


837-H "Content-Type: application/json" \837-H "Content-Type: application/json" \

838-H "Authorization: Bearer $OPENAI_API_KEY" \838-H "Authorization: Bearer $OPENAI_API_KEY" \

839-d '{839-d '{

840 "model": "gpt-6-astra",840 "model": "gpt-6.2-astra",

841 "tools": [841 "tools": [

842 {842 {

843 "type": "mcp",843 "type": "mcp",


856const client = new OpenAI();856const client = new OpenAI();

857 857 

858const resp = await client.responses.create({858const resp = await client.responses.create({

859 model: "gpt-6-astra",859 model: "gpt-6.2-astra",

860 tools: [860 tools: [

861 {861 {

862 type: "mcp",862 type: "mcp",


879client = OpenAI()879client = OpenAI()

880 880 

881resp = client.responses.create(881resp = client.responses.create(

882 model="gpt-6-astra",882 model="gpt-6.2-astra",

883 tools=[883 tools=[

884 {884 {

885 "type": "mcp",885 "type": "mcp",


914 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}914 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}

915 915 

916 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{916 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

917 Model: "gpt-6-astra",917 Model: "gpt-6.2-astra",

918 Tools: []responses.ToolUnionParam{tool},918 Tools: []responses.ToolUnionParam{tool},

919 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},919 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},

920 })920 })


933 933 

934ResponseCreateParams params =934ResponseCreateParams params =

935 ResponseCreateParams.builder()935 ResponseCreateParams.builder()

936 .model("gpt-6-astra")936 .model("gpt-6.2-astra")

937 .input(937 .input(

938 "Search the OpenAI docs for Responses API streaming and return the relevant links.")938 "Search the OpenAI docs for Responses API streaming and return the relevant links.")

939 .addTool(939 .addTool(


959string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;959string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

960ResponsesClient client = new(key);960ResponsesClient client = new(key);

961 961 

962CreateResponseOptions options = new() { Model = "gpt-6-astra" };962CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

963options.Tools.Add(963options.Tools.Add(

964 ResponseTool.CreateMcpTool(964 ResponseTool.CreateMcpTool(

965 serverLabel: "openai_docs",965 serverLabel: "openai_docs",


980openai = OpenAI::Client.new980openai = OpenAI::Client.new

981 981 

982response = openai.responses.create(982response = openai.responses.create(

983 model: "gpt-6-astra",983 model: "gpt-6.2-astra",

984 tools: [984 tools: [

985 {985 {

986 type: "mcp",986 type: "mcp",

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Use `apply_patch` with the Responses API to propose file creations, updates, and deletions as structured diffs. Your application applies each operation and returns its result. The examples use `gpt-6-astra`.5Use `apply_patch` with the Responses API to propose file creations, updates, and deletions as structured diffs. Your application applies each operation and returns its result. The examples use `gpt-6.2-astra`.

6 6 

7## When to use7## When to use

8 8 


72Help me rename the fib() function to fibonacci().`;72Help me rename the fib() function to fibonacci().`;

73 73 

74let response = await client.responses.create({74let response = await client.responses.create({

75 model: "gpt-6-astra",75 model: "gpt-6.2-astra",

76 input: fileContext,76 input: fileContext,

77 tools: [{ type: "apply_patch" }],77 tools: [{ type: "apply_patch" }],

78});78});


114"""114"""

115 115 

116response = client.responses.create(116response = client.responses.create(

117 model="gpt-6-astra",117 model="gpt-6.2-astra",

118 input=RESPONSE_INPUT,118 input=RESPONSE_INPUT,

119 tools=[{"type": "apply_patch"}],119 tools=[{"type": "apply_patch"}],

120)120)


129 129 

130```go130```go

131response, err := client.Responses.New(ctx, responses.ResponseNewParams{131response, err := client.Responses.New(ctx, responses.ResponseNewParams{

132 Model: "gpt-6-astra",132 Model: "gpt-6.2-astra",

133 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(responseInput)},133 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(responseInput)},

134 Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},134 Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},

135})135})


146 146 

147ResponseCreateParams params =147ResponseCreateParams params =

148 ResponseCreateParams.builder()148 ResponseCreateParams.builder()

149 .model("gpt-6-astra")149 .model("gpt-6.2-astra")

150 .input(150 .input(

151 "Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.")151 "Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.")

152 .addTool(ApplyPatchTool.builder().build())152 .addTool(ApplyPatchTool.builder().build())


167}167}

168context = files.map { |path, content| "===== #{path}\n#{content}" }.join168context = files.map { |path, content| "===== #{path}\n#{content}" }.join

169response = client.responses.create(169response = client.responses.create(

170 model: "gpt-6-astra",170 model: "gpt-6.2-astra",

171 input: "The user has the following files:\n<BEGIN_FILES>\n#{context}<END_FILES>\nHelp me rename fib() to fibonacci() in both existing files.",171 input: "The user has the following files:\n<BEGIN_FILES>\n#{context}<END_FILES>\nHelp me rename fib() to fibonacci() in both existing files.",

172 tools: [{ type: :apply_patch }]172 tools: [{ type: :apply_patch }]

173)173)


219 });219 });

220 220 

221 response = await client.responses.create({221 response = await client.responses.create({

222 model: "gpt-6-astra",222 model: "gpt-6.2-astra",

223 previous_response_id: response.id,223 previous_response_id: response.id,

224 input: results,224 input: results,

225 tools: [{ type: "apply_patch" }],225 tools: [{ type: "apply_patch" }],


259 )259 )

260 260 

261 response = client.responses.create(261 response = client.responses.create(

262 model="gpt-6-astra",262 model="gpt-6.2-astra",

263 previous_response_id=response.id,263 previous_response_id=response.id,

264 input=results,264 input=results,

265 tools=[{"type": "apply_patch"}],265 tools=[{"type": "apply_patch"}],


301 results = append(results, result)301 results = append(results, result)

302 }302 }

303 response, err = client.Responses.New(ctx, responses.ResponseNewParams{303 response, err = client.Responses.New(ctx, responses.ResponseNewParams{

304 Model: "gpt-6-astra",304 Model: "gpt-6.2-astra",

305 PreviousResponseID: openai.String(response.ID),305 PreviousResponseID: openai.String(response.ID),

306 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: results},306 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: results},

307 Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},307 Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},


322 322 

323ResponseCreateParams params =323ResponseCreateParams params =

324 ResponseCreateParams.builder()324 ResponseCreateParams.builder()

325 .model("gpt-6-astra")325 .model("gpt-6.2-astra")

326 .inputOfResponse(326 .inputOfResponse(

327 List.of(327 List.of(

328 ResponseInputItem.ofApplyPatchCallOutput(328 ResponseInputItem.ofApplyPatchCallOutput(


364 }364 }

365 end365 end

366 response = client.responses.create(366 response = client.responses.create(

367 model: "gpt-6-astra",367 model: "gpt-6.2-astra",

368 previous_response_id: response.id,368 previous_response_id: response.id,

369 input: results,369 input: results,

370 tools: [{ type: :apply_patch }]370 tools: [{ type: :apply_patch }]


505 505 

506const agent = new Agent({506const agent = new Agent({

507 name: "Patch Assistant",507 name: "Patch Assistant",

508 model: "gpt-6-astra",508 model: "gpt-6.2-astra",

509 instructions:509 instructions:

510 "Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",510 "Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",

511 tools: [511 tools: [


570 570 

571agent = Agent(571agent = Agent(

572 name="Patch Assistant",572 name="Patch Assistant",

573 model="gpt-6-astra",573 model="gpt-6.2-astra",

574 instructions="Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",574 instructions="Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",

575 tools=[575 tools=[

576 ApplyPatchTool(576 ApplyPatchTool(


710- [`gpt-6-sol`](https://developers.openai.com/api/docs/models/gpt-6-sol)710- [`gpt-6-sol`](https://developers.openai.com/api/docs/models/gpt-6-sol)

711- [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol)711- [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol)

712- [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra)712- [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra)

713- [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra)

714- [`gpt-6.2-sol`](https://developers.openai.com/api/docs/models/gpt-6.2-sol)

713 </td>715 </td>

714</tr>716</tr>

715 717 

Details

7- Processing files with diverse data and formatting7- Processing files with diverse data and formatting

8- Generating files with data and images of graphs8- Generating files with data and images of graphs

9- Writing and running code iteratively to solve problems—for example, a model that writes code that fails to run can keep rewriting and running that code until it succeeds9- Writing and running code iteratively to solve problems—for example, a model that writes code that fails to run can keep rewriting and running that code until it succeeds

10- Inspecting images with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra). Code Interpreter can crop, zoom, rotate, or read individual pixels using Python.10- Inspecting images with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra). Code Interpreter can crop, zoom, rotate, or read individual pixels using Python.

11 11 

12Here's an example of calling the [Responses API](https://developers.openai.com/api/reference/resources/responses) with a tool call to Code Interpreter:12Here's an example of calling the [Responses API](https://developers.openai.com/api/reference/resources/responses) with a tool call to Code Interpreter:

13 13 


18 -H "Content-Type: application/json" \18 -H "Content-Type: application/json" \

19 -H "Authorization: Bearer $OPENAI_API_KEY" \19 -H "Authorization: Bearer $OPENAI_API_KEY" \

20 -d '{20 -d '{

21 "model": "gpt-6-astra",21 "model": "gpt-6.2-astra",

22 "tools": [{22 "tools": [{

23 "type": "code_interpreter",23 "type": "code_interpreter",

24 "container": { "type": "auto", "memory_limit": "4g" }24 "container": { "type": "auto", "memory_limit": "4g" }


38`;38`;

39 39 

40const resp = await client.responses.create({40const resp = await client.responses.create({

41 model: "gpt-6-astra",41 model: "gpt-6.2-astra",

42 tools: [42 tools: [

43 {43 {

44 type: "code_interpreter",44 type: "code_interpreter",


63"""63"""

64 64 

65resp = client.responses.create(65resp = client.responses.create(

66 model="gpt-6-astra",66 model="gpt-6.2-astra",

67 tools=[67 tools=[

68 {68 {

69 "type": "code_interpreter",69 "type": "code_interpreter",


92 client := openai.NewClient()92 client := openai.NewClient()

93 tool := responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{MemoryLimit: "4g"})93 tool := responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{MemoryLimit: "4g"})

94 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{94 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

95 Model: "gpt-6-astra",95 Model: "gpt-6.2-astra",

96 Tools: []responses.ToolUnionParam{tool},96 Tools: []responses.ToolUnionParam{tool},

97 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question."),97 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question."),

98 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("I need to solve the equation 3x + 11 = 14. Can you help me?")},98 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("I need to solve the equation 3x + 11 = 14. Can you help me?")},


112 112 

113ResponseCreateParams params =113ResponseCreateParams params =

114 ResponseCreateParams.builder()114 ResponseCreateParams.builder()

115 .model("gpt-6-astra")115 .model("gpt-6.2-astra")

116 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")116 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")

117 .instructions(117 .instructions(

118 "You are a personal math tutor. Write and run Python code to answer each math question.")118 "You are a personal math tutor. Write and run Python code to answer each math question.")


132client = OpenAI::Client.new132client = OpenAI::Client.new

133 133 

134response = client.responses.create(134response = client.responses.create(

135 model: "gpt-6-astra",135 model: "gpt-6.2-astra",

136 instructions: "You are a personal math tutor. Write and run Python code to answer each math question.",136 instructions: "You are a personal math tutor. Write and run Python code to answer each math question.",

137 input: "I need to solve the equation 3x + 11 = 14. Can you help me?",137 input: "I need to solve the equation 3x + 11 = 14. Can you help me?",

138 tools: [138 tools: [


180 -H "Authorization: Bearer $OPENAI_API_KEY" \180 -H "Authorization: Bearer $OPENAI_API_KEY" \

181 -H "Content-Type: application/json" \181 -H "Content-Type: application/json" \

182 -d '{182 -d '{

183 "model": "gpt-6-astra",183 "model": "gpt-6.2-astra",

184 "tools": [{184 "tools": [{

185 "type": "code_interpreter",185 "type": "code_interpreter",

186 "container": "cntr_abc123"186 "container": "cntr_abc123"


200});200});

201 201 

202const resp = await client.responses.create({202const resp = await client.responses.create({

203 model: "gpt-6-astra",203 model: "gpt-6.2-astra",

204 tools: [204 tools: [

205 {205 {

206 type: "code_interpreter",206 type: "code_interpreter",


223container = client.containers.create(name="test-container", memory_limit="4g")223container = client.containers.create(name="test-container", memory_limit="4g")

224 224 

225response = client.responses.create(225response = client.responses.create(

226 model="gpt-6-astra",226 model="gpt-6.2-astra",

227 tools=[{"type": "code_interpreter", "container": container.id}],227 tools=[{"type": "code_interpreter", "container": container.id}],

228 tool_choice="required",228 tool_choice="required",

229 input="use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result",229 input="use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result",


259 }()259 }()

260 260 

261 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{261 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

262 Model: "gpt-6-astra",262 Model: "gpt-6.2-astra",

263 Tools: []responses.ToolUnionParam{responses.ToolParamOfCodeInterpreter(container.ID)},263 Tools: []responses.ToolUnionParam{responses.ToolParamOfCodeInterpreter(container.ID)},

264 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},264 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},

265 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result")},265 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result")},


292 .responses()292 .responses()

293 .create(293 .create(

294 ResponseCreateParams.builder()294 ResponseCreateParams.builder()

295 .model("gpt-6-astra")295 .model("gpt-6.2-astra")

296 .input("Calculate 4 * 3.82, then take the square root twice.")296 .input("Calculate 4 * 3.82, then take the square root twice.")

297 .toolChoice(ToolChoiceOptions.REQUIRED)297 .toolChoice(ToolChoiceOptions.REQUIRED)

298 .addCodeInterpreterTool(container.id())298 .addCodeInterpreterTool(container.id())


311client = OpenAI::Client.new311client = OpenAI::Client.new

312container = client.containers.create(name: "analysis", memory_limit: "4g")312container = client.containers.create(name: "analysis", memory_limit: "4g")

313response = client.responses.create(313response = client.responses.create(

314 model: "gpt-6-astra",314 model: "gpt-6.2-astra",

315 tools: [315 tools: [

316 {316 {

317 type: :code_interpreter,317 type: :code_interpreter,

Details

529const client = new OpenAI();529const client = new OpenAI();

530 530 

531const response = await client.responses.create({531const response = await client.responses.create({

532 model: "gpt-6.1-sol",532 model: "gpt-6.2-sol",

533 tools: [{ type: "computer" }],533 tools: [{ type: "computer" }],

534 input:534 input:

535 "Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",535 "Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",


544client = OpenAI()544client = OpenAI()

545 545 

546response = client.responses.create(546response = client.responses.create(

547 model="gpt-6.1-sol",547 model="gpt-6.2-sol",

548 tools=[{"type": "computer"}],548 tools=[{"type": "computer"}],

549 input="Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",549 input="Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",

550)550)


566func main() {566func main() {

567 client := openai.NewClient()567 client := openai.NewClient()

568 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{568 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

569 Model: "gpt-6.1-sol",569 Model: "gpt-6.2-sol",

570 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},570 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},

571 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.")},571 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.")},

572 })572 })


587 587 

588ResponseCreateParams params =588ResponseCreateParams params =

589 ResponseCreateParams.builder()589 ResponseCreateParams.builder()

590 .model("gpt-6.1-sol")590 .model("gpt-6.2-sol")

591 .input(591 .input(

592 "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.")592 "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.")

593 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))593 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))


601 601 

602client = OpenAI::Client.new602client = OpenAI::Client.new

603response = client.responses.create(603response = client.responses.create(

604 model: "gpt-6.1-sol",604 model: "gpt-6.2-sol",

605 input: "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.",605 input: "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.",

606 tools: [{ type: :computer }]606 tools: [{ type: :computer }]

607)607)


630 };630 };

631 631 

632 return await client.responses.create({632 return await client.responses.create({

633 model: "gpt-6.1-sol",633 model: "gpt-6.2-sol",

634 tools: [{ type: "computer" }],634 tools: [{ type: "computer" }],

635 previous_response_id: response.id,635 previous_response_id: response.id,

636 input: [636 input: [


652 652 

653def send_computer_screenshot(response, call_id, screenshot_base64):653def send_computer_screenshot(response, call_id, screenshot_base64):

654 return client.responses.create(654 return client.responses.create(

655 model="gpt-6.1-sol",655 model="gpt-6.2-sol",

656 tools=[{"type": "computer"}],656 tools=[{"type": "computer"}],

657 previous_response_id=response.id,657 previous_response_id=response.id,

658 input=[658 input=[


695 }695 }

696 screenshot.SetExtraFields(map[string]any{"detail": "original"})696 screenshot.SetExtraFields(map[string]any{"detail": "original"})

697 return client.Responses.New(context.Background(), responses.ResponseNewParams{697 return client.Responses.New(context.Background(), responses.ResponseNewParams{

698 Model: "gpt-6.1-sol",698 Model: "gpt-6.2-sol",

699 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},699 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},

700 PreviousResponseID: openai.String(responseID),700 PreviousResponseID: openai.String(responseID),

701 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{701 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{


723 723 

724ResponseCreateParams params =724ResponseCreateParams params =

725 ResponseCreateParams.builder()725 ResponseCreateParams.builder()

726 .model("gpt-6.1-sol")726 .model("gpt-6.2-sol")

727 .input(727 .input(

728 ResponseCreateParams.Input.ofResponse(728 ResponseCreateParams.Input.ofResponse(

729 List.of(729 List.of(


748 748 

749client = OpenAI::Client.new749client = OpenAI::Client.new

750response = client.responses.create(750response = client.responses.create(

751 model: "gpt-6.1-sol",751 model: "gpt-6.2-sol",

752 previous_response_id: "resp_abc123",752 previous_response_id: "resp_abc123",

753 input: [753 input: [

754 {754 {


902 const response = await tools.run(902 const response = await tools.run(

903 client,903 client,

904 {904 {

905 model: "gpt-6.1-sol",905 model: "gpt-6.2-sol",

906 store: false,906 store: false,

907 input:907 input:

908 "Take a screenshot. Open 'Show pickup details' and report the locker and pickup code. Use only screenshots and left clicks.",908 "Take a screenshot. Open 'Show pickup details' and report the locker and pickup code. Use only screenshots and left clicks.",


992 response = await tools.run(992 response = await tools.run(

993 client,993 client,

994 {994 {

995 "model": "gpt-6.1-sol",995 "model": "gpt-6.2-sol",

996 "store": False,996 "store": False,

997 "input": "Take a screenshot. Open 'Show pickup details' and report the locker and pickup code. Use only screenshots and left clicks.",997 "input": "Take a screenshot. Open 'Show pickup details' and report the locker and pickup code. Use only screenshots and left clicks.",

998 },998 },


1118 const response = await new ResponsesToolRunner({ browser: tools }).run(1118 const response = await new ResponsesToolRunner({ browser: tools }).run(

1119 client,1119 client,

1120 {1120 {

1121 model: "gpt-6-astra",1121 model: "gpt-6.2-astra",

1122 store: false,1122 store: false,

1123 input: "Create a visitor badge for Mira.",1123 input: "Create a visitor badge for Mira.",

1124 },1124 },


1214 response = await AsyncResponsesToolRunner(browser=tools).run(1214 response = await AsyncResponsesToolRunner(browser=tools).run(

1215 client,1215 client,

1216 {1216 {

1217 "model": "gpt-6-astra",1217 "model": "gpt-6.2-astra",

1218 "store": False,1218 "store": False,

1219 "input": "Create a visitor badge for Mira.",1219 "input": "Create a visitor badge for Mira.",

1220 },1220 },


1687const client = new OpenAI();1687const client = new OpenAI();

1688 1688 

1689const response = await client.responses.create({1689const response = await client.responses.create({

1690 model: "gpt-6.1-sol",1690 model: "gpt-6.2-sol",

1691 tools: [{ type: "computer" }],1691 tools: [{ type: "computer" }],

1692 input:1692 input:

1693 "Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",1693 "Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",


1702client = OpenAI()1702client = OpenAI()

1703 1703 

1704response = client.responses.create(1704response = client.responses.create(

1705 model="gpt-6.1-sol",1705 model="gpt-6.2-sol",

1706 tools=[{"type": "computer"}],1706 tools=[{"type": "computer"}],

1707 input="Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",1707 input="Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",

1708)1708)


1724func main() {1724func main() {

1725 client := openai.NewClient()1725 client := openai.NewClient()

1726 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1726 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1727 Model: "gpt-6.1-sol",1727 Model: "gpt-6.2-sol",

1728 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},1728 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},

1729 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.")},1729 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.")},

1730 })1730 })


1745 1745 

1746ResponseCreateParams params =1746ResponseCreateParams params =

1747 ResponseCreateParams.builder()1747 ResponseCreateParams.builder()

1748 .model("gpt-6.1-sol")1748 .model("gpt-6.2-sol")

1749 .input(1749 .input(

1750 "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.")1750 "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.")

1751 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))1751 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))


1759 1759 

1760client = OpenAI::Client.new1760client = OpenAI::Client.new

1761response = client.responses.create(1761response = client.responses.create(

1762 model: "gpt-6.1-sol",1762 model: "gpt-6.2-sol",

1763 input: "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.",1763 input: "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.",

1764 tools: [{ type: :computer }]1764 tools: [{ type: :computer }]

1765)1765)


1833 };1833 };

1834 1834 

1835 return await client.responses.create({1835 return await client.responses.create({

1836 model: "gpt-6.1-sol",1836 model: "gpt-6.2-sol",

1837 tools: [{ type: "computer" }],1837 tools: [{ type: "computer" }],

1838 previous_response_id: response.id,1838 previous_response_id: response.id,

1839 input: [1839 input: [


1855 1855 

1856def send_computer_screenshot(response, call_id, screenshot_base64):1856def send_computer_screenshot(response, call_id, screenshot_base64):

1857 return client.responses.create(1857 return client.responses.create(

1858 model="gpt-6.1-sol",1858 model="gpt-6.2-sol",

1859 tools=[{"type": "computer"}],1859 tools=[{"type": "computer"}],

1860 previous_response_id=response.id,1860 previous_response_id=response.id,

1861 input=[1861 input=[


1898 }1898 }

1899 screenshot.SetExtraFields(map[string]any{"detail": "original"})1899 screenshot.SetExtraFields(map[string]any{"detail": "original"})

1900 return client.Responses.New(context.Background(), responses.ResponseNewParams{1900 return client.Responses.New(context.Background(), responses.ResponseNewParams{

1901 Model: "gpt-6.1-sol",1901 Model: "gpt-6.2-sol",

1902 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},1902 Tools: []responses.ToolUnionParam{{OfComputer: &responses.ComputerToolParam{}}},

1903 PreviousResponseID: openai.String(responseID),1903 PreviousResponseID: openai.String(responseID),

1904 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1904 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{


1926 1926 

1927ResponseCreateParams params =1927ResponseCreateParams params =

1928 ResponseCreateParams.builder()1928 ResponseCreateParams.builder()

1929 .model("gpt-6.1-sol")1929 .model("gpt-6.2-sol")

1930 .input(1930 .input(

1931 ResponseCreateParams.Input.ofResponse(1931 ResponseCreateParams.Input.ofResponse(

1932 List.of(1932 List.of(


1951 1951 

1952client = OpenAI::Client.new1952client = OpenAI::Client.new

1953response = client.responses.create(1953response = client.responses.create(

1954 model: "gpt-6.1-sol",1954 model: "gpt-6.2-sol",

1955 previous_response_id: "resp_abc123",1955 previous_response_id: "resp_abc123",

1956 input: [1956 input: [

1957 {1957 {

Details

218 await tools.run(218 await tools.run(

219 client,219 client,

220 {220 {

221 model: "gpt-6.1-sol",221 model: "gpt-6.2-sol",

222 store: false,222 store: false,

223 input:223 input:

224 `The open editor has dispatch.txt. Replace its content with exactly "${note}". ` +224 `The open editor has dispatch.txt. Replace its content with exactly "${note}". ` +


323 tools.run(323 tools.run(

324 client,324 client,

325 {325 {

326 "model": "gpt-6.1-sol",326 "model": "gpt-6.2-sol",

327 "store": False,327 "store": False,

328 "input": (328 "input": (

329 f'The open editor has dispatch.txt. Replace its content with exactly "{NOTE}". '329 f'The open editor has dispatch.txt. Replace its content with exactly "{NOTE}". '


423 423 

424Install Playwright:424Install Playwright:

425 425 

426- Python: `pip install playwright` and then `playwright install`

427- JavaScript: `npm i playwright` and then `npx playwright install`

428 426 

429Then launch a browser instance. Keep the browser and page alive while you run the remaining steps. In Python, those steps belong inside the `with sync_playwright()` block:427 

428 

429Install Playwright with `pip install playwright` and then `playwright install`.

430 

431 

432 

433 

434 

435 

436 

437Install Playwright with `npm i playwright` and then `npx playwright install`.

438 

439 

440 

441 

442 

443 

444 

445With Node.js installed, run `gem install playwright-ruby-client -v 1.61.0`, `npm install playwright@1.61.1`, and then `npx playwright install chromium`.

446 

447 

448 

449 

450 

451 

452 

453For Ruby, run the installation commands in your project directory. Before running the sample, set `PLAYWRIGHT_CLI_EXECUTABLE_PATH` to the absolute path of `node_modules/.bin/playwright` in that directory.

454 

455 

456 

457 

458Then launch a browser instance. Keep the browser and page alive while you run the remaining steps.

459 

460 

461 

462 

463In Python, those steps belong inside the `with sync_playwright()` block.

464 

465 

466 

467 

468 

469 

470 

471In Ruby, run those steps in the block passed to `with_browser`.

472 

473 

474 

430 475 

431Start a browser instance476Start a browser instance

432 477 


458 page = browser.new_page(viewport={"width": 1280, "height": 720})503 page = browser.new_page(viewport={"width": 1280, "height": 720})

459```504```

460 505 

506```ruby

507require "playwright"

508 

509def with_browser

510 Playwright.create(playwright_cli_executable_path: ENV.fetch("PLAYWRIGHT_CLI_EXECUTABLE_PATH")) do |playwright|

511 playwright.chromium.launch(

512 headless: true, chromiumSandbox: true, env: [],

513 args: ["--disable-extensions", "--disable-file-system"]

514 ) do |browser|

515 page = browser.new_page(

516 viewport: {

517 width: 1280,

518 height: 720

519 }

520 )

521 yield page

522 end

523 end

524end

525```

526 

461 527 

462 528 

463 529 


609vm = VM(display=":99", container_name="cua-image")675vm = VM(display=":99", container_name="cua-image")

610```676```

611 677 

678```ruby

679def docker_exec(container_name, executable, args, decode: true, env: {})

680 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }

681 command = ["docker", "exec", *environment, container_name, executable, *args.map(&:to_s)]

682 output = IO.popen(command, "rb", &:read)

683 status = $?

684 raise "docker exec failed (#{status&.exitstatus})" unless status&.success?

685 return output unless decode

686 

687 output.force_encoding(Encoding::UTF_8)

688 raise EncodingError, "Command output is not UTF-8" unless output.valid_encoding?

689 

690 output

691end

692 

693VM = Struct.new(:display, :container_name)

694vm = VM.new(display: ":99", container_name: "cua-image")

695```

696 

612 697 

613When you finish, stop the container:698When you finish, stop the container:

614 699 


807 return [(point.x, point.y) for point in path]892 return [(point.x, point.y) for point in path]

808```893```

809 894 

895```ruby

896def normalize_key(key)

897 names = {

898 "ENTER" => "Enter",

899 

900 "RETURN" => "Enter",

901 

902 "ESC" => "Escape",

903 

904 "ESCAPE" => "Escape",

905 "TAB" => "Tab",

906 

907 "SPACE" => "Space",

908 

909 "BACKSPACE" => "Backspace",

910 

911 "DELETE" => "Delete",

912 

913 "DEL" => "Delete",

914 "HOME" => "Home",

915 

916 "END" => "End",

917 

918 "PAGEUP" => "PageUp",

919 

920 "PAGEDOWN" => "PageDown",

921 "UP" => "ArrowUp",

922 

923 "DOWN" => "ArrowDown",

924 

925 "LEFT" => "ArrowLeft",

926 

927 "RIGHT" => "ArrowRight",

928 "ARROWUP" => "ArrowUp",

929 

930 "ARROWDOWN" => "ArrowDown",

931 

932 "ARROWLEFT" => "ArrowLeft",

933 

934 "ARROWRIGHT" => "ArrowRight",

935 "CTRL" => "Control",

936 

937 "CONTROL" => "Control",

938 

939 "SHIFT" => "Shift",

940 

941 "OPTION" => "Alt",

942 

943 "ALT" => "Alt",

944 "META" => "Meta",

945 

946 "CMD" => "Meta",

947 

948 "COMMAND" => "Meta"

949 }

950 names.fetch(key, key)

951end

952 

953def normalize_playwright_button(button = "left")

954 {

955 "left" => "left",

956 "right" => "right",

957 "wheel" => "middle"

958 }.fetch(button.to_s) do

959 raise ArgumentError, "Unsupported Playwright mouse button: #{button}"

960 end

961end

962 

963def normalize_drag_path(path)

964 path.map { |point| [point.x, point.y_] }

965end

966```

967 

810 968

811 969 

812 970


1002 return [(point.x, point.y) for point in path]1160 return [(point.x, point.y) for point in path]

1003```1161```

1004 1162 

1163```ruby

1164def normalize_xdotool_key(key)

1165 names = {

1166 "ENTER" => "Return",

1167 

1168 "RETURN" => "Return",

1169 

1170 "ESC" => "Escape",

1171 

1172 "ESCAPE" => "Escape",

1173 "TAB" => "Tab",

1174 

1175 "SPACE" => "space",

1176 

1177 "BACKSPACE" => "BackSpace",

1178 

1179 "DELETE" => "Delete",

1180 

1181 "DEL" => "Delete",

1182 "HOME" => "Home",

1183 

1184 "END" => "End",

1185 

1186 "PAGEUP" => "Page_Up",

1187 

1188 "PAGEDOWN" => "Page_Down",

1189 "UP" => "Up",

1190 

1191 "DOWN" => "Down",

1192 

1193 "LEFT" => "Left",

1194 

1195 "RIGHT" => "Right",

1196 "ARROWUP" => "Up",

1197 

1198 "ARROWDOWN" => "Down",

1199 

1200 "ARROWLEFT" => "Left",

1201 

1202 "ARROWRIGHT" => "Right",

1203 "CTRL" => "ctrl",

1204 

1205 "CONTROL" => "ctrl",

1206 

1207 "SHIFT" => "shift",

1208 

1209 "OPTION" => "alt",

1210 

1211 "ALT" => "alt",

1212 "META" => "super",

1213 

1214 "CMD" => "super",

1215 

1216 "COMMAND" => "super"

1217 }

1218 names.fetch(key, key)

1219end

1220 

1221def normalize_xdotool_button(button = "left")

1222 {

1223 "left" => 1,

1224 "wheel" => 2,

1225 "right" => 3,

1226 "back" => 8,

1227 "forward" => 9

1228 }.fetch(button.to_s) do

1229 raise ArgumentError, "Unsupported xdotool mouse button: #{button}"

1230 end

1231end

1232 

1233def get_xdotool_scroll_buttons(scroll_x, scroll_y)

1234 [[scroll_y, 4, 5], [scroll_x, 6, 7]].flat_map do |delta, negative, positive|

1235 next [] if delta.zero?

1236 

1237 [delta.negative? ? negative : positive] * [(delta / 100.0).round(half: :even).abs, 1].max

1238 end

1239end

1240 

1241def normalize_drag_path(path)

1242 path.map { |point| [point.x, point.y_] }

1243end

1244```

1245 

1005 1246 

1006 1247 

1007 1248 


1153 raise ValueError(f"Unsupported action: {action.type}")1394 raise ValueError(f"Unsupported action: {action.type}")

1154```1395```

1155 1396 

1397```ruby

1398def perform_browser_action(page, action)

1399 case action.type

1400 when :click

1401 page.mouse.click(action.x, action.y_, button: normalize_playwright_button(action.button))

1402 when :double_click

1403 page.mouse.dblclick(action.x, action.y_)

1404 when :drag

1405 path = normalize_drag_path(action.path)

1406 raise ArgumentError, "A drag requires at least two path points" if path.length < 2

1407 

1408 page.mouse.move(*path.first)

1409 page.mouse.down

1410 begin

1411 path.drop(1).each { |point| page.mouse.move(*point) }

1412 ensure

1413 page.mouse.up

1414 end

1415 when :move

1416 page.mouse.move(action.x, action.y_)

1417 when :scroll

1418 page.mouse.move(action.x, action.y_)

1419 page.mouse.wheel(action.scroll_x, action.scroll_y)

1420 when :keypress

1421 page.keyboard.press(action.keys.map { |key| normalize_key(key) }.join("+"))

1422 when :type

1423 page.keyboard.type(action.text)

1424 when :wait

1425 sleep 2

1426 when :screenshot

1427 # Capture the screenshot after applying the actions.

1428 else

1429 raise ArgumentError, "Unsupported action: #{action.type}"

1430 end

1431end

1432 

1433def handle_computer_actions(page, actions)

1434 actions.each do |action|

1435 if action.type != :keypress && action.respond_to?(:keys) && !Array(action.keys).empty?

1436 raise ArgumentError, "Use the modifier-aware handler for mouse modifiers"

1437 end

1438 

1439 perform_browser_action(page, action)

1440 end

1441end

1442```

1443 

1156 1444

1157 1445 

1158 1446


1396 raise ValueError(f"Unsupported action: {action.type}")1684 raise ValueError(f"Unsupported action: {action.type}")

1397```1685```

1398 1686 

1687```ruby

1688def run_xdotool(vm, *args)

1689 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })

1690end

1691 

1692def perform_desktop_action(vm, action)

1693 case action.type

1694 when :click

1695 button = normalize_xdotool_button(action.button)

1696 run_xdotool(vm, "mousemove", action.x, action.y_, "click", button)

1697 when :double_click

1698 run_xdotool(vm, "mousemove", action.x, action.y_, "click", "--repeat", 2, 1)

1699 when :drag

1700 path = normalize_drag_path(action.path)

1701 raise ArgumentError, "A drag requires at least two path points" if path.length < 2

1702 

1703 run_xdotool(vm, "mousemove", path.fetch(0).fetch(0), path.fetch(0).fetch(1), "mousedown", 1)

1704 begin

1705 path.drop(1).each { |point| run_xdotool(vm, "mousemove", point.fetch(0), point.fetch(1)) }

1706 ensure

1707 run_xdotool(vm, "mouseup", 1)

1708 end

1709 when :move

1710 run_xdotool(vm, "mousemove", action.x, action.y_)

1711 when :scroll

1712 run_xdotool(vm, "mousemove", action.x, action.y_)

1713 get_xdotool_scroll_buttons(action.scroll_x, action.scroll_y).each do |button|

1714 run_xdotool(vm, "click", button)

1715 end

1716 when :keypress

1717 run_xdotool(vm, "key", action.keys.map { |key| normalize_xdotool_key(key) }.join("+"))

1718 when :type

1719 run_xdotool(vm, "type", "--delay", 0, "--", action.text)

1720 when :wait

1721 sleep 2

1722 when :screenshot

1723 # Capture the screenshot after applying the actions.

1724 else

1725 raise ArgumentError, "Unsupported action: #{action.type}"

1726 end

1727end

1728 

1729def handle_computer_actions(vm, actions)

1730 actions.each do |action|

1731 if action.type != :keypress && action.respond_to?(:keys) && !Array(action.keys).empty?

1732 raise ArgumentError, "Use the modifier-aware handler for mouse modifiers"

1733 end

1734 

1735 perform_desktop_action(vm, action)

1736 end

1737end

1738```

1739 

1399 1740 

1400 1741 

1401For mouse interactions that need held modifiers, use the mouse action's `keys` array. Use `keypress` for standalone keyboard input.1742For mouse interactions that need held modifiers, use the mouse action's `keys` array. Use `keypress` for standalone keyboard input.


1623 raise ValueError(f"Unsupported action: {action.type}")1964 raise ValueError(f"Unsupported action: {action.type}")

1624```1965```

1625 1966 

1967```ruby

1968def with_modifiers(page, keys)

1969 pressed = []

1970 begin

1971 Array(keys).each do |key|

1972 normalized = normalize_key(key)

1973 page.keyboard.down(normalized)

1974 pressed << normalized

1975 end

1976 yield

1977 ensure

1978 pressed.reverse_each { |key| page.keyboard.up(key) }

1979 end

1980end

1981 

1982def handle_computer_actions_with_modifiers(page, actions)

1983 actions.each do |action|

1984 if [:click, :double_click, :drag, :move, :scroll].include?(action.type)

1985 with_modifiers(page, action.keys) { perform_browser_action(page, action) }

1986 else

1987 perform_browser_action(page, action)

1988 end

1989 end

1990end

1991```

1992 

1626 1993

1627 1994 

1628 1995


1921 raise ValueError(f"Unsupported action: {action.type}")2288 raise ValueError(f"Unsupported action: {action.type}")

1922```2289```

1923 2290 

2291```ruby

2292def with_modifiers(vm, keys)

2293 pressed = []

2294 begin

2295 Array(keys).each do |key|

2296 normalized = normalize_xdotool_key(key)

2297 run_xdotool(vm, "keydown", normalized)

2298 pressed << normalized

2299 end

2300 yield

2301 ensure

2302 pressed.reverse_each { |key| run_xdotool(vm, "keyup", key) }

2303 end

2304end

2305 

2306def handle_computer_actions_with_modifiers(vm, actions)

2307 actions.each do |action|

2308 if [:click, :double_click, :drag, :move, :scroll].include?(action.type)

2309 with_modifiers(vm, action.keys) { perform_desktop_action(vm, action) }

2310 else

2311 perform_desktop_action(vm, action)

2312 end

2313 end

2314end

2315```

2316 

1924 2317 

1925 2318 

1926 2319 


1970 };2363 };

1971 2364 

1972 response = await client.responses.create({2365 response = await client.responses.create({

1973 model: "gpt-6.1-sol",2366 model: "gpt-6.2-sol",

1974 tools: [{ type: "computer" }],2367 tools: [{ type: "computer" }],

1975 previous_response_id: response.id,2368 previous_response_id: response.id,

1976 input: [2369 input: [


2008 screenshot_base64 = base64.b64encode(screenshot).decode("utf-8")2401 screenshot_base64 = base64.b64encode(screenshot).decode("utf-8")

2009 2402 

2010 response = client.responses.create(2403 response = client.responses.create(

2011 model="gpt-6.1-sol",2404 model="gpt-6.2-sol",

2012 tools=[{"type": "computer"}],2405 tools=[{"type": "computer"}],

2013 previous_response_id=response.id,2406 previous_response_id=response.id,

2014 input=[2407 input=[


2236 .responses()2629 .responses()

2237 .create(2630 .create(

2238 ResponseCreateParams.builder()2631 ResponseCreateParams.builder()

2239 .model("gpt-6.1-sol")2632 .model("gpt-6.2-sol")

2240 .previousResponseId(response.id())2633 .previousResponseId(response.id())

2241 .putAdditionalBodyProperty(2634 .putAdditionalBodyProperty(

2242 "tools", JsonValue.from(List.of(Map.of("type", "computer"))))2635 "tools", JsonValue.from(List.of(Map.of("type", "computer"))))


2262 .forEach(text -> System.out.println(text.text()));2655 .forEach(text -> System.out.println(text.text()));

2263```2656```

2264 2657 

2658```ruby

2659require "base64"

2660 

2661def computer_use_loop(client, target, response)

2662 loop do

2663 call = response.output.find { |item| item.type == :computer_call }

2664 return response unless call

2665 raise "Computer action requires user approval" unless Array(call.pending_safety_checks).empty?

2666 

2667 actions = call.actions || [call.action].compact

2668 raise "Computer call did not contain an action" if actions.empty?

2669 

2670 handle_computer_actions(target, actions)

2671 screenshot = Base64.strict_encode64(capture_screenshot(target))

2672 response = client.responses.create(

2673 model: "gpt-6.2-sol", tools: [{ type: :computer }], previous_response_id: response.id,

2674 input: [

2675 {

2676 type: :computer_call_output,

2677 

2678 call_id: call.call_id,

2679 output: {

2680 type: :computer_screenshot,

2681 image_url: "data:image/png;base64,#{screenshot}",

2682 detail: :original

2683 }

2684 }

2685 ]

2686 )

2687 end

2688end

2689```

2690 

2265 2691 

2266 2692 

2267 2693 


2312 return page.screenshot(type="png")2738 return page.screenshot(type="png")

2313```2739```

2314 2740 

2741```ruby

2742def capture_screenshot(page)

2743 page.screenshot(type: "png")

2744end

2745```

2746 

2315 2747

2316 2748 

2317 2749


2346 )2778 )

2347```2779```

2348 2780 

2781```ruby

2782def capture_screenshot(vm)

2783 docker_exec(

2784 vm.container_name, "import", ["-window", "root", "png:-"],

2785 env: { "DISPLAY" => vm.display }, decode: false

2786 )

2787end

2788```

2789 

2349 2790 

2350 2791 

2351For Computer use, prefer `detail: "original"` on screenshot inputs to preserve resolution and improve click accuracy. Large screenshots can use more input tokens, and `original` can still resize images that exceed the model's dimension limits. For patch-based image inputs, the API rejects screenshots that still exceed the [30,000-patch limit](https://developers.openai.com/api/docs/guides/images-vision#image-input-requirements) after resizing. It does not resize them to fit that limit. If `detail: "original"` uses too many tokens or exceeds the limit, scale down the image before sending it to the API, and make sure you remap model-generated coordinates from the scaled image's coordinate space to the original image's coordinate space. Avoid using `high` or `low` image detail for computer use tasks. When scaling down, we observe strong performance with 1440 × 900 and 1600 × 900 desktop resolutions. See the [Images and Vision guide](https://developers.openai.com/api/docs/guides/images-vision#model-sizing-behavior) for the limits that apply to each model.2792For Computer use, prefer `detail: "original"` on screenshot inputs to preserve resolution and improve click accuracy. Large screenshots can use more input tokens, and `original` can still resize images that exceed the model's dimension limits. For patch-based image inputs, the API rejects screenshots that still exceed the [30,000-patch limit](https://developers.openai.com/api/docs/guides/images-vision#image-input-requirements) after resizing. It does not resize them to fit that limit. If `detail: "original"` uses too many tokens or exceeds the limit, scale down the image before sending it to the API, and make sure you remap model-generated coordinates from the scaled image's coordinate space to the original image's coordinate space. Avoid using `high` or `low` image detail for computer use tasks. When scaling down, we observe strong performance with 1440 × 900 and 1600 × 900 desktop resolutions. See the [Images and Vision guide](https://developers.openai.com/api/docs/guides/images-vision#model-sizing-behavior) for the limits that apply to each model.


2747```3188```

2748 3189 

2749 3190 

2750Python, TypeScript, Ruby, and Go have complete [API loop examples](https://developers.openai.com/api/docs/guides/tools-computer-use#connect-your-own-runtime) for this execution-service contract. Use `run_computer_use` in Python or Ruby, or `runComputerUse` in TypeScript or Go, with your endpoint and task. The Go example also takes a context, SDK client, terminal scanner, and output writer; use its included adapter to preserve those inputs across calls. The loop preserves the runtime session and uses `previous_response_id` to continue the model conversation. It stops after 20 responses if the task has not finished.3191Complete [API loop examples](https://developers.openai.com/api/docs/guides/tools-computer-use#connect-your-own-runtime) are available for this execution-service contract. The loop preserves the runtime session and uses `previous_response_id` to continue the model conversation. It stops after 20 responses if the task has not finished.

3192 

3193 

3194 

3195 

3196Use `run_computer_use` with your endpoint and task.

3197 

3198 

3199 

3200 

3201 

3202 

3203 

3204Use `run_computer_use` with your endpoint and task.

3205 

3206 

3207 

3208 

3209 

3210 

3211 

3212Use `runComputerUse` with your endpoint and task.

3213 

3214 

3215 

3216 

3217 

3218 

3219 

3220Use `runComputerUse` with your endpoint and task. The Go example also takes a context, SDK client, terminal scanner, and output writer; use its included adapter to preserve those inputs across calls.

3221 

3222 

3223 

2751 3224 

2752This adapter asks for approval before every generated script as a conservative demonstration. A production runtime must enforce the action-specific rules in [Handle user confirmation and consent](#handle-user-confirmation-and-consent). Removing the prompt does not supply those controls.3225This adapter asks for approval before every generated script as a conservative demonstration. A production runtime must enforce the action-specific rules in [Handle user confirmation and consent](#handle-user-confirmation-and-consent). Removing the prompt does not supply those controls.

2753 3226 

Details

27-H "Content-Type: application/json" \27-H "Content-Type: application/json" \

28-H "Authorization: Bearer $OPENAI_API_KEY" \28-H "Authorization: Bearer $OPENAI_API_KEY" \

29-d '{29-d '{

30 "model": "gpt-6-astra",30 "model": "gpt-6.2-astra",

31 "tools": [31 "tools": [

32 {32 {

33 "type": "mcp",33 "type": "mcp",


46const client = new OpenAI();46const client = new OpenAI();

47 47 

48const resp = await client.responses.create({48const resp = await client.responses.create({

49 model: "gpt-6-astra",49 model: "gpt-6.2-astra",

50 tools: [50 tools: [

51 {51 {

52 type: "mcp",52 type: "mcp",


69client = OpenAI()69client = OpenAI()

70 70 

71resp = client.responses.create(71resp = client.responses.create(

72 model="gpt-6-astra",72 model="gpt-6.2-astra",

73 tools=[73 tools=[

74 {74 {

75 "type": "mcp",75 "type": "mcp",


104 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}104 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}

105 105 

106 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{106 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

107 Model: "gpt-6-astra",107 Model: "gpt-6.2-astra",

108 Tools: []responses.ToolUnionParam{tool},108 Tools: []responses.ToolUnionParam{tool},

109 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},109 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},

110 })110 })


123 123 

124ResponseCreateParams params =124ResponseCreateParams params =

125 ResponseCreateParams.builder()125 ResponseCreateParams.builder()

126 .model("gpt-6-astra")126 .model("gpt-6.2-astra")

127 .input(127 .input(

128 "Search the OpenAI docs for Responses API streaming and return the relevant links.")128 "Search the OpenAI docs for Responses API streaming and return the relevant links.")

129 .addTool(129 .addTool(


149string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;149string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

150ResponsesClient client = new(key);150ResponsesClient client = new(key);

151 151 

152CreateResponseOptions options = new() { Model = "gpt-6-astra" };152CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

153options.Tools.Add(153options.Tools.Add(

154 ResponseTool.CreateMcpTool(154 ResponseTool.CreateMcpTool(

155 serverLabel: "openai_docs",155 serverLabel: "openai_docs",


170openai = OpenAI::Client.new170openai = OpenAI::Client.new

171 171 

172response = openai.responses.create(172response = openai.responses.create(

173 model: "gpt-6-astra",173 model: "gpt-6.2-astra",

174 tools: [174 tools: [

175 {175 {

176 type: "mcp",176 type: "mcp",


314-H "Content-Type: application/json" \314-H "Content-Type: application/json" \

315-H "Authorization: Bearer $OPENAI_API_KEY" \315-H "Authorization: Bearer $OPENAI_API_KEY" \

316-d '{316-d '{

317 "model": "gpt-6-astra",317 "model": "gpt-6.2-astra",

318 "tools": [318 "tools": [

319 {319 {

320 "type": "mcp",320 "type": "mcp",


334const client = new OpenAI();334const client = new OpenAI();

335 335 

336const resp = await client.responses.create({336const resp = await client.responses.create({

337 model: "gpt-6-astra",337 model: "gpt-6.2-astra",

338 tools: [338 tools: [

339 {339 {

340 type: "mcp",340 type: "mcp",


358client = OpenAI()358client = OpenAI()

359 359 

360resp = client.responses.create(360resp = client.responses.create(

361 model="gpt-6-astra",361 model="gpt-6.2-astra",

362 tools=[362 tools=[

363 {363 {

364 "type": "mcp",364 "type": "mcp",


395 tool.OfMcp.AllowedTools = responses.ToolMcpAllowedToolsUnionParam{OfMcpAllowedTools: []string{"search_openai_docs"}}395 tool.OfMcp.AllowedTools = responses.ToolMcpAllowedToolsUnionParam{OfMcpAllowedTools: []string{"search_openai_docs"}}

396 396 

397 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{397 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

398 Model: "gpt-6-astra",398 Model: "gpt-6.2-astra",

399 Tools: []responses.ToolUnionParam{tool},399 Tools: []responses.ToolUnionParam{tool},

400 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},400 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},

401 })401 })


415 415 

416ResponseCreateParams params =416ResponseCreateParams params =

417 ResponseCreateParams.builder()417 ResponseCreateParams.builder()

418 .model("gpt-6-astra")418 .model("gpt-6.2-astra")

419 .input(419 .input(

420 "Search the OpenAI docs for Responses API streaming and return the relevant links.")420 "Search the OpenAI docs for Responses API streaming and return the relevant links.")

421 .addTool(421 .addTool(


442string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;442string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

443ResponsesClient client = new(key);443ResponsesClient client = new(key);

444 444 

445CreateResponseOptions options = new() { Model = "gpt-6-astra" };445CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

446options.Tools.Add(446options.Tools.Add(

447 ResponseTool.CreateMcpTool(447 ResponseTool.CreateMcpTool(

448 serverLabel: "openai_docs",448 serverLabel: "openai_docs",


464client = OpenAI::Client.new464client = OpenAI::Client.new

465 465 

466response = client.responses.create(466response = client.responses.create(

467 model: "gpt-6-astra",467 model: "gpt-6.2-astra",

468 input: "Search the OpenAI docs for Responses API streaming and return the relevant links.",468 input: "Search the OpenAI docs for Responses API streaming and return the relevant links.",

469 tools: [469 tools: [

470 {470 {


526-H "Content-Type: application/json" \526-H "Content-Type: application/json" \

527-H "Authorization: Bearer $OPENAI_API_KEY" \527-H "Authorization: Bearer $OPENAI_API_KEY" \

528-d '{528-d '{

529 "model": "gpt-6-astra",529 "model": "gpt-6.2-astra",

530 "tools": [530 "tools": [

531 {531 {

532 "type": "mcp",532 "type": "mcp",


550const client = new OpenAI();550const client = new OpenAI();

551 551 

552const resp = await client.responses.create({552const resp = await client.responses.create({

553 model: "gpt-6-astra",553 model: "gpt-6.2-astra",

554 tools: [554 tools: [

555 {555 {

556 type: "mcp",556 type: "mcp",


580client = OpenAI()580client = OpenAI()

581 581 

582resp = client.responses.create(582resp = client.responses.create(

583 model="gpt-6-astra",583 model="gpt-6.2-astra",

584 tools=[584 tools=[

585 {585 {

586 "type": "mcp",586 "type": "mcp",


622 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("always")}622 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("always")}

623 623 

624 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{624 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

625 Model: "gpt-6-astra",625 Model: "gpt-6.2-astra",

626 PreviousResponseID: openai.String("resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa"),626 PreviousResponseID: openai.String("resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa"),

627 Tools: []responses.ToolUnionParam{tool},627 Tools: []responses.ToolUnionParam{tool},

628 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{628 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{


650 650 

651ResponseCreateParams params =651ResponseCreateParams params =

652 ResponseCreateParams.builder()652 ResponseCreateParams.builder()

653 .model("gpt-6-astra")653 .model("gpt-6.2-astra")

654 .input(654 .input(

655 ResponseCreateParams.Input.ofResponse(655 ResponseCreateParams.Input.ofResponse(

656 List.of(656 List.of(


685 685 

686CreateResponseOptions options = new()686CreateResponseOptions options = new()

687{687{

688 Model = "gpt-6-astra",688 Model = "gpt-6.2-astra",

689 ToolChoice = ResponseToolChoice.CreateRequiredChoice(),689 ToolChoice = ResponseToolChoice.CreateRequiredChoice(),

690 ParallelToolCallsEnabled = false690 ParallelToolCallsEnabled = false

691};691};


722 722 

723client = OpenAI::Client.new723client = OpenAI::Client.new

724response = client.responses.create(724response = client.responses.create(

725 model: "gpt-6-astra",725 model: "gpt-6.2-astra",

726 previous_response_id: "resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",726 previous_response_id: "resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",

727 input: [727 input: [

728 {728 {


757-H "Content-Type: application/json" \757-H "Content-Type: application/json" \

758-H "Authorization: Bearer $OPENAI_API_KEY" \758-H "Authorization: Bearer $OPENAI_API_KEY" \

759-d '{759-d '{

760 "model": "gpt-6-astra",760 "model": "gpt-6.2-astra",

761 "tools": [761 "tools": [

762 {762 {

763 "type": "mcp",763 "type": "mcp",


779const client = new OpenAI();779const client = new OpenAI();

780 780 

781const resp = await client.responses.create({781const resp = await client.responses.create({

782 model: "gpt-6-astra",782 model: "gpt-6.2-astra",

783 tools: [783 tools: [

784 {784 {

785 type: "mcp",785 type: "mcp",


805client = OpenAI()805client = OpenAI()

806 806 

807resp = client.responses.create(807resp = client.responses.create(

808 model="gpt-6-astra",808 model="gpt-6.2-astra",

809 tools=[809 tools=[

810 {810 {

811 "type": "mcp",811 "type": "mcp",


846 }846 }

847 847 

848 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{848 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

849 Model: "gpt-6-astra",849 Model: "gpt-6.2-astra",

850 Tools: []responses.ToolUnionParam{tool},850 Tools: []responses.ToolUnionParam{tool},

851 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?")},851 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?")},

852 })852 })


865 865 

866ResponseCreateParams params =866ResponseCreateParams params =

867 ResponseCreateParams.builder()867 ResponseCreateParams.builder()

868 .model("gpt-6-astra")868 .model("gpt-6.2-astra")

869 .input("What transport protocols does the 2025-03-26 version of the MCP spec support?")869 .input("What transport protocols does the 2025-03-26 version of the MCP spec support?")

870 .addTool(870 .addTool(

871 Tool.Mcp.builder()871 Tool.Mcp.builder()


896string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;896string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

897ResponsesClient client = new(key);897ResponsesClient client = new(key);

898 898 

899CreateResponseOptions options = new() { Model = "gpt-6-astra" };899CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

900options.Tools.Add(900options.Tools.Add(

901 ResponseTool.CreateMcpTool(901 ResponseTool.CreateMcpTool(

902 serverLabel: "deepwiki",902 serverLabel: "deepwiki",


927client = OpenAI::Client.new927client = OpenAI::Client.new

928 928 

929response = client.responses.create(929response = client.responses.create(

930 model: "gpt-6-astra",930 model: "gpt-6.2-astra",

931 input: "What transport protocols does the 2025-03-26 version of the MCP spec support?",931 input: "What transport protocols does the 2025-03-26 version of the MCP spec support?",

932 tools: [932 tools: [

933 {933 {


956-H "Content-Type: application/json" \956-H "Content-Type: application/json" \

957-H "Authorization: Bearer $OPENAI_API_KEY" \957-H "Authorization: Bearer $OPENAI_API_KEY" \

958-d '{958-d '{

959 "model": "gpt-6-astra",959 "model": "gpt-6.2-astra",

960 "input": "Create a payment link for $20",960 "input": "Create a payment link for $20",

961 "tools": [961 "tools": [

962 {962 {


974const client = new OpenAI();974const client = new OpenAI();

975 975 

976const resp = await client.responses.create({976const resp = await client.responses.create({

977 model: "gpt-6-astra",977 model: "gpt-6.2-astra",

978 input: "Create a payment link for $20",978 input: "Create a payment link for $20",

979 tools: [979 tools: [

980 {980 {


997authorization = os.environ["STRIPE_OAUTH_ACCESS_TOKEN"]997authorization = os.environ["STRIPE_OAUTH_ACCESS_TOKEN"]

998 998 

999resp = client.responses.create(999resp = client.responses.create(

1000 model="gpt-6-astra",1000 model="gpt-6.2-astra",

1001 input="Create a payment link for $20",1001 input="Create a payment link for $20",

1002 tools=[1002 tools=[

1003 {1003 {


1035 tool.OfMcp.Authorization = openai.String(authorization)1035 tool.OfMcp.Authorization = openai.String(authorization)

1036 1036 

1037 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1037 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1038 Model: "gpt-6-astra",1038 Model: "gpt-6.2-astra",

1039 Tools: []responses.ToolUnionParam{tool},1039 Tools: []responses.ToolUnionParam{tool},

1040 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Create a payment link for $20")},1040 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Create a payment link for $20")},

1041 })1041 })


1056 1056 

1057ResponseCreateParams params =1057ResponseCreateParams params =

1058 ResponseCreateParams.builder()1058 ResponseCreateParams.builder()

1059 .model("gpt-6-astra")1059 .model("gpt-6.2-astra")

1060 .input("Create a payment link for $20.")1060 .input("Create a payment link for $20.")

1061 .addTool(1061 .addTool(

1062 Tool.Mcp.builder()1062 Tool.Mcp.builder()


1082string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1082string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1083ResponsesClient client = new(key);1083ResponsesClient client = new(key);

1084 1084 

1085CreateResponseOptions options = new() { Model = "gpt-6-astra" };1085CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1086options.Tools.Add(1086options.Tools.Add(

1087 ResponseTool.CreateMcpTool(1087 ResponseTool.CreateMcpTool(

1088 serverLabel: "stripe",1088 serverLabel: "stripe",


1104 1104 

1105client = OpenAI::Client.new1105client = OpenAI::Client.new

1106response = client.responses.create(1106response = client.responses.create(

1107 model: "gpt-6-astra",1107 model: "gpt-6.2-astra",

1108 input: "Create a payment link for $20.",1108 input: "Create a payment link for $20.",

1109 tools: [1109 tools: [

1110 {1110 {

Details

31const openai = new OpenAI();31const openai = new OpenAI();

32 32 

33const response = await openai.responses.create({33const response = await openai.responses.create({

34 model: "gpt-6-astra",34 model: "gpt-6.2-astra",

35 input:35 input:

36 "Generate an image of gray tabby cat hugging an otter with an orange scarf",36 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

37 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],37 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


57client = OpenAI()57client = OpenAI()

58 58 

59response = client.responses.create(59response = client.responses.create(

60 model="gpt-6-astra",60 model="gpt-6.2-astra",

61 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",61 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

62 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],62 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

63)63)


90func main() {90func main() {

91 client := openai.NewClient()91 client := openai.NewClient()

92 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{92 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

93 Model: "gpt-6-astra",93 Model: "gpt-6.2-astra",

94 Input: responses.ResponseNewParamsInputUnion{94 Input: responses.ResponseNewParamsInputUnion{

95 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),95 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

96 },96 },


131 131 

132ResponseCreateParams params =132ResponseCreateParams params =

133 ResponseCreateParams.builder()133 ResponseCreateParams.builder()

134 .model("gpt-6-astra")134 .model("gpt-6.2-astra")

135 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")135 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

136 .addTool(Tool.ImageGeneration.builder().build())136 .addTool(Tool.ImageGeneration.builder().build())

137 .build();137 .build();


153string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;153string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

154ResponsesClient client = new(key);154ResponsesClient client = new(key);

155 155 

156CreateResponseOptions options = new() { Model = "gpt-6-astra" };156CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

157options.InputItems.Add(157options.InputItems.Add(

158 ResponseItem.CreateUserMessageItem(158 ResponseItem.CreateUserMessageItem(

159 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."159 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."


175 175 

176client = OpenAI::Client.new176client = OpenAI::Client.new

177response = client.responses.create(177response = client.responses.create(

178 model: "gpt-6-astra",178 model: "gpt-6.2-astra",

179 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",179 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

180 tools: [180 tools: [

181 {181 {


260const openai = new OpenAI();260const openai = new OpenAI();

261 261 

262const response = await openai.responses.create({262const response = await openai.responses.create({

263 model: "gpt-6-astra",263 model: "gpt-6.2-astra",

264 input:264 input:

265 "Generate an image of gray tabby cat hugging an otter with an orange scarf",265 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

266 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],266 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


280// Follow up280// Follow up

281 281 

282const response_fwup = await openai.responses.create({282const response_fwup = await openai.responses.create({

283 model: "gpt-6-astra",283 model: "gpt-6.2-astra",

284 previous_response_id: response.id,284 previous_response_id: response.id,

285 input: "Now make it look realistic",285 input: "Now make it look realistic",

286 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],286 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


308client = OpenAI()308client = OpenAI()

309 309 

310response = client.responses.create(310response = client.responses.create(

311 model="gpt-6-astra",311 model="gpt-6.2-astra",

312 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",312 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

313 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],313 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

314)314)


329# Follow up329# Follow up

330 330 

331response_fwup = client.responses.create(331response_fwup = client.responses.create(

332 model="gpt-6-astra",332 model="gpt-6.2-astra",

333 previous_response_id=response.id,333 previous_response_id=response.id,

334 input="Now make it look realistic",334 input="Now make it look realistic",

335 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],335 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],


362func main() {362func main() {

363 client := openai.NewClient()363 client := openai.NewClient()

364 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{364 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

365 Model: "gpt-6-astra",365 Model: "gpt-6.2-astra",

366 Input: responses.ResponseNewParamsInputUnion{366 Input: responses.ResponseNewParamsInputUnion{

367 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),367 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

368 },368 },


374 saveFirstGeneratedImage(first, "cat_and_otter.png")374 saveFirstGeneratedImage(first, "cat_and_otter.png")

375 375 

376 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{376 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

377 Model: "gpt-6-astra",377 Model: "gpt-6.2-astra",

378 PreviousResponseID: openai.String(first.ID),378 PreviousResponseID: openai.String(first.ID),

379 Input: responses.ResponseNewParamsInputUnion{379 Input: responses.ResponseNewParamsInputUnion{

380 OfString: openai.String("Now make it look realistic"),380 OfString: openai.String("Now make it look realistic"),


419 .responses()419 .responses()

420 .create(420 .create(

421 ResponseCreateParams.builder()421 ResponseCreateParams.builder()

422 .model("gpt-6-astra")422 .model("gpt-6.2-astra")

423 .input(423 .input(

424 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")424 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

425 .addTool(Tool.ImageGeneration.builder().build())425 .addTool(Tool.ImageGeneration.builder().build())


442 .responses()442 .responses()

443 .create(443 .create(

444 ResponseCreateParams.builder()444 ResponseCreateParams.builder()

445 .model("gpt-6-astra")445 .model("gpt-6.2-astra")

446 .input("Now make it look realistic.")446 .input("Now make it look realistic.")

447 .previousResponseId(first.id())447 .previousResponseId(first.id())

448 .addTool(Tool.ImageGeneration.builder().build())448 .addTool(Tool.ImageGeneration.builder().build())


469string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;469string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

470ResponsesClient client = new(key);470ResponsesClient client = new(key);

471 471 

472CreateResponseOptions options = new() { Model = "gpt-6-astra" };472CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

473options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));473options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

474options.InputItems.Add(474options.InputItems.Add(

475 ResponseItem.CreateUserMessageItem(475 ResponseItem.CreateUserMessageItem(


485 485 

486CreateResponseOptions followUp = new()486CreateResponseOptions followUp = new()

487{487{

488 Model = "gpt-6-astra",488 Model = "gpt-6.2-astra",

489 PreviousResponseId = first.Id,489 PreviousResponseId = first.Id,

490};490};

491followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));491followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));


507 507 

508client = OpenAI::Client.new508client = OpenAI::Client.new

509first = client.responses.create(509first = client.responses.create(

510 model: "gpt-6-astra",510 model: "gpt-6.2-astra",

511 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",511 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

512 tools: [512 tools: [

513 {513 {


528File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))528File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))

529 529 

530follow_up = client.responses.create(530follow_up = client.responses.create(

531 model: "gpt-6-astra",531 model: "gpt-6.2-astra",

532 input: "Now make it look realistic.",532 input: "Now make it look realistic.",

533 previous_response_id: first.id,533 previous_response_id: first.id,

534 tools: [534 tools: [


564const openai = new OpenAI();564const openai = new OpenAI();

565 565 

566const response = await openai.responses.create({566const response = await openai.responses.create({

567 model: "gpt-6-astra",567 model: "gpt-6.2-astra",

568 input:568 input:

569 "Generate an image of gray tabby cat hugging an otter with an orange scarf",569 "Generate an image of gray tabby cat hugging an otter with an orange scarf",

570 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],570 tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],


586// Follow up586// Follow up

587 587 

588const response_fwup = await openai.responses.create({588const response_fwup = await openai.responses.create({

589 model: "gpt-6-astra",589 model: "gpt-6.2-astra",

590 input: [590 input: [

591 {591 {

592 role: "user",592 role: "user",


620import base64620import base64

621 621 

622response = openai.responses.create(622response = openai.responses.create(

623 model="gpt-6-astra",623 model="gpt-6.2-astra",

624 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",624 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",

625 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],625 tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],

626)626)


641# Follow up641# Follow up

642 642 

643response_fwup = openai.responses.create(643response_fwup = openai.responses.create(

644 model="gpt-6-astra",644 model="gpt-6.2-astra",

645 input=[645 input=[

646 {646 {

647 "role": "user",647 "role": "user",


683func main() {683func main() {

684 client := openai.NewClient()684 client := openai.NewClient()

685 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{685 first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

686 Model: "gpt-6-astra",686 Model: "gpt-6.2-astra",

687 Input: responses.ResponseNewParamsInputUnion{687 Input: responses.ResponseNewParamsInputUnion{

688 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),688 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),

689 },689 },


701 ))701 ))

702 702 

703 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{703 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

704 Model: "gpt-6-astra",704 Model: "gpt-6.2-astra",

705 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},705 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},

706 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},706 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},

707 })707 })


761 .responses()761 .responses()

762 .create(762 .create(

763 ResponseCreateParams.builder()763 ResponseCreateParams.builder()

764 .model("gpt-6-astra")764 .model("gpt-6.2-astra")

765 .input(765 .input(

766 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")766 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

767 .addTool(Tool.ImageGeneration.builder().build())767 .addTool(Tool.ImageGeneration.builder().build())


784 .responses()784 .responses()

785 .create(785 .create(

786 ResponseCreateParams.builder()786 ResponseCreateParams.builder()

787 .model("gpt-6-astra")787 .model("gpt-6.2-astra")

788 .inputOfResponse(788 .inputOfResponse(

789 List.of(789 List.of(

790 ResponseInputItem.ofMessage(790 ResponseInputItem.ofMessage(


819string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;819string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

820ResponsesClient client = new(key);820ResponsesClient client = new(key);

821 821 

822CreateResponseOptions options = new() { Model = "gpt-6-astra" };822CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

823options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));823options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

824options.InputItems.Add(824options.InputItems.Add(

825 ResponseItem.CreateUserMessageItem(825 ResponseItem.CreateUserMessageItem(


833 .First();833 .First();

834await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());834await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());

835 835 

836CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };836CreateResponseOptions followUp = new() { Model = "gpt-6.2-astra" };

837followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));837followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));

838followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));838followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));

839followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));839followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));


854 854 

855client = OpenAI::Client.new855client = OpenAI::Client.new

856first = client.responses.create(856first = client.responses.create(

857 model: "gpt-6-astra",857 model: "gpt-6.2-astra",

858 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",858 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",

859 tools: [859 tools: [

860 {860 {


875File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))875File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))

876 876 

877follow_up = client.responses.create(877follow_up = client.responses.create(

878 model: "gpt-6-astra",878 model: "gpt-6.2-astra",

879 input: [879 input: [

880 {880 {

881 role: :user,881 role: :user,


932}932}

933 933 

934const stream = await openai.responses.create({934const stream = await openai.responses.create({

935 model: "gpt-6-astra",935 model: "gpt-6.2-astra",

936 input:936 input:

937 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",937 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",

938 stream: true,938 stream: true,


971 971 

972 972 

973stream = client.responses.create(973stream = client.responses.create(

974 model="gpt-6-astra",974 model="gpt-6.2-astra",

975 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",975 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",

976 stream=True,976 stream=True,

977 tools=[977 tools=[


1010func main() {1010func main() {

1011 client := openai.NewClient()1011 client := openai.NewClient()

1012 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{1012 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

1013 Model: "gpt-6-astra",1013 Model: "gpt-6.2-astra",

1014 Input: responses.ResponseNewParamsInputUnion{1014 Input: responses.ResponseNewParamsInputUnion{

1015 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),1015 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),

1016 },1016 },


1060 1060 

1061ResponseCreateParams params =1061ResponseCreateParams params =

1062 ResponseCreateParams.builder()1062 ResponseCreateParams.builder()

1063 .model("gpt-6-astra")1063 .model("gpt-6.2-astra")

1064 .input("Generate an image of a river made of white owl feathers.")1064 .input("Generate an image of a river made of white owl feathers.")

1065 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())1065 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())

1066 .build();1066 .build();


1100 1100 

1101client = OpenAI::Client.new1101client = OpenAI::Client.new

1102stream = client.responses.stream(1102stream = client.responses.stream(

1103 model: "gpt-6-astra",1103 model: "gpt-6.2-astra",

1104 input: "Generate an image of a river made of white owl feathers.",1104 input: "Generate an image of a river made of white owl feathers.",

1105 tools: [1105 tools: [

1106 {1106 {


1153- [`gpt-6-sol`](https://developers.openai.com/api/docs/models/gpt-6-sol)1153- [`gpt-6-sol`](https://developers.openai.com/api/docs/models/gpt-6-sol)

1154- [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol)1154- [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol)

1155- [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra)1155- [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra)

1156- [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra)

1157- [`gpt-6.2-sol`](https://developers.openai.com/api/docs/models/gpt-6.2-sol)

1156 1158 

1157For model availability and shutdown dates, see [Deprecations](https://developers.openai.com/api/docs/deprecations).1159For model availability and shutdown dates, see [Deprecations](https://developers.openai.com/api/docs/deprecations).

Details

299 299 

300while (true) {300while (true) {

301 const response = await client.responses.create({301 const response = await client.responses.create({

302 model: "gpt-6-astra",302 model: "gpt-6.2-astra",

303 store: false,303 store: false,

304 input,304 input,

305 tools,305 tools,


350from openai import OpenAI350from openai import OpenAI

351 351 

352client = OpenAI()352client = OpenAI()

353model = "gpt-6-astra"353model = "gpt-6.2-astra"

354 354 

355 355 

356def get_inventory(sku):356def get_inventory(sku):


504 504 

505 for {505 for {

506 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{506 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

507 Model: "gpt-6-astra",507 Model: "gpt-6.2-astra",

508 Store: openai.Bool(false),508 Store: openai.Bool(false),

509 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},509 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},

510 Tools: tools,510 Tools: tools,


675 .responses()675 .responses()

676 .create(676 .create(

677 ResponseCreateParams.builder()677 ResponseCreateParams.builder()

678 .model("gpt-6-astra")678 .model("gpt-6.2-astra")

679 .store(false)679 .store(false)

680 .inputOfResponse(input)680 .inputOfResponse(input)

681 .tools(tools)681 .tools(tools)


841 841 

842loop do842loop do

843 response = client.responses.create(843 response = client.responses.create(

844 model: "gpt-6-astra",844 model: "gpt-6.2-astra",

845 store: false,845 store: false,

846 input: input,846 input: input,

847 tools: tools847 tools: tools

Details

28 -H "Content-Type: application/json" \28 -H "Content-Type: application/json" \

29 -H "Authorization: Bearer $OPENAI_API_KEY" \29 -H "Authorization: Bearer $OPENAI_API_KEY" \

30 -d '{30 -d '{

31 "model": "gpt-6-astra",31 "model": "gpt-6.2-astra",

32 "tools": [32 "tools": [

33 { "type": "shell", "environment": { "type": "container_auto" } }33 { "type": "shell", "environment": { "type": "container_auto" } }

34 ],34 ],


51const client = new OpenAI();51const client = new OpenAI();

52 52 

53const response = await client.responses.create({53const response = await client.responses.create({

54 model: "gpt-6-astra",54 model: "gpt-6.2-astra",

55 tools: [{ type: "shell", environment: { type: "container_auto" } }],55 tools: [{ type: "shell", environment: { type: "container_auto" } }],

56 input: [56 input: [

57 {57 {


77client = OpenAI()77client = OpenAI()

78 78 

79response = client.responses.create(79response = client.responses.create(

80 model="gpt-6-astra",80 model="gpt-6.2-astra",

81 tools=[{"type": "shell", "environment": {"type": "container_auto"}}],81 tools=[{"type": "shell", "environment": {"type": "container_auto"}}],

82 input=[82 input=[

83 {83 {


114 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{}},114 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{}},

115 }}115 }}

116 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{116 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

117 Model: "gpt-6-astra",117 Model: "gpt-6.2-astra",

118 Tools: []responses.ToolUnionParam{tool},118 Tools: []responses.ToolUnionParam{tool},

119 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Execute: ls -lah /mnt/data && python --version && node --version")},119 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Execute: ls -lah /mnt/data && python --version && node --version")},

120 })120 })


134 134 

135ResponseCreateParams params =135ResponseCreateParams params =

136 ResponseCreateParams.builder()136 ResponseCreateParams.builder()

137 .model("gpt-6-astra")137 .model("gpt-6.2-astra")

138 .input("Run ls -lah /mnt/data, then show the Python and Node.js versions.")138 .input("Run ls -lah /mnt/data, then show the Python and Node.js versions.")

139 .addTool(139 .addTool(

140 FunctionShellTool.builder().environment(ContainerAuto.builder().build()).build())140 FunctionShellTool.builder().environment(ContainerAuto.builder().build()).build())


152 152 

153client = OpenAI::Client.new153client = OpenAI::Client.new

154response = client.responses.create(154response = client.responses.create(

155 model: "gpt-6-astra",155 model: "gpt-6.2-astra",

156 input: "Run ls -lah /mnt/data, then show the Python and Node.js versions.",156 input: "Run ls -lah /mnt/data, then show the Python and Node.js versions.",

157 tools: [157 tools: [

158 {158 {


302 -H "Content-Type: application/json" \302 -H "Content-Type: application/json" \

303 -H "Authorization: Bearer $OPENAI_API_KEY" \303 -H "Authorization: Bearer $OPENAI_API_KEY" \

304 -d '{304 -d '{

305 "model": "gpt-6-astra",305 "model": "gpt-6.2-astra",

306 "tools": [306 "tools": [

307 {307 {

308 "type": "shell",308 "type": "shell",


322const client = new OpenAI();322const client = new OpenAI();

323 323 

324const response = await client.responses.create({324const response = await client.responses.create({

325 model: "gpt-6-astra",325 model: "gpt-6.2-astra",

326 tools: [326 tools: [

327 {327 {

328 type: "shell",328 type: "shell",


340 340 

341```python341```python

342response = client.responses.create(342response = client.responses.create(

343 model="gpt-6-astra",343 model="gpt-6.2-astra",

344 tools=[344 tools=[

345 {345 {

346 "type": "shell",346 "type": "shell",


373 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"}},373 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"}},

374 }}374 }}

375 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{375 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

376 Model: "gpt-6-astra",376 Model: "gpt-6.2-astra",

377 Tools: []responses.ToolUnionParam{tool},377 Tools: []responses.ToolUnionParam{tool},

378 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List files in the container and show disk usage.")},378 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List files in the container and show disk usage.")},

379 })379 })


394 394 

395ResponseCreateParams params =395ResponseCreateParams params =

396 ResponseCreateParams.builder()396 ResponseCreateParams.builder()

397 .model("gpt-6-astra")397 .model("gpt-6.2-astra")

398 .input("List files in the container and show disk usage.")398 .input("List files in the container and show disk usage.")

399 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())399 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())

400 .build();400 .build();


411 411 

412client = OpenAI::Client.new412client = OpenAI::Client.new

413response = client.responses.create(413response = client.responses.create(

414 model: "gpt-6-astra",414 model: "gpt-6.2-astra",

415 input: "List files in the container and show disk usage.",415 input: "List files in the container and show disk usage.",

416 tools: [416 tools: [

417 {417 {


588 -H "Authorization: Bearer $OPENAI_API_KEY" \588 -H "Authorization: Bearer $OPENAI_API_KEY" \

589 -H "Content-Type: application/json" \589 -H "Content-Type: application/json" \

590 -d '{590 -d '{

591 "model": "gpt-6-astra",591 "model": "gpt-6.2-astra",

592 "tool_choice": "required",592 "tool_choice": "required",

593 "tools": [593 "tools": [

594 {594 {


617const client = new OpenAI();617const client = new OpenAI();

618 618 

619const response = await client.responses.create({619const response = await client.responses.create({

620 model: "gpt-6-astra",620 model: "gpt-6.2-astra",

621 tool_choice: "required",621 tool_choice: "required",

622 tools: [622 tools: [

623 {623 {


649client = OpenAI()649client = OpenAI()

650 650 

651response = client.responses.create(651response = client.responses.create(

652 model="gpt-6-astra",652 model="gpt-6.2-astra",

653 tool_choice="required",653 tool_choice="required",

654 tools=[654 tools=[

655 {655 {


699 }},699 }},

700 }}700 }}

701 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{701 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

702 Model: "gpt-6-astra",702 Model: "gpt-6.2-astra",

703 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},703 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},

704 Tools: []responses.ToolUnionParam{tool},704 Tools: []responses.ToolUnionParam{tool},

705 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md.")},705 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md.")},


722 722 

723ResponseCreateParams params =723ResponseCreateParams params =

724 ResponseCreateParams.builder()724 ResponseCreateParams.builder()

725 .model("gpt-6-astra")725 .model("gpt-6.2-astra")

726 .input("Fetch release pages and write /mnt/data/release_digest.md.")726 .input("Fetch release pages and write /mnt/data/release_digest.md.")

727 .toolChoice(ToolChoiceOptions.REQUIRED)727 .toolChoice(ToolChoiceOptions.REQUIRED)

728 .addTool(728 .addTool(


751 751 

752client = OpenAI::Client.new752client = OpenAI::Client.new

753response = client.responses.create(753response = client.responses.create(

754 model: "gpt-6-astra",754 model: "gpt-6.2-astra",

755 input: "Fetch release pages and write /mnt/data/release_digest.md.",755 input: "Fetch release pages and write /mnt/data/release_digest.md.",

756 tool_choice: :required,756 tool_choice: :required,

757 tools: [757 tools: [


830 -H "Content-Type: application/json" \830 -H "Content-Type: application/json" \

831 -H "Authorization: Bearer $OPENAI_API_KEY" \831 -H "Authorization: Bearer $OPENAI_API_KEY" \

832 -d '{832 -d '{

833 "model": "gpt-6-astra",833 "model": "gpt-6.2-astra",

834 "tools": [834 "tools": [

835 {835 {

836 "type": "shell",836 "type": "shell",


887});887});

888 888 

889const response = await client.responses.create({889const response = await client.responses.create({

890 model: "gpt-6-astra",890 model: "gpt-6.2-astra",

891 tools: [891 tools: [

892 {892 {

893 type: "shell",893 type: "shell",


947)947)

948 948 

949response = client.responses.create(949response = client.responses.create(

950 model="gpt-6-astra",950 model="gpt-6.2-astra",

951 tools=[951 tools=[

952 {952 {

953 "type": "shell",953 "type": "shell",


1012 log.Fatal(err)1012 log.Fatal(err)

1013}1013}

1014response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1014response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1015 Model: "gpt-6-astra",1015 Model: "gpt-6.2-astra",

1016 Tools: []responses.ToolUnionParam{1016 Tools: []responses.ToolUnionParam{

1017 {1017 {

1018 OfShell: &responses.FunctionShellToolParam{1018 OfShell: &responses.FunctionShellToolParam{


1097 .responses()1097 .responses()

1098 .create(1098 .create(

1099 ResponseCreateParams.builder()1099 ResponseCreateParams.builder()

1100 .model("gpt-6-astra")1100 .model("gpt-6.2-astra")

1101 .addTool(1101 .addTool(

1102 FunctionShellTool.builder()1102 FunctionShellTool.builder()

1103 .containerReferenceEnvironment(container.id())1103 .containerReferenceEnvironment(container.id())


1149 ]1149 ]

1150)1150)

1151response = client.responses.create(1151response = client.responses.create(

1152 model: "gpt-6-astra",1152 model: "gpt-6.2-astra",

1153 tools: [1153 tools: [

1154 {1154 {

1155 type: :shell,1155 type: :shell,


1279 -H "Authorization: Bearer $OPENAI_API_KEY" \1279 -H "Authorization: Bearer $OPENAI_API_KEY" \

1280 -H "Content-Type: application/json" \1280 -H "Content-Type: application/json" \

1281 -d '{1281 -d '{

1282 "model": "gpt-6-astra",1282 "model": "gpt-6.2-astra",

1283 "input": [1283 "input": [

1284 {1284 {

1285 "role": "user",1285 "role": "user",


1315const client = new OpenAI();1315const client = new OpenAI();

1316 1316 

1317const response = await client.responses.create({1317const response = await client.responses.create({

1318 model: "gpt-6-astra",1318 model: "gpt-6.2-astra",

1319 input: [1319 input: [

1320 {1320 {

1321 role: "user",1321 role: "user",


1354client = OpenAI()1354client = OpenAI()

1355 1355 

1356response = client.responses.create(1356response = client.responses.create(

1357 model="gpt-6-astra",1357 model="gpt-6.2-astra",

1358 input=[1358 input=[

1359 {1359 {

1360 "role": "user",1360 "role": "user",


1412 }},1412 }},

1413 }}1413 }}

1414 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1414 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1415 Model: "gpt-6-astra",1415 Model: "gpt-6.2-astra",

1416 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},1416 ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},

1417 Tools: []responses.ToolUnionParam{tool},1417 Tools: []responses.ToolUnionParam{tool},

1418 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response.")},1418 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response.")},


1436 1436 

1437ResponseCreateParams params =1437ResponseCreateParams params =

1438 ResponseCreateParams.builder()1438 ResponseCreateParams.builder()

1439 .model("gpt-6-astra")1439 .model("gpt-6.2-astra")

1440 .input(1440 .input(

1441 "Run exactly this one shell command, without additional commands:\n"1441 "Run exactly this one shell command, without additional commands:\n"

1442 + "curl -q -sS -o /dev/null -w '%{http_code}' "1442 + "curl -q -sS -o /dev/null -w '%{http_code}' "


1474 1474 

1475client = OpenAI::Client.new1475client = OpenAI::Client.new

1476response = client.responses.create(1476response = client.responses.create(

1477 model: "gpt-6-astra",1477 model: "gpt-6.2-astra",

1478 input: "Use curl to call https://httpbin.org/headers with an " \1478 input: "Use curl to call https://httpbin.org/headers with an " \

1479 '"Authorization: Bearer $API_KEY" header.',1479 '"Authorization: Bearer $API_KEY" header.',

1480 tool_choice: :required,1480 tool_choice: :required,


1514 -H "Content-Type: application/json" \1514 -H "Content-Type: application/json" \

1515 -H "Authorization: Bearer $OPENAI_API_KEY" \1515 -H "Authorization: Bearer $OPENAI_API_KEY" \

1516 -d '{1516 -d '{

1517 "model": "gpt-6-astra",1517 "model": "gpt-6.2-astra",

1518 "previous_response_id": "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",1518 "previous_response_id": "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",

1519 "tools": [1519 "tools": [

1520 {1520 {


1535const client = new OpenAI();1535const client = new OpenAI();

1536 1536 

1537const response = await client.responses.create({1537const response = await client.responses.create({

1538 model: "gpt-6-astra",1538 model: "gpt-6.2-astra",

1539 previous_response_id:1539 previous_response_id:

1540 "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",1540 "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",

1541 tools: [1541 tools: [


1559client = OpenAI()1559client = OpenAI()

1560 1560 

1561response = client.responses.create(1561response = client.responses.create(

1562 model="gpt-6-astra",1562 model="gpt-6.2-astra",

1563 previous_response_id="resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",1563 previous_response_id="resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",

1564 tools=[1564 tools=[

1565 {1565 {


1593 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041"}},1593 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041"}},

1594 }}1594 }}

1595 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1595 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1596 Model: "gpt-6-astra",1596 Model: "gpt-6.2-astra",

1597 PreviousResponseID: openai.String("resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47"),1597 PreviousResponseID: openai.String("resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47"),

1598 Tools: []responses.ToolUnionParam{tool},1598 Tools: []responses.ToolUnionParam{tool},

1599 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Read /mnt/data/top5.csv and report the top candidate.")},1599 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Read /mnt/data/top5.csv and report the top candidate.")},


1617 1617 

1618ResponseCreateParams params =1618ResponseCreateParams params =

1619 ResponseCreateParams.builder()1619 ResponseCreateParams.builder()

1620 .model("gpt-6-astra")1620 .model("gpt-6.2-astra")

1621 .input("Read /mnt/data/top5.csv and report the top candidate.")1621 .input("Read /mnt/data/top5.csv and report the top candidate.")

1622 .previousResponseId(responseId)1622 .previousResponseId(responseId)

1623 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())1623 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())


1635 1635 

1636client = OpenAI::Client.new1636client = OpenAI::Client.new

1637response = client.responses.create(1637response = client.responses.create(

1638 model: "gpt-6-astra",1638 model: "gpt-6.2-astra",

1639 input: "Read /mnt/data/top5.csv and report the top candidate.",1639 input: "Read /mnt/data/top5.csv and report the top candidate.",

1640 previous_response_id: "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",1640 previous_response_id: "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",

1641 tools: [1641 tools: [


1689 -H "Content-Type: application/json" \1689 -H "Content-Type: application/json" \

1690 -H "Authorization: Bearer $OPENAI_API_KEY" \1690 -H "Authorization: Bearer $OPENAI_API_KEY" \

1691 -d '{1691 -d '{

1692 "model": "gpt-6-astra",1692 "model": "gpt-6.2-astra",

1693 "instructions": "The local bash shell environment is on Mac.",1693 "instructions": "The local bash shell environment is on Mac.",

1694 "input": "find me the largest pdf file in ~/Documents",1694 "input": "find me the largest pdf file in ~/Documents",

1695 "tools": [{ "type": "shell", "environment": { "type": "local" } }]1695 "tools": [{ "type": "shell", "environment": { "type": "local" } }]


1702const client = new OpenAI();1702const client = new OpenAI();

1703 1703 

1704const response = await client.responses.create({1704const response = await client.responses.create({

1705 model: "gpt-6-astra",1705 model: "gpt-6.2-astra",

1706 instructions: "The local bash shell environment is on Mac.",1706 instructions: "The local bash shell environment is on Mac.",

1707 input: "find me the largest pdf file in ~/Documents",1707 input: "find me the largest pdf file in ~/Documents",

1708 tools: [{ type: "shell", environment: { type: "local" } }],1708 tools: [{ type: "shell", environment: { type: "local" } }],


1717client = OpenAI()1717client = OpenAI()

1718 1718 

1719response = client.responses.create(1719response = client.responses.create(

1720 model="gpt-6-astra",1720 model="gpt-6.2-astra",

1721 instructions="The local bash shell environment is on Mac.",1721 instructions="The local bash shell environment is on Mac.",

1722 input="find me the largest pdf file in ~/Documents",1722 input="find me the largest pdf file in ~/Documents",

1723 tools=[{"type": "shell", "environment": {"type": "local"}}],1723 tools=[{"type": "shell", "environment": {"type": "local"}}],


1743 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfLocal: &responses.LocalEnvironmentParam{}},1743 Environment: responses.FunctionShellToolEnvironmentUnionParam{OfLocal: &responses.LocalEnvironmentParam{}},

1744 }}1744 }}

1745 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1745 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1746 Model: "gpt-6-astra",1746 Model: "gpt-6.2-astra",

1747 Instructions: openai.String("The local bash shell environment is on Mac."),1747 Instructions: openai.String("The local bash shell environment is on Mac."),

1748 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("find me the largest pdf file in ~/Documents")},1748 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("find me the largest pdf file in ~/Documents")},

1749 Tools: []responses.ToolUnionParam{tool},1749 Tools: []responses.ToolUnionParam{tool},


1765 1765 

1766ResponseCreateParams params =1766ResponseCreateParams params =

1767 ResponseCreateParams.builder()1767 ResponseCreateParams.builder()

1768 .model("gpt-6-astra")1768 .model("gpt-6.2-astra")

1769 .input("Find the largest PDF in ~/Documents.")1769 .input("Find the largest PDF in ~/Documents.")

1770 .instructions("The local shell environment is macOS.")1770 .instructions("The local shell environment is macOS.")

1771 .putAdditionalBodyProperty(1771 .putAdditionalBodyProperty(


1785 1785 

1786client = OpenAI::Client.new1786client = OpenAI::Client.new

1787response = client.responses.create(1787response = client.responses.create(

1788 model: "gpt-6-astra",1788 model: "gpt-6.2-astra",

1789 instructions: "The local shell environment is macOS.",1789 instructions: "The local shell environment is macOS.",

1790 input: "Find the largest PDF in ~/Documents.",1790 input: "Find the largest PDF in ~/Documents.",

1791 tools: [1791 tools: [


2110 2110 

2111const agent = new Agent({2111const agent = new Agent({

2112 name: "Shell Assistant",2112 name: "Shell Assistant",

2113 model: "gpt-6-astra",2113 model: "gpt-6.2-astra",

2114 instructions:2114 instructions:

2115 "You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",2115 "You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",

2116 tools: [2116 tools: [


2166 2166 

2167agent = Agent(2167agent = Agent(

2168 name="Shell Assistant",2168 name="Shell Assistant",

2169 model="gpt-6-astra",2169 model="gpt-6.2-astra",

2170 instructions="You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",2170 instructions="You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",

2171 tools=[shell_tool],2171 tools=[shell_tool],

2172)2172)

Details

91 -H "Content-Type: application/json" \91 -H "Content-Type: application/json" \

92 -H "Authorization: Bearer $OPENAI_API_KEY" \92 -H "Authorization: Bearer $OPENAI_API_KEY" \

93 -d '{93 -d '{

94 "model": "gpt-6-astra",94 "model": "gpt-6.2-astra",

95 "tools": [95 "tools": [

96 {96 {

97 "type": "shell",97 "type": "shell",


114const client = new OpenAI();114const client = new OpenAI();

115 115 

116const response = await client.responses.create({116const response = await client.responses.create({

117 model: "gpt-6-astra",117 model: "gpt-6.2-astra",

118 tools: [118 tools: [

119 {119 {

120 type: "shell",120 type: "shell",


136 136 

137```python137```python

138response = client.responses.create(138response = client.responses.create(

139 model="gpt-6-astra",139 model="gpt-6.2-astra",

140 tools=[140 tools=[

141 {141 {

142 "type": "shell",142 "type": "shell",


181 }},181 }},

182 }}182 }}

183 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{183 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

184 Model: "gpt-6-astra",184 Model: "gpt-6.2-astra",

185 Tools: []responses.ToolUnionParam{tool},185 Tools: []responses.ToolUnionParam{tool},

186 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the skills to add 144 and 377, then compute triangle area with base 9 height 13.")},186 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the skills to add 144 and 377, then compute triangle area with base 9 height 13.")},

187 })187 })


204 204 

205ResponseCreateParams params =205ResponseCreateParams params =

206 ResponseCreateParams.builder()206 ResponseCreateParams.builder()

207 .model("gpt-6-astra")207 .model("gpt-6.2-astra")

208 .input(208 .input(

209 "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.")209 "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.")

210 .putAdditionalBodyProperty(210 .putAdditionalBodyProperty(


239 239 

240client = OpenAI::Client.new240client = OpenAI::Client.new

241response = client.responses.create(241response = client.responses.create(

242 model: "gpt-6-astra",242 model: "gpt-6.2-astra",

243 input: "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.",243 input: "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.",

244 tools: [244 tools: [

245 {245 {


309 -H "Content-Type: application/json" \309 -H "Content-Type: application/json" \

310 -H "Authorization: Bearer $OPENAI_API_KEY" \310 -H "Authorization: Bearer $OPENAI_API_KEY" \

311 -d '{311 -d '{

312 "model": "gpt-6-astra",312 "model": "gpt-6.2-astra",

313 "tools": [313 "tools": [

314 {314 {

315 "type": "shell",315 "type": "shell",


346 const client = new OpenAI();346 const client = new OpenAI();

347 /** @type {OpenAI.Responses.ResponseCreateParamsNonStreaming} */347 /** @type {OpenAI.Responses.ResponseCreateParamsNonStreaming} */

348 const params: OpenAI.Responses.ResponseCreateParamsNonStreaming = {348 const params: OpenAI.Responses.ResponseCreateParamsNonStreaming = {

349 model: "gpt-6-astra",349 model: "gpt-6.2-astra",

350 tools: [350 tools: [

351 {351 {

352 type: "shell",352 type: "shell",


390 390 

391```python391```python

392response = client.responses.create(392response = client.responses.create(

393 model="gpt-6-astra",393 model="gpt-6.2-astra",

394 tools=[394 tools=[

395 {395 {

396 "type": "shell",396 "type": "shell",


428 },428 },

429}}429}}

430params := responses.ResponseNewParams{430params := responses.ResponseNewParams{

431 Model: "gpt-6-astra",431 Model: "gpt-6.2-astra",

432 Tools: []responses.ToolUnionParam{tool},432 Tools: []responses.ToolUnionParam{tool},

433 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(433 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(

434 "Use the csv-insights skill and run locally to summarize /workspace/reports.csv. Read the skill instructions, write /workspace/report.md, and include the total in your final answer.")},434 "Use the csv-insights skill and run locally to summarize /workspace/reports.csv. Read the skill instructions, write /workspace/report.md, and include the total in your final answer.")},


483 483 

484ResponseCreateParams params =484ResponseCreateParams params =

485 ResponseCreateParams.builder()485 ResponseCreateParams.builder()

486 .model("gpt-6-astra")486 .model("gpt-6.2-astra")

487 .input("Use the csv-insights skill to summarize today's CSV reports.")487 .input("Use the csv-insights skill to summarize today's CSV reports.")

488 .putAdditionalBodyProperty(488 .putAdditionalBodyProperty(

489 "tools",489 "tools",


526 sandbox.prepare526 sandbox.prepare

527 client = OpenAI::Client.new(max_retries: 0)527 client = OpenAI::Client.new(max_retries: 0)

528 params = {528 params = {

529 model: "gpt-6-astra",529 model: "gpt-6.2-astra",

530 input: "Use the csv-insights skill and run locally to summarize /workspace/reports.csv. Read the skill instructions, write /workspace/report.md, and include the total in your final answer.",530 input: "Use the csv-insights skill and run locally to summarize /workspace/reports.csv. Read the skill instructions, write /workspace/report.md, and include the total in your final answer.",

531 tools: [531 tools: [

532 {532 {

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Ultrafast mode is the fastest service tier in the OpenAI API. It is broadly available for GPT-6 Astra and GPT-6.1 Sol. Use it when speed justifies the higher cost.5Ultrafast mode is the fastest service tier in the OpenAI API. It supports GPT-6.2 Astra, GPT-6.2 Sol, GPT-6 Astra, and GPT-6.1 Sol. Use it when speed justifies the higher cost.

6 

7To use Ultrafast in ChatGPT Work or Codex, [choose a speed in the composer](https://learn.chatgpt.com/docs/agent-configuration/speed#choose-a-speed-in-the-composer).

6 8 

7We strongly recommend [WebSockets](https://developers.openai.com/api/docs/guides/websocket-mode), especially for agentic applications that make many tool calls in quick succession. Without a persistent connection, network overhead can reduce the latency gains.9We strongly recommend [WebSockets](https://developers.openai.com/api/docs/guides/websocket-mode), especially for agentic applications that make many tool calls in quick succession. Without a persistent connection, network overhead can reduce the latency gains.

8 10 


13 15 

14## Configure your request16## Configure your request

15 17 

16Set `model` to `gpt-6-astra` or `gpt-6.1-sol` and `service_tier` to `ultrafast` in each `response.create` event.18Set `model` to `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6-astra`, or `gpt-6.1-sol`. Set `service_tier` to `ultrafast` in each `response.create` event.

17 19 

18Install your language's SDK and WebSocket dependencies as described in [Connect and create responses](https://developers.openai.com/api/docs/guides/websocket-mode#connect-and-create-responses). Set `OPENAI_API_KEY` in your environment before running the example.20Install your language's SDK and WebSocket dependencies as described in [Connect and create responses](https://developers.openai.com/api/docs/guides/websocket-mode#connect-and-create-responses). Set `OPENAI_API_KEY` in your environment before running the example.

19 21 


372 374 

373## Availability375## Availability

374 376 

377Check your organization’s [rate limits](https://platform.openai.com/settings/organization/limits) for GPT-6.2 Astra and GPT-6.2 Sol.

378 

375GPT-6.1 Sol has the following default Ultrafast token rate limits:379GPT-6.1 Sol has the following default Ultrafast token rate limits:

376 380 

377| API usage tier | Tokens per minute (TPM) |381| API usage tier | Tokens per minute (TPM) |


390 394 

391See the [Ultrafast pricing table](https://developers.openai.com/api/docs/pricing?latest-pricing=ultrafast) for input, cached input, cache write, and output prices.395See the [Ultrafast pricing table](https://developers.openai.com/api/docs/pricing?latest-pricing=ultrafast) for input, cached input, cache write, and output prices.

392 396 

397Ultrafast data residency for GPT-6.2 Astra and GPT-6.2 Sol is limited to the US. See the [Data residency guide](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency) for other service tiers.

398 

393Ultrafast mode for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only.399Ultrafast mode for GPT-6.1 Sol supports US and EU data residency and global processing. GPT-6 Astra Ultrafast supports US data residency and global processing only.

Details

64agent = Agent(64agent = Agent(

65 name="Assistant",65 name="Assistant",

66 instructions="You are a helpful voice assistant.",66 instructions="You are a helpful voice assistant.",

67 model="gpt-6-astra",67 model="gpt-6.2-astra",

68 tools=[get_weather],68 tools=[get_weather],

69)69)

70 70 

Details

1421 1421 

1422#### Example1422#### Example

1423 1423 

1424Add sample phrases to a tool description

1425 

1424```python1426```python

1425tools = [1427tools = [

1426 {1428 {


1464]1466]

1465```1467```

1466 1468 

1469```ruby

1470tools = [

1471 {

1472 "type" => "function",

1473 "name" => "lookup_account",

1474 "description" => "Retrieve a customer account using either an email or phone number to e" \

1475 "nable verification and account-specific actions.\n\nPreamble sample phra" \

1476 "ses:\n- For security, I’ll pull up your account using the email on file" \

1477 ".\n- Let me look up your account by {email} now.\n- I’m fetching the acc" \

1478 "ount linked to {phone} to verify access.\n- One moment—I’m opening your" \

1479 " account details.",

1480 "parameters" => {

1481 "type" => "object",

1482 "properties" => {

1483 "email" => {

1484 "type" => "string"

1485 },

1486 "phone" => {

1487 "type" => "string"

1488 }

1489 },

1490 "additionalProperties" => false

1491 }

1492 },

1493 {

1494 "type" => "function",

1495 "name" => "check_outage",

1496 "description" => "Check for network outages affecting a given service address and return" \

1497 " status and ETA if applicable.\n\nPreamble sample phrases:\n- I’ll check " \

1498 "for any outages at {service_address} right now.\n- Let me look up netwo" \

1499 "rk status for your area.\n- I’m checking whether there’s an active outa" \

1500 "ge impacting your address.\n- One sec—verifying service status and any " \

1501 "posted ETA.",

1502 "parameters" => {

1503 "type" => "object",

1504 "properties" => {

1505 "service_address" => {

1506 "type" => "string"

1507 }

1508 },

1509 "required" => ["service_address"],

1510 "additionalProperties" => false

1511 }

1512 }

1513]

1514```

1515 

1467 1516 

1468### Tool Calls Without Confirmation1517### Tool Calls Without Confirmation

1469 1518 


1950 1999 

1951#### Example2000#### Example

1952 2001 

2002Update the conversation state

2003 

1953```python2004```python

1954from typing import Literal2005from typing import Literal

1955 2006 


2047 }2098 }

2048```2099```

2049 2100 

2101```ruby

2102TRANSITIONS = {

2103 "verify" => ["resolve"],

2104 "resolve" => []

2105}.freeze

2106 

2107TOOLS_BY_STATE = {

2108 "verify" => [

2109 {

2110 "type" => "function",

2111 "name" => "lookup_account",

2112 "description" => "Fetch account by email or phone.",

2113 "parameters" => {

2114 "type" => "object",

2115 "properties" => {

2116 "email_or_phone" => {

2117 "type" => "string"

2118 }

2119 },

2120 "required" => ["email_or_phone"]

2121 }

2122 }

2123 ],

2124 "resolve" => [

2125 {

2126 "type" => "function",

2127 "name" => "schedule_technician",

2128 "description" => "Book a technician visit.",

2129 "parameters" => {

2130 "type" => "object",

2131 "properties" => {

2132 "account_id" => {

2133 "type" => "string"

2134 },

2135 "window" => {

2136 "type" => "string",

2137 "enum" => ["10-12 ET", "14-16 ET"]

2138 }

2139 },

2140 "required" => ["account_id", "window"]

2141 }

2142 }

2143 ]

2144}.freeze

2145 

2146INSTRUCTIONS_BY_STATE = {

2147 "verify" => "# Role & Objective\nVerify identity to access the account.\n\n# Conversat" \

2148 "ion (Verify)\n- Ask for the email or phone on the account.\n- Read back " \

2149 "digits one-by-one (e.g., '4-1-5… Is that correct?').\nExit when: Accoun" \

2150 "t ID is returned.\nWhen exit is satisfied: call set_conversation_state(" \

2151 "next_state=\"resolve\").",

2152 "resolve" => "# Role & Objective\nApply a fix by booking a technician.\n\n# Conversatio" \

2153 "n (Resolve)\n- Offer two windows: '10–12 ET' or '2–4 ET'.\n- Book the ch" \

2154 "osen window.\nExit when: Appointment is confirmed.\nWhen exit is satisfi" \

2155 "ed: end the call politely."

2156}.freeze

2157 

2158def build_state_change_tool(current)

2159 allowed = TRANSITIONS.fetch(current)

2160 readable = allowed.empty? ? "no further states (terminal)" : allowed.join(", ")

2161 {

2162 "type" => "function",

2163 "name" => "set_conversation_state",

2164 "description" => "Switch the conversation phase. Current: '#{current}'. " \

2165 "You may switch only to: #{readable}. Call this AFTER exit criteria are satisfied.",

2166 "parameters" => {

2167 "type" => "object",

2168 "properties" => {

2169 "next_state" => {

2170 "type" => "string",

2171 "enum" => allowed

2172 }

2173 },

2174 "required" => ["next_state"]

2175 }

2176 }

2177end

2178 

2179def build_session_update(state)

2180 {

2181 "type" => "session.update",

2182 "session" => {

2183 "type" => "realtime",

2184 "instructions" => INSTRUCTIONS_BY_STATE.fetch(state),

2185 "tools" => TOOLS_BY_STATE.fetch(state) + [build_state_change_tool(state)]

2186 }

2187 }

2188end

2189```

2190 

2050 2191 

2051## Safety & Escalation2192## Safety & Escalation

2052 2193 

Details

337}337}

338```338```

339 339 

340```ruby

341require "openai"

342 

343# Use the call ID from the WebRTC creation Location header or SIP webhook.

344call_id = ENV.fetch("OPENAI_CALL_ID")

345client = OpenAI::Client.new

346client.realtime.connect_to_call(call_id: call_id) do |connection|

347 connection.session.update(type: :realtime, instructions: "Be extra nice today!")

348 updated = connection.find do |event|

349 raise event.error.message if event.is_a?(OpenAI::Realtime::RealtimeErrorEvent)

350 

351 if event.is_a?(OpenAI::Realtime::SessionUpdatedEvent)

352 session = event.session

353 raise "Session update was not applied" unless session.is_a?(OpenAI::Realtime::RealtimeSessionCreateRequest) && session.instructions == "Be extra nice today!"

354 

355 puts "session.updated"

356 true

357 else

358 false

359 end

360 end

361 raise "Connection closed before the session update" unless updated

362end

363```

364 

340 365 

341In this way, you are able to add tools, monitor sessions, and carry out business logic on the server instead of needing to configure those actions on the client.366In this way, you are able to add tools, monitor sessions, and carry out business logic on the server instead of needing to configure those actions on the client.

342 367 

Details

780}780}

781```781```

782 782 

783```ruby

784require "openai"

785require "webrick"

786require "json"

787require "uri"

788 

789client = OpenAI::Client.new(max_retries: 0)

790server = WEBrick::HTTPServer.new(

791 BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "3000")),

792 Logger: WEBrick::Log.new($stderr), AccessLog: []

793)

794server.mount_proc("/session") do |request, response|

795 unless request.request_method == "POST" && request.path == "/session"

796 response.status = 405

797 next

798 end

799 begin

800 options = { extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" } }

801 upstream = client.realtime.calls.create(

802 sdp: request.body.to_s,

803 session: {

804 type: :realtime,

805 model: "gpt-realtime-2.1",

806 audio: { output: { voice: :marin } }

807 },

808 request_options: options

809 )

810 response.status = upstream.status

811 response["Content-Type"] = "application/sdp"

812 # Resolve against the API origin before WEBrick normalizes Location headers.

813 location = upstream.headers["location"]

814 response["Location"] = URI.join(client.base_url.to_s, location).to_s if location

815 response.body = upstream.body.to_a.join

816 rescue OpenAI::Errors::APIError => error

817 response.status = error.status || 502

818 response["Content-Type"] = "application/json"

819 response.body = JSON.generate(error.body)

820 rescue

821 response.status = 500

822 response["Content-Type"] = "application/json"

823 response.body = JSON.generate(error: "Failed to create session")

824 end

825end

826trap("INT") { server.shutdown }

827trap("TERM") { server.shutdown }

828server.start

829```

830 

783 831 

784If your application assigns a [safety identifier](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers)832If your application assigns a [safety identifier](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers)

785for each end user, include it as the `OpenAI-Safety-Identifier` header in this833for each end user, include it as the `OpenAI-Safety-Identifier` header in this


923}971}

924```972```

925 973 

974```ruby

975require "openai"

976require "webrick"

977require "json"

978require "uri"

979 

980client = OpenAI::Client.new(max_retries: 0)

981server = WEBrick::HTTPServer.new(

982 BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "3000")),

983 Logger: WEBrick::Log.new($stderr), AccessLog: []

984)

985server.mount_proc("/token") do |request, response|

986 response["Cache-Control"] = "no-store"

987 response["Content-Type"] = "application/json"

988 unless request.request_method == "GET" && request.path == "/token"

989 response.status = 405

990 next

991 end

992 begin

993 token = client.realtime.client_secrets.create(

994 session: {

995 type: :realtime,

996 model: "gpt-realtime-2.1",

997 audio: { output: { voice: :marin } }

998 },

999 request_options: {

1000 include_raw_body: true,

1001 extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" }

1002 }

1003 )

1004 upstream = token.last_response or raise "Missing token response metadata"

1005 response.status = upstream.status

1006 response.body = upstream.body or raise "Missing token response body"

1007 rescue OpenAI::Errors::APIError => error

1008 response.status = error.status || 502

1009 response.body = JSON.generate(error.body)

1010 rescue

1011 response.status = 500

1012 response.body = JSON.generate(error: "Failed to generate token")

1013 end

1014end

1015trap("INT") { server.shutdown }

1016trap("TERM") { server.shutdown }

1017server.start

1018```

1019 

926 1020 

927You can create a server endpoint like this one on any platform that can send and receive HTTP requests. Just ensure that **you only use standard OpenAI API keys on the server, not in the browser.**1021You can create a server endpoint like this one on any platform that can send and receive HTTP requests. Just ensure that **you only use standard OpenAI API keys on the server, not in the browser.**

928 1022 

Details

159-H "Content-Type: application/json" \159-H "Content-Type: application/json" \

160-H "Authorization: Bearer $OPENAI_API_KEY" \160-H "Authorization: Bearer $OPENAI_API_KEY" \

161-d '{161-d '{

162 "model": "gpt-6-astra",162 "model": "gpt-6.2-astra",

163 "input": "Write a very long novel about otters in space.",163 "input": "Write a very long novel about otters in space.",

164 "background": true164 "background": true

165}'165}'


170const client = new OpenAI();170const client = new OpenAI();

171 171 

172const resp = await client.responses.create({172const resp = await client.responses.create({

173 model: "gpt-6-astra",173 model: "gpt-6.2-astra",

174 input: "Write a very long novel about otters in space.",174 input: "Write a very long novel about otters in space.",

175 background: true,175 background: true,

176});176});


184client = OpenAI()184client = OpenAI()

185 185 

186resp = client.responses.create(186resp = client.responses.create(

187 model="gpt-6-astra",187 model="gpt-6.2-astra",

188 input="Write a very long novel about otters in space.",188 input="Write a very long novel about otters in space.",

189 background=True,189 background=True,

190)190)


207 client := openai.NewClient()207 client := openai.NewClient()

208 208 

209 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{209 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

210 Model: "gpt-6-astra",210 Model: "gpt-6.2-astra",

211 Background: openai.Bool(true),211 Background: openai.Bool(true),

212 Input: responses.ResponseNewParamsInputUnion{212 Input: responses.ResponseNewParamsInputUnion{

213 OfString: openai.String("Write a very long novel about otters in space."),213 OfString: openai.String("Write a very long novel about otters in space."),


228 228 

229ResponseCreateParams params =229ResponseCreateParams params =

230 ResponseCreateParams.builder()230 ResponseCreateParams.builder()

231 .model("gpt-6-astra")231 .model("gpt-6.2-astra")

232 .input("Write a detailed market analysis.")232 .input("Write a detailed market analysis.")

233 .background(true)233 .background(true)

234 .build();234 .build();


246 246 

247CreateResponseOptions options = new()247CreateResponseOptions options = new()

248{248{

249 Model = "gpt-6-astra",249 Model = "gpt-6.2-astra",

250 BackgroundModeEnabled = true,250 BackgroundModeEnabled = true,

251};251};

252options.InputItems.Add(252options.InputItems.Add(


262 262 

263client = OpenAI::Client.new263client = OpenAI::Client.new

264response = client.responses.create(264response = client.responses.create(

265 model: "gpt-6-astra",265 model: "gpt-6.2-astra",

266 input: "Write a detailed market analysis.",266 input: "Write a detailed market analysis.",

267 background: true267 background: true

268)268)

Details

33 ws.send({33 ws.send({

34 type: "response.create",34 type: "response.create",

35 stream_id: "main",35 stream_id: "main",

36 model: "gpt-6-astra",36 model: "gpt-6.2-astra",

37 store: false,37 store: false,

38 input: [38 input: [

39 {39 {


76with client.responses.connect() as connection:76with client.responses.connect() as connection:

77 connection.response.create(77 connection.response.create(

78 stream_id="main",78 stream_id="main",

79 model="gpt-6-astra",79 model="gpt-6.2-astra",

80 store=False,80 store=False,

81 input=[81 input=[

82 {82 {


107}107}

108defer conn.Close()108defer conn.Close()

109if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{109if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{

110 Model: "gpt-6-astra",110 Model: "gpt-6.2-astra",

111 Store: openai.Bool(false),111 Store: openai.Bool(false),

112 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{112 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{

113 OfString: openai.String("Find fizz_buzz()"),113 OfString: openai.String("Find fizz_buzz()"),


138 conn.send(138 conn.send(

139 ResponsesClientEvent.ofResponseCreate(139 ResponsesClientEvent.ofResponseCreate(

140 ResponsesClientEvent.ResponseCreate.builder()140 ResponsesClientEvent.ResponseCreate.builder()

141 .model("gpt-6-astra")141 .model("gpt-6.2-astra")

142 .store(false)142 .store(false)

143 .input("Find fizz_buzz()")143 .input("Find fizz_buzz()")

144 .streamId("main")144 .streamId("main")


178 task.with_timeout(120) do178 task.with_timeout(120) do

179 client.responses.connect(request_options: { timeout: 10 }) do |connection|179 client.responses.connect(request_options: { timeout: 10 }) do |connection|

180 connection.response.create(180 connection.response.create(

181 stream_id: "main", model: "gpt-6-astra", store: false,181 stream_id: "main", model: "gpt-6.2-astra", store: false,

182 input: [182 input: [

183 {183 {

184 role: "user",184 role: "user",


209import { ResponsesWS } from "openai/resources/responses/ws";209import { ResponsesWS } from "openai/resources/responses/ws";

210 210 

211const client = new OpenAI();211const client = new OpenAI();

212const model = "gpt-6-astra";212const model = "gpt-6.2-astra";

213 213 

214const tools: OpenAI.Responses.Tool[] = [214const tools: OpenAI.Responses.Tool[] = [

215 {215 {


294from openai.types.responses import FunctionToolParam, Response294from openai.types.responses import FunctionToolParam, Response

295 295 

296client = OpenAI()296client = OpenAI()

297model = "gpt-6-astra"297model = "gpt-6.2-astra"

298tools: list[FunctionToolParam] = [298tools: list[FunctionToolParam] = [

299 {299 {

300 "type": "function",300 "type": "function",


387}387}

388defer conn.Close()388defer conn.Close()

389if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{389if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{

390 Model: "gpt-6-astra",390 Model: "gpt-6.2-astra",

391 Store: openai.Bool(false),391 Store: openai.Bool(false),

392 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{392 Input: responses.ResponsesClientEventResponseCreateInputUnionParam{

393 OfString: openai.String("Find the failing test and suggest a fix."),393 OfString: openai.String("Find the failing test and suggest a fix."),


423// The result is a local demo fixture; carry the real response and call IDs.423// The result is a local demo fixture; carry the real response and call IDs.

424result := `{"test":"test_fizz_buzz","failure":"Expected FizzBuzz for 15, got Fizz."}`424result := `{"test":"test_fizz_buzz","failure":"Expected FizzBuzz for 15, got Fizz."}`

425if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{425if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{

426 Model: "gpt-6-astra",426 Model: "gpt-6.2-astra",

427 StreamID: openai.String("main"),427 StreamID: openai.String("main"),

428 Store: openai.Bool(false),428 Store: openai.Bool(false),

429 PreviousResponseID: openai.String(first.ID),429 PreviousResponseID: openai.String(first.ID),


481 conn.send(481 conn.send(

482 ResponsesClientEvent.ofResponseCreate(482 ResponsesClientEvent.ofResponseCreate(

483 ResponsesClientEvent.ResponseCreate.builder()483 ResponsesClientEvent.ResponseCreate.builder()

484 .model("gpt-6-astra")484 .model("gpt-6.2-astra")

485 .store(false)485 .store(false)

486 .input("Find the failing test and suggest a fix.")486 .input("Find the failing test and suggest a fix.")

487 .streamId("main")487 .streamId("main")


505 conn.send(505 conn.send(

506 ResponsesClientEvent.ofResponseCreate(506 ResponsesClientEvent.ofResponseCreate(

507 ResponsesClientEvent.ResponseCreate.builder()507 ResponsesClientEvent.ResponseCreate.builder()

508 .model("gpt-6-astra")508 .model("gpt-6.2-astra")

509 .streamId("main")509 .streamId("main")

510 .store(false)510 .store(false)

511 .previousResponseId(first.id())511 .previousResponseId(first.id())


574 task.with_timeout(120) do574 task.with_timeout(120) do

575 client.responses.connect(request_options: { timeout: 10 }) do |connection|575 client.responses.connect(request_options: { timeout: 10 }) do |connection|

576 connection.response.create(576 connection.response.create(

577 stream_id: "main", model: "gpt-6-astra", store: false,577 stream_id: "main", model: "gpt-6.2-astra", store: false,

578 input: "Find the failing test and suggest a fix.", tools: tools,578 input: "Find the failing test and suggest a fix.", tools: tools,

579 tool_choice: {579 tool_choice: {

580 type: "function",580 type: "function",


593 failure: 'Expected "FizzBuzz" for 15, got "Fizz".'593 failure: 'Expected "FizzBuzz" for 15, got "Fizz".'

594 }594 }

595 connection.response.create(595 connection.response.create(

596 stream_id: "main", model: "gpt-6-astra", store: false,596 stream_id: "main", model: "gpt-6.2-astra", store: false,

597 previous_response_id: response.id,597 previous_response_id: response.id,

598 input: [598 input: [

599 {599 {


647 647 

648// Compact your current window with an HTTP request.648// Compact your current window with an HTTP request.

649const compacted = await client.responses.compact({649const compacted = await client.responses.compact({

650 model: "gpt-6-astra",650 model: "gpt-6.2-astra",

651 input: longInputItems,651 input: longInputItems,

652});652});

653const nextInput = toResponseInputItems(compacted.output);653const nextInput = toResponseInputItems(compacted.output);


663 ws.send({663 ws.send({

664 type: "response.create",664 type: "response.create",

665 stream_id: "main",665 stream_id: "main",

666 model: "gpt-6-astra",666 model: "gpt-6.2-astra",

667 store: false,667 store: false,

668 input: nextInput,668 input: nextInput,

669 tools: [],669 tools: [],


700 700 

701# Compact your current window (HTTP call).701# Compact your current window (HTTP call).

702compacted = client.responses.compact(702compacted = client.responses.compact(

703 model="gpt-6-astra",703 model="gpt-6.2-astra",

704 input=long_input_items_array,704 input=long_input_items_array,

705)705)

706next_input = cast(706next_input = cast(


719with client.responses.connect() as connection:719with client.responses.connect() as connection:

720 connection.response.create(720 connection.response.create(

721 stream_id="main",721 stream_id="main",

722 model="gpt-6-astra",722 model="gpt-6.2-astra",

723 store=False,723 store=False,

724 input=next_input,724 input=next_input,

725 tools=[],725 tools=[],


751 751 

752client = OpenAI::Client.new752client = OpenAI::Client.new

753compacted = client.responses.compact(753compacted = client.responses.compact(

754 model: "gpt-6-astra",754 model: "gpt-6.2-astra",

755 input: [755 input: [

756 {756 {

757 role: :user,757 role: :user,


769 task.with_timeout(120) do769 task.with_timeout(120) do

770 client.responses.connect(request_options: { timeout: 10 }) do |connection|770 client.responses.connect(request_options: { timeout: 10 }) do |connection|

771 connection.response.create(771 connection.response.create(

772 stream_id: "main", model: "gpt-6-astra", store: false,772 stream_id: "main", model: "gpt-6.2-astra", store: false,

773 input: next_input, tools: []773 input: next_input, tools: []

774 )774 )

775 puts(wait_for_response(connection).output_text)775 puts(wait_for_response(connection).output_text)


862 ws.send({862 ws.send({

863 type: "response.create",863 type: "response.create",

864 stream_id: streamId,864 stream_id: streamId,

865 model: "gpt-6-astra",865 model: "gpt-6.2-astra",

866 store: false,866 store: false,

867 input: [867 input: [

868 {868 {


985 previous_response_id = latest_response_id_by_lane.get(stream_id)985 previous_response_id = latest_response_id_by_lane.get(stream_id)

986 connection.response.create(986 connection.response.create(

987 stream_id=stream_id,987 stream_id=stream_id,

988 model="gpt-6-astra",988 model="gpt-6.2-astra",

989 store=False,989 store=False,

990 input=[990 input=[

991 {991 {


1071def send_create(connection, stream_id, text, previous_response_id = nil)1071def send_create(connection, stream_id, text, previous_response_id = nil)

1072 payload = {1072 payload = {

1073 stream_id: stream_id,1073 stream_id: stream_id,

1074 model: "gpt-6-astra",1074 model: "gpt-6.2-astra",

1075 store: false,1075 store: false,

1076 input: [1076 input: [

1077 {1077 {

Details

488});488});

489 489 

490const response = await client.responses.create({490const response = await client.responses.create({

491 model: "gpt-5.6-terra",491 model: "gpt-6.1-terra",

492 input: "Say hello from AWS outbound workload identity federation.",492 input: "Say hello from AWS outbound workload identity federation.",

493});493});

494 494 


531)531)

532 532 

533response = client.responses.create(533response = client.responses.create(

534 model="gpt-5.6-terra",534 model="gpt-6.1-terra",

535 input="Say hello from AWS outbound workload identity federation.",535 input="Say hello from AWS outbound workload identity federation.",

536)536)

537 537 


708 708 

709 ResponseCreateParams params =709 ResponseCreateParams params =

710 ResponseCreateParams.builder()710 ResponseCreateParams.builder()

711 .model("gpt-5.6-terra")711 .model("gpt-6.1-terra")

712 .input("Say hello from AWS outbound workload identity federation.")712 .input("Say hello from AWS outbound workload identity federation.")

713 .build();713 .build();

714 714 


774client = OpenAI::Client.new(workload_identity: workload_identity)774client = OpenAI::Client.new(workload_identity: workload_identity)

775 775 

776response = client.responses.create(776response = client.responses.create(

777 model: "gpt-5.6-terra",777 model: "gpt-6.1-terra",

778 input: "Say hello from AWS outbound workload identity federation."778 input: "Say hello from AWS outbound workload identity federation."

779)779)

780 780 


1249});1249});

1250 1250 

1251const response = await client.responses.create({1251const response = await client.responses.create({

1252 model: "gpt-5.6-terra",1252 model: "gpt-6.1-terra",

1253 input: "Say hello from AWS workload identity federation.",1253 input: "Say hello from AWS workload identity federation.",

1254});1254});

1255 1255 


1285)1285)

1286 1286 

1287response = client.responses.create(1287response = client.responses.create(

1288 model="gpt-5.6-terra",1288 model="gpt-6.1-terra",

1289 input="Say hello from AWS workload identity federation.",1289 input="Say hello from AWS workload identity federation.",

1290)1290)

1291 1291 


1431 1431 

1432 ResponseCreateParams params =1432 ResponseCreateParams params =

1433 ResponseCreateParams.builder()1433 ResponseCreateParams.builder()

1434 .model("gpt-5.6-terra")1434 .model("gpt-6.1-terra")

1435 .input("Say hello from AWS workload identity federation.")1435 .input("Say hello from AWS workload identity federation.")

1436 .build();1436 .build();

1437 1437 


1489client = OpenAI::Client.new(workload_identity: workload_identity)1489client = OpenAI::Client.new(workload_identity: workload_identity)

1490 1490 

1491response = client.responses.create(1491response = client.responses.create(

1492 model: "gpt-5.6-terra",1492 model: "gpt-6.1-terra",

1493 input: "Say hello from AWS workload identity federation."1493 input: "Say hello from AWS workload identity federation."

1494)1494)

1495 1495 

Details

515});515});

516 516 

517const response = await client.responses.create({517const response = await client.responses.create({

518 model: "gpt-5.6-terra",518 model: "gpt-6.1-terra",

519 input: "Say hello from GitHub Actions workload identity federation.",519 input: "Say hello from GitHub Actions workload identity federation.",

520});520});

521 521 


570)570)

571 571 

572response = client.responses.create(572response = client.responses.create(

573 model="gpt-5.6-terra",573 model="gpt-6.1-terra",

574 input="Say hello from GitHub Actions workload identity federation.",574 input="Say hello from GitHub Actions workload identity federation.",

575)575)

576 576 


799 799 

800 ResponseCreateParams params =800 ResponseCreateParams params =

801 ResponseCreateParams.builder()801 ResponseCreateParams.builder()

802 .model("gpt-5.6-terra")802 .model("gpt-6.1-terra")

803 .input("Say hello from GitHub Actions workload identity federation.")803 .input("Say hello from GitHub Actions workload identity federation.")

804 .build();804 .build();

805 805 


885client = OpenAI::Client.new(workload_identity: workload_identity)885client = OpenAI::Client.new(workload_identity: workload_identity)

886 886 

887response = client.responses.create(887response = client.responses.create(

888 model: "gpt-5.6-terra",888 model: "gpt-6.1-terra",

889 input: "Say hello from GitHub Actions workload identity federation."889 input: "Say hello from GitHub Actions workload identity federation."

890)890)

891 891 

Details

450});450});

451 451 

452const response = await client.responses.create({452const response = await client.responses.create({

453 model: "gpt-5.6-terra",453 model: "gpt-6.1-terra",

454 input: "Say hello from Google Cloud workload identity federation.",454 input: "Say hello from Google Cloud workload identity federation.",

455});455});

456 456 


501)501)

502 502 

503response = client.responses.create(503response = client.responses.create(

504 model="gpt-5.6-terra",504 model="gpt-6.1-terra",

505 input="Say hello from Google Cloud workload identity federation.",505 input="Say hello from Google Cloud workload identity federation.",

506)506)

507 507 


710 710 

711 ResponseCreateParams params =711 ResponseCreateParams params =

712 ResponseCreateParams.builder()712 ResponseCreateParams.builder()

713 .model("gpt-5.6-terra")713 .model("gpt-6.1-terra")

714 .input("Say hello from Google Cloud workload identity federation.")714 .input("Say hello from Google Cloud workload identity federation.")

715 .build();715 .build();

716 716 


793client = OpenAI::Client.new(workload_identity: workload_identity)793client = OpenAI::Client.new(workload_identity: workload_identity)

794 794 

795response = client.responses.create(795response = client.responses.create(

796 model: "gpt-5.6-terra",796 model: "gpt-6.1-terra",

797 input: "Say hello from Google Cloud workload identity federation."797 input: "Say hello from Google Cloud workload identity federation."

798)798)

799 799 


1274});1274});

1275 1275 

1276const response = await client.responses.create({1276const response = await client.responses.create({

1277 model: "gpt-5.6-terra",1277 model: "gpt-6.1-terra",

1278 input: "Say hello from Google GKE workload identity federation.",1278 input: "Say hello from Google GKE workload identity federation.",

1279});1279});

1280 1280 


1310)1310)

1311 1311 

1312response = client.responses.create(1312response = client.responses.create(

1313 model="gpt-5.6-terra",1313 model="gpt-6.1-terra",

1314 input="Say hello from Google GKE workload identity federation.",1314 input="Say hello from Google GKE workload identity federation.",

1315)1315)

1316 1316 


1456 1456 

1457 ResponseCreateParams params =1457 ResponseCreateParams params =

1458 ResponseCreateParams.builder()1458 ResponseCreateParams.builder()

1459 .model("gpt-5.6-terra")1459 .model("gpt-6.1-terra")

1460 .input("Say hello from Google GKE workload identity federation.")1460 .input("Say hello from Google GKE workload identity federation.")

1461 .build();1461 .build();

1462 1462 


1514client = OpenAI::Client.new(workload_identity: workload_identity)1514client = OpenAI::Client.new(workload_identity: workload_identity)

1515 1515 

1516response = client.responses.create(1516response = client.responses.create(

1517 model: "gpt-5.6-terra",1517 model: "gpt-6.1-terra",

1518 input: "Say hello from Google GKE workload identity federation."1518 input: "Say hello from Google GKE workload identity federation."

1519)1519)

1520 1520 

Details

493});493});

494 494 

495const response = await client.responses.create({495const response = await client.responses.create({

496 model: "gpt-5.6-terra",496 model: "gpt-6.1-terra",

497 input: "Say hello from SPIFFE workload identity federation.",497 input: "Say hello from SPIFFE workload identity federation.",

498});498});

499 499 


529)529)

530 530 

531response = client.responses.create(531response = client.responses.create(

532 model="gpt-5.6-terra",532 model="gpt-6.1-terra",

533 input="Say hello from SPIFFE workload identity federation.",533 input="Say hello from SPIFFE workload identity federation.",

534)534)

535 535 


673 673 

674 ResponseCreateParams params =674 ResponseCreateParams params =

675 ResponseCreateParams.builder()675 ResponseCreateParams.builder()

676 .model("gpt-5.6-terra")676 .model("gpt-6.1-terra")

677 .input("Say hello from SPIFFE workload identity federation.")677 .input("Say hello from SPIFFE workload identity federation.")

678 .build();678 .build();

679 679 


731client = OpenAI::Client.new(workload_identity: workload_identity)731client = OpenAI::Client.new(workload_identity: workload_identity)

732 732 

733response = client.responses.create(733response = client.responses.create(

734 model: "gpt-5.6-terra",734 model: "gpt-6.1-terra",

735 input: "Say hello from SPIFFE workload identity federation."735 input: "Say hello from SPIFFE workload identity federation."

736)736)

737 737 

Details

459});459});

460 460 

461const response = await client.responses.create({461const response = await client.responses.create({

462 model: "gpt-5.6-terra",462 model: "gpt-6.1-terra",

463 input: "Say hello from Kubernetes workload identity federation.",463 input: "Say hello from Kubernetes workload identity federation.",

464});464});

465 465 


495)495)

496 496 

497response = client.responses.create(497response = client.responses.create(

498 model="gpt-5.6-terra",498 model="gpt-6.1-terra",

499 input="Say hello from Kubernetes workload identity federation.",499 input="Say hello from Kubernetes workload identity federation.",

500)500)

501 501 


641 641 

642 ResponseCreateParams params =642 ResponseCreateParams params =

643 ResponseCreateParams.builder()643 ResponseCreateParams.builder()

644 .model("gpt-5.6-terra")644 .model("gpt-6.1-terra")

645 .input("Say hello from Kubernetes workload identity federation.")645 .input("Say hello from Kubernetes workload identity federation.")

646 .build();646 .build();

647 647 


699client = OpenAI::Client.new(workload_identity: workload_identity)699client = OpenAI::Client.new(workload_identity: workload_identity)

700 700 

701response = client.responses.create(701response = client.responses.create(

702 model: "gpt-5.6-terra",702 model: "gpt-6.1-terra",

703 input: "Say hello from Kubernetes workload identity federation."703 input: "Say hello from Kubernetes workload identity federation."

704)704)

705 705 

Details

467});467});

468 468 

469const response = await client.responses.create({469const response = await client.responses.create({

470 model: "gpt-5.6-terra",470 model: "gpt-6.1-terra",

471 input: "Say hello from Azure managed identity workload identity federation.",471 input: "Say hello from Azure managed identity workload identity federation.",

472});472});

473 473 


524)524)

525 525 

526response = client.responses.create(526response = client.responses.create(

527 model="gpt-5.6-terra",527 model="gpt-6.1-terra",

528 input="Say hello from Azure managed identity workload identity federation.",528 input="Say hello from Azure managed identity workload identity federation.",

529)529)

530 530 


742 742 

743 ResponseCreateParams params =743 ResponseCreateParams params =

744 ResponseCreateParams.builder()744 ResponseCreateParams.builder()

745 .model("gpt-5.6-terra")745 .model("gpt-6.1-terra")

746 .input("Say hello from Azure managed identity workload identity federation.")746 .input("Say hello from Azure managed identity workload identity federation.")

747 .build();747 .build();

748 748 


827client = OpenAI::Client.new(workload_identity: workload_identity)827client = OpenAI::Client.new(workload_identity: workload_identity)

828 828 

829response = client.responses.create(829response = client.responses.create(

830 model: "gpt-5.6-terra",830 model: "gpt-6.1-terra",

831 input: "Say hello from Azure managed identity workload identity federation."831 input: "Say hello from Azure managed identity workload identity federation."

832)832)

833 833 


1317});1317});

1318 1318 

1319const response = await client.responses.create({1319const response = await client.responses.create({

1320 model: "gpt-5.6-terra",1320 model: "gpt-6.1-terra",

1321 input: "Say hello from AKS workload identity federation.",1321 input: "Say hello from AKS workload identity federation.",

1322});1322});

1323 1323 


1353)1353)

1354 1354 

1355response = client.responses.create(1355response = client.responses.create(

1356 model="gpt-5.6-terra",1356 model="gpt-6.1-terra",

1357 input="Say hello from AKS workload identity federation.",1357 input="Say hello from AKS workload identity federation.",

1358)1358)

1359 1359 


1499 1499 

1500 ResponseCreateParams params =1500 ResponseCreateParams params =

1501 ResponseCreateParams.builder()1501 ResponseCreateParams.builder()

1502 .model("gpt-5.6-terra")1502 .model("gpt-6.1-terra")

1503 .input("Say hello from AKS workload identity federation.")1503 .input("Say hello from AKS workload identity federation.")

1504 .build();1504 .build();

1505 1505 


1557client = OpenAI::Client.new(workload_identity: workload_identity)1557client = OpenAI::Client.new(workload_identity: workload_identity)

1558 1558 

1559response = client.responses.create(1559response = client.responses.create(

1560 model: "gpt-5.6-terra",1560 model: "gpt-6.1-terra",

1561 input: "Say hello from AKS workload identity federation."1561 input: "Say hello from AKS workload identity federation."

1562)1562)

1563 1563 

Details

468)468)

469 469 

470response = client.responses.create(470response = client.responses.create(

471 model="gpt-5.6-terra",471 model="gpt-6.1-terra",

472 input="Say hello from Oracle Cloud Infrastructure workload identity federation.",472 input="Say hello from Oracle Cloud Infrastructure workload identity federation.",

473)473)

474 474 


576client = OpenAI::Client.new(workload_identity: workload_identity)576client = OpenAI::Client.new(workload_identity: workload_identity)

577 577 

578response = client.responses.create(578response = client.responses.create(

579 model: "gpt-5.6-terra",579 model: "gpt-6.1-terra",

580 input: "Say hello from Oracle Cloud Infrastructure workload identity federation."580 input: "Say hello from Oracle Cloud Infrastructure workload identity federation."

581)581)

582 582 

Details

521});521});

522 522 

523const response = await client.responses.create({523const response = await client.responses.create({

524 model: "gpt-5.6-terra",524 model: "gpt-6.1-terra",

525 input: "Say hello from SPIFFE workload identity federation.",525 input: "Say hello from SPIFFE workload identity federation.",

526});526});

527 527 


557)557)

558 558 

559response = client.responses.create(559response = client.responses.create(

560 model="gpt-5.6-terra",560 model="gpt-6.1-terra",

561 input="Say hello from SPIFFE workload identity federation.",561 input="Say hello from SPIFFE workload identity federation.",

562)562)

563 563 


701 701 

702 ResponseCreateParams params =702 ResponseCreateParams params =

703 ResponseCreateParams.builder()703 ResponseCreateParams.builder()

704 .model("gpt-5.6-terra")704 .model("gpt-6.1-terra")

705 .input("Say hello from SPIFFE workload identity federation.")705 .input("Say hello from SPIFFE workload identity federation.")

706 .build();706 .build();

707 707 


759client = OpenAI::Client.new(workload_identity: workload_identity)759client = OpenAI::Client.new(workload_identity: workload_identity)

760 760 

761response = client.responses.create(761response = client.responses.create(

762 model: "gpt-5.6-terra",762 model: "gpt-6.1-terra",

763 input: "Say hello from SPIFFE workload identity federation."763 input: "Say hello from SPIFFE workload identity federation."

764)764)

765 765 

Details

144try {144try {

145 const client = new OpenAI({ credential });145 const client = new OpenAI({ credential });

146 const response = await client.responses.create({146 const response = await client.responses.create({

147 model: "gpt-5.6-terra",147 model: "gpt-6.1-terra",

148 input: "Say hello from X.509 workload identity federation.",148 input: "Say hello from X.509 workload identity federation.",

149 });149 });

150 150 


176 http_client=DefaultHttpx2Client(verify=tls_context, follow_redirects=False),176 http_client=DefaultHttpx2Client(verify=tls_context, follow_redirects=False),

177) as client:177) as client:

178 response = client.responses.create(178 response = client.responses.create(

179 model="gpt-5.6-terra",179 model="gpt-6.1-terra",

180 input="Say hello from X.509 workload identity federation.",180 input="Say hello from X.509 workload identity federation.",

181 )181 )

182 182 


229 )229 )

230 230 

231 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{231 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

232 Model: "gpt-5.6-terra",232 Model: "gpt-6.1-terra",

233 Input: responses.ResponseNewParamsInputUnion{233 Input: responses.ResponseNewParamsInputUnion{

234 OfString: openai.String("Say hello from X.509 workload identity federation."),234 OfString: openai.String("Say hello from X.509 workload identity federation."),

235 },235 },


305 try {305 try {

306 ResponseCreateParams params =306 ResponseCreateParams params =

307 ResponseCreateParams.builder()307 ResponseCreateParams.builder()

308 .model("gpt-5.6-terra")308 .model("gpt-6.1-terra")

309 .input("Say hello from X.509 workload identity federation.")309 .input("Say hello from X.509 workload identity federation.")

310 .build();310 .build();

311 311 


347begin347begin

348 client = OpenAI::Client.new(api_key: nil, workload_identity: workload_identity)348 client = OpenAI::Client.new(api_key: nil, workload_identity: workload_identity)

349 response = client.responses.create(349 response = client.responses.create(

350 model: "gpt-5.6-terra",350 model: "gpt-6.1-terra",

351 input: "Say hello from X.509 workload identity federation."351 input: "Say hello from X.509 workload identity federation."

352 )352 )

353 353 


402 402 

403## Call the OpenAI API manually403## Call the OpenAI API manually

404 404 

405Set `OPENAI_MODEL` to `gpt-6-astra`, the current default, or another model available to the target project. Then send the bearer token and an accepted client certificate to the API mTLS endpoint:405Set `OPENAI_MODEL` to `gpt-6.2-astra`, the current default, or another model available to the target project. Then send the bearer token and an accepted client certificate to the API mTLS endpoint:

406 406 

407```bash407```bash

408curl --request POST \408curl --request POST \

Details

109 109 

110- Except as noted below, the Responses API has a 30 day Application State retention period by default, or when the `store` parameter is set to `true`. In those cases, response data will be stored for at least 30 days.110- Except as noted below, the Responses API has a 30 day Application State retention period by default, or when the `store` parameter is set to `true`. In those cases, response data will be stored for at least 30 days.

111- When Zero Data Retention is enabled for an organization, the `store` parameter will always be treated as `false`, even if the request attempts to set the value to `true`.111- When Zero Data Retention is enabled for an organization, the `store` parameter will always be treated as `false`, even if the request attempts to set the value to `true`.

112- Background mode stores response data to disk for roughly 10 minutes to enable polling. For projects using [Modified Abuse Monitoring](#modified-abuse-monitoring), including enhanced Modified Abuse Monitoring, foreground requests follow standard retention when `store` is omitted or set to `true`. Background responses follow the standard retention period only when the request explicitly sets `store=true`. If `store` is omitted or set to `false` for a background request, the response is deleted after the temporary polling period.112- Background mode with the default completion window stores response data to disk for roughly 10 minutes to run the request and make the response available for retrieval. For projects using [Modified Abuse Monitoring](#modified-abuse-monitoring), including enhanced Modified Abuse Monitoring, foreground requests follow standard retention when `store` is omitted or set to `true`. With the default completion window, background responses follow the standard retention period only if you explicitly set `store=true`. If you omit `store` or set it to `false`, the response is deleted after the temporary retention period.

113- Projects with [Zero Data Retention](#zero-data-retention) can use the `2h` and `8h` [background completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows). The API treats `store` as `false` and temporarily stores application state to process the request and make the response available for retrieval.

113- Audio outputs application state is stored for 1 hour to enable [multi-turn conversations](https://developers.openai.com/api/docs/guides/audio).114- Audio outputs application state is stored for 1 hour to enable [multi-turn conversations](https://developers.openai.com/api/docs/guides/audio).

114- See [image and file inputs](#image-and-file-inputs).115- See [image and file inputs](#image-and-file-inputs).

115- MCP servers (used with the [remote MCP server tool](https://developers.openai.com/api/docs/guides/tools-connectors-mcp)) are third-party services, and data sent to an MCP server is subject to their data retention policies.116- MCP servers (used with the [remote MCP server tool](https://developers.openai.com/api/docs/guides/tools-connectors-mcp)) are third-party services, and data sent to an MCP server is subject to their data retention policies.

libraries.md +8 −8

Details

62const client = new OpenAI();62const client = new OpenAI();

63 63 

64const response = await client.responses.create({64const response = await client.responses.create({

65 model: "gpt-6-astra",65 model: "gpt-6.2-astra",

66 input: "Write a one-sentence bedtime story about a unicorn.",66 input: "Write a one-sentence bedtime story about a unicorn.",

67});67});

68 68 


109client = OpenAI()109client = OpenAI()

110 110 

111response = client.responses.create(111response = client.responses.create(

112 model="gpt-6-astra",112 model="gpt-6.2-astra",

113 input="Write a one-sentence bedtime story about a unicorn.",113 input="Write a one-sentence bedtime story about a unicorn.",

114)114)

115 115 


153ResponsesClient client = new(key);153ResponsesClient client = new(key);

154 154 

155ResponseResult response = await client.CreateResponseAsync(155ResponseResult response = await client.CreateResponseAsync(

156 "gpt-6-astra",156 "gpt-6.2-astra",

157 "Say 'this is a test.'"157 "Say 'this is a test.'"

158);158);

159 159 


177<dependency>177<dependency>

178 <groupId>com.openai</groupId>178 <groupId>com.openai</groupId>

179 <artifactId>openai-java</artifactId>179 <artifactId>openai-java</artifactId>

180 <version>4.105.0</version>180 <version>4.107.0</version>

181</dependency>181</dependency>

182```182```

183 183 


198 OpenAIClient client = OpenAIOkHttpClient.fromEnv();198 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

199 199 

200 ResponseCreateParams params =200 ResponseCreateParams params =

201 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();201 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();

202 202 

203 Response response = client.responses().create(params);203 Response response = client.responses().create(params);

204 response.output().stream()204 response.output().stream()


247 client := openai.NewClient()247 client := openai.NewClient()

248 248 

249 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{249 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

250 Model: "gpt-6-astra",250 Model: "gpt-6.2-astra",

251 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},251 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

252 })252 })

253 if err != nil {253 if err != nil {


296openai = OpenAI::Client.new296openai = OpenAI::Client.new

297 297 

298response = openai.responses.create(298response = openai.responses.create(

299 model: "gpt-6-astra",299 model: "gpt-6.2-astra",

300 input: "Write a one-sentence bedtime story about a unicorn."300 input: "Write a one-sentence bedtime story about a unicorn."

301)301)

302 302 


337 337 

338```bash338```bash

339openai responses create \339openai responses create \

340 --model "gpt-6-astra" \340 --model "gpt-6.2-astra" \

341 --input "Write a one-sentence bedtime story about a unicorn." \341 --input "Write a one-sentence bedtime story about a unicorn." \

342 --raw-output \342 --raw-output \

343 --transform 'output.#(type=="message").content.0.text'343 --transform 'output.#(type=="message").content.0.text'

Details

84 84 

85```bash85```bash

86openai responses create \86openai responses create \

87 --model gpt-6-astra \87 --model gpt-6.2-astra \

88 --input "Say hello in one sentence."88 --input "Say hello in one sentence."

89```89```

90 90 


132 132 

133```bash133```bash

134openai responses create \134openai responses create \

135 --model gpt-6-astra \135 --model gpt-6.2-astra \

136 --input "Summarize this note in one sentence.136 --input "Summarize this note in one sentence.

137 137 

138<note>138<note>


190 sed 's/^/ /' ./note.md190 sed 's/^/ /' ./note.md

191 printf ' </note>\n'191 printf ' </note>\n'

192} | openai responses create \192} | openai responses create \

193 --model gpt-6-astra \193 --model gpt-6.2-astra \

194 --format yaml \194 --format yaml \

195 --transform 'output.#(type=="message").content.0.text'195 --transform 'output.#(type=="message").content.0.text'

196```196```


223 223 

224```bash224```bash

225openai responses create \225openai responses create \

226 --model gpt-6-astra \226 --model gpt-6.2-astra \

227 --instructions "Extract the person and topic from the input." \227 --instructions "Extract the person and topic from the input." \

228 --input "Ada Lovelace wrote notes about the Analytical Engine." \228 --input "Ada Lovelace wrote notes about the Analytical Engine." \

229 --text.format "$(cat ./schema.json)" \229 --text.format "$(cat ./schema.json)" \


308 308 

309```bash309```bash

310openai responses create \310openai responses create \

311 --model gpt-6-astra \311 --model gpt-6.2-astra \

312 --format yaml \312 --format yaml \

313 --transform 'output.#(type=="message").content.0.text' <<'YAML'313 --transform 'output.#(type=="message").content.0.text' <<'YAML'

314tools:314tools:

mcp.md +145 −5

Details

167 167 

168 168 

169 169 

170A full implementation of both the `search` and `fetch` tools in FastMCP is below also for convenience.170The following examples implement both `search` and `fetch` with an MCP SDK.

171 171 

172 172 

173 173 

174#### Full implementation - FastMCP server174#### Full MCP server implementation

175 175 

176 176 

177 177 

178Create a document search MCP server

179 

178```python180```python

179# Replace the illustrative IDs and URLs below with your own resource values.181# Replace the illustrative IDs and URLs below with your own resource values.

180"""182"""


389 main()391 main()

390```392```

391 393 

394```ruby

395require "openai"

396require "mcp"

397require "json"

398 

399class SearchDocuments < MCP::Tool

400 tool_name "search"

401 description "Search documents and return identities, titles, and citation URLs."

402 input_schema(type: "object", properties: { query: { type: "string" } }, required: ["query"])

403 output_schema(

404 type: "object", properties: {

405 results: {

406 type: "array",

407 

408 items: {

409 type: "object",

410 

411 properties: {

412 id: { type: "string" },

413 title: { type: "string" },

414 url: { type: "string" }

415 },

416 required: %w[id title url]

417 }

418 }

419 }, required: ["results"]

420 )

421 

422 def self.call(query:, server_context:)

423 results = []

424 unless query.strip.empty?

425 response = server_context.fetch(:client).vector_stores.search(server_context.fetch(:store), query: query)

426 results = response.data.map do |item|

427 {

428 id: item.file_id,

429 title: item.filename,

430 url: "https://platform.openai.com/storage/files/#{item.file_id}"

431 }

432 end

433 end

434 result = { results: results }

435 MCP::Tool::Response.new(

436 [

437 {

438 type: "text",

439 text: JSON.generate(result)

440 }

441 ], structured_content: result

442 )

443 end

444end

445 

446class FetchDocument < MCP::Tool

447 tool_name "fetch"

448 description "Retrieve a complete document with its citation and metadata."

449 input_schema(type: "object", properties: { id: { type: "string" } }, required: ["id"])

450 output_schema(

451 type: "object", properties: {

452 id: { type: "string" },

453 

454 title: { type: "string" },

455 

456 text: { type: "string" },

457 

458 url: { type: "string" },

459 metadata: { type: ["object", "null"] }

460 }, required: %w[id title text url]

461 )

462 

463 def self.call(id:, server_context:)

464 if id.empty?

465 return MCP::Tool::Response.new(

466 [

467 {

468 type: "text",

469 text: "Document ID is required"

470 }

471 ], error: true

472 )

473 end

474 

475 client = server_context.fetch(:client)

476 store = server_context.fetch(:store)

477 content = client.vector_stores.files.content(id, vector_store_id: store)

478 info = client.vector_stores.files.retrieve(id, vector_store_id: store)

479 file = client.files.retrieve(id)

480 text = content.data.map(&:text).join("\n")

481 result = {

482 id: id,

483 

484 title: file.filename,

485 

486 text: text,

487 url: "https://platform.openai.com/storage/files/#{id}"

488 }

489 result[:metadata] = info.attributes unless info.attributes.nil? || info.attributes.empty?

490 MCP::Tool::Response.new(

491 [

492 {

493 type: "text",

494 text: JSON.generate(result)

495 }

496 ], structured_content: result

497 )

498 end

499end

500 

501server = MCP::Server.new(

502 name: "Sample MCP Server", version: "1.0.0", tools: [SearchDocuments, FetchDocument],

503 instructions: "Search for relevant documents, then fetch complete content with citations.",

504 server_context: {

505 client: OpenAI::Client.new,

506 store: ENV.fetch("OPENAI_VECTOR_STORE_ID", "vs_123")

507 }

508)

509if ARGV.first == "stdio"

510 MCP::Server::Transports::StdioTransport.new(server).open

511 exit

512end

513 

514require "rackup"

515require "rackup/handler/webrick"

516transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true)

517app = Rack::URLMap.new("/mcp" => transport)

518Rackup::Handler::WEBrick.run(app, Host: ENV.fetch("MCP_HOST", "127.0.0.1"), Port: Integer(ENV.fetch("PORT", "8000"))) do |http_server|

519 trap("INT") { http_server.shutdown }

520 trap("TERM") { http_server.shutdown }

521end

522```

523 

392 524 

393 525 

394 526 


406 538 

407![replit configuration](https://cdn.openai.com/API/docs/images/replit.png)539![replit configuration](https://cdn.openai.com/API/docs/images/replit.png)

408 540 

409In the long dev URL, ensure it ends with `/sse/`, which is the server-sent events (streaming) interface to the MCP server. This is the URL you will use to connect your app in ChatGPT and call it via API. An example Replit URL looks like:541For the Python server, ensure the long dev URL ends with `/sse/`, which is the server-sent events (streaming) interface to the MCP server. This is the URL you will use to connect your app in ChatGPT and call it via API. An example Replit URL looks like:

410 542 

411```text543```text

412https://777xxx.janeway.replit.dev/sse/544https://777xxx.janeway.replit.dev/sse/


416 548 

417 549 

418 550 

551For Ruby, install the `openai`, `mcp` (version 1.10.0), `rackup`, and `webrick` gems, save the Ruby source as `server.rb`, and run `ruby server.rb`. Set `OPENAI_VECTOR_STORE_ID` to your vector store ID and `MCP_HOST` to `0.0.0.0` on Replit. The Ruby server uses Streamable HTTP at `/mcp`; use that path instead of `/sse/` in the connection URL. The Ruby server uses port 8000 by default or the port specified by `PORT`.

552 

553 

554 

555 

556 

557 

558 

419 559 

420## Test and connect your MCP server560## Test and connect your MCP server

421 561 

422You can test your MCP server with `gpt-6.1-sol` [in the prompts dashboard](https://platform.openai.com/chat). Create a new prompt, or edit an existing one, and add a new MCP tool to the prompt configuration. This compatibility example exposes only read-only `search` and `fetch` tools, so its API request skips approval for those tools. Keep approval enabled for tools that can modify data or take other consequential actions.562You can test your MCP server with `gpt-6.2-sol` [in the prompts dashboard](https://platform.openai.com/chat). Create a new prompt, or edit an existing one, and add a new MCP tool to the prompt configuration. This compatibility example exposes only read-only `search` and `fetch` tools, so its API request skips approval for those tools. Keep approval enabled for tools that can modify data or take other consequential actions.

423 563 

424If you are testing this server as part of a plugin, follow [Connect and test your plugin](https://developers.openai.com/plugins/deploy/connect-chatgpt).564If you are testing this server as part of a plugin, follow [Connect and test your plugin](https://developers.openai.com/plugins/deploy/connect-chatgpt).

425 565 


436 -H "Content-Type: application/json" \576 -H "Content-Type: application/json" \

437 -H "Authorization: Bearer $OPENAI_API_KEY" \577 -H "Authorization: Bearer $OPENAI_API_KEY" \

438 -d '{578 -d '{

439 "model": "gpt-6.1-sol",579 "model": "gpt-6.2-sol",

440 "input": [580 "input": [

441 {581 {

442 "role": "developer",582 "role": "developer",

models.md +6 −4

Details

4 4 

5> Explore models available on the OpenAI API.5> Explore models available on the OpenAI API.

6 6 

7If you're not sure where to start, use [GPT-6 Astra](/api/docs/models/gpt-6-astra), our flagship model for complex reasoning and coding. Choose [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol) to balance intelligence and cost, or [GPT-6 Luna](/api/docs/models/gpt-6-luna) for cost-sensitive, high-volume workloads.7If you're not sure where to start, use [GPT-6.2 Astra](/api/docs/models/gpt-6.2-astra), our flagship model for complex reasoning and coding. Choose [GPT-6.2 Sol](/api/docs/models/gpt-6.2-sol) to balance intelligence and cost, or [GPT-6 Luna](/api/docs/models/gpt-6-luna) for cost-sensitive, high-volume workloads.

8 8 

9All latest OpenAI models support text and image input, text output, multilingual capabilities, and vision. Models are available via the [Responses API](/api/reference/resources/responses/methods/create) and our [Client SDKs](/api/docs/libraries).9All latest OpenAI models support text and image input, text output, multilingual capabilities, and vision. Models are available via the [Responses API](/api/reference/resources/responses/methods/create) and our [Client SDKs](/api/docs/libraries).

10 10 

11## Featured models11## Featured models

12 12 

13- [GPT-6 Astra](/api/docs/models/gpt-6-astra.md): Our most capable model for the most demanding work.13- [GPT-6.2 Astra](/api/docs/models/gpt-6.2-astra.md): Our most capable model for your hardest projects, from start to finish.

14- [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md): Near-Astra performance for complex work at a lower cost.14- [GPT-6.2 Sol](/api/docs/models/gpt-6.2-sol.md): Our go-to model for everyday work, from coding to powering agents at scale.

15- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.15- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.

16- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.16- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.

17 17 


33- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): GPT-5.6 model optimized for cost-sensitive workloads33- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): GPT-5.6 model optimized for cost-sensitive workloads

34- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): GPT-5.6 flagship model for complex professional work34- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): GPT-5.6 flagship model for complex professional work

35- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost35- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost

36- [GPT-6 Astra](/api/docs/models/gpt-6-astra.md): Our most capable model for the most demanding work.36- [GPT-6 Astra](/api/docs/models/gpt-6-astra.md): A reasoning model for complex coding and professional work.

37- [GPT-6 Cyber](/api/docs/models/gpt-6-cyber.md): Investigate a vulnerability, reproduce it in an authorized test environment, or verify a fix.37- [GPT-6 Cyber](/api/docs/models/gpt-6-cyber.md): Investigate a vulnerability, reproduce it in an authorized test environment, or verify a fix.

38- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.38- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.

39- [GPT-6 Sol](/api/docs/models/gpt-6-sol.md): Built to power complex coding and agentic workflows.39- [GPT-6 Sol](/api/docs/models/gpt-6-sol.md): Built to power complex coding and agentic workflows.

40- [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md): Near-Astra performance for complex work at a lower cost.40- [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md): Near-Astra performance for complex work at a lower cost.

41- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.41- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.

42- [GPT-6.2 Astra](/api/docs/models/gpt-6.2-astra.md): Our most capable model for your hardest projects, from start to finish.

43- [GPT-6.2 Sol](/api/docs/models/gpt-6.2-sol.md): Our go-to model for everyday work, from coding to powering agents at scale.

42- [GPT-Audio-1.5](/api/docs/models/gpt-audio-1.5.md): The best voice model for audio in, audio out with Chat Completions.44- [GPT-Audio-1.5](/api/docs/models/gpt-audio-1.5.md): The best voice model for audio in, audio out with Chat Completions.

43- [GPT-Image-2.5 Flare](/api/docs/models/gpt-image-2.5-flare.md): Fast, high-quality everyday image generation45- [GPT-Image-2.5 Flare](/api/docs/models/gpt-image-2.5-flare.md): Fast, high-quality everyday image generation

44- [GPT-Image-2.5 Sunburst](/api/docs/models/gpt-image-2.5-sunburst.md): Our most capable model for image generation and editing46- [GPT-Image-2.5 Sunburst](/api/docs/models/gpt-image-2.5-sunburst.md): Our most capable model for image generation and editing

models/all.md +4 −2

Details

10 10 

11Compare capabilities and specifications.11Compare capabilities and specifications.

12 12 

13- [GPT-6 Astra](/api/docs/models/gpt-6-astra.md): Our most capable model for the most demanding work.13- [GPT-6.2 Astra](/api/docs/models/gpt-6.2-astra.md): Our most capable model for your hardest projects, from start to finish.

14- [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md): Near-Astra performance for complex work at a lower cost.14- [GPT-6.2 Sol](/api/docs/models/gpt-6.2-sol.md): Our go-to model for everyday work, from coding to powering agents at scale.

15- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.15- [GPT-6.1 Terra](/api/docs/models/gpt-6.1-terra.md): A fast, efficient model for visual reasoning, precise computer use, and clear, natural writing.

16- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.16- [GPT-6 Luna](/api/docs/models/gpt-6-luna.md): Our most efficient model for focused, high-volume tasks.

17 17 


71 71 

72Diverse models for a variety of tasks.72Diverse models for a variety of tasks.

73 73 

74- [GPT-6 Astra](/api/docs/models/gpt-6-astra.md): A reasoning model for complex coding and professional work.

75- [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md): Near-Astra performance for complex work at a lower cost.

74- [GPT-6 Sol](/api/docs/models/gpt-6-sol.md): Built to power complex coding and agentic workflows.76- [GPT-6 Sol](/api/docs/models/gpt-6-sol.md): Built to power complex coding and agentic workflows.

75- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): GPT-5.6 flagship model for complex professional work77- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): GPT-5.6 flagship model for complex professional work

76- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost78- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost

Details

6 6 

7| Model | Context window | Max output | Supported endpoints |7| Model | Context window | Max output | Supported endpoints |

8| --- | ---: | ---: | --- |8| --- | ---: | ---: | --- |

9| [GPT-6 Astra](/api/docs/models/gpt-6-astra.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |9| [GPT-6.2 Astra](/api/docs/models/gpt-6.2-astra.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

10| [GPT-6.1 Sol](/api/docs/models/gpt-6.1-sol.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |10| [GPT-6.2 Sol](/api/docs/models/gpt-6.2-sol.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

11| [GPT-6 Luna](/api/docs/models/gpt-6-luna.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |11| [GPT-6 Luna](/api/docs/models/gpt-6-luna.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

quickstart.md +70 −70

Details

72const client = new OpenAI();72const client = new OpenAI();

73 73 

74const response = await client.responses.create({74const response = await client.responses.create({

75 model: "gpt-6-astra",75 model: "gpt-6.2-astra",

76 input: "Write a one-sentence bedtime story about a unicorn.",76 input: "Write a one-sentence bedtime story about a unicorn.",

77});77});

78 78 


119client = OpenAI()119client = OpenAI()

120 120 

121response = client.responses.create(121response = client.responses.create(

122 model="gpt-6-astra",122 model="gpt-6.2-astra",

123 input="Write a one-sentence bedtime story about a unicorn.",123 input="Write a one-sentence bedtime story about a unicorn.",

124)124)

125 125 


163ResponsesClient client = new(key);163ResponsesClient client = new(key);

164 164 

165ResponseResult response = await client.CreateResponseAsync(165ResponseResult response = await client.CreateResponseAsync(

166 "gpt-6-astra",166 "gpt-6.2-astra",

167 "Say 'this is a test.'"167 "Say 'this is a test.'"

168);168);

169 169 


187<dependency>187<dependency>

188 <groupId>com.openai</groupId>188 <groupId>com.openai</groupId>

189 <artifactId>openai-java</artifactId>189 <artifactId>openai-java</artifactId>

190 <version>4.105.0</version>190 <version>4.107.0</version>

191</dependency>191</dependency>

192```192```

193 193 


208 OpenAIClient client = OpenAIOkHttpClient.fromEnv();208 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

209 209 

210 ResponseCreateParams params =210 ResponseCreateParams params =

211 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();211 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();

212 212 

213 Response response = client.responses().create(params);213 Response response = client.responses().create(params);

214 response.output().stream()214 response.output().stream()


257 client := openai.NewClient()257 client := openai.NewClient()

258 258 

259 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{259 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

260 Model: "gpt-6-astra",260 Model: "gpt-6.2-astra",

261 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},261 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

262 })262 })

263 if err != nil {263 if err != nil {


306openai = OpenAI::Client.new306openai = OpenAI::Client.new

307 307 

308response = openai.responses.create(308response = openai.responses.create(

309 model: "gpt-6-astra",309 model: "gpt-6.2-astra",

310 input: "Write a one-sentence bedtime story about a unicorn."310 input: "Write a one-sentence bedtime story about a unicorn."

311)311)

312 312 


372const client = new OpenAI();372const client = new OpenAI();

373 373 

374const response = await client.responses.create({374const response = await client.responses.create({

375 model: "gpt-6-astra",375 model: "gpt-6.2-astra",

376 input: [376 input: [

377 {377 {

378 role: "user",378 role: "user",


401client = OpenAI()401client = OpenAI()

402 402 

403response = client.responses.create(403response = client.responses.create(

404 model="gpt-6-astra",404 model="gpt-6.2-astra",

405 input=[405 input=[

406 {406 {

407 "role": "user",407 "role": "user",


436func main() {436func main() {

437 client := openai.NewClient()437 client := openai.NewClient()

438 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{438 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

439 Model: "gpt-6-astra",439 Model: "gpt-6.2-astra",

440 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{440 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

441 responses.ResponseInputItemParamOfMessage(441 responses.ResponseInputItemParamOfMessage(

442 responses.ResponseInputMessageContentListParam{442 responses.ResponseInputMessageContentListParam{


480 480 

481ResponseCreateParams params =481ResponseCreateParams params =

482 ResponseCreateParams.builder()482 ResponseCreateParams.builder()

483 .model("gpt-6-astra")483 .model("gpt-6.2-astra")

484 .inputOfResponse(List.of(imageInput))484 .inputOfResponse(List.of(imageInput))

485 .build();485 .build();

486 486 


503);503);

504 504 

505ResponseResult response = await client.CreateResponseAsync(505ResponseResult response = await client.CreateResponseAsync(

506 "gpt-6-astra",506 "gpt-6.2-astra",

507 [507 [

508 ResponseItem.CreateUserMessageItem(508 ResponseItem.CreateUserMessageItem(

509 [509 [


523openai = OpenAI::Client.new523openai = OpenAI::Client.new

524 524 

525response = openai.responses.create(525response = openai.responses.create(

526 model: "gpt-6-astra",526 model: "gpt-6.2-astra",

527 input: [527 input: [

528 {528 {

529 role: "user",529 role: "user",


549 -H "Content-Type: application/json" \549 -H "Content-Type: application/json" \

550 -H "Authorization: Bearer $OPENAI_API_KEY" \550 -H "Authorization: Bearer $OPENAI_API_KEY" \

551 -d '{551 -d '{

552 "model": "gpt-6-astra",552 "model": "gpt-6.2-astra",

553 "input": [553 "input": [

554 {554 {

555 "role": "user",555 "role": "user",


570 570 

571```bash571```bash

572openai responses create \572openai responses create \

573 --model gpt-6-astra \573 --model gpt-6.2-astra \

574 --raw-output \574 --raw-output \

575 --transform 'output.#(type=="message").content.0.text' <<'YAML'575 --transform 'output.#(type=="message").content.0.text' <<'YAML'

576input:576input:


597const client = new OpenAI();597const client = new OpenAI();

598 598 

599const response = await client.responses.create({599const response = await client.responses.create({

600 model: "gpt-6-astra",600 model: "gpt-6.2-astra",

601 input: [601 input: [

602 {602 {

603 role: "user",603 role: "user",


624client = OpenAI()624client = OpenAI()

625 625 

626response = client.responses.create(626response = client.responses.create(

627 model="gpt-6-astra",627 model="gpt-6.2-astra",

628 input=[628 input=[

629 {629 {

630 "role": "user",630 "role": "user",


660 client := openai.NewClient()660 client := openai.NewClient()

661 661 

662 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{662 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

663 Model: "gpt-6-astra",663 Model: "gpt-6.2-astra",

664 Input: responses.ResponseNewParamsInputUnion{664 Input: responses.ResponseNewParamsInputUnion{

665 OfInputItemList: responses.ResponseInputParam{665 OfInputItemList: responses.ResponseInputParam{

666 responses.ResponseInputItemParamOfMessage(666 responses.ResponseInputItemParamOfMessage(


699 699 

700ResponseCreateParams params =700ResponseCreateParams params =

701 ResponseCreateParams.builder()701 ResponseCreateParams.builder()

702 .model("gpt-6-astra")702 .model("gpt-6.2-astra")

703 .inputOfResponse(703 .inputOfResponse(

704 List.of(704 List.of(

705 ResponseInputItem.ofMessage(705 ResponseInputItem.ofMessage(


734);734);

735 735 

736ResponseResult response = await client.CreateResponseAsync(736ResponseResult response = await client.CreateResponseAsync(

737 "gpt-6-astra",737 "gpt-6.2-astra",

738 [738 [

739 ResponseItem.CreateUserMessageItem(739 ResponseItem.CreateUserMessageItem(

740 [740 [


756openai = OpenAI::Client.new756openai = OpenAI::Client.new

757 757 

758response = openai.responses.create(758response = openai.responses.create(

759 model: "gpt-6-astra",759 model: "gpt-6.2-astra",

760 input: [760 input: [

761 {761 {

762 role: "user",762 role: "user",


782 -H "Content-Type: application/json" \782 -H "Content-Type: application/json" \

783 -H "Authorization: Bearer $OPENAI_API_KEY" \783 -H "Authorization: Bearer $OPENAI_API_KEY" \

784 -d '{784 -d '{

785 "model": "gpt-6-astra",785 "model": "gpt-6.2-astra",

786 "input": [786 "input": [

787 {787 {

788 "role": "user",788 "role": "user",


821});821});

822 822 

823const response = await client.responses.create({823const response = await client.responses.create({

824 model: "gpt-6-astra",824 model: "gpt-6.2-astra",

825 input: [825 input: [

826 {826 {

827 role: "user",827 role: "user",


850file = client.files.create(file=open("draconomicon.pdf", "rb"), purpose="user_data")850file = client.files.create(file=open("draconomicon.pdf", "rb"), purpose="user_data")

851 851 

852response = client.responses.create(852response = client.responses.create(

853 model="gpt-6-astra",853 model="gpt-6.2-astra",

854 input=[854 input=[

855 {855 {

856 "role": "user",856 "role": "user",


901 }901 }

902 902 

903 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{903 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

904 Model: "gpt-6-astra",904 Model: "gpt-6.2-astra",

905 Input: responses.ResponseNewParamsInputUnion{905 Input: responses.ResponseNewParamsInputUnion{

906 OfInputItemList: responses.ResponseInputParam{906 OfInputItemList: responses.ResponseInputParam{

907 responses.ResponseInputItemParamOfMessage(907 responses.ResponseInputItemParamOfMessage(


953 .responses()953 .responses()

954 .create(954 .create(

955 ResponseCreateParams.builder()955 ResponseCreateParams.builder()

956 .model("gpt-6-astra")956 .model("gpt-6.2-astra")

957 .inputOfResponse(957 .inputOfResponse(

958 List.of(958 List.of(

959 ResponseInputItem.ofMessage(959 ResponseInputItem.ofMessage(


987);987);

988 988 

989ResponseResult response = await client.CreateResponseAsync(989ResponseResult response = await client.CreateResponseAsync(

990 "gpt-6-astra",990 "gpt-6.2-astra",

991 [991 [

992 ResponseItem.CreateUserMessageItem(992 ResponseItem.CreateUserMessageItem(

993 [993 [


1015)1015)

1016 1016 

1017response = openai.responses.create(1017response = openai.responses.create(

1018 model: "gpt-6-astra",1018 model: "gpt-6.2-astra",

1019 input: [1019 input: [

1020 {1020 {

1021 role: "user",1021 role: "user",


1046 -H "Content-Type: application/json" \1046 -H "Content-Type: application/json" \

1047 -H "Authorization: Bearer $OPENAI_API_KEY" \1047 -H "Authorization: Bearer $OPENAI_API_KEY" \

1048 -d '{1048 -d '{

1049 "model": "gpt-6-astra",1049 "model": "gpt-6.2-astra",

1050 "input": [1050 "input": [

1051 {1051 {

1052 "role": "user",1052 "role": "user",


1094const client = new OpenAI();1094const client = new OpenAI();

1095 1095 

1096const response = await client.responses.create({1096const response = await client.responses.create({

1097 model: "gpt-6-astra",1097 model: "gpt-6.2-astra",

1098 tools: [{ type: "web_search" }],1098 tools: [{ type: "web_search" }],

1099 input: "What was a positive news story from today?",1099 input: "What was a positive news story from today?",

1100});1100});


1108client = OpenAI()1108client = OpenAI()

1109 1109 

1110response = client.responses.create(1110response = client.responses.create(

1111 model="gpt-6-astra",1111 model="gpt-6.2-astra",

1112 tools=[{"type": "web_search"}],1112 tools=[{"type": "web_search"}],

1113 input="What was a positive news story from today?",1113 input="What was a positive news story from today?",

1114)1114)


1130func main() {1130func main() {

1131 client := openai.NewClient()1131 client := openai.NewClient()

1132 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1132 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1133 Model: "gpt-6-astra",1133 Model: "gpt-6.2-astra",

1134 Tools: []responses.ToolUnionParam{1134 Tools: []responses.ToolUnionParam{

1135 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),1135 responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),

1136 },1136 },


1151 1151 

1152ResponseCreateParams params =1152ResponseCreateParams params =

1153 ResponseCreateParams.builder()1153 ResponseCreateParams.builder()

1154 .model("gpt-6-astra")1154 .model("gpt-6.2-astra")

1155 .input("What was a positive news story from today?")1155 .input("What was a positive news story from today?")

1156 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())1156 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

1157 .build();1157 .build();


1170string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1170string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1171ResponsesClient client = new(key);1171ResponsesClient client = new(key);

1172 1172 

1173CreateResponseOptions options = new() { Model = "gpt-6-astra" };1173CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1174options.Tools.Add(ResponseTool.CreateWebSearchTool());1174options.Tools.Add(ResponseTool.CreateWebSearchTool());

1175options.InputItems.Add(1175options.InputItems.Add(

1176 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")1176 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")


1187openai = OpenAI::Client.new1187openai = OpenAI::Client.new

1188 1188 

1189response = openai.responses.create(1189response = openai.responses.create(

1190 model: "gpt-6-astra",1190 model: "gpt-6.2-astra",

1191 tools: [{ type: "web_search" }],1191 tools: [{ type: "web_search" }],

1192 input: "What was a positive news story from today?"1192 input: "What was a positive news story from today?"

1193)1193)


1200 -H "Content-Type: application/json" \1200 -H "Content-Type: application/json" \

1201 -H "Authorization: Bearer $OPENAI_API_KEY" \1201 -H "Authorization: Bearer $OPENAI_API_KEY" \

1202 -d '{1202 -d '{

1203 "model": "gpt-6-astra",1203 "model": "gpt-6.2-astra",

1204 "tools": [{"type": "web_search"}],1204 "tools": [{"type": "web_search"}],

1205 "input": "what was a positive news story from today?"1205 "input": "what was a positive news story from today?"

1206}'1206}'


1208 1208 

1209```bash1209```bash

1210openai responses create \1210openai responses create \

1211 --model gpt-6-astra \1211 --model gpt-6.2-astra \

1212 --raw-output \1212 --raw-output \

1213 --transform 'output.#(type=="message").content.0.text' <<'YAML'1213 --transform 'output.#(type=="message").content.0.text' <<'YAML'

1214tools:1214tools:


1231const openai = new OpenAI();1231const openai = new OpenAI();

1232 1232 

1233const response = await openai.responses.create({1233const response = await openai.responses.create({

1234 model: "gpt-6-astra",1234 model: "gpt-6.2-astra",

1235 input: "What is deep research by OpenAI?",1235 input: "What is deep research by OpenAI?",

1236 tools: [1236 tools: [

1237 {1237 {


1249client = OpenAI()1249client = OpenAI()

1250 1250 

1251response = client.responses.create(1251response = client.responses.create(

1252 model="gpt-6-astra",1252 model="gpt-6.2-astra",

1253 input="What is deep research by OpenAI?",1253 input="What is deep research by OpenAI?",

1254 tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],1254 tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],

1255)1255)


1270func main() {1270func main() {

1271 client := openai.NewClient()1271 client := openai.NewClient()

1272 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1272 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1273 Model: "gpt-6-astra",1273 Model: "gpt-6.2-astra",

1274 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},1274 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},

1275 Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},1275 Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},

1276 })1276 })


1291 1291 

1292ResponseCreateParams params =1292ResponseCreateParams params =

1293 ResponseCreateParams.builder()1293 ResponseCreateParams.builder()

1294 .model("gpt-6-astra")1294 .model("gpt-6.2-astra")

1295 .input("What is deep research by OpenAI?")1295 .input("What is deep research by OpenAI?")

1296 .addFileSearchTool(List.of(vectorStoreId))1296 .addFileSearchTool(List.of(vectorStoreId))

1297 .build();1297 .build();


1311string vectorStoreId = "<vector_store_id>";1311string vectorStoreId = "<vector_store_id>";

1312ResponsesClient client = new(key);1312ResponsesClient client = new(key);

1313 1313 

1314CreateResponseOptions options = new() { Model = "gpt-6-astra" };1314CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1315options.Tools.Add(1315options.Tools.Add(

1316 ResponseTool.CreateFileSearchTool([vectorStoreId])1316 ResponseTool.CreateFileSearchTool([vectorStoreId])

1317);1317);


1330openai = OpenAI::Client.new1330openai = OpenAI::Client.new

1331 1331 

1332response = openai.responses.create(1332response = openai.responses.create(

1333 model: "gpt-6-astra",1333 model: "gpt-6.2-astra",

1334 input: "What is deep research by OpenAI?",1334 input: "What is deep research by OpenAI?",

1335 tools: [1335 tools: [

1336 {1336 {


1357const client = new OpenAI();1357const client = new OpenAI();

1358 1358 

1359const response = await client.responses.create({1359const response = await client.responses.create({

1360 model: "gpt-6-astra",1360 model: "gpt-6.2-astra",

1361 instructions:1361 instructions:

1362 "You are a personal math tutor. When asked a math question, write and run code to answer the question.",1362 "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

1363 tools: [1363 tools: [


1378client = OpenAI()1378client = OpenAI()

1379 1379 

1380response = client.responses.create(1380response = client.responses.create(

1381 model="gpt-6-astra",1381 model="gpt-6.2-astra",

1382 instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.",1382 instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.",

1383 tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],1383 tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],

1384 input="I need to solve the equation 3x + 11 = 14. Can you help me?",1384 input="I need to solve the equation 3x + 11 = 14. Can you help me?",


1401func main() {1401func main() {

1402 client := openai.NewClient()1402 client := openai.NewClient()

1403 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1403 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1404 Model: "gpt-6-astra",1404 Model: "gpt-6.2-astra",

1405 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code to answer the question."),1405 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code to answer the question."),

1406 Tools: []responses.ToolUnionParam{1406 Tools: []responses.ToolUnionParam{

1407 responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{}),1407 responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{}),


1423 1423 

1424ResponseCreateParams params =1424ResponseCreateParams params =

1425 ResponseCreateParams.builder()1425 ResponseCreateParams.builder()

1426 .model("gpt-6-astra")1426 .model("gpt-6.2-astra")

1427 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")1427 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")

1428 .instructions(1428 .instructions(

1429 "You are a personal math tutor. When asked a math question, write and run code to answer the question.")1429 "You are a personal math tutor. When asked a math question, write and run code to answer the question.")


1450);1450);

1451CreateResponseOptions options = new()1451CreateResponseOptions options = new()

1452{1452{

1453 Model = "gpt-6-astra",1453 Model = "gpt-6.2-astra",

1454 Instructions = "You are a personal math tutor. Write and run code to answer math questions.",1454 Instructions = "You are a personal math tutor. Write and run code to answer math questions.",

1455};1455};

1456options.Tools.Add(ResponseTool.CreateCodeInterpreterTool(container));1456options.Tools.Add(ResponseTool.CreateCodeInterpreterTool(container));


1470openai = OpenAI::Client.new1470openai = OpenAI::Client.new

1471 1471 

1472response = openai.responses.create(1472response = openai.responses.create(

1473 model: "gpt-6-astra",1473 model: "gpt-6.2-astra",

1474 instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.",1474 instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

1475 tools: [1475 tools: [

1476 {1476 {


1489 -H "Content-Type: application/json" \1489 -H "Content-Type: application/json" \

1490 -H "Authorization: Bearer $OPENAI_API_KEY" \1490 -H "Authorization: Bearer $OPENAI_API_KEY" \

1491 -d '{1491 -d '{

1492 "model": "gpt-6-astra",1492 "model": "gpt-6.2-astra",

1493 "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.",1493 "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

1494 "tools": [1494 "tools": [

1495 {1495 {


1535];1535];

1536 1536 

1537const response = await client.responses.create({1537const response = await client.responses.create({

1538 model: "gpt-6-astra",1538 model: "gpt-6.2-astra",

1539 input: [1539 input: [

1540 { role: "user", content: "What is the weather like in Paris today?" },1540 { role: "user", content: "What is the weather like in Paris today?" },

1541 ],1541 ],


1571]1571]

1572 1572 

1573response = client.responses.create(1573response = client.responses.create(

1574 model="gpt-6-astra",1574 model="gpt-6.2-astra",

1575 input=[1575 input=[

1576 {"role": "user", "content": "What is the weather like in Paris today?"},1576 {"role": "user", "content": "What is the weather like in Paris today?"},

1577 ],1577 ],


1609 tool.OfFunction.Description = openai.String("Get current temperature for a given location.")1609 tool.OfFunction.Description = openai.String("Get current temperature for a given location.")

1610 1610 

1611 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1611 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1612 Model: "gpt-6-astra",1612 Model: "gpt-6.2-astra",

1613 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{1613 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

1614 responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),1614 responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),

1615 }},1615 }},


1633 1633 

1634ResponseCreateParams params =1634ResponseCreateParams params =

1635 ResponseCreateParams.builder()1635 ResponseCreateParams.builder()

1636 .model("gpt-6-astra")1636 .model("gpt-6.2-astra")

1637 .input("What is the weather like in Paris today?")1637 .input("What is the weather like in Paris today?")

1638 .addTool(1638 .addTool(

1639 FunctionTool.builder()1639 FunctionTool.builder()


1668string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1668string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1669ResponsesClient client = new(key);1669ResponsesClient client = new(key);

1670 1670 

1671CreateResponseOptions options = new() { Model = "gpt-6-astra" };1671CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1672options.Tools.Add(1672options.Tools.Add(

1673 ResponseTool.CreateFunctionTool(1673 ResponseTool.CreateFunctionTool(

1674 functionName: "get_weather",1674 functionName: "get_weather",


1747]1747]

1748 1748 

1749response = openai.responses.create(1749response = openai.responses.create(

1750 model: "gpt-6-astra",1750 model: "gpt-6.2-astra",

1751 input: [1751 input: [

1752 {1752 {

1753 role: "user",1753 role: "user",


1765 -H "Authorization: Bearer $OPENAI_API_KEY" \1765 -H "Authorization: Bearer $OPENAI_API_KEY" \

1766 -H "Content-Type: application/json" \1766 -H "Content-Type: application/json" \

1767 -d '{1767 -d '{

1768 "model": "gpt-6-astra",1768 "model": "gpt-6.2-astra",

1769 "input": [1769 "input": [

1770 {"role": "user", "content": "What is the weather like in Paris today?"}1770 {"role": "user", "content": "What is the weather like in Paris today?"}

1771 ],1771 ],


1805-H "Content-Type: application/json" \1805-H "Content-Type: application/json" \

1806-H "Authorization: Bearer $OPENAI_API_KEY" \1806-H "Authorization: Bearer $OPENAI_API_KEY" \

1807-d '{1807-d '{

1808 "model": "gpt-6-astra",1808 "model": "gpt-6.2-astra",

1809 "tools": [1809 "tools": [

1810 {1810 {

1811 "type": "mcp",1811 "type": "mcp",


1824const client = new OpenAI();1824const client = new OpenAI();

1825 1825 

1826const resp = await client.responses.create({1826const resp = await client.responses.create({

1827 model: "gpt-6-astra",1827 model: "gpt-6.2-astra",

1828 tools: [1828 tools: [

1829 {1829 {

1830 type: "mcp",1830 type: "mcp",


1847client = OpenAI()1847client = OpenAI()

1848 1848 

1849resp = client.responses.create(1849resp = client.responses.create(

1850 model="gpt-6-astra",1850 model="gpt-6.2-astra",

1851 tools=[1851 tools=[

1852 {1852 {

1853 "type": "mcp",1853 "type": "mcp",


1882 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}1882 tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}

1883 1883 

1884 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1884 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

1885 Model: "gpt-6-astra",1885 Model: "gpt-6.2-astra",

1886 Tools: []responses.ToolUnionParam{tool},1886 Tools: []responses.ToolUnionParam{tool},

1887 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},1887 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")},

1888 })1888 })


1901 1901 

1902ResponseCreateParams params =1902ResponseCreateParams params =

1903 ResponseCreateParams.builder()1903 ResponseCreateParams.builder()

1904 .model("gpt-6-astra")1904 .model("gpt-6.2-astra")

1905 .input(1905 .input(

1906 "Search the OpenAI docs for Responses API streaming and return the relevant links.")1906 "Search the OpenAI docs for Responses API streaming and return the relevant links.")

1907 .addTool(1907 .addTool(


1927string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1927string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1928ResponsesClient client = new(key);1928ResponsesClient client = new(key);

1929 1929 

1930CreateResponseOptions options = new() { Model = "gpt-6-astra" };1930CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };

1931options.Tools.Add(1931options.Tools.Add(

1932 ResponseTool.CreateMcpTool(1932 ResponseTool.CreateMcpTool(

1933 serverLabel: "openai_docs",1933 serverLabel: "openai_docs",


1948openai = OpenAI::Client.new1948openai = OpenAI::Client.new

1949 1949 

1950response = openai.responses.create(1950response = openai.responses.create(

1951 model: "gpt-6-astra",1951 model: "gpt-6.2-astra",

1952 tools: [1952 tools: [

1953 {1953 {

1954 type: "mcp",1954 type: "mcp",


1989const client = new OpenAI();1989const client = new OpenAI();

1990 1990 

1991const stream = await client.responses.create({1991const stream = await client.responses.create({

1992 model: "gpt-6-astra",1992 model: "gpt-6.2-astra",

1993 input: [1993 input: [

1994 {1994 {

1995 role: "user",1995 role: "user",


2010client = OpenAI()2010client = OpenAI()

2011 2011 

2012stream = client.responses.create(2012stream = client.responses.create(

2013 model="gpt-6-astra",2013 model="gpt-6.2-astra",

2014 input=[2014 input=[

2015 {2015 {

2016 "role": "user",2016 "role": "user",


2038func main() {2038func main() {

2039 client := openai.NewClient()2039 client := openai.NewClient()

2040 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{2040 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

2041 Model: "gpt-6-astra",2041 Model: "gpt-6.2-astra",

2042 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},2042 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},

2043 })2043 })

2044 for stream.Next() {2044 for stream.Next() {


2059 2059 

2060ResponseCreateParams params =2060ResponseCreateParams params =

2061 ResponseCreateParams.builder()2061 ResponseCreateParams.builder()

2062 .model("gpt-6-astra")2062 .model("gpt-6.2-astra")

2063 .input("Say 'double bubble bath' ten times fast.")2063 .input("Say 'double bubble bath' ten times fast.")

2064 .build();2064 .build();

2065 2065 


2076ResponsesClient client = new(key);2076ResponsesClient client = new(key);

2077 2077 

2078var responses = client.CreateResponseStreamingAsync(2078var responses = client.CreateResponseStreamingAsync(

2079 "gpt-6-astra",2079 "gpt-6.2-astra",

2080 "Say 'double bubble bath' ten times fast."2080 "Say 'double bubble bath' ten times fast."

2081);2081);

2082 2082 


2095openai = OpenAI::Client.new2095openai = OpenAI::Client.new

2096 2096 

2097stream = openai.responses.stream(2097stream = openai.responses.stream(

2098 model: "gpt-6-astra",2098 model: "gpt-6.2-astra",

2099 input: [2099 input: [

2100 {2100 {

2101 role: "user",2101 role: "user",

Details

188 188 

189## Summarizing and analyzing the transcript with a GPT model189## Summarizing and analyzing the transcript with a GPT model

190 190 

191Pass the transcript to a GPT model through the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). This tutorial demonstrates the still-supported Chat Completions path for existing integrations. For new projects, use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) and start with [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra). The snippets below use a tested model to generate a summary, extract key points and action items, and analyze sentiment.191Pass the transcript to a GPT model through the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). This tutorial demonstrates the still-supported Chat Completions path for existing integrations. For new projects, use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) and start with [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra). The snippets below use a tested model to generate a summary, extract key points and action items, and analyze sentiment.

192 192 

193This tutorial uses a separate model call for each task. You can combine the instructions into one request to reduce calls, but separate prompts make each result easier to tune.193This tutorial uses a separate model call for each task. You can combine the instructions into one request to reduce calls, but separate prompts make each result easier to tune.

194 194 


488 488 

489### Sentiment analysis489### Sentiment analysis

490 490 

491The sentiment helper classifies the discussion as positive, negative, or neutral and explains the assessment. For simpler tasks, try [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra) to see whether it meets your quality target with lower cost and latency.491The sentiment helper classifies the discussion as positive, negative, or neutral and explains the assessment. For simpler tasks, try [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra) to see whether it meets your quality target with lower cost and latency.

492 492 

493```typescript493```typescript

494async function analyzeSentiment(transcription: string) {494async function analyzeSentiment(transcription: string) {

Details

16python -m pip install openai pandas numpy requests beautifulsoup4 tiktoken matplotlib16python -m pip install openai pandas numpy requests beautifulsoup4 tiktoken matplotlib

17```17```

18 18 

19Copy the examples into a Python file or notebook in the order shown and run them in the same working directory.19 

20 

21 

22For Ruby, use Ruby 3.3 with the `openai`, `nokogiri`, `tiktoken_ruby`, and `chunky_png` gems. The [sample dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile) list tested versions.

23 

24 

25 

26 

27Set `OPENAI_API_KEY` for either language.

28 

29Copy the examples into a file or notebook for the selected language in the order shown.

30 

31 

32 

33 

34For Ruby, append all snippets to one `.rb` file and run it in a directory where the script can create `text` and `processed`. Set `CRAWL_URL` to the website to crawl; it defaults to `https://example.com`. Ruby saves the scraped rows in `processed/scraped.csv`, the chunks in `processed/chunks.json`, and the completed index in `processed/embeddings.csv`. Each later step reads the preceding output.

35 

36 

37 

20 38 

21## Setting up a web crawler39## Setting up a web crawler

22 40 


46 64 

47This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages, set the starting URL, and define a subclass of `HTMLParser`.65This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages, set the starting URL, and define a subclass of `HTMLParser`.

48 66 

67Set up the web crawler

68 

49```python69```python

50import requests70import requests

51import re71import re


79 self.hyperlinks.append(attrs["href"])99 self.hyperlinks.append(attrs["href"])

80```100```

81 101 

102```ruby

103require "net/http"

104require "uri"

105require "json"

106require "digest"

107require "csv"

108require "fileutils"

109require "nokogiri"

110 

111class HyperlinkParser

112 attr_reader :hyperlinks

113 

114 def initialize

115 @hyperlinks = []

116 end

117 

118 def feed(html)

119 @hyperlinks.concat(Nokogiri::HTML.parse(html).css("a[href]").map { |anchor| anchor["href"] })

120 end

121end

122```

123 

82 124 

83The next function takes a URL as an argument, opens the URL, and reads the HTML content. Then, it returns all the hyperlinks found on that page.125The next function takes a URL as an argument, opens the URL, and reads the HTML content. Then, it returns all the hyperlinks found on that page.

84 126 

127Extract links from a page

128 

85```python129```python

86# Function to get the hyperlinks from a URL130# Function to get the hyperlinks from a URL

87def get_hyperlinks(url):131def get_hyperlinks(url):


105 return parser.hyperlinks149 return parser.hyperlinks

106```150```

107 151 

152```ruby

153def fetch_page(url, local_domain = nil)

154 uri = URI.parse(url)

155 raise ArgumentError, "Expected an HTTP or HTTPS URL" unless uri.is_a?(URI::HTTP)

156 

157 local_domain ||= uri.authority

158 6.times do |redirect_count|

159 unless uri.authority == local_domain

160 raise ArgumentError, "Expected a same-domain HTTP or HTTPS URL"

161 end

162 

163 response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 10, read_timeout: 10) do |http|

164 http.get(uri.request_uri)

165 end

166 return [uri, response] unless response.is_a?(Net::HTTPRedirection)

167 

168 raise ArgumentError, "Too many redirects" if redirect_count == 5

169 

170 location = response["location"]

171 raise ArgumentError, "Redirect has no location" if location.to_s.empty?

172 

173 target = URI.join(uri.to_s, location)

174 unless target.is_a?(URI::HTTP) && target.authority == local_domain

175 raise ArgumentError, "Expected a same-domain HTTP or HTTPS URL"

176 end

177 

178 uri = target

179 uri.fragment = nil

180 end

181end

182 

183def get_hyperlinks(url)

184 uri, response = fetch_page(url)

185 return [] unless response.is_a?(Net::HTTPSuccess) && response.content_type == "text/html"

186 

187 parser = HyperlinkParser.new

188 parser.feed(response.body)

189 parser.hyperlinks.filter_map do |link|

190 next if link.empty? || link.start_with?("#")

191 

192 begin

193 URI.join(uri.to_s, link).to_s

194 rescue URI::InvalidURIError

195 nil

196 end

197 end

198end

199```

200 

108 201 

109The goal is to crawl through and index only the content that lives under the OpenAI domain. For this purpose, a function that calls the `get_hyperlinks` function but filters out any URLs that are not part of the specified domain is needed.202The goal is to crawl through and index only the content that lives under the OpenAI domain. For this purpose, a function that calls the `get_hyperlinks` function but filters out any URLs that are not part of the specified domain is needed.

110 203 

204Keep links within the target domain

205 

111```python206```python

112# Function to get the hyperlinks from a URL that are within the same domain207# Function to get the hyperlinks from a URL that are within the same domain

113def get_domain_hyperlinks(local_domain, url):208def get_domain_hyperlinks(local_domain, url):


122 return list(links)217 return list(links)

123```218```

124 219 

220```ruby

221def get_domain_hyperlinks(local_domain, url)

222 get_hyperlinks(url).filter_map do |link|

223 next if link.empty? || link.start_with?("#")

224 

225 begin

226 candidate = URI.join(url, link)

227 candidate.fragment = nil

228 candidate.to_s if candidate.is_a?(URI::HTTP) && candidate.authority == local_domain

229 rescue URI::InvalidURIError

230 nil

231 end

232 end.uniq

233end

234```

235 

125 236 

126The `crawl` function is the final step in the web scraping task setup. It keeps track of the visited URLs to avoid repeating the same page, which might be linked across multiple pages on a site. It also extracts the raw text from a page without the HTML tags, and writes the text content into a local .txt file specific to the page.237The `crawl` function is the final step in the web scraping task setup. It keeps track of the visited URLs to avoid repeating the same page, which might be linked across multiple pages on a site. It also extracts the raw text from a page without the HTML tags, and writes the text content into a local .txt file specific to the page.

127 238 

239Crawl the website

240 

128```python241```python

129from hashlib import sha256242from hashlib import sha256

130 243 


200crawl(full_url)313crawl(full_url)

201```314```

202 315 

316```ruby

317def crawl(full_url)

318 initial = URI.parse(full_url)

319 raise ArgumentError, "Expected an HTTP or HTTPS URL" unless initial.is_a?(URI::HTTP)

320 

321 local_domain = initial.authority or raise ArgumentError, "URL has no host"

322 initial.path = "/" if initial.path.to_s.empty?

323 queue = [initial.to_s]

324 seen = Set.new(queue)

325 directory = File.join("text", local_domain)

326 FileUtils.mkdir_p([directory, "processed"])

327 until queue.empty?

328 url = queue.pop

329 uri, response = fetch_page(url, local_domain)

330 next if uri.to_s != url && !seen.add?(uri.to_s)

331 

332 url = uri.to_s

333 puts url

334 

335 page_name = (local_domain + uri.path).tr("/", "_")

336 if uri.query

337 suffix = "##{Digest::SHA256.hexdigest(url)}"

338 prefix = page_name.byteslice(0, 255 - suffix.bytesize - ".txt".bytesize).to_s.scrub("")

339 page_name = prefix + suffix

340 end

341 response.value

342 text = Nokogiri::HTML.parse(response.body).text

343 File.write(File.join(directory, "#{page_name}.txt"), text)

344 get_domain_hyperlinks(local_domain, url).each do |link|

345 queue << link if seen.add?(link)

346 end

347 end

348end

349 

350crawl(ENV.fetch("CRAWL_URL", "https://example.com"))

351```

352 

203 353 

204The last line of the above example runs the crawler which goes through all the accessible links and turns those pages into text files. This will take a few minutes to run depending on the size and complexity of your site.354The last line of the above example runs the crawler which goes through all the accessible links and turns those pages into text files. This will take a few minutes to run depending on the size and complexity of your site.

205 355 


231 381 

232 382 

233 383 

384Clean the scraped text

385 

234```python386```python

235def remove_newlines(serie):387def remove_newlines(serie):

236 serie = serie.str.replace("\n", " ")388 serie = serie.str.replace("\n", " ")


240 return serie392 return serie

241```393```

242 394 

395```ruby

396def remove_newlines(texts)

397 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }

398end

399```

400 

243 401 

244Converting the text to CSV requires looping through the text files in the text directory created earlier. After opening each file, remove the extra spacing and append the modified text to a list. Then, add the text with the new lines removed to an empty Pandas data frame and write the data frame to a CSV file.402Converting the text to CSV requires looping through the text files in the text directory created earlier. After opening each file, remove the extra spacing and append the modified text to a list. Then, add the text with the new lines removed to an empty Pandas data frame and write the data frame to a CSV file.

245 403 


248 party libraries or other methods useful to get rid of more unnecessary406 party libraries or other methods useful to get rid of more unnecessary

249 characters.407 characters.

250 408 

409Save scraped pages as a dataset

410 

251```python411```python

252from pathlib import Path412from pathlib import Path

253 413 


286df.head()446df.head()

287```447```

288 448 

449```ruby

450require "csv"

451require "fileutils"

452 

453require "uri"

454 

455initial = URI.parse(ENV.fetch("CRAWL_URL", "https://example.com"))

456raise ArgumentError, "Expected an HTTP or HTTPS URL" unless initial.is_a?(URI::HTTP)

457 

458local_domain = initial.authority or raise ArgumentError, "URL has no host"

459directory = File.join("text", local_domain)

460FileUtils.mkdir_p("processed")

461 

462def remove_newlines(texts)

463 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }

464end

465 

466rows = Dir.children(directory).sort.map do |file|

467 page_name = File.basename(file, ".txt")

468 page_name = [local_domain, "#{local_domain}_"].include?(page_name) ? "index" : page_name.delete_prefix("#{local_domain}_")

469 title = page_name.tr("-_", " ").gsub("#update", "")

470 text = remove_newlines([File.read(File.join(directory, file))]).fetch(0)

471 {

472 "fname" => title,

473 "text" => "#{title}. #{text}"

474 }

475end

476CSV.open("processed/scraped.csv", "w") do |csv|

477 csv << ["fname", "text"]

478 rows.each { |row| csv << row.values_at("fname", "text") }

479end

480```

481 

289 482 

290The next step is tokenization after saving the raw text into a CSV file. This process splits the input text into tokens by breaking down the sentences and words. A visual demonstration of this can be seen by [checking out our tokenizer](https://platform.openai.com/tokenizer) in the docs.483The next step is tokenization after saving the raw text into a CSV file. This process splits the input text into tokens by breaking down the sentences and words. A visual demonstration of this can be seen by [checking out our tokenizer](https://platform.openai.com/tokenizer) in the docs.

291 484 


293 486 

294The API has a limit on the maximum number of input tokens for embeddings. To stay below the limit, the text in the CSV file needs to be broken down into multiple rows. The existing length of each row will be recorded first to identify which rows need to be split.487The API has a limit on the maximum number of input tokens for embeddings. To stay below the limit, the text in the CSV file needs to be broken down into multiple rows. The existing length of each row will be recorded first to identify which rows need to be split.

295 488 

489Count tokens in scraped pages

490 

296```python491```python

297import tiktoken492import tiktoken

298 493 


309df.n_tokens.hist()504df.n_tokens.hist()

310```505```

311 506 

507```ruby

508require "csv"

509require "tiktoken_ruby"

510require "chunky_png"

511 

512tokenizer = Tiktoken.get_encoding("cl100k_base")

513rows = CSV.read("processed/scraped.csv", headers: true)

514counts = rows.map { |row| tokenizer.encode(row.fetch("text")).length }

515histogram = counts.tally

516plot = ChunkyPNG::Image.new(600, 400, ChunkyPNG::Color::WHITE)

517maximum = histogram.values.max || 1

518histogram.sort.each_with_index do |(_token_count, frequency), index|

519 left = 20 + index * 560 / histogram.size

520 right = 20 + (index + 1) * 560 / histogram.size - 1

521 top = 380 - frequency * 360 / maximum

522 plot.rect(left, top, right, 380, ChunkyPNG::Color::BLACK, ChunkyPNG::Color.from_hex("#006400"))

523end

524plot.save("token-histogram.png")

525```

526 

312 527 

313 528 

314 529 


326 541 

327Split longer pages into chunks that fit within the [embedding model’s input limit](https://developers.openai.com/api/docs/models/text-embedding-3-small).542Split longer pages into chunks that fit within the [embedding model’s input limit](https://developers.openai.com/api/docs/models/text-embedding-3-small).

328 543 

544Split long pages into chunks

545 

329```python546```python

330max_tokens = 500547max_tokens = 500

331 548 


376 shortened.append(row[1]["text"])593 shortened.append(row[1]["text"])

377```594```

378 595 

596```ruby

597require "csv"

598require "json"

599require "tiktoken_ruby"

600 

601TOKENIZER = Tiktoken.get_encoding("cl100k_base")

602def split_into_many(text, max_tokens = 500)

603 raise ArgumentError, "text must be a string" unless text.is_a?(String)

604 raise ArgumentError, "max_tokens must be a positive integer" unless max_tokens.is_a?(Integer) && max_tokens.positive?

605 return [] if text.strip.empty?

606 

607 sentences = text.split(". ", -1)

608 chunks = []

609 chunk = ""

610 sentences.each_with_index do |sentence, index|

611 sentence += "." if index < sentences.length - 1

612 if TOKENIZER.encode(sentence).length > max_tokens

613 raise ArgumentError, "A sentence exceeds max_tokens; split it before chunking"

614 end

615 

616 candidate = chunk.empty? ? sentence : "#{chunk} #{sentence}"

617 if TOKENIZER.encode(candidate).length > max_tokens

618 chunks << chunk

619 chunk = sentence

620 else

621 chunk = candidate

622 end

623 end

624 chunks << chunk unless chunk.empty?

625 chunks

626end

627 

628rows = CSV.read("processed/scraped.csv", headers: true)

629texts = rows.map { |row| row.fetch("text") }

630shortened = texts.compact.flat_map { |text| split_into_many(text) }

631File.write("processed/chunks.json", JSON.generate(shortened))

632```

633 

379 634 

380Visualizing the updated histogram again can help to confirm if the rows were successfully split into shortened sections.635Visualizing the updated histogram again can help to confirm if the rows were successfully split into shortened sections.

381 636 

637Visualize token counts after splitting

638 

382```python639```python

383df = pd.DataFrame(shortened, columns=["text"])640df = pd.DataFrame(shortened, columns=["text"])

384df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))641df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))

385df.n_tokens.hist()642df.n_tokens.hist()

386```643```

387 644 

645```ruby

646require "json"

647require "tiktoken_ruby"

648require "chunky_png"

649 

650tokenizer = Tiktoken.get_encoding("cl100k_base")

651shortened = JSON.parse(File.read("processed/chunks.json"))

652counts = shortened.map { |text| tokenizer.encode(text).length }

653histogram = counts.tally

654plot = ChunkyPNG::Image.new(600, 400, ChunkyPNG::Color::WHITE)

655maximum = histogram.values.max || 1

656histogram.sort.each_with_index do |(_token_count, frequency), index|

657 left = 20 + index * 560 / histogram.size

658 right = 20 + (index + 1) * 560 / histogram.size - 1

659 top = 380 - frequency * 360 / maximum

660 plot.rect(left, top, right, 380, ChunkyPNG::Color::BLACK, ChunkyPNG::Color.from_hex("#006400"))

661end

662plot.save("token-histogram.png")

663```

664 

388 665 

389 666 

390 667 


402 679 

403Create an embedding for each chunk with `text-embedding-3-small`. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.680Create an embedding for each chunk with `text-embedding-3-small`. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.

404 681 

682Create embeddings for the scraped text

683 

405```python684```python

406from openai import OpenAI685from openai import OpenAI

407 686 


417df.head()696df.head()

418```697```

419 698 

699```ruby

700require "openai"

701require "csv"

702require "json"

703require "fileutils"

704 

705shortened = JSON.parse(File.read("processed/chunks.json"))

706client = OpenAI::Client.new

707rows = shortened.map do |text|

708 response = client.embeddings.create(input: text, model: "text-embedding-3-small")

709 [text, response.usage.prompt_tokens, JSON.generate(response.data.fetch(0).embedding)]

710end

711FileUtils.mkdir_p("processed")

712CSV.open("processed/embeddings.csv", "w") do |csv|

713 csv << ["text", "n_tokens", "embeddings"]

714 rows.each { |row| csv << row }

715end

716```

717 

420 718 

421This should take about 3-5 minutes but after you will have your embeddings ready to use!719This should take about 3-5 minutes but after you will have your embeddings ready to use!

422 720 


440 738 

441Turning the embeddings into a NumPy array is the first step, which will provide more flexibility in how to use it given the many functions available that operate on NumPy arrays. It will also flatten the dimension to 1-D, which is the required format for many subsequent operations.739Turning the embeddings into a NumPy array is the first step, which will provide more flexibility in how to use it given the many functions available that operate on NumPy arrays. It will also flatten the dimension to 1-D, which is the required format for many subsequent operations.

442 740 

741Load the saved embeddings

742 

443```python743```python

444from ast import literal_eval744from ast import literal_eval

445import numpy as np745import numpy as np


450df.head()750df.head()

451```751```

452 752 

753```ruby

754require "csv"

755require "json"

756 

757path = "processed/embeddings.csv"

758rows = CSV.read(path, headers: true).map do |row|

759 row.to_h.merge("embeddings" => JSON.parse(row.fetch("embeddings")))

760end

761```

762 

453 763 

454Embed the question using the same model you used to build the index. The example computes cosine distances with NumPy and retrieves the closest text chunks.764Embed the question using the same model you used to build the index. The example computes cosine distances with NumPy and retrieves the closest text chunks.

455 765 

766Build context for a question

767 

456```python768```python

457def distances_from_embeddings(query, embeddings, distance_metric="cosine"):769def distances_from_embeddings(query, embeddings, distance_metric="cosine"):

458 if distance_metric != "cosine":770 if distance_metric != "cosine":


498 return "\n\n###\n\n".join(returns)810 return "\n\n###\n\n".join(returns)

499```811```

500 812 

813```ruby

814require "openai"

815require "csv"

816require "json"

817 

818def cosine_distance(query, vector)

819 raise ArgumentError, "Embedding dimensions differ" unless query.length == vector.length

820 

821 dot = query.zip(vector).sum { |a, b| a * b }

822 norm = Math.sqrt(query.sum { |x| x * x } * vector.sum { |x| x * x })

823 raise ArgumentError, "Embedding must have a nonzero norm" unless norm.positive?

824 

825 1.0 - dot / norm

826end

827 

828def create_context(client, question, rows, max_len: 1800)

829 embedding = client.embeddings.create(input: question, model: "text-embedding-3-small").data.fetch(0).embedding

830 ranked = rows.sort_by { |row| cosine_distance(embedding, row.fetch("embeddings")) }

831 length = 0

832 context = []

833 ranked.each do |row|

834 length += Integer(row.fetch("n_tokens")) + 4

835 break if length > max_len

836 

837 context << row.fetch("text")

838 end

839 context.join("\n\n###\n\n")

840end

841```

842 

501 843 

502The `max_len` argument limits how many tokens of retrieved text to include. Pass that text and the question to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) using `gpt-6-luna`. Read the answer from `response.output_text`.844The `max_len` argument limits how many tokens of retrieved text to include. Pass that text and the question to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) using `gpt-6-luna`. Read the answer from `response.output_text`.

503 845 

846Answer a question from the website

847 

504```python848```python

505def answer_question(df, question, max_len=1800):849def answer_question(df, question, max_len=1800):

506 context = create_context(question, df, max_len=max_len)850 context = create_context(question, df, max_len=max_len)


515 return response.output_text.strip()859 return response.output_text.strip()

516```860```

517 861 

862```ruby

863def answer_question(client, rows, question, max_len: 1800)

864 context = create_context(client, question, rows, max_len: max_len)

865 response = client.responses.create(

866 model: "gpt-6-luna",

867 instructions: "Answer the question using only the supplied context. " \

868 "If the context doesn't answer the question, say \"I don't know.\"",

869 input: "Context: #{context}\n\nQuestion: #{question}"

870 )

871 response.output_text.strip

872end

873```

874 

518 875 

519Ask a question the indexed pages can answer, then ask one they cannot. If the index contains a description of ChatGPT, the first call should answer from it. The second should return “I don't know.”876Ask a question the indexed pages can answer, then ask one they cannot. If the index contains a description of ChatGPT, the first call should answer from it. The second should return “I don't know.”

520 877 

878Try example questions

879 

521```python880```python

522print(answer_question(df, "What is ChatGPT?"))881print(answer_question(df, "What is ChatGPT?"))

523print(answer_question(df, "What did I have for breakfast today?"))882print(answer_question(df, "What did I have for breakfast today?"))

524```883```

525 884 

885```ruby

886client = OpenAI::Client.new

887rows = CSV.read("processed/embeddings.csv", headers: true).map do |row|

888 row.to_h.merge("embeddings" => JSON.parse(row.fetch("embeddings")))

889end

890puts answer_question(client, rows, "What is ChatGPT?")

891puts answer_question(client, rows, "What did I have for breakfast today?")

892```

893 

526 894 

527If the system is not able to answer a question that is expected, it is worth searching through the raw text files to see if the information that is expected to be known actually ended up being embedded or not. The crawling process that was done initially was setup to skip sites outside the original domain that was provided, so it might not have that knowledge if there was a subdomain setup.895If the system is not able to answer a question that is expected, it is worth searching through the raw text files to see if the information that is expected to be known actually ended up being embedded or not. The crawling process that was done initially was setup to skip sites outside the original domain that was provided, so it might not have that knowledge if there was a subdomain setup.

528 896