SpyBara
Go Premium

Documentation 2026-07-27 17:02 UTC to 2026-07-28 23:01 UTC

177 files changed +9,431 −3,237. View all changes and history on the product overview
2026
Thu 30 23:58 Wed 29 22:58 Tue 28 23:01 Mon 27 17:02 Sat 25 05:59 Fri 24 19:01 Thu 23 03:02 Wed 22 20:02 Tue 21 15:00 Mon 20 21:59 Sat 18 22:00 Fri 17 19:58 Thu 16 17:00 Wed 15 16:58 Tue 14 21:58 Mon 13 21:58 Sat 11 07:01 Fri 10 23:02 Thu 9 17:03 Wed 8 22:02 Mon 6 22:58 Sat 4 16:59
Details

1# GPT Actions library1# GPT Actions library

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.

4 

3## Purpose5## Purpose

4 6 

5While GPT Actions should be significantly less work for an API developer to set up than an entire application using those APIs from scratch, there’s still some set up required to get GPT Actions up and running. A Library of GPT Actions is meant to provide guidance for building GPT Actions on common applications.7While GPT Actions should be significantly less work for an API developer to set up than an entire application using those APIs from scratch, there’s still some set up required to get GPT Actions up and running. A Library of GPT Actions is meant to provide guidance for building GPT Actions on common applications.

Details

1# GPT Action authentication1# GPT Action authentication

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.

4 

3Actions offer different authentication schemas to accommodate various use cases. To specify the authentication schema for your action, use the GPT editor and select "None", "API Key", or "OAuth".5Actions offer different authentication schemas to accommodate various use cases. To specify the authentication schema for your action, use the GPT editor and select "None", "API Key", or "OAuth".

4 6 

5By default, the authentication method for all actions is set to "None", but you can change this and allow different actions to have different authentication methods.7By default, the authentication method for all actions is set to "None", but you can change this and allow different actions to have different authentication methods.

Details

1# Data retrieval with GPT Actions1# Data retrieval with GPT Actions

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.

4 

3One of the most common tasks an action in a GPT can perform is data retrieval. An action might:5One of the most common tasks an action in a GPT can perform is data retrieval. An action might:

4 6 

51. Access an API to retrieve data based on a keyword search71. Access an API to retrieve data based on a keyword search

Details

1# Getting started with GPT Actions1# Getting started with GPT Actions

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.

4 

3## Weather.gov example5## Weather.gov example

4 6 

5The NSW (National Weather Service) maintains a [public API](https://www.weather.gov/documentation/services-web-api) that users can query to receive a weather forecast for any lat-long point. To retrieve a forecast, there’s 2 steps:7The NSW (National Weather Service) maintains a [public API](https://www.weather.gov/documentation/services-web-api) that users can query to receive a weather forecast for any lat-long point. To retrieve a forecast, there’s 2 steps:

Details

1# GPT Actions1# GPT Actions

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.

4 

3GPT Actions are stored in [Custom GPTs](https://openai.com/blog/introducing-gpts), which enable users to customize ChatGPT for specific use cases by providing instructions, attaching documents as knowledge, and connecting to 3rd party services.5GPT Actions are stored in [Custom GPTs](https://openai.com/blog/introducing-gpts), which enable users to customize ChatGPT for specific use cases by providing instructions, attaching documents as knowledge, and connecting to 3rd party services.

4 6 

5GPT Actions empower ChatGPT users to interact with external applications via RESTful APIs calls outside of ChatGPT simply by using natural language. They convert natural language text into the json schema required for an API call. GPT Actions are usually either used to do [data retrieval](https://developers.openai.com/api/docs/actions/data-retrieval) to ChatGPT (e.g. query a Data Warehouse) or take action in another application (e.g. file a JIRA ticket).7GPT Actions empower ChatGPT users to interact with external applications via RESTful APIs calls outside of ChatGPT simply by using natural language. They convert natural language text into the json schema required for an API call. GPT Actions are usually either used to do [data retrieval](https://developers.openai.com/api/docs/actions/data-retrieval) to ChatGPT (e.g. query a Data Warehouse) or take action in another application (e.g. file a JIRA ticket).

Details

1# Production notes on GPT Actions1# Production notes on GPT Actions

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.

4 

3## Rate limits5## Rate limits

4 6 

5Consider implementing rate limiting on the API endpoints you expose. ChatGPT will respect 429 response codes and dynamically back off from sending requests to your action after receiving a certain number of 429's or 500's in a short period of time.7Consider implementing rate limiting on the API endpoints you expose. ChatGPT will respect 429 response codes and dynamically back off from sending requests to your action after receiving a certain number of 429's or 500's in a short period of time.

Details

1# Sending and returning files with GPT Actions1# Sending and returning files with GPT Actions

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.

4 

3## Sending files5## Sending files

4 6 

5POST requests can include up to ten files (including DALL-E generated images) from the conversation. They will be sent as URLs which are valid for five minutes.7POST requests can include up to ten files (including DALL-E generated images) from the conversation. They will be sent as URLs which are valid for five minutes.

Details

1# Assistants API deep dive1# Assistants API deep dive

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.

4 

5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).

6 

3## Overview7## Overview

4 8 

5Don't start a new integration on the Assistants API. We've announced plans to deprecate it soon, as the Responses API now provides the same features and a more elegant integration.9Don't start a new integration on the Assistants API. We've announced plans to deprecate it soon, as the Responses API now provides the same features and a more elegant integration.

6 10 

7There are several concepts involved in building an app with the Assistants API, covered below in case it helps with your [migration to Responses](https://developers.openai.com/api/docs/guides/assistants/migration).11There are several concepts involved in building an app with the Assistants API, covered below in case it helps with your [migration to Responses](https://developers.openai.com/api/docs/assistants/migration).

8 12 

9## Creating assistants13## Creating assistants

10 14 

11We recommend using OpenAI's <a href="/api/docs/models">latest models</a> with15We recommend using OpenAI's [latest models](https://developers.openai.com/api/docs/models) with

12 the Assistants API for best results and maximum compatibility with tools.16 the Assistants API for best results and maximum compatibility with tools.

13 17 

14To get started, creating an Assistant only requires specifying the `model` to use. But you can further customize the behavior of the Assistant:18To get started, creating an Assistant only requires specifying the `model` to use. But you can further customize the behavior of the Assistant:

15 19 

161. Use the `instructions` parameter to guide the personality of the Assistant and define its goals. Instructions are similar to system messages in the Chat Completions API.201. Use the `instructions` parameter to guide the personality of the Assistant and define its goals. Instructions are similar to system messages in the Chat Completions API.

172. Use the `tools` parameter to give the Assistant access to up to 128 tools. You can give it access to OpenAI built-in tools like `code_interpreter` and `file_search`, or call a third-party tools via a `function` calling.212. Use the `tools` parameter to give the Assistant access to up to 128 tools. You can give it access to OpenAI built-in tools like `code_interpreter` and `file_search`, or call a third-party tools via a `function` calling.

183. Use the `tool_resources` parameter to give the tools like `code_interpreter` and `file_search` access to files. Files are uploaded using the `File` [upload endpoint](https://developers.openai.com/api/docs/api-reference/files/create) and must have the `purpose` set to `assistants` to be used with this API.223. Use the `tool_resources` parameter to give the tools like `code_interpreter` and `file_search` access to files. Files are uploaded using the `File` [upload endpoint](https://developers.openai.com/api/reference/resources/files/methods/create) and must have the `purpose` set to `assistants` to be used with this API.

19 23 

20For example, to create an Assistant that can create data visualization based on a `.csv` file, first upload a file.24For example, to create an Assistant that can create data visualization based on a `.csv` file, first upload a file.

21 25 


85```89```

86 90 

87 91 

88You can attach a maximum of 20 files to `code_interpreter` and 10,000 files to `file_search` (using `vector_store` [objects](https://developers.openai.com/api/docs/api-reference/vector-stores/object)). For vector stores created starting in November 2025, the `file_search` limit is 100,000,000 files.92You can attach a maximum of 20 files to `code_interpreter` and 10,000 files to `file_search` (using `vector_store` [objects](https://developers.openai.com/api/reference/resources/vector_stores)). For vector stores created starting in November 2025, the `file_search` limit is 100,000,000 files.

89 93 

90Each file can be at most 512 MB in size and have a maximum of 5,000,000 tokens. By default, each project can store up to 2.5 TB of files total. There is no organization-wide storage limit. You can reach out to our support team to increase this limit.94Each file can be at most 512 MB in size and have a maximum of 5,000,000 tokens. By default, each project can store up to 2.5 TB of files total. There is no organization-wide storage limit. You can reach out to our support team to increase this limit.

91 95 


152 156 

153### Creating image input content157### Creating image input content

154 158 

155Message content can contain either external image URLs or File IDs uploaded via the [File API](https://developers.openai.com/api/docs/api-reference/files/create). Only [models](https://developers.openai.com/api/docs/models) with Vision support can accept image input. Supported image content types include png, jpg, gif, and webp. When creating image files, pass `purpose="vision"` to allow you to later download and display the input content. Projects are limited to 2.5 TB total file storage, and there is no organization-wide storage limit. Please contact us to request a limit increase.159Message content can contain either external image URLs or File IDs uploaded via the [File API](https://developers.openai.com/api/reference/resources/files/methods/create). Only [models](https://developers.openai.com/api/docs/models) with Vision support can accept image input. Supported image content types include png, jpg, gif, and webp. When creating image files, pass `purpose="vision"` to allow you to later download and display the input content. Projects are limited to 2.5 TB total file storage, and there is no organization-wide storage limit. Please contact us to request a limit increase.

156 160 

157Tools cannot access image content unless specified. To pass image files to Code Interpreter, add the file ID in the message `attachments` list to allow the tool to read and analyze the input. Image URLs cannot be downloaded in Code Interpreter today.161Tools cannot access image content unless specified. To pass image files to Code Interpreter, add the file ID in the message `attachments` list to allow the tool to read and analyze the input. Image URLs cannot be downloaded in Code Interpreter today.

158 162 


349 353 

350### Message annotations354### Message annotations

351 355 

352Messages created by Assistants may contain [`annotations`](https://developers.openai.com/api/docs/api-reference/messages/object#messages/object-content) within the `content` array of the object. Annotations provide information around how you should annotate the text in the Message.356Messages created by Assistants may contain [`annotations`](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/messages#messages/object-content) within the `content` array of the object. Annotations provide information around how you should annotate the text in the Message.

353 357 

354There are two types of Annotations:358There are two types of Annotations:

355 359 


471```475```

472 476 

473 477 

474Note: `tool_resources` associated with the Assistant cannot be overridden during Run creation. You must use the [modify Assistant](https://developers.openai.com/api/docs/api-reference/assistants/modifyAssistant) endpoint to do this.478Note: `tool_resources` associated with the Assistant cannot be overridden during Run creation. You must use the [modify Assistant](https://developers.openai.com/api/reference/resources/beta/subresources/assistants/methods/update) endpoint to do this.

475 479 

476#### Run lifecycle480#### Run lifecycle

477 481 


482| Status | Definition |486| Status | Definition |

483| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |487| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

484| `queued` | When Runs are first created or when you complete the `required_action`, they are moved to a queued status. They should almost immediately move to `in_progress`. |488| `queued` | When Runs are first created or when you complete the `required_action`, they are moved to a queued status. They should almost immediately move to `in_progress`. |

485| `in_progress` | While in_progress, the Assistant uses the model and tools to perform steps. You can view progress being made by the Run by examining the [Run Steps](https://developers.openai.com/api/docs/api-reference/runs/step-object). |489| `in_progress` | While `in_progress`, the Assistant uses the model and tools to perform steps. You can view progress being made by the Run by examining the [Run Steps](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/runs/subresources/steps). |

486| `completed` | The Run successfully completed! You can now view all Messages the Assistant added to the Thread, and all the steps the Run took. You can also continue the conversation by adding more user Messages to the Thread and creating another Run. |490| `completed` | The Run successfully completed! You can now view all Messages the Assistant added to the Thread, and all the steps the Run took. You can also continue the conversation by adding more user Messages to the Thread and creating another Run. |

487| `requires_action` | When using the [Function calling](https://developers.openai.com/api/docs/assistants/tools/function-calling) tool, the Run will move to a `required_action` state once the model determines the names and arguments of the functions to be called. You must then run those functions and [submit the outputs](https://developers.openai.com/api/docs/api-reference/runs/submitToolOutputs) before the run proceeds. If the outputs are not provided before the `expires_at` timestamp passes (roughly 10 mins past creation), the run will move to an expired status. |491| `requires_action` | When using the [Function calling](https://developers.openai.com/api/docs/assistants/tools/function-calling) tool, the Run will move to a `required_action` state once the model determines the names and arguments of the functions to be called. You must then run those functions and [submit the outputs](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/runs/methods/submit_tool_outputs) before the run proceeds. If the outputs are not provided before the `expires_at` timestamp passes (roughly 10 mins past creation), the run will move to an expired status. |

488| `expired` | This happens when the function calling outputs were not submitted before `expires_at` and the run expires. Additionally, if the runs take too long to execute and go beyond the time stated in `expires_at`, our systems will expire the run. |492| `expired` | This happens when the function calling outputs were not submitted before `expires_at` and the run expires. Additionally, if the runs take too long to execute and go beyond the time stated in `expires_at`, our systems will expire the run. |

489| `cancelling` | You can attempt to cancel an `in_progress` run using the [Cancel Run](https://developers.openai.com/api/docs/api-reference/runs/cancelRun) endpoint. Once the attempt to cancel succeeds, status of the Run moves to `cancelled`. Cancellation is attempted but not guaranteed. |493| `cancelling` | You can attempt to cancel an `in_progress` run using the [Cancel Run](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/runs/methods/cancel) endpoint. Once the attempt to cancel succeeds, status of the Run moves to `cancelled`. Cancellation is attempted but not guaranteed. |

490| `cancelled` | Run was successfully cancelled. |494| `cancelled` | Run was successfully cancelled. |

491| `failed` | You can view the reason for the failure by looking at the `last_error` object in the Run. The timestamp for the failure will be recorded under `failed_at`. |495| `failed` | You can view the reason for the failure by looking at the `last_error` object in the Run. The timestamp for the failure will be recorded under `failed_at`. |

492| `incomplete` | Run ended due to `max_prompt_tokens` or `max_completion_tokens` reached. You can view the specific reason by looking at the `incomplete_details` object in the Run. |496| `incomplete` | Run ended due to `max_prompt_tokens` or `max_completion_tokens` reached. You can view the specific reason by looking at the `incomplete_details` object in the Run. |

493 497 

494#### Polling for updates498#### Polling for updates

495 499 

496If you are not using [streaming](https://developers.openai.com/api/docs/assistants/overview#step-4-create-a-run?context=with-streaming), in order to keep the status of your run up to date, you will have to periodically [retrieve the Run](https://developers.openai.com/api/docs/api-reference/runs/getRun) object. You can check the status of the run each time you retrieve the object to determine what your application should do next.500If you are not using [streaming](https://developers.openai.com/api/docs/assistants/migration#step-4-create-a-run?context=with-streaming), in order to keep the status of your run up to date, you will have to periodically [retrieve the Run](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/runs/methods/retrieve) object. You can check the status of the run each time you retrieve the object to determine what your application should do next.

497 501 

498You can optionally use Polling Helpers in our [Node](https://github.com/openai/openai-node?tab=readme-ov-file#polling-helpers) and [Python](https://github.com/openai/openai-python?tab=readme-ov-file#polling-helpers) SDKs to help you with this. These helpers will automatically poll the Run object for you and return the Run object when it's in a terminal state.502You can optionally use Polling Helpers in our [Node](https://github.com/openai/openai-node?tab=readme-ov-file#polling-helpers) and [Python](https://github.com/openai/openai-python?tab=readme-ov-file#polling-helpers) SDKs to help you with this. These helpers will automatically poll the Run object for you and return the Run object when it's in a terminal state.

499 503 

Details

1# Assistants migration guide1# Assistants migration guide

2 2 

3<br />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 

5We're moving from the Assistants API to the new [Responses API](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions) for a simpler and more flexible mental model.5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).

6 6 

7Responses are simpler—send input items and get output items back. With the Responses API, you also get better performance and new features like [deep research](https://developers.openai.com/api/docs/guides/deep-research), [MCP](https://developers.openai.com/api/docs/guides/tools-remote-mcp), and [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use). This change also lets you manage conversations instead of passing back `previous_response_id`.7 

8 

9 

10We're moving from the Assistants API to the new [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for a simpler and more flexible mental model.

11 

12Responses are simpler—send input items and get output items back. With the Responses API, you also get better performance and new features like [deep research](https://developers.openai.com/api/docs/guides/deep-research), [MCP](https://developers.openai.com/api/docs/guides/tools-connectors-mcp), and [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use). This change also lets you manage conversations instead of passing back `previous_response_id`.

8 13 

9### What's changed?14### What's changed?

10 15 


78 83 

79### Response example84### Response example

80 85 

86 

87 

88#### Thread object

89 

90```json

91{

92 "id": "thread_CrXtCzcyEQbkAcXuNmVSKFs1",

93 "object": "thread",

94 "created_at": 1752855924,

95 "metadata": {

96 "user_id": "peter_le_fleur"

97 },

98 "tool_resources": {}

99}

100```

101 

102#### Conversation object

103 

104```json

105{

106 "id": "conv_68542dc602388199a30af27d040cefd4087a04b576bfeb24",

107 "object": "conversation",

108 "created_at": 1752855924,

109 "metadata": {

110 "user_id": "peter_le_fleur"

111 }

112}

113```

114 

115 

116 

81---117---

82 118 

83## From runs to responses119## From runs to responses


90 126 

91### Response example127### Response example

92 128 

93<CodeComparison129 

94 client:load130 

95 snippets={[131#### Run object

96 {132 

97 language: "json",133```json

98 code: `

99{134{

100 "id": "run_FKIpcs5ECSwuCmehBqsqkORj",135 "id": "run_FKIpcs5ECSwuCmehBqsqkORj",

101 "assistant_id": "asst_8fVY45hU3IM6creFkVi5MBKB",136 "assistant_id": "asst_8fVY45hU3IM6creFkVi5MBKB",


140 "tool_resources": {},175 "tool_resources": {},

141 "reasoning_effort": null176 "reasoning_effort": null

142}177}

143`,178```

144 title: "Run object",179 

145 },180#### Response object

146 {181 

147 language: "json",182```json

148 code: `

149{183{

150 "id": "resp_687a7b53036c819baad6012d58b39bcb074adcd9e24850fc",184 "id": "resp_687a7b53036c819baad6012d58b39bcb074adcd9e24850fc",

151 "created_at": 1752857427,185 "created_at": 1752857427,


164 "content": [198 "content": [

165 {199 {

166 "annotations": [],200 "annotations": [],

167 "text": "The \\"5 Ds of Dodgeball\\" are a humorous set of rules made famous by the 2004 comedy film **\\"Dodgeball: A True Underdog Story.\\"** In the movie, dodgeball coach Patches O’Houlihan teaches these basics to his team. The **5 Ds** are:\n\n1. **Dodge**\n2. **Duck**\n3. **Dip**\n4. **Dive**\n5. **Dodge** (yes, dodge is listed twice for emphasis!)\n\nIn summary: \n> **“If you can dodge a wrench, you can dodge a ball!”**\n\nThese 5 Ds are not official competitive rules, but have become a fun and memorable pop culture reference for the sport of dodgeball.",201 "text": "The \"5 Ds of Dodgeball\" are a humorous set of rules made famous by the 2004 comedy film **\"Dodgeball: A True Underdog Story.\"** In the movie, dodgeball coach Patches O’Houlihan teaches these basics to his team. The **5 Ds** are:\n\n1. **Dodge**\n2. **Duck**\n3. **Dip**\n4. **Dive**\n5. **Dodge** (yes, dodge is listed twice for emphasis!)\n\nIn summary: \n> **“If you can dodge a wrench, you can dodge a ball!”**\n\nThese 5 Ds are not official competitive rules, but have become a fun and memorable pop culture reference for the sport of dodgeball.",

168 "type": "output_text",202 "type": "output_text",

169 "logprobs": []203 "logprobs": []

170 }204 }


211 "store": true,245 "store": true,

212 "top_logprobs": 0246 "top_logprobs": 0

213}247}

214`,248```

215 title: "Response object",249 

216 },250 

217 ]}

218/>

219 251 

220---252---

221 253 


292 324 

293 325 

294 326 

295<div data-content-switcher-pane data-value="assistants">327Assistants API

296 <div class="hidden">Assistants API</div>328 

297 ```python329```python

298threads_by_session: dict[str, str] = {}330threads_by_session: dict[str, str] = {}

299 331 

300 332 


332```364```

333 365 

334 366 

335 </div>367

336 <div data-content-switcher-pane data-value="responses" hidden>368 

337 <div class="hidden">Responses API</div>369

338 ```python370 

371

372Responses API

373 

374```python

339conversations_by_session: dict[str, str] = {}375conversations_by_session: dict[str, str] = {}

340 376 

341 377 


354 390 

355 return {"content": response.output_text}391 return {"content": response.output_text}

356```392```

357 

358 

359 </div>

Details

1# Assistants API tools1# Assistants API tools

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.

4 

5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).

6 

3## Overview7## Overview

4 8 

5Assistants created using the Assistants API can be equipped with tools that allow them to perform more complex tasks or interact with your application.9Assistants created using the Assistants API can be equipped with tools that allow them to perform more complex tasks or interact with your application.


9 13 

10 14 

11 15 

12<IconItem title="File Search" className="mt-2">16File Search

13 <span slot="icon">17 

14 </span>18 

19 

15 Built-in RAG tool to process and search through files20 Built-in RAG tool to process and search through files

16 </IconItem>

17 21 

18 22 

19 23 

20 24 

21<IconItem title="Code Interpreter" className="mt-2">25Code Interpreter

22 <span slot="icon">26 

23 </span>27 

28 

24 Write and run python code, process files and diverse data29 Write and run python code, process files and diverse data

25 </IconItem>

26 30 

27 31 

28 32 

29 33 

30<IconItem title="Function Calling" className="mt-2">34Function Calling

31 <span slot="icon">35 

32 </span>36 

37 

33 Use your own custom functions to interact with your application38 Use your own custom functions to interact with your application

34 </IconItem>

35 39 

36 40 

37 41 

38## Next steps42## Next steps

39 43 

40- See the API reference to [submit tool outputs](https://developers.openai.com/api/docs/api-reference/runs/submitToolOutputs)44- See the API reference to [submit tool outputs](https://developers.openai.com/api/reference/resources/beta/subresources/threads/subresources/runs/methods/submit_tool_outputs)

41- Build a tool-using assistant with our [Quickstart app](https://github.com/openai/openai-assistants-quickstart)45- Build a tool-using assistant with our [Quickstart app](https://github.com/openai/openai-assistants-quickstart)

Details

1# Assistants Code Interpreter1# Assistants Code Interpreter

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.

4 

5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).

6 

3## Overview7## Overview

4 8 

5Code Interpreter allows Assistants to write and run Python code in a sandboxed execution environment. This tool can process files with diverse data and formatting, and generate files with data and images of graphs. Code Interpreter allows your Assistant to run code iteratively to solve challenging code and math problems. When your Assistant writes code that fails to run, it can iterate on this code by attempting to run different code until the code execution succeeds.9Code Interpreter allows Assistants to write and run Python code in a sandboxed execution environment. This tool can process files with diverse data and formatting, and generate files with data and images of graphs. Code Interpreter allows your Assistant to run code iteratively to solve challenging code and math problems. When your Assistant writes code that fails to run, it can iterate on this code by attempting to run different code until the code execution succeeds.

6 10 

7See a quickstart of how to get started with Code Interpreter [here](https://developers.openai.com/api/docs/assistants/overview#step-1-create-an-assistant?context=with-streaming).11See a quickstart of how to get started with Code Interpreter [here](https://developers.openai.com/api/docs/assistants/migration#step-1-create-an-assistant?context=with-streaming).

8 12 

9## How it works13## How it works

10 14 


109```113```

110 114 

111 115 

112Files can also be passed at the Thread level. These files are only accessible in the specific Thread. Upload the File using the [File upload](https://developers.openai.com/api/docs/api-reference/files/create) endpoint and then pass the File ID as part of the Message creation request:116Files can also be passed at the Thread level. These files are only accessible in the specific Thread. Upload the File using the [File upload](https://developers.openai.com/api/reference/resources/files/methods/create) endpoint and then pass the File ID as part of the Message creation request:

113 117 

114```python118```python

115thread = client.beta.threads.create(119thread = client.beta.threads.create(

Details

1# Assistants Function Calling1# Assistants Function Calling

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.

4 

5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).

6 

3## Overview7## Overview

4 8 

5Similar to the Chat Completions API, the Assistants API supports function calling. Function calling allows you to describe functions to the Assistants API and have it intelligently return the functions that need to be called along with their arguments.9Similar to the Chat Completions API, the Assistants API supports function calling. Function calling allows you to describe functions to the Assistants API and have it intelligently return the functions that need to be called along with their arguments.


195```199```

196 200 

197<figcaption>Run object truncated here for readability</figcaption>201<figcaption>Run object truncated here for readability</figcaption>

198<br />202 

203 

199 204 

200How you initiate a Run and submit `tool_calls` will differ depending on whether you are using streaming or not,205How you initiate a Run and submit `tool_calls` will differ depending on whether you are using streaming or not,

201although in both cases all `tool_calls` need to be submitted at the same time.206although in both cases all `tool_calls` need to be submitted at the same time.


204 209 

205 210 

206 211 

207<div data-content-switcher-pane data-value="streaming">212With streaming

208 <div class="hidden">With streaming</div>213 

209 </div>214

210 <div data-content-switcher-pane data-value="without-streaming" hidden>215 

211 <div class="hidden">Without streaming</div>216For the streaming case, we create an EventHandler class to handle events in the response stream and submit all tool outputs at once with the “submit tool outputs stream” helper in the Python and Node SDKs.

212 </div>217 

218```python

219from typing_extensions import override

220from openai import AssistantEventHandler

221 

222class EventHandler(AssistantEventHandler):

223 @override

224 def on_event(self, event):

225 # Retrieve events that are denoted with 'requires_action'

226 # since these will have our tool_calls

227 if event.event == "thread.run.requires_action":

228 run_id = event.data.id # Retrieve the run ID from the event data

229 self.handle_requires_action(event.data, run_id)

230 

231 def handle_requires_action(self, data, run_id):

232 tool_outputs = []

233 

234 for tool in data.required_action.submit_tool_outputs.tool_calls:

235 if tool.function.name == "get_current_temperature":

236 tool_outputs.append({"tool_call_id": tool.id, "output": "57"})

237 elif tool.function.name == "get_rain_probability":

238 tool_outputs.append({"tool_call_id": tool.id, "output": "0.06"})

239 

240 # Submit all tool_outputs at the same time

241 self.submit_tool_outputs(tool_outputs, run_id)

242 

243 def submit_tool_outputs(self, tool_outputs, run_id):

244 # Use the submit_tool_outputs_stream helper

245 with client.beta.threads.runs.submit_tool_outputs_stream(

246 thread_id=self.current_run.thread_id,

247 run_id=self.current_run.id,

248 tool_outputs=tool_outputs,

249 event_handler=EventHandler(),

250 ) as stream:

251 for text in stream.text_deltas:

252 print(text, end="", flush=True)

253 print()

254 

255with client.beta.threads.runs.stream(

256 thread_id=thread.id,

257 assistant_id=assistant.id,

258 event_handler=EventHandler(),

259) as stream:

260 stream.until_done()

261```

262 

263```javascript

264class EventHandler extends EventEmitter {

265 constructor(client) {

266 super();

267 this.client = client;

268 }

269 

270async onEvent(event) {

271try {

272console.log(event);

273// Retrieve events that are denoted with 'requires_action'

274// since these will have our tool_calls

275if (event.event === "thread.run.requires_action") {

276await this.handleRequiresAction(

277event.data,

278event.data.id,

279event.data.thread_id,

280);

281}

282} catch (error) {

283console.error("Error handling event:", error);

284}

285}

286 

287async handleRequiresAction(data, runId, threadId) {

288try {

289const toolOutputs =

290data.required_action.submit_tool_outputs.tool_calls.map((toolCall) => {

291if (toolCall.function.name === "getCurrentTemperature") {

292return {

293tool_call_id: toolCall.id,

294output: "57",

295};

296} else if (toolCall.function.name === "getRainProbability") {

297return {

298tool_call_id: toolCall.id,

299output: "0.06",

300};

301}

302});

303// Submit all the tool outputs at the same time

304await this.submitToolOutputs(toolOutputs, runId, threadId);

305} catch (error) {

306console.error("Error processing required action:", error);

307}

308}

309 

310async submitToolOutputs(toolOutputs, runId, threadId) {

311try {

312// Use the submitToolOutputsStream helper

313const stream = this.client.beta.threads.runs.submitToolOutputsStream(

314threadId,

315runId,

316{ tool_outputs: toolOutputs },

317);

318for await (const event of stream) {

319this.emit("event", event);

320}

321} catch (error) {

322console.error("Error submitting tool outputs:", error);

323}

324}

325}

326 

327const eventHandler = new EventHandler(client);

328eventHandler.on("event", eventHandler.onEvent.bind(eventHandler));

329 

330const stream = await client.beta.threads.runs.stream(

331threadId,

332{ assistant_id: assistantId },

333eventHandler,

334);

335 

336for await (const event of stream) {

337eventHandler.emit("event", event);

338}

339```

340 

341 

342

343 

344

345 

346

347Without streaming

348 

349

350 

351Runs are asynchronous, which means you'll want to monitor their `status` by polling the Run object until a

352[terminal status](https://developers.openai.com/api/docs/assistants/deep-dive#runs-and-run-steps) is reached. For convenience, the 'create and poll' SDK helpers assist both in

353creating the run and then polling for its completion. Once the Run completes, you can list the

354Messages added to the Thread by the Assistant. Finally, you would retrieve all the `tool_outputs` from

355`required_action` and submit them at the same time to the 'submit tool outputs and poll' helper.

356 

357```python

358run = client.beta.threads.runs.create_and_poll(

359 thread_id=thread.id,

360 assistant_id=assistant.id,

361)

362 

363if run.status == "completed":

364 messages = client.beta.threads.messages.list(thread_id=thread.id)

365 print(messages)

366 

367# Define the list to store tool outputs

368tool_outputs = []

369 

370# Loop through each tool in the required action section

371if run.required_action:

372 for tool in run.required_action.submit_tool_outputs.tool_calls:

373 if tool.function.name == "get_current_temperature":

374 tool_outputs.append({"tool_call_id": tool.id, "output": "57"})

375 elif tool.function.name == "get_rain_probability":

376 tool_outputs.append({"tool_call_id": tool.id, "output": "0.06"})

377 

378# Submit all tool outputs at once after collecting them in a list

379if tool_outputs:

380 try:

381 run = client.beta.threads.runs.submit_tool_outputs_and_poll(

382 thread_id=thread.id,

383 run_id=run.id,

384 tool_outputs=tool_outputs,

385 )

386 print("Tool outputs submitted successfully.")

387 except Exception as e:

388 print("Failed to submit tool outputs:", e)

389else:

390 print("No tool outputs to submit.")

391 

392if run.status == "completed":

393 messages = client.beta.threads.messages.list(thread_id=thread.id)

394 print(messages)

395else:

396 print(run.status)

397```

398 

399```javascript

400const handleRequiresAction = async (run) => {

401 // Check if there are tools that require outputs

402 if (

403 run.required_action &&

404 run.required_action.submit_tool_outputs &&

405 run.required_action.submit_tool_outputs.tool_calls

406 ) {

407 // Loop through each tool in the required action section

408 const toolOutputs = run.required_action.submit_tool_outputs.tool_calls.map(

409 (tool) => {

410 if (tool.function.name === "getCurrentTemperature") {

411 return {

412 tool_call_id: tool.id,

413 output: "57",

414 };

415 } else if (tool.function.name === "getRainProbability") {

416 return {

417 tool_call_id: tool.id,

418 output: "0.06",

419 };

420 }

421 },

422 );

423 

424 // Submit all tool outputs at once after collecting them in a list

425 if (toolOutputs.length > 0) {

426 run = await client.beta.threads.runs.submitToolOutputsAndPoll(

427 thread.id,

428 run.id,

429 { tool_outputs: toolOutputs },

430 );

431 console.log("Tool outputs submitted successfully.");

432 } else {

433 console.log("No tool outputs to submit.");

434 }

435 

436 // Check status after submitting tool outputs

437 return handleRunStatus(run);

438 

439}

440};

441 

442const handleRunStatus = async (run) => {

443// Check if the run is completed

444if (run.status === "completed") {

445let messages = await client.beta.threads.messages.list(thread.id);

446console.log(messages.data);

447return messages.data;

448} else if (run.status === "requires_action") {

449console.log(run.status);

450return await handleRequiresAction(run);

451} else {

452console.error("Run did not complete:", run);

453}

454};

455 

456// Create and poll run

457let run = await client.beta.threads.runs.createAndPoll(thread.id, {

458assistant_id: assistant.id,

459});

460 

461handleRunStatus(run);

462```

213 463 

214 464 

215 465 

bots.md +27 −6

Details

1# Overview of OpenAI Crawlers1# Overview of OpenAI Crawlers

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.

4 

3OpenAI uses web crawlers (“robots”) and user agents to perform actions for its products, either automatically or triggered by user request. OpenAI uses OAI-SearchBot and GPTBot robots.txt tags to enable webmasters to manage how their sites and content work with AI. Each setting is independent of the others – for example, a webmaster can allow OAI-SearchBot in order to appear in search results while disallowing GPTBot to indicate that crawled content should not be used for training OpenAI’s generative AI foundation models. If your site has allowed both bots, we may use the results from just one crawl for both use cases to avoid duplicative crawling. For search results, please note it can take ~24 hours from a site’s robots.txt update for our systems to adjust.5OpenAI uses web crawlers (“robots”) and user agents to perform actions for its products, either automatically or triggered by user request. OpenAI uses OAI-SearchBot and GPTBot robots.txt tags to enable webmasters to manage how their sites and content work with AI. Each setting is independent of the others – for example, a webmaster can allow OAI-SearchBot in order to appear in search results while disallowing GPTBot to indicate that crawled content should not be used for training OpenAI’s generative AI foundation models. If your site has allowed both bots, we may use the results from just one crawl for both use cases to avoid duplicative crawling. For search results, please note it can take ~24 hours from a site’s robots.txt update for our systems to adjust.

4 6 

5<div className="docs-models-toc">7 

8 

6 | User agent | Description & details |9 | User agent | Description & details |

7 | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |10 | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |

8 | OAI-SearchBot | OAI-SearchBot is for search. OAI-SearchBot is used to surface websites in search results in ChatGPT's search features. Sites that are opted out of OAI-SearchBot will not be shown in ChatGPT search answers, though can still appear as navigational links. To help ensure your site appears in search results, we recommend allowing OAI-SearchBot in your site’s robots.txt file and allowing requests from our published IP ranges below. <br/><br/>Example user-agent string (the version number may change): `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.4; +https://openai.com/searchbot` <br/><br/>When fetching robots.txt files, we may use a user-agent string with an additional `robots.txt` marker. The marker helps site owners more easily distinguish requests for the robots.txt file from requests for other resources, especially when their logs do not include paths: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.4; robots.txt; +https://openai.com/searchbot` <br/><br/>Published IP addresses: https://openai.com/searchbot.json11 | OAI-SearchBot | OAI-SearchBot is for search. OAI-SearchBot is used to surface websites in search results in ChatGPT's search features. Sites that are opted out of OAI-SearchBot will not be shown in ChatGPT search answers, though can still appear as navigational links. To help ensure your site appears in search results, we recommend allowing OAI-SearchBot in your site’s robots.txt file and allowing requests from our published IP ranges below.

9 | OAI-AdsBot | OAI-AdsBot is used to validate the safety of web pages submitted as ads on ChatGPT. When you submit an ad, OpenAI may visit the landing page to ensure it complies with our policies. We may also use content from the landing page to determine when it's most relevant to show the ad to users. OAI-AdsBot only visits pages submitted as ads, and the data collected by OAI-AdsBot is not used to train generative AI foundation models. <br/><br/>Full user-agent string: `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-AdsBot/1.0; +https://openai.com/adsbot` <br/><br/>Published IP addresses: https://openai.com/adsbot.json12 

10 | GPTBot | GPTBot is used to make our generative AI foundation models more useful and safe. It is used to crawl content that may be used in training our generative AI foundation models. Disallowing GPTBot indicates a site’s content should not be used in training generative AI foundation models. <br/><br/>Example user-agent string (the version number may change): `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.4; +https://openai.com/gptbot` <br/><br/>When fetching robots.txt files, we may add a `robots.txt` marker to the user-agent string to help site owners distinguish those requests from requests for other resources, especially when logs do not include paths. <br/><br/>Published IP addresses: https://openai.com/gptbot.json13Example user-agent string (the version number may change): `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.4; +https://openai.com/searchbot`

11 | ChatGPT-User | OpenAI also uses ChatGPT-User for certain user actions in ChatGPT and [Custom GPTs](https://openai.com/index/introducing-gpts/). When users ask ChatGPT or a CustomGPT a question, it may visit a web page with a ChatGPT-User agent. ChatGPT users may also interact with external applications via [GPT Actions](https://developers.openai.com/api/docs/actions/introduction). ChatGPT-User is not used for crawling the web in an automatic fashion. Because these actions are initiated by a user, robots.txt rules may not apply. ChatGPT-User is not used to determine whether content may appear in Search. Please use OAI-SearchBot in robots.txt for managing Search opt outs and automatic crawl. <br/><br/>Full user-agent string: `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot` <br/><br/>Published IP addresses: https://openai.com/chatgpt-user.json14 

15When fetching robots.txt files, we may use a user-agent string with an additional `robots.txt` marker. The marker helps site owners more easily distinguish requests for the robots.txt file from requests for other resources, especially when their logs do not include paths: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.4; robots.txt; +https://openai.com/searchbot`

16 

17Published IP addresses: https://openai.com/searchbot.json

18 | OAI-AdsBot | OAI-AdsBot is used to validate the safety of web pages submitted as ads on ChatGPT. When you submit an ad, OpenAI may visit the landing page to ensure it complies with our policies. We may also use content from the landing page to determine when it's most relevant to show the ad to users. OAI-AdsBot only visits pages submitted as ads, and the data collected by OAI-AdsBot is not used to train generative AI foundation models.

19 

20Full user-agent string: `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-AdsBot/1.0; +https://openai.com/adsbot`

21 

22Published IP addresses: https://openai.com/adsbot.json

23 | GPTBot | GPTBot is used to make our generative AI foundation models more useful and safe. It is used to crawl content that may be used in training our generative AI foundation models. Disallowing GPTBot indicates a site’s content should not be used in training generative AI foundation models.

24 

25Example user-agent string (the version number may change): `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.4; +https://openai.com/gptbot`

26 

27When fetching robots.txt files, we may add a `robots.txt` marker to the user-agent string to help site owners distinguish those requests from requests for other resources, especially when logs do not include paths.

28 

29Published IP addresses: https://openai.com/gptbot.json

30 | ChatGPT-User | OpenAI also uses ChatGPT-User for certain user actions in ChatGPT and [Custom GPTs](https://openai.com/index/introducing-gpts/). When users ask ChatGPT or a CustomGPT a question, it may visit a web page with a ChatGPT-User agent. ChatGPT users may also interact with external applications via [GPT Actions](https://developers.openai.com/api/docs/actions/introduction). ChatGPT-User is not used for crawling the web in an automatic fashion. Because these actions are initiated by a user, robots.txt rules may not apply. ChatGPT-User is not used to determine whether content may appear in Search. Please use OAI-SearchBot in robots.txt for managing Search opt outs and automatic crawl.

31 

32Full user-agent string: `Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot`

12 33 

13</div>34Published IP addresses: https://openai.com/chatgpt-user.json

concepts.md +4 −2

Details

1# Key concepts1# Key concepts

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.

4 

3At OpenAI, protecting user data is fundamental to our mission. We do not train5At OpenAI, protecting user data is fundamental to our mission. We do not train

4 our models on inputs and outputs through our API. Learn more on our 6 our models on inputs and outputs through our API. Learn more on our

5 <a href="https://openai.com/api-data-privacy">API data privacy page</a>.7 [API data privacy page](https://openai.com/api-data-privacy).

6 8 

7## Text generation models9## Text generation models

8 10 

9OpenAI's text generation models (often referred to as generative pre-trained transformers or "GPT" models for short), like [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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-generation) 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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).

10 12 

11## Embeddings13## Embeddings

12 14 

deprecations.md +18 −2

Details

1# Deprecations1# Deprecations

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.

4 

3## Overview5## Overview

4 6 

5As we launch safer and more capable models, we regularly retire older models. Software relying on OpenAI models may need occasional updates to keep working. Impacted customers will always be notified by email and in our documentation along with [blog posts](https://openai.com/blog) for larger changes.7As we launch safer and more capable models, we regularly retire older models. Software relying on OpenAI models may need occasional updates to keep working. Impacted customers will always be notified by email and in our documentation along with [blog posts](https://openai.com/blog) for larger changes.


224 226 

225On August 26th, 2025, we notified developers using the Assistants API of its deprecation and removal from the API one year later, on August 26, 2026.227On August 26th, 2025, we notified developers using the Assistants API of its deprecation and removal from the API one year later, on August 26, 2026.

226 228 

227When we released the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create) in [March 2025](https://developers.openai.com/api/docs/changelog), we announced plans to bring all Assistants API features to the easier to use Responses API, with a sunset date in 2026.229When we released the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) in [March 2025](https://developers.openai.com/api/docs/changelog), we announced plans to bring all Assistants API features to the easier to use Responses API, with a sunset date in 2026.

228 230 

229See the Assistants to Conversations [migration guide](https://developers.openai.com/api/docs/assistants/migration) to learn more about how to migrate your current integration to the Responses API and Conversations API.231See the Assistants to Conversations [migration guide](https://developers.openai.com/api/docs/assistants/migration) to learn more about how to migrate your current integration to the Responses API and Conversations API.

230 232 


310 312 

311### 2024-10-02: Assistants API beta v1313### 2024-10-02: Assistants API beta v1

312 314 

313In [April 2024](https://developers.openai.com/api/docs/assistants/whats-new) when we released the v2 beta version of the Assistants API, we announced that access to the v1 beta would be shut off by the end of 2024. Access to the v1 beta will be discontinued on December 18, 2024.315In [April 2024](https://developers.openai.com/api/docs/assistants/migration) when we released the v2 beta version of the Assistants API, we announced that access to the v1 beta would be shut off by the end of 2024. Access to the v1 beta will be discontinued on December 18, 2024.

314 316 

315See the Assistants API v2 beta [migration guide](https://developers.openai.com/api/docs/assistants/migration) to learn more about how to migrate your tool usage to the latest version of the Assistants API.317See the Assistants API v2 beta [migration guide](https://developers.openai.com/api/docs/assistants/migration) to learn more about how to migrate your tool usage to the latest version of the Assistants API.

316 318 


459| 2022-12-03 | `/v1/search` | [View transition guide](https://help.openai.com/en/articles/6272952-search-transition-guide) |461| 2022-12-03 | `/v1/search` | [View transition guide](https://help.openai.com/en/articles/6272952-search-transition-guide) |

460| 2022-12-03 | `/v1/classifications` | [View transition guide](https://help.openai.com/en/articles/6272941-classifications-transition-guide) |462| 2022-12-03 | `/v1/classifications` | [View transition guide](https://help.openai.com/en/articles/6272941-classifications-transition-guide) |

461| 2022-12-03 | `/v1/answers` | [View transition guide](https://help.openai.com/en/articles/6233728-answers-transition-guide) |463| 2022-12-03 | `/v1/answers` | [View transition guide](https://help.openai.com/en/articles/6233728-answers-transition-guide) |

464 

465### Plain-text aliases

466 

467- computer-use-preview-2025-03-11 | computer-use-preview

468- o3-deep-research-2025-06-26 | o3-deep-research

469- o4-mini-deep-research-2025-06-26 | o4-mini-deep-research

470- gpt-3.5-turbo-0125 | gpt-3.5-turbo, gpt-3.5-turbo-completions

471- gpt-4-0613 | gpt-4, gpt-4-0613-completions, gpt-4-completions

472- gpt-4-turbo | gpt-4-turbo-2024-04-09, gpt-4-turbo-completions

473- gpt-4.1-nano | gpt-4.1-nano-2025-04-14

474- o1-2024-12-17 | o1

475- o1-pro-2025-03-19 | o1-pro

476- o3-mini-2025-01-31 | o3-mini

477- o4-mini-2025-04-16 | o4-mini

Details

1# GPT Release Notes1# GPT Release Notes

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.

4 

3Keep track of updates to OpenAI GPTs. You can also view all of the broader [ChatGPT releases](https://help.openai.com/en/articles/6825453-chatgpt-release-notes) which is used to share new features and capabilities. This page is maintained in a best effort fashion and may not reflect all changes5Keep track of updates to OpenAI GPTs. You can also view all of the broader [ChatGPT releases](https://help.openai.com/en/articles/6825453-chatgpt-release-notes) which is used to share new features and capabilities. This page is maintained in a best effort fashion and may not reflect all changes

4being made.6being made.

5 7 

6### May 13th, 20248### May 13th, 2024

7 9 

8- Actions can [return](https://developers.openai.com/api/docs/actions/getting-started/returning-files) up to 10 files per request to be integrated into the conversation10- Actions can [return](https://developers.openai.com/api/docs/actions/sending-files#returning-files) up to 10 files per request to be integrated into the conversation

9 11 

10### April 8th, 202412### April 8th, 2024

11 13 

12- Files created by Code Interpreter can now be [included](https://developers.openai.com/api/docs/actions/getting-started/sending-files) in POST requests14- Files created by Code Interpreter can now be [included](https://developers.openai.com/api/docs/actions/sending-files#sending-files) in POST requests

13 15 

14### Mar 18th, 202416### Mar 18th, 2024

15 17 


17 19 

18### Mar 15th, 202420### Mar 15th, 2024

19 21 

20- POST requests can [include up to ten files](https://developers.openai.com/api/docs/actions/getting-started/including-files) (including DALL-E generated images) from the conversation22- POST requests can [include up to ten files](https://developers.openai.com/api/docs/actions/sending-files#sending-files) (including DALL-E generated images) from the conversation

21 23 

22### Feb 22nd, 202424### Feb 22nd, 2024

23 25 

Details

1# Admin APIs1# Admin APIs

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.

4 

3Admin APIs let you automate organization management workflows such as user invitations, audit log review, project administration, API key management, spend limits and alerts, data retention, and rate limit operations. Use them for back-office automation, security workflows, and operational tooling that should run outside the dashboard.5Admin APIs let you automate organization management workflows such as user invitations, audit log review, project administration, API key management, spend limits and alerts, data retention, and rate limit operations. Use them for back-office automation, security workflows, and operational tooling that should run outside the dashboard.

4 6 

5For endpoint details, see the [Administration API reference](https://developers.openai.com/api/reference/administration/overview), including [Admin API keys](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys), [Invites](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/invites), [Users](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/users), [Projects](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects), [Spend limits](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/spend_limit), and [Audit logs](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/audit_logs).7For endpoint details, see the [Administration API reference](https://developers.openai.com/api/reference/administration/overview), including [Admin API keys](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys), [Invites](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/invites), [Users](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/users), [Projects](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects), [Spend limits](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/spend_limit), and [Audit logs](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/audit_logs).

Details

1# Advanced usage1# Advanced usage

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.

4 

3OpenAI's text generation models (often called generative pre-trained transformers or large language models) have been trained to understand natural language, code, and images. The models provide text outputs in response to their inputs. The text inputs to these models are also referred to as "prompts." Designing a prompt is essentially how you “program” a large language model, usually by providing instructions or some examples of how to successfully complete a task.5OpenAI's text generation models (often called generative pre-trained transformers or large language models) have been trained to understand natural language, code, and images. The models provide text outputs in response to their inputs. The text inputs to these models are also referred to as "prompts." Designing a prompt is essentially how you “program” a large language model, usually by providing instructions or some examples of how to successfully complete a task.

4 6 

5## Reproducible outputs7## Reproducible outputs

6 8 

7Chat Completions are non-deterministic by default (which means model outputs may differ from request to request). That being said, we offer some control towards deterministic outputs by giving you access to the [`seed`](https://developers.openai.com/api/docs/api-reference/chat/create#chat-create-seed) parameter and the [`system_fingerprint`](https://developers.openai.com/api/docs/api-reference/completions/object#completions/object-system_fingerprint) response field.9Chat Completions are non-deterministic by default (which means model outputs may differ from request to request). That being said, we offer some control towards deterministic outputs by giving you access to the [`seed`](https://developers.openai.com/api/reference/resources/chat#chat-create-seed) parameter and the [`system_fingerprint`](https://developers.openai.com/api/reference/resources/completions#completions/object-system_fingerprint) response field.

8 10 

9To receive (mostly) deterministic outputs across API calls, you can:11To receive (mostly) deterministic outputs across API calls, you can:

10 12 

11- Set the [seed](https://developers.openai.com/api/docs/api-reference/chat/create#chat-create-seed) parameter to any integer of your choice and use the same value across requests you'd like deterministic outputs for.13- Set the [seed](https://developers.openai.com/api/reference/resources/chat#chat-create-seed) parameter to any integer of your choice and use the same value across requests you'd like deterministic outputs for.

12- Ensure all other parameters (like `prompt` or `temperature`) are the exact same across requests.14- Ensure all other parameters (like `prompt` or `temperature`) are the exact same across requests.

13 15 

14Sometimes, determinism may be impacted due to necessary changes OpenAI makes to model configurations on our end. To help you keep track of these changes, we expose the [`system_fingerprint`](https://developers.openai.com/api/docs/api-reference/chat/object#chat/object-system_fingerprint) field. If this value is different, you may see different outputs due to changes we've made on our systems.16Sometimes, determinism may be impacted due to necessary changes OpenAI makes to model configurations on our end. To help you keep track of these changes, we expose the [`system_fingerprint`](https://developers.openai.com/api/reference/resources/chat#chat/object-system_fingerprint) field. If this value is different, you may see different outputs due to changes we've made on our systems.

15 

16<a

17 href="https://cookbook.openai.com/examples/reproducible_outputs_with_the_seed_parameter"

18 target="_blank"

19 rel="noreferrer"

20>

21 17 

18[Deterministic outputs

22 19 

23<span slot="icon">

24 </span>

25 Explore the new seed parameter in the OpenAI cookbook

26 20 

27 21 

28</a>22 Explore the new seed parameter in the OpenAI cookbook](https://developers.openai.com/cookbook/examples/reproducible_outputs_with_the_seed_parameter)

29 23 

30## Managing tokens24## Managing tokens

31 25 


34As 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.

35 29 

36Check out our 30Check out our

37 <a31 [Tokenizer tool](https://platform.openai.com/tokenizer)

38 href="https://platform.openai.com/tokenizer"

39 target="_blank"

40 rel="noreferrer"

41 >

42 Tokenizer tool

43 </a>

44 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.

45 33 

46For 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", "!"]`.


160 148 

161### Frequency and presence penalties149### Frequency and presence penalties

162 150 

163The frequency and presence penalties found in the [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat/create) and [Legacy Completions API](https://developers.openai.com/api/docs/api-reference/completions) can be used to reduce the likelihood of sampling repetitive sequences of tokens.151The frequency and presence penalties found in the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat) and [Legacy Completions API](https://developers.openai.com/api/reference/resources/completions) can be used to reduce the likelihood of sampling repetitive sequences of tokens.

164 152 

165 153 

166 154 


187 175 

188### Token log probabilities176### Token log probabilities

189 177 

190The [`logprobs`](https://developers.openai.com/api/docs/api-reference/chat/create#chat-create-logprobs) parameter found in the [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat/create) and [Legacy Completions API](https://developers.openai.com/api/docs/api-reference/completions), when requested, provides the log probabilities of each output token, and a limited number of the most likely tokens at each token position alongside their log probabilities. This can be useful in some cases to assess the confidence of the model in its output, or to examine alternative responses the model might have given.178The [`logprobs`](https://developers.openai.com/api/reference/resources/chat#chat-create-logprobs) parameter found in the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat) and [Legacy Completions API](https://developers.openai.com/api/reference/resources/completions), when requested, provides the log probabilities of each output token, and a limited number of the most likely tokens at each token position alongside their log probabilities. This can be useful in some cases to assess the confidence of the model in its output, or to examine alternative responses the model might have given.

191 179 

192### Other parameters180### Other parameters

193 181 

Details

1# Agent Builder1# Agent Builder

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.

4 

3**Agent Builder** is a visual canvas for building multi-step agent workflows.5**Agent Builder** is a visual canvas for building multi-step agent workflows.

4 6 

5You can start from templates, drag and drop nodes for each step in your workflow, provide typed inputs and outputs, and preview runs using live data. When you're ready to deploy, embed the workflow into your site with ChatKit, or download the SDK code to run it yourself.7You can start from templates, drag and drop nodes for each step in your workflow, provide typed inputs and outputs, and preview runs using live data. When you're ready to deploy, embed the workflow into your site with ChatKit, or download the SDK code to run it yourself.


21Open Agent Builder23Open Agent Builder

22 24 

23 25 

24<br />26 

25<br />27 

28 

29 

26 30 

27There are three main steps in building agents to handle tasks:31There are three main steps in building agents to handle tasks:

28 32 

Details

1# Safety in building agents1# Safety in building agents

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.

4 

3As you build and deploy agents with [Agent Builder](https://developers.openai.com/api/docs/guides/agent-builder), it's important to understand the risks. Learn about risk types and how to mitigate them when building multi-agent workflows.5As you build and deploy agents with [Agent Builder](https://developers.openai.com/api/docs/guides/agent-builder), it's important to understand the risks. Learn about risk types and how to mitigate them when building multi-agent workflows.

4 6 

5OpenAI is deprecating Agent Builder. Existing users can continue using it7OpenAI is deprecating Agent Builder. Existing users can continue using it

Details

1# Migrate from Agent Builder1# Migrate from Agent Builder

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.

4 

3Use this guide to export an existing Agent Builder workflow as Agents SDK code.5Use this guide to export an existing Agent Builder workflow as Agents SDK code.

4You can use the export to recreate the workflow as a ChatGPT Workspace Agent or6You can use the export to recreate the workflow as a ChatGPT Workspace Agent or

5continue with the Agents SDK in your application.7continue with the Agents SDK in your application.

Details

1# Evaluate agent workflows1# Evaluate agent workflows

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.

4 

3The OpenAI Platform offers a suite of evaluation tools to help you ensure your agents perform consistently and accurately.5The OpenAI Platform offers a suite of evaluation tools to help you ensure your agents perform consistently and accurately.

4 6 

5Use this page as the decision point for the evaluation surfaces that matter most for agent workflows.7Use this page as the decision point for the evaluation surfaces that matter most for agent workflows.


32 34 

33## Related evaluation surfaces35## Related evaluation surfaces

34 36 

35<a37[Getting started with evals: Datasets

36 href="/api/docs/guides/evaluation-getting-started"

37 target="_blank"

38 rel="noreferrer"

39>

40

41 

42<span slot="icon">

43 </span>

44 Operate a flywheel of continuous improvement using evaluations.

45 

46 

47</a>

48 38 

49<a href="/api/docs/guides/evals" target="_blank" rel="noreferrer">

50 39 

51 40 

52<span slot="icon">41 Operate a flywheel of continuous improvement using evaluations.](https://developers.openai.com/api/docs/guides/evaluation-getting-started)

53 </span>

54 Evaluate against external models, interact with evals via API, and more.

55 42 

43[Working with evals

56 44 

57</a>

58 45 

59<a href="/api/docs/guides/prompt-optimizer" target="_blank" rel="noreferrer">

60 46 

47 Evaluate against external models, interact with evals via API, and more.](https://developers.openai.com/api/docs/guides/evals)

61 48 

62<span slot="icon">49[Prompt optimizer

63 </span>

64 Use your dataset to automatically improve your prompts.

65 50 

66 51 

67</a>

68 52 

69<a53 Use your dataset to automatically improve your prompts.](https://developers.openai.com/api/docs/guides/prompt-optimizer)

70 href="https://cookbook.openai.com/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel"

71 target="_blank"

72 rel="noreferrer"

73>

74 54 

55[Cookbook: Building resilient prompts with evals

75 56 

76<span slot="icon">

77 </span>

78 Operate a flywheel of continuous improvement using evaluations.

79 57 

80 58 

81</a>59 Operate a flywheel of continuous improvement using evaluations.](https://developers.openai.com/cookbook/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel)

guides/agents.md +8 −22

Details

1# Agents SDK1# Agents SDK

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.

4 

3Agents are applications that plan, call tools, collaborate across specialists, and keep enough state to complete multi-step work.5Agents are applications that plan, call tools, collaborate across specialists, and keep enough state to complete multi-step work.

4 6 

5## Get your first agent running7## Get your first agent running


10 12 

11Use the GitHub repositories for more examples, issues, and language-specific reference details.13Use the GitHub repositories for more examples, issues, and language-specific reference details.

12 14 

13<div class="not-prose mt-4 grid gap-3">

14 <a

15 href="https://github.com/openai/openai-agents-js"

16 class="block no-underline hover:no-underline"

17 target="_blank"

18 rel="noopener noreferrer"

19 >

20 15 

21 16 

22<span slot="icon">17 [TypeScript SDK

23 </span>18 

24 Open the TypeScript SDK repository on GitHub.19 

25 20 

21 Open the TypeScript SDK repository on GitHub.](https://github.com/openai/openai-agents-js)

22 [Python SDK

26 23 

27 </a>

28 <a

29 href="https://github.com/openai/openai-agents-python"

30 class="block no-underline hover:no-underline"

31 target="_blank"

32 rel="noopener noreferrer"

33 >

34 24 

35 25 

36<span slot="icon">26 Open the Python SDK repository on GitHub.](https://github.com/openai/openai-agents-python)

37 </span>

38 Open the Python SDK repository on GitHub.

39 27 

40 28 

41 </a>

42</div>

43 29 

44## Choose your starting point30## Choose your starting point

45 31 

Details

1# Agent definitions1# Agent definitions

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.

4 

3An agent is the core unit of an SDK-based workflow. It packages a model, instructions, and optional runtime behavior such as tools, guardrails, MCP servers, handoffs, and structured outputs.5An agent is the core unit of an SDK-based workflow. It packages a model, instructions, and optional runtime behavior such as tools, guardrails, MCP servers, handoffs, and structured outputs.

4 6 

5## What belongs on an agent7## What belongs on an agent


13| `prompt` | Stored prompt configuration for Responses-based runs | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models) |15| `prompt` | Stored prompt configuration for Responses-based runs | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models) |

14| `model` and model settings | Choosing the model and tuning behavior | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models) |16| `model` and model settings | Choosing the model and tuning behavior | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models) |

15| `tools` | Capabilities the agent can call directly | [Using tools](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk) |17| `tools` | Capabilities the agent can call directly | [Using tools](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk) |

16| | Hinting when another agent should delegate here | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration) |18| `handoffDescription` in TypeScript or `handoff_description` in Python | Hinting when another agent should delegate here | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration) |

17| `handoffs` | Delegating to another agent | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration) |19| `handoffs` | Delegating to another agent | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration) |

18| | Returning structured output instead of plain text | This page |20| `outputType` in TypeScript or `output_type` in Python | Returning structured output instead of plain text | This page |

19| Guardrails and approvals | Validation, blocking, and review flows | [Guardrails and human review](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals) |21| Guardrails and approvals | Validation, blocking, and review flows | [Guardrails and human review](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals) |

20| MCP servers and hosted MCP tools | Attaching MCP-backed capabilities | [Integrations and observability](https://developers.openai.com/api/docs/guides/agents/integrations-observability#mcp) |22| MCP servers and hosted MCP tools | Attaching MCP-backed capabilities | [Integrations and observability](https://developers.openai.com/api/docs/guides/agents/integrations-observability#mcp) |

21 23 


70Three configuration choices deserve extra care:72Three configuration choices deserve extra care:

71 73 

72- Start with static `instructions`. When the guidance depends on the current user, tenant, or runtime context, switch to a dynamic instructions callback instead of stitching strings together at the call site.74- Start with static `instructions`. When the guidance depends on the current user, tenant, or runtime context, switch to a dynamic instructions callback instead of stitching strings together at the call site.

73- Keep short and concrete so routing agents know when to pick this specialist.75- Keep `handoffDescription` in TypeScript or `handoff_description` in Python short and concrete so routing agents know when to pick this specialist.

74- Use when downstream code needs typed data rather than free-form prose.76- Use `outputType` in TypeScript or `output_type` in Python when downstream code needs typed data rather than free-form prose.

75 77 

76Return structured output78Return structured output

77 79 


227 229 

228Once one specialist is defined cleanly, move to the guide that matches the next design question.230Once one specialist is defined cleanly, move to the guide that matches the next design question.

229 231 

230<div class="not-prose mt-4 grid gap-3">

231 <a

232 href="/api/docs/guides/agents/models"

233 class="block no-underline hover:no-underline"

234 >

235

236 

237<span slot="icon">

238 </span>

239 Choose models, defaults, and transport strategy for this agent.

240 232 

241 233 

242 </a>234 [Models and providers

243 <a

244 href="/api/docs/guides/tools#usage-in-the-agents-sdk"

245 class="block no-underline hover:no-underline"

246 >

247 235 

248 236 

249<span slot="icon">

250 </span>

251 Add capabilities the agent can call directly.

252 237 

238 Choose models, defaults, and transport strategy for this agent.](https://developers.openai.com/api/docs/guides/agents/models)

239 [Using tools

253 240 

254 </a>

255 <a

256 href="/api/docs/guides/agents/orchestration"

257 class="block no-underline hover:no-underline"

258 >

259 241 

260 242 

261<span slot="icon">243 Add capabilities the agent can call directly.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)

262 </span>244 [Orchestration and handoffs

263 Choose how specialists collaborate once one agent is no longer enough.

264 245 

265 246 

266 </a>

267 <a

268 href="/api/docs/guides/agents/running-agents"

269 class="block no-underline hover:no-underline"

270 >

271 247 

248 Choose how specialists collaborate once one agent is no longer enough.](https://developers.openai.com/api/docs/guides/agents/orchestration)

249 [Running agents

272 250 

273<span slot="icon">

274 </span>

275 Understand the runtime loop, state, and streaming behavior.

276 251 

277 252 

278 </a>253 Understand the runtime loop, state, and streaming behavior.](https://developers.openai.com/api/docs/guides/agents/running-agents)

279</div>

Details

1# Guardrails and human review1# Guardrails and human review

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.

4 

3Use guardrails for automatic checks and human review for approval decisions. Together, they define when a run should continue, pause, or stop.5Use guardrails for automatic checks and human review for approval decisions. Together, they define when a run should continue, pause, or stop.

4 6 

5- **Guardrails** validate input, output, or tool behavior automatically.7- **Guardrails** validate input, output, or tool behavior automatically.


196```198```

197 199 

198 200 

199This same interruption pattern applies even when the approving tool lives deeper in the workflow, such as after a handoff or inside a nested call.201This same interruption pattern applies even when the approving tool lives deeper in the workflow, such as after a handoff or inside a nested `agent.asTool()` in TypeScript or `agent.as_tool()` in Python call.

200 202 

201## Approval lifecycle203## Approval lifecycle

202 204 


227 229 

228Once the control boundaries are clear, continue with the guide that covers the runtime or tool surface around them.230Once the control boundaries are clear, continue with the guide that covers the runtime or tool surface around them.

229 231 

230<div class="not-prose mt-4 grid gap-3">

231 <a

232 href="/api/docs/guides/agents/running-agents"

233 class="block no-underline hover:no-underline"

234 >

235

236 232 

237<span slot="icon">

238 </span>

239 See how interruptions and resumptions fit into the runtime loop.

240 233 

234 [Running agents

241 235 

242 </a>

243 <a

244 href="/api/docs/guides/agents/results"

245 class="block no-underline hover:no-underline"

246 >

247 236 

248 237 

249<span slot="icon">238 See how interruptions and resumptions fit into the runtime loop.](https://developers.openai.com/api/docs/guides/agents/running-agents)

250 </span>239 [Results and state

251 Learn which result surfaces paused runs return to your application.

252 240 

253 241 

254 </a>

255 <a

256 href="/api/docs/guides/tools#usage-in-the-agents-sdk"

257 class="block no-underline hover:no-underline"

258 >

259 242 

243 Learn which result surfaces paused runs return to your application.](https://developers.openai.com/api/docs/guides/agents/results)

244 [Using tools

260 245 

261<span slot="icon">

262 </span>

263 Decide which tool surfaces need validation or approval before side effects

264 happen.

265 246 

266 247 

267 </a>248 Decide which tool surfaces need validation or approval before side effects

268</div>249 happen.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)

Details

1# Integrations and observability1# Integrations and observability

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.

4 

3After the workflow shape is clear, the next questions are which external surfaces should live inside the agent loop and how you will inspect what actually happened at runtime.5After the workflow shape is clear, the next questions are which external surfaces should live inside the agent loop and how you will inspect what actually happened at runtime.

4 6 

5## Choose what lives in the SDK7## Choose what lives in the SDK


190 192 

191Once the external surfaces are wired in, continue with the guide that covers capability design, review boundaries, or evaluation.193Once the external surfaces are wired in, continue with the guide that covers capability design, review boundaries, or evaluation.

192 194 

193<div class="not-prose mt-4 grid gap-3">

194 <a

195 href="/api/docs/guides/tools#usage-in-the-agents-sdk"

196 class="block no-underline hover:no-underline"

197 >

198

199 195 

200<span slot="icon">

201 </span>

202 See how hosted tools, function tools, and agents-as-tools fit beside MCP.

203 196 

197 [Using tools

204 198 

205 </a>

206 <a

207 href="/api/docs/guides/agents/guardrails-approvals"

208 class="block no-underline hover:no-underline"

209 >

210 199 

211 200 

212<span slot="icon">201 See how hosted tools, function tools, and agents-as-tools fit beside MCP.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)

213 </span>202 [Guardrails and human review

214 Add approval or validation boundaries around sensitive capabilities.

215 203 

216 204 

217 </a>

218 <a

219 href="/api/docs/guides/agent-evals"

220 class="block no-underline hover:no-underline"

221 >

222 205 

206 Add approval or validation boundaries around sensitive capabilities.](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals)

207 [Agent workflow evaluation

223 208 

224<span slot="icon">

225 </span>

226 Move from one-off traces into repeatable grading once behavior stabilizes.

227 209 

228 210 

229 </a>211 Move from one-off traces into repeatable grading once behavior stabilizes.](https://developers.openai.com/api/docs/guides/agent-evals)

230</div>

Details

1# Models and providers1# Models and providers

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.

4 

3Every SDK run eventually resolves a model and a transport. Most applications should keep that setup straightforward: choose models explicitly, use the standard OpenAI path by default, and reach for provider or transport overrides only when the workflow actually needs them.5Every SDK run eventually resolves a model and a transport. Most applications should keep that setup straightforward: choose models explicitly, use the standard OpenAI path by default, and reach for provider or transport overrides only when the workflow actually needs them.

4 6 

5## Start with explicit model selection7## Start with explicit model selection


72```74```

73 75 

74 76 

75For most new SDK workflows, start with [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) and move to a smaller variant only when latency or cost matters enough to justify it. Use the platform-wide <a href="/api/docs/guides/latest-model">Model guidance</a> page for current model-selection advice.77For most new SDK workflows, start with [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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.

76 78 

77## Choose the simplest default strategy79## Choose the simplest default strategy

78 80 


104 106 

105Model choice is only part of the runtime contract.107Model choice is only part of the runtime contract.

106 108 

107- Use for tuning such as reasoning effort, verbosity, and tool behavior.109- Use `modelSettings` in TypeScript or `model_settings` in Python for tuning such as reasoning effort, verbosity, and tool behavior.

108- Use `prompt` when you want a stored prompt configuration to control the run instead of embedding the full system prompt in code.110- Use `prompt` when you want a stored prompt configuration to control the run instead of embedding the full system prompt in code.

109- Some SDK features depend on the OpenAI Responses path rather than older compatibility surfaces, so check the SDK docs when you need advanced tool-loading or transport features.111- Some SDK features depend on the OpenAI Responses path rather than older compatibility surfaces, so check the SDK docs when you need advanced tool-loading or transport features.

110 112 


114 116 

115Once the runtime contract is clear, continue with the guide that matches the rest of the workflow design.117Once the runtime contract is clear, continue with the guide that matches the rest of the workflow design.

116 118 

117<div class="not-prose mt-4 grid gap-3">

118 <a

119 href="/api/docs/guides/agents/define-agents"

120 class="block no-underline hover:no-underline"

121 >

122

123 119 

124<span slot="icon">

125 </span>

126 Keep model choices aligned with the responsibilities of each specialist.

127 120 

121 [Agent definitions

128 122 

129 </a>

130 <a

131 href="/api/docs/guides/agents/running-agents"

132 class="block no-underline hover:no-underline"

133 >

134 123 

135 124 

136<span slot="icon">125 Keep model choices aligned with the responsibilities of each specialist.](https://developers.openai.com/api/docs/guides/agents/define-agents)

137 </span>126 [Running agents

138 See how transport and model choices affect the runtime loop.

139 127 

140 128 

141 </a>

142 <a

143 href="/api/docs/guides/external-models"

144 class="block no-underline hover:no-underline"

145 >

146 129 

130 See how transport and model choices affect the runtime loop.](https://developers.openai.com/api/docs/guides/agents/running-agents)

131 [External models

147 132 

148<span slot="icon">

149 </span>

150 Compare broader provider options when a mixed-model stack matters.

151 133 

152 134 

153 </a>135 Compare broader provider options when a mixed-model stack matters.](https://developers.openai.com/api/docs/guides/external-models)

154</div>

Details

1# Orchestration and handoffs1# Orchestration and handoffs

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.

4 

3Multi-agent workflows are useful when specialists should own different parts of the job. The first design choice is deciding who owns the final user-facing answer at each branch of the workflow.5Multi-agent workflows are useful when specialists should own different parts of the job. The first design choice is deciding who owns the final user-facing answer at each branch of the workflow.

4 6 

5## Choose the orchestration pattern7## Choose the orchestration pattern


43Keep the routing surface legible:45Keep the routing surface legible:

44 46 

45- Give each specialist a narrow job.47- Give each specialist a narrow job.

46- Keep short and concrete.48- Keep `handoffDescription` in TypeScript or `handoff_description` in Python short and concrete.

47- Split only when the next branch truly needs different instructions, tools, or policy.49- Split only when the next branch truly needs different instructions, tools, or policy.

48 50 

49At the advanced end, handoffs can also carry structured metadata or filtered history. Those exact APIs stay in the SDK docs because the wiring differs by language.51At the advanced end, handoffs can also carry structured metadata or filtered history. Those exact APIs stay in the SDK docs because the wiring differs by language.

50 52 

51## Use agents as tools for manager-style workflows53## Use agents as tools for manager-style workflows

52 54 

53Use when the main agent should stay responsible for the final answer and call specialists as helpers.55Use `agent.asTool()` in TypeScript or `agent.as_tool()` in Python when the main agent should stay responsible for the final answer and call specialists as helpers.

54 56 

55Call a specialist as a tool57Call a specialist as a tool

56 58 


109 111 

110Once the ownership pattern is clear, continue with the guide that covers the adjacent runtime or state question.112Once the ownership pattern is clear, continue with the guide that covers the adjacent runtime or state question.

111 113 

112<div class="not-prose mt-4 grid gap-3">

113 <a

114 href="/api/docs/guides/agents/define-agents"

115 class="block no-underline hover:no-underline"

116 >

117

118 114 

119<span slot="icon">

120 </span>

121 Refine each specialist's instructions, tools, and output contract.

122 115 

116 [Agent definitions

123 117 

124 </a>

125 <a

126 href="/api/docs/guides/agents/running-agents"

127 class="block no-underline hover:no-underline"

128 >

129 118 

130 119 

131<span slot="icon">120 Refine each specialist's instructions, tools, and output contract.](https://developers.openai.com/api/docs/guides/agents/define-agents)

132 </span>121 [Running agents

133 Understand how handoffs and tools behave inside a run.

134 122 

135 123 

136 </a>

137 <a

138 href="/api/docs/guides/agents/results"

139 class="block no-underline hover:no-underline"

140 >

141 124 

125 Understand how handoffs and tools behave inside a run.](https://developers.openai.com/api/docs/guides/agents/running-agents)

126 [Results and state

142 127 

143<span slot="icon">

144 </span>

145 See how

146 and resumable state affect the next turn.

147 128 

148 129 

149 </a>130 See how

150</div>131 `lastAgent` in TypeScript or `last_agent` in Python

132 and resumable state affect the next turn.](https://developers.openai.com/api/docs/guides/agents/results)

Details

1# Quickstart1# Quickstart

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.

4 

3Use this page when you want the shortest path to a working SDK-based agent. The examples below use the same high-level concepts in both TypeScript and Python: define an agent, run it, then add tools and specialist agents as your workflow grows.5Use this page when you want the shortest path to a working SDK-based agent. The examples below use the same high-level concepts in both TypeScript and Python: define an agent, run it, then add tools and specialist agents as your workflow grows.

4 6 

5## Install the SDK7## Install the SDK


11Create an API Key13Create an API Key

12 14 

13 15 

14<p></p>16 

17 

18 

15 19 

16```bash20```bash

17# TypeScript21# TypeScript


72 76 

73| If you want | Start with |77| If you want | Start with |

74| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |78| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |

75| Keep the full history in your application | |79| Keep the full history in your application | `result.history` in TypeScript or `result.to_input_list()` in Python |

76| Let the SDK load and save history for you | A session |80| Let the SDK load and save history for you | A session |

77| Let OpenAI manage continuation state | A server-managed continuation ID |81| Let OpenAI manage continuation state | A server-managed continuation ID |

78| Resume a run that paused for approval or interruption | , together with `interruptions` |82| Resume a run that paused for approval or interruption | `result.state` in TypeScript or `result.to_state()` in Python, together with `interruptions` |

79 83 

80After handoffs, reuse for the next turn when that specialist should stay in control.84After handoffs, reuse `lastAgent` in TypeScript or `last_agent` in Python for the next turn when that specialist should stay in control.

81 85 

82## Give the agent a tool86## Give the agent a tool

83 87 


227 231 

228Once the first run works, continue with the guide that matches the next capability you want to add.232Once the first run works, continue with the guide that matches the next capability you want to add.

229 233 

230<div class="not-prose mt-4 grid gap-3">

231 <a

232 href="/api/docs/guides/agents/define-agents"

233 class="block no-underline hover:no-underline"

234 >

235

236 

237<span slot="icon">

238 </span>

239 Shape one specialist cleanly before you scale the workflow.

240 234 

241 235 

242 </a>236 [Agent definitions

243 <a

244 href="/api/docs/guides/tools#usage-in-the-agents-sdk"

245 class="block no-underline hover:no-underline"

246 >

247 237 

248 238 

249<span slot="icon">

250 </span>

251 Add hosted tools, function tools, and agents-as-tools.

252 239 

240 Shape one specialist cleanly before you scale the workflow.](https://developers.openai.com/api/docs/guides/agents/define-agents)

241 [Using tools

253 242 

254 </a>

255 <a

256 href="/api/docs/guides/agents/running-agents"

257 class="block no-underline hover:no-underline"

258 >

259 243 

260 244 

261<span slot="icon">245 Add hosted tools, function tools, and agents-as-tools.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)

262 </span>246 [Running agents

263 Learn the agent loop, streaming, and continuation strategies.

264 247 

265 248 

266 </a>

267 <a

268 href="/api/docs/guides/agents/orchestration"

269 class="block no-underline hover:no-underline"

270 >

271 249 

250 Learn the agent loop, streaming, and continuation strategies.](https://developers.openai.com/api/docs/guides/agents/running-agents)

251 [Orchestration and handoffs

272 252 

273<span slot="icon">

274 </span>

275 Decide when specialists should take over the conversation.

276 253 

277 254 

278 </a>255 Decide when specialists should take over the conversation.](https://developers.openai.com/api/docs/guides/agents/orchestration)

279</div>

Details

1# Results and state1# Results and state

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.

4 

3When you run an agent, the result is more than just the final answer. It's also the handoff boundary, the next-turn continuation surface, and the resumable snapshot when a run pauses for review.5When you run an agent, the result is more than just the final answer. It's also the handoff boundary, the next-turn continuation surface, and the resumable snapshot when a run pauses for review.

4 6 

5## Choose the result surface you need7## Choose the result surface you need


8 10 

9| If you need | Use |11| If you need | Use |

10| ---------------------------------------------------- | ----------------------------------------------------------------------------------- |12| ---------------------------------------------------- | ----------------------------------------------------------------------------------- |

11| The final answer to show the user | |13| The final answer to show the user | `finalOutput` in TypeScript or `final_output` in Python |

12| Local replay-ready history | |14| Local replay-ready history | `history` in TypeScript or `to_input_list()` in Python |

13| The specialist that should usually own the next turn | |15| The specialist that should usually own the next turn | `lastAgent` in TypeScript or `last_agent` in Python |

14| OpenAI-managed response chaining | |16| OpenAI-managed response chaining | `lastResponseId` in TypeScript or `last_response_id` in Python |

15| Pending approvals and a resumable snapshot | `interruptions` plus |17| Pending approvals and a resumable snapshot | `interruptions` plus `state` in TypeScript or `to_state()` in Python |

16 18 

17Those are the guide-level surfaces to learn first. Richer run items, raw model responses, and detailed diagnostics still belong in the SDK docs and reference material.19Those are the guide-level surfaces to learn first. Richer run items, raw model responses, and detailed diagnostics still belong in the SDK docs and reference material.

18 20 


20 22 

21Use the result in a way that matches your continuation strategy:23Use the result in a way that matches your continuation strategy:

22 24 

23- If your application owns full local history, reuse .25- If your application owns full local history, reuse `history` in TypeScript or `to_input_list()` in Python.

24- If you are using a session, keep passing the same session and let the SDK load and persist history for you.26- If you are using a session, keep passing the same session and let the SDK load and persist history for you.

25- If you are using server-managed continuation, pass only the new user input and reuse the stored ID instead of replaying the full transcript.27- If you are using server-managed continuation, pass only the new user input and reuse the stored ID instead of replaying the full transcript.

26- After handoffs, reuse when that specialist should stay in control for the next turn.28- After handoffs, reuse `lastAgent` in TypeScript or `last_agent` in Python when that specialist should stay in control for the next turn.

27 29 

28## Interrupted runs return state, not a final answer30## Interrupted runs return state, not a final answer

29 31 

30Approval flows are the main case where a result is intentionally incomplete.32Approval flows are the main case where a result is intentionally incomplete.

31 33 

32- can34- `finalOutput` in TypeScript or `final_output` in Python can

33 stay empty because the run hasn't actually finished.35 stay empty because the run hasn't actually finished.

34- `interruptions` tells you which pending tool calls need a decision.36- `interruptions` tells you which pending tool calls need a decision.

35- is the saved37- `state` in TypeScript or `to_state()` in Python is the saved

36 snapshot you pass back into the runtime after approving or rejecting those38 snapshot you pass back into the runtime after approving or rejecting those

37 items.39 items.

38 40 


48 50 

49Once you know which result surfaces matter, continue with the guide that explains how those surfaces get produced or inspected.51Once you know which result surfaces matter, continue with the guide that explains how those surfaces get produced or inspected.

50 52 

51<div class="not-prose mt-4 grid gap-3">

52 <a

53 href="/api/docs/guides/agents/running-agents"

54 class="block no-underline hover:no-underline"

55 >

56

57 53 

58<span slot="icon">

59 </span>

60 Connect result handling back to the runtime loop and continuation

61 strategy.

62 54 

55 [Running agents

63 56 

64 </a>

65 <a

66 href="/api/docs/guides/agents/guardrails-approvals"

67 class="block no-underline hover:no-underline"

68 >

69 57 

70 58 

71<span slot="icon">59 Connect result handling back to the runtime loop and continuation

72 </span>60 strategy.](https://developers.openai.com/api/docs/guides/agents/running-agents)

73 See how paused runs return interruptions and resumable state.61 [Guardrails and human review

74 62 

75 63 

76 </a>

77 <a

78 href="/api/docs/guides/agents/integrations-observability"

79 class="block no-underline hover:no-underline"

80 >

81 64 

65 See how paused runs return interruptions and resumable state.](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals)

66 [Integrations and observability

82 67 

83<span slot="icon">

84 </span>

85 Use traces when you need to inspect the richer workflow record.

86 68 

87 69 

88 </a>

89</div>

70 Use traces when you need to inspect the richer workflow record.](https://developers.openai.com/api/docs/guides/agents/integrations-observability)

Details

1# Running agents1# Running agents

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.

4 

3Defining an agent is only the setup step. The runtime questions are what a single run does, how the next turn continues, and how the workflow behaves when it pauses for approvals or tool work.5Defining an agent is only the setup step. The runtime questions are what a single run does, how the next turn continues, and how the workflow behaves when it pauses for approvals or tool work.

4 6 

5## The agent loop7## The agent loop


20 22 

21| Strategy | Where state lives | Best for | What you pass on the next turn |23| Strategy | Where state lives | Best for | What you pass on the next turn |

22| ------------------------------------------------------------------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------- |24| ------------------------------------------------------------------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------- |

23| | Your application | Small chat loops and maximum control | The replay-ready history |25| `result.history` in TypeScript or `result.to_input_list()` in Python | Your application | Small chat loops and maximum control | The replay-ready history |

24| `session` | Your storage plus the SDK | Persistent chat state, resumable runs, and storage you control | The same session |26| `session` | Your storage plus the SDK | Persistent chat state, resumable runs, and storage you control | The same session |

25| `conversationId` | OpenAI Conversations API | Shared server-managed state across workers or services | The same conversation ID and only the new turn |27| `conversationId` | OpenAI Conversations API | Shared server-managed state across workers or services | The same conversation ID and only the new turn |

26| | OpenAI Responses API | The lightest server-managed continuation from one response to the next | The last response ID and only the new turn |28| `previousResponseId` in TypeScript or `previous_response_id` in Python | OpenAI Responses API | The lightest server-managed continuation from one response to the next | The last response ID and only the new turn |

27 29 

28In most applications, pick one strategy per conversation. Mixing local replay with server-managed state can duplicate context unless you are deliberately reconciling both layers.30In most applications, pick one strategy per conversation. Mixing local replay with server-managed state can duplicate context unless you are deliberately reconciling both layers.

29 31 


140```142```

141 143 

142 144 

143Use `conversationId` when multiple systems should share one named conversation. Use when you want the cheapest response-to-response continuation option.145Use `conversationId` when multiple systems should share one named conversation. Use `previousResponseId` in TypeScript or `previous_response_id` in Python when you want the cheapest response-to-response continuation option.

144 146 

145## Stream runs incrementally147## Stream runs incrementally

146 148 


225 227 

226Once the runtime loop is clear, move to the guide that matches the next workflow boundary you need to design.228Once the runtime loop is clear, move to the guide that matches the next workflow boundary you need to design.

227 229 

228<div class="not-prose mt-4 grid gap-3">

229 <a

230 href="/api/docs/guides/agents/results"

231 class="block no-underline hover:no-underline"

232 >

233

234 230 

235<span slot="icon">

236 </span>

237 Learn which result surfaces your application should carry into the next

238 turn.

239 231 

232 [Results and state

240 233 

241 </a>

242 <a

243 href="/api/docs/guides/agents/orchestration"

244 class="block no-underline hover:no-underline"

245 >

246 234 

247 235 

248<span slot="icon">236 Learn which result surfaces your application should carry into the next

249 </span>237 turn.](https://developers.openai.com/api/docs/guides/agents/results)

250 Decide how multiple specialists behave inside the same runtime loop.238 [Orchestration and handoffs

251 239 

252 240 

253 </a>

254 <a

255 href="/api/docs/guides/agents/guardrails-approvals"

256 class="block no-underline hover:no-underline"

257 >

258 241 

242 Decide how multiple specialists behave inside the same runtime loop.](https://developers.openai.com/api/docs/guides/agents/orchestration)

243 [Guardrails and human review

259 244 

260<span slot="icon">

261 </span>

262 Add validation and approval pauses without breaking turn continuity.

263 245 

264 246 

265 </a>247 Add validation and approval pauses without breaking turn continuity.](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals)

266</div>

Details

1# Sandbox Agents1# Sandbox Agents

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.

4 

3A sandbox gives an agent an isolated, Unix-like execution environment with a5A sandbox gives an agent an isolated, Unix-like execution environment with a

4filesystem, shell, installed packages, mounted data, exposed ports, snapshots,6filesystem, shell, installed packages, mounted data, exposed ports, snapshots,

5and controlled access to external systems.7and controlled access to external systems.


29credentials and mounts; the harness can keep auth, billing, audit logs, human31credentials and mounts; the harness can keep auth, billing, audit logs, human

30review, and recovery state outside any one container.32review, and recovery state outside any one container.

31 33 

32<div className="not-prose my-8 grid gap-4 lg:grid-cols-2">34 

35 

33 <figure>36 <figure>

34 <figcaption className="mt-3 text-sm text-gray-600 dark:text-gray-400">37 <figcaption className="mt-3 text-sm text-gray-600 dark:text-gray-400">

35 Running the harness inside the sandbox can be convenient for prototypes,38 Running the harness inside the sandbox can be convenient for prototypes,


44 provider-specific, stateful execution.47 provider-specific, stateful execution.

45 </figcaption>48 </figcaption>

46 </figure>49 </figure>

47</div>50 

51 

48 52 

49## When to use a sandbox53## When to use a sandbox

50 54 


711 715 

712| Provider | SDK client | Documentation and examples |716| Provider | SDK client | Documentation and examples |

713| ---------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |717| ---------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

714| Blaxel | `BlaxelSandboxClient` | <a href="https://docs.blaxel.ai/Sandboxes/Overview">Sandbox overview</a> |718| Blaxel | `BlaxelSandboxClient` | [Sandbox overview](https://docs.blaxel.ai/Sandboxes/Overview) |

715| Cloudflare | `CloudflareSandboxClient` | <a href="https://developers.cloudflare.com/sandbox/">Sandbox documentation</a><br /><a href="https://docs.cloudflare.com/sandbox/tutorials/openai-agents/">OpenAI Agents tutorial</a><br /><a href="https://github.com/cloudflare/sandbox-sdk/tree/main/bridge/examples">Sandbox Bridge examples</a> |719| Cloudflare | `CloudflareSandboxClient` | [Sandbox documentation](https://developers.cloudflare.com/sandbox/)<br />[OpenAI Agents tutorial](https://docs.cloudflare.com/sandbox/tutorials/openai-agents/)<br />[Sandbox Bridge examples](https://github.com/cloudflare/sandbox-sdk/tree/main/bridge/examples) |

716| Daytona | `DaytonaSandboxClient` | <a href="https://www.daytona.io/docs/en/sandboxes/">Sandbox documentation</a><br /><a href="https://www.daytona.io/docs/en/guides/openai-agents/openai-agents-sdk-with-sandboxes">OpenAI Agents SDK guide</a> |720| Daytona | `DaytonaSandboxClient` | [Sandbox documentation](https://www.daytona.io/docs/en/sandboxes/)<br />[OpenAI Agents SDK guide](https://www.daytona.io/docs/en/guides/openai-agents/openai-agents-sdk-with-sandboxes) |

717| Docker | `DockerSandboxClient` | <a href="https://docs.docker.com/">Docker documentation</a><br /><a href="https://github.com/openai/openai-agents-js/blob/main/examples/docs/sandbox-agents/docker-client.ts">TypeScript Docker SDK example</a><br /><a href="https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/docker/docker_runner.py">Python Docker SDK example</a> |721| Docker | `DockerSandboxClient` | [Docker documentation](https://docs.docker.com/)<br />[TypeScript Docker SDK example](https://github.com/openai/openai-agents-js/blob/main/examples/docs/sandbox-agents/docker-client.ts)<br />[Python Docker SDK example](https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/docker/docker_runner.py) |

718| E2B | `E2BSandboxClient` | <a href="https://e2b.dev/docs">Sandbox documentation</a><br /><a href="https://e2b.dev/docs/agents/openai-agents-sdk">OpenAI Agents SDK guide</a><br /><a href="https://e2b.dev/blog/e2b-is-now-in-agents-sdk">Launch blog</a> |722| E2B | `E2BSandboxClient` | [Sandbox documentation](https://e2b.dev/docs)<br />[OpenAI Agents SDK guide](https://e2b.dev/docs/agents/openai-agents-sdk)<br />[Launch blog](https://e2b.dev/blog/e2b-is-now-in-agents-sdk) |

719| Modal | `ModalSandboxClient` | <a href="https://modal.com/docs/guide/sandboxes">Sandbox guide</a><br /><a href="https://modal.com/blog/building-with-modal-and-the-openai-agent-sdk">Integration blog</a><br /><a href="https://github.com/modal-labs/openai-agents-python-example">Example repo</a><br /><a href="https://github.com/modal-labs/openai-agents-python-example?tab=readme-ov-file#modal-extension-reference">Modal extension reference</a> |723| Modal | `ModalSandboxClient` | [Sandbox guide](https://modal.com/docs/guide/sandboxes)<br />[Integration blog](https://modal.com/blog/building-with-modal-and-the-openai-agent-sdk)<br />[Example repo](https://github.com/modal-labs/openai-agents-python-example)<br />[Modal extension reference](https://github.com/modal-labs/openai-agents-python-example?tab=readme-ov-file#modal-extension-reference) |

720| Runloop | `RunloopSandboxClient` | <a href="https://docs.runloop.ai/docs/devboxes/overview">Devbox overview</a><br /><a href="https://docs.runloop.ai/docs/devboxes/tunnels">Tunnels</a> |724| Runloop | `RunloopSandboxClient` | [Devbox overview](https://docs.runloop.ai/docs/devboxes/overview)<br />[Tunnels](https://docs.runloop.ai/docs/devboxes/tunnels) |

721| Unix-local | `UnixLocalSandboxClient` | <a href="https://github.com/openai/openai-agents-js/blob/main/examples/docs/sandbox-agents/basic.ts">TypeScript local SDK example</a><br /><a href="https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/unix_local_runner.py">Python local SDK example</a> |725| Unix-local | `UnixLocalSandboxClient` | [TypeScript local SDK example](https://github.com/openai/openai-agents-js/blob/main/examples/docs/sandbox-agents/basic.ts)<br />[Python local SDK example](https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/unix_local_runner.py) |

722| Vercel | `VercelSandboxClient` | <a href="https://vercel.com/docs/vercel-sandbox">Sandbox documentation</a><br /><a href="https://vercel.com/kb/guide/building-an-agent-with-openai-agents-sdk-and-vercel-sandbox">OpenAI Agents SDK guide</a><br /><a href="https://vercel.com/templates/template/openai-agents-sdk-with-fastapi">FastAPI template</a><br /><a href="https://github.com/vercel-labs/openai-agents-fastapi-starter">Sample app</a> |726| Vercel | `VercelSandboxClient` | [Sandbox documentation](https://vercel.com/docs/vercel-sandbox)<br />[OpenAI Agents SDK guide](https://vercel.com/kb/guide/building-an-agent-with-openai-agents-sdk-and-vercel-sandbox)<br />[FastAPI template](https://vercel.com/templates/template/openai-agents-sdk-with-fastapi)<br />[Sample app](https://github.com/vercel-labs/openai-agents-fastapi-starter) |

723 727 

724[sdk-example-agents-as-tools]: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/sandbox_agents_as_tools.py728[sdk-example-agents-as-tools]: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/sandbox_agents_as_tools.py

725[sdk-example-basic]: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/basic.py729[sdk-example-basic]: https://github.com/openai/openai-agents-python/blob/main/examples/sandbox/basic.py

Details

1# OpenAI models in Amazon Bedrock1# OpenAI models in Amazon Bedrock

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.

4 

3Amazon Bedrock makes supported OpenAI models available through AWS-managed5Amazon Bedrock makes supported OpenAI models available through AWS-managed

4infrastructure. This deployment path is useful when your organization wants to6infrastructure. This deployment path is useful when your organization wants to

5keep procurement, identity, regional controls, and related cloud operations in7keep procurement, identity, regional controls, and related cloud operations in

guides/audio.md +16 −12

Details

1# Audio and speech1# Audio and speech

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.

4 

3Audio models can understand spoken input, generate spoken output, or do both in the same interaction. This guide explains the vocabulary used across OpenAI's audio docs. When you're ready to choose an implementation path, start with the [Realtime and audio overview](https://developers.openai.com/api/docs/guides/realtime).5Audio models can understand spoken input, generate spoken output, or do both in the same interaction. This guide explains the vocabulary used across OpenAI's audio docs. When you're ready to choose an implementation path, start with the [Realtime and audio overview](https://developers.openai.com/api/docs/guides/realtime).

4 6 

5## Audio modalities7## Audio modalities


15 17 

16## Common speech tasks18## Common speech tasks

17 19 

18**Speech to text** converts speech into text. Use it for captions, notes, transcripts, analytics, search, and accessibility. Transcription can be request-based for files or streaming for live audio.20**Speech to text** converts speech into text. Use it for captions, notes, transcripts, analytics, search, and accessibility. Transcription can be request-based for files or streaming for live audio. Start with the [Transcription overview](https://developers.openai.com/api/docs/guides/transcription) to choose a workflow and model.

19 21 

20**Text to speech** converts text into spoken audio. Use it for narration, assistants, accessibility, and generated voice responses. Speech generation can stream audio back as the model produces it.22**Text to speech** converts text into spoken audio. Use it for narration, assistants, accessibility, and generated voice responses. Speech generation can stream audio back as the model produces it.

21 23 


35 37 

36| Architecture | Use when | Examples |38| Architecture | Use when | Examples |

37| --------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |39| --------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |

38| Request-based audio APIs | You have a file, a text input, or a bounded request. | [Speech to text](https://developers.openai.com/api/docs/guides/speech-to-text), [text to speech](https://developers.openai.com/api/docs/guides/text-to-speech). |40| Request-based audio APIs | You have a file, a text input, or a bounded request. | [File transcription](https://developers.openai.com/api/docs/guides/speech-to-text), [text to speech](https://developers.openai.com/api/docs/guides/text-to-speech). |

39| Realtime sessions | Audio is live and the app needs low-latency events. | [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents), [translation](https://developers.openai.com/api/docs/guides/realtime-translation), [transcription](https://developers.openai.com/api/docs/guides/realtime-transcription). |41| Realtime sessions | Audio is live and the app needs low-latency events. | [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents), [translation](https://developers.openai.com/api/docs/guides/realtime-translation), [transcription](https://developers.openai.com/api/docs/guides/realtime-transcription). |

40| Multimodal chat completions | You are extending an existing chat flow with audio. | [Audio input or output](#add-audio-to-your-existing-application). |42| Multimodal Chat Completions | You are extending an existing chat flow with audio. | [Audio input or output](#add-audio-to-your-existing-application). |

41 43 

42For build-path guidance, see the [Realtime and audio overview](https://developers.openai.com/api/docs/guides/realtime).44For build-path guidance, see the [Realtime and audio overview](https://developers.openai.com/api/docs/guides/realtime).

43 45 


69 71 

70This example uses JavaScript because browser voice agents connect with WebRTC from the client. For Python voice workflows, use the [Voice agents guide](https://developers.openai.com/api/docs/guides/voice-agents), which covers chained voice pipelines.72This example uses JavaScript because browser voice agents connect with WebRTC from the client. For Python voice workflows, use the [Voice agents guide](https://developers.openai.com/api/docs/guides/voice-agents), which covers chained voice pipelines.

71 73 

72If you already have a text-based LLM application with the [Chat Completions endpoint](https://developers.openai.com/api/docs/api-reference/chat/), you may want to add audio capabilities. For example, if your chat application supports text input, you can add audio input and output: include `audio` in the `modalities` array and use an audio model, like [`gpt-audio-1.5`](https://developers.openai.com/api/docs/models/gpt-audio-1.5).74If you already have a text-based LLM application with the [Chat Completions endpoint](https://developers.openai.com/api/reference/resources/chat), you may want to add audio capabilities. For example, if your chat application supports text input, you can add audio input and output: include `audio` in the `modalities` array and use an audio model, like [`gpt-audio-1.5`](https://developers.openai.com/api/docs/models/gpt-audio-1.5).

73 75 

74The [Responses API](https://developers.openai.com/api/docs/api-reference/responses) docs currently describe76The [Responses API](https://developers.openai.com/api/reference/resources/responses) docs currently describe

75 text and image inputs with text outputs. For this audio-chat pattern, use Chat77 text and image inputs with text outputs. For this audio-chat pattern, use Chat

76 Completions with an audio-capable model.78 Completions with an audio-capable model.

77 79 

78 80 

79 81 

80<div data-content-switcher-pane data-value="audio-out">82Audio output from model

81 <div class="hidden">Audio output from model</div>83 

82 Create a human-like audio response to a prompt84 Create a human-like audio response to a prompt

83 85 

84```javascript86```javascript


149 }'151 }'

150```152```

151 153 

152 </div>154

153 <div data-content-switcher-pane data-value="audio-in" hidden>155 

154 <div class="hidden">Audio input to model</div>156

157 

158

159Audio input to model

160 

155 Use audio inputs for prompting a model161 Use audio inputs for prompting a model

156 162 

157```javascript163```javascript


246 ]252 ]

247 }'253 }'

248```254```

249 

250 </div>

Details

1# Background mode1# Background mode

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.

4 

3Agents 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.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.

4 6 

5Background 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`: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`:

guides/batch.md +12 −10

Details

1# Batch API1# Batch API

2 2 

3Learn 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/docs/api-reference/batch).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 

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).

4 6 

5## Overview7## Overview

6 8 


25 27 

26Batches start with a `.jsonl` file where each line contains the details of an individual request to the API. For now, the available endpoints are:28Batches start with a `.jsonl` file where each line contains the details of an individual request to the API. For now, the available endpoints are:

27 29 

28- `/v1/responses` ([Responses API](https://developers.openai.com/api/docs/api-reference/responses))30- `/v1/responses` ([Responses API](https://developers.openai.com/api/reference/resources/responses))

29- `/v1/chat/completions` ([Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat))31- `/v1/chat/completions` ([Chat Completions API](https://developers.openai.com/api/reference/resources/chat))

30- `/v1/embeddings` ([Embeddings API](https://developers.openai.com/api/docs/api-reference/embeddings))32- `/v1/embeddings` ([Embeddings API](https://developers.openai.com/api/reference/resources/embeddings))

31- `/v1/completions` ([Completions API](https://developers.openai.com/api/docs/api-reference/completions))33- `/v1/completions` ([Completions API](https://developers.openai.com/api/reference/resources/completions))

32- `/v1/moderations` ([Moderation guide](https://developers.openai.com/api/docs/guides/moderation))34- `/v1/moderations` ([Moderation guide](https://developers.openai.com/api/docs/guides/moderation))

33- `/v1/images/generations` ([Images API](https://developers.openai.com/api/docs/api-reference/images))35- `/v1/images/generations` ([Images API](https://developers.openai.com/api/reference/resources/images))

34- `/v1/images/edits` ([Images API](https://developers.openai.com/api/docs/api-reference/images))36- `/v1/images/edits` ([Images API](https://developers.openai.com/api/reference/resources/images))

35- `/v1/videos` ([Video generation guide](https://developers.openai.com/api/docs/guides/video-generation))37- `/v1/videos` ([Video generation guide](https://developers.openai.com/api/docs/guides/video-generation))

36 38 

37For a given input file, the parameters in each line's `body` field are the same as the parameters for the underlying endpoint. Each request must include a unique `custom_id` value, which you can use to reference results after completion. Here's an example of an input file with 2 requests. Note that each input file can only include requests to a single model.39For a given input file, the parameters in each line's `body` field are the same as the parameters for the underlying endpoint. Each request must include a unique `custom_id` value, which you can use to reference results after completion. Here's an example of an input file with 2 requests. Note that each input file can only include requests to a single model.


99 101 

100### 2. Upload your batch input file102### 2. Upload your batch input file

101 103 

102Similar to our [Fine-tuning API](https://developers.openai.com/api/docs/guides/model-optimization), you must first upload your input file so that you can reference it correctly when kicking off batches. Upload your `.jsonl` file using the [Files API](https://developers.openai.com/api/docs/api-reference/files).104Similar to our [Fine-tuning API](https://developers.openai.com/api/docs/guides/model-optimization), you must first upload your input file so that you can reference it correctly when kicking off batches. Upload your `.jsonl` file using the [Files API](https://developers.openai.com/api/reference/resources/files).

103 105 

104Upload files for Batch API106Upload files for Batch API

105 107 


190```192```

191 193 

192 194 

193This request will return a [Batch object](https://developers.openai.com/api/docs/api-reference/batch/object) with metadata about your batch:195This request will return a [Batch object](https://developers.openai.com/api/reference/resources/batches) with metadata about your batch:

194 196 

195```json197```json

196{198{


264 266 

265### 5. Retrieve the results267### 5. Retrieve the results

266 268 

267Once the batch is complete, you can download the output by making a request against the [Files API](https://developers.openai.com/api/docs/api-reference/files) via the `output_file_id` field from the Batch object and writing it to a file on your machine, in this case `batch_output.jsonl`269Once the batch is complete, you can download the output by making a request against the [Files API](https://developers.openai.com/api/reference/resources/files) via the `output_file_id` field from the Batch object and writing it to a file on your machine, in this case `batch_output.jsonl`

268 270 

269Retrieving the batch results271Retrieving the batch results

270 272 

guides/chatkit.md +25 −51

Details

1# ChatKit1# ChatKit

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.

4 

3ChatKit is the best way to build agentic chat experiences. Whether you’re building an internal knowledge base assistant, HR onboarding helper, research companion, shopping or scheduling assistant, troubleshooting bot, financial planning advisor, or support agent, ChatKit provides a customizable chat embed to handle all user experience details.5ChatKit is the best way to build agentic chat experiences. Whether you’re building an internal knowledge base assistant, HR onboarding helper, research companion, shopping or scheduling assistant, troubleshooting bot, financial planning advisor, or support agent, ChatKit provides a customizable chat embed to handle all user experience details.

4 6 

5Use ChatKit's embeddable UI widgets, customizable prompts, tool‑invocation support, file attachments, and chain‑of‑thought visualizations to build agents without reinventing the chat UI.7Use ChatKit's embeddable UI widgets, customizable prompts, tool‑invocation support, file attachments, and chain‑of‑thought visualizations to build agents without reinventing the chat UI.


21 23 

22## Get started with ChatKit24## Get started with ChatKit

23 25 

26- **[Custom server integration](https://developers.openai.com/api/docs/guides/custom-chatkit)**: Use any server and the ChatKit SDKs to build your own custom ChatKit user experience

27- **[Existing hosted workflow](#embed-chatkit-in-your-frontend)**: Connect ChatKit to an existing Agent Builder workflow during the transition window

28 

24## Embed ChatKit in your frontend29## Embed ChatKit in your frontend

25 30 

26Use this path only if you already have an Agent Builder workflow that backs your ChatKit implementation. For new ChatKit apps, or when migrating before Agent Builder shuts down, use the [advanced integration](https://developers.openai.com/api/docs/guides/custom-chatkit) to connect ChatKit to your own server-side agent implementation.31Use this path only if you already have an Agent Builder workflow that backs your ChatKit implementation. For new ChatKit apps, or when migrating before Agent Builder shuts down, use the [advanced integration](https://developers.openai.com/api/docs/guides/custom-chatkit) to connect ChatKit to your own server-side agent implementation.

27 32 

28At a high level, setting up ChatKit with an existing hosted workflow is a three-step process. Open your existing workflow while Agent Builder remains available. Then set up ChatKit and add features to build your chat experience.33At a high level, setting up ChatKit with an existing hosted workflow is a three-step process. Open your existing workflow while Agent Builder remains available. Then set up ChatKit and add features to build your chat experience.

29 34 

30<br />35 

36 

31![OpenAI-hosted37![OpenAI-hosted

32ChatKit](https://cdn.openai.com/API/docs/images/openai-hosted.png)38ChatKit](https://cdn.openai.com/API/docs/images/openai-hosted.png)

33 39 


165 171 

1663. In your project directory, install the ChatKit React bindings:1723. In your project directory, install the ChatKit React bindings:

167 173 

168 ```bash174```bash

169 npm install @openai/chatkit-react175 npm install @openai/chatkit-react

170 ```176```

171 177 

1724. Add the ChatKit JS script to your page. Drop this snippet into your page’s `<head>` or wherever you load scripts, and the browser will fetch and run ChatKit for you.1784. Add the ChatKit JS script to your page. Drop this snippet into your page’s `<head>` or wherever you load scripts, and the browser will fetch and run ChatKit for you.

173 179 


252 258 

253#### Build your implementation259#### Build your implementation

254 260 

255<a href="https://openai.github.io/chatkit-python">261[ChatKit docs on GitHub

256 262 

257 263 

258<span slot="icon">

259 </span>

260 Learn to handle authentication, add theming and customization, and more.

261 264 

265 Learn to handle authentication, add theming and customization, and more.](https://openai.github.io/chatkit-python)

266[ChatKit Python SDK

262 267 

263</a>

264<a href="https://github.com/openai/chatkit-python">

265 268 

266 269 

267<span slot="icon">

268 </span>

269 Add server-side storage, access control, tools, and other backend270 Add server-side storage, access control, tools, and other backend

270 functionality.271 functionality.](https://github.com/openai/chatkit-python)

271 

272 

273</a>

274 272 

275<a href="https://github.com/openai/chatkit-js">273[ChatKit JS SDK

276 274 

277 275 

278<span slot="icon">

279 </span>

280 Check out the ChatKit JS repo.

281 276 

282 277 Check out the ChatKit JS repo.](https://github.com/openai/chatkit-js)

283</a>

284 278 

285#### Explore ChatKit UI279#### Explore ChatKit UI

286 280 

287<a href="https://chatkit.world">281[chatkit.world

288

289 

290<span slot="icon">

291 </span>

292 Play with an interactive demo of ChatKit.

293 282 

294 283 

295</a>

296 284 

297<a href="https://widgets.chatkit.studio">285 Play with an interactive demo of ChatKit.](https://chatkit.world)

298 286 

287[Widget builder

299 288 

300<span slot="icon">

301 </span>

302 Browse available widgets.

303 289 

304 290 

305</a>291 Browse available widgets.](https://widgets.chatkit.studio)

306 292 

307<a href="https://chatkit.studio/playground">293[ChatKit playground

308 294 

309 295 

310<span slot="icon">

311 </span>

312 Play with an interactive demo to learn by doing.

313 296 

314 297 Play with an interactive demo to learn by doing.](https://chatkit.studio/playground)

315</a>

316 298 

317#### See working examples299#### See working examples

318 300 

319<a href="https://github.com/openai/openai-chatkit-advanced-samples">301[Samples on GitHub

320

321 

322<span slot="icon">

323 </span>

324 See working examples of ChatKit and get inspired.

325 302 

326 303 

327</a>

328 304 

329<a href="https://github.com/openai/openai-chatkit-starter-app">305 See working examples of ChatKit and get inspired.](https://github.com/openai/openai-chatkit-advanced-samples)

330 306 

307[Starter app repo

331 308 

332<span slot="icon">

333 </span>

334 Clone a repo to start with a fully working template.

335 309 

336 310 

337</a>311 Clone a repo to start with a fully working template.](https://github.com/openai/openai-chatkit-starter-app)

338 312 

339## Next steps313## Next steps

340 314 

Details

1# Actions in ChatKit1# Actions in ChatKit

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.

4 

3Actions are a way for the ChatKit SDK frontend to trigger a streaming response without the user submitting a message. They can also be used to trigger side-effects outside ChatKit SDK.5Actions are a way for the ChatKit SDK frontend to trigger a streaming response without the user submitting a message. They can also be used to trigger side-effects outside ChatKit SDK.

4 6 

5## Triggering actions7## Triggering actions

Details

1# Theming and customization in ChatKit1# Theming and customization in ChatKit

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.

4 

3After following the [ChatKit quickstart](https://developers.openai.com/api/docs/guides/chatkit), learn how to change themes and add customization to your chat embed. Match your app’s aesthetic with light and dark themes, setting an accent color, controlling the density, and rounded corners.5After following the [ChatKit quickstart](https://developers.openai.com/api/docs/guides/chatkit), learn how to change themes and add customization to your chat embed. Match your app’s aesthetic with light and dark themes, setting an accent color, controlling the density, and rounded corners.

4 6 

5## Overview7## Overview


17 19 

18#### Explore ChatKit UI20#### Explore ChatKit UI

19 21 

20<a href="https://chatkit.world">22[chatkit.world

21

22 

23<span slot="icon">

24 </span>

25 Play with an interactive demo of ChatKit.

26 

27 23 

28</a>

29 24 

30<a href="https://widgets.chatkit.studio">

31 25 

26 Play with an interactive demo of ChatKit.](https://chatkit.world)

32 27 

33<span slot="icon">28[Widget builder

34 </span>

35 Browse available widgets.

36 29 

37 30 

38</a>

39 31 

40<a href="https://chatkit.studio/playground">32 Browse available widgets.](https://widgets.chatkit.studio)

41 33 

34[ChatKit playground

42 35 

43<span slot="icon">

44 </span>

45 Play with an interactive demo to learn by doing.

46 36 

47 37 

48</a>38 Play with an interactive demo to learn by doing.](https://chatkit.studio/playground)

49 39 

50#### See working examples40#### See working examples

51 41 

52<a href="https://github.com/openai/openai-chatkit-advanced-samples">42[Samples on GitHub

53 43 

54 44 

55<span slot="icon">

56 </span>

57 See working examples of ChatKit and get inspired.

58 45 

46 See working examples of ChatKit and get inspired.](https://github.com/openai/openai-chatkit-advanced-samples)

59 47 

60</a>48[Starter app repo

61 49 

62<a href="https://github.com/openai/openai-chatkit-starter-app">

63 50 

64 51 

65<span slot="icon">52 Clone a repo to start with a fully working template.](https://github.com/openai/openai-chatkit-starter-app)

66 </span>

67 Clone a repo to start with a fully working template.

68 

69 

70</a>

71 53 

72## Change the theme54## Change the theme

73 55 


208 190 

209You can customize the appearance of entity tags on mouseover using widgets. Show rich previews such as a business card, document summary, or image when the user hovers over an entity tag.191You can customize the appearance of entity tags on mouseover using widgets. Show rich previews such as a business card, document summary, or image when the user hovers over an entity tag.

210 192 

211<a href="https://widgets.chatkit.studio">193[Widget builder

212

213 194 

214<span slot="icon">

215 </span>

216 Browse available widgets.

217 195 

218 196 

219</a>197 Browse available widgets.](https://widgets.chatkit.studio)

220 198 

221```jsx199```jsx

222const options: Partial<ChatKitOptions> = {200const options: Partial<ChatKitOptions> = {

Details

1# ChatKit widgets1# ChatKit widgets

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.

4 

3Widgets are the containers and components that come with ChatKit. You can use prebuilt widgets, modify templates, or design your own to fully customize ChatKit in your product.5Widgets are the containers and components that come with ChatKit. You can use prebuilt widgets, modify templates, or design your own to fully customize ChatKit in your product.

4 6 

5![widgets](https://cdn.openai.com/API/images/widget-graphic.png)7![widgets](https://cdn.openai.com/API/images/widget-graphic.png)

Details

1# Citation Formatting1# Citation Formatting

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.

4 

3Reliable citations build trust and help readers verify the accuracy of responses. This guide provides practical guidance on how to prepare citable material and instruct the model to format citations effectively, using patterns that are familiar to OpenAI models.5Reliable citations build trust and help readers verify the accuracy of responses. This guide provides practical guidance on how to prepare citable material and instruct the model to format citations effectively, using patterns that are familiar to OpenAI models.

4 6 

5## Overview7## Overview


53[L3] Exceptions may apply for approved accommodations.55[L3] Exceptions may apply for approved accommodations.

54```56```

55 57 

56<strong>Source IDs vs. locators:</strong> A source ID is a stable,58**Source IDs vs. locators:** A source ID is a stable,

57 model-generated identifier such as <code>block1</code>. A locator is the59 model-generated identifier such as `block1`. A locator is the

58 precise UI-rendered highlight, such as <code>lines L8-L13</code> or 60 precise UI-rendered highlight, such as `lines L8-L13` or

59 <code>Paragraph 21</code>. In general, the model should emit the source ID,61 `Paragraph 21`. In general, the model should emit the source ID,

60 while your system resolves or renders the locator. Mixing the two too early62 while your system resolves or renders the locator. Mixing the two too early

61 tends to increase formatting errors.63 tends to increase formatting errors.

62 64 


79| Locator (optional) | Narrows the citation to a precise span. | `L8-L13` |81| Locator (optional) | Narrows the citation to a precise span. | `L8-L13` |

80| `CITATION_STOP` | Closes the citation marker. | `\ue201` |82| `CITATION_STOP` | Closes the citation marker. | `\ue201` |

81 83 

82For tool calls, <code>turnN</code> increments once per tool invocation, not84For tool calls, `turnN` increments once per tool invocation, not

83 once per individual result. Within a single invocation, sources are85 once per individual result. Within a single invocation, sources are

84 distinguished by suffixes such as <code>file0</code>, <code>file1</code>, and86 distinguished by suffixes such as `file0`, `file1`, and

85 so on. In a single-response system, all references will be 87 so on. In a single-response system, all references will be

86 <code>turn0...</code> only if the model makes exactly one tool call before88 `turn0...` only if the model makes exactly one tool call before

87 answering. If it makes multiple tool calls, you may instead see references89 answering. If it makes multiple tool calls, you may instead see references

88 like <code>turn0fileX</code>, <code>turn1fileX</code>, and so on.90 like `turn0fileX`, `turn1fileX`, and so on.

89 91 

90### Template92### Template

91 93 


538The Court held that the District Court lacked personal jurisdiction over the petitioner. \ue200cite\ue202block5\ue201540The Court held that the District Court lacked personal jurisdiction over the petitioner. \ue200cite\ue202block5\ue201

539```541```

540 542 

541<strong>Note:</strong> OpenAI-hosted tools such as web search provide543**Note:** OpenAI-hosted tools such as web search provide

542 automatic inline citations. If you want to use hosted tools instead, see the 544 automatic inline citations. If you want to use hosted tools instead, see the

543 <a href="/api/docs/guides/tools">tools overview</a>, 545 [tools overview](https://developers.openai.com/api/docs/guides/tools),

544 <a href="/api/docs/guides/tools-web-search">web search guide</a>, and 546 [web search guide](https://developers.openai.com/api/docs/guides/tools-web-search), and

545 <a href="/api/docs/guides/tools-file-search">file search guide</a>.547 [file search guide](https://developers.openai.com/api/docs/guides/tools-file-search).

Details

1# Code generation1# Code generation

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.

4 

3Writing, 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) and Codex.

4 6 

5## Get started7## Get started

6 8 

7<div className="mb-10 w-full max-w-full overflow-hidden">9 

8 </div>10 

11 - **[Use Codex for out-of-the-box coding agents](#use-codex)**: Connect your codebase to Codex and accelerate your projects using software engineering agents.

12- **[Integrate with coding models](#integrate-with-coding-models)**: Use OpenAI models in your application. Add them to a model picker, for instance.

13 

14 

9 15 

10## Use Codex16## Use Codex

11 17 

12[**Codex**](https://developers.openai.com/codex/overview) is OpenAI's coding agent for software development. It helps you write, review and debug code. Interact with Codex in a variety of interfaces: in your IDE, through the CLI, on web and mobile sites, or in your CI/CD pipelines with the SDK. Codex is the best way to get agentic software engineering on your projects.18[**Codex**](https://developers.openai.com/codex) is OpenAI's coding agent for software development. It helps you write, review and debug code. Interact with Codex in a variety of interfaces: in your IDE, through the CLI, on web and mobile sites, or in your CI/CD pipelines with the SDK. Codex is the best way to get agentic software engineering on your projects.

13 19 

14Codex works best with the latest models from the GPT-5 family, such as [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol). We offer a range of models specifically designed to work with coding agents like Codex, such as [`gpt-5.3-codex`](https://developers.openai.com/api/docs/models/gpt-5.3-codex), but we recommend using the latest general-purpose model for most code generation tasks.20Codex works best with the latest models from the GPT-5 family, such as [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol). We offer a range of models specifically designed to work with coding agents like Codex, such as [`gpt-5.3-codex`](https://developers.openai.com/api/docs/models/gpt-5.3-codex), but we recommend using the latest general-purpose model for most code generation tasks.

15 21 


17 23 

18## Integrate with coding models24## Integrate with coding models

19 25 

20For most API-based code generation, start with <strong>`gpt-5.6`</strong>. 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-5.6`**. 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.

21 27 

22This example shows how you can use the [Responses API](https://developers.openai.com/api/docs/api-reference/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:

23 29 

24Default model for most coding tasks30Default model for most coding tasks

25 31 


83## Next steps89## Next steps

84 90 

85- 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.91- 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.

86- Read <a href="/api/docs/guides/latest-model">Model guidance</a> for model selection, features, migration guidance, and prompting patterns that work well on coding and agentic tasks.92- 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.

87- Compare [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) and [`gpt-5.3-codex`](https://developers.openai.com/api/docs/models/gpt-5.3-codex) on the model pages.93- Compare [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) and [`gpt-5.3-codex`](https://developers.openai.com/api/docs/models/gpt-5.3-codex) on the model pages.

Details

1# Compaction1# Compaction

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.

4 

3## Overview5## Overview

4 6 

5To support long-running interactions, you can use compaction to reduce context7To support long-running interactions, you can use compaction to reduce context


82## Standalone compact endpoint84## Standalone compact endpoint

83 85 

84For explicit control, use the86For explicit control, use the

85[standalone compact endpoint](https://developers.openai.com/api/docs/api-reference/responses/compact) for87[standalone compact endpoint](https://developers.openai.com/api/reference/resources/responses/methods/compact) for

86stateless compaction in long-running workflows.88stateless compaction in long-running workflows.

87 89 

88This endpoint is fully stateless and ZDR-friendly.90This endpoint is fully stateless and ZDR-friendly.

Details

1# Completions API1# Completions API

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.

4 

3The completions API endpoint received its final update in July 2023 and has a different interface than the new Chat Completions endpoint. Instead of the input being a list of messages, the input is a freeform text string called a `prompt`.5The completions API endpoint received its final update in July 2023 and has a different interface than the new Chat Completions endpoint. Instead of the input being a list of messages, the input is a freeform text string called a `prompt`.

4 6 

5An example legacy Completions API call looks like the following:7An example legacy Completions API call looks like the following:


26 28 

27#### Inserting text29#### Inserting text

28 30 

29The completions endpoint also supports inserting text by providing a [suffix](https://developers.openai.com/api/docs/api-reference/completions/create#completions-create-suffix) in addition to the standard prompt which is treated as a prefix. This need naturally arises when writing long-form text, transitioning between paragraphs, following an outline, or guiding the model towards an ending. This also works on code, and can be used to insert in the middle of a function or file.31The completions endpoint also supports inserting text by providing a [suffix](https://developers.openai.com/api/reference/resources/completions/methods/create#completions-create-suffix) in addition to the standard prompt which is treated as a prefix. This need naturally arises when writing long-form text, transitioning between paragraphs, following an outline, or guiding the model towards an ending. This also works on code, and can be used to insert in the middle of a function or file.

30 32 

31 33 

32 34 


95 97 

96### Inserting text98### Inserting text

97 99 

98The completions endpoint also supports inserting text by providing a [suffix](https://developers.openai.com/api/docs/api-reference/completions/create#completions-create-suffix) in addition to the standard prompt which is treated as a prefix. This need naturally arises when writing long-form text, transitioning between paragraphs, following an outline, or guiding the model towards an ending. This also works on code, and can be used to insert in the middle of a function or file.100The completions endpoint also supports inserting text by providing a [suffix](https://developers.openai.com/api/reference/resources/completions/methods/create#completions-create-suffix) in addition to the standard prompt which is treated as a prefix. This need naturally arises when writing long-form text, transitioning between paragraphs, following an outline, or guiding the model towards an ending. This also works on code, and can be used to insert in the middle of a function or file.

99 101 

100 102 

101 103 

Details

1# Conversation state1# Conversation state

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.

4 

3OpenAI provides a few ways to manage conversation state, which is important for preserving information across multiple messages or turns in a conversation.5OpenAI provides a few ways to manage conversation state, which is important for preserving information across multiple messages or turns in a conversation.

4 6 

5 7 


145 147 

146### Using the Conversations API148### Using the Conversations API

147 149 

148The [Conversations API](https://developers.openai.com/api/docs/api-reference/conversations/create) works with the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create) to persist conversation state as a long-running object with its own durable identifier. After creating a conversation object, you can keep using it across sessions, devices, or jobs.150The [Conversations API](https://developers.openai.com/api/reference/resources/conversations/methods/create) works with the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) to persist conversation state as a long-running object with its own durable identifier. After creating a conversation object, you can keep using it across sessions, devices, or jobs.

149 151 

150Conversations store items, which can be messages, tool calls, tool outputs, and other data.152Conversations store items, which can be messages, tool calls, tool outputs, and other data.

151 153 


272 274 

273The connection-local cache currently keeps the most recent previous response in memory for low-latency continuation. If an uncached ID cannot be resolved, send a new turn with `previous_response_id` set to `null` and pass full input context.275The connection-local cache currently keeps the most recent previous response in memory for low-latency continuation. If an uncached ID cannot be resolved, send a new turn with `previous_response_id` set to `null` and pass full input context.

274 276 

275<div style={{ margin: "-16px 0 10px 0" }}>277 

278 

276 Data retention for model responses279 Data retention for model responses

277 280 

278Response objects are saved for 30 days by default. They can be viewed in the dashboard 281Response objects are saved for 30 days by default. They can be viewed in the dashboard

279 [logs](https://platform.openai.com/logs?api=responses) page or 282 [logs](https://platform.openai.com/logs?api=responses) page or

280 [retrieved](https://developers.openai.com/api/docs/api-reference/responses/get) via the API. 283 [retrieved](https://developers.openai.com/api/reference/resources/responses/methods/retrieve) via the API.

281 You can disable this behavior by setting <code>store</code> to <code>false</code>284 You can disable this behavior by setting `store` to `false`

282 when creating a Response.285 when creating a Response.

283 286 

284 Conversation objects and items in them are not subject to the 30 day TTL. Any response attached to a conversation will have its items persisted with no 30 day TTL.287 Conversation objects and items in them are not subject to the 30 day TTL. Any response attached to a conversation will have its items persisted with no 30 day TTL.

285 288 

286 OpenAI does not use data sent via API to train our models without your explicit consent—[learn more](https://developers.openai.com/api/docs/guides/your-data).289 OpenAI does not use data sent via API to train our models without your explicit consent—[learn more](https://developers.openai.com/api/docs/guides/your-data).

287</div>290 

291 

288 292 

289 293 

290Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.294Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.


310 314 

311 315 

312 316 

313For example, when making an API request to the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) with a reasoning enabled model, like the [o1 model](https://developers.openai.com/api/docs/guides/reasoning), the following token counts will apply toward the context window total:317For example, when making an API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) with a reasoning enabled model, like the [o1 model](https://developers.openai.com/api/docs/guides/reasoning), the following token counts will apply toward the context window total:

314 318 

315- Input tokens (inputs you include in the `input` array for the [Responses API](https://developers.openai.com/api/docs/api-reference/responses))319- Input tokens (inputs you include in the `input` array for the [Responses API](https://developers.openai.com/api/reference/resources/responses))

316- Output tokens (tokens generated in response to your prompt) 320- Output tokens (tokens generated in response to your prompt)

317- Reasoning tokens (used by the model to plan a response)321- Reasoning tokens (used by the model to plan a response)

318 322 


334 [Server-side compaction](https://developers.openai.com/api/docs/guides/compaction#server-side-compaction).338 [Server-side compaction](https://developers.openai.com/api/docs/guides/compaction#server-side-compaction).

335- For explicit compaction control, see339- For explicit compaction control, see

336 [Standalone compact endpoint](https://developers.openai.com/api/docs/guides/compaction#standalone-compact-endpoint)340 [Standalone compact endpoint](https://developers.openai.com/api/docs/guides/compaction#standalone-compact-endpoint)

337 and the [`/responses/compact` API reference](https://developers.openai.com/api/docs/api-reference/responses/compact).341 and the [`/responses/compact` API reference](https://developers.openai.com/api/reference/resources/responses/methods/compact).

338 342 

339## Next steps343## Next steps

340 344 

Details

1# Cost optimization1# Cost optimization

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.

4 

3There 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.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.

4 6 

5## Cost and latency7## Cost and latency

Details

1# Advanced integrations with ChatKit1# Advanced integrations with ChatKit

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.

4 

3When you need full control—custom authentication, data residency, on‑prem deployment, or bespoke agent orchestration—you can run ChatKit on your own infrastructure. Use OpenAI's advanced self‑hosted option to use your own server and customized ChatKit.5When you need full control—custom authentication, data residency, on‑prem deployment, or bespoke agent orchestration—you can run ChatKit on your own infrastructure. Use OpenAI's advanced self‑hosted option to use your own server and customized ChatKit.

4 6 

5Agent Builder-hosted ChatKit workflows are in a transition window. For new7Agent Builder-hosted ChatKit workflows are in a transition window. For new


228| `messages` | `object` | Configure message features (feedback, annotations, etc.). | |230| `messages` | `object` | Configure message features (feedback, annotations, etc.). | |

229| `composer` | `object` | Control attachments, entity tags, and placeholder text. | |231| `composer` | `object` | Control attachments, entity tags, and placeholder text. | |

230| `entities` | `object` | Callbacks for entity lookup, click handling, and previews. | |232| `entities` | `object` | Callbacks for entity lookup, click handling, and previews. | |

233 

234### Plain-text aliases

235 

236- "light" | "dark"

237- string | null

238- object | boolean

Details

1# Deep research1# Deep research

2 2 

3The [`o3-deep-research`](https://developers.openai.com/api/docs/models/o3-deep-research) and [`o4-mini-deep-research`](https://developers.openai.com/api/docs/models/o4-mini-deep-research) models can find, analyze, and synthesize hundreds of sources to create a comprehensive report at the level of a research analyst. These models are optimized for browsing and data analysis, and can use [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [remote MCP](https://developers.openai.com/api/docs/guides/tools-remote-mcp) servers, and [file search](https://developers.openai.com/api/docs/guides/tools-file-search) over internal [vector stores](https://developers.openai.com/api/docs/api-reference/vector-stores) to generate detailed reports, ideal for use cases like: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 [`o3-deep-research`](https://developers.openai.com/api/docs/models/o3-deep-research) and [`o4-mini-deep-research`](https://developers.openai.com/api/docs/models/o4-mini-deep-research) models can find, analyze, and synthesize hundreds of sources to create a comprehensive report at the level of a research analyst. These models are optimized for browsing and data analysis, and can use [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [remote MCP](https://developers.openai.com/api/docs/guides/tools-connectors-mcp) servers, and [file search](https://developers.openai.com/api/docs/guides/tools-file-search) over internal [vector stores](https://developers.openai.com/api/reference/resources/vector_stores) to generate detailed reports, ideal for use cases like:

4 6 

5- Legal or scientific research7- Legal or scientific research

6- Market analysis8- Market analysis

7- Reporting on large bodies of internal company data9- Reporting on large bodies of internal company data

8 10 

9To use deep research, use the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) with the model set to `o3-deep-research` or `o4-mini-deep-research`. You must include at least one data source: web search, remote MCP servers, or file search with vector stores. You can also include the [code interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter) tool to allow the model to perform complex analysis by writing code.11To use deep research, use the [Responses API](https://developers.openai.com/api/reference/resources/responses) with the model set to `o3-deep-research` or `o4-mini-deep-research`. You must include at least one data source: web search, remote MCP servers, or file search with vector stores. You can also include the [code interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter) tool to allow the model to perform complex analysis by writing code.

10 12 

11Kick off a deep research task13Kick off a deep research task

12 14 


435 437 

436- Include relevant data directly in the prompt text438- Include relevant data directly in the prompt text

437- Upload files to vector stores, and use the file search tool to connect model to vector stores439- Upload files to vector stores, and use the file search tool to connect model to vector stores

438- Use [connectors](https://developers.openai.com/api/docs/guides/tools-remote-mcp#connectors) to pull in context from popular applications, like Dropbox and Gmail440- Use [connectors](https://developers.openai.com/api/docs/guides/tools-connectors-mcp#connectors) to pull in context from popular applications, like Dropbox and Gmail

439- Connect the model to a remote MCP server that can access your data source441- Connect the model to a remote MCP server that can access your data source

440 442 

441### Prompt text443### Prompt text


448 450 

449### Connectors451### Connectors

450 452 

451Connectors are third-party integrations with popular applications, like Dropbox and Gmail, that let you pull in context to build richer experiences in a single API call. In the Responses API, you can think of these connectors as built-in tools, with a third-party backend. Learn how to [set up connectors](https://developers.openai.com/api/docs/guides/tools-remote-mcp#connectors) in the remote MCP guide.453Connectors are third-party integrations with popular applications, like Dropbox and Gmail, that let you pull in context to build richer experiences in a single API call. In the Responses API, you can think of these connectors as built-in tools, with a third-party backend. Learn how to [set up connectors](https://developers.openai.com/api/docs/guides/tools-connectors-mcp#connectors) in the remote MCP guide.

452 454 

453### Remote MCP servers455### Remote MCP servers

454 456 


540```542```

541 543 

542 544 

543[545[Build a deep research compatible remote MCP server

544 546 

545<span slot="icon">

546 </span>

547 Give deep research models access to private data via remote Model Context

548 Protocol (MCP) servers.

549 547 

550](https://developers.openai.com/api/docs/mcp)548 

549 Give deep research models access to private data via remote Model Context

550 Protocol (MCP) servers.](https://developers.openai.com/api/docs/mcp)

551 551 

552### Supported tools552### Supported tools

553 553 

Details

1# API deployment checklist1# API deployment checklist

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.

4 

3| Contents | Expected impact |5| Contents | Expected impact |

4| ------------------------------------------------------------------------------- | ----------------------------------- |6| ------------------------------------------------------------------------------- | ----------------------------------- |

5| [Use the Responses API](#use-the-responses-api) | Quality, cost, latency, reliability |7| [Use the Responses API](#use-the-responses-api) | Quality, cost, latency, reliability |


559[Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) automatically reduces latency561[Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) automatically reduces latency

560and cost when requests reuse the same long prefix. For high-volume workflows,562and cost when requests reuse the same long prefix. For high-volume workflows,

561set563set

562[`prompt_cache_key`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-prompt_cache_key)564[`prompt_cache_key`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-prompt_cache_key)

563consistently for requests that share the same stable prefix. The service565consistently for requests that share the same stable prefix. The service

564combines the key with the prompt prefix hash to help route similar requests to566combines the key with the prompt prefix hash to help route similar requests to

565the same cache without changing the model input. Keep the key stable for567the same cache without changing the model input. Keep the key stable for

Details

1# ChatGPT Developer mode1# ChatGPT Developer mode

2 2 

3<div class="not-prose mt-2 mb-6">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 <a4 

5 href="https://help.openai.com/en/articles/20001062"5[<span

6 class="inline-flex items-center gap-1 rounded-full border px-2 py-1 text-[11px] font-semibold leading-none uppercase tracking-[0.02em] no-underline transition-colors hover:opacity-90"

7 style="background-color: var(--color-background-warning-soft); color: var(--color-text-warning-outline); border-color: var(--color-border-warning-outline);"

8 >

9 <span

10 aria-hidden="true"6 aria-hidden="true"

11 class="h-4 w-4 shrink-0 bg-current"7 class="h-4 w-4 shrink-0 bg-current"

12 style="-webkit-mask: url('/images/codex/exclamation-shield.svg') no-repeat center / contain; mask: url('/images/codex/exclamation-shield.svg') no-repeat center / contain;"8 style="-webkit-mask: url('/images/codex/exclamation-shield.svg') no-repeat center / contain; mask: url('/images/codex/exclamation-shield.svg') no-repeat center / contain;"

13 ></span>9 >

14 Elevated risk10 

15 </a>11 Elevated risk](https://help.openai.com/en/articles/20001062)

16</div>12 

13 

17 14 

18## What is ChatGPT developer mode15## What is ChatGPT developer mode

19 16 


45 42 

46 Examples:43 Examples:

47 44 

48 ```45```

49 Schedule a 30‑minute meeting tomorrow at 3pm PT with46 Schedule a 30‑minute meeting tomorrow at 3pm PT with

50 alice@example.com and bob@example.com using "Calendar.create_event".47 alice@example.com and bob@example.com using "Calendar.create_event".

51 Do not use any other scheduling tools.48 Do not use any other scheduling tools.

52 ```49```

53 50 

54 ```51```

55 Create a pull request using "GitHub.open_pull_request" from branch52 Create a pull request using "GitHub.open_pull_request" from branch

56 "feat-retry" into "main" with title "Add retry logic" and body "…".53 "feat-retry" into "main" with title "Add retry logic" and body "…".

57 Do not push directly to main.54 Do not push directly to main.

58 ```55```

59 56 

60- **Reviewing and confirming tool calls:**57- **Reviewing and confirming tool calls:**

61 - Inspect JSON tool payloads verify correctness and debug problems. For each tool call, you can use the carat to expand and collapse the tool call details. Full JSON contents of the tool input and output are available.58 - Inspect JSON tool payloads verify correctness and debug problems. For each tool call, you can use the carat to expand and collapse the tool call details. Full JSON contents of the tool input and output are available.

Details

1# Direct preference optimization1# Direct preference optimization

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.

4 

3[Direct Preference Optimization](https://arxiv.org/abs/2305.18290) (DPO) fine-tuning allows you to fine-tune models based on prompts and pairs of responses. This approach enables the model to learn from more subjective human preferences, optimizing for outputs that are more likely to be favored. DPO is currently only supported for text inputs and outputs.5[Direct Preference Optimization](https://arxiv.org/abs/2305.18290) (DPO) fine-tuning allows you to fine-tune models based on prompts and pairs of responses. This approach enables the model to learn from more subjective human preferences, optimizing for outputs that are more likely to be favored. DPO is currently only supported for text inputs and outputs.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).

12 15 

13<br />16 

17 

14 18 

15<table>19<table>

16<tbody>20<tbody>


45- A preferred output (an ideal assistant response).49- A preferred output (an ideal assistant response).

46- A non-preferred output (a suboptimal assistant response).50- A non-preferred output (a suboptimal assistant response).

47 51 

48The data should be formatted in JSONL format, with each line [representing an example](https://developers.openai.com/api/docs/api-reference/fine-tuning/preference-input) in the following structure:52The data should be formatted in JSONL format, with each line [representing an example](https://developers.openai.com/api/reference/resources/fine_tuning) in the following structure:

49 53 

50```json54```json

51{55{


80 84 

81Uploading training data and using a model fine-tuned with DPO follows the [same flow described here](https://developers.openai.com/api/docs/guides/model-optimization).85Uploading training data and using a model fine-tuned with DPO follows the [same flow described here](https://developers.openai.com/api/docs/guides/model-optimization).

82 86 

83To create a DPO fine-tune job, use the `method` field in the [fine-tuning job creation endpoint](https://developers.openai.com/api/docs/api-reference/fine-tuning/create), where you can specify `type` as well as any associated `hyperparameters`. For DPO:87To create a DPO fine-tune job, use the `method` field in the [fine-tuning job creation endpoint](https://developers.openai.com/api/reference/resources/fine_tuning), where you can specify `type` as well as any associated `hyperparameters`. For DPO:

84 88 

85- set the `type` parameter to `dpo`89- set the `type` parameter to `dpo`

86- optionally set the `hyperparameters` property with any options you'd like to configure.90- optionally set the `hyperparameters` property with any options you'd like to configure.


173 177 

174Now that you know the basics of DPO, explore these other methods as well.178Now that you know the basics of DPO, explore these other methods as well.

175 179 

176[180[Supervised fine-tuning

181 

182 

183 

184 Fine-tune a model by providing correct outputs for sample inputs.](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

177 185 

178<span slot="icon">186[Vision fine-tuning

179 </span>

180 Fine-tune a model by providing correct outputs for sample inputs.

181 187 

182](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

183 188 

184[

185 189 

186<span slot="icon">190 Learn to fine-tune for computer vision with image inputs.](https://developers.openai.com/api/docs/guides/vision-fine-tuning)

187 </span>

188 Learn to fine-tune for computer vision with image inputs.

189 191 

190](https://developers.openai.com/api/docs/guides/vision-fine-tuning)192[Reinforcement fine-tuning

191 193 

192[

193 194 

194<span slot="icon">

195 </span>

196 Fine-tune a reasoning model by grading its outputs.

197 195 

198](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)196 Fine-tune a reasoning model by grading its outputs.](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

Details

1# Vector embeddings1# Vector embeddings

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.

4 

3## What are embeddings?5## What are embeddings?

4 6 

5OpenAI’s text embeddings measure the relatedness of text strings. Embeddings are commonly used for:7OpenAI’s text embeddings measure the relatedness of text strings. Embeddings are commonly used for:


13 15 

14An embedding is a vector (list) of floating point numbers. The [distance](#which-distance-function-should-i-use) between two vectors measures their relatedness. Small distances suggest high relatedness and large distances suggest low relatedness.16An embedding is a vector (list) of floating point numbers. The [distance](#which-distance-function-should-i-use) between two vectors measures their relatedness. Small distances suggest high relatedness and large distances suggest low relatedness.

15 17 

16Visit our [pricing page](https://openai.com/api/pricing/) to learn about embeddings pricing. Requests are billed based on the number of [tokens](https://platform.openai.com/tokenizer) in the [input](https://developers.openai.com/api/docs/api-reference/embeddings/create#embeddings/create-input).18Visit our [pricing page](https://openai.com/api/pricing/) to learn about embeddings pricing. Requests are billed based on the number of [tokens](https://platform.openai.com/tokenizer) in the [input](https://developers.openai.com/api/reference/resources/embeddings/methods/create#embeddings/create-input).

17 19 

18## How to get embeddings20## How to get embeddings

19 21 

20To get an embedding, send your text string to the [embeddings API endpoint](https://developers.openai.com/api/docs/api-reference/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 (e.g., `text-embedding-3-small`):

21 23 

22Example: Getting embeddings24Example: Getting embeddings

23 25 


80}82}

81```83```

82 84 

83By 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/docs/api-reference/embeddings/create#embeddings-create-dimensions). Find more detail on embedding dimensions in the [embedding use case section](#use-cases).85By 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).

84 86 

85## Embedding models87## Embedding models

86 88 


102 104 

103The dataset contains a total of 568,454 food reviews left by Amazon users up to October 2012. We use a subset of the 1000 most recent reviews for illustration purposes. The reviews are in English and tend to be positive or negative. Each review has a `ProductId`, `UserId`, `Score`, review title (`Summary`) and review body (`Text`). For example:105The dataset contains a total of 568,454 food reviews left by Amazon users up to October 2012. We use a subset of the 1000 most recent reviews for illustration purposes. The reviews are in English and tend to be positive or negative. Each review has a `ProductId`, `UserId`, `Score`, review title (`Summary`) and review body (`Text`). For example:

104 106 

105<div className="docs-embeddings-sample-data-table">107 

108 

106 109 

107| Product Id | User Id | Score | Summary | Text |110| Product Id | User Id | Score | Summary | Text |

108| ---------- | -------------- | ----- | --------------------- | ------------------------------------------------- |111| ---------- | -------------- | ----- | --------------------- | ------------------------------------------------- |

109| B001E4KFG0 | A3SGXH7AUHU8GW | 5 | Good Quality Dog Food | I have bought several of the Vitality canned... |112| B001E4KFG0 | A3SGXH7AUHU8GW | 5 | Good Quality Dog Food | I have bought several of the Vitality canned... |

110| B00813GRG4 | A1D87F6ZCVE5NK | 1 | Not as Advertised | Product arrived labeled as Jumbo Salted Peanut... |113| B00813GRG4 | A1D87F6ZCVE5NK | 1 | Not as Advertised | Product arrived labeled as Jumbo Salted Peanut... |

111 114 

112</div>115 

116 

113 117 

114Below, 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.118Below, 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.

115 119 

116 120 

117 121 

118<span>Get_embeddings_from_dataset.ipynb</span> ```python122Get_embeddings_from_dataset.ipynb

123```python

119from openai import OpenAI124from openai import OpenAI

120 125 

121client = OpenAI()126client = OpenAI()


147 152 

148Using 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.153Using 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.

149 154 

150Both 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/docs/api-reference/embeddings/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).155Both 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).

151 156 

152In 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.157In 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.

153 158 


185 190 

186Question answering using embeddings-based search191Question answering using embeddings-based search

187 192 

188<p>

189 193 

190 194 

191<span>Question_answering_using_embeddings.ipynb</span> </p>

192 195

193There 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.196 

197Question_answering_using_embeddings.ipynb

198 There 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.

194 199 

195```python200```python

196query = f"""Use the below article on the 2022 Winter Olympics to answer the subsequent question. If the answer cannot be found, write "I don't know."201query = f"""Use the below article on the 2022 Winter Olympics to answer the subsequent question. If the answer cannot be found, write "I don't know."


220 225 

221Text search using embeddings226Text search using embeddings

222 227 

223<p>

224 228 

225 229 

226<span>Semantic_text_search_using_embeddings.ipynb</span> </p>

227 230

228To 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.231 

232Semantic_text_search_using_embeddings.ipynb

233 To 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.

229 234 

230```python235```python

231def search_reviews(df, product_description, n=3, pprint=True):236def search_reviews(df, product_description, n=3, pprint=True):


243 248 

244Code search using embeddings249Code search using embeddings

245 250 

246<p>

247 251 

248 252 

249<span>Code_search.ipynb</span> </p>

250 253

251Code search works similarly to embedding-based text search. We provide a method to extract Python functions from all the Python files in a given repository. Each function is then indexed by the `text-embedding-3-small` model.254 

255Code_search.ipynb

256 Code search works similarly to embedding-based text search. We provide a method to extract Python functions from all the Python files in a given repository. Each function is then indexed by the `text-embedding-3-small` model.

252 257 

253To 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.258To 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.

254 259 


274 279 

275Recommendations using embeddings280Recommendations using embeddings

276 281 

277<p>

278 282 

279 283 

280<span>Recommendation_using_embeddings.ipynb</span> </p>

281 284

282Because shorter distances between embedding vectors represent greater similarity, embeddings can be useful for recommendation.285 

286Recommendation_using_embeddings.ipynb

287 Because shorter distances between embedding vectors represent greater similarity, embeddings can be useful for recommendation.

283 288 

284Below, 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.289Below, 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.

285 290 


312 317 

313Data visualization in 2D318Data visualization in 2D

314 319 

315<p>

316 320 

317 321 

318<span>Visualizing_embeddings_in_2D.ipynb</span> </p>

319 322

320The size of the embeddings varies with the complexity of the underlying model. In order to visualize this high dimensional data we use the t-SNE algorithm to transform the data into two dimensions.323 

324Visualizing_embeddings_in_2D.ipynb

325 The size of the embeddings varies with the complexity of the underlying model. In order to visualize this high dimensional data we use the t-SNE algorithm to transform the data into two dimensions.

321 326 

322We color the individual reviews based on the star rating which the reviewer has given:327We color the individual reviews based on the star rating which the reviewer has given:

323 328 


358 363 

359Embedding as a text feature encoder for ML algorithms364Embedding as a text feature encoder for ML algorithms

360 365 

361<p>

362 366 

363 367 

364<span>Regression_using_embeddings.ipynb</span> </p>

365 368

366An 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.369 

370Regression_using_embeddings.ipynb

371 An 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.

367 372 

368We 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.373We 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.

369 374 


395 400 

396Classification using the embedding features401Classification using the embedding features

397 402 

398<p>

399 403 

400 404 

401<span>Classification_using_embeddings.ipynb</span> </p>

402 405

403This time, instead of having the algorithm predict a value anywhere between 1 and 5, we will attempt to classify the exact number of stars for a review into 5 buckets, ranging from 1 to 5 stars.406 

407Classification_using_embeddings.ipynb

408 This time, instead of having the algorithm predict a value anywhere between 1 and 5, we will attempt to classify the exact number of stars for a review into 5 buckets, ranging from 1 to 5 stars.

404 409 

405After 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.410After 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.

406 411 


416 421 

417Zero-shot classification422Zero-shot classification

418 423 

419<p>

420 424 

421 425 

422<span>Zero-shot_classification_with_embeddings.ipynb</span> </p>

423 426

424We 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.427 

428Zero-shot_classification_with_embeddings.ipynb

429 We 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.

425 430 

426```python431```python

427df = df[df.Score != 3]432df = df[df.Score != 3]


447 452 

448Obtaining user and product embeddings for cold-start recommendation453Obtaining user and product embeddings for cold-start recommendation

449 454 

450<p>

451 455 

452 456 

453<span>User_and_product_embeddings.ipynb</span> </p>

454 457

455We can obtain a user embedding by averaging over all of their reviews. Similarly, we can obtain a product embedding by averaging over all the reviews about that product. In order to showcase the usefulness of this approach we use a subset of 50k reviews to cover more reviews per user and per product.458 

459User_and_product_embeddings.ipynb

460 We can obtain a user embedding by averaging over all of their reviews. Similarly, we can obtain a product embedding by averaging over all the reviews about that product. In order to showcase the usefulness of this approach we use a subset of 50k reviews to cover more reviews per user and per product.

456 461 

457We 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.462We 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.

458 463 


464 469 

465Clustering470Clustering

466 471 

467<p>

468 472 

469 473 

470<span>Clustering.ipynb</span> </p>

471 474

472Clustering is one way of making sense of a large volume of textual data. Embeddings are useful for this task, as they provide semantically meaningful vector representations of each text. Thus, in an unsupervised way, clustering will uncover hidden groupings in our dataset.475 

476Clustering.ipynb

477 Clustering is one way of making sense of a large volume of textual data. Embeddings are useful for this task, as they provide semantically meaningful vector representations of each text. Thus, in an unsupervised way, clustering will uncover hidden groupings in our dataset.

473 478 

474In this example, we discover four distinct clusters: one focusing on dog food, one on negative reviews, and two on positive reviews.479In this example, we discover four distinct clusters: one focusing on dog food, one on negative reviews, and two on positive reviews.

475 480 

Details

1# Error codes1# Error codes

2 2 

3This guide includes an overview on error codes you might see from both the [API](https://developers.openai.com/api/docs/introduction) and our [official Python library](https://developers.openai.com/api/docs/libraries#install-an-official-sdk). Each error code mentioned in the overview has a dedicated section with further guidance.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 

5This guide includes an overview on error codes you might see from both the [API](https://developers.openai.com/api/docs/concepts) and our [official Python library](https://developers.openai.com/api/docs/libraries#install-an-official-sdk). Each error code mentioned in the overview has a dedicated section with further guidance.

4 6 

5## API errors7## API errors

6 8 


64 66 

65- If you have left or been removed from your previous organization, you can either request a new organization or get invited to an existing one.67- If you have left or been removed from your previous organization, you can either request a new organization or get invited to an existing one.

66- To request a new organization, reach out to us via help.openai.com68- To request a new organization, reach out to us via help.openai.com

67- Existing organization owners can invite you to join their organization via the [Team page](https://platform.openai.com/settings/organization/people) or can create a new project from the [Settings page](https://developers.openai.com/api/docs/guides/settings/organization/general)69- Existing organization owners can invite you to join their organization via the [Team page](https://platform.openai.com/settings/organization/people) or can create a new project from the [Settings page](https://platform.openai.com/settings/organization/general).

68- If you have left or been removed from a previous project, you can ask your organization or project owner to add you to it, or create a new one.70- If you have left or been removed from a previous project, you can ask your organization or project owner to add you to it, or create a new one.

69 71 

70429 - Rate limit reached for requests72429 - Rate limit reached for requests


125| APIConnectionError | **Cause:** Issue connecting to our services. <br /> **Solution:** Check your network settings, proxy configuration, SSL certificates, or firewall rules. |127| APIConnectionError | **Cause:** Issue connecting to our services. <br /> **Solution:** Check your network settings, proxy configuration, SSL certificates, or firewall rules. |

126| APITimeoutError | **Cause:** Request timed out. <br /> **Solution:** Retry your request after a brief wait and contact us if the issue persists. |128| APITimeoutError | **Cause:** Request timed out. <br /> **Solution:** Retry your request after a brief wait and contact us if the issue persists. |

127| AuthenticationError | **Cause:** Your API key or token was invalid, expired, or revoked. <br /> **Solution:** Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard. |129| AuthenticationError | **Cause:** Your API key or token was invalid, expired, or revoked. <br /> **Solution:** Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard. |

128| BadRequestError | **Cause:** Your request was malformed or missing some required parameters, such as a token or an input. <br /> **Solution:** The error message should advise you on the specific error made. Check the [documentation](https://developers.openai.com/api/docs/api-reference/) for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data. |130| BadRequestError | **Cause:** Your request was malformed or missing some required parameters, such as a token or an input. <br /> **Solution:** The error message should advise you on the specific error made. Check the [documentation](https://developers.openai.com/api/reference/overview) for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data. |

129| ConflictError | **Cause:** The resource was updated by another request. <br /> **Solution:** Try to update the resource again and ensure no other requests are trying to update it. |131| ConflictError | **Cause:** The resource was updated by another request. <br /> **Solution:** Try to update the resource again and ensure no other requests are trying to update it. |

130| InternalServerError | **Cause:** Issue on our side. <br /> **Solution:** Retry your request after a brief wait and contact us if the issue persists. |132| InternalServerError | **Cause:** Issue on our side. <br /> **Solution:** Retry your request after a brief wait and contact us if the issue persists. |

131| NotFoundError | **Cause:** Requested resource does not exist. <br /> **Solution:** Ensure you are the correct resource identifier. |133| NotFoundError | **Cause:** Requested resource does not exist. <br /> **Solution:** Ensure you are the correct resource identifier. |


172If you encounter an `BadRequestError`, please try the following steps:174If you encounter an `BadRequestError`, please try the following steps:

173 175 

174- Read the error message carefully and identify the specific error made. The error message should advise you on what parameter was invalid or missing, and what value or format was expected.176- Read the error message carefully and identify the specific error made. The error message should advise you on what parameter was invalid or missing, and what value or format was expected.

175- Check the [API Reference](https://developers.openai.com/api/docs/api-reference/) for the specific API method you were calling and make sure you are sending valid and complete parameters. You may need to review the parameter names, types, values, and formats, and ensure they match the documentation.177- Check the [API Reference](https://developers.openai.com/api/reference/overview) for the specific API method you were calling and make sure you are sending valid and complete parameters. You may need to review the parameter names, types, values, and formats, and ensure they match the documentation.

176- Check the encoding, format, or size of your request data and make sure they are compatible with our services. You may need to encode your data in UTF-8, format your data in JSON, or compress your data if it is too large.178- Check the encoding, format, or size of your request data and make sure they are compatible with our services. You may need to encode your data in UTF-8, format your data in JSON, or compress your data if it is too large.

177- Test your request using a tool like Postman or curl and make sure it works as expected. You may need to debug your code and fix any errors or inconsistencies in your request logic.179- Test your request using a tool like Postman or curl and make sure it works as expected. You may need to debug your code and fix any errors or inconsistencies in your request logic.

178- If the issue persists, check out our persistent errors next steps section.180- If the issue persists, check out our persistent errors next steps section.

guides/evals.md +20 −46

Details

1# Working with evals1# Working with evals

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.

4 

3Evaluations (often called **evals**) test model outputs to ensure they meet style and content criteria that you specify. Writing evals to understand how your LLM applications are performing against your expectations, especially when upgrading or trying new models, is an essential component to building reliable applications.5Evaluations (often called **evals**) test model outputs to ensure they meet style and content criteria that you specify. Writing evals to understand how your LLM applications are performing against your expectations, especially when upgrading or trying new models, is an essential component to building reliable applications.

4 6 

5In this guide, we will focus on **configuring evals programmatically using the [Evals API](https://developers.openai.com/api/docs/api-reference/evals)**. If you prefer, you can also configure evals [in the OpenAI dashboard](https://platform.openai.com/evaluations).7In this guide, we will focus on **configuring evals programmatically using the [Evals API](https://developers.openai.com/api/reference/resources/evals)**. If you prefer, you can also configure evals [in the OpenAI dashboard](https://platform.openai.com/evaluations).

6 8 

7OpenAI is deprecating the Evals platform. Existing evals content remains9OpenAI is deprecating the Evals platform. Existing evals content remains

8 available during the transition window. Evals will become read-only for10 available during the transition window. Evals will become read-only for


211. Run your eval with test inputs (a prompt and input data)231. Run your eval with test inputs (a prompt and input data)

221. Analyze the results, then iterate and improve on your prompt241. Analyze the results, then iterate and improve on your prompt

23 25 

24This process is somewhat similar to behavior-driven development (BDD), where you begin by specifying how the system should behave before implementing and testing the system. Let's see how we would complete each of the steps above using the [Evals API](https://developers.openai.com/api/docs/api-reference/evals).26This process is somewhat similar to behavior-driven development (BDD), where you begin by specifying how the system should behave before implementing and testing the system. Let's see how we would complete each of the steps above using the [Evals API](https://developers.openai.com/api/reference/resources/evals).

25 27 

26## Create an eval for a task28## Create an eval for a task

27 29 

28Creating an eval begins by describing a task to be done by a model. Let's say that we would like to use a model to classify the contents of IT support tickets into one of three categories: `Hardware`, `Software`, or `Other`.30Creating an eval begins by describing a task to be done by a model. Let's say that we would like to use a model to classify the contents of IT support tickets into one of three categories: `Hardware`, `Software`, or `Other`.

29 31 

30To implement this use case, you can use either the [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat) or the [Responses API](https://developers.openai.com/api/docs/api-reference/responses). Both examples below combine a [developer message](https://developers.openai.com/api/docs/guides/text) with a user message containing the text of a support ticket.32To implement this use case, you can use either the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat) or the [Responses API](https://developers.openai.com/api/reference/resources/responses). Both examples below combine a [developer message](https://developers.openai.com/api/docs/guides/text) with a user message containing the text of a support ticket.

31 33 

32 34 

33 Categorize IT support tickets35 Categorize IT support tickets


102 104 

103 105 

104 106 

105Let's set up an eval to test this behavior [via API](https://developers.openai.com/api/docs/api-reference/evals). An eval needs two key ingredients:107Let's set up an eval to test this behavior [via API](https://developers.openai.com/api/reference/resources/evals). An eval needs two key ingredients:

106 108 

107- `data_source_config`: A schema for the test data you will use along with the eval.109- `data_source_config`: A schema for the test data you will use along with the eval.

108- `testing_criteria`: The [graders](https://developers.openai.com/api/docs/guides/graders) that determine if the model output is correct.110- `testing_criteria`: The [graders](https://developers.openai.com/api/docs/guides/graders) that determine if the model output is correct.


292 294 

293This data set contains both test inputs and ground truth labels to compare model outputs against.295This data set contains both test inputs and ground truth labels to compare model outputs against.

294 296 

295Next, let's upload our test data file to the OpenAI platform so we can reference it later. You can upload files [in the dashboard here](https://platform.openai.com/storage/files), but it's possible to [upload files via API](https://developers.openai.com/api/docs/api-reference/files/create) as well. The samples below assume you are running the command in a directory where you saved the sample JSON data above to a file called `tickets.jsonl`:297Next, let's upload our test data file to the OpenAI platform so we can reference it later. You can upload files [in the dashboard here](https://platform.openai.com/storage/files), but it's possible to [upload files via API](https://developers.openai.com/api/reference/resources/files/methods/create) as well. The samples below assume you are running the command in a directory where you saved the sample JSON data above to a file called `tickets.jsonl`:

296 298 

297Upload a test data file299Upload a test data file

298 300 


346 348 

347### Creating an eval run349### Creating an eval run

348 350 

349With our test data in place, let's evaluate a prompt and see how it performs against our test criteria. Via API, we can do this by [creating an eval run](https://developers.openai.com/api/docs/api-reference/evals/createRun).351With our test data in place, let's evaluate a prompt and see how it performs against our test criteria. Via API, we can do this by [creating an eval run](https://developers.openai.com/api/reference/resources/evals/methods/create).

350 352 

351Make sure to replace `YOUR_EVAL_ID` and `YOUR_FILE_ID` with the unique IDs of the eval configuration and test data files you created in the steps above.353Make sure to replace `YOUR_EVAL_ID` and `YOUR_FILE_ID` with the unique IDs of the eval configuration and test data files you created in the steps above.

352 354 


433 435 

434 436 

435 437 

436When we create the run, we set up a prompt using either a [Chat Completions](https://developers.openai.com/api/docs/guides/text?api-mode=chat) messages array or a [Responses](https://developers.openai.com/api/docs/api-reference/responses) input. This prompt is used to generate a model response for every line of test data in your data set. We can use the double curly brace syntax to template in the dynamic variable `item.ticket_text`, which is drawn from the current test data item.438When we create the run, we set up a prompt using either a [Chat Completions](https://developers.openai.com/api/docs/guides/text?api-mode=chat) messages array or a [Responses](https://developers.openai.com/api/reference/resources/responses) input. This prompt is used to generate a model response for every line of test data in your data set. We can use the double curly brace syntax to template in the dynamic variable `item.ticket_text`, which is drawn from the current test data item.

437 439 

438If the eval run is successfully created, you'll receive an API response that looks like this:440If the eval run is successfully created, you'll receive an API response that looks like this:

439 441 


495 497 

496To receive updates when a run succeeds, fails, or is canceled, create a webhook endpoint and subscribe to the `eval.run.succeeded`, `eval.run.failed`, and `eval.run.canceled` events. See the [webhooks guide](https://developers.openai.com/api/docs/guides/webhooks) for more details.498To receive updates when a run succeeds, fails, or is canceled, create a webhook endpoint and subscribe to the `eval.run.succeeded`, `eval.run.failed`, and `eval.run.canceled` events. See the [webhooks guide](https://developers.openai.com/api/docs/guides/webhooks) for more details.

497 499 

498Depending on the size of your dataset, the eval run may take some time to complete. You can view current status in the dashboard, but you can also [fetch the current status of an eval run via API](https://developers.openai.com/api/docs/api-reference/evals/getRun):500Depending on the size of your dataset, the eval run may take some time to complete. You can view current status in the dashboard, but you can also [fetch the current status of an eval run via API](https://developers.openai.com/api/reference/resources/evals/methods/retrieve):

499 501 

500Retrieve eval run status502Retrieve eval run status

501 503 


606 608 

607Now you know how to create and run evals via API, and using the dashboard! Here are a few other resources that may be useful to you as you continue to improve your model results.609Now you know how to create and run evals via API, and using the dashboard! Here are a few other resources that may be useful to you as you continue to improve your model results.

608 610 

609<a611[Cookbook: Detecting prompt regressions

610 href="https://cookbook.openai.com/examples/evaluation/use-cases/regression"

611 target="_blank"

612 rel="noreferrer"

613>

614 612 

615 613 

616<span slot="icon">

617 </span>

618 Keep tabs on the performance of your prompts as you iterate on them.

619 614 

615 Keep tabs on the performance of your prompts as you iterate on them.](https://developers.openai.com/cookbook/examples/evaluation/use-cases/regression)

620 616 

621</a>617[Cookbook: Bulk model and prompt experimentation

622 618 

623<a

624 href="https://cookbook.openai.com/examples/evaluation/use-cases/bulk-experimentation"

625 target="_blank"

626 rel="noreferrer"

627>

628 619 

629 620 

630<span slot="icon">621 Compare the results of many different prompts and models at once.](https://developers.openai.com/cookbook/examples/evaluation/use-cases/bulk-experimentation)

631 </span>

632 Compare the results of many different prompts and models at once.

633 622 

623[Cookbook: Monitoring stored completions

634 624 

635</a>

636 625 

637<a

638 href="https://cookbook.openai.com/examples/evaluation/use-cases/completion-monitoring"

639 target="_blank"

640 rel="noreferrer"

641>

642 626 

627 Examine stored completions to test for prompt regressions.](https://developers.openai.com/cookbook/examples/evaluation/use-cases/completion-monitoring)

643 628 

644<span slot="icon">629[Fine-tuning

645 </span>

646 Examine stored completions to test for prompt regressions.

647 630 

648 631 

649</a>

650 632 

651[633 Improve a model's ability to generate responses tailored to your use case.](https://developers.openai.com/api/docs/guides/model-optimization)

634[Model distillation

652 635 

653<span slot="icon">

654 </span>

655 Improve a model's ability to generate responses tailored to your use case.

656 636 

657](https://developers.openai.com/api/docs/guides/fine-tuning)

658[

659 637 

660<span slot="icon">

661 </span>

662 Learn how to distill large model results to smaller, cheaper, and faster638 Learn how to distill large model results to smaller, cheaper, and faster

663 models.639 models.](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#distilling-from-a-larger-model)

664 

665](https://developers.openai.com/api/docs/guides/distillation)

Details

1# Evaluation best practices1# Evaluation best practices

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.

4 

3Generative AI is variable. Models sometimes produce different output from the same input, which makes traditional software testing methods insufficient for AI architectures. Evaluations (**evals**) are a way to test your AI system despite this variability.5Generative AI is variable. Models sometimes produce different output from the same input, which makes traditional software testing methods insufficient for AI architectures. Evaluations (**evals**) are a way to test your AI system despite this variability.

4 6 

5This guide provides high-level guidance on designing evals. To get started with the [Evals API](https://developers.openai.com/api/docs/api-reference/evals), see [evaluating model performance](https://developers.openai.com/api/docs/guides/evals).7This guide provides high-level guidance on designing evals. To get started with the [Evals API](https://developers.openai.com/api/reference/resources/evals), see [evaluating model performance](https://developers.openai.com/api/docs/guides/evals).

6 8 

7OpenAI is deprecating the Evals platform. Existing evals content remains9OpenAI is deprecating the Evals platform. Existing evals content remains

8 available during the transition window. Evals will become read-only for10 available during the transition window. Evals will become read-only for


30You'll often see numerical eval scores between 0 and 1. There's more to evals than just scores. Combine metrics with human judgment to ensure you're answering the right questions.32You'll often see numerical eval scores between 0 and 1. There's more to evals than just scores. Combine metrics with human judgment to ensure you're answering the right questions.

31 33 

32**Evals tips**34**Evals tips**

33<br/>35 

36 

34- Adopt eval-driven development: Evaluate early and often. Write scoped tests at every stage.37- Adopt eval-driven development: Evaluate early and often. Write scoped tests at every stage.

35- Design task-specific evals: Make tests reflect model capability in real-world distributions.38- Design task-specific evals: Make tests reflect model capability in real-world distributions.

36- Log everything: Log as you develop so you can mine your logs for good eval cases.39- Log everything: Log as you develop so you can mine your logs for good eval cases.


40 43 

41**Anti-patterns**44**Anti-patterns**

42 45 

43<br/>46 

47 

44- Overly generic metrics: Relying solely on academic metrics like perplexity or BLEU score.48- Overly generic metrics: Relying solely on academic metrics like perplexity or BLEU score.

45- Biased design: Creating eval datasets that don't faithfully reproduce production traffic patterns.49- Biased design: Creating eval datasets that don't faithfully reproduce production traffic patterns.

46- Vibe-based evals: Using "it seems like it's working" as an evaluation strategy, or waiting until you ship before implementing any evals.50- Vibe-based evals: Using "it seems like it's working" as an evaluation strategy, or waiting until you ship before implementing any evals.


62 66 

63To test your LLM-based application's ability to summarize transcripts, your eval design might be:67To test your LLM-based application's ability to summarize transcripts, your eval design might be:

64 68 

651. **Define eval objective**<br/>691. **Define eval objective**

70 

66 The model should be able to compete with reference summaries for relevance and accuracy.71 The model should be able to compete with reference summaries for relevance and accuracy.

671. **Collect dataset**<br/>721. **Collect dataset**

73 

68 Use a mix of production data (collected from user feedback on generated summaries) and datasets created by domain experts (writers) to determine a "good" summary.74 Use a mix of production data (collected from user feedback on generated summaries) and datasets created by domain experts (writers) to determine a "good" summary.

691. **Define eval metrics**<br/>751. **Define eval metrics**

76 

70 On a held-out set of 1000 reference transcripts → summaries, the implementation should achieve a ROUGE-L score of at least 0.40 and coherence score of at least 80% using G-Eval.77 On a held-out set of 1000 reference transcripts → summaries, the implementation should achieve a ROUGE-L score of at least 0.40 and coherence score of at least 80% using G-Eval.

711. **Run and compare evals**<br/>781. **Run and compare evals**

79 

72 Use the [Evals API](https://developers.openai.com/api/docs/guides/evals) to create and run evals in the OpenAI dashboard.80 Use the [Evals API](https://developers.openai.com/api/docs/guides/evals) to create and run evals in the OpenAI dashboard.

731. **Continuously evaluate**<br/>811. **Continuously evaluate**

82 

74 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.83 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.

75 84 

76LLMs are better at discriminating between options. Therefore, evaluations85LLMs are better at discriminating between options. Therefore, evaluations


83 92 

84To test your LLM-based application's ability to do Q&A over docs, your eval design might be:93To test your LLM-based application's ability to do Q&A over docs, your eval design might be:

85 94 

861. **Define eval objective**<br/>951. **Define eval objective**

96 

87 The model should be able to provide precise answers, recall context as needed to reason through user prompts, and provide an answer that satisfies the user's need.97 The model should be able to provide precise answers, recall context as needed to reason through user prompts, and provide an answer that satisfies the user's need.

881. **Collect dataset**<br/>981. **Collect dataset**

99 

89 Use a mix of production data (collected from users' satisfaction with answers provided to their questions), hard-coded correct answers to questions created by domain experts, and historical data from logs.100 Use a mix of production data (collected from users' satisfaction with answers provided to their questions), hard-coded correct answers to questions created by domain experts, and historical data from logs.

901. **Define eval metrics**<br/>1011. **Define eval metrics**

102 

91 Context recall of at least 0.85, context precision of over 0.7, and 70+% positively rated answers.103 Context recall of at least 0.85, context precision of over 0.7, and 70+% positively rated answers.

921. **Run and compare evals**<br/>1041. **Run and compare evals**

105 

93 Use the [Evals API](https://developers.openai.com/api/docs/guides/evals) to create and run evals in the OpenAI dashboard.106 Use the [Evals API](https://developers.openai.com/api/docs/guides/evals) to create and run evals in the OpenAI dashboard.

941. **Continuously evaluate**<br/>1071. **Continuously evaluate**

108 

95 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.

96 110 

97When creating an eval dataset, 111When creating an eval dataset,


139 <td>153 <td>

140 **Instruction following**: Does the model accurately understand and act154 **Instruction following**: Does the model accurately understand and act

141 according to the provided instructions?155 according to the provided instructions?

142 <br />156

143 <br />157 

158

159 

144 **Instruction following**: Does the model prioritize the system prompt160 **Instruction following**: Does the model prioritize the system prompt

145 over a conflicting user prompt?161 over a conflicting user prompt?

146 </td>162 </td>


187 <td>203 <td>

188 **Instruction following**: Does the model accurately understand and act204 **Instruction following**: Does the model accurately understand and act

189 according to the provided instructions?205 according to the provided instructions?

190 <br />206

191 <br />207 

208

209 

192 **Instruction following**: Does the model prioritize the system prompt210 **Instruction following**: Does the model prioritize the system prompt

193 over a conflicting user prompt?211 over a conflicting user prompt?

194 </td>212 </td>

195 <td>213 <td>

196 Does the model stay focused on the triage task or get swayed by the user's214 Does the model stay focused on the triage task or get swayed by the user's

197 question?215 question?

198 <br />216

199 <br /> Does the model follow instructions to attempt to extract an Order217 

218

219 Does the model follow instructions to attempt to extract an Order

200 ID?220 ID?

201 <br />221

202 <br />222 

223

224 

203 Does the final response include the order status, estimated arrival date,225 Does the final response include the order status, estimated arrival date,

204 and tracking number?226 and tracking number?

205 </td>227 </td>


213 <td>235 <td>

214 Does the model's determination of intent correctly match the expected236 Does the model's determination of intent correctly match the expected

215 intent?237 intent?

216 <br />238

217 <br />239 

240

241 

218 Does the final response have the correct order status, estimated arrival242 Does the final response have the correct order status, estimated arrival

219 date, and tracking number?243 date, and tracking number?

220 </td>244 </td>


251 <td>275 <td>

252 **Instruction following**: Does the model accurately understand and act276 **Instruction following**: Does the model accurately understand and act

253 according to the provided instructions?277 according to the provided instructions?

254 <br />278

255 <br />279 

280

281 

256 **Instruction following**: Does the model prioritize the system prompt282 **Instruction following**: Does the model prioritize the system prompt

257 over a conflicting user prompt?283 over a conflicting user prompt?

258 </td>284 </td>

259 <td>285 <td>

260 Does the model stay focused on the triage task or get swayed by the user's286 Does the model stay focused on the triage task or get swayed by the user's

261 question?287 question?

262 <br />288

263 <br />289 

290

291 

264 Does the model follow instructions to attempt to extract an Order ID?292 Does the model follow instructions to attempt to extract an Order ID?

265 </td>293 </td>

266 </tr>294 </tr>


280 <td>308 <td>

281 **Tool selection**: Evaluations that test whether the agent is able to309 **Tool selection**: Evaluations that test whether the agent is able to

282 select the correct tool to use.310 select the correct tool to use.

283 <br />311

284 <br />312 

313

314 

285 **Data precision**: Evaluations that verify the agent calls the tool with315 **Data precision**: Evaluations that verify the agent calls the tool with

286 the correct arguments. Typically these arguments are extracted from the316 the correct arguments. Typically these arguments are extracted from the

287 conversation history, so the goal is to validate this extraction was317 conversation history, so the goal is to validate this extraction was


290 <td>320 <td>

291 When the user asks about their order status, does the model correctly321 When the user asks about their order status, does the model correctly

292 recommend invoking the order lookup tool?322 recommend invoking the order lookup tool?

293 <br />323

294 <br />324 

325

326 

295 Does the model correctly extract the user-provided order ID to the lookup327 Does the model correctly extract the user-provided order ID to the lookup

296 tool?328 tool?

297 </td>329 </td>


325 </tr>357 </tr>

326 <tr>358 <tr>

327 <td>Inputs provided by the developer and user</td>359 <td>Inputs provided by the developer and user</td>

328 <td>**Instruction following**: Does the model accurately understand and act according to the provided instructions?<br/><br/>**Instruction following**: Does the model prioritize the system prompt over a conflicting user prompt?</td>360 <td>**Instruction following**: Does the model accurately understand and act according to the provided instructions?

329 <td>Does the model stay focused on the triage task or get swayed by the user's question?<br/><br/>Assuming the `lookup_order` call returned, does the order agent return a tracking number and delivery date (doesn't have to be the correct one)?</td>361 

362**Instruction following**: Does the model prioritize the system prompt over a conflicting user prompt?</td>

363 <td>Does the model stay focused on the triage task or get swayed by the user's question?

364 

365Assuming the `lookup_order` call returned, does the order agent return a tracking number and delivery date (doesn't have to be the correct one)?</td>

330 </tr>366 </tr>

331 <tr>367 <tr>

332 <td>Outputs generated by the model</td>368 <td>Outputs generated by the model</td>

333 <td>**Functional correctness**: Are the model's outputs are accurate, relevant, and thorough enough to fulfill the intended task or objective?</td>369 <td>**Functional correctness**: Are the model's outputs are accurate, relevant, and thorough enough to fulfill the intended task or objective?</td>

334 <td>Does the model's determination of intent correctly match the expected intent?<br/><br/>Assuming the `lookup_order` call returned, does the order agent provide the correct tracking number and delivery date in its response?<br/><br/>Does the order agent follow system instructions to ask the customer their reason for requesting a return before processing the return?</td>370 <td>Does the model's determination of intent correctly match the expected intent?

371 

372Assuming the `lookup_order` call returned, does the order agent provide the correct tracking number and delivery date in its response?

373 

374Does the order agent follow system instructions to ask the customer their reason for requesting a return before processing the return?</td>

335 </tr>375 </tr>

336 <tr>376 <tr>

337 <td>Tools chosen by the model</td>377 <td>Tools chosen by the model</td>

338 <td>**Tool selection**: Evaluations that test whether the agent is able to select the correct tool to use.<br/><br/>**Data precision**: Evaluations that verify the agent calls the tool with the correct arguments. Typically these arguments are extracted from the conversation history, so the goal is to validate this extraction was correct.</td>378 <td>**Tool selection**: Evaluations that test whether the agent is able to select the correct tool to use.

339 <td>Does the order agent correctly call the lookup order tool?<br/><br/>Does the order agent correctly call the `refund_order` tool?<br/><br/>Does the order agent call the lookup order tool with the correct order ID?<br/><br/>Does the account agent correctly call the `reset_password` tool with the correct account ID?</td>379 

380**Data precision**: Evaluations that verify the agent calls the tool with the correct arguments. Typically these arguments are extracted from the conversation history, so the goal is to validate this extraction was correct.</td>

381 <td>Does the order agent correctly call the lookup order tool?

382 

383Does the order agent correctly call the `refund_order` tool?

384 

385Does the order agent call the lookup order tool with the correct order ID?

386 

387Does the account agent correctly call the `reset_password` tool with the correct account ID?</td>

340 </tr>388 </tr>

341 389 

342 <tr>390 <tr>

343 <td>Agent handoff</td>391 <td>Agent handoff</td>

344 <td>**Agent handoff accuracy**: Evaluations that test whether each agent can appropriately recognize the decision boundary for triaging to another agent</td>392 <td>**Agent handoff accuracy**: Evaluations that test whether each agent can appropriately recognize the decision boundary for triaging to another agent</td>

345 <td>When a user asks about order status, does the triage agent correctly pass to the order agent?<br/><br/>When the user changes the subject to talk about the latest product, does the order agent hand back control to the triage agent?</td>393 <td>When a user asks about order status, does the triage agent correctly pass to the order agent?

394 

395When the user changes the subject to talk about the latest product, does the order agent hand back control to the triage agent?</td>

346 </tr>396 </tr>

347</table>397</table>

348 398 


441- [How to evaluate a summarization task](https://developers.openai.com/cookbook/examples/evaluation/how_to_eval_abstractive_summarization)491- [How to evaluate a summarization task](https://developers.openai.com/cookbook/examples/evaluation/how_to_eval_abstractive_summarization)

442- [Fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)492- [Fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)

443- [Graders](https://developers.openai.com/api/docs/guides/graders)493- [Graders](https://developers.openai.com/api/docs/guides/graders)

444- [Evals API reference](https://developers.openai.com/api/docs/api-reference/evals)494- [Evals API reference](https://developers.openai.com/api/reference/resources/evals)

Details

1# Getting started with datasets1# Getting started with datasets

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.

4 

3Evaluations (often called **evals**) test model outputs to ensure they meet your specified style and content criteria. Writing evals is an essential part of building reliable applications. [Datasets](https://platform.openai.com/evaluation/datasets), a feature of the OpenAI platform, provide a quick way to get started with evals and test prompts.5Evaluations (often called **evals**) test model outputs to ensure they meet your specified style and content criteria. Writing evals is an essential part of building reliable applications. [Datasets](https://platform.openai.com/evaluation/datasets), a feature of the OpenAI platform, provide a quick way to get started with evals and test prompts.

4 6 

5OpenAI is deprecating the Evals platform. Existing evals content remains7OpenAI is deprecating the Evals platform. Existing evals content remains


66 68 

671. In the prompt panel, use the provided fields and settings to control the inference call:691. In the prompt panel, use the provided fields and settings to control the inference call:

68 70 

69- Click the slider icon in the top right to control model [`temperature`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-temperature) and [`top_p`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-top_p).71- Click the slider icon in the top right to control model [`temperature`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-temperature) and [`top_p`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-top_p).

70- Add tools to grant your inference call the ability to access the web, use an MCP, or complete other tool-call actions.72- Add tools to grant your inference call the ability to access the web, use an MCP, or complete other tool-call actions.

71- Add variables. The prompt and your [graders](#add-graders) can both refer to these variables.73- Add variables. The prompt and your [graders](#add-graders) can both refer to these variables.

72- Type your system message directly, or click the pencil icon to have a model help generate a prompt for you, based on basic instructions you provide.74- Type your system message directly, or click the pencil icon to have a model help generate a prompt for you, based on basic instructions you provide.


152 154 

153For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook/topic/evals), which contains example code and links to third-party resources, or learn more about our evaluation tools:155For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook/topic/evals), which contains example code and links to third-party resources, or learn more about our evaluation tools:

154 156 

155<a157[Cookbook: Building resilient prompts with evals

156 href="https://cookbook.openai.com/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel"

157 target="_blank"

158 rel="noreferrer"

159>

160

161 

162<span slot="icon">

163 </span>

164 Operate a flywheel of continuous improvement using evaluations.

165 158 

166 159 

167</a>

168 160 

169<a href="/api/docs/guides/evals" target="_blank" rel="noreferrer">161 Operate a flywheel of continuous improvement using evaluations.](https://developers.openai.com/cookbook/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel)

170 162 

163[Working with evals

171 164 

172<span slot="icon">

173 </span>

174 Evaluate against external models, interact with evals via API, and more.

175 165 

176 166 

177</a>167 Evaluate against external models, interact with evals via API, and more.](https://developers.openai.com/api/docs/guides/evals)

178 168 

179<a href="/api/docs/guides/prompt-optimizer" target="_blank" rel="noreferrer">169[Prompt optimizer

180 170 

181 171 

182<span slot="icon">

183 </span>

184 Use your dataset to automatically improve your prompts.

185 172 

173 Use your dataset to automatically improve your prompts.](https://developers.openai.com/api/docs/guides/prompt-optimizer)

186 174 

187</a>175[Graders

188 176 

189[

190 177 

191<span slot="icon">

192 </span>

193 Build sophisticated graders to improve the effectiveness of your evals.

194 178 

195](https://developers.openai.com/api/docs/guides/graders)179 Build sophisticated graders to improve the effectiveness of your evals.](https://developers.openai.com/api/docs/guides/graders)

Details

1# Evaluate external models1# Evaluate external models

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.

4 

3Model selection is an important lever that enables builders to improve their AI applications. When using Evaluations on the OpenAI Platform, in addition to evaluating OpenAI’s native models, you can also evaluate a variety of external models.5Model selection is an important lever that enables builders to improve their AI applications. When using Evaluations on the OpenAI Platform, in addition to evaluating OpenAI’s native models, you can also evaluate a variety of external models.

4 6 

5We support accessing **third-party models** (no API key required) and accessing **custom endpoints** (API key required).7We support accessing **third-party models** (no API key required) and accessing **custom endpoints** (API key required).


15 17 

16In order to use third-party models, the following must be true:18In order to use third-party models, the following must be true:

17 19 

18- Your OpenAI organization must be in [usage tier 1](https://developers.openai.com/api/docs/guides/rate-limits/usage-tiers#usage-tiers) or higher.20- Your OpenAI organization must be in [usage tier 1](https://developers.openai.com/api/docs/guides/rate-limits#usage-tiers) or higher.

19- An admin for your OpenAI organization must enable this feature via [Settings > Organization > General](https://platform.openai.com/settings/organization/general). To enable this feature, the admin must accept the usage disclaimer shown.21- An admin for your OpenAI organization must enable this feature via [Settings > Organization > General](https://platform.openai.com/settings/organization/general). To enable this feature, the admin must accept the usage disclaimer shown.

20 22 

21Calls made to external models pass data to third parties and are subject to23Calls made to external models pass data to third parties and are subject to


52 54 

53Once you are eligible to use custom providers, you can set up a provider under the **Evaluations** tab under [Settings](https://platform.openai.com/settings/). Note that custom providers are configured on a per-project basis. To connect your custom endpoint, you will need:55Once you are eligible to use custom providers, you can set up a provider under the **Evaluations** tab under [Settings](https://platform.openai.com/settings/). Note that custom providers are configured on a per-project basis. To connect your custom endpoint, you will need:

54 56 

55- An endpoint compatible with [OpenAI’s chat completions endpoint](https://developers.openai.com/api/docs/api-reference/chat/create)57- An endpoint compatible with [OpenAI’s chat completions endpoint](https://developers.openai.com/api/reference/resources/chat)

56- An API key58- An API key

57 59 

58Name your endpoint, provide an endpoint URL, and specify your API key. We require that you use an `https://` endpoint, and we encrypt your keys for security. Specify any model names (slugs) you wish to evaluate. You can click the **Verify** button to ensure that your models are set up correctly. This will make a test call containing minimal input to each of your model slugs, and will indicate any failures.60Name your endpoint, provide an endpoint URL, and specify your API key. We require that you use an `https://` endpoint, and we encrypt your keys for security. Specify any model names (slugs) you wish to evaluate. You can click the **Verify** button to ensure that your models are set up correctly. This will make a test call containing minimal input to each of your model slugs, and will indicate any failures.


70 72 

71For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and links to third-party resources, or learn more about our tools for evals:73For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and links to third-party resources, or learn more about our tools for evals:

72 74 

73<a75[Getting started with evals

74 href="/api/docs/guides/evaluation-getting-started"

75 target="_blank"

76 rel="noreferrer"

77>

78

79 

80<span slot="icon">

81 </span>

82 Uses Datasets to quickly build evals and iterate on prompts.

83 76 

84 77 

85</a>

86 78 

87<a href="/api/docs/guides/evals" target="_blank" rel="noreferrer">79 Uses Datasets to quickly build evals and iterate on prompts.](https://developers.openai.com/api/docs/guides/evaluation-getting-started)

88 80 

81[Working with evals

89 82 

90<span slot="icon">

91 </span>

92 Evaluate against external models, interact with evals via API, and more.

93 83 

94 84 

95</a>85 Evaluate against external models, interact with evals via API, and more.](https://developers.openai.com/api/docs/guides/evals)

Details

1# File inputs1# File inputs

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.

4 

3OpenAI models can accept files as `input_file` items. In the Responses API, you can send a file as Base64-encoded data, a file ID returned by the Files API (`/v1/files`), or an external URL.5OpenAI models can accept files as `input_file` items. In the Responses API, you can send a file as Base64-encoded data, a file ID returned by the Files API (`/v1/files`), or an external URL.

4 6 

5## How it works7## How it works


195```197```

196 198 

197```csharp199```csharp

198using OpenAI.Files;

199using OpenAI.Responses;200using OpenAI.Responses;

201#pragma warning disable OPENAI001

200 202 

201string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;203string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

202OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);204ResponsesClient client = new(key);

203 205 

204using HttpClient http = new();206Uri fileUrl = new(

205using Stream stream = await http.GetStreamAsync("https://www.berkshirehathaway.com/letters/2024ltr.pdf");207 "https://www.berkshirehathaway.com/letters/2024ltr.pdf"

206OpenAIFileClient files = new(key);208);

207OpenAIFile file = files.UploadFile(stream, "2024ltr.pdf", FileUploadPurpose.UserData);

208 209 

209OpenAIResponse response = (OpenAIResponse)client.CreateResponse([210ResponseResult response = await client.CreateResponseAsync(

210 ResponseItem.CreateUserMessageItem([211 "gpt-5.6",

211 ResponseContentPart.CreateInputTextPart("Analyze the letter and provide a summary of the key points."),212 [

212 ResponseContentPart.CreateInputFilePart(file.Id),213 ResponseItem.CreateUserMessageItem(

213 ]),214 [

214]);215 ResponseContentPart.CreateInputTextPart(

216 "Analyze the letter and provide a summary of the key points."

217 ),

218 ResponseContentPart.CreateInputFilePart(fileUrl),

219 ]

220 ),

221 ]

222);

215 223 

216Console.WriteLine(response.GetOutputText());224Console.WriteLine(response.GetOutputText());

217```225```


223 231 

224## Uploading files232## Uploading files

225 233 

226The following example uploads a file with the [Files API](https://developers.openai.com/api/docs/api-reference/files), then references its file ID in a request to the model.234The following example uploads a file with the [Files API](https://developers.openai.com/api/reference/resources/files), then references its file ID in a request to the model.

227 235 

228 236 

229 237 


348```csharp356```csharp

349using OpenAI.Files;357using OpenAI.Files;

350using OpenAI.Responses;358using OpenAI.Responses;

359#pragma warning disable OPENAI001

351 360 

352string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;361string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

353OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);362ResponsesClient client = new(key);

354 363 

355OpenAIFileClient files = new(key);364OpenAIFileClient files = new(key);

356OpenAIFile file = files.UploadFile("draconomicon.pdf", FileUploadPurpose.UserData);

357 365 

358OpenAIResponse response = (OpenAIResponse)client.CreateResponse([366OpenAIFile file = await files.UploadFileAsync(

359 ResponseItem.CreateUserMessageItem([367 "draconomicon.pdf",

368 FileUploadPurpose.UserData

369);

370 

371ResponseResult response = await client.CreateResponseAsync(

372 "gpt-5.6",

373 [

374 ResponseItem.CreateUserMessageItem(

375 [

360 ResponseContentPart.CreateInputFilePart(file.Id),376 ResponseContentPart.CreateInputFilePart(file.Id),

361 ResponseContentPart.CreateInputTextPart("What is the first dragon in the book?"),377 ResponseContentPart.CreateInputTextPart(

362 ]),378 "What is the first dragon in the book?"

363]);379 ),

380 ]

381 ),

382 ]

383);

364 384 

365Console.WriteLine(response.GetOutputText());385Console.WriteLine(response.GetOutputText());

366```386```


480- **Token usage:** PDF parsing includes both extracted text and page images in context, which can increase token usage. In the Responses API, set `detail` to `auto` (the default), `low`, or `high` to control the amount of visual detail for PDF page images. Before deploying at scale, review pricing and token implications. [More on pricing](https://developers.openai.com/api/docs/pricing).500- **Token usage:** PDF parsing includes both extracted text and page images in context, which can increase token usage. In the Responses API, set `detail` to `auto` (the default), `low`, or `high` to control the amount of visual detail for PDF page images. Before deploying at scale, review pricing and token implications. [More on pricing](https://developers.openai.com/api/docs/pricing).

481- **File size limits:** A single request can include more than one file, but each file must be under 50 MB. The combined limit across all files in the request is 50 MB.501- **File size limits:** A single request can include more than one file, but each file must be under 50 MB. The combined limit across all files in the request is 50 MB.

482- **Supported models:** PDF parsing that includes text and page images requires models with vision capabilities, such as `gpt-4o` and later models.502- **Supported models:** PDF parsing that includes text and page images requires models with vision capabilities, such as `gpt-4o` and later models.

483- **File upload purpose:** You can upload files with any supported [purpose](https://developers.openai.com/api/docs/api-reference/files/create#files-create-purpose), but use `user_data` for files you plan to pass as model inputs.503- **File upload purpose:** You can upload files with any supported [purpose](https://developers.openai.com/api/reference/resources/files/methods/create#files-create-purpose), but use `user_data` for files you plan to pass as model inputs.

484 504 

485## Full list of accepted file types505## Full list of accepted file types

486 506 


497 517 

498Next, you might want to explore one of these resources:518Next, you might want to explore one of these resources:

499 519 

500<div>

501 [

502 520 

503<span slot="icon">

504 </span>

505 Use the Playground to develop and iterate on prompts with file inputs.

506 521 

507](https://platform.openai.com/chat/edit)522 [Experiment with file inputs in the Playground

508</div>523 

524 

525 

526 Use the Playground to develop and iterate on prompts with file inputs.](https://platform.openai.com/chat/edit)

509 527 

510<div>

511 [

512 528 

513<span slot="icon">

514 </span>

515 Check out the API reference for more options.

516 529 

517](https://developers.openai.com/api/docs/api-reference/responses)

518</div>

519 530 

520<div>

521 [

522 531 

523<span slot="icon">532 [Full API reference

524 </span>533 

534 

535 

536 Check out the API reference for more options.](https://developers.openai.com/api/reference/resources/responses)

537 

538 

539 

540 

541 

542 [Use File Search for large corpora

543 

544 

545 

525 Use retrieval over chunked files when you need scalable search instead of546 Use retrieval over chunked files when you need scalable search instead of

526 sending whole files in a single context window.547 sending whole files in a single context window.](https://developers.openai.com/api/docs/guides/tools-file-search)

548 

527 549 

528](https://developers.openai.com/api/docs/guides/tools-file-search)

529</div>

530 550 

531<div>

532 [

533 551 

534<span slot="icon">

535 </span>

536 Use Hosted Shell for advanced spreadsheet workflows such as joins,

537 aggregations, and charting.

538 552 

539](https://developers.openai.com/api/docs/guides/tools-shell#hosted-shell-quickstart)553 [Use Hosted Shell for deep spreadsheet analysis

540</div>554 

555 

556 

557 Use Hosted Shell for advanced spreadsheet workflows such as joins,

558 aggregations, and charting.](https://developers.openai.com/api/docs/guides/tools-shell#hosted-shell-quickstart)

Details

1# Fine-tuning best practices1# Fine-tuning best practices

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.

4 

3If you're not getting strong results with a fine-tuned model, consider the following iterations on your process.5If you're not getting strong results with a fine-tuned model, consider the following iterations on your process.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).


133 136 

134Before uploading your data, you may want to check formatting and potential token costs - an example of how to do this can be found in the cookbook.137Before uploading your data, you may want to check formatting and potential token costs - an example of how to do this can be found in the cookbook.

135 138 

136<a139[Fine-tuning data format validation

137 href="https://cookbook.openai.com/examples/chat_finetuning_data_prep"

138 target="_blank"

139 rel="noreferrer"

140>

141

142 140 

143<span slot="icon">

144 </span>

145 Learn about fine-tuning data formatting

146 141 

147 142 

148</a>143 Learn about fine-tuning data formatting](https://developers.openai.com/cookbook/examples/chat_finetuning_data_prep)

Details

1# Flex processing1# Flex processing

2 2 

3Flex processing provides lower costs for [Responses](https://developers.openai.com/api/docs/api-reference/responses) or [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat) requests in exchange for slower response times and occasional resource unavailability. It's ideal for non-production or lower priority tasks, such as model evaluations, data enrichment, and asynchronous workloads.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 

5Flex processing provides lower costs for [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) requests in exchange for slower response times and occasional resource unavailability. It's ideal for non-production or lower priority tasks, such as model evaluations, data enrichment, and asynchronous workloads.

4 6 

5Tokens are [priced](https://developers.openai.com/api/docs/pricing) at [Batch API rates](https://developers.openai.com/api/docs/guides/batch), with additional discounts from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).7Tokens are [priced](https://developers.openai.com/api/docs/pricing) at [Batch API rates](https://developers.openai.com/api/docs/guides/batch), with additional discounts from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).

6 8 

Details

1# Frontend prompt instructions1# Frontend prompt instructions

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.

4 

3These instructions target GPT-5.5, but many of the patterns apply to other model versions as well.5These instructions target GPT-5.5, but many of the patterns apply to other model versions as well.

4 6 

5```prompt7```prompt

Details

1# Function calling1# Function calling

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.

4 

3**Function calling** (also known as **tool calling**) provides a powerful and flexible way for OpenAI models to interface with external systems and access data outside their training data. This guide shows how you can connect a model to data and actions provided by your application. We'll show how to use function tools (defined by a JSON schema) and custom tools which work with free form text inputs and outputs.5**Function calling** (also known as **tool calling**) provides a powerful and flexible way for OpenAI models to interface with external systems and access data outside their training data. This guide shows how you can connect a model to data and actions provided by your application. We'll show how to use function tools (defined by a JSON schema) and custom tools which work with free form text inputs and outputs.

4 6 

5If your application has many functions or large schemas, you can pair function calling with [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) to defer rarely used tools and load them only when the model needs them. Only `gpt-5.4` and later models support `tool_search`.7If your application has many functions or large schemas, you can pair function calling with [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) to defer rarely used tools and load them only when the model needs them. Only `gpt-5.4` and later models support `tool_search`.


35 37 

36- The model has access to a `get_weather` **tool** that takes `location` as an argument.38- The model has access to a `get_weather` **tool** that takes `location` as an argument.

37- In response to a prompt like "what's the weather in Paris?" the model returns a **tool call** that contains a `location` argument with a value of `Paris`39- In response to a prompt like "what's the weather in Paris?" the model returns a **tool call** that contains a `location` argument with a value of `Paris`

38- The **tool call output** might return a JSON object (e.g., `{"temperature": "25", "unit": "C"}`, indicating a current temperature of 25 degrees), [Image contents](https://developers.openai.com/api/docs/guides/images), or [File contents](https://developers.openai.com/api/docs/guides/file-inputs).40- The **tool call output** might return a JSON object (e.g., `{"temperature": "25", "unit": "C"}`, indicating a current temperature of 25 degrees), [Image contents](https://developers.openai.com/api/docs/guides/images-vision), or [File contents](https://developers.openai.com/api/docs/guides/file-inputs).

39 41 

40We then send all of the tool definition, the original prompt, the model's tool call, and the tool call output back to the model to finally receive a text response like:42We then send all of the tool definition, the original prompt, the model's tool call, and the tool call output back to the model to finally receive a text response like:

41 43 


47 49 

48- A function is a specific kind of tool, defined by a JSON schema. A function definition allows the model to pass data to your application, where your code can access data or take actions suggested by the model.50- A function is a specific kind of tool, defined by a JSON schema. A function definition allows the model to pass data to your application, where your code can access data or take actions suggested by the model.

49- In addition to function tools, there are custom tools (described in this guide) that work with free text inputs and outputs.51- In addition to function tools, there are custom tools (described in this guide) that work with free text inputs and outputs.

50- There are also [built-in tools](https://developers.openai.com/api/docs/guides/tools) that are part of the OpenAI platform. These tools enable the model to [search the web](https://developers.openai.com/api/docs/guides/tools-web-search), [execute code](https://developers.openai.com/api/docs/guides/tools-code-interpreter), access the functionality of an [MCP server](https://developers.openai.com/api/docs/guides/tools-remote-mcp), and more.52- There are also [built-in tools](https://developers.openai.com/api/docs/guides/tools) that are part of the OpenAI platform. These tools enable the model to [search the web](https://developers.openai.com/api/docs/guides/tools-web-search), [execute code](https://developers.openai.com/api/docs/guides/tools-code-interpreter), access the functionality of an [MCP server](https://developers.openai.com/api/docs/guides/tools-connectors-mcp), and more.

51 53 

52### The tool calling flow54### The tool calling flow

53 55 


343 345 

3441. **Leverage OpenAI resources.**3461. **Leverage OpenAI resources.**

345 - **Generate and iterate on function schemas** in the [Playground](https://platform.openai.com/playground).347 - **Generate and iterate on function schemas** in the [Playground](https://platform.openai.com/playground).

346 - **Consider [fine-tuning](https://developers.openai.com/api/docs/guides/fine-tuning) to increase function calling accuracy** for large numbers of functions or difficult tasks. ([cookbook](https://developers.openai.com/cookbook/examples/fine_tuning_for_function_calling))348 - **Consider [fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization) to increase function calling accuracy** for large numbers of functions or difficult tasks. ([cookbook](https://developers.openai.com/cookbook/examples/fine_tuning_for_function_calling))

347 349 

348### Token Usage350### Token Usage

349 351 

350Under the hood, functions are injected into the system message in a syntax the model has been trained on. This means callable function definitions count against the model's context limit and are billed as input tokens. If you run into token limits, we suggest limiting the number of functions loaded up front, shortening descriptions where possible, or using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) so deferred tools are loaded only when needed.352Under the hood, functions are injected into the system message in a syntax the model has been trained on. This means callable function definitions count against the model's context limit and are billed as input tokens. If you run into token limits, we suggest limiting the number of functions loaded up front, shortening descriptions where possible, or using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) so deferred tools are loaded only when needed.

351 353 

352It is also possible to use [fine-tuning](https://developers.openai.com/api/docs/guides/fine-tuning#fine-tuning-examples) to reduce the number of tokens used if you have many functions defined in your tools specification.354It is also possible to use [fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization#fine-tuning-examples) to reduce the number of tokens used if you have many functions defined in your tools specification.

353 355 

354## Handling function calls356## Handling function calls

355 357 


463 465 

464The result you pass in the `function_call_output` message should typically be a string, where the format is up to you (JSON, error codes, plain text, etc.). The model will interpret that string as needed.466The result you pass in the `function_call_output` message should typically be a string, where the format is up to you (JSON, error codes, plain text, etc.). The model will interpret that string as needed.

465 467 

466For functions that return images or files, you can pass an [array of image or file objects](https://developers.openai.com/api/docs/api-reference/responses/create#responses_create-input-input_item_list-item-function_tool_call_output-output) instead of a string.468For functions that return images or files, you can pass an [array of image or file objects](https://developers.openai.com/api/reference/resources/responses/methods/create#responses_create-input-input_item_list-item-function_tool_call_output-output) instead of a string.

467 469 

468If your function has no return value (e.g. `send_email`), simply return a string that indicates success or failure. (e.g. `"success"`)470If your function has no return value (e.g. `send_email`), simply return a string that indicates success or failure. (e.g. `"success"`)

469 471 


573 575 

574 576 

575 577 

576<div data-content-switcher-pane data-value="enabled">578Strict mode enabled

577 <div class="hidden">Strict mode enabled</div>579 

578 ```json580```json

579{581{

580 "type": "function",582 "type": "function",

581 "name": "get_weather",583 "name": "get_weather",


606}608}

607```609```

608 610 

609 </div>611

610 <div data-content-switcher-pane data-value="disabled" hidden>612 

611 <div class="hidden">Strict mode disabled</div>613

612 ```json614 

615

616Strict mode disabled

617 

618```json

613{619{

614 "type": "function",620 "type": "function",

615 "name": "get_weather",621 "name": "get_weather",


636}642}

637```643```

638 644 

639 </div>

640 

641 645 

642 646 

643 647 

Details

1# Graders1# Graders

2 2 

3Graders are a way to evaluate your model's performance against reference answers. Our [graders API](https://developers.openai.com/api/docs/api-reference/graders) is a way to test your graders, experiment with results, and improve your fine-tuning or evaluation framework to get the results you want.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 

5Graders are a way to evaluate your model's performance against reference answers. Our [graders API](https://developers.openai.com/api/reference/resources/graders) is a way to test your graders, experiment with results, and improve your fine-tuning or evaluation framework to get the results you want.

4 6 

5OpenAI is deprecating graders as part of the evals and fine-tuning workflows7OpenAI is deprecating graders as part of the evals and fine-tuning workflows

6 they support. See the [deprecations page](https://developers.openai.com/api/docs/deprecations) for the8 they support. See the [deprecations page](https://developers.openai.com/api/docs/deprecations) for the


47 49 

48- `output_text`, the model output content as a string.50- `output_text`, the model output content as a string.

49- `output_json`, the model output content as a JSON object, only if `response_format` is included in the sample.51- `output_json`, the model output content as a JSON object, only if `response_format` is included in the sample.

50- `output_tools`, the model output `tool_calls`, which have the same structure as output tool calls in the [chat completions API](https://developers.openai.com/api/docs/api-reference/chat/object).52- `output_tools`, the model output `tool_calls`, which have the same structure as output tool calls in the [chat completions API](https://developers.openai.com/api/reference/resources/chat).

51- `choices`, the output choices, which has the same structure as output choices in the [chat completions API](https://developers.openai.com/api/docs/api-reference/chat/object).53- `choices`, the output choices, which has the same structure as output choices in the [chat completions API](https://developers.openai.com/api/reference/resources/chat).

52- `output_audio`, the model audio output object containing Base64-encoded `data` and a `transcript`.54- `output_audio`, the model audio output object containing Base64-encoded `data` and a `transcript`.

53 55 

54For example, to access the model output content as a string, `{{ sample.output_text }}` can be used within the grader.56For example, to access the model output content as a string, `{{ sample.output_text }}` can be used within the grader.


250 252 

251### Model grader constraints253### Model grader constraints

252 254 

253- Only the following models are supported for the `model` parameter`255- Only the following models are supported for the `model` parameter

254 - `gpt-4o-2024-08-06`256 - `gpt-4o-2024-08-06`

255 - `gpt-4o-mini-2024-07-18`257 - `gpt-4o-mini-2024-07-18`

256 - `gpt-4.1-2025-04-14`258 - `gpt-4.1-2025-04-14`

Details

1# Image generation1# Image generation

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.

4 

3## Overview5## Overview

4 6 

5The OpenAI API lets you generate and edit images from text prompts using GPT Image models, including our latest, `gpt-image-2`. You can access image generation capabilities through two APIs:7The OpenAI API lets you generate and edit images from text prompts using GPT Image models, including our latest, `gpt-image-2`. You can access image generation capabilities through two APIs:

6 8 

7### Image API9### Image API

8 10 

9Starting with `gpt-image-1` and later models, the [Image API](https://developers.openai.com/api/docs/api-reference/images) provides two endpoints, each with distinct capabilities:11Starting with `gpt-image-1` and later models, the [Image API](https://developers.openai.com/api/reference/resources/images) provides two endpoints, each with distinct capabilities:

10 12 

11- **Generations**: [Generate images](#generate-images) from scratch based on a text prompt13- **Generations**: [Generate images](#generate-images) from scratch based on a text prompt

12- **Edits**: [Modify existing images](#edit-images) using a new prompt, either partially or entirely14- **Edits**: [Modify existing images](#edit-images) using a new prompt, either partially or entirely


15 17 

16### Responses API18### Responses API

17 19 

18The [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-tools) allows you to generate images as part of conversations or multi-step flows. It supports image generation as a [built-in tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses), and accepts image inputs and outputs within context.20The [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-tools) allows you to generate images as part of conversations or multi-step flows. It supports image generation as a [built-in tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses), and accepts image inputs and outputs within context.

19 21 

20Compared to the Image API, it adds:22Compared to the Image API, it adds:

21 23 

22- **Multi-turn editing**: Iteratively make high fidelity edits to images with prompting24- **Multi-turn editing**: Iteratively make high fidelity edits to images with prompting

23- **Flexible inputs**: Accept image [File](https://developers.openai.com/api/docs/api-reference/files) IDs as input images, not just bytes25- **Flexible inputs**: Accept image [File](https://developers.openai.com/api/reference/resources/files) IDs as input images, not just bytes

24 26 

25The Responses API image generation tool uses its own GPT Image model selection. For details on mainline models that support calling this tool, refer to the [supported models](#supported-models) below.27The Responses API image generation tool uses its own GPT Image model selection. For details on mainline models that support calling this tool, refer to the [supported models](#supported-models) below.

26 28 


51 alt="A beige coffee mug on a wooden table"53 alt="A beige coffee mug on a wooden table"

52 style={{ height: "180px", width: "auto", borderRadius: "8px" }}54 style={{ height: "180px", width: "auto", borderRadius: "8px" }}

53 />55 />

54</div>56 

57 

55 58 

56## Generate Images59## Generate Images

57 60 

58You can use the [image generation endpoint](https://developers.openai.com/api/docs/api-reference/images/create) to create images based on text prompts, or the [image generation tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses) in the Responses API to generate images as part of a conversation.61You can use the [image generation endpoint](https://developers.openai.com/api/reference/resources/images) to create images based on text prompts, or the [image generation tool](https://developers.openai.com/api/docs/guides/tools?api-mode=responses) in the Responses API to generate images as part of a conversation.

59 62 

60To learn more about customizing the output (size, quality, format, compression), refer to the [customize image output](#customize-image-output) section below.63To learn more about customizing the output (size, quality, format, compression), refer to the [customize image output](#customize-image-output) section below.

61 64 


63 66 

64 67 

65 68 

66<div data-content-switcher-pane data-value="image">69Image API

67 <div class="hidden">Image API</div>70 

68 Generate an image71 Generate an image

69 72 

70```javascript73```javascript


127 --transform 'data.0.b64_json' | base64 --decode > otter.png130 --transform 'data.0.b64_json' | base64 --decode > otter.png

128```131```

129 132 

130 </div>133

131 <div data-content-switcher-pane data-value="responses" hidden>134 

132 <div class="hidden">Responses API</div>135

136 

137

138Responses API

139 

133 Generate an image140 Generate an image

134 141 

135```javascript142```javascript


180 f.write(base64.b64decode(image_base64))187 f.write(base64.b64decode(image_base64))

181```188```

182 189 

183 </div>

184 

185 190 

186 191 

187### Multi-turn image generation192### Multi-turn image generation


246 251 

247 252 

248 253 

249<div data-content-switcher-pane data-value="responseid">254Using previous response ID

250 <div class="hidden">Using previous response ID</div>255 

251 Multi-turn image generation256 Multi-turn image generation

252 257 

253```javascript258```javascript


340 f.write(base64.b64decode(image_base64))345 f.write(base64.b64decode(image_base64))

341```346```

342 347 

343 </div>348

344 <div data-content-switcher-pane data-value="imageid" hidden>349 

345 <div class="hidden">Using image ID</div>350

351 

352

353Using image ID

354 

346 Multi-turn image generation355 Multi-turn image generation

347 356 

348```javascript357```javascript


451 f.write(base64.b64decode(image_base64))460 f.write(base64.b64decode(image_base64))

452```461```

453 462 

454 </div>

455 

456 463 

457 464 

458#### Result465#### Result

459 466 

460<div className="not-prose">467 

468 

461 <table style={{ width: "100%" }}>469 <table style={{ width: "100%" }}>

462 <tbody>470 <tbody>

463 <tr>471 <tr>


491 </tr>499 </tr>

492 </tbody>500 </tbody>

493 </table>501 </table>

494</div>502 

503 

495 504 

496### Streaming505### Streaming

497 506 


504 513 

505 514 

506 515 

507<div data-content-switcher-pane data-value="responses">516Responses API

508 <div class="hidden">Responses API</div>517 

509 Stream an image518 Stream an image

510 519 

511```javascript520```javascript


577 save_base64_image("river-final.png", image_data[0])586 save_base64_image("river-final.png", image_data[0])

578```587```

579 588 

580 </div>589

581 <div data-content-switcher-pane data-value="image" hidden>590 

582 <div class="hidden">Image API</div>591

592 

593

594Image API

595 

583 Stream an image596 Stream an image

584 597 

585```javascript598```javascript


629 f.write(image_bytes)642 f.write(image_bytes)

630```643```

631 644 

632 </div>

633 

634 645 

635 646 

636#### Result647#### Result

637 648 

638<div className="images-examples">649 

650 

639 651 

640| Partial 1 | Partial 2 | Final image |652| Partial 1 | Partial 2 | Final image |

641| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |653| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |

642| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming1.png" alt="1st partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming2.png" alt="2nd partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming3.png" alt="3rd partial" /> |654| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming1.png" alt="1st partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming2.png" alt="2nd partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming3.png" alt="3rd partial" /> |

643 655 

644</div>

645 656 

646<div className="images-edit-prompt body-small">657 

658 

659 

660 

647 Prompt: Draw a gorgeous image of a river made of white owl feathers, snaking661 Prompt: Draw a gorgeous image of a river made of white owl feathers, snaking

648 its way through a serene winter landscape662 its way through a serene winter landscape

649</div>663 

664 

650 665 

651### Revised prompt666### Revised prompt

652 667 


669 684 

670## Edit Images685## Edit Images

671 686 

672The [image edits](https://developers.openai.com/api/docs/api-reference/images/createEdit) endpoint lets you:687The [image edits](https://developers.openai.com/api/reference/resources/images) endpoint lets you:

673 688 

674- Edit existing images689- Edit existing images

675- Generate new images using other images as a reference690- Generate new images using other images as a reference


681 696 

682In this example, we'll use 4 input images to generate a new image of a gift basket containing the items in the reference images.697In this example, we'll use 4 input images to generate a new image of a gift basket containing the items in the reference images.

683 698 

684<div data-content-switcher-pane data-value="responses">699Responses API

685 <div class="hidden">Responses API</div>700 

686 </div>701

687 <div data-content-switcher-pane data-value="image" hidden>702 

688 <div class="hidden">Image API</div>703With the Responses API, you can provide input images in 3 different ways:

704 

705- By providing a fully qualified URL

706- By providing an image as a Base64-encoded data URL

707- By providing a file ID (created with the [Files API](https://developers.openai.com/api/reference/resources/files))

708 

709#### Create a File

710 

711Create a File

712 

713```python

714from openai import OpenAI

715 

716client = OpenAI()

717 

718 

719def create_file(file_path):

720 with open(file_path, "rb") as file_content:

721 result = client.files.create(

722 file=file_content,

723 purpose="vision",

724 )

725 return result.id

726```

727 

728```javascript

729import fs from "fs";

730import OpenAI from "openai";

731 

732const openai = new OpenAI();

733 

734async function createFile(filePath) {

735 const fileContent = fs.createReadStream(filePath);

736 const result = await openai.files.create({

737 file: fileContent,

738 purpose: "vision",

739 });

740 return result.id;

741}

742```

743 

744 

745#### Create a base64 encoded image

746 

747Create a base64 encoded image

748 

749```python

750import base64

751 

752 

753def encode_image(file_path):

754 with open(file_path, "rb") as f:

755 base64_image = base64.b64encode(f.read()).decode("utf-8")

756 return base64_image

757```

758 

759```javascript

760import fs from "fs";

761 

762function encodeImage(filePath) {

763 const base64Image = fs.readFileSync(filePath, "base64");

764 return base64Image;

765}

766```

767 

768 

769Edit an image

770 

771```python

772from openai import OpenAI

773import base64

774 

775client = OpenAI()

776 

777 

778def encode_image(file_path):

779 with open(file_path, "rb") as image_file:

780 return base64.b64encode(image_file.read()).decode("utf-8")

781 

782 

783def create_file(file_path):

784 with open(file_path, "rb") as file_content:

785 result = client.files.create(file=file_content, purpose="vision")

786 return result.id

787 

788 

789prompt = """Generate a photorealistic image of a gift basket on a white background

790labeled 'Relax & Unwind' with a ribbon and handwriting-like font,

791containing all the items in the reference pictures."""

792 

793base64_image1 = encode_image("body-lotion.png")

794base64_image2 = encode_image("soap.png")

795file_id1 = create_file("bath-bomb.png")

796file_id2 = create_file("incense-kit.png")

797 

798response = client.responses.create(

799 model="gpt-5.6",

800 input=[

801 {

802 "role": "user",

803 "content": [

804 {"type": "input_text", "text": prompt},

805 {

806 "type": "input_image",

807 "image_url": f"data:image/png;base64,{base64_image1}",

808 },

809 {

810 "type": "input_image",

811 "image_url": f"data:image/png;base64,{base64_image2}",

812 },

813 {

814 "type": "input_image",

815 "file_id": file_id1,

816 },

817 {

818 "type": "input_image",

819 "file_id": file_id2,

820 },

821 ],

822 }

823 ],

824 tools=[{"type": "image_generation"}],

825)

826 

827image_generation_calls = [

828 output for output in response.output if output.type == "image_generation_call"

829]

830 

831image_data = [output.result for output in image_generation_calls]

832 

833if image_data:

834 image_base64 = image_data[0]

835 with open("gift-basket.png", "wb") as f:

836 f.write(base64.b64decode(image_base64))

837else:

838 print(response.output_text)

839```

840 

841```javascript

842import fs from "fs";

843import OpenAI from "openai";

844 

845const openai = new OpenAI();

846 

847function encodeImage(filePath) {

848 return fs.readFileSync(filePath, "base64");

849}

850 

851async function createFile(filePath) {

852 const result = await openai.files.create({

853 file: fs.createReadStream(filePath),

854 purpose: "vision",

855 });

856 return result.id;

857}

858 

859const prompt = `Generate a photorealistic image of a gift basket on a white background

860labeled 'Relax & Unwind' with a ribbon and handwriting-like font,

861containing all the items in the reference pictures.`;

862 

863const base64Image1 = encodeImage("fixtures/body-lotion.png");

864const base64Image2 = encodeImage("fixtures/soap.png");

865const fileId1 = await createFile("fixtures/bath-bomb.png");

866const fileId2 = await createFile("fixtures/incense-kit.png");

867 

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

869 model: "gpt-5.6",

870 input: [

871 {

872 role: "user",

873 content: [

874 { type: "input_text", text: prompt },

875 {

876 type: "input_image",

877 image_url: `data:image/png;base64,${base64Image1}`,

878 detail: "auto",

879 },

880 {

881 type: "input_image",

882 image_url: `data:image/png;base64,${base64Image2}`,

883 detail: "auto",

884 },

885 {

886 type: "input_image",

887 file_id: fileId1,

888 detail: "auto",

889 },

890 {

891 type: "input_image",

892 file_id: fileId2,

893 detail: "auto",

894 },

895 ],

896 },

897 ],

898 tools: [{ type: "image_generation" }],

899});

900 

901const imageData = response.output

902 .filter((output) => output.type === "image_generation_call")

903 .map((output) => output.result);

904 

905if (imageData.length > 0) {

906 const imageBase64 = imageData[0];

907 fs.writeFileSync("gift-basket.png", Buffer.from(imageBase64, "base64"));

908} else {

909 console.log(response.output_text);

910}

911```

912 

913 

914

915 

916

917 

918

919Image API

920 

689 Edit an image921 Edit an image

690 922 

691```python923```python


784 --transform 'data.0.b64_json' | base64 --decode > gift-basket.png1016 --transform 'data.0.b64_json' | base64 --decode > gift-basket.png

785```1017```

786 1018 

787 </div>

788 

789 1019 

790 1020 

791### Edit an image using a mask1021### Edit an image using a mask


801 1031 

802 1032 

803 1033 

804<div data-content-switcher-pane data-value="responses">1034Responses API

805 <div class="hidden">Responses API</div>1035 

806 Edit an image with a mask1036 Edit an image with a mask

807 1037 

808```python1038```python


917}1147}

918```1148```

919 1149 

920 </div>1150

921 <div data-content-switcher-pane data-value="image" hidden>1151 

922 <div class="hidden">Image API</div>1152

1153 

1154

1155Image API

1156 

923 Edit an image with a mask1157 Edit an image with a mask

924 1158 

925```python1159```python


987 --transform 'data.0.b64_json' | base64 --decode > out.png1221 --transform 'data.0.b64_json' | base64 --decode > out.png

988```1222```

989 1223 

990 </div>

991 1224 

992 1225 

993 1226 

994<div className="images-examples">1227 

995 1228 

996| Image | Mask | Output |1229| Image | Mask | Output |

997| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1230| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

998| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge.png" alt="A pink room with a pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/mask.png" alt="A mask in part of the pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge_result.png" alt="The original pool with an inflatable flamingo replacing the mask" /> |1231| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge.png" alt="A pink room with a pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/mask.png" alt="A mask in part of the pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge_result.png" alt="The original pool with an inflatable flamingo replacing the mask" /> |

999 1232 

1000</div>

1001 1233 

1002<div className="images-edit-prompt body-small">1234 

1235 

1236 

1237 

1003 Prompt: a sunlit indoor lounge area with a pool containing a flamingo1238 Prompt: a sunlit indoor lounge area with a pool containing a flamingo

1004</div>1239 

1240 

1005 1241 

1006#### Mask requirements1242#### Mask requirements

1007 1243 


1074 <td>1310 <td>

1075 <ul>1311 <ul>

1076 <li>1312 <li>

1077 <code>1024x1024</code> (square)1313 `1024x1024` (square)

1078 </li>1314 </li>

1079 <li>1315 <li>

1080 <code>1536x1024</code> (landscape)1316 `1536x1024` (landscape)

1081 </li>1317 </li>

1082 <li>1318 <li>

1083 <code>1024x1536</code> (portrait)1319 `1024x1536` (portrait)

1084 </li>1320 </li>

1085 <li>1321 <li>

1086 <code>2048x2048</code> (2K square)1322 `2048x2048` (2K square)

1087 </li>1323 </li>

1088 <li>1324 <li>

1089 <code>2048x1152</code> (2K landscape)1325 `2048x1152` (2K landscape)

1090 </li>1326 </li>

1091 <li>1327 <li>

1092 <code>3840x2160</code> (4K landscape)1328 `3840x2160` (4K landscape)

1093 </li>1329 </li>

1094 <li>1330 <li>

1095 <code>2160x3840</code> (4K portrait)1331 `2160x3840` (4K portrait)

1096 </li>1332 </li>

1097 <li>1333 <li>

1098 <code>auto</code> (default)1334 `auto` (default)

1099 </li>1335 </li>

1100 </ul>1336 </ul>

1101 </td>1337 </td>


1106 <ul>1342 <ul>

1107 <li>1343 <li>

1108 Maximum edge length must be less than or equal to 1344 Maximum edge length must be less than or equal to

1109 <code>3840px</code>1345 `3840px`

1110 </li>1346 </li>

1111 <li>1347 <li>

1112 Both edges must be multiples of <code>16px</code>1348 Both edges must be multiples of `16px`

1113 </li>1349 </li>

1114 <li>1350 <li>

1115 Long edge to short edge ratio must not exceed <code>3:1</code>1351 Long edge to short edge ratio must not exceed `3:1`

1116 </li>1352 </li>

1117 <li>1353 <li>

1118 Total pixels must be at least <code>655,360</code> and no more than 1354 Total pixels must be at least `655,360` and no more than

1119 <code>8,294,400</code>1355 `8,294,400`

1120 </li>1356 </li>

1121 </ul>1357 </ul>

1122 </td>1358 </td>


1126 <td>1362 <td>

1127 <ul>1363 <ul>

1128 <li>1364 <li>

1129 <code>low</code>1365 `low`

1130 </li>1366 </li>

1131 <li>1367 <li>

1132 <code>medium</code>1368 `medium`

1133 </li>1369 </li>

1134 <li>1370 <li>

1135 <code>high</code>1371 `high`

1136 </li>1372 </li>

1137 <li>1373 <li>

1138 <code>auto</code> (default)1374 `auto` (default)

1139 </li>1375 </li>

1140 </ul>1376 </ul>

1141 </td>1377 </td>


1369 <tr>1605 <tr>

1370 <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>1606 <td rowSpan="3" style={{ padding: "8px", width: "28%" }}>

1371 GPT Image 21607 GPT Image 2

1372 <br />1608

1373 <span style={{ fontSize: "0.875em" }}>Additional sizes available</span>1609 

1610

1611Additional sizes available

1612 

1374 </td>1613 </td>

1375 <td style={{ padding: "8px" }}>Low</td>1614 <td style={{ padding: "8px" }}>Low</td>

1376 <td style={{ padding: "8px" }}>$0.006</td>1615 <td style={{ padding: "8px" }}>$0.006</td>

Details

1# Images and vision1# Images and vision

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.

4 

3## Overview5## Overview

4 6 

5<div className="mb-10 w-full max-w-full overflow-hidden">7 

6 </div>8 

9 - **[Create images](https://developers.openai.com/api/docs/guides/image-generation)**: Use GPT Image models to generate or edit images.

10- **[Process image inputs](#analyze-images)**: Use our models' vision capabilities to analyze images.

11 

12 

7 13 

8In this guide, you will learn about building applications involving images with the OpenAI API.14In this guide, you will learn about building applications involving images with the OpenAI API.

9If you know what you want to build, find your use case below to get started. If you're not sure where to start, continue reading to get an overview.15If you know what you want to build, find your use case below to get started. If you're not sure where to start, continue reading to get an overview.


16 22 

17| API | Supported use cases |23| API | Supported use cases |

18| ---------------------------------------------------- | --------------------------------------------------------------------- |24| ---------------------------------------------------- | --------------------------------------------------------------------- |

19| [Responses API](https://developers.openai.com/api/docs/api-reference/responses) | Analyze images and use them as input and/or generate images as output |25| [Responses API](https://developers.openai.com/api/reference/resources/responses) | Analyze images and use them as input and/or generate images as output |

20| [Images API](https://developers.openai.com/api/docs/api-reference/images) | Generate images as output, optionally using images as input |26| [Images API](https://developers.openai.com/api/reference/resources/images) | Generate images as output, optionally using images as input |

21| [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat) | Analyze images and use them as input to generate text or audio |27| [Chat Completions API](https://developers.openai.com/api/reference/resources/chat) | Analyze images and use them as input to generate text or audio |

22 28 

23To learn more about the input and output modalities supported by our models, refer to our [models page](https://developers.openai.com/api/docs/models).29To learn more about the input and output modalities supported by our models, refer to our [models page](https://developers.openai.com/api/docs/models).

24 30 


117 123 

118- By providing a fully qualified URL to an image file124- By providing a fully qualified URL to an image file

119- By providing an image as a Base64-encoded data URL125- By providing an image as a Base64-encoded data URL

120- By providing a file ID (created with the [Files API](https://developers.openai.com/api/docs/api-reference/files))126- By providing a file ID (created with the [Files API](https://developers.openai.com/api/reference/resources/files))

121 127 

122You can provide multiple images as input in a single request by including multiple images in the `content` array, but keep in mind that [images count as tokens](#calculating-costs) and will be billed accordingly.128You can provide multiple images as input in a single request by including multiple images in the `content` array, but keep in mind that [images count as tokens](#calculating-costs) and will be billed accordingly.

123 129 

124 130 

125 131 

126<div data-content-switcher-pane data-value="url">132Passing a URL

127 <div class="hidden">Passing a URL</div>133 

128 Analyze the content of an image134 Analyze the content of an image

129 135 

130```javascript136```javascript


179 185 

180```csharp186```csharp

181using OpenAI.Responses;187using OpenAI.Responses;

188#pragma warning disable OPENAI001

182 189 

183string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;190string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

184OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);191ResponsesClient client = new(key);

185 192 

186Uri imageUrl = new("https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg");193Uri imageUrl = new(

194 "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"

195);

187 196 

188OpenAIResponse response = (OpenAIResponse)client.CreateResponse([197ResponseResult response = await client.CreateResponseAsync(

189 ResponseItem.CreateUserMessageItem([198 "gpt-5.6",

199 [

200 ResponseItem.CreateUserMessageItem(

201 [

190 ResponseContentPart.CreateInputTextPart("What is in this image?"),202 ResponseContentPart.CreateInputTextPart("What is in this image?"),

191 ResponseContentPart.CreateInputImagePart(imageUrl)203 ResponseContentPart.CreateInputImagePart(imageUrl),

192 ])204 ]

193]);205 ),

206 ]

207);

194 208 

195Console.WriteLine(response.GetOutputText());209Console.WriteLine(response.GetOutputText());

196```210```


231YAML245YAML

232```246```

233 247 

234 </div>248

235 <div data-content-switcher-pane data-value="base64-encoded" hidden>249 

236 <div class="hidden">Passing a Base64 encoded image</div>250

251 

252

253Passing a Base64 encoded image

254 

237 Analyze the content of an image255 Analyze the content of an image

238 256 

239```javascript257```javascript


306 324 

307```csharp325```csharp

308using OpenAI.Responses;326using OpenAI.Responses;

327#pragma warning disable OPENAI001

309 328 

310string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;329string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

311OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);330ResponsesClient client = new(key);

331 

332Uri imageUrl = new(

333 "https://openai-documentation.vercel.app/images/cat_and_otter.png"

334);

312 335 

313Uri imageUrl = new("https://openai-documentation.vercel.app/images/cat_and_otter.png");

314using HttpClient http = new();336using HttpClient http = new();

315 337 

316// Download an image as stream338// Download an image as a stream.

317using var stream = await http.GetStreamAsync(imageUrl);339using Stream stream = await http.GetStreamAsync(imageUrl);

340BinaryData imageData = BinaryData.FromStream(stream, "image/png");

318 341 

319OpenAIResponse response1 = (OpenAIResponse)client.CreateResponse([342ResponseResult response1 = await client.CreateResponseAsync(

320 ResponseItem.CreateUserMessageItem([343 "gpt-5.6",

344 [

345 ResponseItem.CreateUserMessageItem(

346 [

321 ResponseContentPart.CreateInputTextPart("What is in this image?"),347 ResponseContentPart.CreateInputTextPart("What is in this image?"),

322 ResponseContentPart.CreateInputImagePart(BinaryData.FromStream(stream), "image/png")348 ResponseContentPart.CreateInputImagePart(imageData),

323 ])349 ]

324]);350 ),

351 ]

352);

325 353 

326Console.WriteLine($"From image stream: {response1.GetOutputText()}");354Console.WriteLine($"From image stream: {response1.GetOutputText()}");

327 355 

328// Download an image as byte array356// Download an image as a byte array.

329byte[] bytes = await http.GetByteArrayAsync(imageUrl);357byte[] bytes = await http.GetByteArrayAsync(imageUrl);

358imageData = BinaryData.FromBytes(bytes, "image/png");

330 359 

331OpenAIResponse response2 = (OpenAIResponse)client.CreateResponse([360ResponseResult response2 = await client.CreateResponseAsync(

332 ResponseItem.CreateUserMessageItem([361 "gpt-5.6",

362 [

363 ResponseItem.CreateUserMessageItem(

364 [

333 ResponseContentPart.CreateInputTextPart("What is in this image?"),365 ResponseContentPart.CreateInputTextPart("What is in this image?"),

334 ResponseContentPart.CreateInputImagePart(BinaryData.FromBytes(bytes), "image/png")366 ResponseContentPart.CreateInputImagePart(imageData),

335 ])367 ]

336]);368 ),

369 ]

370);

337 371 

338Console.WriteLine($"From byte array: {response2.GetOutputText()}");372Console.WriteLine($"From byte array: {response2.GetOutputText()}");

339```373```

340 374 

341 </div>375

342 <div data-content-switcher-pane data-value="file" hidden>376 

343 <div class="hidden">Passing a file ID</div>377

378 

379

380Passing a file ID

381 

344 Analyze the content of an image382 Analyze the content of an image

345 383 

346```javascript384```javascript


423```csharp461```csharp

424using OpenAI.Files;462using OpenAI.Files;

425using OpenAI.Responses;463using OpenAI.Responses;

464#pragma warning disable OPENAI001

426 465 

427string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;466string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

428OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);467ResponsesClient client = new(key);

429 468 

430string filename = "cat_and_otter.png";469string filename = "cat_and_otter.png";

431Uri imageUrl = new($"https://openai-documentation.vercel.app/images/{filename}");470Uri imageUrl = new(

432using var http = new HttpClient();471 $"https://openai-documentation.vercel.app/images/{filename}"

472);

473 

474using HttpClient http = new();

433 475 

434// Download an image as stream476// Download an image as a stream.

435using var stream = await http.GetStreamAsync(imageUrl);477using Stream stream = await http.GetStreamAsync(imageUrl);

436 478 

437OpenAIFileClient files = new(key);479OpenAIFileClient files = new(key);

438OpenAIFile file = await files.UploadFileAsync(BinaryData.FromStream(stream), filename, FileUploadPurpose.Vision);

439 480 

440OpenAIResponse response = (OpenAIResponse)client.CreateResponse([481OpenAIFile file = await files.UploadFileAsync(

441 ResponseItem.CreateUserMessageItem([482 stream,

483 filename,

484 FileUploadPurpose.Vision

485);

486 

487ResponseResult response = await client.CreateResponseAsync(

488 "gpt-5.6",

489 [

490 ResponseItem.CreateUserMessageItem(

491 [

442 ResponseContentPart.CreateInputTextPart("what's in this image?"),492 ResponseContentPart.CreateInputTextPart("what's in this image?"),

443 ResponseContentPart.CreateInputImagePart(file.Id)493 ResponseContentPart.CreateInputImagePart(file.Id),

444 ])494 ]

445]);495 ),

496 ]

497);

446 498 

447Console.WriteLine(response.GetOutputText());499Console.WriteLine(response.GetOutputText());

448```500```

449 501 

450 </div>

451 

452 502 

453 503 

454 504 


487 537 

488 538 

489 539 

490 ```plain540```plain

491{541{

492 "type": "input_image",542 "type": "input_image",

493 "image_url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",543 "image_url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",


525 <tr>575 <tr>

526 <td>GPT-5.6 family</td>576 <td>GPT-5.6 family</td>

527 <td>577 <td>

528 <code>low</code>, <code>high</code>, <code>original</code>,578 `low`, `high`, `original`,

529 <code>auto</code>579 `auto`

530 </td>580 </td>

531 <td>581 <td>

532 <code>low</code> and <code>high</code> can resize images under their582 `low` and `high` can resize images under their

533 finite limits. <code>original</code> preserves the input dimensions and583 finite limits. `original` preserves the input dimensions and

534 does not resize the image to a pixel-dimension or patch-budget limit.584 does not resize the image to a pixel-dimension or patch-budget limit.

535 <code>auto</code> and omitted <code>detail</code> use the same sizing585 `auto` and omitted `detail` use the same sizing

536 behavior as <code>original</code>. Request payload and other image-input586 behavior as `original`. Request payload and other image-input

537 limits still apply.587 limits still apply.

538 </td>588 </td>

539 </tr>589 </tr>

540 <tr>590 <tr>

541 <td>591 <td>

542 <code>gpt-5.5</code>592 `gpt-5.5`

543 </td>593 </td>

544 <td>594 <td>

545 <code>low</code>, <code>high</code>, <code>original</code>,595 `low`, `high`, `original`,

546 <code>auto</code>596 `auto`

547 </td>597 </td>

548 <td>598 <td>

549 <code>high</code> allows up to 2,500 patches or a 2048-pixel maximum599 `high` allows up to 2,500 patches or a 2048-pixel maximum

550 dimension. <code>original</code> allows up to 10,000 patches or a600 dimension. `original` allows up to 10,000 patches or a

551 6000-pixel maximum dimension. If either limit is exceeded, we resize the601 6000-pixel maximum dimension. If either limit is exceeded, we resize the

552 image while preserving aspect ratio to fit within the lesser of those two602 image while preserving aspect ratio to fit within the lesser of those two

553 constraints for the selected detail level. <code>auto</code> and omitted603 constraints for the selected detail level. `auto` and omitted

554 <code>detail</code> use the same sizing behavior as604 `detail` use the same sizing behavior as

555 <code>original</code>. [Full resizing details605 `original`. [Full resizing details

556 below.](#patch-based-image-tokenization)606 below.](#patch-based-image-tokenization)

557 </td>607 </td>

558 </tr>608 </tr>

559 <tr>609 <tr>

560 <td>610 <td>

561 <code>gpt-5.4</code>611 `gpt-5.4`

562 </td>612 </td>

563 <td>613 <td>

564 <code>low</code>, <code>high</code>, <code>original</code>,614 `low`, `high`, `original`,

565 <code>auto</code>615 `auto`

566 </td>616 </td>

567 <td>617 <td>

568 <code>high</code> allows up to 2,500 patches or a 2048-pixel maximum618 `high` allows up to 2,500 patches or a 2048-pixel maximum

569 dimension. <code>original</code> allows up to 10,000 patches or a619 dimension. `original` allows up to 10,000 patches or a

570 6000-pixel maximum dimension. If either limit is exceeded, we resize the620 6000-pixel maximum dimension. If either limit is exceeded, we resize the

571 image while preserving aspect ratio to fit within the lesser of those two621 image while preserving aspect ratio to fit within the lesser of those two

572 constraints for the selected detail level. <code>auto</code> and omitted622 constraints for the selected detail level. `auto` and omitted

573 <code>detail</code> use the same sizing behavior as623 `detail` use the same sizing behavior as

574 <code>high</code>. [Full resizing details624 `high`. [Full resizing details

575 below.](#patch-based-image-tokenization)625 below.](#patch-based-image-tokenization)

576 </td>626 </td>

577 </tr>627 </tr>

578 <tr>628 <tr>

579 <td>629 <td>

580 <code>gpt-5.4-mini</code>, <code>gpt-5.4-nano</code>,630 `gpt-5.4-mini`, `gpt-5.4-nano`,

581 <code>gpt-5-mini</code>, <code>gpt-5-nano</code>, <code>gpt-5.2</code>,631 `gpt-5-mini`, `gpt-5-nano`, `gpt-5.2`,

582 <code>gpt-5.3-codex</code>, <code>gpt-5-codex-mini</code>,632 `gpt-5.3-codex`, `gpt-5-codex-mini`,

583 <code>gpt-5.1-codex-mini</code>, <code>gpt-5.2-codex</code>,633 `gpt-5.1-codex-mini`, `gpt-5.2-codex`,

584 <code>gpt-5.2-chat-latest</code>, <code>o4-mini</code>, and the 634 `gpt-5.2-chat-latest`, `o4-mini`, and the

585 <code>gpt-4.1-mini</code> and <code>gpt-4.1-nano</code> 2025-04-14635 `gpt-4.1-mini` and `gpt-4.1-nano` 2025-04-14

586 snapshot variants636 snapshot variants

587 </td>637 </td>

588 <td>638 <td>

589 <code>low</code>, <code>high</code>, <code>auto</code>639 `low`, `high`, `auto`

590 </td>640 </td>

591 <td>641 <td>

592 <code>high</code> allows up to 1,536 patches or a 2048-pixel maximum642 `high` allows up to 1,536 patches or a 2048-pixel maximum

593 dimension. If either limit is exceeded, we resize the image while643 dimension. If either limit is exceeded, we resize the image while

594 preserving aspect ratio to fit within the lesser of those two constraints.644 preserving aspect ratio to fit within the lesser of those two constraints.

595 [Full resizing details below.](#patch-based-image-tokenization)645 [Full resizing details below.](#patch-based-image-tokenization)


597 </tr>647 </tr>

598 <tr>648 <tr>

599 <td>649 <td>

600 <code>GPT-4o</code>, <code>GPT-4.1</code>, <code>GPT-4o-mini</code>,650 `GPT-4o`, `GPT-4.1`, `GPT-4o-mini`,

601 <code>computer-use-preview</code>, and o-series models except651 `computer-use-preview`, and o-series models except

602 <code>o4-mini</code>652 `o4-mini`

603 </td>653 </td>

604 <td>654 <td>

605 <code>low</code>, <code>high</code>, <code>auto</code>655 `low`, `high`, `auto`

606 </td>656 </td>

607 <td>657 <td>

608 Use tile-based resizing behavior. See 658 Use tile-based resizing behavior. See

609 <a href="#gpt-4o-gpt-41-gpt-4o-mini-cua-and-o-series-except-o4-mini">659 [the detailed behavior below](#gpt-4o-gpt-41-gpt-4o-mini-cua-and-o-series-except-o4-mini)

610 the detailed behavior below

611 </a>

612 </td>660 </td>

613 </tr>661 </tr>

614</table>662</table>

Details

1# IP egress ranges1# IP egress ranges

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.

4 

3Some OpenAI products make outbound requests to services you control. If your network requires an IP allowlist, use the published ranges for the product making the request.5Some OpenAI products make outbound requests to services you control. If your network requires an IP allowlist, use the published ranges for the product making the request.

4 6 

5An IP allowlist identifies traffic from an OpenAI-operated network, not a specific user or workspace, and does not replace request authentication or authorization when your integration requires them. For plugins, use [mutual TLS](https://developers.openai.com/plugins/build/auth#mutual-tls-mtls) to authenticate ChatGPT as the MCP client. When your plugin requires user authentication, use OAuth 2.1 to authenticate and authorize the user.7An IP allowlist identifies traffic from an OpenAI-operated network, not a specific user or workspace, and does not replace request authentication or authorization when your integration requires them. For plugins, use [mutual TLS](https://developers.openai.com/plugins/build/auth#mutual-tls-mtls) to authenticate ChatGPT as the MCP client. When your plugin requires user authentication, use OAuth 2.1 to authenticate and authorize the user.

Details

1# Latency optimization1# Latency optimization

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.

4 

3This guide covers the core set of principles you can apply to improve latency across a wide variety of LLM-related use cases. These techniques come from working with a wide range of customers and developers on production applications, so they should apply regardless of what you're building – from a granular workflow to an end-to-end chatbot.5This guide covers the core set of principles you can apply to improve latency across a wide variety of LLM-related use cases. These techniques come from working with a wide range of customers and developers on production applications, so they should apply regardless of what you're building – from a granular workflow to an end-to-end chatbot.

4 6 

5While there's many individual techniques, we'll be grouping them into **seven principles** meant to represent a high-level taxonomy of approaches for improving latency.7While there's many individual techniques, we'll be grouping them into **seven principles** meant to represent a high-level taxonomy of approaches for improving latency.


31 33 

32 34 

33Other factors that affect inference speed are the amount of 35Other factors that affect inference speed are the amount of

34 <strong>compute</strong> you have available and any additional 36 **compute** you have available and any additional

35 <strong>inference optimizations</strong> you employ. <br /> <br />37 **inference optimizations** you employ.

38

39 

36 Most people can't influence these factors directly, but if you're curious, and40 Most people can't influence these factors directly, but if you're curious, and

37 have some control over your infra, <strong>faster hardware</strong> or 41 have some control over your infra, **faster hardware** or

38 <strong>running engines at a lower saturation</strong> may give you a modest42 **running engines at a lower saturation** may give you a modest

39 TPM boost. And if you're down in the trenches, there's a myriad of other 43 TPM boost. And if you're down in the trenches, there's a myriad of other

40 <a href="https://lilianweng.github.io/posts/2023-01-10-inference-optimization/">44 [inference optimizations](https://lilianweng.github.io/posts/2023-01-10-inference-optimization/)

41 inference optimizations

42 </a>

43 that are a bit beyond the scope of this guide.45 that are a bit beyond the scope of this guide.

44 46 

45 47 


270 272 

271USER: [JSON-formatted input conversation here]273USER: [JSON-formatted input conversation here]

272```274```

273<br/>275 

276 

274 277 

275Actually, adding context and determining whether to retrieve are very straightforward and well defined tasks, so we can likely use a **smaller, fine-tuned model** instead. Switching to GPT-3.5 will let us [process tokens faster](#process-tokens-faster).278Actually, adding context and determining whether to retrieve are very straightforward and well defined tasks, so we can likely use a **smaller, fine-tuned model** instead. Switching to GPT-3.5 will let us [process tokens faster](#process-tokens-faster).

276 279 


374` ` `377` ` `

375```378```

376 379 

377<br />380 

381 

378 382 

379In fact, now that the reasoning prompt does not depend on the retrieved context we can [parallelize](#parallelize) and fire it off at the same time as the retrieval prompts.383In fact, now that the reasoning prompt does not depend on the retrieved context we can [parallelize](#parallelize) and fire it off at the same time as the retrieval prompts.

380 384 


431![Assistants object architecture diagram](https://cdn.openai.com/API/docs/images/diagram-latency-customer-service-11b.png)435![Assistants object architecture diagram](https://cdn.openai.com/API/docs/images/diagram-latency-customer-service-11b.png)

432 436 

4331. **Combined** query contextualization and retrieval check steps to [make fewer requests](#make-fewer-requests).4371. **Combined** query contextualization and retrieval check steps to [make fewer requests](#make-fewer-requests).

4342. For the new prompt, **switched to a smaller, fine-tuned GPT-3.5** to [process tokens faster](https://developers.openai.com/api/docs/guides/process-tokens-faster).4382. For the new prompt, **switched to a smaller, fine-tuned GPT-3.5** to [process tokens faster](#process-tokens-faster).

4353. Split the assistant prompt in two, **switching to a smaller, fine-tuned GPT-3.5** for the reasoning, again to [process tokens faster](#process-tokens-faster).4393. Split the assistant prompt in two, **switching to a smaller, fine-tuned GPT-3.5** for the reasoning, again to [process tokens faster](#process-tokens-faster).

4364. [Parallelized](#parallelize) the retrieval checks and the reasoning steps.4404. [Parallelized](#parallelize) the retrieval checks and the reasoning steps.

4375. **Shortened reasoning field names** and moved comments into the prompt, to [generate fewer tokens](#generate-fewer-tokens).4415. **Shortened reasoning field names** and moved comments into the prompt, to [generate fewer tokens](#generate-fewer-tokens).

Details

7 7 

8# Using GPT-5.68# Using GPT-5.6

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.

11 

10## Introduction12## Introduction

11 13 

12GPT-5.6 sets a new quality and efficiency baseline for complex production workflows. GPT-5.6 is especially token-efficient and improves frontend aesthetics, including layout, visual hierarchy, and design judgment.14GPT-5.6 sets a new quality and efficiency baseline for complex production workflows. GPT-5.6 is especially token-efficient and improves frontend aesthetics, including layout, visual hierarchy, and design judgment.


36 38 

37We are continuously evolving these safeguards so that they are robust and effective in holding up to adversarial pressure, while preserving access to legitimate work such as code review, vulnerability research, patch development, debugging, security education, and defensive testing.39We are continuously evolving these safeguards so that they are robust and effective in holding up to adversarial pressure, while preserving access to legitimate work such as code review, vulnerability research, patch development, debugging, security education, and defensive testing.

38 40 

39<div id="migrate-to-gpt-56" aria-hidden="true"></div>41 

42 

43 

40 44 

41## Migration quickstart45## Migration quickstart

42 46 


61 - Use `high` or `xhigh` when more reasoning produces a measured quality gain.65 - Use `high` or `xhigh` when more reasoning produces a measured quality gain.

62 - Reserve `max` for the hardest quality-first workloads. Compare `max` and `xhigh` to find the best quality, latency, and cost tradeoff for your use case.66 - Reserve `max` for the hardest quality-first workloads. Compare `max` and `xhigh` to find the best quality, latency, and cost tradeoff for your use case.

63- To use pro mode, keep your selected GPT-5.6 model and set `reasoning.mode` to `pro` in the Responses API; do not switch to a separate Pro model slug. Choose `reasoning.effort` independently. If you omit it, GPT-5.6 defaults to `medium` in both standard and pro modes. See [reasoning mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode) for a request example and billing details.67- To use pro mode, keep your selected GPT-5.6 model and set `reasoning.mode` to `pro` in the Responses API; do not switch to a separate Pro model slug. Choose `reasoning.effort` independently. If you omit it, GPT-5.6 defaults to `medium` in both standard and pro modes. See [reasoning mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode) for a request example and billing details.

64- Configure persisted reasoning based on how much prior reasoning is still relevant.68- Configure persisted reasoning based on how much prior reasoning is still relevant. GPT-5.6 models default to `all_turns`; earlier models default to `current_turn`.

65 - Omit `reasoning.context` or set it to `auto` to use the model's default. Check the response's `reasoning.context` field to confirm the effective mode.69 - Omit `reasoning.context` or set it to `auto` to use `all_turns`, the GPT-5.6 default. Check the response's `reasoning.context` field to confirm the effective mode.

66 - Set `reasoning.context` to `all_turns` when the task's goals, assumptions, and priorities stay stable across turns.70 - Set `reasoning.context` to `all_turns` when the task's goals, assumptions, and priorities stay stable across turns.

67 - With `all_turns`, continue with `previous_response_id` to make reasoning from earlier responses available to the model.71 - With `all_turns`, continue with `previous_response_id` to make reasoning from earlier responses available to the model.

68 - When managing history manually, preserve and resend previous user inputs and every response output item. For `store: false` or Zero Data Retention, replay the encrypted reasoning items that the API returns by default.72 - When managing history manually, preserve and resend previous user inputs and every response output item. For `store: false` or Zero Data Retention, replay the encrypted reasoning items that the API returns by default.

Details

1# Using GPT-4.11# Using GPT-4.1

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.

4 

3## Introduction5## Introduction

4 6 

5The GPT-4.1 family of models represents a significant step forward from GPT-4o in capabilities across coding, instruction following, and long context. In this prompting guide, we collate a series of important prompting tips derived from extensive internal testing to help developers fully leverage the improved abilities of this new model family.7The GPT-4.1 family of models represents a significant step forward from GPT-4o in capabilities across coding, instruction following, and long context. In this prompting guide, we collate a series of important prompting tips derived from extensive internal testing to help developers fully leverage the improved abilities of this new model family.


542### Caveats544### Caveats

543 545 

544- In some isolated cases we have observed the model being resistant to producing very long, repetitive outputs, for example, analyzing hundreds of items one by one. If this is necessary for your use case, instruct the model strongly to output this information in full, and consider breaking down the problem or using a more concise approach.546- In some isolated cases we have observed the model being resistant to producing very long, repetitive outputs, for example, analyzing hundreds of items one by one. If this is necessary for your use case, instruct the model strongly to output this information in full, and consider breaking down the problem or using a more concise approach.

545- We have seen some rare instances of parallel tool calls being incorrect. We advise testing this, and considering setting the [parallel_tool_calls](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-parallel_tool_calls) param to false if you’re seeing issues.547- We have seen some rare instances of parallel tool calls being incorrect. We advise testing this, and considering setting the [parallel_tool_calls](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-parallel_tool_calls) param to false if you’re seeing issues.

546 548 

547### Appendix: Generating and Applying File Diffs549### Appendix: Generating and Applying File Diffs

548 550 

Details

1# Using GPT-51# Using GPT-5

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.

4 

3## Introduction5## Introduction

4 6 

5GPT-5 represents a substantial leap forward in agentic task performance, coding, raw intelligence, and control.7GPT-5 represents a substantial leap forward in agentic task performance, coding, raw intelligence, and control.


35 37 

36### Agentic workflow predictability38### Agentic workflow predictability

37 39 

38We trained GPT-5 with developers in mind: we’ve focused on improving tool calling, instruction following, and long-context understanding to serve as the best foundation model for agentic applications. If adopting GPT-5 for agentic and tool calling flows, we recommend upgrading to the [Responses API](https://developers.openai.com/api/docs/api-reference/responses), where reasoning is persisted between tool calls, leading to more efficient and intelligent outputs.40We trained GPT-5 with developers in mind: we’ve focused on improving tool calling, instruction following, and long-context understanding to serve as the best foundation model for agentic applications. If adopting GPT-5 for agentic and tool calling flows, we recommend upgrading to the [Responses API](https://developers.openai.com/api/reference/resources/responses), where reasoning is persisted between tool calls, leading to more efficient and intelligent outputs.

39 41 

40#### Controlling agentic eagerness42#### Controlling agentic eagerness

41 43 

Details

1# Using GPT-5.11# Using GPT-5.1

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.

4 

3## Introduction5## Introduction

4 6 

5GPT-5.1 is designed to balance intelligence and speed for a variety of agentic and coding tasks, while also introducing a new `none` reasoning mode for low-latency interactions. Building on the strengths of GPT-5, GPT-5.1 is better calibrated to prompt difficulty, consuming far fewer tokens on lower-complexity inputs and more efficiently handling challenging ones. Along with these benefits, GPT-5.1 is more steerable in personality, tone, and output formatting.7GPT-5.1 is designed to balance intelligence and speed for a variety of agentic and coding tasks, while also introducing a new `none` reasoning mode for low-latency interactions. Building on the strengths of GPT-5, GPT-5.1 is better calibrated to prompt difficulty, consuming far fewer tokens on lower-complexity inputs and more efficiently handling challenging ones. Along with these benefits, GPT-5.1 is more steerable in personality, tone, and output formatting.

Details

1# Using GPT-5.21# Using GPT-5.2

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.

4 

3## Introduction5## Introduction

4 6 

5GPT-5.2 was released as a flagship general-purpose model for both general and agentic tasks. Compared with GPT-5.1, it improved:7GPT-5.2 was released as a flagship general-purpose model for both general and agentic tasks. Compared with GPT-5.1, it improved:


177 179 

178When the GPT-5 model family launched, we introduced a new capability called custom tools, which lets models send any raw text as tool call input but still constrain outputs if desired. This tool behavior remains true in GPT-5.2.180When the GPT-5 model family launched, we introduced a new capability called custom tools, which lets models send any raw text as tool call input but still constrain outputs if desired. This tool behavior remains true in GPT-5.2.

179 181 

180[182[Function calling guide

183 

181 184 

182<span slot="icon">

183 </span>

184 Learn about custom tools in the function calling guide.

185 185 

186](https://developers.openai.com/api/docs/guides/function-calling)186 Learn about custom tools in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)

187 187 

188#### Freeform inputs188#### Freeform inputs

189 189 


212 212 

213The `allowed_tools` parameter under `tool_choice` lets you pass N tool definitions but restrict the model to only M (&lt; N) of them. List your full toolkit in `tools`, and then use an `allowed_tools` block to name the subset and specify a mode—either `auto` (the model may pick any of those) or `required` (the model must invoke one).213The `allowed_tools` parameter under `tool_choice` lets you pass N tool definitions but restrict the model to only M (&lt; N) of them. List your full toolkit in `tools`, and then use an `allowed_tools` block to name the subset and specify a mode—either `auto` (the model may pick any of those) or `required` (the model must invoke one).

214 214 

215[215[Function calling guide

216 216 

217<span slot="icon">

218 </span>

219 Learn about the allowed tools option in the function calling guide.

220 217 

221](https://developers.openai.com/api/docs/guides/function-calling)218 

219 Learn about the allowed tools option in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)

222 220 

223By separating all possible tools from the subset that can be used _now_, you gain greater safety, predictability, and improved prompt caching. You also avoid brittle prompt engineering, such as hard-coded call order. GPT-5.2 dynamically invokes or requires specific functions mid-conversation while reducing the risk of unintended tool usage over long contexts.221By separating all possible tools from the subset that can be used _now_, you gain greater safety, predictability, and improved prompt caching. You also avoid brittle prompt engineering, such as hard-coded call order. GPT-5.2 dynamically invokes or requires specific functions mid-conversation while reducing the risk of unintended tool usage over long contexts.

224 222 


287 285 

288### Migrating from Chat Completions to Responses API286### Migrating from Chat Completions to Responses API

289 287 

290The biggest difference, and main reason to migrate from Chat Completions to the Responses API for GPT-5.2, is support for passing chain of thought (CoT) between turns. See a full [comparison of the APIs](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions).288The biggest difference, and main reason to migrate from Chat Completions to the Responses API for GPT-5.2, is support for passing chain of thought (CoT) between turns. See a full [comparison of the APIs](https://developers.openai.com/api/docs/guides/migrate-to-responses).

291 289 

292Passing CoT exists only in the Responses API, and we've seen improved intelligence, fewer generated reasoning tokens, higher cache hit rates, and lower latency as a result of doing so. Most other parameters remain at parity, though the formatting is different. Here's how new parameters are handled differently between Chat Completions and the Responses API:290Passing CoT exists only in the Responses API, and we've seen improved intelligence, fewer generated reasoning tokens, higher cache hit rates, and lower latency as a result of doing so. Most other parameters remain at parity, though the formatting is different. Here's how new parameters are handled differently between Chat Completions and the Responses API:

293 291 


295 293 

296 294 

297 295 

298<div data-content-switcher-pane data-value="responses">296Responses API

299 <div class="hidden">Responses API</div>297 

300 Generate response with reasoning effort set to none298 Generate response with reasoning effort set to none

301 299 

302```bash300```bash


313}'311}'

314```312```

315 313 

316 </div>314

317 <div data-content-switcher-pane data-value="chat" hidden>315 

318 <div class="hidden">Chat Completions</div>316

317 

318

319Chat Completions

320 

319 Generate response with reasoning effort set to none321 Generate response with reasoning effort set to none

320 322 

321```bash323```bash


335}'337}'

336```338```

337 339 

338 </div>

339 

340 340 

341 341 

342**Verbosity**342**Verbosity**

343 343 

344 344 

345 345 

346<div data-content-switcher-pane data-value="responses">346Responses API

347 <div class="hidden">Responses API</div>347 

348 Control verbosity348 Control verbosity

349 349 

350```bash350```bash


361}'361}'

362```362```

363 363 

364 </div>364

365 <div data-content-switcher-pane data-value="chat" hidden>365 

366 <div class="hidden">Chat Completions</div>366

367 

368

369Chat Completions

370 

367 Control verbosity371 Control verbosity

368 372 

369```bash373```bash


383}'387}'

384```388```

385 389 

386 </div>

387 

388 390 

389 391 

390**Custom tools**392**Custom tools**

391 393 

392 394 

393 395 

394<div data-content-switcher-pane data-value="responses">396Responses API

395 <div class="hidden">Responses API</div>397 

396 Custom tool call398 Custom tool call

397 399 

398```bash400```bash


413}'415}'

414```416```

415 417 

416 </div>418

417 <div data-content-switcher-pane data-value="chat" hidden>419 

418 <div class="hidden">Chat Completions</div>420

421 

422

423Chat Completions

424 

419 Custom tool call425 Custom tool call

420 426 

421```bash427```bash


443}'449}'

444```450```

445 451 

446 </div>

447 

448 452 

449 453 

450 454 


583- Keep prompts functionally identical when resuming to avoid behavior drift587- Keep prompts functionally identical when resuming to avoid behavior drift

584- Treat compacted items as opaque; don’t parse or depend on internals588- Treat compacted items as opaque; don’t parse or depend on internals

585 589 

586For guidance on when and how to compact in production, see the [Conversation State](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses) guide and [Compact a Response](https://developers.openai.com/api/docs/api-reference/responses/compact) page.590For guidance on when and how to compact in production, see the [Conversation State](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses) guide and [Compact a Response](https://developers.openai.com/api/reference/resources/responses/methods/compact) page.

587 591 

588Here is an example:592Here is an example:

589 593 

Details

1# Using GPT-5.3-Codex1# Using GPT-5.3-Codex

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.

4 

3## Introduction5## Introduction

4 6 

5GPT-5.3-Codex advances the frontier of intelligence and efficiency for agentic coding. Follow this guide closely to ensure you’re getting the best performance possible from this model. This guide is for anyone using the model directly via the API for maximum customizability; we also have the [Codex SDK](https://developers.openai.com/codex/codex-sdk/) for simpler integrations.7GPT-5.3-Codex advances the frontier of intelligence and efficiency for agentic coding. Follow this guide closely to ensure you’re getting the best performance possible from this model. This guide is for anyone using the model directly via the API for maximum customizability; we also have the [Codex SDK](https://developers.openai.com/codex/codex-sdk/) for simpler integrations.


229 2. The endpoint is ZDR compatible and will return an “encrypted_content” item that you can pass into future requests.231 2. The endpoint is ZDR compatible and will return an “encrypted_content” item that you can pass into future requests.

2303. For subsequent calls to the /responses endpoint, you can pass your updated, compacted list of conversation items (including the added compaction item). The model retains key prior state with fewer conversation tokens.2323. For subsequent calls to the /responses endpoint, you can pass your updated, compacted list of conversation items (including the added compaction item). The model retains key prior state with fewer conversation tokens.

231 233 

232For endpoint details see our `/responses/compact` [docs](https://developers.openai.com/api/docs/api-reference/responses/compact).234For endpoint details see our `/responses/compact` [docs](https://developers.openai.com/api/reference/resources/responses/methods/compact).

233 235 

234### Tools236### Tools

235 237 

Details

1# Using GPT-5.41# Using GPT-5.4

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.

4 

3## Introduction5## Introduction

4 6 

5[GPT-5.4](https://developers.openai.com/api/docs/models/gpt-5.4) was released as a frontier model for professional work across the API and Codex. It helps developers analyze complex information, build production software, and automate multi-step workflows.7[GPT-5.4](https://developers.openai.com/api/docs/models/gpt-5.4) was released as a frontier model for professional work across the API and Codex. It helps developers analyze complex information, build production software, and automate multi-step workflows.


182 184 

183Use it in an isolated browser or VM, and keep a human in the loop for high-impact actions. The full guide covers the built-in Responses API loop, custom harness patterns, and code-execution-based setups.185Use it in an isolated browser or VM, and keep a human in the loop for high-impact actions. The full guide covers the built-in Responses API loop, custom harness patterns, and code-execution-based setups.

184 186 

185[187[Computer use guide

186 188 

187<span slot="icon">

188 </span>

189 Learn how to run the built-in computer tool safely and integrate it with

190 your own harness.

191 189 

192](https://developers.openai.com/api/docs/guides/tools-computer-use)190 

191 Learn how to run the built-in computer tool safely and integrate it with

192 your own harness.](https://developers.openai.com/api/docs/guides/tools-computer-use)

193 193 

194### Tool search tool194### Tool search tool

195 195 


197 197 

198Use hosted tool search when the candidate tools are already known at request time, or client-executed tool search when your application needs to decide what to load dynamically. The full guide also covers best practices for `namespaces`, MCP servers, and deferred loading.198Use hosted tool search when the candidate tools are already known at request time, or client-executed tool search when your application needs to decide what to load dynamically. The full guide also covers best practices for `namespaces`, MCP servers, and deferred loading.

199 199 

200[200[Tool search guide

201 201 

202<span slot="icon">

203 </span>

204 Learn how to defer tool definitions and load the right subset at runtime.

205 202 

206](https://developers.openai.com/api/docs/guides/tools-tool-search)203 

204 Learn how to defer tool definitions and load the right subset at runtime.](https://developers.openai.com/api/docs/guides/tools-tool-search)

207 205 

208### Custom tools206### Custom tools

209 207 

210When the GPT-5 model family launched, we introduced a new capability called custom tools, which lets models send any raw text as tool call input but still constrain outputs if desired. This tool behavior remains true in GPT-5.4.208When the GPT-5 model family launched, we introduced a new capability called custom tools, which lets models send any raw text as tool call input but still constrain outputs if desired. This tool behavior remains true in GPT-5.4.

211 209 

212[210[Function calling guide

211 

213 212 

214<span slot="icon">

215 </span>

216 Learn about custom tools in the function calling guide.

217 213 

218](https://developers.openai.com/api/docs/guides/function-calling)214 Learn about custom tools in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)

219 215 

220#### Freeform inputs216#### Freeform inputs

221 217 


244 240 

245The `allowed_tools` parameter under `tool_choice` lets you pass N tool definitions but restrict the model to only M (&lt; N) of them. List your full toolkit in `tools`, and then use an `allowed_tools` block to name the subset and specify a mode—either `auto` (the model may pick any of those) or `required` (the model must invoke one).241The `allowed_tools` parameter under `tool_choice` lets you pass N tool definitions but restrict the model to only M (&lt; N) of them. List your full toolkit in `tools`, and then use an `allowed_tools` block to name the subset and specify a mode—either `auto` (the model may pick any of those) or `required` (the model must invoke one).

246 242 

247[243[Function calling guide

248 244 

249<span slot="icon">

250 </span>

251 Learn about the allowed tools option in the function calling guide.

252 245 

253](https://developers.openai.com/api/docs/guides/function-calling)246 

247 Learn about the allowed tools option in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)

254 248 

255By separating all possible tools from the subset that can be used _now_, you gain greater safety, predictability, and improved prompt caching. You also avoid brittle prompt engineering, such as hard-coded call order. GPT-5.4 dynamically invokes or requires specific functions mid-conversation while reducing the risk of unintended tool usage over long contexts.249By separating all possible tools from the subset that can be used _now_, you gain greater safety, predictability, and improved prompt caching. You also avoid brittle prompt engineering, such as hard-coded call order. GPT-5.4 dynamically invokes or requires specific functions mid-conversation while reducing the risk of unintended tool usage over long contexts.

256 250 


397 391 

398### Migrating from Chat Completions to Responses API392### Migrating from Chat Completions to Responses API

399 393 

400The biggest difference, and main reason to migrate from Chat Completions to the Responses API for GPT-5.4, is support for passing chain of thought (CoT) between turns. See a full [comparison of the APIs](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions).394The biggest difference, and main reason to migrate from Chat Completions to the Responses API for GPT-5.4, is support for passing chain of thought (CoT) between turns. See a full [comparison of the APIs](https://developers.openai.com/api/docs/guides/migrate-to-responses).

401 395 

402Passing CoT exists only in the Responses API, and we've seen improved intelligence, fewer generated reasoning tokens, higher cache hit rates, and lower latency as a result of doing so. Most other parameters remain at parity, though the formatting is different. Here's how new parameters are handled differently between Chat Completions and the Responses API:396Passing CoT exists only in the Responses API, and we've seen improved intelligence, fewer generated reasoning tokens, higher cache hit rates, and lower latency as a result of doing so. Most other parameters remain at parity, though the formatting is different. Here's how new parameters are handled differently between Chat Completions and the Responses API:

403 397 


405 399 

406 400 

407 401 

408<div data-content-switcher-pane data-value="responses">402Responses API

409 <div class="hidden">Responses API</div>403 

410 Generate response with reasoning effort set to none404 Generate response with reasoning effort set to none

411 405 

412```bash406```bash


423}'417}'

424```418```

425 419 

426 </div>420

427 <div data-content-switcher-pane data-value="chat" hidden>421 

428 <div class="hidden">Chat Completions</div>422

423 

424

425Chat Completions

426 

429 Generate response with reasoning effort set to none427 Generate response with reasoning effort set to none

430 428 

431```bash429```bash


445}'443}'

446```444```

447 445 

448 </div>

449 

450 446 

451 447 

452**Verbosity**448**Verbosity**

453 449 

454 450 

455 451 

456<div data-content-switcher-pane data-value="responses">452Responses API

457 <div class="hidden">Responses API</div>453 

458 Control verbosity454 Control verbosity

459 455 

460```bash456```bash


471}'467}'

472```468```

473 469 

474 </div>470

475 <div data-content-switcher-pane data-value="chat" hidden>471 

476 <div class="hidden">Chat Completions</div>472

473 

474

475Chat Completions

476 

477 Control verbosity477 Control verbosity

478 478 

479```bash479```bash


493}'493}'

494```494```

495 495 

496 </div>

497 

498 496 

499 497 

500**Custom tools**498**Custom tools**

501 499 

502 500 

503 501 

504<div data-content-switcher-pane data-value="responses">502Responses API

505 <div class="hidden">Responses API</div>503 

506 Custom tool call504 Custom tool call

507 505 

508```bash506```bash


523}'521}'

524```522```

525 523 

526 </div>524

527 <div data-content-switcher-pane data-value="chat" hidden>525 

528 <div class="hidden">Chat Completions</div>526

527 

528

529Chat Completions

530 

529 Custom tool call531 Custom tool call

530 532 

531```bash533```bash


553}'555}'

554```556```

555 557 

556 </div>

557 

558 558 

559 559 

560 560 


993 993 

994If you are using [Compaction](https://developers.openai.com/api/docs/guides/compaction) in the Responses API, compact after major milestones, treat compacted items as opaque state, and keep prompts functionally identical after compaction. The endpoint is ZDR compatible and returns an `encrypted_content` item that you can pass into future requests. GPT-5.4 tends to remain more coherent and reliable over longer, multi-turn conversations with fewer breakdowns as sessions grow.994If you are using [Compaction](https://developers.openai.com/api/docs/guides/compaction) in the Responses API, compact after major milestones, treat compacted items as opaque state, and keep prompts functionally identical after compaction. The endpoint is ZDR compatible and returns an `encrypted_content` item that you can pass into future requests. GPT-5.4 tends to remain more coherent and reliable over longer, multi-turn conversations with fewer breakdowns as sessions grow.

995 995 

996For more guidance, see the [`/responses/compact` API reference](https://developers.openai.com/api/docs/api-reference/responses/compact).996For more guidance, see the [`/responses/compact` API reference](https://developers.openai.com/api/reference/resources/responses/methods/compact).

997 997 

998#### Control personality for customer-facing workflows998#### Control personality for customer-facing workflows

999 999 

Details

1# Using GPT-5.51# Using GPT-5.5

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.

4 

3## Introduction5## Introduction

4 6 

5GPT-5.5 raises the baseline for complex production workflows. It’s a strong fit for coding use cases, tool-heavy agents, grounded assistants, long-context retrieval, product-spec-to-plan workflows, and customer-facing workflows where execution quality and response polish are critical.7GPT-5.5 raises the baseline for complex production workflows. It’s a strong fit for coding use cases, tool-heavy agents, grounded assistants, long-context retrieval, product-spec-to-plan workflows, and customer-facing workflows where execution quality and response polish are critical.

Details

7 7 

8# Using GPT-5.68# Using GPT-5.6

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.

11 

10## Introduction12## Introduction

11 13 

12GPT-5.6 sets a new quality and efficiency baseline for complex production workflows. GPT-5.6 is especially token-efficient and improves frontend aesthetics, including layout, visual hierarchy, and design judgment.14GPT-5.6 sets a new quality and efficiency baseline for complex production workflows. GPT-5.6 is especially token-efficient and improves frontend aesthetics, including layout, visual hierarchy, and design judgment.


36 38 

37We are continuously evolving these safeguards so that they are robust and effective in holding up to adversarial pressure, while preserving access to legitimate work such as code review, vulnerability research, patch development, debugging, security education, and defensive testing.39We are continuously evolving these safeguards so that they are robust and effective in holding up to adversarial pressure, while preserving access to legitimate work such as code review, vulnerability research, patch development, debugging, security education, and defensive testing.

38 40 

39<div id="migrate-to-gpt-56" aria-hidden="true"></div>41 

42 

43 

40 44 

41## Migration quickstart45## Migration quickstart

42 46 


61 - Use `high` or `xhigh` when more reasoning produces a measured quality gain.65 - Use `high` or `xhigh` when more reasoning produces a measured quality gain.

62 - Reserve `max` for the hardest quality-first workloads. Compare `max` and `xhigh` to find the best quality, latency, and cost tradeoff for your use case.66 - Reserve `max` for the hardest quality-first workloads. Compare `max` and `xhigh` to find the best quality, latency, and cost tradeoff for your use case.

63- To use pro mode, keep your selected GPT-5.6 model and set `reasoning.mode` to `pro` in the Responses API; do not switch to a separate Pro model slug. Choose `reasoning.effort` independently. If you omit it, GPT-5.6 defaults to `medium` in both standard and pro modes. See [reasoning mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode) for a request example and billing details.67- To use pro mode, keep your selected GPT-5.6 model and set `reasoning.mode` to `pro` in the Responses API; do not switch to a separate Pro model slug. Choose `reasoning.effort` independently. If you omit it, GPT-5.6 defaults to `medium` in both standard and pro modes. See [reasoning mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode) for a request example and billing details.

64- Configure persisted reasoning based on how much prior reasoning is still relevant.68- Configure persisted reasoning based on how much prior reasoning is still relevant. GPT-5.6 models default to `all_turns`; earlier models default to `current_turn`.

65 - Omit `reasoning.context` or set it to `auto` to use the model's default. Check the response's `reasoning.context` field to confirm the effective mode.69 - Omit `reasoning.context` or set it to `auto` to use `all_turns`, the GPT-5.6 default. Check the response's `reasoning.context` field to confirm the effective mode.

66 - Set `reasoning.context` to `all_turns` when the task's goals, assumptions, and priorities stay stable across turns.70 - Set `reasoning.context` to `all_turns` when the task's goals, assumptions, and priorities stay stable across turns.

67 - With `all_turns`, continue with `previous_response_id` to make reasoning from earlier responses available to the model.71 - With `all_turns`, continue with `previous_response_id` to make reasoning from earlier responses available to the model.

68 - When managing history manually, preserve and resend previous user inputs and every response output item. For `store: false` or Zero Data Retention, replay the encrypted reasoning items that the API returns by default.72 - When managing history manually, preserve and resend previous user inputs and every response output item. For `store: false` or Zero Data Retention, replay the encrypted reasoning items that the API returns by default.

Details

1# Migrate to the Responses API1# Migrate to the Responses API

2 2 

3The [Responses API](https://developers.openai.com/api/docs/api-reference/responses) is our new API primitive, an evolution of [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat) which brings added simplicity and powerful agentic primitives to your integrations.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 [Responses API](https://developers.openai.com/api/reference/resources/responses) is our new API primitive, an evolution of [Chat Completions](https://developers.openai.com/api/reference/resources/chat) which brings added simplicity and powerful agentic primitives to your integrations.

4 6 

5**While Chat Completions remains supported, Responses is recommended for all new projects.**7**While Chat Completions remains supported, Responses is recommended for all new projects.**

6 8 


8 10 

9The Responses API is a unified interface for building powerful, agent-like applications. It contains:11The Responses API is a unified interface for building powerful, agent-like applications. It contains:

10 12 

11- Built-in tools like [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [file search](https://developers.openai.com/api/docs/guides/tools-file-search), [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [code interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter), and [remote MCPs](https://developers.openai.com/api/docs/guides/tools-remote-mcp).13- Built-in tools like [web search](https://developers.openai.com/api/docs/guides/tools-web-search), [file search](https://developers.openai.com/api/docs/guides/tools-file-search), [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [code interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter), and [remote MCPs](https://developers.openai.com/api/docs/guides/tools-connectors-mcp).

12- Seamless multi-turn interactions that allow you to pass previous responses for higher accuracy reasoning results.14- Seamless multi-turn interactions that allow you to pass previous responses for higher accuracy reasoning results.

13- Native multimodal support for text and images.15- Native multimodal support for text and images.

14 16 


24- **Encrypted reasoning**: Opt-out of statefulness while still benefiting from advanced reasoning.26- **Encrypted reasoning**: Opt-out of statefulness while still benefiting from advanced reasoning.

25- **Future-proof**: Future-proofed for upcoming models.27- **Future-proof**: Future-proofed for upcoming models.

26 28 

27<div className="roles-table">29 

30 

28 31 

29| Capabilities | Chat Completions API | Responses API |32| Capabilities | Chat Completions API | Responses API |

30| ------------------- | --------------------- | --------------------- |33| ------------------- | --------------------- | --------------------- |


41| Image generation | | |44| Image generation | | |

42| Reasoning summaries | | |45| Reasoning summaries | | |

43 46 

44</div>47 

48 

45 49 

46### Examples50### Examples

47 51 


64The objects you receive back from these APIs will differ slightly. In Chat Completions, you receive an array of68The objects you receive back from these APIs will differ slightly. In Chat Completions, you receive an array of

65`choices`, each containing a `message`. In Responses, you receive an array of Items labeled `output`.69`choices`, each containing a `message`. In Responses, you receive an array of Items labeled `output`.

66 70 

71 

72 

73#### Chat Completions API

74 

75```json

76{

77 "id": "chatcmpl-C9EDpkjH60VPPIB86j2zIhiR8kWiC",

78 "object": "chat.completion",

79 "created": 1756315657,

80 "model": "gpt-5.5",

81 "choices": [

82 {

83 "index": 0,

84 "message": {

85 "role": "assistant",

86 "content": "Under a blanket of starlight, a sleepy unicorn tiptoed through moonlit meadows, gathering dreams like dew to tuck beneath its silver mane until morning.",

87 "refusal": null,

88 "annotations": []

89 },

90 "finish_reason": "stop"

91 }

92 ],

93 ...

94}

95```

96 

97#### Responses API

98 

99```json

100{

101 "id": "resp_68af4030592c81938ec0a5fbab4a3e9f05438e46b5f69a3b",

102 "object": "response",

103 "created_at": 1756315696,

104 "model": "gpt-5.5",

105 "output": [

106 {

107 "id": "rs_68af4030baa48193b0b43b4c2a176a1a05438e46b5f69a3b",

108 "type": "reasoning",

109 "content": [],

110 "summary": []

111 },

112 {

113 "id": "msg_68af40337e58819392e935fb404414d005438e46b5f69a3b",

114 "type": "message",

115 "status": "completed",

116 "content": [

117 {

118 "type": "output_text",

119 "annotations": [],

120 "logprobs": [],

121 "text": "Under a quilt of moonlight, a drowsy unicorn wandered through quiet meadows, brushing blossoms with her glowing horn so they sighed soft lullabies that carried every dreamer gently to sleep."

122 }

123 ],

124 "role": "assistant"

125 }

126 ],

127 ...

128}

129```

130 

131 

132 

67### Additional differences133### Additional differences

68 134 

69- Responses are stored by default. Chat completions are stored by default for new accounts. To disable storage in either API, set `store: false`.135- Responses are stored by default. Chat completions are stored by default for new accounts. To disable storage in either API, set `store: false`.


140 206 

141 207 

142 208 

143<div data-content-switcher-pane data-value="chat-completions">209Chat Completions

144 <div class="hidden">Chat Completions</div>210 

145 With Chat Completions, you create a `messages` array and read the model text211 With Chat Completions, you create a `messages` array and read the model text

146 from `completion.choices[0].message.content`.212 from `completion.choices[0].message.content`.

147 Generate text from a model213 Generate text from a model


189```255```

190 256 

191 257 

192 </div>258

193 <div data-content-switcher-pane data-value="responses" hidden>259 

194 <div class="hidden">Responses</div>260

261 

262

263Responses

264 

195 With Responses, you can separate `instructions` and `input` at the top level265 With Responses, you can separate `instructions` and `input` at the top level

196 and read generated text from `response.output_text`.266 and read generated text from `response.output_text`.

197 Generate text from a model267 Generate text from a model


232```302```

233 303 

234 304 

235 </div>

236 

237 

238 305 

239### 2. Map Messages to Items306### 2. Map Messages to Items

240 307 


262 329 

263 330 

264 331 

265<div data-content-switcher-pane data-value="chat-completions">332Chat Completions

266 <div class="hidden">Chat Completions</div>333 

267 In Chat Completions, you store the transcript and send the accumulated334 In Chat Completions, you store the transcript and send the accumulated

268 `messages` array on each request.335 `messages` array on each request.

269 Multi-turn conversation336 Multi-turn conversation


302```369```

303 370 

304 371 

305 </div>372

306 <div data-content-switcher-pane data-value="responses" hidden>373 

307 <div class="hidden">Responses</div>374

375 

376

377Responses

378 

308 With Responses, you can manually pass outputs from one response into the379 With Responses, you can manually pass outputs from one response into the

309 input of another.380 input of another.

310 Multi-turn conversation381 Multi-turn conversation


382```453```

383 454 

384 455 

385 </div>

386 

387 

388 456 

389Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.457Even when using `previous_response_id`, all previous input tokens for responses in the chain are billed as input tokens in the API.

390 458 


396 464 

397To disable statefulness but still take advantage of reasoning:465To disable statefulness but still take advantage of reasoning:

398 466 

399- Set `store: false` in the [store field](https://developers.openai.com/api/docs/api-reference/responses/create#responses_create-store).467- Set `store: false` in the [store field](https://developers.openai.com/api/reference/resources/responses/methods/create#responses_create-store).

400- Preserve and replay every returned reasoning item. Each item includes `encrypted_content` by default when you create a response.468- Preserve and replay every returned reasoning item. Each item includes `encrypted_content` by default when you create a response.

401 469 

402The API will then return an encrypted version of the reasoning tokens, which you can pass back in future requests just like regular reasoning items.470The API will then return an encrypted version of the reasoning tokens, which you can pass back in future requests just like regular reasoning items.


411 479 

412The Responses API function example on the right is functionally equivalent to the Chat Completions example on the left.480The Responses API function example on the right is functionally equivalent to the Chat Completions example on the left.

413 481 

482 

483 

484#### Chat Completions API

485 

486```javascript

487{

488 "type": "function",

489 "function": {

490 "name": "get_weather",

491 "description": "Determine weather in my location",

492 "strict": true,

493 "parameters": {

494 "type": "object",

495 "properties": {

496 "location": {

497 "type": "string",

498 },

499 },

500 "additionalProperties": false,

501 "required": [

502 "location"

503 ]

504 }

505 }

506}

507```

508 

509#### Responses API

510 

511```javascript

512{

513 "type": "function",

514 "name": "get_weather",

515 "description": "Determine weather in my location",

516 "parameters": {

517 "type": "object",

518 "properties": {

519 "location": {

520 "type": "string",

521 },

522 },

523 "additionalProperties": false,

524 "required": [

525 "location"

526 ]

527 }

528}

529```

530 

531 

532 

414#### Follow function-calling best practices533#### Follow function-calling best practices

415 534 

416In Responses, tool calls and their outputs are two distinct types of Items that are correlated using a `call_id`. See535In Responses, tool calls and their outputs are two distinct types of Items that are correlated using a `call_id`. See


422 541 

423 542 

424 543 

425<div data-content-switcher-pane data-value="chat-completions">544Chat Completions

426 <div class="hidden">Chat Completions</div>545 

427 Structured Outputs546 Structured Outputs

428 547 

429```bash548```bash


537});656});

538```657```

539 658 

540 </div>659

541 <div data-content-switcher-pane data-value="responses" hidden>660 

542 <div class="hidden">Responses</div>661

662 

663

664Responses

665 

543 Structured Outputs666 Structured Outputs

544 667 

545```bash668```bash


631});754});

632```755```

633 756 

634 </div>

635 

636 757 

637 758 

638### 7. Update streaming consumers759### 7. Update streaming consumers


646- `response.completed`767- `response.completed`

647- `error`768- `error`

648 769 

649Function-calling streams can also emit events such as `response.function_call_arguments.delta` and `response.function_call_arguments.done`. See the [streaming Responses guide](https://developers.openai.com/api/docs/guides/streaming-responses?api-mode=responses) and [Responses streaming events reference](https://developers.openai.com/api/docs/api-reference/responses-streaming).770Function-calling streams can also emit events such as `response.function_call_arguments.delta` and `response.function_call_arguments.done`. See the [streaming Responses guide](https://developers.openai.com/api/docs/guides/streaming-responses?api-mode=responses) and [Responses streaming events reference](https://developers.openai.com/api/reference/resources/responses).

650 771 

651### 8. Upgrade to native tools772### 8. Upgrade to native tools

652 773 


654 775 

655 776 

656 777 

657<div data-content-switcher-pane data-value="chat-completions">778Chat Completions

658 <div class="hidden">Chat Completions</div>779 

659 With Chat Completions, you cannot use OpenAI-hosted tools natively and have780 With Chat Completions, you cannot use OpenAI-hosted tools natively and have

660 to write your own tool integration.781 to write your own tool integration.

661 Web search tool782 Web search tool


723 --data-urlencode "key=$SEARCH_API_KEY"\844 --data-urlencode "key=$SEARCH_API_KEY"\

724```845```

725 846 

726 </div>847

727 <div data-content-switcher-pane data-value="responses" hidden>848 

728 <div class="hidden">Responses</div>849

850 

851

852Responses

853 

729 With Responses, you can specify the tools that you want the model to use.854 With Responses, you can specify the tools that you want the model to use.

730 Web search tool855 Web search tool

731 856 


761```886```

762 887 

763 888 

764 </div>

765 

766 

767 889 

768### 9. Check common migration errors890### 9. Check common migration errors

769 891 


795 917 

796## Assistants API918## Assistants API

797 919 

798Based on developer feedback from the [Assistants API](https://developers.openai.com/api/docs/api-reference/assistants) beta, we've incorporated key improvements into the Responses API to make it more flexible, faster, and easier to use. The Responses API represents the future direction for building agents on OpenAI.920Based on developer feedback from the [Assistants API](https://developers.openai.com/api/reference/resources/beta/subresources/assistants) beta, we've incorporated key improvements into the Responses API to make it more flexible, faster, and easier to use. The Responses API represents the future direction for building agents on OpenAI.

799 921 

800We now have Assistant-like and Thread-like objects in the Responses API. Learn more in the [migration guide](https://developers.openai.com/api/docs/guides/assistants/migration). As of August 26, 2025, we're deprecating the Assistants API, with a sunset date of August 26, 2026.922We now have Assistant-like and Thread-like objects in the Responses API. Learn more in the [migration guide](https://developers.openai.com/api/docs/assistants/migration). As of August 26, 2025, we're deprecating the Assistants API, with a sunset date of August 26, 2026.

Details

1# Model optimization1# Model optimization

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.

4 

3LLM output is non-deterministic, and model behavior changes between model snapshots and families. Developers must constantly measure and tune the performance of LLM applications to ensure they're getting the best results. In this guide, we explore the techniques and OpenAI platform tools you can use to ensure high quality outputs from the model.5LLM output is non-deterministic, and model behavior changes between model snapshots and families. Developers must constantly measure and tune the performance of LLM applications to ensure they're getting the best results. In this guide, we explore the techniques and OpenAI platform tools you can use to ensure high quality outputs from the model.

4 6 

5This guide covers evals and fine-tuning workflows that are being moved into7This guide covers evals and fine-tuning workflows that are being moved into

6 legacy documentation. See the [deprecations page](https://developers.openai.com/api/docs/deprecations) for8 legacy documentation. See the [deprecations page](https://developers.openai.com/api/docs/deprecations) for

7 the current timelines for the affected platform surfaces.9 the current timelines for the affected platform surfaces.

8 10 

9<div className="my-4 w-full max-w-full overflow-hidden">11 

10 </div>12 

13 - **[Evals](https://developers.openai.com/api/docs/guides/evals)**: Systematically measure performance.

14- **[Prompt engineering](https://developers.openai.com/api/docs/guides/text?api-mode=responses#prompt-engineering)**: Give context, instructions, and goals.

15- **[Fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)**: Train models to excel at a task.

16 

17 

11 18 

12## Model optimization workflow19## Model optimization workflow

13 20 


28 35 

29Run your evals against test inputs like you expect to see in production. Using one of several available [graders](https://developers.openai.com/api/docs/guides/graders), measure the results of a prompt against your test data set.36Run your evals against test inputs like you expect to see in production. Using one of several available [graders](https://developers.openai.com/api/docs/guides/graders), measure the results of a prompt against your test data set.

30 37 

31[38[Learn about evals

39 

32 40 

33<span slot="icon">

34 </span>

35 Run tests on your model outputs to ensure you're getting the right results.

36 41 

37](https://developers.openai.com/api/docs/guides/evals)42 Run tests on your model outputs to ensure you're getting the right results.](https://developers.openai.com/api/docs/guides/evals)

38 43 

39## Write effective prompts44## Write effective prompts

40 45 


44- **Provide clear instructions** - your prompt should contain clear goals about what kind of output you want. Start with [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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.

45- **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.

46 51 

47[52[Learn about prompt engineering

53 

48 54 

49<span slot="icon">

50 </span>

51 Learn the basics of writing good prompts for the model.

52 55 

53](https://developers.openai.com/api/docs/guides/text)56 Learn the basics of writing good prompts for the model.](https://developers.openai.com/api/docs/guides/text)

54 57 

55## Fine-tune a model58## Fine-tune a model

56 59 

57OpenAI is winding down the fine-tuning platform. The platform is no longer60OpenAI is winding down the fine-tuning platform. The platform is no longer

58 accessible to new users, but existing users of the fine-tuning platform will61 accessible to new users, but existing users of the fine-tuning platform will

59 be able to create training jobs for the coming months.62 be able to create training jobs for the coming months.

60 <br />63

64 

61 All fine-tuned models will remain available for inference until their base65 All fine-tuned models will remain available for inference until their base

62 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is66 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

63 [here](https://developers.openai.com/api/docs/deprecations).67 [here](https://developers.openai.com/api/docs/deprecations).


77 81 

78These are the fine-tuning methods supported in the OpenAI platform today.82These are the fine-tuning methods supported in the OpenAI platform today.

79 83 

84 

85 

86<table>

87<tbody>

88<tr>

89<th>Method</th>

90<th>How it works</th>

91<th>Best for</th>

92<th>Use with</th>

93</tr>

94 

95<tr>

96<td>

97[Supervised fine-tuning (SFT)](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

98</td>

99<td>

100Provide examples of correct responses to prompts to guide the model's behavior.

101 

102Often uses human-generated "ground truth" responses to show the model how it should respond.

103 

104</td>

105<td>

106- Classification

107- Nuanced translation

108- Generating content in a specific format

109- Correcting instruction-following failures

110</td>

111<td>

112`gpt-4.1-2025-04-14`

113`gpt-4.1-mini-2025-04-14`

114`gpt-4.1-nano-2025-04-14`

115</td>

116</tr>

117 

118<tr>

119 <td>[Vision fine-tuning](https://developers.openai.com/api/docs/guides/vision-fine-tuning)</td>

120 <td>

121 Provide image inputs for supervised fine-tuning to improve the model's

122 understanding of image inputs.

123 </td>

124 <td>

125 - Image classification - Correcting failures in instruction following for

126 complex prompts

127 </td>

128 <td>`gpt-4o-2024-08-06`</td>

129</tr>

130 

131<tr>

132 <td>

133 [Direct preference optimization

134 (DPO)](https://developers.openai.com/api/docs/guides/direct-preference-optimization)

135 </td>

136 <td>

137 Provide both a correct and incorrect example response for a prompt. Indicate

138 the correct response to help the model perform better.

139 </td>

140 <td>

141 - Summarizing text, focusing on the right things - Generating chat messages

142 with the right tone and style

143 </td>

144 <td>

145 `gpt-4.1-2025-04-14` `gpt-4.1-mini-2025-04-14` `gpt-4.1-nano-2025-04-14`

146 </td>

147</tr>

148 

149<tr>

150<td>

151[Reinforcement fine-tuning (RFT)](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

152</td>

153<td>

154Generate a response for a prompt, provide an expert grade for the result, and reinforce the model's chain-of-thought for higher-scored responses.

155 

156Requires expert graders to agree on the ideal output from the model.

157 

158**Reasoning models only**.

159 

160</td>

161<td>

162- Complex domain-specific tasks that require advanced reasoning

163- Medical diagnoses based on history and diagnostic guidelines

164- Determining relevant passages from legal case law

165</td>

166<td>

167`o4-mini-2025-04-16`

168</td>

169</tr>

170</tbody>

171</table>

172 

173 

174 

80### How fine-tuning works175### How fine-tuning works

81 176 

82In the OpenAI platform, you can create fine-tuned models either in the [dashboard](https://platform.openai.com/finetune) or [with the API](https://developers.openai.com/api/docs/api-reference/fine-tuning). This is the general shape of the fine-tuning process:177In the OpenAI platform, you can create fine-tuned models either in the [dashboard](https://platform.openai.com/finetune) or [with the API](https://developers.openai.com/api/reference/resources/fine_tuning). This is the general shape of the fine-tuning process:

83 178 

841. Collect a dataset of examples to use as training data1791. Collect a dataset of examples to use as training data

851. Upload that dataset to OpenAI, formatted in JSONL1801. Upload that dataset to OpenAI, formatted in JSONL


95 190 

96 191 

97 192 

98<div data-content-switcher-pane data-value="cost">193Cost/accuracy/latency

99 <div class="hidden">Cost/accuracy/latency</div>194 

100 <iframe195 <iframe

101 width="100%"196 width="100%"

102 height="400"197 height="400"


105 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"200 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"

106 allowFullScreen201 allowFullScreen

107 ></iframe>202 ></iframe>

108 </div>203

109 <div data-content-switcher-pane data-value="distillation" hidden>204 

110 <div class="hidden">Distillation</div>205

206 

207

208Distillation

209 

111 <iframe210 <iframe

112 width="100%"211 width="100%"

113 height="400"212 height="400"


116 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"215 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"

117 allowFullScreen216 allowFullScreen

118 ></iframe>217 ></iframe>

119 </div>218

120 <div data-content-switcher-pane data-value="techniques" hidden>219 

121 <div class="hidden">Optimizing LLM Performance</div>220

221 

222

223Optimizing LLM Performance

224 

122 <iframe225 <iframe

123 width="100%"226 width="100%"

124 height="400"227 height="400"


127 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"230 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"

128 allowFullScreen231 allowFullScreen

129 ></iframe>232 ></iframe>

130 </div>

Details

1# Model selection1# Model selection

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.

4 

3Choosing the right model, whether [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) or a smaller option like [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra), requires balancing **accuracy**, **latency**, and **cost**. This guide explains key principles to help you make informed decisions, along with a practical example.5Choosing the right model, whether [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) or a smaller option like [`gpt-5.6-terra`](https://developers.openai.com/api/docs/models/gpt-5.6-terra), requires balancing **accuracy**, **latency**, and **cost**. This guide explains key principles to help you make informed decisions, along with a practical example.

4 6 

5## Core principles7## Core principles

Details

1# Moderation1# Moderation

2 2 

3Use OpenAI moderation models to detect harmful content in text and images. You can classify standalone inputs with the [moderation endpoint](https://developers.openai.com/api/docs/api-reference/moderations) or request moderation scores alongside a generated response. Use the results to enforce your application's policy, such as filtering content, routing a request for review, or intervening with accounts that submit flagged content.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 

5Use OpenAI moderation models to detect harmful content in text and images. You can classify standalone inputs with the [moderation endpoint](https://developers.openai.com/api/reference/resources/moderations) or request moderation scores alongside a generated response. Use the results to enforce your application's policy, such as filtering content, routing a request for review, or intervening with accounts that submit flagged content.

4 6 

5The `omni-moderation-latest` model accepts text and image inputs. It doesn't classify audio. The moderation endpoint is free to use, and image files can be up to 20 MB.7The `omni-moderation-latest` model accepts text and image inputs. It doesn't classify audio. The moderation endpoint is free to use, and image files can be up to 20 MB.

6 8 


102 104 

103## Classify standalone inputs105## Classify standalone inputs

104 106 

105Use the [moderation endpoint](https://developers.openai.com/api/docs/api-reference/moderations) to classify text or image inputs without generating a model response. The tabs below show how to use the [OpenAI libraries](https://developers.openai.com/api/docs/libraries) and the [`omni-moderation-latest` model](https://developers.openai.com/api/docs/models#moderation):107Use the [moderation endpoint](https://developers.openai.com/api/reference/resources/moderations) to classify text or image inputs without generating a model response. The tabs below show how to use the [OpenAI libraries](https://developers.openai.com/api/docs/libraries) and the [`omni-moderation-latest` model](https://developers.openai.com/api/docs/models#moderation):

108 

109 

110 

111Moderate text inputs

112 

113

114 

115Get classification information for a text input

116 

117```python

118from openai import OpenAI

119 

120client = OpenAI()

121 

122response = client.moderations.create(

123 model="omni-moderation-latest",

124 input="...text to classify goes here...",

125)

126 

127print(response)

128```

129 

130```javascript

131import OpenAI from "openai";

132const openai = new OpenAI();

133 

134const moderation = await openai.moderations.create({

135 model: "omni-moderation-latest",

136 input: "...text to classify goes here...",

137});

138 

139console.log(moderation);

140```

141 

142```bash

143curl https://api.openai.com/v1/moderations \

144 -X POST \

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

146 -H "Authorization: Bearer $OPENAI_API_KEY" \

147 -d '{

148 "model": "omni-moderation-latest",

149 "input": "...text to classify goes here..."

150 }'

151```

152 

153 

154

155 

156

157 

158

159Moderate images and text

106 160 

107 161

108 162 

109<div data-content-switcher-pane data-value="text">163Get classification information for image and text input

110 <div class="hidden">Moderate text inputs</div>164 

111 </div>165```python

112 <div data-content-switcher-pane data-value="images" hidden>166from openai import OpenAI

113 <div class="hidden">Moderate images and text</div>167 

114 </div>168client = OpenAI()

169 

170response = client.moderations.create(

171 model="omni-moderation-latest",

172 input=[

173 {"type": "text", "text": "...text to classify goes here..."},

174 {

175 "type": "image_url",

176 "image_url": {

177 "url": "https://example.com/image.png",

178 # You can also use a Base64 encoded image URL.

179 # "url": "data:image/jpeg;base64,abcdefg..."

180 },

181 },

182 ],

183)

184 

185print(response)

186```

187 

188```javascript

189import OpenAI from "openai";

190const openai = new OpenAI();

191 

192const moderation = await openai.moderations.create({

193 model: "omni-moderation-latest",

194 input: [

195 { type: "text", text: "...text to classify goes here..." },

196 {

197 type: "image_url",

198 image_url: {

199 url: "https://example.com/image.png",

200 // You can also use a Base64 encoded image URL.

201 // url: "data:image/jpeg;base64,abcdefg...",

202 },

203 },

204 ],

205});

206 

207console.log(moderation);

208```

209 

210```bash

211curl https://api.openai.com/v1/moderations \

212 -X POST \

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

214 -H "Authorization: Bearer $OPENAI_API_KEY" \

215 -d '{

216 "model": "omni-moderation-latest",

217 "input": [

218 { "type": "text", "text": "...text to classify goes here..." },

219 {

220 "type": "image_url",

221 "image_url": {

222 "url": "https://example.com/image.png"

223 }

224 }

225 ]

226 }'

227```

115 228 

116 229 

117 230 


232<table>345<table>

233 <tr>346 <tr>

234 <th>347 <th>

235 <strong>Category</strong>348 **Category**

236 </th>349 </th>

237 <th>350 <th>

238 <strong>Description</strong>351 **Description**

239 </th>352 </th>

240 <th>353 <th>

241 <strong>Inputs</strong>354 **Inputs**

242 </th>355 </th>

243 </tr>356 </tr>

244 <tr>357 <tr>

Details

1# Node reference1# Node reference

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.

4 

3[Agent Builder](https://platform.openai.com/agent-builder) is a visual canvas for composing agentic workflows. Workflows are made up of nodes and connections that control the sequence and flow. Insert nodes, then configure and connect them to define the process you want your agents to follow.5[Agent Builder](https://platform.openai.com/agent-builder) is a visual canvas for composing agentic workflows. Workflows are made up of nodes and connections that control the sequence and flow. Insert nodes, then configure and connect them to define the process you want your agents to follow.

4 6 

5OpenAI is deprecating Agent Builder. Existing users can continue using it7OpenAI is deprecating Agent Builder. Existing users can continue using it

Details

1# Optimizing LLM Accuracy1# Optimizing LLM Accuracy

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.

4 

3### How to maximize correctness and consistent behavior when working with LLMs5### How to maximize correctness and consistent behavior when working with LLMs

4 6 

5Optimizing LLMs is hard.7Optimizing LLMs is hard.


73 75 

74Given an Icelandic sentence, we want the model to return a corrected version of the sentence. We’ll use Bleu score to measure the relative quality of the translation.76Given an Icelandic sentence, we want the model to return a corrected version of the sentence. We’ll use Bleu score to measure the relative quality of the translation.

75 77 

76<div className="icelandic-zero-shot-table">78 

79 

77 80 

78| system | user | ground_truth | assistant | BLEU |81| system | user | ground_truth | assistant | BLEU |

79| ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---- |82| ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---- |

80| The following sentences contain Icelandic sentences which may include errors. Please correct these errors using as few word changes as possible. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjótsti. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjósti. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjósti. | 1.0 |83| The following sentences contain Icelandic sentences which may include errors. Please correct these errors using as few word changes as possible. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjótsti. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjósti. | Sörvistölur eru nær hálsi og skartgripir kvenna á brjósti. | 1.0 |

81 84 

82</div>85 

86 

83 87 

84We perform a first attempt with GPT-4 with no examples, and it performs decently, getting a BLEU score of 62.88We perform a first attempt with GPT-4 with no examples, and it performs decently, getting a BLEU score of 62.

85We’ll now add some few-shot examples and see whether we can teach the model the style we’re looking for by showing rather than telling.89We’ll now add some few-shot examples and see whether we can teach the model the style we’re looking for by showing rather than telling.


179 183 

180| Area | Problem | Resolution |184| Area | Problem | Resolution |

181| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |185| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

182| Retrieval | You can supply the wrong context, so the model can’t possibly answer, or you can supply too much irrelevant context, which drowns out the real information and causes hallucinations. | Optimizing your retrieval, which can include:<br/>- Tuning the search to return the right results.<br/>- Tuning the search to include less noise.<br/>- Providing more information in each retrieved result<br/>These are just examples, as tuning RAG performance is an industry into itself, with libraries like LlamaIndex and LangChain giving many approaches to tuning here. |186| Retrieval | You can supply the wrong context, so the model can’t possibly answer, or you can supply too much irrelevant context, which drowns out the real information and causes hallucinations. | Optimizing your retrieval, which can include:<br />- Tuning the search to return the right results.<br />- Tuning the search to include less noise.<br />- Providing more information in each retrieved result<br />These are just examples, as tuning RAG performance is an industry into itself, with libraries like LlamaIndex and LangChain giving many approaches to tuning here. |

183| LLM | The model can also get the right context and do the wrong thing with it. | Prompt engineering by improving the instructions and method the model uses, and, if showing it examples increases accuracy, adding in fine-tuning |187| LLM | The model can also get the right context and do the wrong thing with it. | Prompt engineering by improving the instructions and method the model uses, and, if showing it examples increases accuracy, adding in fine-tuning |

184 188 

185The key thing to take away here is that the principle remains the same from our mental model at the beginning - you evaluate to find out what has gone wrong, and take an optimization step to fix it. The only difference with RAG is you now have the retrieval axis to consider.189The key thing to take away here is that the principle remains the same from our mental model at the beginning - you evaluate to find out what has gone wrong, and take an optimization step to fix it. The only difference with RAG is you now have the retrieval axis to consider.


203 207 

204![Fine-tuning process diagram](https://cdn.openai.com/API/docs/images/diagram-optimizing-accuracy-06.png)208![Fine-tuning process diagram](https://cdn.openai.com/API/docs/images/diagram-optimizing-accuracy-06.png)

205 209 

206Once you have this clean set, you can train a fine-tuned model by performing a **training** run - depending on the platform or framework you’re using for training you may have hyperparameters you can tune here, similar to any other machine learning model. We always recommend maintaining a hold-out set to use for **evaluation** following training to detect overfitting. For tips on how to construct a good training set you can check out the [guidance](https://developers.openai.com/api/docs/guides/fine-tuning#analyzing-your-fine-tuned-model) in our Fine-tuning documentation. Once training is completed, the new, fine-tuned model is available for inference.210Once you have this clean set, you can train a fine-tuned model by performing a **training** run - depending on the platform or framework you’re using for training you may have hyperparameters you can tune here, similar to any other machine learning model. We always recommend maintaining a hold-out set to use for **evaluation** following training to detect overfitting. For tips on how to construct a good training set you can check out the [guidance](https://developers.openai.com/api/docs/guides/model-optimization#analyzing-your-fine-tuned-model) in our Fine-tuning documentation. Once training is completed, the new, fine-tuned model is available for inference.

207 211 

208For optimizing fine-tuning we’ll focus on best practices we observe with OpenAI’s model customization offerings, but these principles should hold true with other providers and OSS offerings. The key practices to observe here are:212For optimizing fine-tuning we’ll focus on best practices we observe with OpenAI’s model customization offerings, but these principles should hold true with other providers and OSS offerings. The key practices to observe here are:

209 213 


282 286 

283First we identify the primary success and failure cases, and assign an estimated cost to them. This gives us a clear articulation of what the solution is likely to save or cost based on pilot performance.287First we identify the primary success and failure cases, and assign an estimated cost to them. This gives us a clear articulation of what the solution is likely to save or cost based on pilot performance.

284 288 

285- For example, a case getting solved by an AI where it was previously solved by a human may save <strong>$20</strong>.289- For example, a case getting solved by an AI where it was previously solved by a human may save **$20**.

286- Someone getting escalated to a human when they shouldn’t might cost **$40**290- Someone getting escalated to a human when they shouldn’t might cost **$40**

287- In the worst case scenario, a customer gets so frustrated with the AI they churn, costing us **$1000**. We assume this happens in 5% of cases.291- In the worst case scenario, a customer gets so frustrated with the AI they churn, costing us **$1000**. We assume this happens in 5% of cases.

288 292 

Details

1# Predicted Outputs1# Predicted Outputs

2 2 

3**Predicted Outputs** enable you to speed up API responses from [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat/create) when many of the output tokens are known ahead of time. This is most common when you are regenerating a text or code file with minor modifications. You can provide your prediction using the [`prediction` request parameter in Chat Completions](https://developers.openai.com/api/docs/api-reference/chat/create#chat-create-prediction).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 

5**Predicted Outputs** enable you to speed up API responses from [Chat Completions](https://developers.openai.com/api/reference/resources/chat) when many of the output tokens are known ahead of time. This is most common when you are regenerating a text or code file with minor modifications. You can provide your prediction using the [`prediction` request parameter in Chat Completions](https://developers.openai.com/api/reference/resources/chat#chat-create-prediction).

4 6 

5Predicted Outputs are available today using the latest `gpt-4o`, `gpt-4o-mini`, `gpt-4.1`, `gpt-4.1-mini`, and `gpt-4.1-nano` models. Read on to learn how to use Predicted Outputs to reduce latency in your applications.7Predicted Outputs are available today using the latest `gpt-4o`, `gpt-4o-mini`, `gpt-4.1`, `gpt-4.1-mini`, and `gpt-4.1-nano` models. Read on to learn how to use Predicted Outputs to reduce latency in your applications.

6 8 


351When using Predicted Outputs, you should consider the following factors and limitations.353When using Predicted Outputs, you should consider the following factors and limitations.

352 354 

353- Predicted Outputs are only supported with the GPT-4o, GPT-4o-mini, GPT-4.1, GPT-4.1-mini, and GPT-4.1-nano series of models.355- Predicted Outputs are only supported with the GPT-4o, GPT-4o-mini, GPT-4.1, GPT-4.1-mini, and GPT-4.1-nano series of models.

354- When providing a prediction, any tokens provided that are not part of the final completion are still charged at completion token rates. See the [`rejected_prediction_tokens` property of the `usage` object](https://developers.openai.com/api/docs/api-reference/chat/object#chat/object-usage) to see how many tokens are not used in the final response.356- When providing a prediction, any tokens provided that are not part of the final completion are still charged at completion token rates. See the [`rejected_prediction_tokens` property of the `usage` object](https://developers.openai.com/api/reference/resources/chat#chat/object-usage) to see how many tokens are not used in the final response.

355- The following [API parameters](https://developers.openai.com/api/docs/api-reference/chat/create) are not supported when using Predicted Outputs:357- The following [API parameters](https://developers.openai.com/api/reference/resources/chat) are not supported when using Predicted Outputs:

356 - `n`: values higher than 1 are not supported358 - `n`: values higher than 1 are not supported

357 - `logprobs`: not supported359 - `logprobs`: not supported

358 - `presence_penalty`: values greater than 0 are not supported360 - `presence_penalty`: values greater than 0 are not supported

Details

1# Priority processing1# Priority processing

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.

4 

3Priority processing delivers significantly lower and more consistent latency compared to Standard processing while keeping pay-as-you-go flexibility.5Priority processing delivers significantly lower and more consistent latency compared to Standard processing while keeping pay-as-you-go flexibility.

4 6 

5Priority processing is ideal for high-value, user-facing applications with regular traffic where latency is paramount. Priority processing should not be used for data processing, evaluations, or other highly erratic traffic.7Priority processing is ideal for high-value, user-facing applications with regular traffic where latency is paramount. Priority processing should not be used for data processing, evaluations, or other highly erratic traffic.

Details

1# Production best practices1# Production best practices

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.

4 

3This guide provides a comprehensive set of best practices to help you transition from prototype to production. Whether you are a seasoned machine learning engineer or a recent enthusiast, this guide should provide you with the tools you need to successfully put the platform to work in a production setting: from securing access to our API to designing a robust architecture that can handle high traffic volumes. Use this guide to help develop a plan for deploying your application as smoothly and effectively as possible.5This guide provides a comprehensive set of best practices to help you transition from prototype to production. Whether you are a seasoned machine learning engineer or a recent enthusiast, this guide should provide you with the tools you need to successfully put the platform to work in a production setting: from securing access to our API to designing a robust architecture that can handle high traffic volumes. Use this guide to help develop a plan for deploying your application as smoothly and effectively as possible.

4 6 

5If you want to explore best practices for going into production further, please check out our Developer Day talk:7If you want to explore best practices for going into production further, please check out our Developer Day talk:


18 20 

19Once you [log in](https://platform.openai.com/login) to your OpenAI account, you can find your organization name and ID in your [organization settings](https://platform.openai.com/settings/organization/general). The organization name is the label for your organization, shown in user interfaces. The organization ID is the unique identifier for your organization which can be used in API requests.21Once you [log in](https://platform.openai.com/login) to your OpenAI account, you can find your organization name and ID in your [organization settings](https://platform.openai.com/settings/organization/general). The organization name is the label for your organization, shown in user interfaces. The organization ID is the unique identifier for your organization which can be used in API requests.

20 22 

21Users who belong to multiple organizations can [pass a header](https://developers.openai.com/api/docs/api-reference/requesting-organization) to specify which organization is used for an API request. Usage from these API requests will count against the specified organization's quota. If no header is provided, the [default organization](https://platform.openai.com/settings/organization/api-keys) will be billed. You can change your default organization in your [user settings](https://platform.openai.com/settings/organization/api-keys).23Users who belong to multiple organizations can [pass a header](https://developers.openai.com/api/reference/overview#authentication) to specify which organization is used for an API request. Usage from these API requests will count against the specified organization's quota. If no header is provided, the [default organization](https://platform.openai.com/settings/organization/api-keys) will be billed. You can change your default organization in your [user settings](https://platform.openai.com/settings/organization/api-keys).

22 24 

23You can invite new members to your organization from the [Team page](https://platform.openai.com/settings/organization/team). Members can be **readers** or **owners**.25You can invite new members to your organization from the [Team page](https://platform.openai.com/settings/organization/team). Members can be **readers** or **owners**.

24 26 


74 76 

75The latency of a completion request is mostly influenced by two factors: the model and the number of tokens generated. The life cycle of a completion request looks like this:77The latency of a completion request is mostly influenced by two factors: the model and the number of tokens generated. The life cycle of a completion request looks like this:

76 78 

77<br />79- End user to API latency

80- Time to process prompt tokens

81- Time to sample/generate tokens

82- API to end user latency

83 

84 

78 85 

79The bulk of the latency typically arises from the token generation step.86The bulk of the latency typically arises from the token generation step.

80 87 


107 114 

108#### Batching115#### Batching

109 116 

110Depending on your use case, batching <em>may help</em>. If you are sending multiple requests to the same endpoint, you can [batch the prompts](https://developers.openai.com/api/docs/guides/rate-limits#batching-requests) to be sent in the same request. This will reduce the number of requests you need to make. The prompt parameter can hold up to 20 unique prompts. We advise you to test out this method and see if it helps. In some cases, you may end up increasing the number of generated tokens which will slow the response time.117Depending on your use case, batching _may help_. If you are sending multiple requests to the same endpoint, you can [batch the prompts](https://developers.openai.com/api/docs/guides/rate-limits#batching-requests) to be sent in the same request. This will reduce the number of requests you need to make. The prompt parameter can hold up to 20 unique prompts. We advise you to test out this method and see if it helps. In some cases, you may end up increasing the number of generated tokens which will slow the response time.

111 118 

112## Managing costs119## Managing costs

113 120 

Details

1# Prompt caching1# Prompt caching

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.

4 

3Model prompts often contain repetitive content, like system prompts and common instructions. OpenAI routes API requests to servers that recently processed the same prompt, making it faster and less expensive to reuse an exact prompt prefix than to process it from scratch. Prompt Caching works automatically for eligible requests, with no code changes required. It is enabled for all recent [models](https://developers.openai.com/api/docs/models), `gpt-4o` and newer.5Model prompts often contain repetitive content, like system prompts and common instructions. OpenAI routes API requests to servers that recently processed the same prompt, making it faster and less expensive to reuse an exact prompt prefix than to process it from scratch. Prompt Caching works automatically for eligible requests, with no code changes required. It is enabled for all recent [models](https://developers.openai.com/api/docs/models), `gpt-4o` and newer.

4 6 

5Cache writes have no additional fee on models before the GPT-5.6 family. For GPT-5.6 models and later model families, cache writes cost 1.25× the uncached input token rate. On these models, both implicit and explicit caching are more consistent and reliable. You can also use explicit cache breakpoints to control exactly which prompt prefixes OpenAI caches. OpenAI reports writes in `cache_write_tokens` and reads in `cached_tokens`, so you can measure the cost of writes against the savings from later cache hits.7Cache writes have no additional fee on models before the GPT-5.6 family. For GPT-5.6 models and later model families, cache writes cost 1.25× the uncached input token rate. On these models, both implicit and explicit caching are more consistent and reliable. You can also use explicit cache breakpoints to control exactly which prompt prefixes OpenAI caches. OpenAI reports writes in `cache_write_tokens` and reads in `cached_tokens`, so you can measure the cost of writes against the savings from later cache hits.


191. **Cache Routing**:211. **Cache Routing**:

20 22 

21- Requests are routed to a machine based on a hash of the initial prefix of the prompt. The hash typically uses the first 256 tokens, though the exact length varies depending on the model.23- Requests are routed to a machine based on a hash of the initial prefix of the prompt. The hash typically uses the first 256 tokens, though the exact length varies depending on the model.

22- If you provide the [`prompt_cache_key`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-prompt_cache_key) parameter, it is combined with the prefix hash, allowing you to influence routing and improve cache hit rates. This is especially beneficial when many requests share long, common prefixes.24- If you provide the [`prompt_cache_key`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-prompt_cache_key) parameter, it is combined with the prefix hash, allowing you to influence routing and improve cache hit rates. This is especially beneficial when many requests share long, common prefixes.

23 25 

242. **Cache Lookup**: The system checks if the initial portion (prefix) of your prompt exists in the cache on the selected machine.262. **Cache Lookup**: The system checks if the initial portion (prefix) of your prompt exists in the cache on the selected machine.

253. **Cache Hit**: If a matching prefix is found, the system uses the cached result. This decreases latency and bills those tokens at the cached-input rate.273. **Cache Hit**: If a matching prefix is found, the system uses the cached result. This decreases latency and bills those tokens at the cached-input rate.


54 56 

55 57 

56 58 

57<div data-content-switcher-pane data-value="responses">59Responses API

58 <div class="hidden">Responses API</div>60 

59 61 

60 This request uses the default `implicit` mode, which places a breakpoint on62 This request uses the default `implicit` mode, which places a breakpoint on

61 the latest message, and adds an explicit breakpoint after a stable file.63 the latest message, and adds an explicit breakpoint after a stable file.

62 64 

63 ```json65```json

64{66{

65 "model": "gpt-5.6",67 "model": "gpt-5.6",

66 "prompt_cache_key": "tenant:acme:knowledge-base-v1",68 "prompt_cache_key": "tenant:acme:knowledge-base-v1",


87```89```

88 90 

89 91 

90 </div>92

91 <div data-content-switcher-pane data-value="chat-completions" hidden>93 

92 <div class="hidden">Chat Completions API</div>94

95 

96

97Chat Completions API

98 

93 99 

94 This request disables automatic breakpoint placement. Only the marked100 This request disables automatic breakpoint placement. Only the marked

95 system-message prefix is eligible for billable cache writes and discounted101 system-message prefix is eligible for billable cache writes and discounted

96 cache reads.102 cache reads.

97 103 

98 ```json104```json

99{105{

100 "model": "gpt-5.6",106 "model": "gpt-5.6",

101 "prompt_cache_key": "tenant:acme:support-assistant-v1",107 "prompt_cache_key": "tenant:acme:support-assistant-v1",


124```130```

125 131 

126 132 

127 </div>

128 

129 

130 133 

131Only `explicit` is valid for `prompt_cache_breakpoint.mode`. A marker on an unsupported or non-cacheable block returns a `400 invalid_request_error`. Older models also reject `prompt_cache_options` and `prompt_cache_breakpoint`; continue using their existing automatic prompt caching behavior.134Only `explicit` is valid for `prompt_cache_breakpoint.mode`. A marker on an unsupported or non-cacheable block returns a `400 invalid_request_error`. Older models also reject `prompt_cache_options` and `prompt_cache_breakpoint`; continue using their existing automatic prompt caching behavior.

132 135 


192 195 

193Caching is available for prompts containing 1024 tokens or more.196Caching is available for prompts containing 1024 tokens or more.

194 197 

195All requests, including those with fewer than 1024 tokens, display a `cached_tokens` field in the usage token details. Responses API returns this field in `usage.input_tokens_details` on the [Response object](https://developers.openai.com/api/docs/api-reference/responses/object); Chat Completions API returns it in `usage.prompt_tokens_details` on the [Chat object](https://developers.openai.com/api/docs/api-reference/chat/object). The field indicates how many input tokens were read from cache. For requests under 1024 tokens, `cached_tokens` is zero.198All requests, including those with fewer than 1024 tokens, display a `cached_tokens` field in the usage token details. Responses API returns this field in `usage.input_tokens_details` on the [Response object](https://developers.openai.com/api/reference/resources/responses); Chat Completions API returns it in `usage.prompt_tokens_details` on the [Chat object](https://developers.openai.com/api/reference/resources/chat). The field indicates how many input tokens were read from cache. For requests under 1024 tokens, `cached_tokens` is zero.

196 199 

197For GPT-5.6 models and later model families, `cache_write_tokens` reports the number of prompt tokens written to cache. Cache write billing uses this value at 1.25× the uncached input token rate.200For GPT-5.6 models and later model families, `cache_write_tokens` reports the number of prompt tokens written to cache. Cache write billing uses this value at 1.25× the uncached input token rate.

198 201 


225## Best practices228## Best practices

226 229 

227- Structure prompts with **static or repeated content at the beginning** and dynamic, user-specific content at the end.230- Structure prompts with **static or repeated content at the beginning** and dynamic, user-specific content at the end.

228- Use the **[`prompt_cache_key`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-prompt_cache_key) parameter** consistently across requests that share long, common prefixes to improve cache hit rates. On GPT-5.6 models and later model families, you must set this parameter to use the more reliable cache matching. Keep the total traffic for each key to approximately 15 requests per minute, and use more keys for higher-volume workloads.231- Use the **[`prompt_cache_key`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-prompt_cache_key) parameter** consistently across requests that share long, common prefixes to improve cache hit rates. On GPT-5.6 models and later model families, you must set this parameter to use the more reliable cache matching. Keep the total traffic for each key to approximately 15 requests per minute, and use more keys for higher-volume workloads.

229- On GPT-5.6 models and later model families, place **explicit cache breakpoints** after stable prompt content that is likely to be reused. Set `prompt_cache_options.mode` to `explicit` when you want the service to use only the breakpoints you provide.232- On GPT-5.6 models and later model families, place **explicit cache breakpoints** after stable prompt content that is likely to be reused. Set `prompt_cache_options.mode` to `explicit` when you want the service to use only the breakpoints you provide.

230- **Monitor cache reads and writes** by logging `cached_tokens` and `cache_write_tokens`. Compare cache-write volume with subsequent cache reads to understand net cost and adjust breakpoint placement. You can also monitor cached token counts in the OpenAI Usage dashboard.233- **Monitor cache reads and writes** by logging `cached_tokens` and `cache_write_tokens`. Compare cache-write volume with subsequent cache reads to understand net cost and adjust breakpoint placement. You can also monitor cached token counts in the OpenAI Usage dashboard.

231- **Maintain a steady stream of requests** with identical prompt prefixes to minimize cache evictions and maximize caching benefits.234- **Maintain a steady stream of requests** with identical prompt prefixes to minimize cache evictions and maximize caching benefits.

Details

1# Prompt engineering1# Prompt engineering

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.

4 

3With the OpenAI API, you can use a [large language model](https://developers.openai.com/api/docs/models) to generate text from a prompt, as you might using [ChatGPT](https://chatgpt.com). Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.5With the OpenAI API, you can use a [large language model](https://developers.openai.com/api/docs/models) to generate text from a prompt, as you might using [ChatGPT](https://chatgpt.com). Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.

4 6 

5 7 

6 8 

7Here's a simple example using the [Responses API](https://developers.openai.com/api/docs/api-reference/responses).9Here's a simple example using the [Responses API](https://developers.openai.com/api/reference/resources/responses).

8 10 

9Generate text from a simple prompt11Generate text from a simple prompt

10 12 


42```44```

43 45 

44```csharp46```csharp

45using System;47using OpenAI.Responses;

46using System.Threading.Tasks;48#pragma warning disable OPENAI001

47using OpenAI;

48 49 

49class Program50string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

50{51ResponsesClient client = new(key);

51 static async Task Main()

52 {

53 var client = new OpenAIClient(

54 Environment.GetEnvironmentVariable("OPENAI_API_KEY")

55 );

56 52 

57 var response = await client.Responses.CreateAsync(new ResponseCreateRequest53ResponseResult response = await client.CreateResponseAsync(

58 {54 "gpt-5.6",

59 Model = "gpt-5.6",55 "Say 'this is a test.'"

60 Input = "Say 'this is a test.'"56);

61 });

62 57 

63 Console.WriteLine($"[ASSISTANT]: {response.OutputText()}");58Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");

64 }

65}

66```59```

67 60 

68```java61```java


342 335 

343- Keep prompt builders in a small module near the feature they support.336- Keep prompt builders in a small module near the feature they support.

344- Use typed function arguments or schemas for dynamic values such as customer data, files, or task options.337- Use typed function arguments or schemas for dynamic values such as customer data, files, or task options.

345- Pass the generated `instructions` and `input` directly to the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create).338- Pass the generated `instructions` and `input` directly to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create).

346- Add representative fixtures, tests, and evaluation checks before changing production prompts.339- Add representative fixtures, tests, and evaluation checks before changing production prompts.

347- Roll out prompt changes through your deployment system, using feature flags or configuration when you need staged releases.340- Roll out prompt changes through your deployment system, using feature flags or configuration when you need staged releases.

348 341 


365 358 

366 359 

367 360 

368<div data-content-switcher-pane data-value="prompt">361Example prompt

369 <div class="hidden">Example prompt</div>362 

370 A developer message for code generation363 A developer message for code generation

371 364 

372```text365```text


396</assistant_response>389</assistant_response>

397```390```

398 391 

399 </div>392

400 <div data-content-switcher-pane data-value="code" hidden>393 

401 <div class="hidden">API request</div>394

395 

396

397API request

398 

402 Send a prompt to generate code through the API399 Send a prompt to generate code through the API

403 400 

404```javascript401```javascript


445 }'442 }'

446```443```

447 444 

448 </div>

449 

450 445 

451 446 

452#### Save on cost and latency with prompt caching447#### Save on cost and latency with prompt caching

453 448 

454When constructing a message, you should try and keep content that you expect to use over and over in your API requests at the beginning of your prompt, **and** among the first API parameters you pass in the JSON request body to [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat) or [Responses](https://developers.openai.com/api/docs/api-reference/responses). This enables you to maximize cost and latency savings from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).449When constructing a message, you should try and keep content that you expect to use over and over in your API requests at the beginning of your prompt, **and** among the first API parameters you pass in the JSON request body to [Chat Completions](https://developers.openai.com/api/reference/resources/chat) or [Responses](https://developers.openai.com/api/reference/resources/responses). This enables you to maximize cost and latency savings from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).

455 450 

456## Few-shot learning451## Few-shot learning

457 452 


518 513 

519GPT models like [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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 GPT-5 series model, start with the current prompting guide.514GPT models like [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) 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 GPT-5 series model, start with the current prompting guide.

520 515 

521<a href="/api/docs/guides/latest-model#prompting-best-practices">516[

522

523 517 

524<span slot="icon">

525 </span>

526 Get the most out of prompting the latest GPT-5 series model with current518 Get the most out of prompting the latest GPT-5 series model with current

527 guidance, practical examples, and migration notes.519 guidance, practical examples, and migration notes.](https://developers.openai.com/api/docs/guides/latest-model#prompting-best-practices)

528 

529 

530</a>

531 520 

532### Prompting best practices for the latest GPT-5 series model521### Prompting best practices for the latest GPT-5 series model

533 522 


643 632 

644Now that you know the basics of text inputs and outputs, you might want to check out one of these resources next.633Now that you know the basics of text inputs and outputs, you might want to check out one of these resources next.

645 634 

646[635[Build a prompt in the Playground

647 636 

648<span slot="icon">

649 </span>

650 Use the Playground to develop and iterate on prompts.

651 637 

652](https://platform.openai.com/chat/edit)

653 638 

654[639 Use the Playground to develop and iterate on prompts.](https://platform.openai.com/chat/edit)

655 640 

656<span slot="icon">641[Generate JSON data with Structured Outputs

657 </span>

658 Ensure JSON data emitted from a model conforms to a JSON schema.

659 642 

660](https://developers.openai.com/api/docs/guides/structured-outputs)

661 643 

662[

663 644 

664<span slot="icon">645 Ensure JSON data emitted from a model conforms to a JSON schema.](https://developers.openai.com/api/docs/guides/structured-outputs)

665 </span>646 

666 Check out all the options for text generation in the API reference.647[Full API reference

648 

649 

667 650 

668](https://developers.openai.com/api/docs/api-reference/responses)651 Check out all the options for text generation in the API reference.](https://developers.openai.com/api/reference/resources/responses)

669 652 

670## Other resources653## Other resources

671 654 

672For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and also links to third-party resources such as:655For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and also links to third-party resources such as:

673 656 

674- [Prompting libraries & tools](https://developers.openai.com/cookbook/related_resources#prompting-libraries--tools)657- [Prompting libraries & tools](https://developers.openai.com/cookbook/articles/related_resources#prompting-libraries--tools)

675- [Prompting guides](https://developers.openai.com/cookbook/related_resources#prompting-guides)658- [Prompting guides](https://developers.openai.com/cookbook/articles/related_resources#prompting-guides)

676- [Video courses](https://developers.openai.com/cookbook/related_resources#video-courses)659- [Video courses](https://developers.openai.com/cookbook/articles/related_resources#video-courses)

677- [Papers on advanced prompting to improve reasoning](https://developers.openai.com/cookbook/related_resources#papers-on-advanced-prompting-to-improve-reasoning)660- [Papers on advanced prompting to improve reasoning](https://developers.openai.com/cookbook/articles/related_resources#papers-on-advanced-prompting-to-improve-reasoning)

Details

1# Prompt generation1# Prompt generation

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.

4 

3The **Generate** button in the [Playground](https://platform.openai.com/chat/edit) lets you generate prompts, [functions](https://developers.openai.com/api/docs/guides/function-calling), and [schemas](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) from just a description of your task. This guide will walk through exactly how it works.5The **Generate** button in the [Playground](https://platform.openai.com/chat/edit) lets you generate prompts, [functions](https://developers.openai.com/api/docs/guides/function-calling), and [schemas](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) from just a description of your task. This guide will walk through exactly how it works.

4 6 

5## Overview7## Overview


21 23 

22 24 

23 25 

24<div data-content-switcher-pane data-value="text-out">26Text-out

25 <div class="hidden">Text-out</div>27 

26 Text meta-prompt28 Text meta-prompt

27 29 

28````python30````python


95 return completion.choices[0].message.content97 return completion.choices[0].message.content

96````98````

97 99 

98 </div>100

99 <div data-content-switcher-pane data-value="audio-out" hidden>101 

100 <div class="hidden">Audio-out</div>102

103 

104

105Audio-out

106 

101 Audio meta-prompt107 Audio meta-prompt

102 108 

103```python109```python


161 return completion.choices[0].message.content167 return completion.choices[0].message.content

162```168```

163 169 

164 </div>

165 

166 170 

167 171 

168### Prompt edits172### Prompt edits


171 175 

172 176 

173 177 

174<div data-content-switcher-pane data-value="text-out">178Text-out

175 <div class="hidden">Text-out</div>179 

176 Text meta-prompt for edits180 Text meta-prompt for edits

177 181 

178````python182````python


264 return completion.choices[0].message.content268 return completion.choices[0].message.content

265````269````

266 270 

267 </div>271

268 <div data-content-switcher-pane data-value="audio-out" hidden>272 

269 <div class="hidden">Audio-out</div>273

274 

275

276Audio-out

277 

270 Audio meta-prompt for edits278 Audio meta-prompt for edits

271 279 

272```python280```python


349 return completion.choices[0].message.content357 return completion.choices[0].message.content

350```358```

351 359 

352 </div>

353 

354 360 

355 361 

356## Schemas362## Schemas


407 413 

408 414 

409 415 

410<div data-content-switcher-pane data-value="structured-output">416Structured output schema

411 <div class="hidden">Structured output schema</div>417 

412 Structured output meta-schema418 Structured output meta-schema

413 419 

414```python420```python


670 return json.loads(completion.choices[0].message.content)676 return json.loads(completion.choices[0].message.content)

671```677```

672 678 

673 </div>679

674 <div data-content-switcher-pane data-value="function" hidden>680 

675 <div class="hidden">Function schema</div>681

682 

683

684Function schema

685 

676 Structured output meta-schema686 Structured output meta-schema

677 687 

678```python688```python


884 894 

885 return json.loads(completion.choices[0].message.content)895 return json.loads(completion.choices[0].message.content)

886```896```

887 

888 </div>

Details

1# Prompting guidance for GPT-5.6 Sol1# Prompting guidance for GPT-5.6 Sol

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.

4 

3# Prompting guidance for GPT-5.6 Sol5# Prompting guidance for GPT-5.6 Sol

4 6 

5Use this guide when adapting prompts, tool descriptions, agent instructions, or prompt stacks to GPT-5.6 Sol or the GPT-5.6 family. Pair it with the current [GPT-5.6 model guide](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-5.6) for API details, limits, pricing, and feature availability.7Use this guide when adapting prompts, tool descriptions, agent instructions, or prompt stacks to GPT-5.6 Sol or the GPT-5.6 family. Pair it with the current [GPT-5.6 model guide](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-5.6) for API details, limits, pricing, and feature availability.


36 38 

37Prefer:39Prefer:

38 40 

39 Resolve the customer's issue end to end.41```text

42Resolve the customer's issue end to end.

40 43 

41 Success means:44Success means:

42 - make the eligibility decision from available policy and account evidence45- make the eligibility decision from available policy and account evidence

43 - complete any allowed action before responding46- complete any allowed action before responding

44 - return completed_actions, customer_message, and blockers47- return completed_actions, customer_message, and blockers

45 - if required evidence is missing, ask for the smallest missing field48- if required evidence is missing, ask for the smallest missing field

49```

46 50 

47Avoid unnecessary absolute rules. Use ALWAYS, NEVER, must, and only for true invariants such as safety rules, required fields, or actions that should never happen. For judgment calls, such as when to search, ask, use a tool, or keep iterating, prefer decision rules.51Avoid unnecessary absolute rules. Use ALWAYS, NEVER, must, and only for true invariants such as safety rules, required fields, or actions that should never happen. For judgment calls, such as when to search, ask, use a tool, or keep iterating, prefer decision rules.

48 52 


240 244 

241For coding:245For coding:

242 246 

243 After making changes, run the most relevant validation available:247```text

244 - targeted tests for changed behavior248After making changes, run the most relevant validation available:

245 - type checks or lint checks when applicable249- targeted tests for changed behavior

246 - build checks for affected packages250- type checks or lint checks when applicable

247 - a minimal smoke test when full validation is too expensive251- build checks for affected packages

252- a minimal smoke test when full validation is too expensive

248 253 

249 If validation cannot be run, explain why and describe the next best check.254If validation cannot be run, explain why and describe the next best check.

255```

250 256 

251For visual artifacts:257For visual artifacts:

252 258 

Details

1# Prompt optimizer1# Prompt optimizer

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.

4 

3The [prompt optimizer](https://platform.openai.com/chat/edit?optimize=true) is a chat interface in the dashboard, where you enter a prompt, and we optimize it according to current best practices before returning it to you. Pairing the prompt optimizer with [datasets](https://developers.openai.com/api/docs/guides/evaluation-getting-started) is a powerful way to automatically improve prompts.5The [prompt optimizer](https://platform.openai.com/chat/edit?optimize=true) is a chat interface in the dashboard, where you enter a prompt, and we optimize it according to current best practices before returning it to you. Pairing the prompt optimizer with [datasets](https://developers.openai.com/api/docs/guides/evaluation-getting-started) is a powerful way to automatically improve prompts.

4 6 

5OpenAI is deprecating the dataset-backed prompt optimizer as part of the Evals7OpenAI is deprecating the dataset-backed prompt optimizer as part of the Evals


40 42 

41For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and links to third-party resources, or learn more about our tools for evals:43For more inspiration, visit the [OpenAI Cookbook](https://developers.openai.com/cookbook), which contains example code and links to third-party resources, or learn more about our tools for evals:

42 44 

43<a45[Cookbook: Building resilient prompts with evals

44 href="https://cookbook.openai.com/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel"

45 target="_blank"

46 rel="noreferrer"

47>

48 46 

49 47 

50<span slot="icon">

51 </span>

52 Operate a flywheel of continuous improvement using evaluations.

53 48 

49 Operate a flywheel of continuous improvement using evaluations.](https://developers.openai.com/cookbook/examples/evaluation/building_resilient_prompts_using_an_evaluation_flywheel)

54 50 

55</a>51[Working with evals

56 52 

57<a href="/api/docs/guides/evals" target="_blank" rel="noreferrer">

58 53 

59 54 

60<span slot="icon">55 Evaluate against external models, interact with evals via API, and more.](https://developers.openai.com/api/docs/guides/evals)

61 </span>

62 Evaluate against external models, interact with evals via API, and more.

63 56 

57[Graders

64 58 

65</a>

66 59 

67[

68 60 

69<span slot="icon">61 Build sophisticated graders to improve the effectiveness of your evals.](https://developers.openai.com/api/docs/guides/graders)

70 </span>

71 Build sophisticated graders to improve the effectiveness of your evals.

72 62 

73](https://developers.openai.com/api/docs/guides/graders)63[Fine-tuning

74 64 

75[

76 65 

77<span slot="icon">

78 </span>

79 Improve a model's ability to generate responses tailored to your use case.

80 66 

81](https://developers.openai.com/api/docs/guides/fine-tuning)67 Improve a model's ability to generate responses tailored to your use case.](https://developers.openai.com/api/docs/guides/model-optimization)

Details

1# Prompting1# Prompting

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.

4 

3**Prompting** is the process of providing input to a model. The quality of your output often depends on how well you're able to prompt the model.5**Prompting** is the process of providing input to a model. The quality of your output often depends on how well you're able to prompt the model.

4 6 

5## Overview7## Overview


42 44 

43When you feel confident in your prompts, you might want to check out the following guides and resources.45When you feel confident in your prompts, you might want to check out the following guides and resources.

44 46 

45[47[Text generation

48 

49 

46 50 

47<span slot="icon">51 Learn how to prompt a model to generate text.](https://developers.openai.com/api/docs/guides/text)

48 </span>

49 Learn how to prompt a model to generate text.

50 52 

51](https://developers.openai.com/api/docs/guides/text)53[Engineer better prompts

52 54 

53[

54 55 

55<span slot="icon">

56 </span>

57 Learn about OpenAI's prompt engineering tools and techniques.

58 56 

59](https://developers.openai.com/api/docs/guides/prompt-engineering)57 Learn about OpenAI's prompt engineering tools and techniques.](https://developers.openai.com/api/docs/guides/prompt-engineering)

Details

1# Migrate from prompt objects1# Migrate from prompt objects

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.

4 

3OpenAI is deprecating reusable prompt objects in the API. Prompt creation will5OpenAI is deprecating reusable prompt objects in the API. Prompt creation will

4 be de-emphasized beginning June 3, 2026, and `v1/prompts` is scheduled to shut6 be de-emphasized beginning June 3, 2026, and `v1/prompts` is scheduled to shut

5 down on November 30, 2026. See the [deprecations7 down on November 30, 2026. See the [deprecations

Details

1# Rate limits1# Rate limits

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.

4 

3Rate limits are restrictions that our API imposes on the number of times a user or client can5Rate limits are restrictions that our API imposes on the number of times a user or client can

4access our services within a specified period of time.6access our services within a specified period of time.

5 7 


20 22 

21Rate 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.

22 24 

23[Batch API](https://developers.openai.com/api/docs/api-reference/batch/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.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.

24 26 

25Other important things worth noting:27Other important things worth noting:

26 28 

guides/rbac.md +6 −2

Details

1# Manage permissions in the OpenAI platform1# Manage permissions in the OpenAI platform

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.

4 

3Role-based access control (RBAC) lets you decide who can do what across your organization and projects—both through the API and in the Dashboard. The same permissions govern both surfaces: if someone can call an endpoint (for example, `/v1/chat/completions`), they can use the equivalent Dashboard page, and missing permissions disable related UI (such as the **Upload** button in Playground). With RBAC you can:5Role-based access control (RBAC) lets you decide who can do what across your organization and projects—both through the API and in the Dashboard. The same permissions govern both surfaces: if someone can call an endpoint (for example, `/v1/chat/completions`), they can use the equivalent Dashboard page, and missing permissions disable related UI (such as the **Upload** button in Playground). With RBAC you can:

4 6 

5- Group users and assign permissions at scale7- Group users and assign permissions at scale


19 21 

20The table below shows the available permissions, which preset roles include them, and whether they can be configured for custom roles.22The table below shows the available permissions, which preset roles include them, and whether they can be configured for custom roles.

21 23 

22<div style={{ overflowX: "auto" }}>24 

25 

23 26 

24| Area | What it allows | Org owner permissions | Org reader permissions | Project owner permissions | Project member permissions | Project viewer permissions | Custom role eligible |27| Area | What it allows | Org owner permissions | Org reader permissions | Project owner permissions | Project member permissions | Project viewer permissions | Custom role eligible |

25| ---------------------- | ------------------------------------------------------------------------------------ | ----------------------- | ---------------------- | ------------------------- | -------------------------- | -------------------------- | -------------------- |28| ---------------------- | ------------------------------------------------------------------------------------ | ----------------------- | ---------------------- | ------------------------- | -------------------------- | -------------------------- | -------------------- |


53| Voices | Create and retrieve voices | `Read`, `Write` | `Read`, `Write` | `Read`, `Write` | `Read`, `Write` | `Read` | |56| Voices | Create and retrieve voices | `Read`, `Write` | `Read`, `Write` | `Read`, `Write` | `Read`, `Write` | `Read` | |

54| Agent Builder | Create and manage agents and workflows in Agent Builder | `Read`, `Write` | `Read` | `Read`, `Write` | `Read`, `Write` | `Read` | ✓ |57| Agent Builder | Create and manage agents and workflows in Agent Builder | `Read`, `Write` | `Read` | `Read`, `Write` | `Read`, `Write` | `Read` | ✓ |

55 58 

56</div>59 

60 

57 61 

58## Setting up RBAC62## Setting up RBAC

59 63 

guides/realtime.md +36 −38

Details

1# Realtime and audio1# Realtime and audio

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.

4 

3Start with the outcome you want to build. Realtime sessions are best for live audio that needs low latency. Request-based audio APIs are best for files, bounded requests, or generated speech that doesn't need a live session.5Start with the outcome you want to build. Realtime sessions are best for live audio that needs low latency. Request-based audio APIs are best for files, bounded requests, or generated speech that doesn't need a live session.

4 6 

5## Common use cases7## Common use cases

6 8 

7<div className="w-full max-w-full overflow-hidden">9 

8 </div>10 

11 - **[Voice agents](https://developers.openai.com/api/docs/guides/voice-agents)**: Build speech-to-speech agents that listen, reason, speak, and call tools.

12- **[Live translation](https://developers.openai.com/api/docs/guides/realtime-translation)**: Translate live speech with a dedicated realtime translation session.

13- **[Transcription](https://developers.openai.com/api/docs/guides/transcription)**: Stream live transcript deltas or process audio files into text.

14- **[Speech generation](https://developers.openai.com/api/docs/guides/text-to-speech)**: Turn text into natural-sounding spoken audio.

15 

16 

9 17 

10## Understand different architectures18## Understand different architectures

11 19 


24 [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1)32 [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1)

25 </td>33 </td>

26 <td>34 <td>

27 <a href="/api/docs/guides/voice-agents">Voice agents</a>35 [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents)

28 </td>36 </td>

29 </tr>37 </tr>

30 <tr>38 <tr>


33 [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate)41 [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate)

34 </td>42 </td>

35 <td>43 <td>

36 <a href="/api/docs/guides/realtime-translation">Realtime translation</a>44 [Realtime translation](https://developers.openai.com/api/docs/guides/realtime-translation)

37 </td>45 </td>

38 </tr>46 </tr>

39 <tr>47 <tr>

40 <td>Transcribe live audio into streaming text</td>48 <td>Transcribe live audio into streaming text</td>

41 <td className="whitespace-nowrap">49 <td className="whitespace-nowrap">

42 [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper)50 [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe)

43 </td>51 </td>

44 <td>52 <td>

45 <a href="/api/docs/guides/realtime-transcription">53 [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription)

46 Realtime transcription

47 </a>

48 </td>54 </td>

49 </tr>55 </tr>

50 <tr>56 <tr>

51 <td>Transcribe files or bounded audio requests</td>57 <td>Transcribe files or bounded audio requests</td>

52 <td>Audio transcription models</td>58 <td>Audio transcription models</td>

53 <td>59 <td>

54 <a href="/api/docs/guides/speech-to-text">Speech to text</a>60 [File transcription](https://developers.openai.com/api/docs/guides/speech-to-text)

55 </td>61 </td>

56 </tr>62 </tr>

57 <tr>63 <tr>

58 <td>Generate speech from text</td>64 <td>Generate speech from text</td>

59 <td>Speech generation models</td>65 <td>Speech generation models</td>

60 <td>66 <td>

61 <a href="/api/docs/guides/text-to-speech">Text to speech</a>67 [Text to speech](https://developers.openai.com/api/docs/guides/text-to-speech)

62 </td>68 </td>

63 </tr>69 </tr>

64 <tr>70 <tr>

65 <td>Add audio to an existing Chat Completions app</td>71 <td>Add audio to an existing Chat Completions app</td>

66 <td>Audio-capable chat models</td>72 <td>Audio-capable chat models</td>

67 <td>73 <td>

68 <a href="/api/docs/guides/audio#add-audio-to-your-existing-application">74 [Audio and speech](https://developers.openai.com/api/docs/guides/audio#add-audio-to-your-existing-application)

69 Audio and speech

70 </a>

71 </td>75 </td>

72 </tr>76 </tr>

73 </tbody>77 </tbody>


93 conversation state.97 conversation state.

94 </td>98 </td>

95 <td>99 <td>

96 Conversation session on <code>/v1/realtime</code>100 Conversation session on `/v1/realtime`

97 </td>101 </td>

98 </tr>102 </tr>

99 <tr>103 <tr>

100 <td>Translation session</td>104 <td>Translation session</td>

101 <td>The app should continuously translate speech as it arrives.</td>105 <td>The app should continuously translate speech as it arrives.</td>

102 <td>106 <td>

103 Continuous translation session on <code>/v1/realtime/translations</code>107 Continuous translation session on `/v1/realtime/translations`

104 </td>108 </td>

105 </tr>109 </tr>

106 <tr>110 <tr>


138 142 

139### Transcription sessions143### Transcription sessions

140 144 

141You can transcribe audio in more than one way. Use a realtime transcription session when your application needs live transcript deltas from streaming audio. Use the [Speech to text](https://developers.openai.com/api/docs/guides/speech-to-text) guide for file uploads, request-based transcription, or diarization-focused workflows.145You can transcribe audio in more than one way. Use a realtime transcription session when your application needs live transcript deltas from streaming audio. Use the [File transcription](https://developers.openai.com/api/docs/guides/speech-to-text) guide for file uploads, request-based transcription, translation, or speaker-labeling workflows.

142 146 

143For realtime transcription, [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper) gives you controllable latency. Lower delay settings produce earlier partial text, while higher delay settings can improve transcript quality. Test with your real audio conditions, target languages, accents, and domain vocabulary before choosing a production default.147For realtime transcription, [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe) gives you controllable latency. Lower delay settings produce earlier partial text, while higher delay settings can improve transcript quality. Test with your real audio conditions, target languages, accents, and domain vocabulary before choosing a production default.

144 148 

145See [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) for session configuration and event handling.149See [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) for session configuration and event handling.

146 150 


148 152 

149Choose the transport based on where your application captures and plays audio:153Choose the transport based on where your application captures and plays audio:

150 154 

151[155[WebRTC

152 156 

153<span slot="icon">

154 </span>

155 Use for browser and mobile clients that capture or play audio directly.

156 157 

157](https://developers.openai.com/api/docs/guides/realtime-webrtc)

158 158 

159[159 Use for browser and mobile clients that capture or play audio directly.](https://developers.openai.com/api/docs/guides/realtime-webrtc)

160 

161[WebSocket

162 

163 

160 164 

161<span slot="icon">

162 </span>

163 Use when your server already receives raw audio from a media pipeline, call165 Use when your server already receives raw audio from a media pipeline, call

164 system, or worker.166 system, or worker.](https://developers.openai.com/api/docs/guides/realtime-websocket)

165 167 

166](https://developers.openai.com/api/docs/guides/realtime-websocket)168[SIP

167 169 

168[

169 170 

170<span slot="icon">

171 </span>

172 Use for telephony voice agents. Confirm model support before using SIP for

173 translation or transcription.

174 171 

175](https://developers.openai.com/api/docs/guides/realtime-sip)172 Use for telephony voice agents. Confirm model support before using SIP for

173 translation or transcription.](https://developers.openai.com/api/docs/guides/realtime-sip)

176 174 

177## Safety identifiers175## Safety identifiers

178 176 

179If your application identifies individual end users, include a [safety identifier](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers) with Realtime API requests. Safety identifiers are recommended but not required. They help OpenAI monitor and detect abuse while allowing enforcement to target an individual user rather than your entire organization. Use a stable, privacy-preserving value, such as a hashed internal user ID.177If your application identifies individual end users, include a [safety identifier](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers) with Realtime API requests. OpenAI recommends safety identifiers but doesn't require them. They help OpenAI detect harmful behavior and target enforcement to an individual user rather than your entire organization. Use a stable, privacy-preserving value, such as a hashed internal user ID.

180 178 

181For Realtime API requests, send the identifier in the `OpenAI-Safety-Identifier` header. When using ephemeral tokens, set the header on the server-side request that creates the client secret so the identifier is bound to that session. When connecting from a trusted server with WebSocket or the unified WebRTC interface, set the header on the connection request.179For Realtime API requests, send the identifier in the `OpenAI-Safety-Identifier` header. When using ephemeral tokens, set the header on the server-side request that creates the client secret to associate the identifier with the session. When connecting from a trusted server with WebSocket or the unified WebRTC interface, set the header on the connection request.

182 180 

183Safety identifiers do not carry over from Responses API requests or from other sessions. If you use the Responses API `safety_identifier` parameter elsewhere in your application, pass the same stable value separately when you create or connect each Realtime session.181Safety identifiers don't carry over from Responses API requests or other sessions. If you use the Responses API `safety_identifier` parameter elsewhere in your application, pass the same stable value when you create or connect each Realtime session.

184 182 

185## Beta to GA migration183## Beta to GA migration

186 184 

187If you still have a beta Realtime integration, migrate it to the GA interface before moving forward with new work. The most important changes are:185If you still have a beta Realtime integration, migrate it to the GA interface before moving forward with new work. The most important changes are:

188 186 

189- Remove the `OpenAI-Beta: realtime=v1` header when calling the GA interface.187- Remove the `OpenAI-Beta: realtime=v1` header when calling the GA interface.

190- Use [`POST /v1/realtime/client_secrets`](https://developers.openai.com/api/docs/api-reference/realtime-sessions/create-realtime-client-secret) to create ephemeral credentials for browser or mobile clients.188- Use [`POST /v1/realtime/client_secrets`](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets/methods/create) to create ephemeral credentials for browser or mobile clients.

191- Use `/v1/realtime/calls` when establishing WebRTC sessions.189- Use `/v1/realtime/calls` when establishing WebRTC sessions.

192- Update session and event shapes for the GA interface. In particular, set `session.type`, move output audio configuration under `session.audio.output`, and use the newer response event names like `response.output_text.delta`, `response.output_audio.delta`, and `response.output_audio_transcript.delta`.190- Update session and event shapes for the GA interface. In particular, set `session.type`, move output audio configuration under `session.audio.output`, and use the newer response event names like `response.output_text.delta`, `response.output_audio.delta`, and `response.output_audio_transcript.delta`.

193- If you are moving a speech-to-speech app forward, start from the [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents) guide. If you are moving a transcription workflow forward, use [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription).191- If you are moving a speech-to-speech app forward, start from the [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents) guide. If you are moving a transcription workflow forward, use [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription).

194 192 

195See the [Realtime client events reference](https://developers.openai.com/api/docs/api-reference/realtime_client_events), [Realtime sessions reference](https://developers.openai.com/api/docs/api-reference/realtime-sessions), and [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents) guide for the current GA flow.193See the [Realtime client events reference](https://developers.openai.com/api/reference/resources/realtime/client-events), [Realtime sessions reference](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets), and [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents) guide for the current GA flow.

196 194 

197## Related guides195## Related guides

198 196 

Details

1# Realtime conversations1# Realtime conversations

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.

4 

3Once you have connected to the Realtime API through either [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) or [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket), you can call a Realtime model (such as [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1)) to have speech-to-speech conversations. Doing so will require you to **send client events** to initiate actions, and **listen for server events** to respond to actions taken by the Realtime API.5Once you have connected to the Realtime API through either [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) or [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket), you can call a Realtime model (such as [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1)) to have speech-to-speech conversations. Doing so will require you to **send client events** to initiate actions, and **listen for server events** to respond to actions taken by the Realtime API.

4 6 

5This guide will walk through the event flows required to use model capabilities like audio and text generation, image input, and function calling, and how to think about the state of a Realtime Session.7This guide will walk through the event flows required to use model capabilities like audio and text generation, image input, and function calling, and how to think about the state of a Realtime Session.


20 22 

21If you are using WebRTC, much of the media handling required to send and receive audio from the model is assisted by WebRTC APIs.23If you are using WebRTC, much of the media handling required to send and receive audio from the model is assisted by WebRTC APIs.

22 24 

23<br/>25 

26 

24If you are using WebSockets for audio, you will need to manually interact with the **input audio buffer** by sending audio to the server, sent with JSON events with base64-encoded audio.27If you are using WebSockets for audio, you will need to manually interact with the **input audio buffer** by sending audio to the server, sent with JSON events with base64-encoded audio.

25 28 

26All these components together make up a Realtime Session. You will use client events to update the state of the session, and listen for server events to react to state changes within the session.29All these components together make up a Realtime Session. You will use client events to update the state of the session, and listen for server events to react to state changes within the session.


29 32 

30## Session lifecycle events33## Session lifecycle events

31 34 

32After initiating a session via either [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) or [WebSockets](https://developers.openai.com/api/docs/guides/realtime-websockets), the server will send a [`session.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/created) event indicating the session is ready. On the client, you can update the current session configuration with the [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) event. Most session properties can be updated at any time, except for the `voice` the model uses for audio output, after the model has responded with audio once during the session. The maximum duration of a Realtime session is **60 minutes**.35After initiating a session via either [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) or [WebSockets](https://developers.openai.com/api/docs/guides/realtime-websocket), the server will send a [`session.created`](https://developers.openai.com/api/reference/resources/realtime) event indicating the session is ready. On the client, you can update the current session configuration with the [`session.update`](https://developers.openai.com/api/reference/resources/realtime) event. Most session properties can be updated at any time, except for the `voice` the model uses for audio output, after the model has responded with audio once during the session. The maximum duration of a Realtime session is **60 minutes**.

33 36 

34The following example shows updating the session with a `session.update` client event. See the [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc#sending-and-receiving-events) or [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket#sending-and-receiving-events) guide for more on sending client events over these channels.37The following example shows updating the session with a `session.update` client event. See the [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc#sending-and-receiving-events) or [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket#sending-and-receiving-events) guide for more on sending client events over these channels.

35 38 


117```120```

118 121 

119 122 

120When the session has been updated, the server will emit a [`session.updated`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/updated) event with the new state of the session.123When the session has been updated, the server will emit a [`session.updated`](https://developers.openai.com/api/reference/resources/realtime) event with the new state of the session.

121 124 

122<table>125<table>

123 <tr>126 <tr>


126 </tr>129 </tr>

127 <tr>130 <tr>

128 <td>131 <td>

129 [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)132 [`session.update`](https://developers.openai.com/api/reference/resources/realtime)

130 </td>133 </td>

131 <td>134 <td>

132 [`session.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/created)135 [`session.created`](https://developers.openai.com/api/reference/resources/realtime)

133 <div />136

134 [`session.updated`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/updated)137 

138 [`session.updated`](https://developers.openai.com/api/reference/resources/realtime)

135 </td>139 </td>

136 </tr>140 </tr>

137</table>141</table>

138 142 

139## Text inputs and outputs143## Text inputs and outputs

140 144 

141To generate text with a Realtime model, you can add text inputs to the current conversation, ask the model to generate a response, and listen for server-sent events indicating the progress of the model's response. In order to generate text, the [session must be configured](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) with the `text` modality (this is true by default).145To generate text with a Realtime model, you can add text inputs to the current conversation, ask the model to generate a response, and listen for server-sent events indicating the progress of the model's response. In order to generate text, the [session must be configured](https://developers.openai.com/api/reference/resources/realtime) with the `text` modality (this is true by default).

142 146 

143Create a new text conversation item using the [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create) client event. This is similar to sending a [user message (prompt) in Chat Completions](https://developers.openai.com/api/docs/guides/text-generation) in the REST API.147Create a new text conversation item using the [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime) client event. This is similar to sending a [user message (prompt) in Chat Completions](https://developers.openai.com/api/docs/guides/text) in the REST API.

144 148 

145Create a conversation item with user input149Create a conversation item with user input

146 150 


181```185```

182 186 

183 187 

184After adding the user message to the conversation, send the [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) event to initiate a response from the model. If both audio and text are enabled for the current session, the model will respond with both audio and text content. If you'd like to generate text only, you can specify that when sending the `response.create` client event, as shown below.188After adding the user message to the conversation, send the [`response.create`](https://developers.openai.com/api/reference/resources/realtime) event to initiate a response from the model. If both audio and text are enabled for the current session, the model will respond with both audio and text content. If you'd like to generate text only, you can specify that when sending the `response.create` client event, as shown below.

185 189 

186Generate a text-only response190Generate a text-only response

187 191 


203```207```

204 208 

205 209 

206When the response is completely finished, the server will emit the [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done) event. This event will contain the full text generated by the model, as shown below.210When the response is completely finished, the server will emit the [`response.done`](https://developers.openai.com/api/reference/resources/realtime) event. This event will contain the full text generated by the model, as shown below.

207 211 

208Listen for response.done to see the final results212Listen for response.done to see the final results

209 213 


231```235```

232 236 

233 237 

234While the model response is being generated, the server will emit a number of lifecycle events during the process. You can listen for these events, such as [`response.output_text.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_text/delta), to provide realtime feedback to users as the response is generated. A full listing of the events emitted by there server are found below under **related server events**. They are provided in the rough order of when they are emitted, along with relevant client-side events for text generation.238While the model response is being generated, the server will emit a number of lifecycle events during the process. You can listen for these events, such as [`response.output_text.delta`](https://developers.openai.com/api/reference/resources/realtime), to provide realtime feedback to users as the response is generated. A full listing of the events emitted by there server are found below under **related server events**. They are provided in the rough order of when they are emitted, along with relevant client-side events for text generation.

235 239 

236<table>240<table>

237 <tr>241 <tr>


240 </tr>244 </tr>

241 <tr>245 <tr>

242 <td>246 <td>

243 [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create)247 [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime)

244 <div />248

245 [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create)249 

250 [`response.create`](https://developers.openai.com/api/reference/resources/realtime)

246 </td>251 </td>

247 <td>252 <td>

248 [`conversation.item.added`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/conversation/item/added)253 [`conversation.item.added`](https://developers.openai.com/api/reference/resources/realtime)

249 <div />254

250 [`conversation.item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/conversation/item/done)255 

251 <div />256 [`conversation.item.done`](https://developers.openai.com/api/reference/resources/realtime)

252 [`response.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/created)257

253 <div />258 

254 [`response.output_item.added`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/added)259 [`response.created`](https://developers.openai.com/api/reference/resources/realtime)

255 <div />260

256 [`response.content_part.added`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/content_part/added)261 

257 <div />262 [`response.output_item.added`](https://developers.openai.com/api/reference/resources/realtime)

258 [`response.output_text.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_text/delta)263

259 <div />264 

260 [`response.output_text.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_text/done)265 [`response.content_part.added`](https://developers.openai.com/api/reference/resources/realtime)

261 <div />266

262 [`response.content_part.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/content_part/done)267 

263 <div />268 [`response.output_text.delta`](https://developers.openai.com/api/reference/resources/realtime)

264 [`response.output_item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/done)269

265 <div />270 

266 [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done)271 [`response.output_text.done`](https://developers.openai.com/api/reference/resources/realtime)

267 <div />272

268 [`rate_limits.updated`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/rate_limits/updated)273 

274 [`response.content_part.done`](https://developers.openai.com/api/reference/resources/realtime)

275

276 

277 [`response.output_item.done`](https://developers.openai.com/api/reference/resources/realtime)

278

279 

280 [`response.done`](https://developers.openai.com/api/reference/resources/realtime)

281

282 

283 [`rate_limits.updated`](https://developers.openai.com/api/reference/resources/realtime/server-events#rate_limits.updated)

269 </td>284 </td>

270 </tr>285 </tr>

271</table>286</table>


311 326 

312However, WebRTC clients still receive a number of server-sent lifecycle events as audio is moving back and forth between client and server over the peer connection. Examples include:327However, WebRTC clients still receive a number of server-sent lifecycle events as audio is moving back and forth between client and server over the peer connection. Examples include:

313 328 

314- When input is sent over the local media track, you will receive [`input_audio_buffer.speech_started`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/input_audio_buffer/speech_started) events from the server.329- When input is sent over the local media track, you will receive [`input_audio_buffer.speech_started`](https://developers.openai.com/api/reference/resources/realtime) events from the server.

315- When local audio input stops, you'll receive the [`input_audio_buffer.speech_stopped`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/input_audio_buffer/speech_started) event.330- When local audio input stops, you'll receive the [`input_audio_buffer.speech_stopped`](https://developers.openai.com/api/reference/resources/realtime) event.

316- You'll receive [delta events for the in-progress audio transcript](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio_transcript/delta).331- You'll receive [delta events for the in-progress audio transcript](https://developers.openai.com/api/reference/resources/realtime).

317- You'll receive a [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done) event when the model has transcribed and completed sending a response.332- You'll receive a [`response.done`](https://developers.openai.com/api/reference/resources/realtime) event when the model has transcribed and completed sending a response.

318 333 

319Manipulating WebRTC APIs for media streams may give you all the control you need. However, it may occasionally be necessary to use lower-level interfaces for audio input and output. Refer to the WebSockets section below for more information and a listing of events required for granular audio input handling.334Manipulating WebRTC APIs for media streams may give you all the control you need. However, it may occasionally be necessary to use lower-level interfaces for audio input and output. Refer to the WebSockets section below for more information and a listing of events required for granular audio input handling.

320 335 


333 <tr>348 <tr>

334 <td>Session initialization</td>349 <td>Session initialization</td>

335 <td>350 <td>

336 [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)351 [`session.update`](https://developers.openai.com/api/reference/resources/realtime)

337 </td>352 </td>

338 <td>353 <td>

339 [`session.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/created)354 [`session.created`](https://developers.openai.com/api/reference/resources/realtime)

340 <div />355

341 [`session.updated`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/session/updated)356 

357 [`session.updated`](https://developers.openai.com/api/reference/resources/realtime)

342 </td>358 </td>

343 </tr>359 </tr>

344 <tr>360 <tr>

345 <td>User audio input</td>361 <td>User audio input</td>

346 <td>362 <td>

347 [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create)363 [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime)

348 <br />364

365 

349 &nbsp;&nbsp;(send whole audio message)366 &nbsp;&nbsp;(send whole audio message)

350 <div />367

351 [`input_audio_buffer.append`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/append)368 

352 <br />369 [`input_audio_buffer.append`](https://developers.openai.com/api/reference/resources/realtime)

370

371 

353 &nbsp;&nbsp;(stream audio in chunks)372 &nbsp;&nbsp;(stream audio in chunks)

354 <div />373

355 [`input_audio_buffer.commit`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/commit)374 

356 <br />375 [`input_audio_buffer.commit`](https://developers.openai.com/api/reference/resources/realtime)

376

377 

357 &nbsp;&nbsp;(used when VAD is disabled)378 &nbsp;&nbsp;(used when VAD is disabled)

358 <div />379

359 [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create)380 

360 <br />381 [`response.create`](https://developers.openai.com/api/reference/resources/realtime)

382

383 

361 &nbsp;&nbsp;(used when VAD is disabled)384 &nbsp;&nbsp;(used when VAD is disabled)

362 </td>385 </td>

363 <td>386 <td>

364 [`input_audio_buffer.speech_started`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/input_audio_buffer/speech_started)387 [`input_audio_buffer.speech_started`](https://developers.openai.com/api/reference/resources/realtime)

365 <div />388

366 [`input_audio_buffer.speech_stopped`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/input_audio_buffer/speech_stopped)389 

367 <div />390 [`input_audio_buffer.speech_stopped`](https://developers.openai.com/api/reference/resources/realtime)

368 [`input_audio_buffer.committed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/input_audio_buffer/committed)391

392 

393 [`input_audio_buffer.committed`](https://developers.openai.com/api/reference/resources/realtime)

369 </td>394 </td>

370 </tr>395 </tr>

371 <tr>396 <tr>

372 <td>Server audio output</td>397 <td>Server audio output</td>

373 <td>398 <td>

374 [`input_audio_buffer.clear`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/clear)399 [`input_audio_buffer.clear`](https://developers.openai.com/api/reference/resources/realtime)

375 <br />400

401 

376 &nbsp;&nbsp;(used when VAD is disabled)402 &nbsp;&nbsp;(used when VAD is disabled)

377 </td>403 </td>

378 <td>404 <td>

379 [`conversation.item.added`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/conversation/item/added)405 [`conversation.item.added`](https://developers.openai.com/api/reference/resources/realtime)

380 <div />406

381 [`conversation.item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/conversation/item/done)407 

382 <div />408 [`conversation.item.done`](https://developers.openai.com/api/reference/resources/realtime)

383 [`response.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/created)409

384 <div />410 

385 [`response.output_item.created`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/created)411 [`response.created`](https://developers.openai.com/api/reference/resources/realtime)

386 <div />412

387 [`response.content_part.added`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/content_part/added)413 

388 <div />414 [`response.output_item.added`](https://developers.openai.com/api/reference/resources/realtime/server-events#response.output_item.added)

389 [`response.output_audio.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio/delta)415

390 <div />416 

391 [`response.output_audio.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio/done)417 [`response.content_part.added`](https://developers.openai.com/api/reference/resources/realtime)

392 <div />418

393 [`response.output_audio_transcript.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio_transcript/delta)419 

394 <div />420 [`response.output_audio.delta`](https://developers.openai.com/api/reference/resources/realtime)

395 [`response.output_audio_transcript.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio_transcript/done)421

396 <div />422 

397 [`response.output_text.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_text/delta)423 [`response.output_audio.done`](https://developers.openai.com/api/reference/resources/realtime)

398 <div />424

399 [`response.output_text.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_text/done)425 

400 <div />426 [`response.output_audio_transcript.delta`](https://developers.openai.com/api/reference/resources/realtime)

401 [`response.content_part.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/content_part/done)427

402 <div />428 

403 [`response.output_item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/done)429 [`response.output_audio_transcript.done`](https://developers.openai.com/api/reference/resources/realtime)

404 <div />430

405 [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done)431 

406 <div />432 [`response.output_text.delta`](https://developers.openai.com/api/reference/resources/realtime)

407 [`rate_limits.updated`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/rate_limits/updated)433

434 

435 [`response.output_text.done`](https://developers.openai.com/api/reference/resources/realtime)

436

437 

438 [`response.content_part.done`](https://developers.openai.com/api/reference/resources/realtime)

439

440 

441 [`response.output_item.done`](https://developers.openai.com/api/reference/resources/realtime)

442

443 

444 [`response.done`](https://developers.openai.com/api/reference/resources/realtime)

445

446 

447 [`rate_limits.updated`](https://developers.openai.com/api/reference/resources/realtime)

408 </td>448 </td>

409 </tr>449 </tr>

410</table>450</table>

411 451 

412### Streaming audio input to the server452### Streaming audio input to the server

413 453 

414To stream audio input to the server, you can use the [`input_audio_buffer.append`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/append) client event. This event requires you to send chunks of **Base64-encoded audio bytes** to the Realtime API over the socket. Each chunk cannot exceed 15 MB in size.454To stream audio input to the server, you can use the [`input_audio_buffer.append`](https://developers.openai.com/api/reference/resources/realtime) client event. This event requires you to send chunks of **Base64-encoded audio bytes** to the Realtime API over the socket. Each chunk cannot exceed 15 MB in size.

415 455 

416The format of the input chunks can be configured either for the entire session, or per response.456The format of the input chunks can be configured either for the entire session, or per response.

417 457 

418- Session: `session.input_audio_format` in [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)458- Session: `session.input_audio_format` in [`session.update`](https://developers.openai.com/api/reference/resources/realtime)

419- Response: `response.input_audio_format` in [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create)459- Response: `response.input_audio_format` in [`response.create`](https://developers.openai.com/api/reference/resources/realtime)

420 460 

421Append audio input bytes to the conversation461Append audio input bytes to the conversation

422 462 


511 551 

512### Send full audio messages552### Send full audio messages

513 553 

514It is also possible to create conversation messages that are full audio recordings. Use the [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create) client event to create messages with `input_audio` content.554It is also possible to create conversation messages that are full audio recordings. Use the [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime) client event to create messages with `input_audio` content.

515 555 

516Create full audio input conversation items556Create full audio input conversation items

517 557 


561 601 

562**To play output audio back on a client device like a web browser, we recommend using WebRTC rather than WebSockets**. WebRTC will be more robust sending media to client devices over uncertain network conditions.602**To play output audio back on a client device like a web browser, we recommend using WebRTC rather than WebSockets**. WebRTC will be more robust sending media to client devices over uncertain network conditions.

563 603 

564But to work with audio output in server-to-server applications using a WebSocket, you will need to listen for [`response.output_audio.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio/delta) events containing the Base64-encoded chunks of audio data from the model. You will either need to buffer these chunks and write them out to a file, or maybe immediately stream them to another source like [a phone call with Twilio](https://www.twilio.com/en-us/blog/twilio-openai-realtime-api-launch-integration).604But to work with audio output in server-to-server applications using a WebSocket, you will need to listen for [`response.output_audio.delta`](https://developers.openai.com/api/reference/resources/realtime) events containing the Base64-encoded chunks of audio data from the model. You will either need to buffer these chunks and write them out to a file, or maybe immediately stream them to another source like [a phone call with Twilio](https://www.twilio.com/en-us/blog/twilio-openai-realtime-api-launch-integration).

565 605 

566Note that the [`response.output_audio.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio/done) and [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done) events won't actually contain audio data in them - just audio content transcriptions. To get the actual bytes, you'll need to listen for the [`response.output_audio.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_audio/delta) events.606Note that the [`response.output_audio.done`](https://developers.openai.com/api/reference/resources/realtime) and [`response.done`](https://developers.openai.com/api/reference/resources/realtime) events won't actually contain audio data in them - just audio content transcriptions. To get the actual bytes, you'll need to listen for the [`response.output_audio.delta`](https://developers.openai.com/api/reference/resources/realtime) events.

567 607 

568The format of the output chunks can be configured either for the entire session, or per response.608The format of the output chunks can be configured either for the entire session, or per response.

569 609 

570- Session: `session.audio.output.format` in [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)610- Session: `session.audio.output.format` in [`session.update`](https://developers.openai.com/api/reference/resources/realtime)

571- Response: `response.audio.output.format` in [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create)611- Response: `response.audio.output.format` in [`response.create`](https://developers.openai.com/api/reference/resources/realtime)

572 612 

573Listen for response.output_audio.delta events613Listen for response.output_audio.delta events

574 614 


630 670 

631### Disable VAD671### Disable VAD

632 672 

633VAD can be disabled by setting `turn_detection` to `null` with the [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) client event. This can be useful for interfaces where you would like to take granular control over audio input, like [push to talk](https://en.wikipedia.org/wiki/Push-to-talk) interfaces.673VAD can be disabled by setting `turn_detection` to `null` with the [`session.update`](https://developers.openai.com/api/reference/resources/realtime) client event. This can be useful for interfaces where you would like to take granular control over audio input, like [push to talk](https://en.wikipedia.org/wiki/Push-to-talk) interfaces.

634 674 

635When VAD is disabled, the client will have to manually emit some additional client events to trigger audio responses:675When VAD is disabled, the client will have to manually emit some additional client events to trigger audio responses:

636 676 

637- Manually send [`input_audio_buffer.commit`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/commit), which will create a new user input item for the conversation.677- Manually send [`input_audio_buffer.commit`](https://developers.openai.com/api/reference/resources/realtime), which will create a new user input item for the conversation.

638- Manually send [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) to trigger an audio response from the model.678- Manually send [`response.create`](https://developers.openai.com/api/reference/resources/realtime) to trigger an audio response from the model.

639- Send [`input_audio_buffer.clear`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/clear) before beginning a new user input.679- Send [`input_audio_buffer.clear`](https://developers.openai.com/api/reference/resources/realtime) before beginning a new user input.

640 680 

641### Keep VAD, but disable automatic responses681### Keep VAD, but disable automatic responses

642 682 

643If you would like to keep VAD mode enabled, but would just like to retain the ability to manually decide when a response is generated, you can set `turn_detection.interrupt_response` and `turn_detection.create_response` to `false` with the [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) client event. This will retain all the behavior of VAD but not automatically create new Responses. Clients can trigger these manually with a [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) event.683If you would like to keep VAD mode enabled, but would just like to retain the ability to manually decide when a response is generated, you can set `turn_detection.interrupt_response` and `turn_detection.create_response` to `false` with the [`session.update`](https://developers.openai.com/api/reference/resources/realtime) client event. This will retain all the behavior of VAD but not automatically create new Responses. Clients can trigger these manually with a [`response.create`](https://developers.openai.com/api/reference/resources/realtime) event.

644 684 

645This can be useful for moderation or input validation or RAG patterns, where you're comfortable trading a bit more latency in the interaction for control over inputs.685This can be useful for moderation or input validation or RAG patterns, where you're comfortable trading a bit more latency in the interaction for control over inputs.

646 686 


648 688 

649By default, all responses generated during a session are added to the session's conversation state (the "default conversation"). However, you may want to generate model responses outside the context of the session's default conversation, or have multiple responses generated concurrently. You might also want to have more granular control over which conversation items are considered while the model generates a response (e.g. only the last N number of turns).689By default, all responses generated during a session are added to the session's conversation state (the "default conversation"). However, you may want to generate model responses outside the context of the session's default conversation, or have multiple responses generated concurrently. You might also want to have more granular control over which conversation items are considered while the model generates a response (e.g. only the last N number of turns).

650 690 

651Generating "out-of-band" responses which are not added to the default conversation state is possible by setting the `response.conversation` field to the string `none` when creating a response with the [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) client event.691Generating "out-of-band" responses which are not added to the default conversation state is possible by setting the `response.conversation` field to the string `none` when creating a response with the [`response.create`](https://developers.openai.com/api/reference/resources/realtime) client event.

652 692 

653When creating an out-of-band response, you will probably also want some way to identify which server-sent events pertain to this response. You can provide `metadata` for your model response that will help you identify which response is being generated for this client-sent event.693When creating an out-of-band response, you will probably also want some way to identify which server-sent events pertain to this response. You can provide `metadata` for your model response that will help you identify which response is being generated for this client-sent event.

654 694 


704```744```

705 745 

706 746 

707Now, when you listen for the [`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done) server event, you can identify the result of your out-of-band response.747Now, when you listen for the [`response.done`](https://developers.openai.com/api/reference/resources/realtime) server event, you can identify the result of your out-of-band response.

708 748 

709Create an out-of-band model response749Create an out-of-band model response

710 750 


747 787 

748### Create a custom context for responses788### Create a custom context for responses

749 789 

750You can also construct a custom context that the model will use to generate a response, outside the default/current conversation. This can be done using the `input` array on a [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) client event. You can use new inputs, or reference existing input items in the conversation by ID.790You can also construct a custom context that the model will use to generate a response, outside the default/current conversation. This can be done using the `input` array on a [`response.create`](https://developers.openai.com/api/reference/resources/realtime) client event. You can use new inputs, or reference existing input items in the conversation by ID.

751 791 

752Listen for out-of-band model response with custom context792Listen for out-of-band model response with custom context

753 793 


866 906 

867The Realtime models also support **function calling**, which enables you to execute custom code to extend the capabilities of the model. Here's how it works at a high level:907The Realtime models also support **function calling**, which enables you to execute custom code to extend the capabilities of the model. Here's how it works at a high level:

868 908 

8691. When [updating the session](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) or [creating a response](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create), you can specify a list of available functions for the model to call.9091. When [updating the session](https://developers.openai.com/api/reference/resources/realtime) or [creating a response](https://developers.openai.com/api/reference/resources/realtime), you can specify a list of available functions for the model to call.

8701. If when processing input, the model determines it should make a function call, it will add items to the conversation representing arguments to a function call.9101. If when processing input, the model determines it should make a function call, it will add items to the conversation representing arguments to a function call.

8711. When the client detects conversation items that contain function call arguments, it will execute custom code using those arguments9111. When the client detects conversation items that contain function call arguments, it will execute custom code using those arguments

8721. When the custom code has been executed, the client will create new conversation items that contain the output of the function call, and ask the model to respond.9121. When the custom code has been executed, the client will create new conversation items that contain the output of the function call, and ask the model to respond.


877 917 

878First, we must give the model a selection of functions it can call based on user input. Available functions can be configured either at the session level, or the individual response level.918First, we must give the model a selection of functions it can call based on user input. Available functions can be configured either at the session level, or the individual response level.

879 919 

880- Session: `session.tools` property in [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)920- Session: `session.tools` property in [`session.update`](https://developers.openai.com/api/reference/resources/realtime)

881- Response: `response.tools` property in [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create)921- Response: `response.tools` property in [`response.create`](https://developers.openai.com/api/reference/resources/realtime)

882 922 

883Here's an example client event payload for a `session.update` that configures a horoscope generation function, that takes a single argument (the astrological sign for which the horoscope should be generated):923Here's an example client event payload for a `session.update` that configures a horoscope generation function, that takes a single argument (the astrological sign for which the horoscope should be generated):

884 924 

885[`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update)925[`session.update`](https://developers.openai.com/api/reference/resources/realtime)

886 926 

887```json927```json

888{928{


928 968 

929### Detect when the model wants to call a function969### Detect when the model wants to call a function

930 970 

931Based on inputs to the model, the model may decide to call a function in order to generate the best response. Let's say our application adds the following conversation item with a [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create) event and then creates a response:971Based on inputs to the model, the model may decide to call a function in order to generate the best response. Let's say our application adds the following conversation item with a [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime) event and then creates a response:

932 972 

933```json973```json

934{974{


946}986}

947```987```

948 988 

949Followed by a [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) client event to generate a response:989Followed by a [`response.create`](https://developers.openai.com/api/reference/resources/realtime) client event to generate a response:

950 990 

951```json991```json

952{992{


954}994}

955```995```

956 996 

957Instead of immediately returning a text or audio response, the model will instead generate a response that contains the arguments that should be passed to a function in the developer's application. You can listen for realtime updates to function call arguments using the [`response.function_call_arguments.delta`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/function_call_arguments/delta) server event, but `response.done` will also have the complete data we need to call our function.997Instead of immediately returning a text or audio response, the model will instead generate a response that contains the arguments that should be passed to a function in the developer's application. You can listen for realtime updates to function call arguments using the [`response.function_call_arguments.delta`](https://developers.openai.com/api/reference/resources/realtime) server event, but `response.done` will also have the complete data we need to call our function.

958 998 

959[`response.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/done)999[`response.done`](https://developers.openai.com/api/reference/resources/realtime)

960 1000 

961```json1001```json

962{1002{


998 1038 

999Upon receiving a response from the model with arguments to a function call, your application can execute code that satisfies the function call. This could be anything you want, like talking to external APIs or accessing databases.1039Upon receiving a response from the model with arguments to a function call, your application can execute code that satisfies the function call. This could be anything you want, like talking to external APIs or accessing databases.

1000 1040 

1001Once you are ready to give the model the results of your custom code, you can create a new conversation item containing the result via the [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create) client event.1041Once you are ready to give the model the results of your custom code, you can create a new conversation item containing the result via the [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime) client event.

1002 1042 

1003```json1043```json

1004{1044{


1015- `item.call_id` is the same ID we got back in the `response.done` event above1055- `item.call_id` is the same ID we got back in the `response.done` event above

1016- `item.output` is a JSON string containing the results of our function call1056- `item.output` is a JSON string containing the results of our function call

1017 1057 

1018Once we have added the conversation item containing our function call results, we again emit the [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) event from the client. This will trigger a model response using the data from the function call.1058Once we have added the conversation item containing our function call results, we again emit the [`response.create`](https://developers.openai.com/api/reference/resources/realtime) event from the client. This will trigger a model response using the data from the function call.

1019 1059 

1020```json1060```json

1021{1061{


1025 1065 

1026## Error handling1066## Error handling

1027 1067 

1028The [`error`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/error) event is emitted by the server whenever an error condition is encountered on the server during the session. Occasionally, these errors can be traced to a client event that was emitted by your application.1068The [`error`](https://developers.openai.com/api/reference/resources/realtime) event is emitted by the server whenever an error condition is encountered on the server during the session. Occasionally, these errors can be traced to a client event that was emitted by your application.

1029 1069 

1030Unlike HTTP requests and responses, where a response is implicitly tied to a request from the client, we need to use an `event_id` property on client events to know when one of them has triggered an error condition on the server. This technique is shown in the code below, where the client attempts to emit an unsupported event type.1070Unlike HTTP requests and responses, where a response is implicitly tied to a request from the client, we need to use an `event_id` property on client events to know when one of them has triggered an error condition on the server. This technique is shown in the code below, where the client attempts to emit an unsupported event type.

1031 1071 


1061 1101 

10621. The client monitors for new `input_audio_buffer.speech_started` events from the server, which indicate the user has started speaking. The server will automatically cancel any in-progress model response and a `response.cancelled` event will be emitted.11021. The client monitors for new `input_audio_buffer.speech_started` events from the server, which indicate the user has started speaking. The server will automatically cancel any in-progress model response and a `response.cancelled` event will be emitted.

10631. When the client detects this event, it should immediately stop playback of any audio currently being played from the model. It should note how much of the last audio response was played before the interruption.11031. When the client detects this event, it should immediately stop playback of any audio currently being played from the model. It should note how much of the last audio response was played before the interruption.

10641. The client should send a [`conversation.item.truncate`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/truncate) event to remove the unplayed portion of the model's last response from the conversation.11041. The client should send a [`conversation.item.truncate`](https://developers.openai.com/api/reference/resources/realtime) event to remove the unplayed portion of the model's last response from the conversation.

1065 1105 

1066Here's an example:1106Here's an example:

1067 1107 


1086 1126 

1087To implement push-to-talk with a WebSocket connection, you'll want the client to stop audio playback, handle interruptions, and kick off a new response. Here's a more detailed procedure:1127To implement push-to-talk with a WebSocket connection, you'll want the client to stop audio playback, handle interruptions, and kick off a new response. Here's a more detailed procedure:

1088 1128 

10891. Turn VAD off by setting `"turn_detection": null` in a [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) event.11291. Turn VAD off by setting `"turn_detection": null` in a [`session.update`](https://developers.openai.com/api/reference/resources/realtime) event.

10901. On push down, start recording audio on the client.11301. On push down, start recording audio on the client.

1091 1. If there is an in-progress response from the model, cancel it by sending a [`response.cancel`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/cancel) event.1131 1. If there is an in-progress response from the model, cancel it by sending a [`response.cancel`](https://developers.openai.com/api/reference/resources/realtime) event.

1092 1. If there is is ongoing output playback from the model, stop playback immediately and send an `conversation.item.truncate` event to remove any unplayed audio from the conversation.1132 1. If there is is ongoing output playback from the model, stop playback immediately and send an `conversation.item.truncate` event to remove any unplayed audio from the conversation.

10931. On up, send an [`input_audio_buffer.append`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/append) message with the audio to place new audio into the input buffer.11331. On up, send an [`input_audio_buffer.append`](https://developers.openai.com/api/reference/resources/realtime) message with the audio to place new audio into the input buffer.

10941. Send an [`input_audio_buffer.commit`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/commit) event, this will commit the audio written to the input buffer and kick off input transcription (if enabled).11341. Send an [`input_audio_buffer.commit`](https://developers.openai.com/api/reference/resources/realtime) event, this will commit the audio written to the input buffer and kick off input transcription (if enabled).

10951. Then trigger a response with a [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) event.11351. Then trigger a response with a [`response.create`](https://developers.openai.com/api/reference/resources/realtime) event.

1096 1136 

1097### WebRTC and SIP1137### WebRTC and SIP

1098 1138 

1099Implementing push-to-talk with WebRTC is similar but the input audio buffer must be explicitly cleared. Here's a procedure:1139Implementing push-to-talk with WebRTC is similar but the input audio buffer must be explicitly cleared. Here's a procedure:

1100 1140 

11011. Turn VAD off by setting `"turn_detection": null` in a [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) event.11411. Turn VAD off by setting `"turn_detection": null` in a [`session.update`](https://developers.openai.com/api/reference/resources/realtime) event.

11021. On push down, send an [`input_audio_buffer.clear`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/clear) event to clear any previous audio input.11421. On push down, send an [`input_audio_buffer.clear`](https://developers.openai.com/api/reference/resources/realtime) event to clear any previous audio input.

1103 1. If there is an in-progress response from the model, cancel it by sending a [`response.cancel`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/cancel) event.1143 1. If there is an in-progress response from the model, cancel it by sending a [`response.cancel`](https://developers.openai.com/api/reference/resources/realtime) event.

1104 1. If there is is ongoing output playback from the model, send an [`output_audio_buffer.clear`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/output_audio_buffer/clear) event to clear out the unplayed audio, this truncates the conversation as well.1144 1. If there is is ongoing output playback from the model, send an [`output_audio_buffer.clear`](https://developers.openai.com/api/reference/resources/realtime) event to clear out the unplayed audio, this truncates the conversation as well.

11051. On up, send an [`input_audio_buffer.commit`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/input_audio_buffer/commit) event, this will commit the audio written to the input buffer and kick off input transcription (if enabled).11451. On up, send an [`input_audio_buffer.commit`](https://developers.openai.com/api/reference/resources/realtime) event, this will commit the audio written to the input buffer and kick off input transcription (if enabled).

11061. Then trigger a response with a [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create) event.11461. Then trigger a response with a [`response.create`](https://developers.openai.com/api/reference/resources/realtime) event.

Details

1# Managing costs1# Managing costs

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.

4 

3This document describes how Realtime API billing works and offers strategies for optimizing costs. Voice-agent sessions accrue input and output tokens across text, audio, and image modalities. Streaming translation and streaming transcription sessions are billed by audio duration. Prices vary per model, with prices listed on the model pages (for example, [`gpt-realtime-2`](https://developers.openai.com/api/docs/models/gpt-realtime-2), [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate), [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper), and [`gpt-realtime`](https://developers.openai.com/api/docs/models/gpt-realtime)).5This document describes how Realtime API billing works and offers strategies for optimizing costs. Voice-agent sessions accrue input and output tokens across text, audio, and image modalities. Streaming translation and streaming transcription sessions are billed by audio duration. Prices vary per model, with prices listed on the model pages (for example, [`gpt-realtime-2`](https://developers.openai.com/api/docs/models/gpt-realtime-2), [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate), [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper), and [`gpt-realtime`](https://developers.openai.com/api/docs/models/gpt-realtime)).

4 6 

5Conversational Realtime API sessions are a series of _turns_, where the user adds input that triggers a _Response_ to produce the model output. The server maintains a _Conversation_, which is a list of _Items_ that form the input for the next turn. When a Response is returned, the output is automatically added to the Conversation.7Conversational Realtime API sessions are a series of _turns_, where the user adds input that triggers a _Response_ to produce the model output. The server maintains a _Conversation_, which is a list of _Items_ that form the input for the next turn. When a Response is returned, the output is automatically added to the Conversation.

Details

1# Realtime with tools1# Realtime with tools

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.

4 

3You can attach tools to a Realtime session so the model can look up data, take actions, or call services during a live conversation. Tool configuration uses the same event surface whether your client is using a [WebRTC data channel](https://developers.openai.com/api/docs/guides/realtime-webrtc) or a [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket).5You can attach tools to a Realtime session so the model can look up data, take actions, or call services during a live conversation. Tool configuration uses the same event surface whether your client is using a [WebRTC data channel](https://developers.openai.com/api/docs/guides/realtime-webrtc) or a [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket).

4 6 

5Use function tools when your application should execute the tool and return the result. Use MCP tools or built-in connectors when the Realtime API should connect to a remote tool server for you.7Use function tools when your application should execute the tool and return the result. Use MCP tools or built-in connectors when the Realtime API should connect to a remote tool server for you.


14 16 

15Add tools in **one of two places**:17Add tools in **one of two places**:

16 18 

17- At the **session level** with `session.tools` in [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update), if you want the tool available for the full session.19- At the **session level** with `session.tools` in [`session.update`](https://developers.openai.com/api/reference/resources/realtime), if you want the tool available for the full session.

18- At the **response level** with `response.tools` in [`response.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/response/create), if you only need the tool for one turn.20- At the **response level** with `response.tools` in [`response.create`](https://developers.openai.com/api/reference/resources/realtime), if you only need the tool for one turn.

19 21 

20## Configure a function tool22## Configure a function tool

21 23 


251 253 

252 254 

253Remote MCP servers 255Remote MCP servers

254 <strong>don't automatically receive the full conversation context</strong>,256 **don't automatically receive the full conversation context**,

255 but <strong>they can see any data the model sends in a tool call</strong>.257 but **they can see any data the model sends in a tool call**.

256 <strong>Keep the tool surface narrow</strong> with <code>allowed_tools</code>,258 **Keep the tool surface narrow** with `allowed_tools`,

257 and require approval for any action you would not auto-run.259 and require approval for any action you would not auto-run.

258 260 

259## Realtime MCP flow261## Realtime MCP flow


264 266 

2651. You send `session.update` or `response.create` with a `tools` entry whose `type` is `mcp`.2671. You send `session.update` or `response.create` with a `tools` entry whose `type` is `mcp`.

2661. The server begins importing tools and emits `mcp_list_tools.in_progress`.2681. The server begins importing tools and emits `mcp_list_tools.in_progress`.

2671. While listing is still in progress, the model can't call a tool that hasn't loaded yet. If you want to wait before starting a turn that depends on those tools, listen for [`mcp_list_tools.completed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/mcp_list_tools/completed). The [`conversation.item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/conversation/item/done) event whose `item.type` is `mcp_list_tools` shows which tool names were actually imported. If import fails, you will receive [`mcp_list_tools.failed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/mcp_list_tools/failed).2691. While listing is still in progress, the model can't call a tool that hasn't loaded yet. If you want to wait before starting a turn that depends on those tools, listen for [`mcp_list_tools.completed`](https://developers.openai.com/api/reference/resources/realtime). The [`conversation.item.done`](https://developers.openai.com/api/reference/resources/realtime) event whose `item.type` is `mcp_list_tools` shows which tool names were actually imported. If import fails, you will receive [`mcp_list_tools.failed`](https://developers.openai.com/api/reference/resources/realtime).

2681. The user speaks or sends text, and a response is created, either by your client or automatically by the session configuration.2701. The user speaks or sends text, and a response is created, either by your client or automatically by the session configuration.

2691. If the model chooses an MCP tool, you will see `response.mcp_call_arguments.delta` and `response.mcp_call_arguments.done`.2711. If the model chooses an MCP tool, you will see `response.mcp_call_arguments.delta` and `response.mcp_call_arguments.done`.

2701. **If approval is required**, the server adds a conversation item whose `item.type` is `mcp_approval_request`. Your client must answer it with an `mcp_approval_response` item.2721. **If approval is required**, the server adds a conversation item whose `item.type` is `mcp_approval_request`. Your client must answer it with an `mcp_approval_response` item.

2711. Once the tool runs, you will see `response.mcp_call.in_progress`. On success, you will later receive a [`response.output_item.done`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/done) event whose `item.type` is `mcp_call`; on failure, you will receive [`response.mcp_call.failed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/mcp_call/failed). The assistant message item and `response.done` complete the turn.2731. Once the tool runs, you will see `response.mcp_call.in_progress`. On success, you will later receive a [`response.output_item.done`](https://developers.openai.com/api/reference/resources/realtime) event whose `item.type` is `mcp_call`; on failure, you will receive [`response.mcp_call.failed`](https://developers.openai.com/api/reference/resources/realtime). The assistant message item and `response.done` complete the turn.

272 274 

273This event handler covers the main checkpoints:275This event handler covers the main checkpoints:

274 276 


426 428 

427## Common failures429## Common failures

428 430 

429- [`mcp_list_tools.failed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/mcp_list_tools/failed): the Realtime API couldn't import tools from the remote server or connector. Check `server_url` or `connector_id`, authentication, server connectivity, and any `allowed_tools` names you specified.431- [`mcp_list_tools.failed`](https://developers.openai.com/api/reference/resources/realtime): the Realtime API couldn't import tools from the remote server or connector. Check `server_url` or `connector_id`, authentication, server connectivity, and any `allowed_tools` names you specified.

430- [`response.mcp_call.failed`](https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/mcp_call/failed): the model selected a tool, but the tool call didn't complete. Inspect the event payload and the later `mcp_call` item for MCP protocol, execution, or transport errors.432- [`response.mcp_call.failed`](https://developers.openai.com/api/reference/resources/realtime): the model selected a tool, but the tool call didn't complete. Inspect the event payload and the later `mcp_call` item for MCP protocol, execution, or transport errors.

431- `mcp_approval_request` with no matching `mcp_approval_response`: the tool call can't continue until your client explicitly approves or rejects it.433- `mcp_approval_request` with no matching `mcp_approval_response`: the tool call can't continue until your client explicitly approves or rejects it.

432- A turn starts while `mcp_list_tools.in_progress` is still active: only tools that have already finished loading are eligible for that turn.434- A turn starts while `mcp_list_tools.in_progress` is still active: only tools that have already finished loading are eligible for that turn.

433- A response uses `tool_choice: "required"` but no tools are currently available: the model has nothing eligible to call. Wait for `mcp_list_tools.completed`, confirm that at least one tool was imported, or use a different `tool_choice` for turns that don't require a tool.435- A response uses `tool_choice: "required"` but no tools are currently available: the model has nothing eligible to call. Wait for `mcp_list_tools.completed`, confirm that at least one tool was imported, or use a different `tool_choice` for turns that don't require a tool.


435 437 

436## Approve or reject MCP tool calls438## Approve or reject MCP tool calls

437 439 

438If a tool requires approval, the Realtime API inserts an `mcp_approval_request` item into the conversation. **To continue**, send a new [`conversation.item.create`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/conversation/item/create) event whose `item.type` is `mcp_approval_response`.440If a tool requires approval, the Realtime API inserts an `mcp_approval_request` item into the conversation. **To continue**, send a new [`conversation.item.create`](https://developers.openai.com/api/reference/resources/realtime) event whose `item.type` is `mcp_approval_response`.

439 441 

440Approve an MCP request442Approve an MCP request

441 443 

Details

1# Using realtime models1# Using realtime models

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.

4 

3`gpt-realtime-2` is our state-of-the-art reasoning voice model for low-latency speech-to-speech applications. It can think before it speaks, follow instructions more reliably, use a larger context window, and call tools with greater precision than earlier realtime models.5`gpt-realtime-2` is our state-of-the-art reasoning voice model for low-latency speech-to-speech applications. It can think before it speaks, follow instructions more reliably, use a larger context window, and call tools with greater precision than earlier realtime models.

4 6 

5To take advantage of these gains, design prompts with more intent. Explicitly define the assistant's responsibilities, decision points, tool-calling behavior, and guardrails: what it should do, when it should do it, and what it should avoid.7To take advantage of these gains, design prompts with more intent. Explicitly define the assistant's responsibilities, decision points, tool-calling behavior, and guardrails: what it should do, when it should do it, and what it should avoid.


20 <tbody>22 <tbody>

21 <tr>23 <tr>

22 <td style={{ whiteSpace: "nowrap" }}>24 <td style={{ whiteSpace: "nowrap" }}>

23 <a href="/api/docs/models/gpt-realtime-2">25 [`gpt-realtime-2`](https://developers.openai.com/api/docs/models/gpt-realtime-2)

24 <code>gpt-realtime-2</code>

25 </a>

26 </td>26 </td>

27 <td>27 <td>

28 You need the strongest realtime reasoning, tool use, and instruction28 You need the strongest realtime reasoning, tool use, and instruction


35 </tr>35 </tr>

36 <tr>36 <tr>

37 <td style={{ whiteSpace: "nowrap" }}>37 <td style={{ whiteSpace: "nowrap" }}>

38 <a href="/api/docs/models/gpt-realtime-1.5">38 [`gpt-realtime-1.5`](https://developers.openai.com/api/docs/models/gpt-realtime-1.5)

39 <code>gpt-realtime-1.5</code>

40 </a>

41 </td>39 </td>

42 <td>You need a fast, reliable non-reasoning speech-to-speech model.</td>40 <td>You need a fast, reliable non-reasoning speech-to-speech model.</td>

43 <td>41 <td>


50 48 

51 49 

52 50 

53<div data-content-switcher-pane data-value="gpt-realtime-2">

54## Realtime 2.0 Prompting Guide51## Realtime 2.0 Prompting Guide

55 52 

56 <p>53

57 Use <code>gpt-realtime-2</code> when the voice agent needs stronger54 

55 Use `gpt-realtime-2` when the voice agent needs stronger

58 reasoning, tool selection, exact entity handling, or long-session state.56 reasoning, tool selection, exact entity handling, or long-session state.

59 Start with <code>reasoning.effort: "low"</code>, test default preamble57 Start with `reasoning.effort: "low"`, test default preamble

60 behavior, and define clear confirmation boundaries before write actions.58 behavior, and define clear confirmation boundaries before write actions.

61 </p>59

60 

62 61 

63## What changed in Realtime 262## What changed in Realtime 2

64 63 


8646. Run a final consistency pass. Confirm the prompt clearly separates hard requirements, defaults, tool rules, safety rules, and fallback behavior.8636. Run a final consistency pass. Confirm the prompt clearly separates hard requirements, defaults, tool rules, safety rules, and fallback behavior.

8657. Run evals, inspect representative failures, and iterate on the prompt until the target behaviors are reliable.8647. Run evals, inspect representative failures, and iterate on the prompt until the target behaviors are reliable.

866 865 

867 </div>866

868 <div data-content-switcher-pane data-value="gpt-realtime-1.5" hidden>867 

868

869 

869 870 

870## Realtime 1.5 Prompting Guide871## Realtime 1.5 Prompting Guide

871 872 


926 927 

927Earlier realtime preview:928Earlier realtime preview:

928 929 

929<div className="my-6">

930 </div>

931 930 

932`gpt-realtime-1.5`:

933 931 

934<div className="my-6">932 `gpt-realtime-1.5`:

935 </div>933 

934 

936 935 

937#### Example (model takes on a character)936 #### Example (model takes on a character)

938 937 

939```938```

940# Role & Objective939# Role & Objective


943 942 

944Earlier realtime preview:943Earlier realtime preview:

945 944 

946<div className="my-6">

947 </div>

948 945 

949`gpt-realtime-1.5`:

950 946 

951<div className="my-6">947 `gpt-realtime-1.5`:

952 </div>948 

949 

953 950 

954`gpt-realtime-1.5` is able to enact the specified role more reliably than earlier realtime preview models.951 `gpt-realtime-1.5` is able to enact the specified role more reliably than earlier realtime preview models.

955 952 

956## Personality and Tone953## Personality and Tone

957 954 


986 983 

987`gpt-realtime-1.5`:984`gpt-realtime-1.5`:

988 985 

989<div className="my-6">

990 </div>

991 986 

992The model is able to adhere to the complex instructions and switch between three emotions throughout the audio response.987 

988 The model is able to adhere to the complex instructions and switch between three emotions throughout the audio response.

993 989 

994### Speed Instructions990### Speed Instructions

995 991 


1019 1015 

1020Earlier realtime preview:1016Earlier realtime preview:

1021 1017 

1022<div className="my-6">

1023 </div>

1024 1018 

1025`gpt-realtime-1.5`:

1026 1019 

1027<div className="my-6">1020 `gpt-realtime-1.5`:

1028 </div>1021 

1029 1022 

1030With explicit pacing instructions, `gpt-realtime-1.5` can produce a noticeably faster pace without sounding too hurried.1023 

1024 With explicit pacing instructions, `gpt-realtime-1.5` can produce a noticeably faster pace without sounding too hurried.

1031 1025 

1032### Language Constraint1026### Language Constraint

1033 1027 


1154 1148 

1155Earlier realtime preview:1149Earlier realtime preview:

1156 1150 

1157<div className="my-6">

1158 </div>

1159 1151 

1160`gpt-realtime-1.5`:

1161 1152 

1162<div className="my-6">1153 `gpt-realtime-1.5`:

1163 </div>1154 

1164 1155 

1165With the reference pronunciation instructions, `gpt-realtime-1.5` can correctly pronounce SQL as "sequel."1156 

1157 With the reference pronunciation instructions, `gpt-realtime-1.5` can correctly pronounce SQL as "sequel."

1166 1158 

1167### Alphanumeric Pronunciations1159### Alphanumeric Pronunciations

1168 1160 


1303 1295 

1304These are the responses **after** applying the instruction using `gpt-realtime-1.5`.1296These are the responses **after** applying the instruction using `gpt-realtime-1.5`.

1305 1297 

1306<div className="my-6">

1307 </div>

1308 1298 

1309In this example, the model asks for clarification after my _(very)_ loud cough and unclear audio.1299 

1300 In this example, the model asks for clarification after my _(very)_ loud cough and unclear audio.

1310 1301 

1311### Background Music or Sounds1302### Background Music or Sounds

1312 1303 


2054 2045 

2055`gpt-realtime-1.5` is able to follow the instruction and escalate to a human more reliably.2046`gpt-realtime-1.5` is able to follow the instruction and escalate to a human more reliably.

2056 2047 

2057 </div>

2058 

2059 2048 

2060 2049 

2061## Next steps2050## Next steps

Details

1# Webhooks and server-side controls1# Webhooks and server-side controls

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.

4 

3The Realtime API allows clients to connect directly to the API server via WebRTC or SIP. However, you'll most likely want tool use and other business logic to reside on your application server to keep this logic private and client-agnostic.5The Realtime API allows clients to connect directly to the API server via WebRTC or SIP. However, you'll most likely want tool use and other business logic to reside on your application server to keep this logic private and client-agnostic.

4 6 

5Keep tool use, business logic, and other details secure on the server side by connecting over a “sideband” control channel. We now have sideband options for both SIP and WebRTC connections.7Keep tool use, business logic, and other details secure on the server side by connecting over a “sideband” control channel. We now have sideband options for both SIP and WebRTC connections.

Details

1# Realtime API with SIP1# Realtime API with SIP

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.

4 

3[SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol) is a5[SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol) is a

4protocol used to make phone calls over the internet. With SIP and the6protocol used to make phone calls over the internet. With SIP and the

5Realtime API you can direct incoming phone calls to the API.7Realtime API you can direct incoming phone calls to the API.


19 21 

20When OpenAI receives SIP traffic associated with your project,22When OpenAI receives SIP traffic associated with your project,

21your webhook will be fired. The event fired will be a23your webhook will be fired. The event fired will be a

22[`realtime.call.incoming`](https://developers.openai.com/api/docs/api-reference/webhook-events/realtime/call/incoming) event,24[`realtime.call.incoming`](https://developers.openai.com/api/reference/resources/webhooks) event,

23like the example below:25like the example below:

24 26 

25```27```


54 56 

55## Accept the call57## Accept the call

56 58 

57Use the [Accept call endpoint](https://developers.openai.com/api/docs/api-reference/realtime-calls/accept-call) to59Use the [Accept call endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/accept) to

58approve the inbound call and configure the realtime session that will answer it.60approve the inbound call and configure the realtime session that will answer it.

59Send the same parameters you would send in a61Send the same parameters you would send in a

60[`create client secret`](https://developers.openai.com/api/docs/api-reference/realtime-sessions/create-realtime-client-secret)62[`create client secret`](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets/methods/create)

61request, i.e., ensure the realtime model, voice, tools, or instructions are set before bridging the63request, i.e., ensure the realtime model, voice, tools, or instructions are set before bridging the

62call to the model.64call to the model.

63 65 


74 76 

75 77 

76The request path must include the `call_id` from the78The request path must include the `call_id` from the

77[`realtime.call.incoming`](https://developers.openai.com/api/docs/api-reference/webhook-events/realtime/call/incoming)79[`realtime.call.incoming`](https://developers.openai.com/api/reference/resources/webhooks)

78webhook, and every request requires the `Authorization` header shown above. The80webhook, and every request requires the `Authorization` header shown above. The

79endpoint returns `200 OK` once the SIP leg is ringing and the realtime session81endpoint returns `200 OK` once the SIP leg is ringing and the realtime session

80is being established.82is being established.

81 83 

82## Reject the call84## Reject the call

83 85 

84Use the [Reject call endpoint](https://developers.openai.com/api/docs/api-reference/realtime-calls/reject-call) to86Use the [Reject call endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/reject) to

85decline an invite when you do not want to handle the incoming call, (e.g., from87decline an invite when you do not want to handle the incoming call, (e.g., from

86an unsupported country code.) Supply the `call_id` path parameter88an unsupported country code.) Supply the `call_id` path parameter

87and an optional SIP `status_code` (e.g., `486` to indicate "busy") in the JSON89and an optional SIP `status_code` (e.g., `486` to indicate "busy") in the JSON


121- `Authorization: Bearer YOUR_API_KEY`123- `Authorization: Bearer YOUR_API_KEY`

122 124 

123The WebSocket behaves exactly like any other Realtime API connection. Send125The WebSocket behaves exactly like any other Realtime API connection. Send

124[`response.create`](https://developers.openai.com/api/docs/api-reference/realtime_client_events/response/create),126[`response.create`](https://developers.openai.com/api/reference/resources/realtime/client-events#response.create),

125and other client events to control the call, and listen for server events to127and other client events to control the call, and listen for server events to

126track progress. See [Webhooks and server-side controls](https://developers.openai.com/api/docs/guides/realtime-server-controls)128track progress. See [Webhooks and server-side controls](https://developers.openai.com/api/docs/guides/realtime-server-controls)

127for more information.129for more information.


130import WebSocket from "ws";132import WebSocket from "ws";

131 133 

132const callId = "rtc_u1_9c6574da8b8a41a18da9308f4ad974ce";134const callId = "rtc_u1_9c6574da8b8a41a18da9308f4ad974ce";

133const ws = new WebSocket(`wss://api.openai.com/v1/realtime?call_id=${callId}`, {135const ws = new WebSocket(`wss://api.openai.com/v1/realtime?call_id=rtc_u1_9c6574da8b8a41a18da9308f4ad974ce`, {

134 headers: {136 headers: {

135 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,137 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,

136 },138 },


149## Redirect the call151## Redirect the call

150 152 

151Transfer an active call using the153Transfer an active call using the

152[Refer call endpoint](https://developers.openai.com/api/docs/api-reference/realtime-calls/refer-call). Provide the154[Refer call endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/refer). Provide the

153`call_id` as well as the `target_uri` that should be placed in the SIP `Refer-To`155`call_id` as well as the `target_uri` that should be placed in the SIP `Refer-To`

154header (for example `tel:+14155550123` or `sip:agent@example.com`).156header (for example `tel:+14155550123` or `sip:agent@example.com`).

155 157 


166 168 

167## Hang up the call169## Hang up the call

168 170 

169End the session with the [Hang up endpoint](https://developers.openai.com/api/docs/api-reference/realtime-calls/hangup-call)171End the session with the [Hang up endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/hangup)

170when your application should disconnect the caller. This endpoint can be used to172when your application should disconnect the caller. This endpoint can be used to

171terminate both SIP and WebRTC realtime sessions.173terminate both SIP and WebRTC realtime sessions.

172 174 


195 197 

196 198 

197 199 

198<div data-content-switcher-pane data-value="python">200Python

199 <div class="hidden">Python</div>201 

200 Python202 Python

201 203 

202```python204```python


271 app.run(port=8000)273 app.run(port=8000)

272```274```

273 275 

274 </div>

275 

276 276 

277 277 

278## Next steps278## Next steps

Details

1# Realtime transcription1# Realtime transcription

2 2 

3Use realtime transcription when your application needs live speech-to-text without a spoken assistant response. Realtime transcription sessions stream transcript deltas as audio arrives, so users can see text before the full utterance is complete.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 

5For the lowest-latency streaming transcription path, use [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper). For offline files or workflows that don't need streaming deltas, use the standard speech-to-text models in the Audio API.5Use realtime transcription when your application needs text from a microphone, call, or other live audio stream without a spoken assistant response. The recommended model returns transcript deltas as speech arrives and a final transcript when your application commits each audio turn.

6 6 

7## Choose a transcription model7Start with [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe). Use [file transcription](https://developers.openai.com/api/docs/guides/speech-to-text) if your audio is already recorded, or see the [Transcription overview](https://developers.openai.com/api/docs/guides/transcription) to compare the workflows.

8 

9<table>

10 <thead>

11 <tr>

12 <th>Model</th>

13 <th>Best for</th>

14 <th>Notes</th>

15 </tr>

16 </thead>

17 <tbody>

18 <tr>

19 <td className="whitespace-nowrap">

20 <a href="/api/docs/models/gpt-realtime-whisper">

21 gpt-realtime-whisper

22 </a>

23 </td>

24 <td>Live audio, transcript deltas, tunable latency.</td>

25 <td>Natively streaming and designed for realtime sessions.</td>

26 </tr>

27 <tr>

28 <td className="whitespace-nowrap">

29 <a href="/api/docs/models/gpt-4o-transcribe">gpt-4o-transcribe</a>

30 </td>

31 <td>Higher-accuracy speech-to-text where streaming isn't required.</td>

32 <td>Use for file and request-response transcription workflows.</td>

33 </tr>

34 <tr>

35 <td className="whitespace-nowrap">

36 <a href="/api/docs/models/gpt-4o-mini-transcribe">

37 gpt-4o-mini-transcribe

38 </a>

39 </td>

40 <td>Lower-cost transcription.</td>

41 <td>Use when cost matters more than top accuracy.</td>

42 </tr>

43 <tr>

44 <td className="whitespace-nowrap">

45 <a href="/api/docs/models/whisper-1">whisper-1</a>

46 </td>

47 <td>Existing Whisper integrations.</td>

48 <td>

49 Not natively streaming in the same way as

50 <code>gpt-realtime-whisper</code>.

51 </td>

52 </tr>

53 </tbody>

54</table>

55 

56`gpt-realtime-whisper` is an alternative for live transcription, not a blanket replacement for every transcription model. Test it against your audio, languages, vocabulary, and latency requirements before switching production traffic.

57 8 

58## Create a transcription session9## Create a transcription session

59 10 

60Realtime transcription uses a session with `type: "transcription"`. You can connect with [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket) for server-side audio pipelines or [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) for browser audio.11Create a session with `type: "transcription"` and select `gpt-live-transcribe`. Connect with [WebSocket](https://developers.openai.com/api/docs/guides/realtime-websocket) for server-side audio pipelines or [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc) for browser audio.

61 12 

62```json13```json

63{14{


71 "rate": 2400022 "rate": 24000

72 },23 },

73 "transcription": {24 "transcription": {

74 "model": "gpt-realtime-whisper",25 "model": "gpt-live-transcribe"

75 "language": "en"26 },

76 }27 "turn_detection": null

77 }28 }

78 }29 }

79 }30 }


81```32```

82 33 

83 34 

84### Session fields35This example uses 24 kHz PCM audio and disables automatic turn detection so that you can explicitly commit each turn. For the full session configuration, see the [Realtime sessions reference](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets).

85 

86- `type`: Set to `transcription` for transcription-only sessions.

87- `audio.input.format`: Input encoding for audio appended to the buffer. Use 24 kHz mono PCM when sending `audio/pcm`.

88- `audio.input.transcription.model`: Use `gpt-realtime-whisper` for streaming transcription.

89- `audio.input.transcription.language`: Optional language hint such as `en`.

90- `audio.input.transcription.delay`: Optional latency/accuracy tradeoff for `gpt-realtime-whisper`. Supported values are `minimal`, `low`, `medium`, `high`, and `xhigh`.

91- `audio.input.turn_detection`: Optional voice activity detection for models that support it. For `gpt-realtime-whisper`, omit this field or set it to `null`, then commit audio manually.

92 36 

93## Stream audio37## Stream audio

94 38 


104```48```

105 49 

106 50 

107If you disable turn detection, commit the buffer when you want transcription to begin:51With automatic turn detection turned off, commit the buffer when you want to finish an audio turn:

108 52 

109```javascript53```javascript

110ws.send(54ws.send(


115```59```

116 60 

117 61 

118For models that support server VAD, the session commits audio automatically when it detects a turn boundary.62To let the server detect and commit turn boundaries, configure [voice activity detection](https://developers.openai.com/api/docs/guides/realtime-vad) instead.

119 63 

120## Handle transcript events64## Handle transcript events

121 65 


160 104 

161Ordering between completion events from different speech turns isn't guaranteed. Use `item_id` to match transcription events to committed input items.105Ordering between completion events from different speech turns isn't guaranteed. Use `item_id` to match transcription events to committed input items.

162 106 

163## Tune latency and accuracy107## Add transcription context

164 

165Streaming transcription trades latency for transcript quality. Lower delay settings can produce earlier partial text. Higher delay settings give the model more audio context before emitting text and can improve word error rate.

166 

167Start by setting `audio.input.transcription.delay` and testing against your real audio. Useful starting points are:

168 108 

169- `minimal` for the most latency-sensitive interactions;109Add context when the audio contains specialized vocabulary or more than one expected language. Send another `session.update` event to change the transcription configuration during an existing session.

170- `low` for low-latency live captions;

171- `medium` for a balanced latency/accuracy tradeoff;

172- `high` when accuracy matters more than immediate display;

173- `xhigh` when your workflow can tolerate the most delay for additional context.

174 110 

175The exact delay in milliseconds can vary by model configuration, so benchmark with representative audio instead of assuming a fixed timing per level.111```json

112{

113 "type": "session.update",

114 "session": {

115 "type": "transcription",

116 "audio": {

117 "input": {

118 "format": {

119 "type": "audio/pcm",

120 "rate": 24000

121 },

122 "transcription": {

123 "model": "gpt-live-transcribe",

124 "prompt": "A customer support call about a premium plan and account AC-42.",

125 "keywords": ["premium plan", "AC-42", "billing"],

126 "languages": ["en", "fr"],

127 "delay": "low"

128 },

129 "turn_detection": null

130 }

131 }

132 }

133}

134```

176 135 

177Don't choose a setting from synthetic audio alone. Test with representative microphones, telephony audio, accents, background noise, code-switching, domain vocabulary, and long sessions.

178 136 

179## Guide vocabulary and domain terms137- Use `prompt` to describe the recording or its setting.

138- Use `keywords` for product names, acronyms, and other literal terms that may appear in the audio.

139- Use `languages` for expected input languages.

180 140 

181If your application depends on exact domain vocabulary, include a language hint and use prompt or keyword steering only when your selected model supports it. For `gpt-realtime-whisper` in GA Realtime sessions, `prompt` is not supported.141Supported language-code formats include:

182 142 

183Where prompt steering is available, use short keyword lists rather than long instructions. The model is already instructed to transcribe, so focus prompts on domain vocabulary, spelling, or style rather than re-stating the transcription task.143- ISO 639-1 codes, such as `en`, `es`, and `fr`.

144- Selected ISO 639-3 codes, such as `eng`, `spa`, `yue`, and `cmn`.

145- Regional `zh` locale codes, such as `zh-cn`, `zh-tw`, and `zh-hk`.

184 146 

185Example keyword style:147The Realtime API rejects unsupported or incorrectly formatted language codes.

186 148 

187```text149Keywords are hints, not required output. Keep each keyword on one line and don't include `<`, `>`, a carriage return, or a line feed. The Realtime API rejects the session update if a keyword contains one of these characters or `prompt` exceeds the model's length limit.

188Keywords: metoprolol, atorvastatin, A1C, systolic, diastolic

189```

190 150 

191For production, treat keyword steering as an aid rather than a guarantee. Continue to evaluate names, numbers, dates, medication names, product names, artist names, and other high-value entities manually.151`gpt-live-transcribe` uses `languages` instead of the singular `language` field. Don't send both.

192 152 

193## Handle confidence, timestamps, and diarization153## Transcribe a committed turn

194 154 

195Only request optional fields that your selected model and endpoint support. If your application needs confidence scoring, timestamps, or diarization, verify support before launch and add fallbacks for fields that aren't available.155Use `gpt-transcribe` in a Realtime session only when you specifically need transcription to begin after a committed audio turn or need detected-language output. This specialized workflow requires a WebSocket connection.

196 156 

197When log probabilities are available, request them with `include`:157When `gpt-transcribe` performs input transcription in a Realtime API session or runs in a dedicated transcription session, it automatically uses earlier transcribed turns as context.

198 158 

199```json159```json

200{160{


203 "type": "transcription",163 "type": "transcription",

204 "audio": {164 "audio": {

205 "input": {165 "input": {

166 "format": {

167 "type": "audio/pcm",

168 "rate": 24000

169 },

206 "transcription": {170 "transcription": {

207 "model": "gpt-realtime-whisper"171 "model": "gpt-transcribe"

172 },

173 "turn_detection": null

208 }174 }

209 }175 }

210 },

211 "include": ["item.input_audio_transcription.logprobs"]

212 }176 }

213}177}

214```178```

215 179 

216 180 

181Append audio and send `input_audio_buffer.commit`. The model can then emit transcript deltas before the final completion event. Its completion event also includes detected languages:

182 

183```json

184{

185 "type": "conversation.item.input_audio_transcription.completed",

186 "item_id": "item_003",

187 "content_index": 0,

188 "transcript": "Bonjour, pouvez-vous m'entendre ?",

189 "languages": [{ "code": "fr" }]

190}

191```

192 

193When `gpt-transcribe` can't make a reliable language prediction, `languages` is an empty array. `gpt-live-transcribe` doesn't return detected-language predictions.

194 

195## Tune latency and accuracy

196 

197Streaming transcription trades latency for transcript quality. Lower delay settings can produce earlier partial text. Higher delay settings give the model more audio context before emitting text and can improve word error rate.

198 

199Start by setting `audio.input.transcription.delay` and testing against your real audio. Useful starting points are:

200 

201- `minimal` for the most latency-sensitive interactions;

202- `low` for low-latency live captions;

203- `medium` for a balanced latency/accuracy tradeoff;

204- `high` when accuracy matters more than immediate display;

205- `xhigh` when your workflow can tolerate the most delay for more context.

206 

207The exact delay in milliseconds can vary by model configuration, so benchmark with representative audio instead of assuming a fixed timing per level.

208 

209Don't choose a setting from synthetic audio alone. Test with representative microphones, telephony audio, accents, background noise, code-switching, domain vocabulary, and long sessions.

210 

211## Handle confidence, timestamps, and speaker labels

212 

213`gpt-live-transcribe` doesn't return word-level timestamps, speaker labels, or transcription confidence scores. If your application requires timestamps or speaker labels, use a compatible [file transcription](https://developers.openai.com/api/docs/guides/speech-to-text) model or add an application-level fallback.

214 

217## Production checklist215## Production checklist

218 216 

219- Pick a target latency and accuracy threshold before tuning.217- Pick a target latency and accuracy threshold before tuning.


223- Track empty, truncated, and delayed transcripts apart from word error rate.221- Track empty, truncated, and delayed transcripts apart from word error rate.

224- Decide how your UI should revise partial text when later deltas correct earlier text.222- Decide how your UI should revise partial text when later deltas correct earlier text.

225- Use `item_id` to order and reconcile final transcripts.223- Use `item_id` to order and reconcile final transcripts.

226- Keep a fallback path for unsupported timestamps, diarization, or confidence fields.224- Keep a fallback path for unsupported timestamps, speaker labels, or confidence fields.

227 225 

228## Related guides226## Related guides

229 227 

230<a href="/api/docs/guides/realtime">228[Realtime and audio overview

231

232 

233<span slot="icon">

234 </span>

235 Compare voice-agent, translation, and transcription sessions.

236 

237 

238</a>

239 229 

240<a href="/api/docs/guides/realtime-translation">

241 230 

242 231 

243<span slot="icon">232 Compare voice-agent, translation, and transcription sessions.](https://developers.openai.com/api/docs/guides/realtime)

244 </span>

245 Translate live speech with a dedicated translation session.

246 233 

234[Realtime translation

247 235 

248</a>

249 236 

250<a href="/api/docs/guides/realtime-websocket">

251 237 

238 Translate live speech with a dedicated translation session.](https://developers.openai.com/api/docs/guides/realtime-translation)

252 239 

253<span slot="icon">240[WebSocket connection

254 </span>

255 Stream raw audio through a server-side media pipeline.

256 241 

257 242 

258</a>

259 243 

260<a href="/api/docs/guides/realtime-vad">244 Stream raw audio through a server-side media pipeline.](https://developers.openai.com/api/docs/guides/realtime-websocket)

261 245 

246[Voice activity detection

262 247 

263<span slot="icon">

264 </span>

265 Configure turn detection for live audio streams.

266 248 

267 249 

268</a>250 Configure turn detection for live audio streams.](https://developers.openai.com/api/docs/guides/realtime-vad)

Details

1# Realtime translation1# Realtime translation

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.

4 

3Realtime translation lets you stream source audio into a dedicated translation session and receive translated audio plus transcript deltas while the speaker is still talking. Use it for live interpretation, multilingual calls, broadcasts, meetings, lessons, and video rooms.5Realtime translation lets you stream source audio into a dedicated translation session and receive translated audio plus transcript deltas while the speaker is still talking. Use it for live interpretation, multilingual calls, broadcasts, meetings, lessons, and video rooms.

4 6 

5Use [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate) when your application should translate what a human says. If you need an assistant that answers questions, calls tools, and manages a conversation, use [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) with a standard Realtime session instead.7Use [`gpt-realtime-translate`](https://developers.openai.com/api/docs/models/gpt-realtime-translate) when your application should translate what a human says. If you need an assistant that answers questions, calls tools, and manages a conversation, use [`gpt-realtime-2.1`](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) with a standard Realtime session instead.


408 410 

409## Related guides411## Related guides

410 412 

411<a href="/api/docs/guides/realtime">413[Realtime and audio overview

412

413 

414<span slot="icon">

415 </span>

416 Compare voice-agent, translation, and transcription sessions.

417 

418 

419</a>

420 414 

421<a href="/api/docs/guides/realtime-webrtc">

422 415 

423 416 

424<span slot="icon">417 Compare voice-agent, translation, and transcription sessions.](https://developers.openai.com/api/docs/guides/realtime)

425 </span>

426 Connect browser media to a realtime session.

427 418 

419[WebRTC connection

428 420 

429</a>

430 421 

431<a href="/api/docs/guides/realtime-websocket">

432 422 

423 Connect browser media to a realtime session.](https://developers.openai.com/api/docs/guides/realtime-webrtc)

433 424 

434<span slot="icon">425[WebSocket connection

435 </span>

436 Stream raw audio through a server-side media pipeline.

437 426 

438 427 

439</a>

440 428 

441<a href="/api/docs/guides/realtime-transcription">429 Stream raw audio through a server-side media pipeline.](https://developers.openai.com/api/docs/guides/realtime-websocket)

442 430 

431[Realtime transcription

443 432 

444<span slot="icon">

445 </span>

446 Stream transcript deltas from live audio.

447 433 

448 434 

449</a>435 Stream transcript deltas from live audio.](https://developers.openai.com/api/docs/guides/realtime-transcription)

Details

1# Voice activity detection (VAD)1# Voice activity detection (VAD)

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.

4 

3Voice activity detection (VAD) is a feature available in the Realtime API allowing to automatically detect when the user has started or stopped speaking.5Voice activity detection (VAD) is a feature available in the Realtime API allowing to automatically detect when the user has started or stopped speaking.

4It is enabled by default in [speech-to-speech](https://developers.openai.com/api/docs/guides/realtime-conversations) Realtime sessions, but is optional and can be turned off.6It is enabled by default in [speech-to-speech](https://developers.openai.com/api/docs/guides/realtime-conversations) Realtime sessions, but is optional and can be turned off.

5In [transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) Realtime sessions, turn detection support depends on the transcription model. Models that support VAD default to `server_vad`, while `gpt-realtime-whisper` requires turn detection to be omitted or set to `null`.7In [transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) Realtime sessions, turn detection support depends on the transcription model. Models that support VAD default to `server_vad`, while `gpt-realtime-whisper` requires turn detection to be omitted or set to `null`.


13 15 

14You can use these events to handle speech turns in your application. For example, you can use them to manage conversation state or process transcripts in chunks.16You can use these events to handle speech turns in your application. For example, you can use them to manage conversation state or process transcripts in chunks.

15 17 

16You can configure VAD with the [`session.update`](https://developers.openai.com/api/docs/api-reference/realtime-client-events/session/update) client event by setting `session.audio.input.turn_detection`.18You can configure VAD with the [`session.update`](https://developers.openai.com/api/reference/resources/realtime) client event by setting `session.audio.input.turn_detection`.

17 19 

18There are two modes for VAD:20There are two modes for VAD:

19 21 

Details

1# Realtime API with WebRTC1# Realtime API with WebRTC

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.

4 

3[WebRTC](https://webrtc.org/) is a powerful set of standard interfaces for building real-time applications. The OpenAI Realtime API supports connecting to realtime models through a WebRTC peer connection.5[WebRTC](https://webrtc.org/) is a powerful set of standard interfaces for building real-time applications. The OpenAI Realtime API supports connecting to realtime models through a WebRTC peer connection.

4 6 

5For browser-based speech-to-speech voice applications, we recommend starting with [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents), which covers the Agents SDK's higher-level helpers and APIs for managing Realtime sessions. The WebRTC interface is powerful and flexible, but lower level than the Agents SDK.7For browser-based speech-to-speech voice applications, we recommend starting with [Voice agents](https://developers.openai.com/api/docs/guides/voice-agents), which covers the Agents SDK's higher-level helpers and APIs for managing Realtime sessions. The WebRTC interface is powerful and flexible, but lower level than the Agents SDK.


12 14 

13## Overview15## Overview

14 16 

15The Realtime API supports two mechanisms for connecting to the Realtime API from the browser, either using ephemeral API keys ([generated via the OpenAI REST API](https://developers.openai.com/api/docs/api-reference/realtime-sessions)), or via the new unified interface. Generally, using the unified interface is simpler, but puts your application server in the critical path for session initialization.17The Realtime API supports two mechanisms for connecting to the Realtime API from the browser, either using ephemeral API keys ([generated via the OpenAI REST API](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets)), or via the new unified interface. Generally, using the unified interface is simpler, but puts your application server in the critical path for session initialization.

16 18 

17### Connecting using the unified interface19### Connecting using the unified interface

18 20 


122The process for initializing a WebRTC connection using an ephemeral API key is as follows (assuming a web browser client):124The process for initializing a WebRTC connection using an ephemeral API key is as follows (assuming a web browser client):

123 125 

1241. The browser makes a request to a developer-controlled server to mint an ephemeral API key.1261. The browser makes a request to a developer-controlled server to mint an ephemeral API key.

1251. The developer's server uses a [standard API key](https://platform.openai.com/settings/organization/api-keys) to request an ephemeral key from the [OpenAI REST API](https://developers.openai.com/api/docs/api-reference/realtime-sessions), and returns that new key to the browser.1271. The developer's server uses a [standard API key](https://platform.openai.com/settings/organization/api-keys) to request an ephemeral key from the [OpenAI REST API](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets), and returns that new key to the browser.

1261. The browser uses the ephemeral key to authenticate a session directly with the OpenAI Realtime API as a [WebRTC peer connection](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection).1281. The browser uses the ephemeral key to authenticate a session directly with the OpenAI Realtime API as a [WebRTC peer connection](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection).

127 129 

128![connect to realtime via WebRTC](https://openaidevs.retool.com/api/file/55b47800-9aaf-48b9-90d5-793ab227ddd3)130![connect to realtime via WebRTC](https://openaidevs.retool.com/api/file/55b47800-9aaf-48b9-90d5-793ab227ddd3)

129 131 

130#### Creating an ephemeral token132#### Creating an ephemeral token

131 133 

132To create an ephemeral token to use on the client-side, you will need to build a small server-side application (or integrate with an existing one) to make an [OpenAI REST API](https://developers.openai.com/api/docs/api-reference/realtime-sessions) request for an ephemeral key. You will use a [standard API key](https://platform.openai.com/settings/organization/api-keys) to authenticate this request on your backend server.134To create an ephemeral token to use on the client-side, you will need to build a small server-side application (or integrate with an existing one) to make an [OpenAI REST API](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets) request for an ephemeral key. You will use a [standard API key](https://platform.openai.com/settings/organization/api-keys) to authenticate this request on your backend server.

133 135 

134Below is an example of a simple Node.js [express](https://expressjs.com/) server which mints an ephemeral API key using the REST API:136Below is an example of a simple Node.js [express](https://expressjs.com/) server which mints an ephemeral API key using the REST API:

135 137 


236 238 

237## Sending and receiving events239## Sending and receiving events

238 240 

239Realtime API sessions are managed using a combination of [client-sent events](https://developers.openai.com/api/docs/api-reference/realtime_client_events/session) emitted by you as the developer, and [server-sent events](https://developers.openai.com/api/docs/api-reference/realtime_server_events/error) created by the Realtime API to indicate session lifecycle events.241Realtime API sessions are managed using a combination of [client-sent events](https://developers.openai.com/api/reference/resources/realtime/client-events#session.update) emitted by you as the developer, and [server-sent events](https://developers.openai.com/api/reference/resources/realtime/server-events#error) created by the Realtime API to indicate session lifecycle events.

240 242 

241When connecting to a Realtime model via WebRTC, you don't have to handle audio events from the model in the same granular way you must with [WebSockets](https://developers.openai.com/api/docs/guides/realtime-websocket). The WebRTC peer connection object, if configured as above, will do all that work for you.243When connecting to a Realtime model via WebRTC, you don't have to handle audio events from the model in the same granular way you must with [WebSockets](https://developers.openai.com/api/docs/guides/realtime-websocket). The WebRTC peer connection object, if configured as above, will do all that work for you.

242 244 


272 274 

273To learn more about managing Realtime conversations, refer to the [Realtime conversations guide](https://developers.openai.com/api/docs/guides/realtime-conversations).275To learn more about managing Realtime conversations, refer to the [Realtime conversations guide](https://developers.openai.com/api/docs/guides/realtime-conversations).

274 276 

275<a277[Realtime Console

276 href="https://github.com/openai/openai-realtime-console/"

277 target="_blank"

278 rel="noreferrer"

279>

280

281 278 

282<span slot="icon">

283 </span>

284 Check out the WebRTC Realtime API in this light weight example app.

285 279 

286 280 

287</a>281 Check out the WebRTC Realtime API in this light weight example app.](https://github.com/openai/openai-realtime-console/)

Details

1# Realtime API with WebSocket1# Realtime API with WebSocket

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.

4 

3[WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) are a broadly supported API for realtime data transfer, and a great choice for connecting to the OpenAI Realtime API in server-to-server applications. For browser and mobile clients, we recommend connecting via [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc).5[WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) are a broadly supported API for realtime data transfer, and a great choice for connecting to the OpenAI Realtime API in server-to-server applications. For browser and mobile clients, we recommend connecting via [WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc).

4 6 

5In a server-to-server integration with Realtime, your backend system will connect via WebSocket directly to the Realtime API. You can use a [standard API key](https://platform.openai.com/settings/organization/api-keys) to authenticate this connection, since the token will only be available on your secure backend server.7In a server-to-server integration with Realtime, your backend system will connect via WebSocket directly to the Realtime API. You can use a [standard API key](https://platform.openai.com/settings/organization/api-keys) to authenticate this connection, since the token will only be available on your secure backend server.


14 16 

15 17 

16 18 

17<div data-content-switcher-pane data-value="ws">19ws module (Node.js)

18 <div class="hidden">ws module (Node.js)</div>20 

19 Connect using the ws module (Node.js)21 Connect using the ws module (Node.js)

20 22 

21```javascript23```javascript


38});40});

39```41```

40 42 

41 </div>43

42 <div data-content-switcher-pane data-value="python" hidden>44 

43 <div class="hidden">websocket-client (Python)</div>45

46 

47

48websocket-client (Python)

49 

44 Connect with websocket-client (Python)50 Connect with websocket-client (Python)

45 51 

46```python52```python


79ws.run_forever()85ws.run_forever()

80```86```

81 87 

82 </div>88

83 <div data-content-switcher-pane data-value="websocket" hidden>89 

84 <div class="hidden">WebSocket (browsers)</div>90

91 

92

93WebSocket (browsers)

94 

85 Connect with standard WebSocket (browsers)95 Connect with standard WebSocket (browsers)

86 96 

87```javascript97```javascript


113});123});

114```124```

115 125 

116 </div>

117 

118 126 

119 127 

120## Sending and receiving events128## Sending and receiving events

121 129 

122Realtime API sessions are managed using a combination of [client-sent events](https://developers.openai.com/api/docs/api-reference/realtime_client_events/session) emitted by you as the developer, and [server-sent events](https://developers.openai.com/api/docs/api-reference/realtime_server_events/error) created by the Realtime API to indicate session lifecycle events.130Realtime API sessions are managed using a combination of [client-sent events](https://developers.openai.com/api/reference/resources/realtime/client-events#session.update) emitted by you as the developer, and [server-sent events](https://developers.openai.com/api/reference/resources/realtime/server-events#error) created by the Realtime API to indicate session lifecycle events.

123 131 

124Over a WebSocket, you will both send and receive JSON-serialized events as strings of text, as in this Node.js example below (the same principles apply for other WebSocket libraries):132Over a WebSocket, you will both send and receive JSON-serialized events as strings of text, as in this Node.js example below (the same principles apply for other WebSocket libraries):

125 133 

guides/reasoning.md +258 −46

Details

1# Reasoning models1# Reasoning models

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.

4 

3**Reasoning models** like [GPT-5.5](https://developers.openai.com/api/docs/models/gpt-5.5) 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** like [GPT-5.5](https://developers.openai.com/api/docs/models/gpt-5.5) 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.

4 6 

5Start with `gpt-5.6` for most reasoning workloads. If you need the highest-intelligence API option for more challenging problems that can tolerate more latency, use <a href="/api/docs/models/gpt-5.6-sol"><code>gpt-5.6-sol</code></a> in the Responses API with `reasoning.mode` set to `pro`. 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.7Start with `gpt-5.6` for most reasoning workloads. If you need the highest-intelligence API option for more challenging problems that can tolerate more latency, use [`gpt-5.6-sol`](https://developers.openai.com/api/docs/models/gpt-5.6-sol) in the Responses API with `reasoning.mode` set to `pro`. 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.

6 8 

7**Reasoning models work better with the [Responses9**Reasoning models work better with the [Responses

8 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


11 13 

12## Get started with reasoning14## Get started with reasoning

13 15 

14Call the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create) and specify your reasoning model and reasoning effort:16Call the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) and specify your reasoning model and reasoning effort:

15 17 

16Using a reasoning model in the Responses API18Using a reasoning model in the Responses API

17 19 


125 127 

126Reasoning models introduce **reasoning tokens** in addition to input and output tokens. The models use these reasoning tokens to "think," breaking down the prompt and considering multiple approaches to generating a response. Our reasoning models like `gpt-5.5` and `gpt-5.4` support interleaved thinking, where the model is able to generate visible output tokens before and in between thinking, and is able to think in between tool calls.128Reasoning models introduce **reasoning tokens** in addition to input and output tokens. The models use these reasoning tokens to "think," breaking down the prompt and considering multiple approaches to generating a response. Our reasoning models like `gpt-5.5` and `gpt-5.4` support interleaved thinking, where the model is able to generate visible output tokens before and in between thinking, and is able to think in between tool calls.

127 129 

128Here is the default behavior for a multi-step conversation between a user and an assistant. Input and output tokens from each step are carried over, while reasoning from earlier turns is not rendered into the next sample. Models that support persisted reasoning can change this behavior with `reasoning.context`.130For models released before GPT-5.6, the default behavior in a multi-step conversation is to carry over input and output tokens from each step without rendering reasoning from earlier turns into the next sample. GPT-5.6 models instead default to rendering available reasoning from earlier turns. Use `reasoning.context` to select either behavior on supported models.

129 131 

130![Reasoning tokens with current-turn context](https://cdn.openai.com/API/docs/images/context-window.png)132![Reasoning tokens with current-turn context](https://cdn.openai.com/API/docs/images/context-window.png)

131 133 


135 137 

136### Managing the context window138### Managing the context window

137 139 

138It's important to ensure there's enough space in the context window for reasoning tokens when creating responses. Depending on the problem's complexity, the models may generate anywhere from a few hundred to tens of thousands of reasoning tokens. The exact number of reasoning tokens used is visible in the [usage object of the response object](https://developers.openai.com/api/docs/api-reference/responses/object), under `output_tokens_details`:140It's important to ensure there's enough space in the context window for reasoning tokens when creating responses. Depending on the problem's complexity, the models may generate anywhere from a few hundred to tens of thousands of reasoning tokens. The exact number of reasoning tokens used is visible in the [usage object of the response object](https://developers.openai.com/api/reference/resources/responses), under `output_tokens_details`:

139 141 

140```json142```json

141{143{


160To manage costs with reasoning models, you can limit the total number of tokens the162To manage costs with reasoning models, you can limit the total number of tokens the

161model generates, including reasoning tokens, visible output tokens, and non-visible163model generates, including reasoning tokens, visible output tokens, and non-visible

162formatting tokens, by using the164formatting tokens, by using the

163[`max_output_tokens`](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-max_output_tokens)165[`max_output_tokens`](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-max_output_tokens)

164parameter. See [output token counts](https://developers.openai.com/api/docs/guides/token-counting#understand-output-token-counts) for details about how generated tokens are reflected in usage and output limits.166parameter. See [output token counts](https://developers.openai.com/api/docs/guides/token-counting#understand-output-token-counts) for details about how generated tokens are reflected in usage and output limits.

165 167 

166### Allocating space for reasoning168### Allocating space for reasoning


237 239 

238### Keeping reasoning items in context240### Keeping reasoning items in context

239 241 

240When doing [function calling](https://developers.openai.com/api/docs/guides/function-calling) with a reasoning model in the [Responses API](https://developers.openai.com/api/docs/api-reference/responses), we highly recommend you pass back any reasoning items returned with the last function call (in addition to the output of your function). If the model calls multiple functions consecutively, you should pass back all reasoning items, function call items, and function call output items, since the last `user` message. This allows the model to continue its reasoning process to produce better results in the most token-efficient manner.242When doing [function calling](https://developers.openai.com/api/docs/guides/function-calling) with a reasoning model in the [Responses API](https://developers.openai.com/api/reference/resources/responses), we highly recommend you pass back any reasoning items returned with the last function call (in addition to the output of your function). If the model calls multiple functions consecutively, you should pass back all reasoning items, function call items, and function call output items, since the last `user` message. This allows the model to continue its reasoning process to produce better results in the most token-efficient manner.

241 243 

242The simplest way to do this is to pass in all reasoning items from a previous response into the next one. Our systems will smartly ignore any reasoning items that aren't relevant to your functions, and only retain those in context that are relevant. You can pass reasoning items from previous responses either using the `previous_response_id` parameter, or by manually passing in all the [output](https://developers.openai.com/api/docs/api-reference/responses/object#responses/object-output) items from a past response into the [input](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-input) of a new one.244The simplest way to do this is to pass in all reasoning items from a previous response into the next one. Our systems will smartly ignore any reasoning items that aren't relevant to your functions, and only retain those in context that are relevant. You can pass reasoning items from previous responses either using the `previous_response_id` parameter, or by manually passing in all the [output](https://developers.openai.com/api/reference/resources/responses#responses/object-output) items from a past response into the [input](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-input) of a new one.

243 245 

244For advanced use cases where you might be truncating and optimizing parts of the context window before passing them on to the next response, just ensure all items between the last user message and your function call output are passed into the next response untouched. This will ensure that the model has all the context it needs.246For advanced use cases where you might be truncating and optimizing parts of the context window before passing them on to the next response, just ensure all items between the last user message and your function call output are passed into the next response untouched. This will ensure that the model has all the context it needs.

245 247 


251 253 

252Persisted reasoning provides continuity; it does not expose the model's raw reasoning. The reasoning items remain opaque, and the API does not return their reasoning text. Set `reasoning.context` to control which available reasoning items the model can use:254Persisted reasoning provides continuity; it does not expose the model's raw reasoning. The reasoning items remain opaque, and the API does not return their reasoning text. Set `reasoning.context` to control which available reasoning items the model can use:

253 255 

254Support for <code>reasoning.context</code> modes is model-dependent. Replace256The [GPT-5.6 model family](https://developers.openai.com/api/docs/guides/latest-model) supports

255 <code>YOUR_MODEL_ID</code> in the examples with a model that supports the mode257 `all_turns` and uses it by default. Earlier models default to

256 you select.258 `current_turn`. Omit `reasoning.context` or set it to

259 `auto` to use the selected model's default.

257 260 

258| Value | Behavior |261| Value | Behavior |

259| -------------- | ------------------------------------------------------------------------------------------------------------------------------- |262| -------------- | ------------------------------------------------------------------------------------------------------------------------- |

260| `auto` | Uses the selected model's default. Omitting `reasoning.context` has the same effect as `auto`. |263| `auto` | Uses the selected model's default. Omitting `reasoning.context` has the same effect as `auto`. |

261| `current_turn` | Makes reasoning from the active turn available, but does not render reasoning from earlier turns into the next sample. |264| `current_turn` | Makes reasoning from the active turn available, but does not render reasoning from earlier turns into the next sample. |

262| `all_turns` | Renders available, compatible reasoning items from earlier turns into the next sample. Only supported models accept this value. |265| `all_turns` | Renders available, compatible reasoning items from earlier turns into the next sample. GPT-5.6 models support this value. |

263 266 

264The response's `reasoning.context` field contains the effective mode, either `current_turn` or `all_turns`. Check this field on each response to confirm which mode the model used. The setting does not create reasoning items that are not already available.267The response's `reasoning.context` field contains the effective mode, either `current_turn` or `all_turns`. Check this field on each response to confirm which mode the model used. The setting does not create reasoning items that are not already available.

265 268 


277const client = new OpenAI();280const client = new OpenAI();

278 281 

279const first = await client.responses.create({282const first = await client.responses.create({

280 model: "YOUR_MODEL_ID",283 model: "gpt-5.6",

281 input: "Inspect this repository and identify the likely bug.",284 input: "Inspect this repository and identify the likely bug.",

282 reasoning: { context: "current_turn" },285 reasoning: { context: "current_turn" },

283});286});

284 287 

285const second = await client.responses.create({288const second = await client.responses.create({

286 model: "YOUR_MODEL_ID",289 model: "gpt-5.6",

287 previous_response_id: first.id,290 previous_response_id: first.id,

288 input: "Now patch the bug and explain the change.",291 input: "Now patch the bug and explain the change.",

289 reasoning: { context: "all_turns" },292 reasoning: { context: "all_turns" },


357];360];

358 361 

359const first = await client.responses.create({362const first = await client.responses.create({

360 model: "YOUR_MODEL_ID",363 model: "gpt-5.6",

361 store: false,364 store: false,

362 input: history,365 input: history,

363 reasoning: { context: "current_turn" },366 reasoning: { context: "current_turn" },


371});374});

372 375 

373const second = await client.responses.create({376const second = await client.responses.create({

374 model: "YOUR_MODEL_ID",377 model: "gpt-5.6",

375 store: false,378 store: false,

376 input: history,379 input: history,

377 reasoning: { context: "all_turns" },380 reasoning: { context: "all_turns" },


426 429 

427Different models support different reasoning summary settings. For example, our computer use model supports the `concise` summarizer, while o4-mini supports `detailed`. To access the most detailed summarizer available for a model, set the value of this parameter to `auto`. `auto` will be equivalent to `detailed` for most reasoning models today, but there may be more granular settings in the future.430Different models support different reasoning summary settings. For example, our computer use model supports the `concise` summarizer, while o4-mini supports `detailed`. To access the most detailed summarizer available for a model, set the value of this parameter to `auto`. `auto` will be equivalent to `detailed` for most reasoning models today, but there may be more granular settings in the future.

428 431 

429Reasoning summary output is part of the `summary` array in the `reasoning` [output item](https://developers.openai.com/api/docs/api-reference/responses/object#responses/object-output). This output will not be included unless you explicitly opt in to including reasoning summaries.432Reasoning summary output is part of the `summary` array in the `reasoning` [output item](https://developers.openai.com/api/reference/resources/responses#responses/object-output). This output will not be included unless you explicitly opt in to including reasoning summaries.

430 433 

431The example below shows how to make an API request that includes a reasoning summary.434The example below shows how to make an API request that includes a reasoning summary.

432 435 


596 599 

597 600 

598 601 

599<div data-content-switcher-pane data-value="refactoring">602Coding (refactoring)

600 <div class="hidden">Coding (refactoring)</div>

601 </div>

602 <div data-content-switcher-pane data-value="planning" hidden>

603 <div class="hidden">Coding (planning)</div>

604 </div>

605 <div data-content-switcher-pane data-value="research" hidden>

606 <div class="hidden">STEM Research</div>

607 </div>

608 603 

609 604

610 605 

611## Use case examples606OpenAI o-series models are able to implement complex algorithms and produce code. This prompt asks o1 to refactor a React component based on some specific criteria.

612 607 

613Some examples of using reasoning models for real-world use cases can be found in [the cookbook](https://developers.openai.com/cookbook).

614 608 

615<a

616 href="https://cookbook.openai.com/examples/o1/using_reasoning_for_data_validation"

617 target="_blank"

618 rel="noreferrer"

619>

620 609 

621 610 

622<span slot="icon">611 Refactor code

623 </span>612 

624 Evaluate a synthetic medical data set for discrepancies.613```javascript

614import OpenAI from "openai";

615 

616const openai = new OpenAI();

617 

618const prompt = `

619Instructions:

620- Given the React component below, change it so that nonfiction books have red

621 text.

622- Return only the code in your reply

623- Do not include any additional formatting, such as markdown code blocks

624- For formatting, use four space tabs, and do not allow any lines of code to

625 exceed 80 columns

626 

627const books = [

628 { title: 'Dune', category: 'fiction', id: 1 },

629 { title: 'Frankenstein', category: 'fiction', id: 2 },

630 { title: 'Moneyball', category: 'nonfiction', id: 3 },

631];

632 

633export default function BookList() {

634 const listItems = books.map(book =>

635 <li>

636 {book.title}

637 </li>

638 );

639 

640 return (

641 <ul>{listItems}</ul>

642 );

643}

644`.trim();

645 

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

647 model: "gpt-5.6",

648 input: [

649 {

650 role: "user",

651 content: prompt,

652 },

653 ],

654});

655 

656console.log(response.output_text);

657```

658 

659```python

660from openai import OpenAI

661 

662client = OpenAI()

663 

664prompt = """

665Instructions:

666- Given the React component below, change it so that nonfiction books have red

667 text.

668- Return only the code in your reply

669- Do not include any additional formatting, such as markdown code blocks

670- For formatting, use four space tabs, and do not allow any lines of code to

671 exceed 80 columns

672 

673const books = [

674 { title: 'Dune', category: 'fiction', id: 1 },

675 { title: 'Frankenstein', category: 'fiction', id: 2 },

676 { title: 'Moneyball', category: 'nonfiction', id: 3 },

677];

678 

679export default function BookList() {

680 const listItems = books.map(book =>

681 <li>

682 {book.title}

683 </li>

684 );

685 

686 return (

687 <ul>{listItems}</ul>

688 );

689}

690"""

691 

692response = client.responses.create(

693 model="gpt-5.6",

694 input=[

695 {

696 "role": "user",

697 "content": prompt,

698 }

699 ],

700)

701 

702print(response.output_text)

703```

704 

705 

706

707 

708

709 

710

711Coding (planning)

712 

713

714 

715OpenAI o-series models are also adept in creating multi-step plans. This example prompt asks o1 to create a filesystem structure for a full solution, along with Python code that implements the desired use case.

716 

717 

718 

719 

720 Plan and create a Python project

721 

722```javascript

723import OpenAI from "openai";

724 

725const openai = new OpenAI();

726 

727const prompt = `

728I want to build a Python app that takes user questions and looks

729them up in a database where they are mapped to answers. If there

730is close match, it retrieves the matched answer. If there isn't,

731it asks the user to provide an answer and stores the

732question/answer pair in the database. Make a plan for the directory

733structure you'll need, then return each file in full. Only supply

734your reasoning at the beginning and end, not throughout the code.

735`.trim();

736 

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

738 model: "gpt-5.6",

739 input: [

740 {

741 role: "user",

742 content: prompt,

743 },

744 ],

745});

746 

747console.log(response.output_text);

748```

749 

750```python

751from openai import OpenAI

752 

753client = OpenAI()

754 

755prompt = """

756I want to build a Python app that takes user questions and looks

757them up in a database where they are mapped to answers. If there

758is close match, it retrieves the matched answer. If there isn't,

759it asks the user to provide an answer and stores the

760question/answer pair in the database. Make a plan for the directory

761structure you'll need, then return each file in full. Only supply

762your reasoning at the beginning and end, not throughout the code.

763"""

764 

765response = client.responses.create(

766 model="gpt-5.6",

767 input=[

768 {

769 "role": "user",

770 "content": prompt,

771 }

772 ],

773)

774 

775print(response.output_text)

776```

777 

778 

779

780 

781

782 

783

784STEM Research

785 

786

787 

788OpenAI o-series models have shown excellent performance in STEM research. Prompts asking for support of basic research tasks should show strong results.

789 

790 

791 

792 

793 Ask questions related to basic scientific research

794 

795```javascript

796import OpenAI from "openai";

797 

798const openai = new OpenAI();

799 

800const prompt = `

801What are three compounds we should consider investigating to

802advance research into new antibiotics? Why should we consider

803them?

804`;

805 

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

807 model: "gpt-5.6",

808 input: [

809 {

810 role: "user",

811 content: prompt,

812 },

813 ],

814});

815 

816console.log(response.output_text);

817```

818 

819```python

820from openai import OpenAI

821 

822client = OpenAI()

823 

824prompt = """

825What are three compounds we should consider investigating to

826advance research into new antibiotics? Why should we consider

827them?

828"""

829 

830response = client.responses.create(

831 model="gpt-5.6", input=[{"role": "user", "content": prompt}]

832)

833 

834print(response.output_text)

835```

836 

837 

838 

839## Use case examples

840 

841Some examples of using reasoning models for real-world use cases can be found in [the cookbook](https://developers.openai.com/cookbook).

842 

843[Using reasoning for data validation

625 844 

626 845 

627</a>

628 846 

629<a847 Evaluate a synthetic medical data set for discrepancies.](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_data_validation)

630 href="https://cookbook.openai.com/examples/o1/using_reasoning_for_routine_generation"

631 target="_blank"

632 rel="noreferrer"

633>

634 848 

849[Using reasoning for routine generation

635 850 

636<span slot="icon">

637 </span>

638 Use help center articles to generate actions that an agent could perform.

639 851 

640 852 

641</a>853 Use help center articles to generate actions that an agent could perform.](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_routine_generation)

Details

1# Reasoning best practices1# Reasoning best practices

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.

4 

3OpenAI offers two types of models: [reasoning models](https://developers.openai.com/api/docs/models#o4-mini) (o3 and o4-mini, for example) and [GPT models](https://developers.openai.com/api/docs/models#gpt-4.1) (like GPT-4.1). These model families behave differently.5OpenAI offers two types of models: [reasoning models](https://developers.openai.com/api/docs/models#o4-mini) (o3 and o4-mini, for example) and [GPT models](https://developers.openai.com/api/docs/models#gpt-4.1) (like GPT-4.1). These model families behave differently.

4 6 

5This guide covers:7This guide covers:


33 35 

34![GPT models pair well with o-series models](https://cdn.openai.com/API/docs/images/customer-service-example.png)36![GPT models pair well with o-series models](https://cdn.openai.com/API/docs/images/customer-service-example.png)

35 37 

36<small>38 

39 

37 40 

38_Our GPT-4o and GPT-4o mini models triage order details with customer information, identify the order issues and the return policy, and then feed all of these data points into o3-mini to make the final decision about the viability of the return based on policy._41_Our GPT-4o and GPT-4o mini models triage order details with customer information, identify the order issues and the return policy, and then feed all of these data points into o3-mini to make the final decision about the viability of the return based on policy._

39 42 

40</small>43 

44 

41 45 

42## When to use our reasoning models46## When to use our reasoning models

43 47 


123 127 

124## How to prompt reasoning models effectively128## How to prompt reasoning models effectively

125 129 

126These models perform best with straightforward prompts. Some prompt engineering techniques, like instructing the model to "think step by step," may not enhance performance (and can sometimes hinder it). See best practices below, or [get started with prompt examples](https://developers.openai.com/api/docs/guides/reasoning/advice-on-prompting#prompt-examples).130These models perform best with straightforward prompts. Some prompt engineering techniques, like instructing the model to "think step by step," may not enhance performance (and can sometimes hinder it). See best practices below, or [get started with prompt examples](https://developers.openai.com/api/docs/guides/reasoning#advice-on-prompting).

127 131 

128- **Developer messages are the new system messages**: Starting with `o1-2024-12-17`, reasoning models support developer messages rather than system messages, to align with the chain of command behavior described in the [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#follow-the-chain-of-command).132- **Developer messages are the new system messages**: Starting with `o1-2024-12-17`, reasoning models support developer messages rather than system messages, to align with the chain of command behavior described in the [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#follow-the-chain-of-command).

129- **Keep prompts simple and direct**: The models excel at understanding and responding to brief, clear instructions.133- **Keep prompts simple and direct**: The models excel at understanding and responding to brief, clear instructions.


138 142 

139With the introduction of `o3` and `o4-mini` models, persisted reasoning items in the Responses API are treated differently. Previously (for `o1`, `o3-mini`, `o1-mini` and `o1-preview`), reasoning items were always ignored in follow‑up API requests, even if they were included in the input items of the requests. With `o3` and `o4-mini`, some reasoning items adjacent to function calls are included in the model’s context to help improve model performance while using the least amount of reasoning tokens.143With the introduction of `o3` and `o4-mini` models, persisted reasoning items in the Responses API are treated differently. Previously (for `o1`, `o3-mini`, `o1-mini` and `o1-preview`), reasoning items were always ignored in follow‑up API requests, even if they were included in the input items of the requests. With `o3` and `o4-mini`, some reasoning items adjacent to function calls are included in the model’s context to help improve model performance while using the least amount of reasoning tokens.

140 144 

141For the best results with this change, we recommend using the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) with the `store` parameter set to `true`, and passing in all reasoning items from previous requests (either using `previous_response_id`, or by taking all the output items from an older request and passing them in as input items for a new one). OpenAI will automatically include any relevant reasoning items in the model's context and ignore any irrelevant ones. In more advanced use‑cases where you’d like to manage what goes into the model's context more precisely, we recommend that you at least include all reasoning items between the latest function call and the previous user message. Doing this will ensure that the model doesn’t have to restart its reasoning when you respond to a function call, resulting in better function‑calling performance and lower overall token usage.145For the best results with this change, we recommend using the [Responses API](https://developers.openai.com/api/reference/resources/responses) with the `store` parameter set to `true`, and passing in all reasoning items from previous requests (either using `previous_response_id`, or by taking all the output items from an older request and passing them in as input items for a new one). OpenAI will automatically include any relevant reasoning items in the model's context and ignore any irrelevant ones. In more advanced use‑cases where you’d like to manage what goes into the model's context more precisely, we recommend that you at least include all reasoning items between the latest function call and the previous user message. Doing this will ensure that the model doesn’t have to restart its reasoning when you respond to a function call, resulting in better function‑calling performance and lower overall token usage.

142 146 

143If you’re using the Chat Completions API, reasoning items are never included in the context of the model. This is because Chat Completions is a stateless API. This will result in slightly degraded model performance and greater reasoning token usage in complex agentic cases involving many function calls. In instances where complex multiple function calling is not involved, there should be no degradation in performance regardless of the API being used.147If you’re using the Chat Completions API, reasoning items are never included in the context of the model. This is because Chat Completions is a stateless API. This will result in slightly degraded model performance and greater reasoning token usage in complex agentic cases involving many function calls. In instances where complex multiple function calling is not involved, there should be no degradation in performance regardless of the API being used.

144 148 


150- [Reasoning guide](https://developers.openai.com/api/docs/guides/reasoning)154- [Reasoning guide](https://developers.openai.com/api/docs/guides/reasoning)

151- [How to use reasoning for validation](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_data_validation)155- [How to use reasoning for validation](https://developers.openai.com/cookbook/examples/o1/using_reasoning_for_data_validation)

152- [Video course: Reasoning with o1](https://www.deeplearning.ai/short-courses/reasoning-with-o1/)156- [Video course: Reasoning with o1](https://www.deeplearning.ai/short-courses/reasoning-with-o1/)

153- [Papers on advanced prompting to improve reasoning](https://developers.openai.com/cookbook/related_resources#papers-on-advanced-prompting-to-improve-reasoning)

157- [Papers on advanced prompting to improve reasoning](https://developers.openai.com/cookbook/articles/related_resources#papers-on-advanced-prompting-to-improve-reasoning)

Details

1# Red teaming1# Red teaming

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.

4 

3Red teaming uses adversarial test cases to help uncover unsafe, insecure, or policy-violating behavior before deployment. It complements evals by focusing on misuse cases, failure modes, and high-risk interactions that ordinary quality testing may not expose.5Red teaming uses adversarial test cases to help uncover unsafe, insecure, or policy-violating behavior before deployment. It complements evals by focusing on misuse cases, failure modes, and high-risk interactions that ordinary quality testing may not expose.

4 6 

5<strong>Important:</strong> Only submit to OpenAI Red Teaming code or other7**Important:** Only submit to OpenAI Red Teaming code or other

6 assets that you own or are expressly authorized to test. Do not use OpenAI Red8 assets that you own or are expressly authorized to test. Do not use OpenAI Red

7 Teaming to analyze or report vulnerabilities in open-source or any third-party9 Teaming to analyze or report vulnerabilities in open-source or any third-party

8 code without OpenAI's express written permission.10 code without OpenAI's express written permission.

Details

1# Reinforcement fine-tuning1# Reinforcement fine-tuning

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.

4 

3Reinforcement fine-tuning (RFT) adapts an OpenAI reasoning model with a feedback signal you define. Like [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning), it tailors the model to your task. The difference is that instead of training on fixed “correct” answers, it relies on a programmable grader that scores every candidate response. The training algorithm then shifts the model’s weights, so high-scoring outputs become more likely and low-scoring ones fade.5Reinforcement fine-tuning (RFT) adapts an OpenAI reasoning model with a feedback signal you define. Like [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning), it tailors the model to your task. The difference is that instead of training on fixed “correct” answers, it relies on a programmable grader that scores every candidate response. The training algorithm then shifts the model’s weights, so high-scoring outputs become more likely and low-scoring ones fade.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).

12 15 

13<br />16 

17 

14 18 

15<table>19<table>

16<tbody>20<tbody>


57It's useful to understand the strengths and weaknesses of reinforcement fine-tuning to identify opportunities and to avoid wasted effort.61It's useful to understand the strengths and weaknesses of reinforcement fine-tuning to identify opportunities and to avoid wasted effort.

58 62 

59- **RFT works best with unambiguous tasks**. Check whether qualified human experts agree on the answers. If conscientious experts working independently (with access only to the same instructions and information as the model) do not converge on the same answers, the task may be too ambiguous and may benefit from revision or reframing.63- **RFT works best with unambiguous tasks**. Check whether qualified human experts agree on the answers. If conscientious experts working independently (with access only to the same instructions and information as the model) do not converge on the same answers, the task may be too ambiguous and may benefit from revision or reframing.

60- **Your task must be compatible with the grading options**. Review [grading options in the API](https://developers.openai.com/api/docs/api-reference/graders) first and verify it's possible to grade your task with them.64- **Your task must be compatible with the grading options**. Review [grading options in the API](https://developers.openai.com/api/reference/resources/graders) first and verify it's possible to grade your task with them.

61- **Your eval results must be variable enough to improve**. Run [evals](https://developers.openai.com/api/docs/guides/evals) before using RFT. If your eval scores between minimum and maximum possible scores, you'll have enough data to work with to reinforce positive answers. If the model you want to fine-tune scores at either the absolute minimum or absolute maximum score, RFT won't be useful to you.65- **Your eval results must be variable enough to improve**. Run [evals](https://developers.openai.com/api/docs/guides/evals) before using RFT. If your eval scores between minimum and maximum possible scores, you'll have enough data to work with to reinforce positive answers. If the model you want to fine-tune scores at either the absolute minimum or absolute maximum score, RFT won't be useful to you.

62- **Your model must have some success at the desired task**. Reinforcement fine-tuning makes gradual changes, sampling many answers and choosing the best ones. If a model has a 0% success rate at a given task, you cannot bootstrap to higher performance levels through RFT.66- **Your model must have some success at the desired task**. Reinforcement fine-tuning makes gradual changes, sampling many answers and choosing the best ones. If a model has a 0% success rate at a given task, you cannot bootstrap to higher performance levels through RFT.

63- **Your task should be guess-proof**. If the model can get a higher reward from a lucky guess, the training signal is too noisy, as the model can get the right answer with an incorrect reasoning process. Reframe your task to make guessing more difficult—for example, by expanding classes into subclasses or revising a multiple choice problem to take open-ended answers.67- **Your task should be guess-proof**. If the model can get a higher reward from a lucky guess, the training signal is too noisy, as the model can get the right answer with an incorrect reasoning process. Reframe your task to make guessing more difficult—for example, by expanding classes into subclasses or revising a multiple choice problem to take open-ended answers.


103 107 

104To perform RFT, define a [grader](https://developers.openai.com/api/docs/guides/graders) to score the model's output during training, indicating the quality of its response. RFT uses the same set of graders as [evals](https://developers.openai.com/api/docs/guides/evals), which you may already be familiar with.108To perform RFT, define a [grader](https://developers.openai.com/api/docs/guides/graders) to score the model's output during training, indicating the quality of its response. RFT uses the same set of graders as [evals](https://developers.openai.com/api/docs/guides/evals), which you may already be familiar with.

105 109 

106In this example, we define [multiple graders](https://developers.openai.com/api/docs/api-reference/graders/multi) to examine the properties of the JSON returned by our fine-tuned model:110In this example, we define [multiple graders](https://developers.openai.com/api/reference/resources/graders) to examine the properties of the JSON returned by our fine-tuned model:

107 111 

108- The [`string_check`](https://developers.openai.com/api/docs/api-reference/graders/string-check) grader to ensure the proper `compliant` property has been set112- The [`string_check`](https://developers.openai.com/api/reference/resources/graders) grader to ensure the proper `compliant` property has been set

109- The [`score_model`](https://developers.openai.com/api/docs/api-reference/graders/score-model) grader to provide a score between zero and one for the explanation text, using another evaluator model113- The [`score_model`](https://developers.openai.com/api/reference/resources/graders) grader to provide a score between zero and one for the explanation text, using another evaluator model

110 114 

111We weight the output of each property equally in the `calculate_output` expression.115We weight the output of each property equally in the `calculate_output` expression.

112 116 


114 118 

115 119 

116 120 

117<div data-content-switcher-pane data-value="grader">121Grader configuration

118 <div class="hidden">Grader configuration</div>122 

119 Multi-grader configuration object123 Multi-grader configuration object

120 124 

121```json125```json


146}150}

147```151```

148 152 

149 </div>153

150 <div data-content-switcher-pane data-value="grader_json" hidden>154 

151 <div class="hidden">Grading prompt</div>155

156 

157

158Grading prompt

159 

152 Grading prompt in the grader config160 Grading prompt in the grader config

153 161 

154```markdown162```markdown


244Model Answer: {{sample.output_json.explanation}}252Model Answer: {{sample.output_json.explanation}}

245```253```

246 254 

247 </div>

248 

249 255 

250 256 

251## Prepare your dataset257## Prepare your dataset

252 258 

253To create an RFT fine-tune, you'll need both a training and test dataset. Both the training and test datasets will share the same [JSONL format](https://jsonlines.org/). Each line in the JSONL data file will contain a `messages` array, along with any additional fields required to grade the output from the model. The full specification for RFT dataset [can be found here](https://developers.openai.com/api/docs/api-reference/fine-tuning/reinforcement-input).259To create an RFT fine-tune, you'll need both a training and test dataset. Both the training and test datasets will share the same [JSONL format](https://jsonlines.org/). Each line in the JSONL data file will contain a `messages` array, along with any additional fields required to grade the output from the model. The full specification for RFT dataset [can be found here](https://developers.openai.com/api/reference/resources/fine_tuning).

254 260 

255In our case, in addition to the `messages` array, each line in our JSONL file also needs `compliant` and `explanation` properties, which we can use as reference values to test the fine-tuned model's Structured Output.261In our case, in addition to the `messages` array, each line in our JSONL file also needs `compliant` and `explanation` properties, which we can use as reference values to test the fine-tuned model's Structured Output.

256 262 


297 303 

298### Upload your files304### Upload your files

299 305 

300The process for uploading RFT training and test data files is the same as [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning). Upload your training data to OpenAI either through the [API](https://developers.openai.com/api/docs/api-reference/files/create) or [using our UI](https://platform.openai.com/storage). Files must be uploaded with a purpose of `fine-tune` in order to be used with fine-tuning.306The process for uploading RFT training and test data files is the same as [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning). Upload your training data to OpenAI either through the [API](https://developers.openai.com/api/reference/resources/files/methods/create) or [using our UI](https://platform.openai.com/storage). Files must be uploaded with a purpose of `fine-tune` in order to be used with fine-tuning.

301 307 

302**You need file IDs for both your test and training data files** to create a fine-tune job.308**You need file IDs for both your test and training data files** to create a fine-tune job.

303 309 

304## Create a fine-tune job310## Create a fine-tune job

305 311 

306Create a fine-tune job using either the [API](https://developers.openai.com/api/docs/api-reference/fine-tuning) or [fine-tuning dashboard](https://platform.openai.com/finetune). To do this, you need:312Create a fine-tune job using either the [API](https://developers.openai.com/api/reference/resources/fine_tuning) or [fine-tuning dashboard](https://platform.openai.com/finetune). To do this, you need:

307 313 

308- File IDs for both your training and test datasets314- File IDs for both your training and test datasets

309- The grader configuration we created earlier315- The grader configuration we created earlier


337 343 

338Generating a JSON schema from a Pydantic model344Generating a JSON schema from a Pydantic model

339 345 

340To simplify JSON schema generation, start from a <a href="https://docs.pydantic.dev/latest/api/base_model/">Pydantic BaseModel</a> class:346To simplify JSON schema generation, start from a [Pydantic BaseModel](https://docs.pydantic.dev/latest/api/base_model/) class:

341 347 

3421. Define your class3481. Define your class

3431. Use `to_strict_json_schema` from the OpenAI library to generate a valid schema3491. Use `to_strict_json_schema` from the OpenAI library to generate a valid schema


437```443```

438 444 

439 445 

440This request returns a [fine-tuning job object](https://developers.openai.com/api/docs/api-reference/fine-tuning/object), which includes a job `id`. Use this ID to monitor the progress of your job and retrieve the fine-tuned model when the job is complete.446This request returns a [fine-tuning job object](https://developers.openai.com/api/reference/resources/fine_tuning), which includes a job `id`. Use this ID to monitor the progress of your job and retrieve the fine-tuned model when the job is complete.

441 447 

442To qualify for [data sharing inference pricing](https://developers.openai.com/api/docs/pricing#fine-tuning), make sure to [share evaluation and fine-tuning data](https://help.openai.com/en/articles/10306912-sharing-feedback-evaluation-and-fine-tuning-data-and-api-inputs-and-outputs-with-openai#h_c93188c569) with OpenAI before creating the job. You can verify the job was marked as shared by confirming `shared_with_openai` is set to `true`.448To qualify for [data sharing inference pricing](https://developers.openai.com/api/docs/pricing#fine-tuning), make sure to [share evaluation and fine-tuning data](https://help.openai.com/en/articles/10306912-sharing-feedback-evaluation-and-fine-tuning-data-and-api-inputs-and-outputs-with-openai#h_c93188c569) with OpenAI before creating the job. You can verify the job was marked as shared by confirming `shared_with_openai` is set to `true`.

443 449 

444### Monitoring your fine-tune job450### Monitoring your fine-tune job

445 451 

446Fine-tuning jobs take some time to complete, and RFT jobs tend to take longer than SFT or DPO jobs. To monitor the progress of your fine-tune job, use the [fine-tuning dashboard](https://platform.openai.com/finetune) or the [API](https://developers.openai.com/api/docs/api-reference/fine-tuning).452Fine-tuning jobs take some time to complete, and RFT jobs tend to take longer than SFT or DPO jobs. To monitor the progress of your fine-tune job, use the [fine-tuning dashboard](https://platform.openai.com/finetune) or the [API](https://developers.openai.com/api/reference/resources/fine_tuning).

447 453 

448#### Reward metrics454#### Reward metrics

449 455 


474 480 

475### Try using your fine-tuned model481### Try using your fine-tuned model

476 482 

477Evaluate your newly optimized model by using it! When the fine-tuned model finishes training, use its ID in either the [Responses](https://developers.openai.com/api/docs/api-reference/responses) or [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat) API, just as you would an OpenAI base model.483Evaluate your newly optimized model by using it! When the fine-tuned model finishes training, use its ID in either the [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) API, just as you would an OpenAI base model.

484 

478 485 

479 486 

487Use your model in the Playground

480 488 

481<div data-content-switcher-pane data-value="ui">489

482 <div class="hidden">Use your model in the Playground</div>490 

483 </div>4911. Navigate to your fine-tuning job in [the dashboard](https://platform.openai.com/finetune).

484 <div data-content-switcher-pane data-value="api" hidden>4921. In the right pane, navigate to **Output model** and copy the model ID. It should start with `ft:…`

485 <div class="hidden">Use your model with an API call</div>4931. Open the [Playground](https://platform.openai.com/playground).

486 </div>4941. In the **Model** dropdown menu, paste the model ID. Here, you should also see other fine-tuned models you've created.

4951. Run some prompts and see how your fine-tuned performs!

496 

497 

498

499 

500

501 

502

503Use your model with an API call

504 

505

506 

507```bash

508curl https://api.openai.com/v1/responses \

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

510 -H "Authorization: Bearer $OPENAI_API_KEY" \

511 -d '{

512 "model": "ft:gpt-4.1-nano-2025-04-14:openai::BTz2REMH",

513 "input": "What is 4+4?"

514 }'

515```

487 516 

488 517 

489 518 


493 522 

494 523 

495 524 

496<div data-content-switcher-pane data-value="ui">525Find checkpoints in the dashboard

497 <div class="hidden">Find checkpoints in the dashboard</div>526 

498 </div>527

499 <div data-content-switcher-pane data-value="api" hidden>528 

500 <div class="hidden">Query the API for checkpoints</div>5291. Navigate to the [fine-tuning dashboard](https://platform.openai.com/finetune).

501 </div>5301. In the left panel, select the job you want to investigate. Wait until it succeeds.

5311. In the right panel, scroll to the list of checkpoints.

5321. Hover over any checkpoint to see a link to launch in the Playground.

5331. Test the checkpoint model's behavior by prompting it in the Playground.

534 

535 

536

537 

538

539 

540

541Query the API for checkpoints

542 

543

544 

5451. Wait until a job succeeds, which you can verify by [querying the status of a job](https://developers.openai.com/api/reference/resources/fine_tuning).

5461. [Query the checkpoints endpoint](https://developers.openai.com/api/reference/resources/fine_tuning/subresources/jobs/subresources/checkpoints/methods/list) with your fine-tuning job ID to access a list of model checkpoints for the fine-tuning job.

5471. Find the `fine_tuned_model_checkpoint` field for the name of the model checkpoint.

5481. Use this model just like you would the final fine-tuned model.

549 

550The checkpoint object contains `metrics` data to help you determine the usefulness of this model. As an example, the response looks like this:

551 

552```json

553{

554 "object": "fine_tuning.job.checkpoint",

555 "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB",

556 "created_at": 1519129973,

557 "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom-suffix:96olL566:ckpt-step-2000",

558 "metrics": {

559 "full_valid_loss": 0.134,

560 "full_valid_mean_token_accuracy": 0.874

561 },

562 "fine_tuning_job_id": "ftjob-abc123",

563 "step_number": 2000

564}

565```

566 

567Each checkpoint specifies:

568 

569- `step_number`: The step at which the checkpoint was created (where each epoch is number of steps in the training set divided by the batch size)

570- `metrics`: An object containing the metrics for your fine-tuning job at the step when the checkpoint was created

502 571 

503 572 

504 573 


530 599 

531How to pass safety checks600How to pass safety checks

532 601 

533In addition to reviewing any failed safety checks in the fine-tuning job object, you can retrieve details about which categories failed by querying the [fine-tuning API events endpoint](https://developers.openai.com/api/docs/api-reference/fine-tuning/list-events). Look for events of type `moderation_checks` for details about category results and enforcement. This information can help you narrow down which categories to target for retraining and improvement. The [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#overview) has rules and examples that can help identify areas for additional training data.602In addition to reviewing any failed safety checks in the fine-tuning job object, you can retrieve details about which categories failed by querying the [fine-tuning API events endpoint](https://developers.openai.com/api/reference/resources/fine_tuning/subresources/jobs/methods/list). Look for events of type `moderation_checks` for details about category results and enforcement. This information can help you narrow down which categories to target for retraining and improvement. The [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#overview) has rules and examples that can help identify areas for additional training data.

534 603 

535While these evaluations cover a broad range of safety categories, conduct your own evaluations of the fine-tuned model to ensure it's appropriate for your use case.604While these evaluations cover a broad range of safety categories, conduct your own evaluations of the fine-tuned model to ensure it's appropriate for your use case.

536 605 


538 607 

539Now that you know the basics of reinforcement fine-tuning, explore other fine-tuning methods.608Now that you know the basics of reinforcement fine-tuning, explore other fine-tuning methods.

540 609 

541[610[Supervised fine-tuning

611 

612 

613 

614 Fine-tune a model by providing correct outputs for sample inputs.](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

542 615 

543<span slot="icon">616[Vision fine-tuning

544 </span>

545 Fine-tune a model by providing correct outputs for sample inputs.

546 617 

547](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

548 618 

549[

550 619 

551<span slot="icon">620 Learn to fine-tune for computer vision with image inputs.](https://developers.openai.com/api/docs/guides/vision-fine-tuning)

552 </span>

553 Learn to fine-tune for computer vision with image inputs.

554 621 

555](https://developers.openai.com/api/docs/guides/vision-fine-tuning)622[Direct preference optimization

556 623 

557[

558 624 

559<span slot="icon">

560 </span>

561 Fine-tune a model using direct preference optimization (DPO).

562 625 

563](https://developers.openai.com/api/docs/guides/direct-preference-optimization)626 Fine-tune a model using direct preference optimization (DPO).](https://developers.openai.com/api/docs/guides/direct-preference-optimization)

564 627 

565## Appendix628## Appendix

566 629 

567### Training metrics630### Training metrics

568 631 

569Reinforcement fine-tuning jobs publish per-step training metrics as [fine-tuning events](https://developers.openai.com/api/docs/api-reference/fine-tuning/event-object). Pull these metrics through the [API](https://developers.openai.com/api/docs/api-reference/fine-tuning/list-events) or view them as graphs and charts in the [fine-tuning dashboard](https://platform.openai.com/finetune).632Reinforcement fine-tuning jobs publish per-step training metrics as [fine-tuning events](https://developers.openai.com/api/reference/resources/fine_tuning). Pull these metrics through the [API](https://developers.openai.com/api/reference/resources/fine_tuning/subresources/jobs/methods/list) or view them as graphs and charts in the [fine-tuning dashboard](https://platform.openai.com/finetune).

570 633 

571Learn more about training metrics below.634Learn more about training metrics below.

572 635 


681 744 

682The top-level metrics to watch are `train_reward_mean` and `valid_reward_mean`, which indicate the average reward assigned by your graders across all samples in the training and validation datasets, respectively.745The top-level metrics to watch are `train_reward_mean` and `valid_reward_mean`, which indicate the average reward assigned by your graders across all samples in the training and validation datasets, respectively.

683 746 

684Additionally, if you use a [multi-grader](https://developers.openai.com/api/docs/api-reference/graders/multi) configuration, per-grader train and validation reward metrics will be published as well. These metrics are included under the `event.data.scores` object in the fine-tuning events object, with one entry per grader. The per-grader metrics are useful for understanding how the model is performing on each individual grader, and can help you identify if the model is overfitting to one grader or another.747Additionally, if you use a [multi-grader](https://developers.openai.com/api/reference/resources/graders) configuration, per-grader train and validation reward metrics will be published as well. These metrics are included under the `event.data.scores` object in the fine-tuning events object, with one entry per grader. The per-grader metrics are useful for understanding how the model is performing on each individual grader, and can help you identify if the model is overfitting to one grader or another.

685 748 

686From the fine-tuning dashboard, the individual grader metrics will be displayed in their own graph below the overall `train_reward_mean` and `valid_reward_mean` metrics.749From the fine-tuning dashboard, the individual grader metrics will be displayed in their own graph below the overall `train_reward_mean` and `valid_reward_mean` metrics.

687 750 


733 796 

734As validation steps are performed, the input prompts, model samples, grader outputs, and more metadata will be combined to make a new [eval run](https://developers.openai.com/api/docs/guides/evals#creating-an-eval-run) for that step. At the end of the job, you will have one run for each validation step. This allows you to compare the performance of the model at different steps, and to see how the model's behavior has changed over the course of training.797As validation steps are performed, the input prompts, model samples, grader outputs, and more metadata will be combined to make a new [eval run](https://developers.openai.com/api/docs/guides/evals#creating-an-eval-run) for that step. At the end of the job, you will have one run for each validation step. This allows you to compare the performance of the model at different steps, and to see how the model's behavior has changed over the course of training.

735 798 

736You can find the eval associated with your fine-tuning job by viewing your job on the fine-tuning dashboard, or by finding the `eval_id` field on the [fine-tuning job object](https://developers.openai.com/api/docs/api-reference/fine-tuning/object).799You can find the eval associated with your fine-tuning job by viewing your job on the fine-tuning dashboard, or by finding the `eval_id` field on the [fine-tuning job object](https://developers.openai.com/api/reference/resources/fine_tuning).

737 800 

738The evals product is useful for inspecting the outputs of the model on specific datapoints, to get an understanding for how the model is behaving in different scenarios. It can help you figure out which slice of your dataset the model is performing poorly on which can help you identify areas for improvement in your training data.801The evals product is useful for inspecting the outputs of the model on specific datapoints, to get an understanding for how the model is behaving in different scenarios. It can help you figure out which slice of your dataset the model is performing poorly on which can help you identify areas for improvement in your training data.

739 802 


741 804 

742### Pausing and resuming jobs805### Pausing and resuming jobs

743 806 

744You can pause a fine-tuning job at any time by using the [fine-tuning jobs API](https://developers.openai.com/api/docs/api-reference/fine-tuning/pause). Calling the pause API will tell the training process to create a new model snapshot, stop training, and put the job into a "Paused" state. The model snapshot will go through a normal safety screening process after which it will be available for you to use throughout the OpenAI platform as a normal fine-tuned model.807You can pause a fine-tuning job at any time by using the [fine-tuning jobs API](https://developers.openai.com/api/reference/resources/fine_tuning). Calling the pause API will tell the training process to create a new model snapshot, stop training, and put the job into a "Paused" state. The model snapshot will go through a normal safety screening process after which it will be available for you to use throughout the OpenAI platform as a normal fine-tuned model.

745 808 

746If you wish to continue the training process for a paused job, you can do so by using the [fine-tuning jobs API](https://developers.openai.com/api/docs/api-reference/fine-tuning/resume). This will resume the training process from the last checkpoint created when the job was paused and will continue training until the job is either completed or paused again.809If you wish to continue the training process for a paused job, you can do so by using the [fine-tuning jobs API](https://developers.openai.com/api/reference/resources/fine_tuning). This will resume the training process from the last checkpoint created when the job was paused and will continue training until the job is either completed or paused again.

747 810 

748### Grading with Tools811### Grading with Tools

749 812 

750If you are training your model to [perform tool calls](https://developers.openai.com/api/docs/guides/function-calling), you will need to:813If you are training your model to [perform tool calls](https://developers.openai.com/api/docs/guides/function-calling), you will need to:

751 814 

7521. Provide the set of tools available for your model to call on each datapoint in the RFT training dataset. More info here in the [dataset API reference](https://developers.openai.com/api/docs/api-reference/fine-tuning/reinforcement-input).8151. Provide the set of tools available for your model to call on each datapoint in the RFT training dataset. More info here in the [dataset API reference](https://developers.openai.com/api/reference/resources/fine_tuning).

7532. Configure your grader to assign rewards based on the contents of the tool calls made by the model. Information on grading tools calls can be found [here in the grading docs](https://developers.openai.com/api/docs/guides/graders/#sample-namespace)8162. Configure your grader to assign rewards based on the contents of the tool calls made by the model. Information on grading tools calls can be found [here in the grading docs](https://developers.openai.com/api/docs/guides/graders/#sample-namespace)

754 817 

755### Billing details818### Billing details

Details

1# Multi-agent1# Multi-agent

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.

4 

3## Overview5## Overview

4 6 

5Multi-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.

guides/retrieval.md +128 −70

Details

1# Retrieval1# Retrieval

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.

4 

3The **Retrieval API** allows you to perform [**semantic search**](#semantic-search) over your data, which is a technique that surfaces semantically similar results—even when they match few or no keywords. Retrieval is useful on its own, but is especially powerful when combined with our models to synthesize responses.5The **Retrieval API** allows you to perform [**semantic search**](#semantic-search) over your data, which is a technique that surfaces semantically similar results—even when they match few or no keywords. Retrieval is useful on its own, but is especially powerful when combined with our models to synthesize responses.

4 6 

5![Retrieval depiction](https://cdn.openai.com/API/docs/images/retrieval-depiction.png)7![Retrieval depiction](https://cdn.openai.com/API/docs/images/retrieval-depiction.png)


204 206 

205 207 

206 208 

207<div data-content-switcher-pane data-value="region">209Region

208 <div class="hidden">Region</div>210 

209 Filter for a region211 Filter for a region

210 212 

211```json213```json


216}218}

217```219```

218 220 

219 </div>221

220 <div data-content-switcher-pane data-value="date-range" hidden>222 

221 <div class="hidden">Date range</div>223

224 

225

226Date range

227 

222 Filter for a date range228 Filter for a date range

223 229 

224```json230```json


239}245}

240```246```

241 247 

242 </div>248

243 <div data-content-switcher-pane data-value="filename" hidden>249 

244 <div class="hidden">Filenames</div>250

251 

252

253Filenames

254 

245 Filter to match any of a set of filenames255 Filter to match any of a set of filenames

246 256 

247```json257```json


252}262}

253```263```

254 264 

255 </div>265

256 <div data-content-switcher-pane data-value="exclude-filenames" hidden>266 

257 <div class="hidden">Exclude filenames</div>267

268 

269

270Exclude filenames

271 

258 Filter to exclude drafts by filename272 Filter to exclude drafts by filename

259 273 

260```json274```json


265}279}

266```280```

267 281 

268 </div>282

269 <div data-content-switcher-pane data-value="date-range-and-region" hidden>283 

270 <div class="hidden">Complex</div>284

285 

286

287Complex

288 

271 Filter for top secret projects with certain names in english289 Filter for top secret projects with certain names in english

272 290 

273```json291```json


308}326}

309```327```

310 328 

311 </div>

312 

313 329 

314 330 

315### Ranking331### Ranking


322 338 

323Vector stores contain `vector_store_file` objects, which are backed by a `file` object.339Vector stores contain `vector_store_file` objects, which are backed by a `file` object.

324 340 

325| <div style={{ minWidth: '150px', whiteSpace: 'nowrap' }}>Object type</div> | Description |341| Object type | Description |

326| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |342| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

327| `file` | Represents content uploaded through the [Files API](https://developers.openai.com/api/docs/api-reference/files). Often used with vector stores, but also for fine-tuning and other use cases. |343| `file` | Represents content uploaded through the [Files API](https://developers.openai.com/api/reference/resources/files). Often used with vector stores, but also for fine-tuning and other use cases. |

328| `vector_store` | Container for searchable files. |344| `vector_store` | Container for searchable files. |

329| `vector_store.file` | Wrapper type specifically representing a `file` that has been chunked and embedded, and has been associated with a `vector_store`. <br/>Contains `attributes` map used for filtering. |345| `vector_store.file` | Wrapper type specifically representing a `file` that has been chunked and embedded, and has been associated with a `vector_store`. <br />Contains `attributes` map used for filtering. |

330 346 

331### Pricing347### Pricing

332 348 


343 359 

344 360 

345 361 

346<div data-content-switcher-pane data-value="create">362Create

347 <div class="hidden">Create</div>363 

348 Create vector store364 Create vector store

349 365 

350```python366```python


361});377});

362```378```

363 379 

364 </div>380

365 <div data-content-switcher-pane data-value="retrieve" hidden>381 

366 <div class="hidden">Retrieve</div>382

383 

384

385Retrieve

386 

367 Retrieve vector store387 Retrieve vector store

368 388 

369```python389```python


378});398});

379```399```

380 400 

381 </div>401

382 <div data-content-switcher-pane data-value="update" hidden>402 

383 <div class="hidden">Update</div>403

404 

405

406Update

407 

384 Update vector store408 Update vector store

385 409 

386```python410```python


397});421});

398```422```

399 423 

400 </div>424

401 <div data-content-switcher-pane data-value="delete" hidden>425 

402 <div class="hidden">Delete</div>426

427 

428

429Delete

430 

403 Delete vector store431 Delete vector store

404 432 

405```python433```python


414});442});

415```443```

416 444 

417 </div>445

418 <div data-content-switcher-pane data-value="list" hidden>446 

419 <div class="hidden">List</div>447

448 

449

450List

451 

420 List vector stores452 List vector stores

421 453 

422```python454```python


427await client.vector_stores.list();459await client.vector_stores.list();

428```460```

429 461 

430 </div>

431 

432 462 

433 463 

434### Vector store file operations464### Vector store file operations

435 465 

436Some operations, like `create` for `vector_store.file`, are asynchronous and may take time to complete—use our helper functions, like `create_and_poll` to block until it is. Otherwise, you may check the status. Removing files from a vector store is eventually consistent, and search results may still include content from a removed file for a short period.466Some operations, like `create` for `vector_store.file`, are asynchronous and may take time to complete—use our helper functions, like `create_and_poll` to block until it is. Otherwise, you may check the status. Removing files from a vector store is eventually consistent, and search results may still include content from a removed file for a short period.

437 467 

438Adding files is rate limited per vector store ID. Requests to [`/vector_stores/{vector_store_id}/files`](https://developers.openai.com/api/docs/api-reference/vector-stores/createFile) and [`/vector_stores/{vector_store_id}/file_batches`](https://developers.openai.com/api/docs/api-reference/vector-stores/createBatch) share a per-vector-store limit of 300 requests per minute.468Adding files is rate limited per vector store ID. Requests to [`/vector_stores/{vector_store_id}/files`](https://developers.openai.com/api/reference/resources/vector_stores/subresources/files/methods/create) and [`/vector_stores/{vector_store_id}/file_batches`](https://developers.openai.com/api/reference/resources/vector_stores/subresources/file_batches/methods/create) share a per-vector-store limit of 300 requests per minute.

439 469 

440 470 

441 471 

442<div data-content-switcher-pane data-value="create">472Create

443 <div class="hidden">Create</div>473 

444 Create vector store file474 Create vector store file

445 475 

446```python476```python


457});487});

458```488```

459 489 

460 </div>490

461 <div data-content-switcher-pane data-value="upload" hidden>491 

462 <div class="hidden">Upload</div>492

493 

494

495Upload

496 

463 Upload vector store file497 Upload vector store file

464 498 

465```python499```python


476});510});

477```511```

478 512 

479 </div>513

480 <div data-content-switcher-pane data-value="retrieve" hidden>514 

481 <div class="hidden">Retrieve</div>515

516 

517

518Retrieve

519 

482 Retrieve vector store file520 Retrieve vector store file

483 521 

484```python522```python


495});533});

496```534```

497 535 

498 </div>536

499 <div data-content-switcher-pane data-value="update" hidden>537 

500 <div class="hidden">Update</div>538

539 

540

541Update

542 

501 Update vector store file543 Update vector store file

502 544 

503```python545```python


516});558});

517```559```

518 560 

519 </div>561

520 <div data-content-switcher-pane data-value="delete" hidden>562 

521 <div class="hidden">Delete</div>563

564 

565

566Delete

567 

522 Delete vector store file568 Delete vector store file

523 569 

524```python570```python


535});581});

536```582```

537 583 

538 </div>584

539 <div data-content-switcher-pane data-value="list" hidden>585 

540 <div class="hidden">List</div>586

587 

588

589List

590 

541 List vector store files591 List vector store files

542 592 

543```python593```python


552});602});

553```603```

554 604 

555 </div>

556 

557 605 

558 606 

559### Batch operations607### Batch operations

560 608 

561 609 

562 610 

563<div data-content-switcher-pane data-value="create">611Create

564 <div class="hidden">Create</div>612 

565 Batch create operation613 Batch create operation

566 614 

567```python615```python


604});652});

605```653```

606 654 

607 </div>655

608 <div data-content-switcher-pane data-value="retrieve" hidden>656 

609 <div class="hidden">Retrieve</div>657

658 

659

660Retrieve

661 

610 Batch retrieve operation662 Batch retrieve operation

611 663 

612```python664```python


623});675});

624```676```

625 677 

626 </div>678

627 <div data-content-switcher-pane data-value="cancel" hidden>679 

628 <div class="hidden">Cancel</div>680

681 

682

683Cancel

684 

629 Batch cancel operation685 Batch cancel operation

630 686 

631```python687```python


642});698});

643```699```

644 700 

645 </div>701

646 <div data-content-switcher-pane data-value="list" hidden>702 

647 <div class="hidden">List</div>703

704 

705

706List

707 

648 List files in a batch708 List files in a batch

649 709 

650```python710```python


660});720});

661```721```

662 722 

663 </div>

664 

665 723 

666 724 

667When creating a batch you can either provide `file_ids` with optional `attributes` and/or `chunking_strategy`, or use the `files` array to pass objects that include a `file_id` plus optional `attributes` and `chunking_strategy` for each file. The two options are mutually exclusive so that you can cleanly control whether every file shares the same settings or you need per-file overrides.725When creating a batch you can either provide `file_ids` with optional `attributes` and/or `chunking_strategy`, or use the `files` array to pass objects that include a `file_id` plus optional `attributes` and `chunking_strategy` for each file. The two options are mutually exclusive so that you can cleanly control whether every file shares the same settings or you need per-file overrides.


733 791 

734By default, `max_chunk_size_tokens` is set to `800` and `chunk_overlap_tokens` is set to `400`, meaning every file is indexed by being split up into 800-token chunks, with 400-token overlap between consecutive chunks.792By default, `max_chunk_size_tokens` is set to `800` and `chunk_overlap_tokens` is set to `400`, meaning every file is indexed by being split up into 800-token chunks, with 400-token overlap between consecutive chunks.

735 793 

736You can adjust this by setting [`chunking_strategy`](https://developers.openai.com/api/docs/api-reference/vector-stores-files/createFile#vector-stores-files-createfile-chunking_strategy) when adding files to the vector store. The strategy has certain limitations:794You can adjust this by setting [`chunking_strategy`](https://developers.openai.com/api/reference/resources/vector_stores/subresources/files/methods/create#vector-stores-files-createfile-chunking_strategy) when adding files to the vector store. The strategy has certain limitations:

737 795 

738- `max_chunk_size_tokens` must be between 100 and 4096 inclusive.796- `max_chunk_size_tokens` must be between 100 and 4096 inclusive.

739- `chunk_overlap_tokens` must be non-negative and should not exceed `max_chunk_size_tokens / 2`.797- `chunk_overlap_tokens` must be non-negative and should not exceed `max_chunk_size_tokens / 2`.


840 },898 },

841 {899 {

842 role: "user",900 role: "user",

843 content: `Sources: ${formattedResults}\n\nQuery: '${userQuery}'`901 content: `Sources: ${formattedResults}\n\nQuery: 'What is the return policy?'`

844 }902 }

845 ],903 ],

846});904});

Details

1# Reinforcement fine-tuning use cases1# Reinforcement fine-tuning use cases

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.

4 

3[Reinforcement fine-tuning](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning) (RFT) provides a way to improve your model's performance at specific tasks. The task must be clear and have verifiable answers.5[Reinforcement fine-tuning](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning) (RFT) provides a way to improve your model's performance at specific tasks. The task must be clear and have verifiable answers.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).


30 33 

31 34 

32 35 

33<div data-content-switcher-pane data-value="use-case">36Use case

34 <div class="hidden">Use case</div>37 

35 </div>38

36 <div data-content-switcher-pane data-value="prompt" hidden>39 

37 <div class="hidden">Prompt</div>40> **Company**: [ChipStack](https://www.chipstack.ai) is building the next-generation of AI-powered tools for chip design and verification, aimed at significantly reducing the time and cost of developing and validating complex semiconductor chips.

38 </div>41>

39 <div data-content-switcher-pane data-value="grader" hidden>42> **Problem to solve**: One task that's challenging and time-consuming for humans is binding design interfaces to verification IPs (pre-created verification components that, when properly applied, can significantly enhance quality and coverage of verification). There are many verification IPs, and each can contain dozens to hundreds of signals that may be mapped. Someone must understand this domain well in order to apply the verification IP correctly.

40 <div class="hidden">Grader code</div>43>

41 </div>44> **Objective**: To train OpenAI reasoning models to do this instead, ChipStack prepared a dataset consisting of less than 50 samples, then performed several RFT variations. For the final evaluation report, they ran this evaluation set three times against each model and variation—o1-mini base and fine-tuned, o3-mini base and fine-tuned—and averaged the results per-sample then overall.

42 <div data-content-switcher-pane data-value="review" hidden>45 

43 <div class="hidden">Results</div>46 

44 </div>47

48 

49

50 

51

52Prompt

53 

54

55 

56> Below is a piece of example data provided.

57 

58```

59[

60 {“name”: “BLOCK_SIZE”, “value”: “8”},

61 {“name”: “ADDR_WIDTH”, “value”: “4”}

62]

63```

64 

65 

66

67 

68

69 

70

71Grader code

72 

73

74 

75> Below is a grader definition in Python of a string map, represented as a list of objects with `name` and `value` properties.

76>

77> Conceptually, this is meant to model a type like `Dict[str, str]`.

78 

79```python

80{

81 "type": "python",

82 "name": "donors_caas",

83 "image_tag": "alpha",

84 "source": """from collections import Counter

85 

86def grade(sample: dict[str, str], item: dict[str, str]) -> float:

87 # multisets of (name, value) pairs

88 predicted = sample["output_json"]["predicted"]

89 expected = item["reference_answer"]

90 pred_counts = Counter((d["name"], d["value"]) for d in predicted)

91 exp_counts = Counter((d["name"], d["value"]) for d in expected)

92 

93 true_pos = sum(min(pred_counts[p], exp_counts[p]) for p in pred_counts)

94 pred_total = sum(pred_counts.values())

95 exp_total = sum(exp_counts.values())

96 

97 precision = true_pos / pred_total if pred_total else 0.0

98 recall = true_pos / exp_total if exp_total else 0.0

99 

100 if precision + recall == 0.0:

101 return 0.0

102 return 2 * precision * recall / (precision + recall)""",

103}

104```

105 

106 

107

108 

109

110 

111

112Results

113 

114

115 

116> For both o1-mini and o3-mini, performance improved by ~12 percentage points. The fine-tuned variants got much better about recognizing when not to apply wiring. Many commercial verification IPs can contain hundreds of optional signals, most of which are not meant to be applied.

117>

118> "Thanks to powerful base models and easy-to-use Reinforced Fine-Tuning APIs, we were able to significantly boost performance on our task with a small set of high-quality samples."

119>

120> —[ChipStack](https://www.chipstack.ai), next-generation of AI-powered tools for chip design and verification

45 121 

46 122 

47 123 


49 125 

50 126 

51 127 

52<div data-content-switcher-pane data-value="use-case">128Use case

53 <div class="hidden">Use case</div>129 

54 </div>130

55 <div data-content-switcher-pane data-value="grader" hidden>131 

56 <div class="hidden">Grader code</div>132> **Company**: [Runloop](https://www.runloop.ai) is a platform for AI-powered coding agents to be deployed into production and built with public and custom benchmarking capabilities to refine performance.

57 </div>133>

58 <div data-content-switcher-pane data-value="review" hidden>134> **Problem to solve**: Runloop wanted to improve model performance at using third-party APIs, such as the Stripe API, which can be large and complex without a human in the loop. If they could train a model to use the Stripe API, Runloop could turn economically impactful business cases into working code.

59 <div class="hidden">Results</div>135>

60 </div>136> **Objective**: Their goal was teaching the model to master usage of the Stripe API, including writing complete code snippets for arbitrary user requests by either adapting information from existing integration guides, merging information from multiple guides, or inferring information not explicitly stated in the guides. They used RFT with two primary rewards:

137>

138> 1. Reward the model for outputting the answer in a Markdown format that aligns with expectation of how a "dynamic" integration guide should look.

139> 1. Reward the model for producing "correct" code snippets by validating the outputted code via AST Grep. This allows them to confirm the model is making the correct Stripe SDK calls with the correct parameters and in some cases even in the correct order.

140 

141 

142

143 

144

145 

146

147Grader code

148 

149

150 

151````python

152# Note this file gets uploaded to the OpenAI API as a grader

153from ast_grep_py import SgRoot

154from pydantic import BaseModel, Field # type: ignore

155from typing import Any, List, Optional

156import re

157 

158SUPPORTED_LANGUAGES = ['typescript', 'javascript', 'ts', 'js']

159 

160class CodeBlock(BaseModel):

161 language: str = Field(

162 description="Programming language of the code block (e.g., 'python', 'javascript')",

163 examples=["python", "javascript", "typescript"]

164 )

165 path: str = Field(

166 description="Target file path where the code should be written",

167 examples=["main.py", "src/app.js", "index.html"]

168 )

169 code: str = Field(

170 description="Actual code content extracted from the code block"

171 )

172 

173class ASTGrepPattern(BaseModel):

174 file_path_mask: str = Field(..., description="The file path pattern to match against")

175 pattern: str = Field(..., description="The main AST grep pattern to search for")

176 additional_greps: Optional[List[str]] = Field(

177 default=None,

178 description="Additional patterns that must also be present in the matched code"

179 )

180 

181def extract_code_blocks(llm_output: str) -> List[CodeBlock]:

182 # Regular expression to match code blocks with optional language and path

183 try:

184 pattern = r"```(\w+\s+)?([\w./-]+)?\n([\s\S]*?)\n```"

185 matches = list(re.finditer(pattern, llm_output, re.DOTALL))

186 

187 print(f"Found {len(matches)} code blocks in the LLM output")

188 

189 # Check if any code blocks were found

190 if not matches:

191 raise Exception("No code blocks found in the LLM response")

192 

193 code_blocks: list[CodeBlock] = []

194 for match in matches:

195 language = match.group(1) or ""

196 path = match.group(2) or ""

197 code = match.group(3)

198 

199 # Clean the path and language

200 path = path.strip()

201 language = language.strip()

202 

203 # If path is relative (doesn't start with /), prefix with /home/user/testbed/

204 if path and not path.startswith("/"):

205 original_path = path

206 path = f"/home/user/testbed/{path}"

207 print(

208 f"Converting relative path '{original_path}' to absolute path '{path}'"

209 )

210 

211 code_blocks.append(

212 CodeBlock(language=language, path=path, code=code.strip())

213 )

214 

215 # Check for missing language or path in code blocks

216 missing_language = [

217 i for i, block in enumerate(code_blocks) if not block.language

218 ]

219 missing_path = [i for i, block in enumerate(code_blocks) if not block.path]

220 

221 if missing_language:

222 print(

223 f"WARNING: Code blocks at positions {missing_language} are missing language identifiers"

224 )

225 raise Exception(

226 f"Code blocks at positions {missing_language} are missing language identifiers"

227 )

228 

229 if missing_path:

230 print(

231 f"WARNING: Code blocks at positions {missing_path} are missing file paths"

232 )

233 raise Exception(

234 f"Code blocks at positions {missing_path} are missing file paths"

235 )

236 

237 paths = [block.path for block in code_blocks if block.path]

238 print(

239 f"Successfully extracted {len(code_blocks)} code blocks with paths: {', '.join(paths)}"

240 )

241 

242 except Exception as e:

243 print(f"Error extracting code blocks: {str(e)}")

244 raise

245 

246 return code_blocks

247 

248 

249def calculate_ast_grep_score(code_blocks: List[CodeBlock], ast_greps: Any) -> float:

250 # Convert ast_greps to list if it's a dict

251 if isinstance(ast_greps, dict):

252 ast_greps = [ast_greps]

253 

254 # Parse each grep pattern into the Pydantic model

255 parsed_patterns: List[ASTGrepPattern] = []

256 for grep in ast_greps:

257 try:

258 pattern = ASTGrepPattern(**grep)

259 parsed_patterns.append(pattern)

260 except Exception as e:

261 print(f"Error parsing AST grep pattern: {e}")

262 return 0.0

263 

264 if not parsed_patterns:

265 return 0.0

266 

267 total_score = 0.0

268 pattern_count = len(parsed_patterns)

269 

270 # Filter code blocks to only include TypeScript and JavaScript files

271 supported_blocks = [

272 block for block in code_blocks

273 if block.language.lower() in SUPPORTED_LANGUAGES

274 ]

275 

276 if not supported_blocks:

277 print("No TypeScript or JavaScript code blocks found to analyze")

278 return 0.0

279 

280 for pattern in parsed_patterns:

281 # Find matching code blocks based on path prefix

282 matching_blocks = [

283 block for block in supported_blocks

284 if block.path.startswith(pattern.file_path_mask)

285 ]

286 

287 if not matching_blocks:

288 print(f"No matching code blocks found for path prefix: {pattern.file_path_mask}")

289 continue

290 

291 pattern_found = False

292 for block in matching_blocks:

293 try:

294 # Create AST root for the code block

295 root = SgRoot(block.code, block.language)

296 node = root.root()

297 

298 # Check main pattern

299 matches = node.find(pattern=pattern.pattern)

300 if not matches:

301 continue

302 

303 # If we have additional greps, check them too

304 if pattern.additional_greps:

305 all_additional_found = True

306 for additional_grep in pattern.additional_greps:

307 if additional_grep not in block.code:

308 all_additional_found = False

309 break

310 

311 if not all_additional_found:

312 continue

313 

314 # If we get here, we found a match with all required patterns

315 pattern_found = True

316 break

317 

318 except Exception as e:

319 print(f"Error processing code block {block.path}: {e}")

320 continue

321 

322 if pattern_found:

323 total_score += 1.0

324 

325 # Return average score across all patterns

326 return total_score / pattern_count if pattern_count > 0 else 0.0

327 

328def grade_format(output_text: str) -> float:

329 # Find <plan> and </plan> tags

330 plan_start = output_text.find('<plan>')

331 plan_end = output_text.find('</plan>')

332 

333 # Find <code> and </code> tags

334 code_start = output_text.find('<code>')

335 code_end = output_text.find('</code>')

336 

337 reward = 0.0

338 

339 if plan_start == -1 or plan_end == -1 or code_start == -1 or code_end == -1:

340 print(f'missing plan or code tags. format reward: {reward}')

341 return reward

342 reward += 0.1 # total: 0.1

343 

344 if not (plan_start < plan_end < code_start < code_end):

345 print(f'tags present but not in the correct order. format reward: {reward}')

346 return reward

347 reward += 0.1 # total: 0.2

348 

349 # Check if there are any stray tags

350 plan_tags = re.findall(r'</?plan>', output_text)

351 code_tags = re.findall(r'</?code>', output_text)

352 

353 if len(plan_tags) != 2 or len(code_tags) != 2:

354 print(f'found stray plan or code tags. format reward: {reward}')

355 return reward

356 reward += 0.2 # total: 0.4

357 

358 # Extract content after </code> tag

359 after_tags = output_text[code_end + len('</code>'):].strip()

360 if after_tags:

361 print(f'found text after code tags. format reward: {reward}')

362 return reward

363 reward += 0.2 # total: 0.6

364 

365 # Extract content inside <plan> tags

366 plan_content = output_text[plan_start + len('<plan>'):plan_end].strip()

367 if not plan_content:

368 print(f'no plan content found. format reward: {reward}')

369 return reward

370 reward += 0.1 # total: 0.7

371 

372 # Extract content inside <code> tags

373 code_content = output_text[code_start + len('<code>'):code_end].strip()

374 if not code_content:

375 print(f'no code content found. format reward: {reward}')

376 return reward

377 reward += 0.1 # total: 0.8

378 

379 # Extract content between </plan> and <code> tags

380 between_tags = output_text[plan_end + len('</plan>'):code_start].strip()

381 if between_tags:

382 print(f'found text between plan and code tags. format reward: {reward}')

383 return reward

384 reward += 0.2 # total: 1.0

385 

386 if reward == 1.0:

387 print(f'global format reward: {reward}')

388 

389 return reward

390 

391def grade(sample: Any, item: Any) -> float:

392 try:

393 output_text = sample["output_text"]

394 

395 format_reward = grade_format(output_text)

396 if format_reward < 1.0:

397 return format_reward

398 

399 # Extract code content for grading

400 code_start = output_text.find('<code>')

401 code_end = output_text.find('</code>')

402 code_to_grade: str = output_text[code_start + len('<code>'):code_end].strip()

403 code_blocks: List[CodeBlock] = []

404 try:

405 code_blocks = extract_code_blocks(code_to_grade)

406 except Exception as e:

407 print(f'error extracting code blocks: {e}')

408 return 0.5

409 

410 ast_greps = item["reference_answer"]["ast_greps"]

411 ast_grep_score = calculate_ast_grep_score(code_blocks, ast_greps)

412 

413 return (format_reward + ast_grep_score) / 2.0

414 except Exception as e:

415 print(f"Error during grading: {str(e)}")

416 return 0.0

417````

418 

419 

420

421 

422

423 

424

425Results

426 

427

428 

429> Looking at the total reward (format and AST Grep) together, Runloop has seen improvements of on average **12%** of the RFT model compared to the base o3-mini model on the benchmark.

430>

431> They implement two types of tests, one providing explicit content from the integration guides (assessing reasoning and instruction following) and one without (assessing knowledge recall). Both variants saw improvement of over **8%**.

432>

433> “OpenAIs RFT platform gives us access to the best generalized reasoning models in the world, with the toolset to supercharge that reasoning on problem domains important to our business.”

434>

435> —[Runloop](https://www.runloop.ai/)

61 436 

62 437 

63 438 


65 440 

66 441 

67 442 

68<div data-content-switcher-pane data-value="use-case">443Use case

69 <div class="hidden">Use case</div>444 

70 </div>445

71 <div data-content-switcher-pane data-value="review" hidden>446 

72 <div class="hidden">Results</div>447> **Company**: [Milo](https://www.joinmilo.com) helps busy parents manage chaotic family schedules by converting messy inputs—like text convos with to-dos, school newsletter PDFs, weekly reminders, sports schedule emails—into reliable calendar and list actions.

73 </div>448>

449> **Problem to solve**: Base GPT-4o prompting and SFT fell short of trust thresholds.

450>

451> **Objective**: Milo used RFT to properly create coding tasks like event vs. list classification, recurrence rule generation, accurate updates and deletes, conflict detection, and strict output formatting. They defined a grader that checked whether generated item objects were complete, categorized correctly, and were a duplicate or had a calendar conflict.

452 

453 

454

455 

456

457 

458

459Results

460 

461

462 

463> Results showed performance improvements across the board, with average correctness scores **increasing from 0.86 to 0.91**, while the most challenging scenarios improved from **0.46 to 0.71** (where a perfect score=1).

464>

465> "Accuracy isn't just a metric—it's peace of mind for busy parents. These are still early days but with such important improvements in base performance, we're able to push more aggressively into complex reasoning needs."

466>

467> "Navigating and supporting family dynamics involves understanding nuanced implications of the data. Take conflicts—knowing soccer for Ethan conflicts with Ella's recital because Dad has to drive both kids goes deeper than simple overlapping times."

468>

469> —[Milo](https://www.joinmilo.com), AI scheduling tool for families

74 470 

75 471 

76 472 


82 478 

83 479 

84 480 

85<div data-content-switcher-pane data-value="use-case">481Use case

86 <div class="hidden">Use case</div>482 

87 </div>483

88 <div data-content-switcher-pane data-value="review" hidden>484 

89 <div class="hidden">Results</div>485> **Company**: [Ambience](https://www.ambiencehealthcare.com) is an AI platform that eliminates administrative burden for clinicians and ensures accurate, compliant documentation across 100+ specialties, helping physicians focus on patient care while increasing documentation quality and reducing compliance risk for health systems.

90 </div>486>

487> **Problem to solve**: ICD-10 coding is one of the most intricate administrative tasks in medicine. After every patient encounter, clinicians must map each diagnosis to one of ~70,000 codes—navigating payor-specific rules on specificity, site-of-care, and mutually exclusive pairings. Errors can trigger audits and fines that stretch into nine figures.

488>

489> **Objective**: Using reinforcement fine-tuning on OpenAI frontier models, Ambience wanted to train a reasoning system that listens to the visit audio, pulls in relevant EHR context, and recommends ICD-10 codes with accuracy exceeding expert clinicians.

490 

491 

492

493 

494

495 

496

497Results

498 

499

500 

501> Ambience achieved model improvements that can lead human experts.

502>

503> On a gold-panel test set spanning hundreds of encounters, reinforcement fine-tuning moved the model from trailing humans to leading them by **12 points—eliminating roughly one quarter of the coding errors trained physicians make**:

504>

505> - o3-mini (base): 0.39 (-6 pts)

506> - Physician baseline: 0.45

507> - RFT-tuned o3-mini: 0.57 (+12 pts)

508>

509> The result is a real-time, point-of-care coding support that can raise reimbursement integrity while reducing compliance risk.

510>

511> “Accurate ICD-10 selection is mission-critical for compliant documentation. RFT unlocked a new level of coding precision we hadn’t seen from any foundation model and set a new bar for automated coding.”

512>

513> —[Ambience Healthcare](https://www.ambiencehealthcare.com)

91 514 

92 515 

93 516 


95 518 

96 519 

97 520 

98<div data-content-switcher-pane data-value="use-case">521Use case

99 <div class="hidden">Use case</div>522 

100 </div>523

101 <div data-content-switcher-pane data-value="prompt" hidden>524 

102 <div class="hidden">Prompt</div>525> **Company**: [Harvey](https://www.harvey.ai) is building AI that legal teams trust—and that trust hinges on retrieving precisely the right evidence from a sprawling corpora of contracts, statutes, and case law. Legal professionals aren’t satisfied with models that merely generate plausible-sounding summaries or paraphrased answers. They demand verifiable citations—passages that can be traced directly back to source documents.

103 </div>526>

104 <div data-content-switcher-pane data-value="grader" hidden>527> **Problem to solve**: Harvey’s clients use its models to triage litigation risk, construct legal arguments, and support due diligence for legal professionals—all tasks where a single missed or misquoted sentence can flip an outcome. Models must be able to parse long, dense legal documents and extract only the portions that matter.

105 <div class="hidden">Grader</div>528> In practice, these inputs are often messy and inconsistent: some claims are vague, while others hinge on rare legal doctrines buried deep in boilerplate.

106 </div>529>

107 <div data-content-switcher-pane data-value="review" hidden>530> **Objective**: The task’s requirements are to interpret nuanced legal claims, navigate long-form documents, and select on-point support with verbatim excerpts.

108 <div class="hidden">Results</div>531 

109 </div>532 

533

534 

535

536 

537

538Prompt

539 

540

541 

542```

543## Instructions

544You will be provided with a question and a text excerpt. Identify any passages in the text that are directly relevant to answering the question.

545- If there are no relevant passages, return an empty list.

546- Passages must be copied **exactly** from the text. Do not paraphrase or summarize.

547## Excerpt

548"""{text_excerpt}"""

549```

550 

551 

552

553 

554

555 

556

557Grader

558 

559

560 

561```python

562from rapidfuzz import fuzz

563 

564 

565# Similarity ratio helper

566def fuzz_ratio(a: str, b: str) -> float:

567 """Return a normalized similarity ratio using RapidFuzz."""

568 if len(a) == 0 and len(b) == 0:

569 return 1.0

570 return fuzz.ratio(a, b) / 100.0

571 

572 

573# Main grading entrypoint (must be named \`grade\`)

574def grade(sample: dict, item: dict) -> float:

575 """Compute an F1‑style score for citation extraction answers using RapidFuzz."""

576 model_passages = (sample.get("output_json") or {}).get("passages", [])

577 ref_passages = (item.get("reference_answer") or {}).get("passages", [])

578 

579 # If there are no reference passages, return 0.

580 if not ref_passages:

581 return 0.0

582 

583 # Recall: average best match for each reference passage.

584 recall_scores = []

585 for ref in ref_passages:

586 best = 0.0

587 for out in model_passages:

588 score = fuzz_ratio(ref, out)

589 if score > best:

590 best = score

591 recall_scores.append(best)

592 recall = sum(recall_scores) / len(recall_scores)

593 

594 # Precision: average best match for each model passage.

595 if not model_passages:

596 precision = 0.0

597 else:

598 precision_scores = []

599 for out in model_passages:

600 best = 0.0

601 for ref in ref_passages:

602 score = fuzz_ratio(ref, out)

603 if score > best:

604 best = score

605 precision_scores.append(best)

606 precision = sum(precision_scores) / len(precision_scores)

607 

608 if precision + recall == 0:

609 return 0.0

610 

611 return 2 * precision * recall / (precision + recall)

612```

613 

614 

615

616 

617

618 

619

620Results

621 

622

623 

624> After reinforcement fine-tuning, Harvey saw a **20% increase** in the F1 score:

625>

626> - Baseline F1: 0.563

627> - Post-RFT F1 - 0.6765

628>

629> Using RFT, Harvey significantly improved legal fact-extraction performance, surpassing GPT-4o efficiency and accuracy. Early trials showed RFT **winning or tying in 93% of comparisons** against GPT-4o.

630>

631> “The RFT model demonstrated comparable or superior performance to GPT-4o, but with significantly faster inference, proving particularly beneficial for real-world legal use cases.

632>

633> —[Harvey](https://www.harvey.ai), AI for legal teams

110 634 

111 635 

112 636 


120 644 

121 645 

122 646 

123<div data-content-switcher-pane data-value="use-case">647Use case

124 <div class="hidden">Use case</div>648 

125 </div>649

126 <div data-content-switcher-pane data-value="grader" hidden>650 

127 <div class="hidden">Grader code</div>651> **Company**: [Accordance](https://www.accordance.com) is building a platform for tax, audit, and CPA teams.

128 </div>652>

129 <div data-content-switcher-pane data-value="review" hidden>653> **Problem to solve**: Taxation is a highly complex domain, requiring deep reasoning across nuanced fact patterns and intricate regulations. It's also a field that continues changing.

130 <div class="hidden">Results</div>654>

131 </div>655> **Objective**: Accordance wanted a high-trust system for sophisticated tax scenarios while maintaining accuracy. Unlike traditional hardcoded software, it's important that their data extraction tool adapts as the tax landscape evolves.

656 

657 

658

659 

660

661 

662

663Grader code

664 

665

666 

667```

668[+0.05] For correctly identifying Alex (33.33%), Barbara (33.33% → 20%), Chris (33.33%), and Dana (13.33%) ownership percentages

669[+0.1] For correctly calculating Barbara's annual allocation as 26.67% and Dana's as 6.67% without closing of books

670[+0.15] For properly allocating Alex ($300,000), Barbara ($240,030), Chris ($300,000), and Dana ($60,030) ordinary income

671[+0.1] For calculating Alex's ending stock basis as $248,333 and debt basis as $75,000

672[+0.05] For calculating Barbara's remaining basis after sale as $264,421

673[+0.1] For calculating AAA before distributions as $1,215,000 and ending AAA as $315,000

674[+0.1] For identifying all distributions as tax-free return of capital under AAA

675[+0.1] For calculating Barbara's capital gain on stock sale as $223,720 ($400,000 - $176,280)

676[+0.1] For explaining that closing of books would allocate based on actual half-year results

677[+0.05] For identifying the ordering rules: AAA first, then E&P ($120,000), then remaining basis

678[+0.05] For noting distributions exceeding $1,215,000 would be dividends up to $120,000 E&P

679[+0.05] For correctly accounting for separately stated items in basis calculations (e.g., $50,000 Section 1231 gain)

680```

681 

682 

683

684 

685

686 

687

688Results

689 

690

691 

692> By collaborating with OpenAI and their in-house tax experts, Accordance achieved:

693>

694> - Almost **40% improvement** in tax analysis tasks over base models

695> - Superior performance compared to all other leading models on benchmarks like TaxBench

696> - The RFT-trained models demonstrated an ability to handle advanced tax scenarios with high accuracy—when evaluated by tax professionals, Accordance’s fine-tuned models showed expert-level reasoning, with the potential to save thousands of hours of manual work

697>

698> “We’ve achieved a 38.89% improvement in our tax analysis tasks over base models and significantly outperformed all other leading models on key tax benchmarks (including TaxBench). The RFT-trained models’ abilities to handle sophisticated tax scenarios while maintaining accuracy demonstrates the readiness of reinforcement fine-tuning—and AI more broadly—for professional applications. Most importantly, RFT provides a foundation for continuous adaptation as the tax landscape evolves, ensuring sustained value and relevance. When evaluated by tax experts, our fine-tuned models demonstrated expert-level reasoning capabilities that will save thousands of professional hours—this isn’t just an incremental improvement, it’s a paradigm shift in how tax work can be done.”

699>

700> —[Accordance](https://www.accordance.com/), AI tax accounting company

132 701 

133 702 

134 703 


136 705 

137 706 

138 707 

139<div data-content-switcher-pane data-value="use-case">708Use case

140 <div class="hidden">Use case</div>709 

141 </div>710

142 <div data-content-switcher-pane data-value="review" hidden>711 

143 <div class="hidden">Results</div>712> **Company**: [SafetyKit](https://www.safetykit.com) is a risk and compliance platform that helps organizations make decisions across complex content moderation workflows.

144 </div>713>

714> **Problem to solve**: These systems must handle large volumes of content and apply intricate policy logic that requires multistep reasoning. Because of the volume of data and subtle distinctions in labelling, these types of tasks can be difficult for general purpose models.

715>

716> **Objective**: SafetyKit aimed to replace multiple nodes in their most complex workflows with a single reasoning agent using a reinforcement fine-tuned model. The goal is to reduce SafetyKit’s time-to-market for novel policy enforcements even in challenging, nuanced domains.

717 

718 

719

720 

721

722 

723

724Results

725 

726

727 

728> SafetyKit is using their o3-mini RFT model to support advanced content moderation capabilities, ensuring user safety for one of the largest AI chatbot companies in the world. They have successfully improved F1-score **from 86% to 90%**, soon to replace dozens of 4o calls within their production pipeline.

729>

730> "SafetyKit’s RFT-enabled moderation achieved substantial improvements in nuanced content moderation tasks, crucial for safeguarding users in dynamic, real-world scenarios."

731>

732> —[SafetyKit](https://www.safetykit.com)

145 733 

146 734 

147 735 


149 737 

150 738 

151 739 

152<div data-content-switcher-pane data-value="use-case">740Use case

153 <div class="hidden">Use case</div>741 

154 </div>742

155 <div data-content-switcher-pane data-value="review" hidden>743 

156 <div class="hidden">Results</div>744> **Company**: [Thomson Reuters](https://www.thomsonreuters.com) is an AI and technology company empowering professionals with trusted content and workflow automation.

157 </div>745>

746> **Problem to solve**: Legal professionals must read through large amounts of content before making any decisions. Thomson Reuter's CoCounsel product is designed to help these experts move faster by providing an AI assistant with content and industry knowledge. The models that power this tool must understand complex legal rules.

747>

748> **Objective**: Thomson Reuters aimed to create a reinforcement fine-tuned model excelling in legal AI skills. They conducted preliminary evaluations of RFT to see if they could achieve model performance improvements, using specialized datasets from three highly-used CoCounsel Legal AI skills for legal professionals:

749>

750> 1. Review documents: Generates detailed answers to questions asked against contracts, transcripts, and other legal documents

751> 1. Compare documents: Highlights substantive differences between two or more different contracts or documents

752> 1. Summarize: Summarizes the most important information within one or more documents to enable rapid legal review

753 

754 

755

756 

757

758 

759

760Results

761 

762

763 

764> ![Provide example data and create a fine-tuning job to optimize model performance for your use case](https://cdn.openai.com/API/docs/images/thomsonreuters-results.png)

765>

766> "LLM as a judge has been helpful in demonstrating the possibility of improving upon the reasoning models - in preliminary evaluations, the RFT model consistently performed better than the baseline o3-mini and o1 model"

767>

768> —[Thomson Reuters](https://www.thomsonreuters.com/), AI and technology company

158 769 

159 770 

160 771 

Details

1# Safety best practices1# Safety best practices

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.

4 

3### Use our free Moderation API5### Use our free Moderation API

4 6 

5OpenAI's [Moderation API](https://developers.openai.com/api/docs/guides/moderation) is free-to-use and can help reduce the frequency of unsafe content in your completions. Alternatively, you may wish to develop your own content filtration system tailored to your use case.7OpenAI's [Moderation API](https://developers.openai.com/api/docs/guides/moderation) is free-to-use and can help reduce the frequency of unsafe content in your completions. Alternatively, you may wish to develop your own content filtration system tailored to your use case.

Details

1# Safety checks1# Safety checks

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.

4 

3We run several types of evaluations on our models and how they're being used. This guide covers how we test for safety and what you can do to avoid violations.5We run several types of evaluations on our models and how they're being used. This guide covers how we test for safety and what you can do to avoid violations.

4 6 

5## Safety classifiers for GPT-5 and forward7## Safety classifiers for GPT-5 and forward


21 23 

22### Implementing safety identifiers for individual users24### Implementing safety identifiers for individual users

23 25 

24The `safety_identifier` parameter is available in both the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create) and older [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat/create). The Realtime API supports the same concept through the `OpenAI-Safety-Identifier` header. To use safety identifiers, provide a stable ID for your end user on each request. Hash user email or internal user IDs to avoid passing any personal information.26The `safety_identifier` parameter is available in both the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) and older [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). The Realtime API supports the same concept through the `OpenAI-Safety-Identifier` header. To use safety identifiers, provide a stable ID for your end user on each request. Hash user email or internal user IDs to avoid passing any personal information.

25 27 

26Safety identifiers do not carry over between APIs or sessions. If your application already sends `safety_identifier` with Responses API requests, pass the same stable value separately when you create or connect each Realtime session.28Safety identifiers do not carry over between APIs or sessions. If your application already sends `safety_identifier` with Responses API requests, pass the same stable value separately when you create or connect each Realtime session.

27 29 

28 30 

29 31 

30<div data-content-switcher-pane data-value="responses">32Responses API

31 <div class="hidden">Responses API</div>33 

32 Providing a safety identifier with the Responses API34 Providing a safety identifier with the Responses API

33 35 

34```python36```python


54}'56}'

55```57```

56 58 

57 </div>59

58 <div data-content-switcher-pane data-value="chat" hidden>60 

59 <div class="hidden">Chat Completions API</div>61

62 

63

64Chat Completions API

65 

60 Providing a safety identifier with the Chat Completions API66 Providing a safety identifier with the Chat Completions API

61 67 

62```python68```python


84}'90}'

85```91```

86 92 

87 </div>93

88 <div data-content-switcher-pane data-value="realtime" hidden>94 

89 <div class="hidden">Realtime API</div>95

96 

97

98Realtime API

99 

90 Providing a safety identifier with the Realtime API100 Providing a safety identifier with the Realtime API

91 101 

92```bash102```bash


102}'112}'

103```113```

104 114 

105 </div>

106 

107 115 

108 116 

109### Potential consequences117### Potential consequences

Details

1# Cybersecurity checks1# Cybersecurity checks

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.

4 

3GPT-5.3-Codex and newer models, including GPT-5.4 and GPT-5.5, are classified as having High Cybersecurity Capability under our [Preparedness Framework](https://cdn.openai.com/pdf/18a02b5d-6b67-4cec-ab64-68cdfbddebcd/preparedness-framework-v2.pdf). As a result, additional automated safeguards apply when these models are used via the API. Please note that the safeguards applied in the API differ from those used in Codex. You can learn more about the Codex safeguards [here](https://developers.openai.com/codex/cyber-safety/).5GPT-5.3-Codex and newer models, including GPT-5.4 and GPT-5.5, are classified as having High Cybersecurity Capability under our [Preparedness Framework](https://cdn.openai.com/pdf/18a02b5d-6b67-4cec-ab64-68cdfbddebcd/preparedness-framework-v2.pdf). As a result, additional automated safeguards apply when these models are used via the API. Please note that the safeguards applied in the API differ from those used in Codex. You can learn more about the Codex safeguards [here](https://developers.openai.com/codex/cyber-safety/).

4 6 

5These safeguards monitor for signals of potentially suspicious cybersecurity activity. If certain thresholds are met, access to the model may be temporarily limited while activity is reviewed. Because these systems are still being calibrated, legitimate security research or defensive work may occasionally be flagged. We expect only a small portion of traffic to be impacted, and we’re continuing to refine the overall API experience.7These safeguards monitor for signals of potentially suspicious cybersecurity activity. If certain thresholds are met, access to the model may be temporarily limited while activity is reviewed. Because these systems are still being calibrated, legitimate security research or defensive work may occasionally be flagged. We expect only a small portion of traffic to be impacted, and we’re continuing to refine the overall API experience.

Details

1# Under 18 API Guidance1# Under 18 API Guidance

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.

4 

3Young people have unique needs online and offline, so developers should implement additional safeguards when using our API to serve minors (under 18 years old). These are in addition to requirements under our [usage policies](https://openai.com/policies/usage-policies/) and [terms and conditions](https://openai.com/policies/services-agreement/).5Young people have unique needs online and offline, so developers should implement additional safeguards when using our API to serve minors (under 18 years old). These are in addition to requirements under our [usage policies](https://openai.com/policies/usage-policies/) and [terms and conditions](https://openai.com/policies/services-agreement/).

4 6 

5**Regulatory Standards**7**Regulatory Standards**

Details

1# Secure MCP Tunnel1# Secure MCP Tunnel

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.

4 

3Secure MCP Tunnel lets you connect private MCP servers to supported OpenAI products without opening inbound firewall ports or exposing those servers to the public internet. Run `tunnel-client` inside the network that can already reach your MCP server; it opens an outbound HTTPS path to OpenAI, pulls queued MCP work, forwards requests locally, and returns responses through the same tunnel.5Secure MCP Tunnel lets you connect private MCP servers to supported OpenAI products without opening inbound firewall ports or exposing those servers to the public internet. Run `tunnel-client` inside the network that can already reach your MCP server; it opens an outbound HTTPS path to OpenAI, pulls queued MCP work, forwards requests locally, and returns responses through the same tunnel.

4 6 

5## What is an MCP tunnel?7## What is an MCP tunnel?


100 102 

101<figure className="not-prose my-8">103<figure className="not-prose my-8">

102 <figcaption className="mt-3 text-sm text-gray-600 dark:text-gray-400">104 <figcaption className="mt-3 text-sm text-gray-600 dark:text-gray-400">

103 The local admin UI at <code>/ui</code> shows whether the running client is105 The local admin UI at `/ui` shows whether the running client is

104 healthy, ready, and connected before you test from ChatGPT, Codex, or an API106 healthy, ready, and connected before you test from ChatGPT, Codex, or an API

105 flow.107 flow.

106 </figcaption>108 </figcaption>


179- Validate your `tunnel-client` profile with `tunnel-client doctor --profile <profile> --explain`.181- Validate your `tunnel-client` profile with `tunnel-client doctor --profile <profile> --explain`.

180- Connect the tunnel from [ChatGPT Plugins](https://chatgpt.com/plugins) or the supported OpenAI surface you are using.182- Connect the tunnel from [ChatGPT Plugins](https://chatgpt.com/plugins) or the supported OpenAI surface you are using.

181 183 

182<div class="not-prose my-8 grid gap-4 lg:grid-cols-2">184 

185 

183 <figure>186 <figure>

184 <a href="https://platform.openai.com/settings/organization/tunnels">187 [<img src="https://developers.openai.com/images/platform/guides/secure-mcp-tunnels/platform-tunnels-settings.png"

185 <img src="https://developers.openai.com/images/platform/guides/secure-mcp-tunnels/platform-tunnels-settings.png"

186 alt="Sanitized OpenAI Platform tunnel settings screenshot."188 alt="Sanitized OpenAI Platform tunnel settings screenshot."

187 loading="lazy"189 loading="lazy"

188 class="w-full rounded-md border border-gray-200 dark:border-gray-800"190 class="w-full rounded-md border border-gray-200 dark:border-gray-800"

189 />191 />](https://platform.openai.com/settings/organization/tunnels)

190 </a>

191 <figcaption class="mt-3 text-sm text-gray-600 dark:text-gray-400">192 <figcaption class="mt-3 text-sm text-gray-600 dark:text-gray-400">

192 Create and manage OpenAI-hosted MCP tunnel endpoints from Platform tunnel193 Create and manage OpenAI-hosted MCP tunnel endpoints from Platform tunnel

193 settings.194 settings.

194 </figcaption>195 </figcaption>

195 </figure>196 </figure>

196 <figure>197 <figure>

197 <a href="https://chatgpt.com/plugins">198 [<img src="https://developers.openai.com/images/platform/guides/secure-mcp-tunnels/chatgpt-connectors-tunnel.png"

198 <img src="https://developers.openai.com/images/platform/guides/secure-mcp-tunnels/chatgpt-connectors-tunnel.png"

199 alt="Sanitized ChatGPT app creation screenshot with Tunnel selected."199 alt="Sanitized ChatGPT app creation screenshot with Tunnel selected."

200 loading="lazy"200 loading="lazy"

201 class="w-full rounded-md border border-gray-200 dark:border-gray-800"201 class="w-full rounded-md border border-gray-200 dark:border-gray-800"

202 />202 />](https://chatgpt.com/plugins)

203 </a>

204 <figcaption class="mt-3 text-sm text-gray-600 dark:text-gray-400">203 <figcaption class="mt-3 text-sm text-gray-600 dark:text-gray-400">

205 Select Tunnel when connecting a ChatGPT developer-mode app to a private204 Select Tunnel when connecting a ChatGPT developer-mode app to a private

206 MCP server.205 MCP server.

207 </figcaption>206 </figcaption>

208 </figure>207 </figure>

209</div>

Details

1# Speech to text1# File transcription

2 2 

3The Audio API provides two speech to text endpoints: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 

5- `transcriptions`5Use file transcription when you have a completed recording or a bounded audio request. Upload the audio and receive a final transcript, or stream text while the model processes the file.

6- `translations`

7 6 

8Historically, both endpoints have been backed by our open source [Whisper model](https://openai.com/blog/whisper/) (`whisper-1`). The `transcriptions` endpoint now also supports higher quality model snapshots, with limited parameter support:7Start with [`gpt-transcribe`](https://developers.openai.com/api/docs/models/gpt-transcribe). This is the recommended model for transcribing recorded speech in its original language. Use a specialized model only if you need speaker labels, word timestamps, subtitle formats, or translation into English.

9 8 

10- `gpt-4o-mini-transcribe`9Files can be up to 25 MB. Supported input formats are `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `wav`, and `webm`.

11- `gpt-4o-transcribe`

12- `gpt-4o-transcribe-diarize`

13 10 

14All endpoints can be used to:11For audio that is still arriving from a microphone, call, or media stream, use

15 12 [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription).

16- Transcribe audio into whatever language the audio is in.

17- Translate and transcribe the audio into English.

18 

19File uploads are currently limited to 25 MB, and the following input file types are supported: `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `wav`, and `webm`. Known speaker reference clips for speaker identification accept the same formats when provided as data URLs.

20 

21Use this guide for file uploads and bounded audio requests. If your

22 application needs live transcript deltas from a microphone, call, or media

23 stream, use [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription)

24 instead.

25 13 

26## Quickstart14## Quickstart

27 15 

28### Transcriptions16### Transcriptions

29 17 

30The transcriptions API takes as input the audio file you want to transcribe and the desired output file format for the transcription of the audio. All models support the same set of input formats. On output:18Send the audio file to `/v1/audio/transcriptions` with `gpt-transcribe`:

31 

32- `whisper-1` supports `json`, `text`, `srt`, `verbose_json`, and `vtt`.

33- `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` support `json` or plain `text`.

34- `gpt-4o-transcribe-diarize` supports `json`, `text`, and `diarized_json` (which adds speaker segments to the response).

35 19 

36Transcribe audio20Transcribe audio

37 21 


43 27 

44const transcription = await openai.audio.transcriptions.create({28const transcription = await openai.audio.transcriptions.create({

45 file: fs.createReadStream("fixtures/audio.wav"),29 file: fs.createReadStream("fixtures/audio.wav"),

46 model: "gpt-4o-transcribe",30 model: "gpt-transcribe",

47});31});

48 32 

49console.log(transcription.text);33console.log(transcription.text);


56audio_file = open("audio.wav", "rb")40audio_file = open("audio.wav", "rb")

57 41 

58transcription = client.audio.transcriptions.create(42transcription = client.audio.transcriptions.create(

59 model="gpt-4o-transcribe", file=audio_file43 model="gpt-transcribe", file=audio_file

60)44)

61 45 

62print(transcription.text)46print(transcription.text)


64 48 

65```cli49```cli

66openai audio:transcriptions create \50openai audio:transcriptions create \

67 --model gpt-4o-transcribe \51 --model gpt-transcribe \

68 --file /path/to/file/audio.mp3 \52 --file /path/to/file/audio.mp3 \

69 --raw-output \53 --raw-output \

70 --transform text54 --transform text


76 --header "Authorization: Bearer $OPENAI_API_KEY" \60 --header "Authorization: Bearer $OPENAI_API_KEY" \

77 --header 'Content-Type: multipart/form-data' \61 --header 'Content-Type: multipart/form-data' \

78 --form file=@/path/to/file/audio.mp3 \62 --form file=@/path/to/file/audio.mp3 \

79 --form model=gpt-4o-transcribe63 --form model=gpt-transcribe

80```64```

81 65 

82 66 

83By default, the response type will be JSON with the raw text included.67The model returns the transcript and the detected languages as JSON:

84 68 

85```example-content69```json

86{70{

87 "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger.71 "text": "Bonjour, pouvez-vous m'entendre ?",

88....72 "languages": [{ "code": "fr" }]

89}73}

90```74```

91 75 

92The Audio API also allows you to set additional parameters in a request. For example, if you want to set the `response_format` as `text`, your request would look like the following:76When the model can't make a reliable language prediction, it returns `"languages": []`. See the [Audio API reference](https://developers.openai.com/api/reference/resources/audio) for the complete request and response fields.

93 77 

94Additional options78## Add transcription context

79 

80Use `prompt`, `keywords`, and `languages` with `gpt-transcribe` to improve transcription of domain terms and multilingual audio:

81 

82Add context and language hints

95 83 

96```javascript84```javascript

97import fs from "fs";85import fs from "fs";


99 87 

100const openai = new OpenAI();88const openai = new OpenAI();

101 89 

102const transcription = await openai.audio.transcriptions.create({90const request = {

103 file: fs.createReadStream("fixtures/speech.wav"),91 model: "gpt-transcribe",

104 model: "gpt-4o-transcribe",92 file: fs.createReadStream("fixtures/audio.wav"),

105 response_format: "text",93 prompt: "A customer support call about a premium plan and account AC-42.",

94};

95 

96const transcription = await openai.audio.transcriptions.create(request, {

97 body: {

98 ...request,

99 keywords: ["premium plan", "AC-42", "billing"],

100 languages: ["en", "fr"],

101 },

106});102});

107 103 

108console.log(transcription);104console.log(transcription.text);

109```105```

110 106 

111```python107```python

112from openai import OpenAI108from openai import OpenAI

113 109 

114client = OpenAI()110client = OpenAI()

115audio_file = open("speech.wav", "rb")

116 111 

117transcription = client.audio.transcriptions.create(112with open("meeting.wav", "rb") as audio_file:

118 model="gpt-4o-transcribe", file=audio_file, response_format="text"113 transcription = client.audio.transcriptions.create(

119)114 model="gpt-transcribe",

115 file=audio_file,

116 prompt="A customer support call about a premium plan and account AC-42.",

117 extra_body={

118 "keywords": ["premium plan", "AC-42", "billing"],

119 "languages": ["en", "fr"],

120 },

121 )

120 122 

121print(transcription.text)123print(transcription.text)

122```124```

123 125 

124```bash126```bash

125curl --request POST \127curl https://api.openai.com/v1/audio/transcriptions \

126 --url https://api.openai.com/v1/audio/transcriptions \128 -H "Authorization: Bearer $OPENAI_API_KEY" \

127 --header "Authorization: Bearer $OPENAI_API_KEY" \129 -H "Content-Type: multipart/form-data" \

128 --header 'Content-Type: multipart/form-data' \130 -F model="gpt-transcribe" \

129 --form file=@/path/to/file/speech.mp3 \131 -F file="@/path/to/file/meeting.wav" \

130 --form model=gpt-4o-transcribe \132 -F 'prompt=A customer support call about a premium plan and account AC-42.' \

131 --form response_format=text133 -F 'keywords[]=premium plan' \

134 -F 'keywords[]=AC-42' \

135 -F 'keywords[]=billing' \

136 -F 'languages[]=en' \

137 -F 'languages[]=fr'

132```138```

133 139 

134 140 

135The [API Reference](https://developers.openai.com/api/docs/api-reference/audio) includes the full list of available parameters.141- Use `prompt` for unstructured context about the recording.

142- Use `keywords` for literal terms you expect to hear.

143- Use `languages` for the expected input languages.

136 144 

137`gpt-4o-transcribe` and `gpt-4o-mini-transcribe` support `json` or `text`145Keywords are hints, not required output. Include only relevant terms, and evaluate whether they improve accuracy without causing unspoken terms to appear.

138 responses and allow prompts and logprobs. `gpt-4o-transcribe-diarize` adds

139 speaker labels but requires `chunking_strategy` when your audio is longer than

140 30 seconds (`"auto"` is recommended) and does not support prompts, logprobs,

141 or `timestamp_granularities[]`.

142 146 

143### Identify speakers147For `gpt-transcribe`, `languages` replaces the singular `language` field. Don't send both fields. Keep each keyword on one line and don't include `<`, `>`, a carriage return, or a line feed. The API rejects the entire request when it encounters one of these characters or when `prompt` exceeds the model's length limit.

144 148 

145`gpt-4o-transcribe-diarize` produces speaker-aware transcripts. Request the `diarized_json` response format to receive an array of segments with `speaker`, `start`, and `end` metadata. Set `chunking_strategy` (either `"auto"` or a Voice Activity Detection configuration) so that the service can split the audio into segments; this is required when the input is longer than 30 seconds.149## Speaker diarization

150 

151Use `gpt-4o-transcribe-diarize` only when you need to identify who speaks during different parts of a recording. This specialized speaker-labeling model isn't the recommended model for ordinary file transcription.

152 

153Request the `diarized_json` response format to receive segments with `speaker`, `start`, and `end` metadata. For audio longer than 30 seconds, set `chunking_strategy` to `"auto"` or a voice activity detection configuration.

146 154 

147You can optionally supply up to four short audio references with `known_speaker_names[]` and `known_speaker_references[]` to map segments onto known speakers. Provide reference clips between 2–10 seconds in any input format supported by the main audio upload; encode them as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) when using multipart form data.155You can optionally supply up to four short audio references with `known_speaker_names[]` and `known_speaker_references[]` to map segments onto known speakers. Provide reference clips between 2–10 seconds in any input format supported by the main audio upload; encode them as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) when using multipart form data.

148 156 


220```228```

221 229 

222 230 

223When `stream=true`, responses from the speaker-aware model emit `transcript.text.segment` events whenever a segment completes. `transcript.text.delta` events include a `segment_id` field, but these deltas do not stream partial speaker assignments until each segment is finalized.231When `stream=true`, speaker-labeled responses emit `transcript.text.segment` events whenever a segment completes. `transcript.text.delta` events include a `segment_id` field, but deltas don't include partial speaker assignments. The model assigns a speaker only when it finalizes the segment.

224 232 

225`gpt-4o-transcribe-diarize` is currently available via233Speaker labeling is available through `/v1/audio/transcriptions`. It isn't

226 `/v1/audio/transcriptions` only and is not yet supported in the Realtime API.234 supported in Realtime transcription sessions.

227 235 

228### Translations236## Translations

229 237 

230The translations API takes as input the audio file in any of the supported languages and transcribes, if necessary, the audio into English. This differs from our /Transcriptions endpoint since the output is not in the original input language and is instead translated to English text. This endpoint supports only the `whisper-1` model.238To translate a completed audio recording into English, use `/v1/audio/translations` with `whisper-1`. Unlike transcription, which preserves the recording's original language, this endpoint returns English text.

231 239 

232Translate audio240Translate audio

233 241 


269```277```

270 278 

271 279 

272In this case, the inputted audio was german and the outputted text looks like:280For an audio recording in another language, the response contains the English translation:

273 281 

274```example-content282```example-content

275Hello, my name is Wolfgang and I come from Germany. Where are you heading today?283Hello, my name is Wolfgang and I come from Germany. Where are you heading today?

276```284```

277 285 

278We only support translation into English at this time.286This endpoint supports translation into English only.

279 287 

280## Supported languages288## Supported languages

281 289 

282We currently [support the following languages](https://github.com/openai/whisper#available-models-and-languages) through both the `transcriptions` and `translations` endpoint:290Use `languages` with `gpt-transcribe` when you know which input languages to expect. Supported language-code formats include:

283 291 

284Afrikaans, Arabic, Armenian, Azerbaijani, Belarusian, Bosnian, Bulgarian, Catalan, Chinese, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, Galician, German, Greek, Hebrew, Hindi, Hungarian, Icelandic, Indonesian, Italian, Japanese, Kannada, Kazakh, Korean, Latvian, Lithuanian, Macedonian, Malay, Marathi, Maori, Nepali, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish, Swahili, Swedish, Tagalog, Tamil, Thai, Turkish, Ukrainian, Urdu, Vietnamese, and Welsh.292- ISO 639-1 codes, such as `en`, `es`, and `fr`.

293- Selected ISO 639-3 codes, such as `eng`, `spa`, `yue`, and `cmn`.

294- Regional `zh` locale codes, such as `zh-cn`, `zh-tw`, and `zh-hk`.

285 295 

286While the underlying model was trained on 98 languages, we only list the languages that exceeded \<50% [word error rate](https://en.wikipedia.org/wiki/Word_error_rate) (WER) which is an industry standard benchmark for speech to text model accuracy. The model will return results for languages not listed above but the quality will be low.296The API rejects unsupported or incorrectly formatted language codes. The response also identifies any languages that the model can reliably detect.

287 297 

288We support some ISO 639-1 and 639-3 language codes for GPT-4o based models. For language codes we don’t have, try prompting for specific languages (that is, “Output in English”).298For `whisper-1`, consult the [Whisper language list](https://github.com/openai/whisper#available-models-and-languages). Whisper supports 98 languages, but accuracy varies by language. Existing models that accept one language hint use `language` instead of `languages`.

289 299 

290## Timestamps300## Timestamps

291 301 

292By default, the Transcriptions API will output a transcript of the provided audio in text. The [`timestamp_granularities[]` parameter](/api/docs/api-reference/audio/createTranscription#audio-createtranscription-timestamp_granularities) enables a more structured and timestamped JSON output format, with timestamps at the segment, word level, or both. This enables word-level precision for transcripts and video edits, which allows for the removal of specific frames tied to individual words.302Use `whisper-1` when you need word or segment timestamps. The [`timestamp_granularities[]` parameter](/api/docs/api-reference/audio/createTranscription#audio-createtranscription-timestamp_granularities) returns structured timestamp data for captioning and video editing.

293 303 

294Timestamp options304Timestamp options

295 305 


340 350 

341## Longer inputs351## Longer inputs

342 352 

343By default, the Transcriptions API only supports files that are less than 25 MB. If you have an audio file that is longer than that, you will need to break it up into chunks of 25 MB's or less or used a compressed audio format. To get the best performance, we suggest that you avoid breaking the audio up mid-sentence as this may cause some context to be lost.353The 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.

344 354 

345One way to handle this is to use the [PyDub open source Python package](https://github.com/jiaaro/pydub) to split the audio:355One way to handle this is to use the [PyDub open source Python package](https://github.com/jiaaro/pydub) to split the audio:

346 356 


358```368```

359 369 

360 370 

361_OpenAI makes no guarantees about the usability or security of 3rd party software like PyDub._371_OpenAI makes no guarantees about the usability or security of third-party software like PyDub._

362 372 

363## Prompting373## Prompting

364 374 

365You can use a [prompt](https://developers.openai.com/api/docs/api-reference/audio/createTranscription#audio/createTranscription-prompt) to improve the quality of the transcripts generated by the Transcriptions API.375Use a [prompt](https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create#audio/createTranscription-prompt) to improve recognition of names, acronyms, formatting, or recording-specific vocabulary. With `gpt-transcribe`, combine the prompt with the `keywords` and `languages` shown in [Add transcription context](#add-transcription-context).

366 376 

367Prompting377Existing `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` integrations also support prompting. `gpt-4o-transcribe-diarize` doesn't support prompts.

368 378 

369```javascript379Useful prompting scenarios include:

370import fs from "fs";

371import OpenAI from "openai";

372 380 

373const openai = new OpenAI();381- Correctly transcribing product names, technical terms, and acronyms.

382- Carrying context from a previous chunk of a longer recording.

383- Preserving punctuation, capitalization, and filler words.

384- Selecting a preferred writing system for a language.

374 385 

375const transcription = await openai.audio.transcriptions.create({386For `whisper-1`, prompts have a 224-token limit and provide less control than the recommended transcription model. See [Improving reliability](#improving-reliability) if your workflow requires Whisper.

376 file: fs.createReadStream("fixtures/speech.wav"),

377 model: "gpt-4o-transcribe",

378 response_format: "text",

379 prompt:

380 "The following conversation is a lecture about the recent developments around OpenAI, GPT-4.5 and the future of AI.",

381});

382 

383console.log(transcription);

384```

385 

386```python

387from openai import OpenAI

388 

389client = OpenAI()

390audio_file = open("speech.wav", "rb")

391 

392transcription = client.audio.transcriptions.create(

393 model="gpt-4o-transcribe",

394 file=audio_file,

395 response_format="text",

396 prompt="The following conversation is a lecture about the recent developments around OpenAI, GPT-4.5 and the future of AI.",

397)

398 

399print(transcription.text)

400```

401 

402```bash

403curl --request POST \

404 --url https://api.openai.com/v1/audio/transcriptions \

405 --header "Authorization: Bearer $OPENAI_API_KEY" \

406 --header 'Content-Type: multipart/form-data' \

407 --form file=@/path/to/file/speech.mp3 \

408 --form model=gpt-4o-transcribe \

409 --form prompt="The following conversation is a lecture about the recent developments around OpenAI, GPT-4.5 and the future of AI."

410```

411 

412 

413For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, you can use the `prompt` parameter to improve the quality of the transcription by giving the model additional context similarly to how you would prompt other GPT-4o models. Prompting is not currently available for `gpt-4o-transcribe-diarize`.

414 

415Here are some examples of how prompting can help in different scenarios:

416 

4171. Prompts can help correct specific words or acronyms that the model transcribes incorrectly. For example, the following prompt improves the transcription of the words DALL·E and GPT-3, which were previously written as "GDP 3" and "DALI": "The transcript is about OpenAI which makes technology like DALL·E, GPT-3, and ChatGPT with the hope of one day building an AGI system that benefits all of humanity."

4182. To preserve the context of a file that was split into segments, prompt the model with the transcript of the preceding segment. The model uses relevant information from the previous audio, improving transcription accuracy. The `whisper-1` model only considers the final 224 tokens of the prompt and ignores anything earlier. For multilingual inputs, Whisper uses a custom tokenizer. For English-only inputs, it uses the standard GPT-2 tokenizer. Find both implementations in the open source [Whisper Python package](https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L361).

4193. Sometimes the model skips punctuation in the transcript. To prevent this, use a short prompt that includes punctuation: "Hello, welcome to my lecture."

4204. The model may also leave out common filler words in the audio. If you want to keep the filler words in your transcript, use a prompt that contains them: "Um, let me think like, hmm… Okay, here's what I'm, like, thinking."

4215. Some languages can be written in different ways, such as simplified or traditional Chinese. The model might not always use the writing style that you want for your transcript by default. You can improve this by using a prompt in your preferred writing style.

422 

423For `whisper-1`, the model tries to match the style of the prompt, so it's more likely to use capitalization and punctuation if the prompt does too. However, the current prompting system is more limited than our other language models and provides limited control over the generated text.

424 

425You can find more examples on improving your `whisper-1` transcriptions in the [improving reliability](#improving-reliability) section.

426 387 

427 388 

428 389 


430 391 

431 392 

432 393 

433You can stream a transcription in two ways, depending on whether you want to transcribe a completed audio recording or handle an ongoing audio stream with OpenAI turn detection.394File transcription can stream partial text while the model processes a completed recording. This doesn't require a Realtime session.

434 395 

435### Streaming the transcription of a completed audio recording396### Streaming the transcription of a completed audio recording

436 397 

437If you have an already completed audio recording, either because it's an audio file or you are using your own turn detection (like push-to-talk), you can use our Transcription API with `stream=True` to receive a stream of [transcript events](https://developers.openai.com/api/docs/api-reference/audio/transcript-text-delta-event) as soon as the model is done transcribing that part of the audio.398Set `stream=true` with `gpt-transcribe`. The Transcriptions API returns [transcript events](https://developers.openai.com/api/reference/resources/audio) as the model transcribes each part of the recording.

438 399 

439Stream transcriptions400Stream transcriptions

440 401 


446 407 

447const stream = await openai.audio.transcriptions.create({408const stream = await openai.audio.transcriptions.create({

448 file: fs.createReadStream("fixtures/speech.wav"),409 file: fs.createReadStream("fixtures/speech.wav"),

449 model: "gpt-4o-mini-transcribe",410 model: "gpt-transcribe",

450 response_format: "text",

451 // highlight-start411 // highlight-start

452 stream: true,412 stream: true,

453 // highlight-end413 // highlight-end


467audio_file = open("speech.wav", "rb")427audio_file = open("speech.wav", "rb")

468 428 

469stream = client.audio.transcriptions.create(429stream = client.audio.transcriptions.create(

470 model="gpt-4o-mini-transcribe",430 model="gpt-transcribe",

471 file=audio_file,431 file=audio_file,

472 response_format="text",

473 # highlight-start432 # highlight-start

474 stream=True,433 stream=True,

475 # highlight-end434 # highlight-end


487 --header "Authorization: Bearer $OPENAI_API_KEY" \446 --header "Authorization: Bearer $OPENAI_API_KEY" \

488 --header 'Content-Type: multipart/form-data' \447 --header 'Content-Type: multipart/form-data' \

489 --form file=@example.wav \448 --form file=@example.wav \

490 --form model=whisper-1 \449 --form model=gpt-transcribe \

491 # highlight-start450 # highlight-start

492 --form stream=True451 --form stream=true

493```452```

494 453 

495 454 

496You will receive a stream of `transcript.text.delta` events as soon as the model is done transcribing that part of the audio, followed by a `transcript.text.done` event when the transcription is complete that includes the full transcript. When using `response_format="diarized_json"`, the stream also emits `transcript.text.segment` events with speaker labels each time a segment is finalized.455The model emits `transcript.text.delta` events as it transcribes the audio, then returns the full transcript in a final `transcript.text.done` event. For speaker-labeled transcription with `response_format="diarized_json"`, the diarization model also emits a `transcript.text.segment` event whenever it finalizes a segment.

497 456 

498Additionally, you can use the `include[]` parameter to include `logprobs` in the response to get the log probabilities of the tokens in the transcription. These can be helpful to determine how confident the model is in the transcription of that particular part of the transcript.457For `gpt-transcribe`, the final event also includes detected languages:

458 

459```json

460{

461 "type": "transcript.text.done",

462 "text": "Bonjour, pouvez-vous m'entendre ?",

463 "languages": [{ "code": "fr" }]

464}

465```

499 466 

500Streamed transcription is not supported in `whisper-1`.467Existing `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and

468 `gpt-4o-transcribe-diarize` integrations also support file streaming.

469 `whisper-1` doesn't.

501 470 

502### Streaming the transcription of an ongoing audio recording471### Streaming the transcription of an ongoing audio recording

503 472 

504For live audio from a microphone, call, or media stream, use the [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) guide instead of the file-oriented streaming path above. It covers the current transcription-session flow and the recommended realtime path with [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper).473For live audio from a microphone, call, or media stream, use the [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription) guide instead of the file-oriented streaming path above. It covers the current transcription-session flow and the recommended realtime path with [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe).

505 474 

506## Improving reliability475## Improving reliability

507 476 

508One of the most common challenges faced when using Whisper is the model often does not recognize uncommon words or acronyms. Here are some different techniques to improve the reliability of Whisper in these cases:477If you use `whisper-1` for timestamps, subtitles, or translation, these techniques can improve recognition of uncommon words and acronyms. For new general-purpose transcription, start with `gpt-transcribe` and use [transcription context](#add-transcription-context) instead.

509 478 

510Using the prompt parameter479Using the prompt parameter

511 480 

512The first method involves using the optional prompt parameter to pass a dictionary of the correct spellings.481The first method involves using the optional prompt parameter to pass a dictionary of the correct spellings.

513 482 

514Because it wasn't trained with instruction-following techniques, Whisper operates more like a base GPT model. Keep in mind that Whisper only considers the first 224 tokens of the prompt.483Whisper doesn't follow instructions like a general-purpose text model and accepts prompts of up to 224 tokens.

515 484 

516Prompt parameter485Prompt parameter

517 486 


561 530 

562While it increases reliability, this technique is limited to 224 tokens, so your list of SKUs needs to be relatively small for this to be a scalable solution.531While it increases reliability, this technique is limited to 224 tokens, so your list of SKUs needs to be relatively small for this to be a scalable solution.

563 532 

564Post-processing with GPT-4533Post-processing with a text model

565 534 

566The second method involves a post-processing step using GPT-4 or GPT-3.5-Turbo.535The second method uses a text model to post-process the transcript.

567 536 

568We start by providing instructions for GPT-4 through the `system_prompt` variable. Similar to what we did with the prompt parameter earlier, we can define our company and product names.537Provide instructions through the `system_prompt` variable. As with the transcription prompt, you can include company and product names.

569 538 

570Post-processing539Post-processing

571 540 


628```597```

629 598 

630 599 

631If you try this on your own audio file, you'll see that GPT-4 corrects many misspellings in the transcript. Due to its larger context window, this method might be more scalable than using Whisper's prompt parameter. It's also more reliable, as GPT-4 can be instructed and guided in ways that aren't possible with Whisper due to its lack of instruction following.600A text model can correct misspellings and handle longer terminology lists than Whisper's 224-token prompt window. Evaluate corrections against the original audio to avoid changing what the speaker said.

Details

1# Spend limits1# Spend limits

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.

4 

3Use spend alerts to track monthly API costs. To stop traffic after tracked spend reaches a configured amount, enforce a hard spend limit for your organization or an individual project.5Use spend alerts to track monthly API costs. To stop traffic after tracked spend reaches a configured amount, enforce a hard spend limit for your organization or an individual project.

4 6 

5Hard spend limits can interrupt production traffic. When tracked spend reaches7Hard spend limits can interrupt production traffic. When tracked spend reaches


26 28 

27 29 

28 30 

29<div data-content-switcher-pane data-value="organization">31Organization

30 <div class="hidden">Organization</div>32 

31 33 

321. Go to [Organization limits](https://platform.openai.com/settings/organization/limits).341. Go to [Organization limits](https://platform.openai.com/settings/organization/limits).

332. In **Spend**, select **Edit spend limit**.352. In **Spend**, select **Edit spend limit**.


354. To make API responses fail after the organization reaches the limit, turn on **Enforce a hard limit**.374. To make API responses fail after the organization reaches the limit, turn on **Enforce a hard limit**.

365. Select **Save**.385. Select **Save**.

37 39 

38 </div>40

39 <div data-content-switcher-pane data-value="project" hidden>41 

40 <div class="hidden">Project</div>42

43 

44

45Project

46 

41 47 

421. Go to [Project settings](https://platform.openai.com/settings/).481. Go to [Project settings](https://platform.openai.com/settings/).

432. Select **Limits**.492. Select **Limits**.


465. To make API responses fail after the project reaches the limit, turn on **Enforce a hard limit**.525. To make API responses fail after the project reaches the limit, turn on **Enforce a hard limit**.

476. Select **Save**.536. Select **Save**.

48 54 

49 </div>

50 

51 55 

52 56 

53## Understand hard-limit behavior57## Understand hard-limit behavior

Details

1# Streaming API responses1# Streaming API responses

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.

4 

3By default, when you make a request to the OpenAI API, we generate the model's entire output before sending it back in a single HTTP response. When generating long outputs, waiting for a response can take time. Streaming responses lets you start printing or processing the beginning of the model's output while it continues generating the full response.5By default, when you make a request to the OpenAI API, we generate the model's entire output before sending it back in a single HTTP response. When generating long outputs, waiting for a response can take time. Streaming responses lets you start printing or processing the beginning of the model's output while it continues generating the full response.

4 6 

5This guide focuses on HTTP streaming (`stream=true`) over server-sent events (SSE). For persistent WebSocket transport with incremental inputs via `previous_response_id`, see [the Responses API WebSocket mode](https://developers.openai.com/api/docs/guides/websocket-mode).7This guide focuses on HTTP streaming (`stream=true`) over server-sent events (SSE). For persistent WebSocket transport with incremental inputs via `previous_response_id`, see [the Responses API WebSocket mode](https://developers.openai.com/api/docs/guides/websocket-mode).


51 53 

52```csharp54```csharp

53using OpenAI.Responses;55using OpenAI.Responses;

56#pragma warning disable OPENAI001

54 57 

55string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;58string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

56OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);59ResponsesClient client = new(key);

57 60 

58var responses = client.CreateResponseStreamingAsync([61var responses = client.CreateResponseStreamingAsync(

59 ResponseItem.CreateUserMessageItem([62 "gpt-5.6",

60 ResponseContentPart.CreateInputTextPart("Say 'double bubble bath' ten times fast."),63 "Say 'double bubble bath' ten times fast."

61 ]),64);

62]);

63 65 

64await foreach (var response in responses)66await foreach (StreamingResponseUpdate response in responses)

65{67{

66 if (response is StreamingResponseOutputTextDeltaUpdate delta)68 if (response is StreamingResponseOutputTextDeltaUpdate delta)

67 {69 {


93 95 

94The Responses API uses semantic events for streaming. Each event is typed with a predefined schema, so you can listen for events you care about.96The Responses API uses semantic events for streaming. Each event is typed with a predefined schema, so you can listen for events you care about.

95 97 

96For a full list of event types, see the [API reference for streaming](https://developers.openai.com/api/docs/api-reference/responses-streaming). Here are a few examples:98For a full list of event types, see the [API reference for streaming](https://developers.openai.com/api/reference/resources/responses). Here are a few examples:

97 99 

98```python100```python

99StreamingEvent = (101StreamingEvent = (


144- `error`146- `error`

145```147```

146 148 

147For a full list of events you can listen for, see the [API reference for streaming](https://developers.openai.com/api/docs/api-reference/responses-streaming).149For a full list of events you can listen for, see the [API reference for streaming](https://developers.openai.com/api/reference/resources/responses).

148 150 

149 151 

150 152 

Details

1# Structured model outputs1# Structured model outputs

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.

4 

3JSON is one of the most widely used formats in the world for applications to exchange data.5JSON is one of the most widely used formats in the world for applications to exchange data.

4 6 

5Structured Outputs is a feature that ensures the model will always generate responses that adhere to your supplied [JSON Schema](https://json-schema.org/overview/what-is-jsonschema), so you don't need to worry about the model omitting a required key, or hallucinating an invalid enum value.7Structured Outputs is a feature that ensures the model will always generate responses that adhere to your supplied [JSON Schema](https://json-schema.org/overview/what-is-jsonschema), so you don't need to worry about the model omitting a required key, or hallucinating an invalid enum value.


12 14 

13In addition to supporting JSON Schema in the REST API, the OpenAI SDKs for [Python](https://github.com/openai/openai-python/blob/main/helpers.md#structured-outputs-parsing-helpers) and [JavaScript](https://github.com/openai/openai-node/blob/master/helpers.md#structured-outputs-parsing-helpers) also make it easy to define object schemas using [Pydantic](https://docs.pydantic.dev/latest/) and [Zod](https://zod.dev/) respectively. Below, you can see how to extract information from unstructured text that conforms to a schema defined in code.15In addition to supporting JSON Schema in the REST API, the OpenAI SDKs for [Python](https://github.com/openai/openai-python/blob/main/helpers.md#structured-outputs-parsing-helpers) and [JavaScript](https://github.com/openai/openai-node/blob/master/helpers.md#structured-outputs-parsing-helpers) also make it easy to define object schemas using [Pydantic](https://docs.pydantic.dev/latest/) and [Zod](https://zod.dev/) respectively. Below, you can see how to extract information from unstructured text that conforms to a schema defined in code.

14 16 

17 

18 

19Getting a structured response

20 

21```javascript

22import OpenAI from "openai";

23import { zodTextFormat } from "openai/helpers/zod";

24import { z } from "zod";

25 

26const openai = new OpenAI();

27 

28const CalendarEvent = z.object({

29 name: z.string(),

30 date: z.string(),

31 participants: z.array(z.string()),

32});

33 

34const response = await openai.responses.parse({

35 model: "gpt-5.6",

36 input: [

37 { role: "system", content: "Extract the event information." },

38 {

39 role: "user",

40 content: "Alice and Bob are going to a science fair on Friday.",

41 },

42 ],

43 text: {

44 format: zodTextFormat(CalendarEvent, "event"),

45 },

46});

47 

48const event = response.output_parsed;

49```

50 

51```python

52from openai import OpenAI

53from pydantic import BaseModel

54 

55client = OpenAI()

56 

57 

58class CalendarEvent(BaseModel):

59 name: str

60 date: str

61 participants: list[str]

62 

63 

64response = client.responses.parse(

65 model="gpt-5.6",

66 input=[

67 {"role": "system", "content": "Extract the event information."},

68 {

69 "role": "user",

70 "content": "Alice and Bob are going to a science fair on Friday.",

71 },

72 ],

73 text_format=CalendarEvent,

74)

75 

76event = response.output_parsed

77```

78 

79 

80 

15### Supported models81### Supported models

16 82 

17Structured 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol). Older models like `gpt-4-turbo` and earlier may use [JSON mode](#json-mode) instead.83Structured 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-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol). Older models like `gpt-4-turbo` and earlier may use [JSON mode](#json-mode) instead.


22 88

23 89 

24When to use Structured Outputs via function calling vs via 90When to use Structured Outputs via function calling vs via

25 <span className="monospace">text.format</span>91

92text.format

26 93 

27 94 

28 95 


84 151 

85 152 

86 153 

87<div data-content-switcher-pane data-value="chain-of-thought">154Chain of thought

88 <div class="hidden">Chain of thought</div>

89 </div>

90 <div data-content-switcher-pane data-value="structured-data" hidden>

91 <div class="hidden">Structured data extraction</div>

92 </div>

93 <div data-content-switcher-pane data-value="ui-generation" hidden>

94 <div class="hidden">UI generation</div>

95 </div>

96 <div data-content-switcher-pane data-value="moderation" hidden>

97 <div class="hidden">Moderation</div>

98 </div>

99 155 

100 156

101 157 

158### Chain of thought

102 159 

160You can ask the model to output an answer in a structured, step-by-step way, to guide the user through the solution.

103 161 

104 162 

105 163 

106 164 

107How to use Structured Outputs with <span className="monospace">text.format</span>165 Structured Outputs for chain-of-thought math tutoring

108 166 

167```javascript

168import OpenAI from "openai";

169import { zodTextFormat } from "openai/helpers/zod";

170import { z } from "zod";

109 171 

110Refusals with Structured Outputs172const openai = new OpenAI();

111 173 

174const Step = z.object({

175 explanation: z.string(),

176 output: z.string(),

177});

112 178 

179const MathReasoning = z.object({

180 steps: z.array(Step),

181 final_answer: z.string(),

182});

113 183 

114When using Structured Outputs with user-generated input, OpenAI models may occasionally refuse to fulfill the request for safety reasons. Since a refusal does not necessarily follow the schema you have supplied in `response_format`, the API response will include a new field called `refusal` to indicate that the model refused to fulfill the request.184const response = await openai.responses.parse({

185 model: "gpt-5.6",

186 input: [

187 {

188 role: "system",

189 content:

190 "You are a helpful math tutor. Guide the user through the solution step by step.",

191 },

192 { role: "user", content: "how can I solve 8x + 7 = -23" },

193 ],

194 text: {

195 format: zodTextFormat(MathReasoning, "math_reasoning"),

196 },

197});

115 198 

116When the `refusal` property appears in your output object, you might present the refusal in your UI, or include conditional logic in code that consumes the response to handle the case of a refused request.199const math_reasoning = response.output_parsed;

200```

117 201 

202```python

203from openai import OpenAI

204from pydantic import BaseModel

118 205 

206client = OpenAI()

119 207 

120 208 

121 ```python

122class Step(BaseModel):209class Step(BaseModel):

123 explanation: str210 explanation: str

124 output: str211 output: str


141 text_format=MathReasoning,228 text_format=MathReasoning,

142)229)

143 230 

144for output in response.output:231math_reasoning = response.output_parsed

145 if output.type != "message":232```

146 continue

147 233 

148 for item in output.content:234```bash

149 if item.type == "refusal":235curl https://api.openai.com/v1/responses \

150 # If the model refuses to respond, you will get a refusal message236 -H "Authorization: Bearer $OPENAI_API_KEY" \

151 print(item.refusal)237 -H "Content-Type: application/json" \

152 continue238 -d '{

239 "model": "gpt-5.6",

240 "input": [

241 {

242 "role": "system",

243 "content": "You are a helpful math tutor. Guide the user through the solution step by step."

244 },

245 {

246 "role": "user",

247 "content": "how can I solve 8x + 7 = -23"

248 }

249 ],

250 "text": {

251 "format": {

252 "type": "json_schema",

253 "name": "math_reasoning",

254 "schema": {

255 "type": "object",

256 "properties": {

257 "steps": {

258 "type": "array",

259 "items": {

260 "type": "object",

261 "properties": {

262 "explanation": { "type": "string" },

263 "output": { "type": "string" }

264 },

265 "required": ["explanation", "output"],

266 "additionalProperties": false

267 }

268 },

269 "final_answer": { "type": "string" }

270 },

271 "required": ["steps", "final_answer"],

272 "additionalProperties": false

273 },

274 "strict": true

275 }

276 }

277 }'

278```

153 279 

154 if not item.parsed:

155 raise Exception("Could not parse response")

156 280 

157 print(item.parsed)281 

282#### Example response

283 

284```json

285{

286 "steps": [

287 {

288 "explanation": "Start with the equation 8x + 7 = -23.",

289 "output": "8x + 7 = -23"

290 },

291 {

292 "explanation": "Subtract 7 from both sides to isolate the term with the variable.",

293 "output": "8x = -23 - 7"

294 },

295 {

296 "explanation": "Simplify the right side of the equation.",

297 "output": "8x = -30"

298 },

299 {

300 "explanation": "Divide both sides by 8 to solve for x.",

301 "output": "x = -30 / 8"

302 },

303 {

304 "explanation": "Simplify the fraction.",

305 "output": "x = -15 / 4"

306 }

307 ],

308 "final_answer": "x = -15 / 4"

309}

158```310```

159 311 

312 

313

314 

315

316 

317

318Structured data extraction

319 

320

321 

322### Structured data extraction

323 

324You can define structured fields to extract from unstructured input data, such as research papers.

325 

326 

327 

328 Extracting data from research papers using Structured Outputs

329 

160```javascript330```javascript

161const Step = z.object({331import OpenAI from "openai";

162 explanation: z.string(),332import { zodTextFormat } from "openai/helpers/zod";

163 output: z.string(),333import { z } from "zod";

164});

165 334 

166const MathReasoning = z.object({335const openai = new OpenAI();

167 steps: z.array(Step),336 

168 final_answer: z.string(),337const ResearchPaperExtraction = z.object({

338 title: z.string(),

339 authors: z.array(z.string()),

340 abstract: z.string(),

341 keywords: z.array(z.string()),

169});342});

170 343 

171const response = await openai.responses.parse({344const response = await openai.responses.parse({


174 {347 {

175 role: "system",348 role: "system",

176 content:349 content:

177 "You are a helpful math tutor. Guide the user through the solution step by step.",350 "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.",

178 },351 },

179 { role: "user", content: "how can I solve 8x + 7 = -23" },352 { role: "user", content: "..." },

180 ],353 ],

181 text: {354 text: {

182 format: zodTextFormat(MathReasoning, "math_response"),355 format: zodTextFormat(ResearchPaperExtraction, "research_paper_extraction"),

183 },356 },

184});357});

185 358 

186for (const output of response.output) {359const research_paper = response.output_parsed;

187 if (output.type !== "message") {

188 continue;

189 }

190 

191 for (const item of output.content) {

192 if (item.type == "refusal") {

193 // If the model refuses to respond, you will get a refusal message

194 console.log(item.refusal);

195 continue;

196 }

197 

198 if (!item.parsed) {

199 throw new Error("Could not parse response");

200 }

201 

202 console.log(item.parsed);

203 }

204}

205```360```

206 361 

362```python

363from openai import OpenAI

364from pydantic import BaseModel

207 365 

366client = OpenAI()

208 367 

209The API response from a refusal will look something like this:368 

369class ResearchPaperExtraction(BaseModel):

370 title: str

371 authors: list[str]

372 abstract: str

373 keywords: list[str]

210 374 

211 375 

376response = client.responses.parse(

377 model="gpt-5.6",

378 input=[

379 {

380 "role": "system",

381 "content": "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.",

382 },

383 {

384 "role": "user",

385 "content": (

386 "Attention Is All You Need by Ashish Vaswani, Noam Shazeer, "

387 "Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, "

388 "Łukasz Kaiser, and Illia Polosukhin. We propose the "

389 "Transformer, a sequence transduction architecture based "

390 "entirely on attention. Keywords: transformers, attention, "

391 "sequence transduction."

392 ),

393 },

394 ],

395 text_format=ResearchPaperExtraction,

396)

212 397 

398research_paper = response.output_parsed

399```

213 400 

214 ```json401```bash

215{402curl https://api.openai.com/v1/responses \

216 "id": "resp_1234567890",403 -H "Authorization: Bearer $OPENAI_API_KEY" \

217 "object": "response",404 -H "Content-Type: application/json" \

218 "created_at": 1721596428,405 -d '{

219 "status": "completed",406 "model": "gpt-5.6",

220 "completed_at": 1721596429,407 "input": [

221 "error": null,

222 "incomplete_details": null,

223 "input": [],

224 "instructions": null,

225 "max_output_tokens": null,

226 "model": "gpt-4o-2024-08-06",

227 "output": [{

228 "id": "msg_1234567890",

229 "type": "message",

230 "role": "assistant",

231 "content": [

232 // highlight-start

233 {408 {

234 "type": "refusal",409 "role": "system",

235 "refusal": "I'm sorry, I cannot assist with that request."410 "content": "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."

411 },

412 {

413 "role": "user",

414 "content": "..."

236 }415 }

237 // highlight-end416 ],

238 ]417 "text": {

239 }],418 "format": {

240 "usage": {419 "type": "json_schema",

241 "input_tokens": 81,420 "name": "research_paper_extraction",

242 "output_tokens": 11,421 "schema": {

243 "total_tokens": 92,422 "type": "object",

244 "output_tokens_details": {423 "properties": {

245 "reasoning_tokens": 0,424 "title": { "type": "string" },

425 "authors": {

426 "type": "array",

427 "items": { "type": "string" }

428 },

429 "abstract": { "type": "string" },

430 "keywords": {

431 "type": "array",

432 "items": { "type": "string" }

246 }433 }

247 },434 },

435 "required": ["title", "authors", "abstract", "keywords"],

436 "additionalProperties": false

437 },

438 "strict": true

439 }

440 }

441 }'

442```

443 

444 

445 

446#### Example response

447 

448```json

449{

450 "title": "Application of Quantum Algorithms in Interstellar Navigation: A New Frontier",

451 "authors": ["Dr. Stella Voyager", "Dr. Nova Star", "Dr. Lyra Hunter"],

452 "abstract": "This paper investigates the utilization of quantum algorithms to improve interstellar navigation systems. By leveraging quantum superposition and entanglement, our proposed navigation system can calculate optimal travel paths through space-time anomalies more efficiently than classical methods. Experimental simulations suggest a significant reduction in travel time and fuel consumption for interstellar missions.",

453 "keywords": [

454 "Quantum algorithms",

455 "interstellar navigation",

456 "space-time anomalies",

457 "quantum superposition",

458 "quantum entanglement",

459 "space travel"

460 ]

248}461}

249```462```

250 463 

251 464 

252 465

253 466 

254Tips and best practices

255 467

256 468 

257 469

258#### Handling user-generated input470UI generation

259 471 

260If your application is using user-generated input, make sure your prompt includes instructions on how to handle situations where the input cannot result in a valid response.

261 472

262The model will always try to adhere to the provided schema, which can result in hallucinations if the input is completely unrelated to the schema.

263 473 

264You could include language in your prompt to specify that you want to return empty parameters, or a specific sentence, if the model detects that the input is incompatible with the task.474### UI Generation

265 475 

266#### Handling mistakes476You can generate valid HTML by representing it as recursive data structures with constraints, like enums.

267 477 

268Structured Outputs can still contain mistakes. If you see mistakes, try adjusting your instructions, providing examples in the system instructions, or splitting tasks into simpler subtasks. Refer to the [prompt engineering guide](https://developers.openai.com/api/docs/guides/prompt-engineering) for more guidance on how to tweak your inputs.

269 478 

270#### Avoid JSON schema divergence

271 479 

272To prevent your JSON Schema and corresponding types in your programming language from diverging, we strongly recommend using the native Pydantic/zod sdk support.

273 480 

274If you prefer to specify the JSON schema directly, you could add CI rules that flag when either the JSON schema or underlying data objects are edited, or add a CI step that auto-generates the JSON Schema from type definitions (or vice-versa).481 Generating HTML using Structured Outputs

275 482 

276## Streaming483```javascript

484import OpenAI from "openai";

485import { zodTextFormat } from "openai/helpers/zod";

486import { z } from "zod";

487 

488const openai = new OpenAI();

489 

490const UI = z.lazy(() =>

491 z.object({

492 type: z.enum(["div", "button", "header", "section", "field", "form"]),

493 label: z.string(),

494 children: z.array(UI),

495 attributes: z.array(

496 z.object({

497 name: z.string(),

498 value: z.string(),

499 })

500 ),

501 })

502);

277 503 

278## Supported schemas504const response = await openai.responses.parse({

505 model: "gpt-5.6",

506 input: [

507 {

508 role: "system",

509 content: "You are a UI generator AI. Convert the user input into a UI.",

510 },

511 {

512 role: "user",

513 content: "Make a User Profile Form",

514 },

515 ],

516 text: {

517 format: zodTextFormat(UI, "ui"),

518 },

519});

279 520 

280## JSON mode521const ui = response.output_parsed;

522```

281 523 

282JSON mode is a more basic version of the Structured Outputs feature. While524```python

283 JSON mode ensures that model output is valid JSON, Structured Outputs reliably525from enum import Enum

284 matches the model's output to the schema you specify. We recommend you use526from typing import List

285 Structured Outputs if it is supported for your use case.

286 527 

287When JSON mode is turned on, the model's output is ensured to be valid JSON, except for in some edge cases that you should detect and handle appropriately.528from openai import OpenAI

529from pydantic import BaseModel

288 530 

531client = OpenAI()

289 532 

290 533 

534class UIType(str, Enum):

535 div = "div"

536 button = "button"

537 header = "header"

538 section = "section"

539 field = "field"

540 form = "form"

291 541 

292To turn on JSON mode with the Responses API you can set the `text.format` to `{ "type": "json_object" }`. If you are using function calling, JSON mode is always turned on.

293 542 

543class Attribute(BaseModel):

544 name: str

545 value: str

294 546 

295Important notes:

296 547 

297- When using JSON mode, you must always instruct the model to produce JSON via some message in the conversation, for example via your system message. If you don't include an explicit instruction to generate JSON, the model may generate an unending stream of whitespace and the request may run continually until it reaches the token limit. To help ensure you don't forget, the API will throw an error if the string "JSON" does not appear somewhere in the context.548class UI(BaseModel):

298- JSON mode will not guarantee the output matches any specific schema, only that it is valid and parses without errors. You should use Structured Outputs to ensure it matches your schema, or if that is not possible, you should use a validation library and potentially retries to ensure that the output matches your desired schema.549 type: UIType

299- Your application must detect and handle the edge cases that can result in the model output not being a complete JSON object (see below)550 label: str

551 children: List["UI"]

552 attributes: List[Attribute]

300 553 

301Handling edge cases554 

555UI.model_rebuild() # This is required to enable recursive types

556 

557 

558class Response(BaseModel):

559 ui: UI

560 

561 

562response = client.responses.parse(

563 model="gpt-5.6",

564 input=[

565 {

566 "role": "system",

567 "content": "You are a UI generator AI. Convert the user input into a UI.",

568 },

569 {"role": "user", "content": "Make a User Profile Form"},

570 ],

571 text_format=Response,

572)

573 

574ui = response.output_parsed

575```

576 

577```bash

578curl https://api.openai.com/v1/responses \

579 -H "Authorization: Bearer $OPENAI_API_KEY" \

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

581 -d '{

582 "model": "gpt-5.6",

583 "input": [

584 {

585 "role": "system",

586 "content": "You are a UI generator AI. Convert the user input into a UI."

587 },

588 {

589 "role": "user",

590 "content": "Make a User Profile Form"

591 }

592 ],

593 "text": {

594 "format": {

595 "type": "json_schema",

596 "name": "ui",

597 "description": "Dynamically generated UI",

598 "schema": {

599 "type": "object",

600 "properties": {

601 "type": {

602 "type": "string",

603 "description": "The type of the UI component",

604 "enum": ["div", "button", "header", "section", "field", "form"]

605 },

606 "label": {

607 "type": "string",

608 "description": "The label of the UI component, used for buttons or form fields"

609 },

610 "children": {

611 "type": "array",

612 "description": "Nested UI components",

613 "items": {"$ref": "#"}

614 },

615 "attributes": {

616 "type": "array",

617 "description": "Arbitrary attributes for the UI component, suitable for any element",

618 "items": {

619 "type": "object",

620 "properties": {

621 "name": {

622 "type": "string",

623 "description": "The name of the attribute, for example onClick or className"

624 },

625 "value": {

626 "type": "string",

627 "description": "The value of the attribute"

628 }

629 },

630 "required": ["name", "value"],

631 "additionalProperties": false

632 }

633 }

634 },

635 "required": ["type", "label", "children", "attributes"],

636 "additionalProperties": false

637 },

638 "strict": true

639 }

640 }

641 }'

642```

643 

644 

645 

646#### Example response

647 

648```json

649{

650 "type": "form",

651 "label": "User Profile Form",

652 "children": [

653 {

654 "type": "div",

655 "label": "",

656 "children": [

657 {

658 "type": "field",

659 "label": "First Name",

660 "children": [],

661 "attributes": [

662 {

663 "name": "type",

664 "value": "text"

665 },

666 {

667 "name": "name",

668 "value": "firstName"

669 },

670 {

671 "name": "placeholder",

672 "value": "Enter your first name"

673 }

674 ]

675 },

676 {

677 "type": "field",

678 "label": "Last Name",

679 "children": [],

680 "attributes": [

681 {

682 "name": "type",

683 "value": "text"

684 },

685 {

686 "name": "name",

687 "value": "lastName"

688 },

689 {

690 "name": "placeholder",

691 "value": "Enter your last name"

692 }

693 ]

694 }

695 ],

696 "attributes": []

697 },

698 {

699 "type": "button",

700 "label": "Submit",

701 "children": [],

702 "attributes": [

703 {

704 "name": "type",

705 "value": "submit"

706 }

707 ]

708 }

709 ],

710 "attributes": [

711 {

712 "name": "method",

713 "value": "post"

714 },

715 {

716 "name": "action",

717 "value": "/submit-profile"

718 }

719 ]

720}

721```

722 

723 

724

725 

726

727 

728

729Moderation

730 

731

732 

733### Moderation

734 

735You can classify inputs on multiple categories, which is a common way of doing moderation.

736 

737 

738 

739 

740 Moderation using Structured Outputs

741 

742```javascript

743import OpenAI from "openai";

744import { zodTextFormat } from "openai/helpers/zod";

745import { z } from "zod";

746 

747const openai = new OpenAI();

748 

749const ContentCompliance = z.object({

750 is_violating: z.boolean(),

751 category: z.enum(["violence", "sexual", "self_harm"]).nullable(),

752 explanation_if_violating: z.string().nullable(),

753});

754 

755const response = await openai.responses.parse({

756 model: "gpt-5.6",

757 input: [

758 {

759 role: "system",

760 content:

761 "Determine if the user input violates specific guidelines and explain if they do.",

762 },

763 {

764 role: "user",

765 content: "How do I prepare for a job interview?",

766 },

767 ],

768 text: {

769 format: zodTextFormat(ContentCompliance, "content_compliance"),

770 },

771});

772 

773const compliance = response.output_parsed;

774```

775 

776```python

777from enum import Enum

778from typing import Optional

779 

780from openai import OpenAI

781from pydantic import BaseModel

782 

783client = OpenAI()

784 

785 

786class Category(str, Enum):

787 violence = "violence"

788 sexual = "sexual"

789 self_harm = "self_harm"

790 

791 

792class ContentCompliance(BaseModel):

793 is_violating: bool

794 category: Optional[Category]

795 explanation_if_violating: Optional[str]

796 

797 

798response = client.responses.parse(

799 model="gpt-5.6",

800 input=[

801 {

802 "role": "system",

803 "content": "Determine if the user input violates specific guidelines and explain if they do.",

804 },

805 {"role": "user", "content": "How do I prepare for a job interview?"},

806 ],

807 text_format=ContentCompliance,

808)

809 

810compliance = response.output_parsed

811```

812 

813```bash

814curl https://api.openai.com/v1/responses \

815 -H "Authorization: Bearer $OPENAI_API_KEY" \

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

817 -d '{

818 "model": "gpt-5.6",

819 "input": [

820 {

821 "role": "system",

822 "content": "Determine if the user input violates specific guidelines and explain if they do."

823 },

824 {

825 "role": "user",

826 "content": "How do I prepare for a job interview?"

827 }

828 ],

829 "text": {

830 "format": {

831 "type": "json_schema",

832 "name": "content_compliance",

833 "description": "Determines if content is violating specific moderation rules",

834 "schema": {

835 "type": "object",

836 "properties": {

837 "is_violating": {

838 "type": "boolean",

839 "description": "Indicates if the content is violating guidelines"

840 },

841 "category": {

842 "type": ["string", "null"],

843 "description": "Type of violation, if the content is violating guidelines. Null otherwise.",

844 "enum": ["violence", "sexual", "self_harm"]

845 },

846 "explanation_if_violating": {

847 "type": ["string", "null"],

848 "description": "Explanation of why the content is violating"

849 }

850 },

851 "required": ["is_violating", "category", "explanation_if_violating"],

852 "additionalProperties": false

853 },

854 "strict": true

855 }

856 }

857 }'

858```

859 

860 

861 

862#### Example response

863 

864```json

865{

866 "is_violating": false,

867 "category": null,

868 "explanation_if_violating": null

869}

870```

871 

872 

873 

874 

875 

876 

877 

878 

879How to use Structured Outputs with

880text.format

881 

882 

883 

884 

885Step 1: Define your schema

886 

887First you must design the JSON Schema that the model should be constrained to follow. See the [examples](https://developers.openai.com/api/docs/guides/structured-outputs#examples) at the top of this guide for reference.

888 

889While Structured Outputs supports much of JSON Schema, some features are unavailable either for performance or technical reasons. See [here](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) for more details.

890 

891#### Tips for your JSON Schema

892 

893To maximize the quality of model generations, we recommend the following:

894 

895- Name keys clearly and intuitively

896- Create clear titles and descriptions for important keys in your structure

897- Create and use evals to determine the structure that works best for your use case

898 

899Step 2: Supply your schema in the API call

900 

901To use Structured Outputs, simply specify

902 

903 

904 

905 

906```json

907text: { format: { type: "json_schema", "strict": true, "schema": … } }

908```

909 

910 

911For example:

912 

913 

914 

915 

916```python

917response = client.responses.create(

918 model="gpt-5.6",

919 input=[

920 {

921 "role": "system",

922 "content": "You are a helpful math tutor. Guide the user through the solution step by step.",

923 },

924 {"role": "user", "content": "how can I solve 8x + 7 = -23"},

925 ],

926 text={

927 "format": {

928 "type": "json_schema",

929 "name": "math_response",

930 "schema": {

931 "type": "object",

932 "properties": {

933 "steps": {

934 "type": "array",

935 "items": {

936 "type": "object",

937 "properties": {

938 "explanation": {"type": "string"},

939 "output": {"type": "string"},

940 },

941 "required": ["explanation", "output"],

942 "additionalProperties": False,

943 },

944 },

945 "final_answer": {"type": "string"},

946 },

947 "required": ["steps", "final_answer"],

948 "additionalProperties": False,

949 },

950 "strict": True,

951 },

952 },

953)

954 

955print(response.output_text)

956```

957 

958```javascript

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

960 model: "gpt-5.6",

961 input: [

962 {

963 role: "system",

964 content:

965 "You are a helpful math tutor. Guide the user through the solution step by step.",

966 },

967 { role: "user", content: "how can I solve 8x + 7 = -23" },

968 ],

969 text: {

970 format: {

971 type: "json_schema",

972 name: "math_response",

973 schema: {

974 type: "object",

975 properties: {

976 steps: {

977 type: "array",

978 items: {

979 type: "object",

980 properties: {

981 explanation: { type: "string" },

982 output: { type: "string" },

983 },

984 required: ["explanation", "output"],

985 additionalProperties: false,

986 },

987 },

988 final_answer: { type: "string" },

989 },

990 required: ["steps", "final_answer"],

991 additionalProperties: false,

992 },

993 strict: true,

994 },

995 },

996});

997 

998console.log(response.output_text);

999```

1000 

1001```bash

1002curl https://api.openai.com/v1/responses \

1003 -H "Authorization: Bearer $OPENAI_API_KEY" \

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

1005 -d '{

1006 "model": "gpt-5.6",

1007 "input": [

1008 {

1009 "role": "system",

1010 "content": "You are a helpful math tutor. Guide the user through the solution step by step."

1011 },

1012 {

1013 "role": "user",

1014 "content": "how can I solve 8x + 7 = -23"

1015 }

1016 ],

1017 "text": {

1018 "format": {

1019 "type": "json_schema",

1020 "name": "math_response",

1021 "schema": {

1022 "type": "object",

1023 "properties": {

1024 "steps": {

1025 "type": "array",

1026 "items": {

1027 "type": "object",

1028 "properties": {

1029 "explanation": { "type": "string" },

1030 "output": { "type": "string" }

1031 },

1032 "required": ["explanation", "output"],

1033 "additionalProperties": false

1034 }

1035 },

1036 "final_answer": { "type": "string" }

1037 },

1038 "required": ["steps", "final_answer"],

1039 "additionalProperties": false

1040 },

1041 "strict": true

1042 }

1043 }

1044 }'

1045```

1046 

1047 

1048 

1049**Note:** the first request you make with any schema will have additional latency as our API processes the schema, but subsequent requests with the same schema will not have additional latency.

1050 

1051Step 3: Handle edge cases

1052 

1053In some cases, the model might not generate a valid response that matches the provided JSON schema.

1054 

1055This can happen in the case of a refusal, if the model refuses to answer for safety reasons, or if for example you reach a max tokens limit and the response is incomplete.

1056 

1057 

1058 

1059 

1060```javascript

1061try {

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

1063 model: "gpt-5.6",

1064 input: [

1065 {

1066 role: "system",

1067 content:

1068 "You are a helpful math tutor. Guide the user through the solution step by step.",

1069 },

1070 {

1071 role: "user",

1072 content: "how can I solve 8x + 7 = -23",

1073 },

1074 ],

1075 max_output_tokens: 50,

1076 text: {

1077 format: {

1078 type: "json_schema",

1079 name: "math_response",

1080 schema: {

1081 type: "object",

1082 properties: {

1083 steps: {

1084 type: "array",

1085 items: {

1086 type: "object",

1087 properties: {

1088 explanation: {

1089 type: "string",

1090 },

1091 output: {

1092 type: "string",

1093 },

1094 },

1095 required: ["explanation", "output"],

1096 additionalProperties: false,

1097 },

1098 },

1099 final_answer: {

1100 type: "string",

1101 },

1102 },

1103 required: ["steps", "final_answer"],

1104 additionalProperties: false,

1105 },

1106 strict: true,

1107 },

1108 },

1109 });

1110 

1111 if (

1112 response.status === "incomplete" &&

1113 response.incomplete_details.reason === "max_output_tokens"

1114 ) {

1115 // Handle the case where the model did not return a complete response

1116 throw new Error("Incomplete response");

1117 }

1118 

1119 const message = response.output.find((item) => item.type === "message");

1120 const math_response = message?.content[0];

1121 

1122 if (!math_response) {

1123 throw new Error("No response content");

1124 }

1125 

1126 if (math_response.type === "refusal") {

1127 // handle refusal

1128 console.log(math_response.refusal);

1129 } else if (math_response.type === "output_text") {

1130 console.log(math_response.text);

1131 } else {

1132 throw new Error("No response content");

1133 }

1134} catch (e) {

1135 // Handle edge cases

1136 console.error(e);

1137}

1138```

1139 

1140```python

1141try:

1142 response = client.responses.create(

1143 model="gpt-5.6",

1144 input=[

1145 {

1146 "role": "system",

1147 "content": "You are a helpful math tutor. Guide the user through the solution step by step.",

1148 },

1149 {"role": "user", "content": "how can I solve 8x + 7 = -23"},

1150 ],

1151 text={

1152 "format": {

1153 "type": "json_schema",

1154 "name": "math_response",

1155 "strict": True,

1156 "schema": {

1157 "type": "object",

1158 "properties": {

1159 "steps": {

1160 "type": "array",

1161 "items": {

1162 "type": "object",

1163 "properties": {

1164 "explanation": {"type": "string"},

1165 "output": {"type": "string"},

1166 },

1167 "required": ["explanation", "output"],

1168 "additionalProperties": False,

1169 },

1170 },

1171 "final_answer": {"type": "string"},

1172 },

1173 "required": ["steps", "final_answer"],

1174 "additionalProperties": False,

1175 },

1176 },

1177 },

1178 max_output_tokens=50,

1179 )

1180 

1181 if (

1182 response.status == "incomplete"

1183 and response.incomplete_details.reason == "max_output_tokens"

1184 ):

1185 raise Exception("Incomplete response")

1186 

1187 message = next((item for item in response.output if item.type == "message"), None)

1188 math_response = message.content[0] if message and message.content else None

1189 

1190 if not math_response:

1191 raise Exception("No response content")

1192 

1193 if math_response.type == "refusal":

1194 print(math_response.refusal)

1195 elif math_response.type == "output_text":

1196 print(math_response.text)

1197 else:

1198 raise Exception("No response content")

1199except Exception as e:

1200 # handle errors like finish_reason, refusal, content_filter, etc.

1201 print(e)

1202```

1203 

1204 

1205 

1206 

1207 

1208 

1209 

1210Refusals with Structured Outputs

1211 

1212 

1213 

1214When using Structured Outputs with user-generated input, OpenAI models may occasionally refuse to fulfill the request for safety reasons. Since a refusal does not necessarily follow the schema you have supplied in `response_format`, the API response will include a new field called `refusal` to indicate that the model refused to fulfill the request.

1215 

1216When the `refusal` property appears in your output object, you might present the refusal in your UI, or include conditional logic in code that consumes the response to handle the case of a refused request.

1217 

1218 

1219 

1220 

1221```python

1222class Step(BaseModel):

1223 explanation: str

1224 output: str

1225 

1226 

1227class MathReasoning(BaseModel):

1228 steps: list[Step]

1229 final_answer: str

1230 

1231 

1232response = client.responses.parse(

1233 model="gpt-5.6",

1234 input=[

1235 {

1236 "role": "system",

1237 "content": "You are a helpful math tutor. Guide the user through the solution step by step.",

1238 },

1239 {"role": "user", "content": "how can I solve 8x + 7 = -23"},

1240 ],

1241 text_format=MathReasoning,

1242)

1243 

1244for output in response.output:

1245 if output.type != "message":

1246 continue

1247 

1248 for item in output.content:

1249 if item.type == "refusal":

1250 # If the model refuses to respond, you will get a refusal message

1251 print(item.refusal)

1252 continue

1253 

1254 if not item.parsed:

1255 raise Exception("Could not parse response")

1256 

1257 print(item.parsed)

1258```

1259 

1260```javascript

1261const Step = z.object({

1262 explanation: z.string(),

1263 output: z.string(),

1264});

1265 

1266const MathReasoning = z.object({

1267 steps: z.array(Step),

1268 final_answer: z.string(),

1269});

1270 

1271const response = await openai.responses.parse({

1272 model: "gpt-5.6",

1273 input: [

1274 {

1275 role: "system",

1276 content:

1277 "You are a helpful math tutor. Guide the user through the solution step by step.",

1278 },

1279 { role: "user", content: "how can I solve 8x + 7 = -23" },

1280 ],

1281 text: {

1282 format: zodTextFormat(MathReasoning, "math_response"),

1283 },

1284});

1285 

1286for (const output of response.output) {

1287 if (output.type !== "message") {

1288 continue;

1289 }

1290 

1291 for (const item of output.content) {

1292 if (item.type == "refusal") {

1293 // If the model refuses to respond, you will get a refusal message

1294 console.log(item.refusal);

1295 continue;

1296 }

1297 

1298 if (!item.parsed) {

1299 throw new Error("Could not parse response");

1300 }

1301 

1302 console.log(item.parsed);

1303 }

1304}

1305```

1306 

1307 

1308 

1309The API response from a refusal will look something like this:

1310 

1311 

1312 

1313 

1314```json

1315{

1316 "id": "resp_1234567890",

1317 "object": "response",

1318 "created_at": 1721596428,

1319 "status": "completed",

1320 "completed_at": 1721596429,

1321 "error": null,

1322 "incomplete_details": null,

1323 "input": [],

1324 "instructions": null,

1325 "max_output_tokens": null,

1326 "model": "gpt-4o-2024-08-06",

1327 "output": [{

1328 "id": "msg_1234567890",

1329 "type": "message",

1330 "role": "assistant",

1331 "content": [

1332 // highlight-start

1333 {

1334 "type": "refusal",

1335 "refusal": "I'm sorry, I cannot assist with that request."

1336 }

1337 // highlight-end

1338 ]

1339 }],

1340 "usage": {

1341 "input_tokens": 81,

1342 "output_tokens": 11,

1343 "total_tokens": 92,

1344 "output_tokens_details": {

1345 "reasoning_tokens": 0,

1346 }

1347 },

1348}

1349```

1350 

1351 

1352 

1353 

1354Tips and best practices

1355 

1356 

1357 

1358#### Handling user-generated input

1359 

1360If your application is using user-generated input, make sure your prompt includes instructions on how to handle situations where the input cannot result in a valid response.

1361 

1362The model will always try to adhere to the provided schema, which can result in hallucinations if the input is completely unrelated to the schema.

1363 

1364You could include language in your prompt to specify that you want to return empty parameters, or a specific sentence, if the model detects that the input is incompatible with the task.

1365 

1366#### Handling mistakes

1367 

1368Structured Outputs can still contain mistakes. If you see mistakes, try adjusting your instructions, providing examples in the system instructions, or splitting tasks into simpler subtasks. Refer to the [prompt engineering guide](https://developers.openai.com/api/docs/guides/prompt-engineering) for more guidance on how to tweak your inputs.

1369 

1370#### Avoid JSON schema divergence

1371 

1372To prevent your JSON Schema and corresponding types in your programming language from diverging, we strongly recommend using the native Pydantic/zod sdk support.

1373 

1374If you prefer to specify the JSON schema directly, you could add CI rules that flag when either the JSON schema or underlying data objects are edited, or add a CI step that auto-generates the JSON Schema from type definitions (or vice-versa).

1375 

1376## Streaming

1377 

1378 

1379 

1380You can use streaming to process model responses or function call arguments as they are being generated, and parse them as structured data.

1381 

1382That way, you don't have to wait for the entire response to complete before handling it.

1383This is particularly useful if you would like to display JSON fields one by one, or handle function call arguments as soon as they are available.

1384 

1385We recommend relying on the SDKs to handle streaming with Structured Outputs.

1386 

1387 

1388 

1389 

1390```python

1391from typing import List

1392 

1393from openai import OpenAI

1394from pydantic import BaseModel

1395 

1396 

1397class EntitiesModel(BaseModel):

1398 attributes: List[str]

1399 colors: List[str]

1400 animals: List[str]

1401 

1402 

1403client = OpenAI()

1404 

1405with client.responses.stream(

1406 model="gpt-5.6",

1407 input=[

1408 {"role": "system", "content": "Extract entities from the input text"},

1409 {

1410 "role": "user",

1411 "content": "The quick brown fox jumps over the lazy dog with piercing blue eyes",

1412 },

1413 ],

1414 text_format=EntitiesModel,

1415) as stream:

1416 for event in stream:

1417 if event.type == "response.refusal.delta":

1418 print(event.delta, end="")

1419 elif event.type == "response.output_text.delta":

1420 print(event.delta, end="")

1421 elif event.type == "response.error":

1422 print(event.error, end="")

1423 elif event.type == "response.completed":

1424 print("Completed") # print(event.response.output)

1425 

1426 final_response = stream.get_final_response()

1427 print(final_response)

1428```

1429 

1430```javascript

1431import { OpenAI } from "openai";

1432import { zodTextFormat } from "openai/helpers/zod";

1433import { z } from "zod";

1434 

1435const EntitiesSchema = z.object({

1436 attributes: z.array(z.string()),

1437 colors: z.array(z.string()),

1438 animals: z.array(z.string()),

1439});

1440 

1441const openai = new OpenAI();

1442const stream = openai.responses

1443 .stream({

1444 model: "gpt-5.6",

1445 input: [

1446 { role: "user", content: "What's the weather like in Paris today?" },

1447 ],

1448 text: {

1449 format: zodTextFormat(EntitiesSchema, "entities"),

1450 },

1451 })

1452 .on("response.refusal.delta", (event) => {

1453 process.stdout.write(event.delta);

1454 })

1455 .on("response.output_text.delta", (event) => {

1456 process.stdout.write(event.delta);

1457 })

1458 .on("response.output_text.done", () => {

1459 process.stdout.write("\n");

1460 })

1461 .on("error", (error) => {

1462 console.error(error);

1463 });

1464 

1465const result = await stream.finalResponse();

1466 

1467console.log(result);

1468```

1469 

1470 

1471 

1472## Supported schemas

1473 

1474 

1475 

1476Structured Outputs supports a subset of the [JSON Schema](https://json-schema.org/docs) language.

1477 

1478#### Supported types

1479 

1480The following types are supported for Structured Outputs:

1481 

1482- String

1483- Number

1484- Boolean

1485- Integer

1486- Object

1487- Array

1488- Enum

1489- anyOf

1490 

1491#### Supported properties

1492 

1493In addition to specifying the type of a property, you can specify a selection of additional constraints:

1494 

1495**Supported `string` properties:**

1496 

1497- `pattern` — A regular expression that the string must match.

1498- `format` — Predefined formats for strings. Currently supported:

1499 - `date-time`

1500 - `time`

1501 - `date`

1502 - `duration`

1503 - `email`

1504 - `hostname`

1505 - `ipv4`

1506 - `ipv6`

1507 - `uuid`

1508 

1509**Supported `number` properties:**

1510 

1511- `multipleOf` — The number must be a multiple of this value.

1512- `maximum` — The number must be less than or equal to this value.

1513- `exclusiveMaximum` — The number must be less than this value.

1514- `minimum` — The number must be greater than or equal to this value.

1515- `exclusiveMinimum` — The number must be greater than this value.

1516 

1517**Supported `array` properties:**

1518 

1519- `minItems` — The array must have at least this many items.

1520- `maxItems` — The array must have at most this many items.

1521 

1522Here are some examples on how you can use these type restrictions:

1523 

1524 

1525 

1526String Restrictions

1527 

1528```json

1529{

1530 "name": "user_data",

1531 "strict": true,

1532 "schema": {

1533 "type": "object",

1534 "properties": {

1535 "name": {

1536 "type": "string",

1537 "description": "The name of the user"

1538 },

1539 "username": {

1540 "type": "string",

1541 "description": "The username of the user. Must start with @",

1542 // highlight-start

1543 "pattern": "^@[a-zA-Z0-9_]+$"

1544 // highlight-end

1545 },

1546 "email": {

1547 "type": "string",

1548 "description": "The email of the user",

1549 // highlight-start

1550 "format": "email"

1551 // highlight-end

1552 }

1553 },

1554 "additionalProperties": false,

1555 "required": [

1556 "name", "username", "email"

1557 ]

1558 }

1559}

1560```

1561 

1562

1563 

1564

1565 

1566

1567Number Restrictions

1568 

1569```json

1570{

1571 "name": "weather_data",

1572 "strict": true,

1573 "schema": {

1574 "type": "object",

1575 "properties": {

1576 "location": {

1577 "type": "string",

1578 "description": "The location to get the weather for"

1579 },

1580 "unit": {

1581 "type": ["string", "null"],

1582 "description": "The unit to return the temperature in",

1583 "enum": ["F", "C"]

1584 },

1585 "value": {

1586 "type": "number",

1587 "description": "The actual temperature value in the location",

1588 // highlight-start

1589 "minimum": -130,

1590 "maximum": 130

1591 // highlight-end

1592 }

1593 },

1594 "additionalProperties": false,

1595 "required": [

1596 "location", "unit", "value"

1597 ]

1598 }

1599}

1600```

1601 

1602 

1603 

1604Note these constraints are [not yet supported for fine-tuned

1605 models](#some-type-specific-keywords-are-not-yet-supported).

1606 

1607#### Root objects must not be `anyOf` and must be an object

1608 

1609Note that the root level object of a schema must be an object, and not use `anyOf`. A pattern that appears in Zod (as one example) is using a discriminated union, which produces an `anyOf` at the top level. So code such as the following won't work:

1610 

1611```javascript

1612import { z } from "zod";

1613import { zodResponseFormat } from "openai/helpers/zod";

1614 

1615const BaseResponseSchema = z.object({

1616 /* ... */

1617});

1618const UnsuccessfulResponseSchema = z.object({

1619 /* ... */

1620});

1621 

1622const finalSchema = z.discriminatedUnion("status", [

1623 BaseResponseSchema,

1624 UnsuccessfulResponseSchema,

1625]);

1626 

1627// Invalid JSON Schema for Structured Outputs

1628const json = zodResponseFormat(finalSchema, "final_schema");

1629```

1630 

1631 

1632#### All fields must be `required`

1633 

1634To use Structured Outputs, all fields or function parameters must be specified as `required`.

1635 

1636```json

1637{

1638 "name": "get_weather",

1639 "description": "Fetches the weather in the given location",

1640 "strict": true,

1641 "parameters": {

1642 "type": "object",

1643 "properties": {

1644 "location": {

1645 "type": "string",

1646 "description": "The location to get the weather for"

1647 },

1648 "unit": {

1649 "type": "string",

1650 "description": "The unit to return the temperature in",

1651 "enum": ["F", "C"]

1652 }

1653 },

1654 "additionalProperties": false,

1655 // highlight-start

1656 "required": ["location", "unit"]

1657 // highlight-end

1658 }

1659}

1660```

1661 

1662 

1663Although all fields must be required (and the model will return a value for each parameter), it is possible to emulate an optional parameter by using a union type with `null`.

1664 

1665```json

1666{

1667 "name": "get_weather",

1668 "description": "Fetches the weather in the given location",

1669 "strict": true,

1670 "parameters": {

1671 "type": "object",

1672 "properties": {

1673 "location": {

1674 "type": "string",

1675 "description": "The location to get the weather for"

1676 },

1677 "unit": {

1678 // highlight-start

1679 "type": ["string", "null"],

1680 // highlight-end

1681 "description": "The unit to return the temperature in",

1682 "enum": ["F", "C"]

1683 }

1684 },

1685 "additionalProperties": false,

1686 "required": [

1687 "location", "unit"

1688 ]

1689 }

1690}

1691```

1692 

1693 

1694#### Objects have limitations on nesting depth and size

1695 

1696A schema may have up to 5000 object properties total, with up to 10 levels of nesting.

1697 

1698#### Limitations on total string size

1699 

1700In a schema, total string length of all property names, definition names, enum values, and const values cannot exceed 120,000 characters.

1701 

1702#### Limitations on enum size

1703 

1704A schema may have up to 1000 enum values across all enum properties.

1705 

1706For a single enum property with string values, the total string length of all enum values cannot exceed 15,000 characters when there are more than 250 enum values.

1707 

1708#### `additionalProperties: false` must always be set in objects

1709 

1710`additionalProperties` controls whether it is allowable for an object to contain additional keys / values that were not defined in the JSON Schema.

1711 

1712Structured Outputs only supports generating specified keys / values, so we require developers to set `additionalProperties: false` to opt into Structured Outputs.

1713 

1714```json

1715{

1716 "name": "get_weather",

1717 "description": "Fetches the weather in the given location",

1718 "strict": true,

1719 "schema": {

1720 "type": "object",

1721 "properties": {

1722 "location": {

1723 "type": "string",

1724 "description": "The location to get the weather for"

1725 },

1726 "unit": {

1727 "type": "string",

1728 "description": "The unit to return the temperature in",

1729 "enum": ["F", "C"]

1730 }

1731 },

1732 // highlight-start

1733 "additionalProperties": false,

1734 // highlight-end

1735 "required": [

1736 "location", "unit"

1737 ]

1738 }

1739}

1740```

1741 

1742 

1743#### Key ordering

1744 

1745When using Structured Outputs, outputs will be produced in the same order as the ordering of keys in the schema.

1746 

1747#### Some type-specific keywords are not yet supported

1748 

1749- **Composition:** `allOf`, `not`, `dependentRequired`, `dependentSchemas`, `if`, `then`, `else`

1750 

1751For fine-tuned models, we additionally do not support the following:

1752 

1753- **For strings:** `minLength`, `maxLength`, `pattern`, `format`

1754- **For numbers:** `minimum`, `maximum`, `multipleOf`

1755- **For objects:** `patternProperties`

1756- **For arrays:** `minItems`, `maxItems`

1757 

1758If you turn on Structured Outputs by supplying `strict: true` and call the API with an unsupported JSON Schema, you will receive an error.

1759 

1760#### For `anyOf`, the nested schemas must each be a valid JSON Schema per this subset

1761 

1762Here's an example supported anyOf schema:

1763 

1764```json

1765{

1766 "type": "object",

1767 "properties": {

1768 "item": {

1769 "anyOf": [

1770 {

1771 "type": "object",

1772 "description": "The user object to insert into the database",

1773 "properties": {

1774 "name": {

1775 "type": "string",

1776 "description": "The name of the user"

1777 },

1778 "age": {

1779 "type": "number",

1780 "description": "The age of the user"

1781 }

1782 },

1783 "additionalProperties": false,

1784 "required": [

1785 "name",

1786 "age"

1787 ]

1788 },

1789 {

1790 "type": "object",

1791 "description": "The address object to insert into the database",

1792 "properties": {

1793 "number": {

1794 "type": "string",

1795 "description": "The number of the address. Eg. for 123 main st, this would be 123"

1796 },

1797 "street": {

1798 "type": "string",

1799 "description": "The street name. Eg. for 123 main st, this would be main st"

1800 },

1801 "city": {

1802 "type": "string",

1803 "description": "The city of the address"

1804 }

1805 },

1806 "additionalProperties": false,

1807 "required": [

1808 "number",

1809 "street",

1810 "city"

1811 ]

1812 }

1813 ]

1814 }

1815 },

1816 "additionalProperties": false,

1817 "required": [

1818 "item"

1819 ]

1820}

1821```

1822 

1823 

1824#### Definitions are supported

1825 

1826You can use definitions to define subschemas which are referenced throughout your schema. The following is a simple example.

1827 

1828```json

1829{

1830 "type": "object",

1831 "properties": {

1832 "steps": {

1833 "type": "array",

1834 "items": {

1835 "$ref": "#/$defs/step"

1836 }

1837 },

1838 "final_answer": {

1839 "type": "string"

1840 }

1841 },

1842 "$defs": {

1843 "step": {

1844 "type": "object",

1845 "properties": {

1846 "explanation": {

1847 "type": "string"

1848 },

1849 "output": {

1850 "type": "string"

1851 }

1852 },

1853 "required": [

1854 "explanation",

1855 "output"

1856 ],

1857 "additionalProperties": false

1858 }

1859 },

1860 "required": [

1861 "steps",

1862 "final_answer"

1863 ],

1864 "additionalProperties": false

1865}

1866```

1867 

1868 

1869#### Recursive schemas are supported

1870 

1871Sample recursive schema using `#` to indicate root recursion.

1872 

1873```json

1874{

1875 "name": "ui",

1876 "description": "Dynamically generated UI",

1877 "strict": true,

1878 "schema": {

1879 "type": "object",

1880 "properties": {

1881 "type": {

1882 "type": "string",

1883 "description": "The type of the UI component",

1884 "enum": ["div", "button", "header", "section", "field", "form"]

1885 },

1886 "label": {

1887 "type": "string",

1888 "description": "The label of the UI component, used for buttons or form fields"

1889 },

1890 "children": {

1891 "type": "array",

1892 "description": "Nested UI components",

1893 "items": {

1894 "$ref": "#"

1895 }

1896 },

1897 "attributes": {

1898 "type": "array",

1899 "description": "Arbitrary attributes for the UI component, suitable for any element",

1900 "items": {

1901 "type": "object",

1902 "properties": {

1903 "name": {

1904 "type": "string",

1905 "description": "The name of the attribute, for example onClick or className"

1906 },

1907 "value": {

1908 "type": "string",

1909 "description": "The value of the attribute"

1910 }

1911 },

1912 "additionalProperties": false,

1913 "required": ["name", "value"]

1914 }

1915 }

1916 },

1917 "required": ["type", "label", "children", "attributes"],

1918 "additionalProperties": false

1919 }

1920}

1921```

1922 

1923 

1924Sample recursive schema using explicit recursion:

1925 

1926```json

1927{

1928 "type": "object",

1929 "properties": {

1930 "linked_list": {

1931 "$ref": "#/$defs/linked_list_node"

1932 }

1933 },

1934 "$defs": {

1935 "linked_list_node": {

1936 "type": "object",

1937 "properties": {

1938 "value": {

1939 "type": "number"

1940 },

1941 "next": {

1942 "anyOf": [

1943 {

1944 "$ref": "#/$defs/linked_list_node"

1945 },

1946 {

1947 "type": "null"

1948 }

1949 ]

1950 }

1951 },

1952 "additionalProperties": false,

1953 "required": [

1954 "next",

1955 "value"

1956 ]

1957 }

1958 },

1959 "additionalProperties": false,

1960 "required": [

1961 "linked_list"

1962 ]

1963}

1964```

1965 

1966 

1967 

1968## JSON mode

1969 

1970JSON mode is a more basic version of the Structured Outputs feature. While

1971 JSON mode ensures that model output is valid JSON, Structured Outputs reliably

1972 matches the model's output to the schema you specify. We recommend you use

1973 Structured Outputs if it is supported for your use case.

1974 

1975When JSON mode is turned on, the model's output is ensured to be valid JSON, except for in some edge cases that you should detect and handle appropriately.

1976 

1977 

1978 

1979 

1980To turn on JSON mode with the Responses API you can set the `text.format` to `{ "type": "json_object" }`. If you are using function calling, JSON mode is always turned on.

1981 

1982 

1983Important notes:

1984 

1985- When using JSON mode, you must always instruct the model to produce JSON via some message in the conversation, for example via your system message. If you don't include an explicit instruction to generate JSON, the model may generate an unending stream of whitespace and the request may run continually until it reaches the token limit. To help ensure you don't forget, the API will throw an error if the string "JSON" does not appear somewhere in the context.

1986- JSON mode will not guarantee the output matches any specific schema, only that it is valid and parses without errors. You should use Structured Outputs to ensure it matches your schema, or if that is not possible, you should use a validation library and potentially retries to ensure that the output matches your desired schema.

1987- Your application must detect and handle the edge cases that can result in the model output not being a complete JSON object (see below)

1988 

1989Handling edge cases

1990 

1991```javascript

1992const we_did_not_specify_stop_tokens = true;

1993 

1994try {

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

1996 model: "gpt-5.6",

1997 input: [

1998 {

1999 role: "system",

2000 content: "You are a helpful assistant designed to output JSON.",

2001 },

2002 {

2003 role: "user",

2004 content:

2005 "Who won the world series in 2020? Please respond in the format {winner: ...}",

2006 },

2007 ],

2008 text: { format: { type: "json_object" } },

2009 });

2010 

2011 const message = response.output.find((item) => item.type === "message");

2012 const messageContent = message?.content[0];

2013 

2014 // Check if the conversation was too long for the context window, resulting in incomplete JSON

2015 if (

2016 response.status === "incomplete" &&

2017 response.incomplete_details.reason === "max_output_tokens"

2018 ) {

2019 // your code should handle this error case

2020 }

2021 

2022 // Check if the OpenAI safety system refused the request and generated a refusal instead

2023 if (messageContent?.type === "refusal") {

2024 // your code should handle this error case

2025 // In this case, the .content field will contain the explanation (if any) that the model generated for why it is refusing

2026 console.log(messageContent.refusal);

2027 }

2028 

2029 // Check if the model's output included restricted content, so the generation of JSON was halted and may be partial

2030 if (

2031 response.status === "incomplete" &&

2032 response.incomplete_details.reason === "content_filter"

2033 ) {

2034 // your code should handle this error case

2035 }

2036 

2037 if (response.status === "completed") {

2038 // In this case the model has either successfully finished generating the JSON object according to your schema, or the model generated one of the tokens you provided as a "stop token"

2039 

2040 if (we_did_not_specify_stop_tokens) {

2041 // If you didn't specify any stop tokens, then the generation is complete and the content key will contain the serialized JSON object

2042 // This will parse successfully and should now contain {"winner": "Los Angeles Dodgers"}

2043 console.log(JSON.parse(response.output_text));

2044 } else {

2045 // Check if the response.output_text ends with one of your stop tokens and handle appropriately

2046 }

2047 }

2048} catch (e) {

2049 // Your code should handle errors here, for example a network error calling the API

2050 console.error(e);

2051}

2052```

2053 

2054```python

2055we_did_not_specify_stop_tokens = True

2056 

2057try:

2058 response = client.responses.create(

2059 model="gpt-5.6",

2060 input=[

2061 {

2062 "role": "system",

2063 "content": "You are a helpful assistant designed to output JSON.",

2064 },

2065 {

2066 "role": "user",

2067 "content": 'Who won the World Series in 2020? Respond as {"winner": "team name"}.',

2068 },

2069 ],

2070 text={"format": {"type": "json_object"}},

2071 )

2072 

2073 message = next((item for item in response.output if item.type == "message"), None)

2074 message_content = message.content[0] if message and message.content else None

2075 

2076 # Check if the conversation was too long for the context window, resulting in incomplete JSON

2077 if (

2078 response.status == "incomplete"

2079 and response.incomplete_details.reason == "max_output_tokens"

2080 ):

2081 raise RuntimeError("The response was truncated before the JSON completed.")

2082 

2083 # Check if the OpenAI safety system refused the request and generated a refusal instead

2084 if message_content and message_content.type == "refusal":

2085 # your code should handle this error case

2086 # In this case, the .content field will contain the explanation (if any) that the model generated for why it is refusing

2087 print(message_content.refusal)

2088 

2089 # Check if the model's output included restricted content, so the generation of JSON was halted and may be partial

2090 if (

2091 response.status == "incomplete"

2092 and response.incomplete_details.reason == "content_filter"

2093 ):

2094 raise RuntimeError("The response was interrupted by the content filter.")

2095 

2096 if response.status == "completed":

2097 # In this case the model has either successfully finished generating the JSON object according to your schema, or the model generated one of the tokens you provided as a "stop token"

2098 

2099 if we_did_not_specify_stop_tokens:

2100 # If you didn't specify any stop tokens, then the generation is complete and the content key will contain the serialized JSON object

2101 # This will parse successfully and should now contain "{"winner": "Los Angeles Dodgers"}"

2102 print(response.output_text)

2103except Exception as e:

2104 # Your code should handle errors here, for example a network error calling the API

2105 print(e)

2106```

302 2107 

303## Resources2108## Resources

304 2109 

Details

1# Supervised fine-tuning1# Supervised fine-tuning

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.

4 

3Supervised fine-tuning (SFT) lets you train an OpenAI model with examples for your specific use case. The result is a customized model that more reliably produces your desired style and content.5Supervised fine-tuning (SFT) lets you train an OpenAI model with examples for your specific use case. The result is a customized model that more reliably produces your desired style and content.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).

12 15 

13<br />16 

17 

14 18 

15<table>19<table>

16<tbody>20<tbody>


55**Good evals first!** Only invest in fine-tuning after setting up evals. You59**Good evals first!** Only invest in fine-tuning after setting up evals. You

56 need a reliable way to determine whether your fine-tuned model is performing60 need a reliable way to determine whether your fine-tuned model is performing

57 better than a base model.61 better than a base model.

58 <br />62

63 

59 [Set up evals →](https://developers.openai.com/api/docs/guides/evals)64 [Set up evals →](https://developers.openai.com/api/docs/guides/evals)

60 65 

61## Build your dataset66## Build your dataset


79### Formatting your data84### Formatting your data

80 85 

81- Use [JSONL format](https://jsonlines.org/), with one complete JSON structure on every line of the training data file86- Use [JSONL format](https://jsonlines.org/), with one complete JSON structure on every line of the training data file

82- Use the [chat completions format](https://developers.openai.com/api/docs/api-reference/fine-tuning/chat-input)87- Use the [chat completions format](https://developers.openai.com/api/reference/resources/fine_tuning)

83- Your file must have at least 10 lines88- Your file must have at least 10 lines

84 89 

85 90 

86 91 

87<div data-content-switcher-pane data-value="jsonl">92JSONL format example file

88 <div class="hidden">JSONL format example file</div>93 

89 </div>94

90 <div data-content-switcher-pane data-value="json" hidden>95 

91 <div class="hidden">Corresponding JSON data</div>96An example of JSONL training data, where the model calls a `get_weather` function:

92 </div>97 

98```

99{"messages":[{"role":"user","content":"What is the weather in San Francisco?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Francisco, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

100{"messages":[{"role":"user","content":"What is the weather in Minneapolis?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Minneapolis, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Minneapolis, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

101{"messages":[{"role":"user","content":"What is the weather in San Diego?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Diego, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Diego, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

102{"messages":[{"role":"user","content":"What is the weather in Memphis?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Memphis, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Memphis, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

103{"messages":[{"role":"user","content":"What is the weather in Atlanta?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Atlanta, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Atlanta, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

104{"messages":[{"role":"user","content":"What is the weather in Sunnyvale?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Sunnyvale, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Sunnyvale, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

105{"messages":[{"role":"user","content":"What is the weather in Chicago?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Chicago, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Chicago, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

106{"messages":[{"role":"user","content":"What is the weather in Boston?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Boston, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Boston, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

107{"messages":[{"role":"user","content":"What is the weather in Honolulu?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Honolulu, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Honolulu, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

108{"messages":[{"role":"user","content":"What is the weather in San Antonio?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Antonio, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Antonio, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}

109```

110 

111 

112

113 

114

115 

116

117Corresponding JSON data

118 

119

120 

121Each line of the training data file contains a JSON structure like the following, containing both an example user prompt and a correct response from the model as an `assistant` message.

122 

123```json

124{

125 "messages": [

126 { "role": "user", "content": "What is the weather in San Francisco?" },

127 {

128 "role": "assistant",

129 "tool_calls": [

130 {

131 "id": "call_id",

132 "type": "function",

133 "function": {

134 "name": "get_current_weather",

135 "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}"

136 }

137 }

138 ]

139 }

140 ],

141 "parallel_tool_calls": false,

142 "tools": [

143 {

144 "type": "function",

145 "function": {

146 "name": "get_current_weather",

147 "description": "Get the current weather",

148 "parameters": {

149 "type": "object",

150 "properties": {

151 "location": {

152 "type": "string",

153 "description": "The city and country, eg. San Francisco, USA"

154 },

155 "format": { "type": "string", "enum": ["celsius", "fahrenheit"] }

156 },

157 "required": ["location", "format"]

158 }

159 }

160 }

161 ]

162}

163```

93 164 

94 165 

95 166 


98One way to build a training data set for a smaller model is to distill the results of a large model to create training data for supervised fine tuning. The general flow of this technique is:169One way to build a training data set for a smaller model is to distill the results of a large model to create training data for supervised fine tuning. The general flow of this technique is:

99 170 

100- Tune a prompt for a larger model (like `gpt-4.1`) until you get great performance against your eval criteria.171- Tune a prompt for a larger model (like `gpt-4.1`) until you get great performance against your eval criteria.

101- Capture results generated from your model using whatever technique is convenient - note that the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) stores model responses for 30 days by default.172- Capture results generated from your model using whatever technique is convenient - note that the [Responses API](https://developers.openai.com/api/reference/resources/responses) stores model responses for 30 days by default.

102- Use the captured responses from the large model that fit your criteria to generate a dataset using the tools and techniques described above.173- Use the captured responses from the large model that fit your criteria to generate a dataset using the tools and techniques described above.

103- Tune a smaller model (like `gpt-4.1-mini`) using the dataset you created from the large model.174- Tune a smaller model (like `gpt-4.1-mini`) using the dataset you created from the large model.

104 175 


112 183 

113 184 

114 185 

115<div data-content-switcher-pane data-value="ui">186Upload your data with button clicks

116 <div class="hidden">Upload your data with button clicks</div>187 

117 </div>188

118 <div data-content-switcher-pane data-value="api" hidden>189 

119 <div class="hidden">Call the API to upload your data</div>1901. Navigate to the dashboard > **[fine-tuning](https://platform.openai.com/finetune)**.

120 </div>1911. Click **+ Create**.

1921. Under **Training data**, upload your JSONL file.

193 

194 

195

196 

197

198 

199

200Call the API to upload your data

201 

202

203 

204Assuming the data above is saved to a file called `mydata.jsonl`, you can upload it to the OpenAI platform using the code below. Note that the `purpose` of the uploaded file is set to `fine-tune`:

205 

206```bash

207curl https://api.openai.com/v1/files \

208 -H "Authorization: Bearer $OPENAI_API_KEY" \

209 -F purpose="fine-tune" \

210 -F file="@mydata.jsonl"

211```

212 

213 

214Note the `id` of the file that is uploaded in the data returned from the API - you'll need that file identifier in subsequent API requests.

215 

216```json

217{

218 "object": "file",

219 "id": "file-RCnFCYRhFDcq1aHxiYkBHw",

220 "purpose": "fine-tune",

221 "filename": "mydata.jsonl",

222 "bytes": 1058,

223 "created_at": 1746484901,

224 "expires_at": null,

225 "status": "processed",

226 "status_details": null

227}

228```

121 229 

122 230 

123 231 

124## Create a fine-tuning job232## Create a fine-tuning job

125 233 

126With your test data uploaded, [create a fine-tuning job](https://developers.openai.com/api/docs/api-reference/fine-tuning/create) to customize a base model using the training data you provide. When creating a fine-tuning job, you must specify:234With your test data uploaded, [create a fine-tuning job](https://developers.openai.com/api/reference/resources/fine_tuning) to customize a base model using the training data you provide. When creating a fine-tuning job, you must specify:

127 235 

128- A base model (`model`) to use for fine-tuning. This can be either an OpenAI model ID or the ID of a previously fine-tuned model. See which models support fine-tuning in the [model docs](https://developers.openai.com/api/docs/models).236- A base model (`model`) to use for fine-tuning. This can be either an OpenAI model ID or the ID of a previously fine-tuned model. See which models support fine-tuning in the [model docs](https://developers.openai.com/api/docs/models).

129- A training file (`training_file`) ID. This is the file you uploaded in the previous step.237- A training file (`training_file`) ID. This is the file you uploaded in the previous step.


131 239 

132 240 

133 241 

134<div data-content-switcher-pane data-value="ui">242Upload your data with button clicks

135 <div class="hidden">Upload your data with button clicks</div>243 

136 </div>244

137 <div data-content-switcher-pane data-value="api" hidden>245 

138 <div class="hidden">Call the API to upload your data</div>2461. In the same **+ Create** modal as above, complete the required fields.

139 </div>2471. Select supervised fine-tuning as the method and whichever model you want to train.

2481. When you're ready, click **Create** to start the job.

249 

250 

251

252 

253

254 

255

256Call the API to upload your data

257 

258

259 

260Create a supervised fine-tuning job by calling the [fine-tuning API](https://developers.openai.com/api/reference/resources/fine_tuning):

261 

262```bash

263curl https://api.openai.com/v1/fine_tuning/jobs \

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

265 -H "Authorization: Bearer $OPENAI_API_KEY" \

266 -d '{

267 "training_file": "file-RCnFCYRhFDcq1aHxiYkBHw",

268 "model": "gpt-4.1-nano-2025-04-14"

269 }'

270```

271 

272 

273The API responds with information about the fine-tuning job in progress. Depending on the size of your training data, the training process may take several minutes or hours. You can [poll the API](https://developers.openai.com/api/reference/resources/fine_tuning) for updates on a specific job.

274 

275When the fine-tuning job finishes, your fine-tuned model is ready to use. A completed fine-tune job returns data like this:

276 

277```json

278{

279 "object": "fine_tuning.job",

280 "id": "ftjob-uL1VKpwx7maorHNbOiDwFIn6",

281 "model": "gpt-4.1-nano-2025-04-14",

282 "created_at": 1746484925,

283 "finished_at": 1746485841,

284 "fine_tuned_model": "ft:gpt-4.1-nano-2025-04-14:openai::BTz2REMH",

285 "organization_id": "org-abc123",

286 "result_files": ["file-9TLxKY2A8tC5YE1RULYxf6"],

287 "status": "succeeded",

288 "validation_file": null,

289 "training_file": "file-RCnFCYRhFDcq1aHxiYkBHw",

290 "hyperparameters": {

291 "n_epochs": 10,

292 "batch_size": 1,

293 "learning_rate_multiplier": 1

294 },

295 "trained_tokens": 1700,

296 "error": {},

297 "user_provided_suffix": null,

298 "seed": 1935755117,

299 "estimated_finish": null,

300 "integrations": [],

301 "metadata": null,

302 "usage_metrics": null,

303 "shared_with_openai": false,

304 "method": {

305 "type": "supervised",

306 "supervised": {

307 "hyperparameters": {

308 "n_epochs": 10,

309 "batch_size": 1,

310 "learning_rate_multiplier": 1.0

311 }

312 }

313 }

314}

315```

316 

317Note the `fine_tuned_model` property. This is the model ID to use in [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) to make API requests using your fine-tuned model.

318 

319Here's an example of calling the Responses API with your fine-tuned model ID:

320 

321```bash

322curl https://api.openai.com/v1/responses \

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

324 -H "Authorization: Bearer $OPENAI_API_KEY" \

325 -d '{

326 "model": "ft:gpt-4.1-nano-2025-04-14:openai::BTz2REMH",

327 "input": "What is the weather like in Boston today?",

328 "tools": [

329 {

330 "name": "get_current_weather",

331 "description": "Get the current weather",

332 "parameters": {

333 "type": "object",

334 "properties": {

335 "location": {

336 "type": "string",

337 "description": "The city and country, eg. San Francisco, USA"

338 },

339 "format": { "type": "string", "enum": ["celsius", "fahrenheit"] }

340 },

341 "required": ["location", "format"]

342 }

343 }

344 ],

345 "tool_choice": "auto"

346 }'

347```

140 348 

141 349 

142 350 


156 364 

157 365 

158 366 

159<div data-content-switcher-pane data-value="ui">367Monitor in the UI

160 <div class="hidden">Monitor in the UI</div>368 

161 </div>369

162 <div data-content-switcher-pane data-value="api" hidden>370 

163 <div class="hidden">Monitor with API calls</div>3711. Navigate to the [fine-tuning dashboard](https://platform.openai.com/finetune).

164 </div>3721. Select the job you want to monitor.

3731. Review the status, checkpoints, message, and metrics.

374 

375 

376

377 

378

379 

380

381Monitor with API calls

382 

383

384 

385Use this curl command to get information about your fine-tuning job:

386 

387```bash

388curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-uL1VKpwx7maorHNbOiDwFIn6 \

389 -H "Authorization: Bearer $OPENAI_API_KEY"

390```

391 

392 

393The job contains a `fine_tuned_model` property, which is your new fine-tuned model's unique ID.

394 

395```json

396{

397 "object": "fine_tuning.job",

398 "id": "ftjob-uL1VKpwx7maorHNbOiDwFIn6",

399 "model": "gpt-4.1-nano-2025-04-14",

400 "created_at": 1746484925,

401 "finished_at": 1746485841,

402 "fine_tuned_model": "ft:gpt-4.1-nano-2025-04-14:openai::BTz2REMH",

403 "organization_id": "org-abc123",

404 "result_files": ["file-9TLxKY2A8tC5YE1RULYxf6"],

405 "status": "succeeded",

406 "validation_file": null,

407 "training_file": "file-RCnFCYRhFDcq1aHxiYkBHw",

408 "hyperparameters": {

409 "n_epochs": 10,

410 "batch_size": 1,

411 "learning_rate_multiplier": 1

412 },

413 "trained_tokens": 1700,

414 "error": {},

415 "user_provided_suffix": null,

416 "seed": 1935755117,

417 "estimated_finish": null,

418 "integrations": [],

419 "metadata": null,

420 "usage_metrics": null,

421 "shared_with_openai": false,

422 "method": {

423 "type": "supervised",

424 "supervised": {

425 "hyperparameters": {

426 "n_epochs": 10,

427 "batch_size": 1,

428 "learning_rate_multiplier": 1.0

429 }

430 }

431 }

432}

433```

165 434 

166 435 

167 436 

168### Try using your fine-tuned model437### Try using your fine-tuned model

169 438 

170Evaluate your newly optimized model by using it! When the fine-tuned model finishes training, use its ID in either the [Responses](https://developers.openai.com/api/docs/api-reference/responses) or [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat) API, just as you would an OpenAI base model.439Evaluate your newly optimized model by using it! When the fine-tuned model finishes training, use its ID in either the [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) API, just as you would an OpenAI base model.

440 

441 

442 

443Use your model in the Playground

444 

445

446 

4471. Navigate to your fine-tuning job in [the dashboard](https://platform.openai.com/finetune).

4481. In the right pane, navigate to **Output model** and copy the model ID. It should start with `ft:…`

4491. Open the [Playground](https://platform.openai.com/playground).

4501. In the **Model** dropdown menu, paste the model ID. Here, you should also see other fine-tuned models you've created.

4511. Run some prompts and see how your fine-tuned performs!

452 

453 

454

455 

456

171 457 

172 458

459Use your model with an API call

173 460 

174<div data-content-switcher-pane data-value="ui">461

175 <div class="hidden">Use your model in the Playground</div>462 

176 </div>463```bash

177 <div data-content-switcher-pane data-value="api" hidden>464curl https://api.openai.com/v1/responses \

178 <div class="hidden">Use your model with an API call</div>465 -H "Content-Type: application/json" \

179 </div>466 -H "Authorization: Bearer $OPENAI_API_KEY" \

467 -d '{

468 "model": "ft:gpt-4.1-nano-2025-04-14:openai::BTz2REMH",

469 "input": "What is 4+4?"

470 }'

471```

180 472 

181 473 

182 474 


186 478 

187 479 

188 480 

189<div data-content-switcher-pane data-value="ui">481Find checkpoints in the dashboard

190 <div class="hidden">Find checkpoints in the dashboard</div>482 

191 </div>483

192 <div data-content-switcher-pane data-value="api" hidden>484 

193 <div class="hidden">Query the API for checkpoints</div>4851. Navigate to the [fine-tuning dashboard](https://platform.openai.com/finetune).

194 </div>4861. In the left panel, select the job you want to investigate. Wait until it succeeds.

4871. In the right panel, scroll to the list of checkpoints.

4881. Hover over any checkpoint to see a link to launch in the Playground.

4891. Test the checkpoint model's behavior by prompting it in the Playground.

490 

491 

492

493 

494

495 

496

497Query the API for checkpoints

498 

499

500 

5011. Wait until a job succeeds, which you can verify by [querying the status of a job](https://developers.openai.com/api/reference/resources/fine_tuning).

5021. [Query the checkpoints endpoint](https://developers.openai.com/api/reference/resources/fine_tuning/subresources/jobs/subresources/checkpoints/methods/list) with your fine-tuning job ID to access a list of model checkpoints for the fine-tuning job.

5031. Find the `fine_tuned_model_checkpoint` field for the name of the model checkpoint.

5041. Use this model just like you would the final fine-tuned model.

505 

506The checkpoint object contains `metrics` data to help you determine the usefulness of this model. As an example, the response looks like this:

507 

508```json

509{

510 "object": "fine_tuning.job.checkpoint",

511 "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB",

512 "created_at": 1519129973,

513 "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom-suffix:96olL566:ckpt-step-2000",

514 "metrics": {

515 "full_valid_loss": 0.134,

516 "full_valid_mean_token_accuracy": 0.874

517 },

518 "fine_tuning_job_id": "ftjob-abc123",

519 "step_number": 2000

520}

521```

522 

523Each checkpoint specifies:

524 

525- `step_number`: The step at which the checkpoint was created (where each epoch is number of steps in the training set divided by the batch size)

526- `metrics`: An object containing the metrics for your fine-tuning job at the step when the checkpoint was created

195 527 

196 528 

197 529 


225 557 

226How to pass safety checks558How to pass safety checks

227 559 

228In addition to reviewing any failed safety checks in the fine-tuning job object, you can retrieve details about which categories failed by querying the [fine-tuning API events endpoint](https://developers.openai.com/api/docs/api-reference/fine-tuning/list-events). Look for events of type `moderation_checks` for details about category results and enforcement. This information can help you narrow down which categories to target for retraining and improvement. The [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#overview) has rules and examples that can help identify areas for additional training data.560In addition to reviewing any failed safety checks in the fine-tuning job object, you can retrieve details about which categories failed by querying the [fine-tuning API events endpoint](https://developers.openai.com/api/reference/resources/fine_tuning/subresources/jobs/methods/list). Look for events of type `moderation_checks` for details about category results and enforcement. This information can help you narrow down which categories to target for retraining and improvement. The [model spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html#overview) has rules and examples that can help identify areas for additional training data.

229 561 

230While these evaluations cover a broad range of safety categories, conduct your own evaluations of the fine-tuned model to ensure it's appropriate for your use case.562While these evaluations cover a broad range of safety categories, conduct your own evaluations of the fine-tuned model to ensure it's appropriate for your use case.

231 563 


233 565 

234Now that you know the basics of supervised fine-tuning, explore these other methods as well.566Now that you know the basics of supervised fine-tuning, explore these other methods as well.

235 567 

236[568[Vision fine-tuning

569 

570 

571 

572 Learn to fine-tune for computer vision with image inputs.](https://developers.openai.com/api/docs/guides/vision-fine-tuning)

237 573 

238<span slot="icon">574[Direct preference optimization

239 </span>

240 Learn to fine-tune for computer vision with image inputs.

241 575 

242](https://developers.openai.com/api/docs/guides/vision-fine-tuning)

243 576 

244[

245 577 

246<span slot="icon">578 Fine-tune a model using direct preference optimization (DPO).](https://developers.openai.com/api/docs/guides/direct-preference-optimization)

247 </span>

248 Fine-tune a model using direct preference optimization (DPO).

249 579 

250](https://developers.openai.com/api/docs/guides/direct-preference-optimization)580[Reinforcement fine-tuning

251 581 

252[

253 582 

254<span slot="icon">

255 </span>

256 Fine-tune a reasoning model by grading its outputs.

257 583 

258](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

584 Fine-tune a reasoning model by grading its outputs.](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

guides/terraform.md +91 −0 created

Details

1# Terraform provider

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 official [OpenAI Terraform provider](https://github.com/openai/terraform-provider-openai) lets you manage OpenAI organization resources with infrastructure as code. The provider uses the [Administration API](https://developers.openai.com/api/reference/administration/overview) to manage projects, users, groups, roles, service accounts, certificates, rate limits, spend alerts, and related project settings.

6 

7This guide creates an OpenAI project. Continue to the use-case guides for project access, service accounts, operational limits, project controls, and imports.

8 

9## Before you begin

10 

11You need:

12 

13- [Terraform](https://developer.hashicorp.com/terraform/install) 1.0 or later. The import examples require Terraform 1.5 or later.

14- An OpenAI organization with permission to create an [Admin API key](https://platform.openai.com/settings/organization/admin-keys).

15 

16Administration API endpoints require Admin API keys, which don't work with non-administration OpenAI API endpoints. Store the key in an environment variable or a secrets manager. Don't commit it to your Terraform configuration or source control.

17 

18## Configure the provider

19 

20Create a new directory and add a `main.tf` file with the following configuration:

21 

22```terraform

23terraform {

24 required_version = ">= 1.0"

25 

26 required_providers {

27 openai = {

28 source = "openai/openai"

29 version = ">= 1.0.0"

30 }

31 }

32}

33 

34provider "openai" {}

35 

36resource "openai_project" "example" {

37 name = "terraform-managed"

38}

39 

40output "project_id" {

41 value = openai_project.example.project_id

42}

43```

44 

45The version constraint allows provider version 1.0.0 and later. Review the [provider releases](https://github.com/openai/terraform-provider-openai/releases) before upgrading.

46 

47Set your Admin API key in the environment:

48 

49```bash

50export OPENAI_ADMIN_KEY="<your-admin-api-key>"

51```

52 

53The provider reads `OPENAI_ADMIN_KEY` by default. You can also set `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` to send the `OpenAI-Organization` and `OpenAI-Project` headers with API requests. When these optional variables aren't set, OpenAI resolves the organization and project from the API key. Set them when you want to explicitly identify which organization or project your Terraform configuration manages. See the [provider configuration reference](https://registry.terraform.io/providers/openai/openai/latest/docs) for all available arguments.

54 

55## Initialize and apply

56 

57Initialize the working directory, then format and check the configuration:

58 

59```bash

60terraform init

61terraform fmt

62terraform validate

63```

64 

65Terraform downloads the provider and creates `.terraform.lock.hcl`. Commit the lock file to source control so future runs select the same provider version. Run `terraform init -upgrade` to select the latest provider version allowed by the constraint.

66 

67Review the changes Terraform will make:

68 

69```bash

70terraform plan

71```

72 

73The plan should show one `openai_project` resource to add. Apply the configuration only after you have reviewed the plan:

74 

75```bash

76terraform apply

77```

78 

79Confirm the apply when prompted. Terraform creates the project and prints its ID from the `project_id` output.

80 

81## Choose a use-case guide

82 

83| Guide | Use it to |

84| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------ |

85| [Projects and access](https://developers.openai.com/api/docs/guides/terraform/projects-and-access) | Create projects and configure role-based and group-based access. |

86| [Service accounts](https://developers.openai.com/api/docs/guides/terraform/service-accounts) | Create service accounts for workload identity or API-key authentication. |

87| [Rate limits and spend](https://developers.openai.com/api/docs/guides/terraform/rate-limits-and-spend) | Reconcile existing rate limits and configure spend alerts. |

88| [Model, tool, and data controls](https://developers.openai.com/api/docs/guides/terraform/project-controls) | Configure model access, hosted tools, and data retention. |

89| [Import and reconciliation](https://developers.openai.com/api/docs/guides/terraform/import-and-reconcile) | Adopt existing resources and detect drift. |

90 

91For individual arguments and import formats, use the [provider resource and data source reference](https://registry.terraform.io/providers/openai/openai/latest/docs).

Details

1# Import and reconcile OpenAI resources

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 

5Import existing OpenAI resources instead of recreating them. A safe adoption starts with configuration that matches the remote resource, previews and applies the import, and produces a no-op plan before any intended update.

6 

7Import blocks require Terraform 1.5 or later.

8 

9## Declare and import resources

10 

11Declare each existing resource using its current settings, then add an `import` block with the ID format from the provider reference:

12 

13```terraform

14resource "openai_project" "existing" {

15 name = "existing-project"

16}

17 

18resource "openai_group" "existing" {

19 name = "existing-group"

20}

21 

22resource "openai_project_service_account" "existing" {

23 project_id = openai_project.existing.project_id

24 name = "existing-service-account"

25}

26 

27import {

28 to = openai_project.existing

29 id = "proj_123"

30}

31 

32import {

33 to = openai_group.existing

34 id = "group_123"

35}

36 

37import {

38 to = openai_project_service_account.existing

39 id = "proj_123/svc_acct_123"

40}

41```

42 

43Preview the imports in a saved plan:

44 

45```bash

46terraform plan -out=tfplan

47terraform show tfplan

48```

49 

50The plan should show the imports without proposing updates to the remote resources. If it proposes updates, make the configuration match the current settings before continuing. Apply the saved plan to perform the imports, then run another plan:

51 

52```bash

53terraform apply tfplan

54terraform plan

55```

56 

57The second plan should report no changes. You can keep the import blocks in your configuration as a record of how Terraform adopted the resources.

58 

59Common import ID formats include:

60 

61| Resource | Import ID format |

62| ----------------------- | ----------------------------------- |

63| Project | `<project_id>` |

64| Organization group | `<group_id>` |

65| Project role | `<project_id>/<role_id>` |

66| Project service account | `<project_id>/<service_account_id>` |

67| Project group role | `<project_id>/<group_id>/<role_id>` |

68| Project user role | `<project_id>/<user_id>/<role_id>` |

69| Project rate limit | `<project_id>/<rate_limit_id>` |

70 

71Check the [provider reference](https://registry.terraform.io/providers/openai/openai/latest/docs) for the exact format of every resource.

72 

73## Read resources without adopting them

74 

75Use data sources when Terraform needs current information but another system owns the resource. The provider includes data sources for projects, groups, roles, users, role assignments, rate limits, model permissions, hosted-tool permissions, spend alerts, data retention, and certificates.

76 

77For example, read an existing project and its current groups:

78 

79```terraform

80data "openai_project" "existing" {

81 project_id = var.project_id

82}

83 

84data "openai_project_groups" "existing" {

85 project_id = data.openai_project.existing.project_id

86}

87 

88output "project_groups" {

89 value = data.openai_project_groups.existing.groups

90}

91```

92 

93The provider can import an existing project service account by ID, but it

94 doesn't currently provide a service-account data source. Keep the project and

95 service-account IDs in your approved inventory when you need to adopt an

96 existing service account. See [Service

97 accounts](https://developers.openai.com/api/docs/guides/terraform/service-accounts) for the API-key

98 bootstrap and import sequence.

99 

100## Detect and reconcile drift

101 

102Run a normal plan to read the current OpenAI settings and compare them with the desired values in your Terraform configuration:

103 

104```bash

105terraform plan -detailed-exitcode

106```

107 

108Exit code `0` means there are no changes, `2` means the plan contains changes, and `1` means Terraform encountered an error.

109 

110If the plan shows a setting that changed outside Terraform:

111 

1121. Determine whether the change was intentional.

1132. To keep the remote change, update the Terraform configuration to match it.

1143. To undo the remote change, review and apply the plan to restore the configured value.

1154. Run another plan and require a no-op result.

116 

117## Understand removal behavior

118 

119Removing a resource block removes the resource from Terraform state, but it doesn't always delete or reset the same kind of remote object:

120 

121| Resource type | Removal behavior |

122| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |

123| `openai_project` | Archives the project. You can't restore an archived project. |

124| `openai_project_service_account` | Deletes the service account. |

125| Role, group, membership, and assignment resources | Deletes the corresponding managed object or assignment. |

126| `openai_project_model_permissions` | Deletes the project model-permission configuration. |

127| Project rate limit, hosted-tool permissions, and data-retention resources | Removes the resource from Terraform state without resetting the remote setting. |

Details

1# Model, tool, and data controls with Terraform

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 

5Use this guide to apply model, hosted-tool, and data-retention controls to an existing project. These controls determine what project workloads can use and which approved retention policy applies. They don't grant users or service accounts access to the project.

6 

7After completing the main workflow, you will have a repeatable configuration that:

8 

9- Limits the project to an approved set of models.

10- Sets an explicit permission for every supported hosted tool.

11- Applies the organization's default data-retention policy to the project.

12 

13## Before you begin

14 

15Complete the [Terraform provider setup](https://developers.openai.com/api/docs/guides/terraform) and export an Admin API key as `OPENAI_ADMIN_KEY`. You also need:

16 

17- The ID of an existing project.

18- The IDs of models available to your organization.

19- An organization with data-retention controls enabled if you plan to manage project retention.

20 

21Use a test project when evaluating the workflow. To disable a hosted tool for one project, the organization-level tool policy must already limit that tool to selected projects. A project can't disable a tool that the organization has enabled for every project.

22 

23## Restrict model access

24 

25`openai_project_model_permissions` applies either an allowlist or a list of denied models to one project. This example permits only `gpt-5.4-mini`:

26 

27```terraform

28resource "openai_project_model_permissions" "application" {

29 project_id = "proj_123"

30 mode = "allow_list"

31 model_ids = ["gpt-5.4-mini"]

32}

33```

34 

35Set `mode` to:

36 

37- `allow_list` to permit only the models in `model_ids`.

38- `deny_list` to permit available models except those in `model_ids`.

39 

40Each model ID must be visible to the organization. This includes any fine-tuned model snapshots that you add to the policy. Terraform reconciles changes to the mode and model list during the next plan and apply.

41 

42## Configure hosted tools

43 

44`openai_project_hosted_tool_permissions` manages five project-level tool permissions. Set every field so the reviewed configuration describes the complete policy:

45 

46```terraform

47resource "openai_project_hosted_tool_permissions" "application" {

48 project_id = "proj_123"

49 file_search_enabled = true

50 web_search_enabled = false

51 image_generation_enabled = false

52 mcp_enabled = false

53 code_interpreter_enabled = true

54}

55```

56 

57The fields control file search, web search, image generation, remote MCP servers, and Code Interpreter. Each organization's hosted-tool policy has three modes: allow all projects, deny all projects, or allow selected projects. Setting a field to `true` permits that tool for the project, subject to the organization's other eligibility and retention requirements. Setting a field to `false` removes the project from that tool's selected-project policy. If the organization currently allows the tool for all projects, setting the field to `false` fails. Change the organization's tool policy to allow selected projects before disabling the tool for an individual project.

58 

59Terraform refreshes all five values from OpenAI and reports dashboard changes as drift on the next plan.

60 

61## Configure data retention

62 

63`openai_project_data_retention` applies an approved retention type to one project. Inherit the organization's current policy unless the project has an approved override:

64 

65```terraform

66resource "openai_project_data_retention" "application" {

67 project_id = "proj_123"

68 type = "organization_default"

69}

70```

71 

72The provider also accepts `none`, `zero_data_retention`, `modified_abuse_monitoring`, `enhanced_zero_data_retention`, and `enhanced_modified_abuse_monitoring`. The available modes and permitted transitions depend on your organization's configuration and the project's data-residency region.

73 

74Review [Your data](https://developers.openai.com/api/docs/guides/your-data) and your organization's OpenAI agreement before selecting a project override.

75 

76### Manage the organization default

77 

78Use `openai_organization_data_retention` only when Terraform owns the existing organization-level setting:

79 

80```terraform

81resource "openai_organization_data_retention" "default" {

82 type = "zero_data_retention"

83}

84```

85 

86This resource changes an existing organization setting; it doesn't enroll an organization in a data-retention program. Some transitions require support or aren't available between retention tiers.

87 

88Removing `openai_project_hosted_tool_permissions` or

89 `openai_project_data_retention` from configuration removes the resource from

90 Terraform state but leaves the remote settings unchanged. Removing

91 `openai_project_model_permissions` deletes the project's model-permission

92 configuration. Review destroy plans with these different behaviors in mind.

93 

94## Detect changes outside Terraform

95 

96Run a plan to refresh remote state and compare it with the reviewed configuration:

97 

98```bash

99terraform plan -detailed-exitcode

100```

101 

102Exit code `0` means no changes, `2` means the plan contains changes, and `1` means Terraform encountered an error. Investigate unexpected changes before applying. Don't automatically overwrite an emergency administrative change without first understanding its purpose.

103 

104## Run the complete example

105 

106The following example manages all three project controls together. Create `main.tf`:

107 

108```terraform

109terraform {

110 required_version = ">= 1.0"

111 

112 required_providers {

113 openai = {

114 source = "openai/openai"

115 version = ">= 1.0.0"

116 }

117 }

118}

119 

120provider "openai" {}

121 

122variable "project_id" {

123 type = string

124 description = "ID of the existing OpenAI project."

125}

126 

127variable "model_permission_mode" {

128 type = string

129 description = "Whether model_ids is an allowlist or denylist."

130 default = "allow_list"

131 

132 validation {

133 condition = contains(["allow_list", "deny_list"], var.model_permission_mode)

134 error_message = "The model permission mode must be allow_list or deny_list."

135 }

136}

137 

138variable "model_ids" {

139 type = list(string)

140 description = "Model IDs included in the project model policy."

141}

142 

143variable "hosted_tools" {

144 type = object({

145 file_search = bool

146 web_search = bool

147 image_generation = bool

148 mcp = bool

149 code_interpreter = bool

150 })

151 description = "Hosted tools enabled for the project."

152}

153 

154variable "project_data_retention_type" {

155 type = string

156 description = "Approved data-retention type for the project."

157 

158 validation {

159 condition = contains([

160 "organization_default",

161 "none",

162 "zero_data_retention",

163 "modified_abuse_monitoring",

164 "enhanced_zero_data_retention",

165 "enhanced_modified_abuse_monitoring",

166 ], var.project_data_retention_type)

167 error_message = "Provide a supported project data-retention type."

168 }

169}

170 

171resource "openai_project_model_permissions" "application" {

172 project_id = var.project_id

173 mode = var.model_permission_mode

174 model_ids = var.model_ids

175}

176 

177resource "openai_project_hosted_tool_permissions" "application" {

178 project_id = var.project_id

179 file_search_enabled = var.hosted_tools.file_search

180 web_search_enabled = var.hosted_tools.web_search

181 image_generation_enabled = var.hosted_tools.image_generation

182 mcp_enabled = var.hosted_tools.mcp

183 code_interpreter_enabled = var.hosted_tools.code_interpreter

184}

185 

186resource "openai_project_data_retention" "application" {

187 project_id = var.project_id

188 type = var.project_data_retention_type

189}

190 

191output "controlled_project_id" {

192 value = var.project_id

193}

194 

195output "model_permission_mode" {

196 value = openai_project_model_permissions.application.mode

197}

198 

199output "project_data_retention_type" {

200 value = openai_project_data_retention.application.type

201}

202```

203 

204Create `terraform.tfvars` with an existing project ID, visible model IDs, the hosted-tool policy, and an approved retention type:

205 

206```terraform

207project_id = "proj_123"

208model_permission_mode = "allow_list"

209model_ids = ["gpt-5.4-mini"]

210 

211hosted_tools = {

212 file_search = true

213 web_search = true

214 image_generation = true

215 mcp = true

216 code_interpreter = true

217}

218 

219project_data_retention_type = "organization_default"

220```

221 

222The example enables all hosted tools so it can run when the organization policy enables tools for every project. Change a value to `false` only after the corresponding organization-level policy uses selected-project access. Confirm that the model ID and retention type are available to your organization before applying.

223 

224Initialize Terraform, then review and apply a saved plan:

225 

226```bash

227terraform init

228terraform fmt

229terraform validate

230terraform plan -out=tfplan

231terraform show tfplan

232terraform apply tfplan

233```

234 

235The first plan should contain three resources to add. For hosted-tool and data-retention controls, an addition means Terraform starts managing an existing singleton project setting; it doesn't create a separate remote object. Model permissions create or update the project's model-permission configuration.

236 

237Run `terraform plan` again to confirm that the configuration produces no further changes. If it shows drift, determine whether another administrator or automation changed a project control before applying another update.

Details

1# Manage projects and access with Terraform

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 

5Use this guide to create an OpenAI project and establish reusable access controls. You will define what identities can do with a project role, collect identities in an organization group, and connect the group to the project.

6 

7After completing the main workflow, you will have a repeatable configuration that:

8 

9- Creates an OpenAI project for an application.

10- Defines a least-privilege project role.

11- Creates an organization group for identities that need access.

12- Grants the group access to the project through the role.

13- Adds an existing organization user to the group.

14 

15## Before you begin

16 

17Complete the [Terraform provider setup](https://developers.openai.com/api/docs/guides/terraform) and export an Admin API key as `OPENAI_ADMIN_KEY`. You also need the ID of an existing organization user and the permission identifiers approved for the application. Use a test organization when evaluating the workflow.

18 

19Destroying an `openai_project` archives the project instead of permanently deleting it. You can't restore an archived project.

20 

21## Create the project boundary

22 

23Create a project for the application:

24 

25```terraform

26resource "openai_project" "application" {

27 name = "example-application-development"

28}

29```

30 

31The project creates the boundary for the application's API usage, service accounts, rate limits, spend alerts, and project settings. Terraform makes the generated ID available as `openai_project.application.project_id`. Project-level resources can reference that value, so Terraform creates the project before them.

32 

33This focused example uses a concrete name. The complete example later replaces it with a variable so you can reuse the configuration across environments.

34 

35## Define project permissions

36 

37Create a project role with the permissions approved for the application:

38 

39```terraform

40resource "openai_project_role" "application" {

41 project_id = openai_project.application.project_id

42 role_name = "Application API access"

43 description = "Permissions approved for this application"

44 permissions = ["api.webhooks.read"]

45}

46```

47 

48The `openai_project_role` resource defines what an identity can do inside the project. This example grants permission to read webhook configuration. Replace `api.webhooks.read` with the permission identifiers approved for your application, and start with only the permissions it needs.

49 

50Changing `permissions` updates the role. Run `terraform plan` to review every added or removed permission before applying the change.

51 

52## Create or reuse a group

53 

54Create an organization group when Terraform should own its lifecycle:

55 

56```terraform

57resource "openai_group" "application_access" {

58 name = "example-application-development-access"

59}

60```

61 

62Groups exist at the organization level, and you can reuse them across projects. A name ending in `-access` communicates that membership grants access rather than merely describing a team.

63 

64If another system owns an existing group, read it instead:

65 

66```terraform

67data "openai_group" "application_access" {

68 group_id = "group_123"

69}

70```

71 

72The data source reads the group without making this configuration responsible for its lifecycle. You can read SCIM-managed groups, but keep membership changes in the identity system that owns them.

73 

74## Grant the group project access

75 

76Connect the group to the custom role inside the project:

77 

78```terraform

79resource "openai_project_group_role" "application_access" {

80 project_id = openai_project.application.project_id

81 group_id = openai_group.application_access.group_id

82 role_id = openai_project_role.application.role_id

83}

84```

85 

86This example uses the Terraform-managed group. If you reused an existing group through the data source, replace the `group_id` expression with `data.openai_group.application_access.group_id`.

87 

88The assignment connects three objects:

89 

90- `project_id` identifies where the group receives access.

91- `group_id` identifies which collection of identities receives access.

92- `role_id` identifies which permissions the group receives.

93 

94Group members inherit the custom role in this project. Adding a role or a group alone doesn't grant access; the assignment is the link between them.

95 

96## Add users and other identities

97 

98Add an identity to a Terraform-managed organization group with `openai_group_user`:

99 

100```terraform

101resource "openai_group_user" "application_developer" {

102 group_id = openai_group.application_access.group_id

103 user_id = "user_123"

104}

105```

106 

107The `user_id` can identify an existing organization user or service account. To add a service account, use `openai_project_service_account.application.id` as the `user_id`. See [Service accounts](https://developers.openai.com/api/docs/guides/terraform/service-accounts) for group-based service-account access, authentication, and credential-lifecycle requirements.

108 

109Use direct role assignments when group-based access isn't appropriate:

110 

111```terraform

112resource "openai_project_user_role" "application_developer" {

113 project_id = openai_project.application.project_id

114 user_id = "user_123"

115 role_id = openai_project_role.application.role_id

116}

117```

118 

119For organization-wide permissions, create an organization role and assign it directly or through a group:

120 

121```terraform

122variable "organization_role_permissions" {

123 type = list(string)

124}

125 

126resource "openai_role" "platform_operator" {

127 role_name = "Platform operator"

128 description = "Organization permissions for the platform team"

129 permissions = var.organization_role_permissions

130}

131 

132resource "openai_user_role" "platform_operator" {

133 user_id = "user_123"

134 role_id = openai_role.platform_operator.role_id

135}

136```

137 

138Set `organization_role_permissions` to the approved organization-level permission identifiers. Keep organization permissions separate from project permissions so each assignment has the narrowest required scope.

139 

140## Inspect current assignments

141 

142Read the organization and project roles assigned to an identity before changing access:

143 

144```terraform

145data "openai_user_roles" "current" {

146 user_id = "user_123"

147}

148 

149data "openai_project_user_roles" "current" {

150 project_id = openai_project.application.project_id

151 user_id = "user_123"

152}

153 

154output "organization_roles" {

155 value = data.openai_user_roles.current.roles

156}

157 

158output "project_roles" {

159 value = data.openai_project_user_roles.current.roles

160}

161```

162 

163Data sources report current assignments but don't make Terraform responsible for them.

164 

165## Remove assignments

166 

167When Terraform already manages an assignment, removing its resource block makes the next plan propose deleting the remote assignment. Review the plan and verify that another path still grants any required access.

168 

169For a pre-existing assignment, first declare the matching resource and import it using the documented composite ID. Confirm that the first plan is a no-op before removing it from configuration and applying the deletion.

170 

171Terraform can remove only assignments recorded in its state. To remove an

172 existing default assignment, first import it into the corresponding Terraform

173 resource. Then remove that resource from your configuration and apply the

174 resulting destroy plan. If your organization doesn't allow this

175 import-and-destroy workflow, remove the assignment through an approved

176 dashboard or Administration API process.

177 

178See [Import and reconciliation](https://developers.openai.com/api/docs/guides/terraform/import-and-reconcile) for import formats and a safe adoption sequence.

179 

180## Run the complete example

181 

182The focused examples use concrete values to make each relationship clear. The complete configuration replaces repeated, environment-specific values with variables so you can reuse it without changing the resource definitions.

183 

184Save the following configuration as `main.tf`:

185 

186```terraform

187terraform {

188 required_version = ">= 1.0"

189 

190 required_providers {

191 openai = {

192 source = "openai/openai"

193 version = ">= 1.0.0"

194 }

195 }

196}

197 

198provider "openai" {}

199 

200variable "project_name" {

201 type = string

202}

203 

204variable "project_role_permissions" {

205 type = list(string)

206}

207 

208variable "user_id" {

209 type = string

210}

211 

212resource "openai_project" "application" {

213 name = var.project_name

214}

215 

216resource "openai_project_role" "application" {

217 project_id = openai_project.application.project_id

218 role_name = "Application API access"

219 description = "Permissions approved for this application"

220 permissions = var.project_role_permissions

221}

222 

223resource "openai_group" "application_access" {

224 name = "${var.project_name}-access"

225}

226 

227resource "openai_project_group_role" "application_access" {

228 project_id = openai_project.application.project_id

229 group_id = openai_group.application_access.group_id

230 role_id = openai_project_role.application.role_id

231}

232 

233resource "openai_group_user" "application_developer" {

234 group_id = openai_group.application_access.group_id

235 user_id = var.user_id

236}

237 

238output "project_id" {

239 value = openai_project.application.project_id

240}

241 

242output "group_id" {

243 value = openai_group.application_access.group_id

244}

245 

246output "project_role_id" {

247 value = openai_project_role.application.role_id

248}

249```

250 

251Create `terraform.tfvars` with a unique project name, an existing organization user ID, and the approved permissions:

252 

253```terraform

254project_name = "example-application-development"

255user_id = "user_123"

256 

257project_role_permissions = [

258 "api.webhooks.read",

259]

260```

261 

262Initialize Terraform, then review and apply a saved plan:

263 

264```bash

265terraform init

266terraform fmt

267terraform validate

268terraform plan -out=tfplan

269terraform show tfplan

270terraform apply tfplan

271```

272 

273The first plan should contain five resources to add. After the apply, the user inherits the custom project role through the group, and `terraform output` prints the project, group, and project-role IDs. Run `terraform plan` again to confirm that the configuration produces no further changes.

274 

275To add more human users, repeat the group membership pattern with a unique Terraform resource name for each user. To configure a nonhuman identity, see [Service accounts](https://developers.openai.com/api/docs/guides/terraform/service-accounts). Use [Model, tool, and data controls](https://developers.openai.com/api/docs/guides/terraform/project-controls) and [Rate limits and spend](https://developers.openai.com/api/docs/guides/terraform/rate-limits-and-spend) to add project guardrails.

Details

1# Rate limits and spend with Terraform

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 

5Use this guide to manage an existing project rate limit and create a monthly spend alert. Rate limits constrain a project's model usage over time. Spend alerts notify your team when monthly usage reaches a threshold, but they don't stop API requests or enforce a spending cap.

6 

7After completing the main workflow, you will have a repeatable configuration that:

8 

9- Reads the rate-limit records available to an existing project.

10- Manages the request and token limits for one model.

11- Sends an email alert when the project's monthly spend reaches a threshold.

12 

13## Before you begin

14 

15Complete the [Terraform provider setup](https://developers.openai.com/api/docs/guides/terraform) and export an Admin API key as `OPENAI_ADMIN_KEY`. You also need:

16 

17- The ID of an existing project.

18- At least one email address that should receive spend alerts.

19 

20Use a test project when evaluating the workflow. You will identify the rate-limit record for a text model in the next section. OpenAI creates the rate-limit records available to a project; Terraform updates those records rather than creating new ones.

21 

22## Discover project rate limits

23 

24Read the rate-limit records available to a project:

25 

26```terraform

27data "openai_project_rate_limits" "current" {

28 project_id = "proj_123"

29}

30 

31output "project_rate_limits" {

32 value = data.openai_project_rate_limits.current.rate_limits

33}

34```

35 

36The data source makes a read-only request:

37 

38- `project_id` selects the project to inspect.

39- `rate_limits` contains one object for each available model rate limit, including its `id`, `model`, and applicable limit values.

40- The output makes the records visible after `terraform plan` or `terraform apply`.

41 

42Use the record whose `model` matches the model you want to control. Copy its `id`; the next resource uses that value as `rate_limit_id`. Keep the ID as an explicit input to prevent a provider or API change from selecting a different record.

43 

44## Manage an existing rate limit

45 

46Manage the request and token limits for the selected text-model record:

47 

48```terraform

49resource "openai_project_rate_limit" "application" {

50 project_id = "proj_123"

51 rate_limit_id = "rl-gpt-3.5-turbo"

52 max_requests_per_1_minute = 500

53 max_tokens_per_1_minute = 200000

54}

55```

56 

57Each argument has a specific role:

58 

59- `project_id` identifies the project whose rate limit will change.

60- `rate_limit_id` identifies an existing model rate-limit record. It isn't a model ID.

61- `max_requests_per_1_minute` limits the number of requests the project can send for that model each minute.

62- `max_tokens_per_1_minute` limits the number of tokens the project can process for that model each minute.

63 

64Set only the fields that apply to the selected record. Other record types can expose limits for images per minute, audio megabytes per minute, requests per day, or Batch input tokens per day. A configured value can't exceed the limit available to the organization and project.

65 

66Although the first Terraform plan shows this resource as an addition, the provider updates the existing rate-limit record and then stores it in Terraform state. Changing a configured limit sends another update.

67 

68Removing `openai_project_rate_limit` from the configuration removes the record

69 from Terraform state, but it doesn't reset or delete the remote rate limit.

70 Set the desired remote values before removing the resource if another workflow

71 will manage the record.

72 

73## Configure a project spend alert

74 

75Create a monthly project spend alert:

76 

77```terraform

78resource "openai_project_spend_alert" "monthly" {

79 project_id = "proj_123"

80 threshold_amount = 20000

81 currency = "USD"

82 interval = "month"

83 notification_channel_type = "email"

84 notification_channel_recipients = ["platform-alerts@example.com"]

85 notification_channel_subject_prefix = "OpenAI project spend"

86}

87```

88 

89The alert definition combines the spend condition and its notification channel:

90 

91- `project_id` limits the alert to spend from one project.

92- `threshold_amount` is the monthly threshold in cents. `20000` represents USD 200.

93- `currency` must be `USD`.

94- `interval` must be `month`.

95- `notification_channel_type` must be `email`.

96- `notification_channel_recipients` must contain at least one recipient.

97- `notification_channel_subject_prefix` is optional text added to alert email subjects.

98 

99Terraform creates the alert and stores its generated `alert_id`. Changing the threshold or notification fields updates the alert. Removing the resource deletes the remote alert.

100 

101Spend alerts are notifications, not hard limits. Define an incident or administrative response for each threshold, and use rate limits to constrain request volume independently.

102 

103## Configure an organization spend alert

104 

105Use an organization alert when the threshold should cover spend across the organization:

106 

107```terraform

108resource "openai_organization_spend_alert" "monthly" {

109 threshold_amount = 100000

110 currency = "USD"

111 interval = "month"

112 notification_channel_type = "email"

113 notification_channel_recipients = ["platform-alerts@example.com"]

114}

115```

116 

117This resource uses the same threshold units, interval, currency, and notification fields as a project alert. It doesn't take a `project_id` because it measures organization-wide spend. The example sends an email after monthly organization spend reaches USD 1,000.

118 

119You can manage project and organization alerts together. Use distinct thresholds and recipients when different teams own the response at each scope.

120 

121## Run the complete example

122 

123The focused examples use concrete values to explain each resource. The complete configuration replaces environment-specific values with variables and combines project rate-limit discovery, one managed rate limit, and one project spend alert.

124 

125Save the following configuration as `main.tf`:

126 

127```terraform

128terraform {

129 required_version = ">= 1.0"

130 

131 required_providers {

132 openai = {

133 source = "openai/openai"

134 version = ">= 1.0.0"

135 }

136 }

137}

138 

139provider "openai" {}

140 

141variable "project_id" {

142 type = string

143}

144 

145variable "rate_limit_id" {

146 type = string

147 description = "Existing rate-limit record for the text model to manage."

148}

149 

150variable "max_requests_per_minute" {

151 type = number

152}

153 

154variable "max_tokens_per_minute" {

155 type = number

156}

157 

158variable "project_spend_threshold_cents" {

159 type = number

160 description = "Monthly project spend threshold in cents."

161 

162 validation {

163 condition = var.project_spend_threshold_cents > 0

164 error_message = "The project spend threshold must be greater than zero."

165 }

166}

167 

168variable "alert_recipients" {

169 type = list(string)

170 

171 validation {

172 condition = length(var.alert_recipients) > 0

173 error_message = "Provide at least one spend-alert recipient."

174 }

175}

176 

177data "openai_project_rate_limits" "current" {

178 project_id = var.project_id

179}

180 

181resource "openai_project_rate_limit" "application" {

182 project_id = var.project_id

183 rate_limit_id = var.rate_limit_id

184 max_requests_per_1_minute = var.max_requests_per_minute

185 max_tokens_per_1_minute = var.max_tokens_per_minute

186}

187 

188resource "openai_project_spend_alert" "monthly" {

189 project_id = var.project_id

190 threshold_amount = var.project_spend_threshold_cents

191 currency = "USD"

192 interval = "month"

193 notification_channel_type = "email"

194 notification_channel_recipients = var.alert_recipients

195 notification_channel_subject_prefix = "OpenAI project spend"

196}

197 

198output "available_rate_limits" {

199 value = data.openai_project_rate_limits.current.rate_limits

200}

201 

202output "managed_rate_limit_model" {

203 value = openai_project_rate_limit.application.model

204}

205 

206output "project_spend_alert_id" {

207 value = openai_project_spend_alert.monthly.alert_id

208}

209```

210 

211Create `terraform.tfvars` with an existing project ID, the rate-limit record ID you discovered for a text model, approved limits, a threshold in cents, and the alert recipients:

212 

213```terraform

214project_id = "proj_123"

215rate_limit_id = "rl-gpt-3.5-turbo"

216 

217max_requests_per_minute = 500

218max_tokens_per_minute = 200000

219 

220project_spend_threshold_cents = 20000

221alert_recipients = ["platform-alerts@example.com"]

222```

223 

224Choose request and token values that don't exceed the limits currently available to the project. The `available_rate_limits` output in the plan shows the current records and values for comparison.

225 

226Initialize Terraform, then review and apply a saved plan:

227 

228```bash

229terraform init

230terraform fmt

231terraform validate

232terraform plan -out=tfplan

233terraform show tfplan

234terraform apply tfplan

235```

236 

237The first plan should contain two resources to add. Terraform describes the rate-limit resource as an addition to state, but applying it updates the existing OpenAI rate-limit record. The other addition creates the project spend alert. After the apply, `terraform output` prints the available rate limits, the model associated with the managed record, and the alert ID.

238 

239Run `terraform plan` again to confirm that the configuration produces no further changes. If it shows drift, determine whether another administrator or automation changed the rate limit or spend alert before applying another update.

Details

1# Manage service accounts with Terraform

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 

5An OpenAI service account is a nonhuman identity owned by a project. Terraform can create the account without a default role, define a least-privilege permission bundle, and assign that bundle through a group. Create and manage service-account API keys outside Terraform through the Administration API.

6 

7This guide follows a typical service-account onboarding workflow:

8 

91. Create a service account without a default project role or API key.

102. Assign a custom project role through a group, granting only the permissions the workload needs.

113. Create a scoped API key and store it in your secrets manager.

12 

13## Before you begin

14 

15Complete the [Terraform provider setup](https://developers.openai.com/api/docs/guides/terraform), export an Admin API key as `OPENAI_ADMIN_KEY`, and export the existing project's ID as `PROJECT_ID`.

16 

17Use a test organization when evaluating service-account creation, import, replacement, and deletion.

18 

19## Create a service account without a default role

20 

21Create the service account with Terraform:

22 

23```terraform

24resource "openai_project_service_account" "application" {

25 project_id = "proj_123"

26 name = "example-application-development-service-account"

27}

28 

29output "service_account_id" {

30 value = openai_project_service_account.application.service_account_id

31}

32```

33 

34Replace `proj_123` with the ID of the existing project that will own the service account.

35 

36The provider creates the service-account identity without generating an API key or assigning a default project role. Terraform stores the service-account ID and other nonsensitive metadata in state. At this stage, the service account has no project permissions.

37 

38## Assign least-privilege permissions

39 

40Define a custom project role with only the permissions the workload requires. Create a group, add the service account to it, and assign the role to the group. This example allows group members to create responses:

41 

42```terraform

43resource "openai_project_role" "application" {

44 project_id = openai_project_service_account.application.project_id

45 role_name = "Application response writer"

46 description = "Allows the application to create responses"

47 permissions = ["api.responses.write"]

48}

49 

50resource "openai_group" "application_access" {

51 name = "example-application-development-access"

52}

53 

54resource "openai_group_user" "application" {

55 group_id = openai_group.application_access.group_id

56 user_id = openai_project_service_account.application.id

57}

58 

59resource "openai_project_group_role" "application_access" {

60 project_id = openai_project_service_account.application.project_id

61 group_id = openai_group.application_access.group_id

62 role_id = openai_project_role.application.role_id

63}

64```

65 

66The `openai_project_role` resource defines the least-privilege permission bundle, `openai_group_user` adds the service account to the group, and `openai_project_group_role` assigns the role to that group. Every service account added to the group inherits the same project role. Replace `api.responses.write` with the smallest set of permissions approved for your workload. See [Projects and access](https://developers.openai.com/api/docs/guides/terraform/projects-and-access) for more information about group-based project access.

67 

68Review and apply the configuration:

69 

70```bash

71terraform plan

72terraform apply

73```

74 

75Don't assign the built-in `member` or `owner` role when a custom project role

76 provides the permissions your workload needs. Keep access limited to the

77 approved permission bundle.

78 

79## Create a scoped API key

80 

81After applying the Terraform configuration, create an API key through the [Create project service account API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects/subresources/service_accounts/subresources/api_keys/methods/create) endpoint. The API returns the key's full value only once, so protect the response file before making the request:

82 

83```bash

84SERVICE_ACCOUNT_ID="$(terraform output -raw service_account_id)"

85umask 077

86 

87curl -X POST \

88 "https://api.openai.com/v1/organization/projects/$PROJECT_ID/service_accounts/$SERVICE_ACCOUNT_ID/api_keys" \

89 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

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

91 -d '{

92 "name": "Production App",

93 "scopes": ["api.responses.write"]

94 }' \

95 --output service-account-api-key.json

96```

97 

98Choose the narrowest scopes the workload needs. API-key scopes can further restrict the service account's permissions, but they can't grant permissions outside its assigned project role.

99 

100Pass the `value` from `service-account-api-key.json` to your approved secrets-manager workflow without printing it. After your secrets manager stores and verifies the secret, remove the response file:

101 

102```bash

103rm service-account-api-key.json

104```

105 

106Treat `service-account-api-key.json` as a secret for as long as it exists. Don't commit it, write the key to Terraform configuration, expose it through a Terraform output, or pass it as a Terraform variable.

107 

108The [API reference](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/projects/subresources/service_accounts/subresources/api_keys/methods/create) includes the response shape and language-specific examples. Workloads that support [workload identity federation](https://developers.openai.com/api/docs/guides/workload-identity-federation) can use the same service account and least-privilege role without creating an API key.

109 

110## Import an existing service account

111 

112You don't need to import a service account that Terraform created. To adopt a service account created outside Terraform, declare it with the same project ID and name:

113 

114```terraform

115resource "openai_project_service_account" "application" {

116 project_id = "proj_123"

117 name = "example-application-development-service-account"

118}

119```

120 

121Import the existing identity before running a normal apply:

122 

123```bash

124SERVICE_ACCOUNT_ID="<existing-service-account-id>"

125 

126terraform import \

127 openai_project_service_account.application \

128 "$PROJECT_ID/$SERVICE_ACCOUNT_ID"

129 

130terraform plan

131```

132 

133The first plan after import should propose no changes to the service account. If it proposes replacement, make the configured name and project match the existing account before applying.

134 

135Import doesn't recover or store an API key, change the service account's existing project role, or import its group membership. Declare and import the existing `openai_project_role`, `openai_group`, `openai_group_user`, and `openai_project_group_role` resources if Terraform should manage them. The workload continues to read any existing secret from your secrets manager.

136 

137Import the service account before applying the resource declaration. If you

138 apply first, Terraform creates a different service account instead of adopting

139 the existing identity.

140 

141## Recover or rotate credentials

142 

143The full API-key value is available only in the API-key create response. Later project API-key retrieval returns a redacted value, so you can't recover a lost key.

144 

145Replace a lost or rotating credential without interrupting the workload:

146 

1471. Declare the replacement as a new `openai_project_service_account` resource, using a different Terraform resource name from the old account.

1482. Apply the configuration to create the replacement service account.

1493. Add the replacement to the existing group with `openai_group_user` so it inherits the least-privilege project role.

1504. Create an API key for the replacement through the Administration API and store the key with your approved secrets-manager workflow.

1515. Deploy the replacement key and verify the workload with the replacement account.

1526. Remove the old `openai_project_service_account` and its `openai_group_user` resource from the Terraform configuration. Keep the role, group, and group role assignment that the replacement service account still uses.

1537. Review and apply the plan that deletes the old service account and its group membership, then run `terraform plan` and require a no-op result.

154 

155Deleting an `openai_project_service_account` resource deletes the remote service account. Require explicit review for that change, especially while the old credential is still serving traffic.

156 

157For broader state adoption and removal behavior, see [Import and reconciliation](https://developers.openai.com/api/docs/guides/terraform/import-and-reconcile).

158 

159## Run the complete example

160 

161The focused examples use concrete values to explain service-account creation, role assignment, and API-key creation. The complete configuration replaces project-specific values and permissions with variables so you can reuse it across environments.

162 

163Save the following configuration as `main.tf`:

164 

165```terraform

166terraform {

167 required_version = ">= 1.0"

168 

169 required_providers {

170 openai = {

171 source = "openai/openai"

172 version = ">= 1.0.0"

173 }

174 }

175}

176 

177provider "openai" {}

178 

179variable "project_id" {

180 type = string

181 description = "ID of the existing OpenAI project."

182}

183 

184variable "service_account_name" {

185 type = string

186 description = "Name of the application service account."

187}

188 

189variable "project_role_permissions" {

190 type = list(string)

191 description = "Least-privilege project permissions for the application."

192 

193 validation {

194 condition = length(var.project_role_permissions) > 0

195 error_message = "Provide at least one approved project permission."

196 }

197}

198 

199resource "openai_project_service_account" "application" {

200 project_id = var.project_id

201 name = var.service_account_name

202}

203 

204resource "openai_project_role" "application" {

205 project_id = var.project_id

206 role_name = "Application API access"

207 description = "Least-privilege permissions approved for the application"

208 permissions = var.project_role_permissions

209}

210 

211resource "openai_group" "application_access" {

212 name = "${var.service_account_name}-access"

213}

214 

215resource "openai_group_user" "application" {

216 group_id = openai_group.application_access.group_id

217 user_id = openai_project_service_account.application.id

218}

219 

220resource "openai_project_group_role" "application_access" {

221 project_id = var.project_id

222 group_id = openai_group.application_access.group_id

223 role_id = openai_project_role.application.role_id

224}

225 

226output "project_id" {

227 value = var.project_id

228}

229 

230output "service_account_id" {

231 value = openai_project_service_account.application.service_account_id

232}

233 

234output "group_id" {

235 value = openai_group.application_access.group_id

236}

237 

238output "project_role_id" {

239 value = openai_project_role.application.role_id

240}

241```

242 

243Create `terraform.tfvars` with an existing project ID, a unique service-account name, and the smallest set of approved project permissions:

244 

245```terraform

246project_id = "proj_123"

247service_account_name = "example-application-development-service-account"

248 

249project_role_permissions = [

250 "api.responses.write",

251]

252```

253 

254Initialize Terraform, then review and apply a saved plan:

255 

256```bash

257terraform init

258terraform fmt

259terraform validate

260terraform plan -out=tfplan

261terraform show tfplan

262terraform apply tfplan

263```

264 

265The first plan should contain five resources to add: the service account, its custom project role, the group, the group membership, and the group role assignment. Run `terraform plan` again to confirm that the configuration produces no further changes.

266 

267Create the service-account API key outside Terraform:

268 

269```bash

270PROJECT_ID="$(terraform output -raw project_id)"

271SERVICE_ACCOUNT_ID="$(terraform output -raw service_account_id)"

272umask 077

273 

274curl -X POST \

275 "https://api.openai.com/v1/organization/projects/$PROJECT_ID/service_accounts/$SERVICE_ACCOUNT_ID/api_keys" \

276 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

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

278 -d '{

279 "name": "Production App",

280 "scopes": ["api.responses.write"]

281 }' \

282 --output service-account-api-key.json

283```

284 

285Move the returned API-key value into your approved secrets manager, then delete `service-account-api-key.json`. Don't store the key in Terraform configuration, state, or outputs.

guides/text.md +23 −36

Details

1# Text generation1# Text generation

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.

4 

3With the OpenAI API, you can use a [large language model](https://developers.openai.com/api/docs/models) to generate text from a prompt, as you might using [ChatGPT](https://chatgpt.com). Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.5With the OpenAI API, you can use a [large language model](https://developers.openai.com/api/docs/models) to generate text from a prompt, as you might using [ChatGPT](https://chatgpt.com). Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.

4 6 

5Use the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) for direct model requests like this text-generation call.7Use the [Responses API](https://developers.openai.com/api/reference/resources/responses) for direct model requests like this text-generation call.

6 8 

7Generate text from a simple prompt9Generate text from a simple prompt

8 10 


40```42```

41 43 

42```csharp44```csharp

43using System;45using OpenAI.Responses;

44using System.Threading.Tasks;46#pragma warning disable OPENAI001

45using OpenAI;

46 47 

47class Program48string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

48{49ResponsesClient client = new(key);

49 static async Task Main()

50 {

51 var client = new OpenAIClient(

52 Environment.GetEnvironmentVariable("OPENAI_API_KEY")

53 );

54 50 

55 var response = await client.Responses.CreateAsync(new ResponseCreateRequest51ResponseResult response = await client.CreateResponseAsync(

56 {52 "gpt-5.6",

57 Model = "gpt-5.6",53 "Say 'this is a test.'"

58 Input = "Say 'this is a test.'"54);

59 });

60 55 

61 Console.WriteLine($"[ASSISTANT]: {response.OutputText()}");56Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");

62 }

63}

64```57```

65 58 

66```java59```java


320 behind developer messages.313 behind developer messages.

321 </td>314 </td>

322 <td>315 <td>

323 Messages generated by the model have the <code>assistant</code> role.316 Messages generated by the model have the `assistant` role.

324 </td>317 </td>

325 </tr>318 </tr>

326 </tbody>319 </tbody>


347 340 

348- Keep prompt builders in a small module near the feature they support.341- Keep prompt builders in a small module near the feature they support.

349- Use typed function arguments or schemas for dynamic values such as customer data, files, or task options.342- Use typed function arguments or schemas for dynamic values such as customer data, files, or task options.

350- Pass the generated `instructions` and `input` directly to the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create).343- Pass the generated `instructions` and `input` directly to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create).

351- Add representative fixtures, tests, and evaluation checks before changing production prompts.344- Add representative fixtures, tests, and evaluation checks before changing production prompts.

352- Roll out prompt changes through your deployment system, using feature flags or configuration when you need staged releases.345- Roll out prompt changes through your deployment system, using feature flags or configuration when you need staged releases.

353 346 


357 350 

358Now that you know the basics of text inputs and outputs, you might want to check out one of these resources next.351Now that you know the basics of text inputs and outputs, you might want to check out one of these resources next.

359 352 

360[353[Build a prompt in the Playground

361 354 

362<span slot="icon">

363 </span>

364 Use the Playground to develop and iterate on prompts.

365 355 

366](https://platform.openai.com/chat/edit)

367 356 

368[357 Use the Playground to develop and iterate on prompts.](https://platform.openai.com/chat/edit)

369 358 

370<span slot="icon">359[Generate JSON data with Structured Outputs

371 </span>

372 Ensure JSON data emitted from a model conforms to a JSON schema.

373 360 

374](https://developers.openai.com/api/docs/guides/structured-outputs)

375 361 

376[

377 362 

378<span slot="icon">363 Ensure JSON data emitted from a model conforms to a JSON schema.](https://developers.openai.com/api/docs/guides/structured-outputs)

379 </span>364 

380 Check out all the options for text generation in the API reference.365[Full API reference

366 

367 

381 368 

382](https://developers.openai.com/api/docs/api-reference/responses)369 Check out all the options for text generation in the API reference.](https://developers.openai.com/api/reference/resources/responses)

Details

1# Text to speech1# Text to speech

2 2 

3The Audio API provides a [`speech`](https://developers.openai.com/api/docs/api-reference/audio/createSpeech) endpoint based on our [GPT-4o mini TTS (text-to-speech) model](https://developers.openai.com/api/docs/models/gpt-4o-mini-tts). It comes with 11 built-in voices and can be used to: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 Audio API provides a [`speech`](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create) endpoint based on our [GPT-4o mini TTS (text-to-speech) model](https://developers.openai.com/api/docs/models/gpt-4o-mini-tts). It comes with 11 built-in voices and can be used to:

4 6 

5- Narrate a written blog post7- Narrate a written blog post

6- Produce spoken audio in multiple languages8- Produce spoken audio in multiple languages


16 18 

17The `speech` endpoint takes three key inputs:19The `speech` endpoint takes three key inputs:

18 20 

191. The [model](https://developers.openai.com/api/docs/api-reference/audio/createSpeech#audio-createspeech-model) you're using211. The [model](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create#audio-createspeech-model) you're using

201. The [text](https://developers.openai.com/api/docs/api-reference/audio/createSpeech#audio-createspeech-input) to be turned into audio221. The [text](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create#audio-createspeech-input) to be turned into audio

211. The [voice](https://developers.openai.com/api/docs/api-reference/audio/createSpeech#audio-createspeech-voice) that will speak the output231. The [voice](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create#audio-createspeech-voice) that will speak the output

22 24 

23Here's a simple request example:25Here's a simple request example:

24 26 


206 208 

207## Custom voices209## Custom voices

208 210 

209Custom voices enable you to create a unique voice for your agent or application. These voices can be used for audio output with the [Text to Speech API](https://developers.openai.com/api/docs/api-reference/audio/createSpeech), the [Realtime API](https://developers.openai.com/api/docs/api-reference/realtime), or the [Chat Completions API with audio output](https://developers.openai.com/api/docs/guides/audio).211Custom voices enable you to create a unique voice for your agent or application. These voices can be used for audio output with the [Text to Speech API](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create), the [Realtime API](https://developers.openai.com/api/reference/resources/realtime), or the [Chat Completions API with audio output](https://developers.openai.com/api/docs/guides/audio).

210 212 

211To create a custom voice, you’ll provide a short sample audio reference that the model will seek to replicate.213To create a custom voice, you’ll provide a short sample audio reference that the model will seek to replicate.

212 214 


295 297 

296#### Using a voice during speech generation298#### Using a voice during speech generation

297 299 

298Speech generation will work as usual. Simply specify the ID of the voice in the `voice` parameter when [creating speech](https://developers.openai.com/api/docs/api-reference/audio/createSpeech), or when initiating a [realtime session](https://developers.openai.com/api/docs/api-reference/realtime/create-call#realtime_create_call-session-audio-output-voice).300Speech generation will work as usual. Simply specify the ID of the voice in the `voice` parameter when [creating speech](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create), or when initiating a [realtime session](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/create#realtime_create_call-session-audio-output-voice).

299 301 

300**Text to speech example**302**Text to speech example**

301 303 


335 337 

336## Related guides338## Related guides

337 339 

338<a href="/api/docs/guides/realtime">340[Realtime and audio overview

339

340 341 

341<span slot="icon">

342 </span>

343 Choose the right path for voice agents, translation, transcription, and

344 speech generation.

345 342 

346 343 

347</a>344 Choose the right path for voice agents, translation, transcription, and

348 345 speech generation.](https://developers.openai.com/api/docs/guides/realtime)

349<a href="/api/docs/guides/audio">

350 346 

347[Audio and speech concepts

351 348 

352<span slot="icon">

353 </span>

354 Review audio modalities, speech tasks, streaming, and request-based APIs.

355 349 

356 350 

357</a>351 Review audio modalities, speech tasks, streaming, and request-based APIs.](https://developers.openai.com/api/docs/guides/audio)

Details

1# Counting tokens1# Counting tokens

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.

4 

3Token counting lets you determine how many input tokens a request will use before you send it to the model. Use it to:5Token counting lets you determine how many input tokens a request will use before you send it to the model. Use it to:

4 6 

5- **Optimize prompts** to fit within context limits7- **Optimize prompts** to fit within context limits


7- **Route requests** based on size (e.g., smaller prompts to faster models)9- **Route requests** based on size (e.g., smaller prompts to faster models)

8- **Avoid surprises** with images and files—no more character-based estimation10- **Avoid surprises** with images and files—no more character-based estimation

9 11 

10The [input token count endpoint](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_tokens/methods/count) accepts the same input format as the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create). Pass text, messages, images, files, tools, or conversations—the API returns the exact count the model will receive.12The [input token count endpoint](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_tokens/methods/count) accepts the same input format as the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create). Pass text, messages, images, files, tools, or conversations—the API returns the exact count the model will receive.

11 13 

12The count includes formatting tokens used to represent request structure, such as message roles and boundaries. These tokens might not appear in the text or fields you tokenize locally.14The count includes formatting tokens used to represent request structure, such as message roles and boundaries. These tokens might not appear in the text or fields you tokenize locally.

13 15 


275```277```

276 278 

277 279 

278You can use `file_id` (from the [Files API](https://developers.openai.com/api/docs/api-reference/files)) or `image_url` (a URL or base64 data URL). See [images and vision](https://developers.openai.com/api/docs/guides/images-vision) for details.280You can use `file_id` (from the [Files API](https://developers.openai.com/api/reference/resources/files)) or `image_url` (a URL or base64 data URL). See [images and vision](https://developers.openai.com/api/docs/guides/images-vision) for details.

279 281 

280## Count tokens with tools282## Count tokens with tools

281 283 


377 379 

378## Count tokens with files380## Count tokens with files

379 381 

380[File inputs](https://developers.openai.com/api/docs/guides/pdf-files)—currently PDFs—are supported. Pass `file_id`, `file_url`, or `file_data` as you would for `responses.create`. The token count reflects the model’s full processed input.382[File inputs](https://developers.openai.com/api/docs/guides/file-inputs)—currently PDFs—are supported. Pass `file_id`, `file_url`, or `file_data` as you would for `responses.create`. The token count reflects the model’s full processed input.

381 383 

382## Understand output token counts384## Understand output token counts

383 385 

guides/tools.md +114 −125

Details

1# Using tools1# Using tools

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.

4 

3When generating model responses or building agents, you can extend capabilities using built‑in tools, function calling, Programmatic Tool Calling, tool search, and remote MCP servers. These enable the model to search the web, retrieve from your files, load deferred tool definitions at runtime, call your own functions, compose tool calls in JavaScript, or access third‑party services. Only `gpt-5.4` and later models support `tool_search`.5When generating model responses or building agents, you can extend capabilities using built‑in tools, function calling, Programmatic Tool Calling, tool search, and remote MCP servers. These enable the model to search the web, retrieve from your files, load deferred tool definitions at runtime, call your own functions, compose tool calls in JavaScript, or access third‑party services. Only `gpt-5.4` and later models support `tool_search`.

4 6 

5 7 

6 8 

7<div data-content-switcher-pane data-value="web-search">9Web search

8 <div class="hidden">Web search</div>10 

9 Include web search results for the model response11 Include web search results for the model response

10 12 

11```javascript13```javascript


59 61 

60```csharp62```csharp

61using OpenAI.Responses;63using OpenAI.Responses;

64#pragma warning disable OPENAI001

62 65 

63string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;66string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

64OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);67ResponsesClient client = new(key);

65 68 

66ResponseCreationOptions options = new();69CreateResponseOptions options = new() { Model = "gpt-5.6" };

67options.Tools.Add(ResponseTool.CreateWebSearchTool());70options.Tools.Add(ResponseTool.CreateWebSearchTool());

71options.InputItems.Add(

72 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")

73);

68 74 

69OpenAIResponse response = (OpenAIResponse)client.CreateResponse([75ResponseResult response = await client.CreateResponseAsync(options);

70 ResponseItem.CreateUserMessageItem([

71 ResponseContentPart.CreateInputTextPart("What was a positive news story from today?"),

72 ]),

73], options);

74 76 

75Console.WriteLine(response.GetOutputText());77Console.WriteLine(response.GetOutputText());

76```78```


89puts(response.output_text)91puts(response.output_text)

90```92```

91 93 

92 </div>94

93 <div data-content-switcher-pane data-value="file-search" hidden>95 

94 <div class="hidden">File search</div>96

97 

98

99File search

100 

95 Search your files in a response101 Search your files in a response

96 102 

97```python103```python


126 132 

127```csharp133```csharp

128using OpenAI.Responses;134using OpenAI.Responses;

135#pragma warning disable OPENAI001

129 136 

130string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;137string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

131OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);138ResponsesClient client = new(key);

132 139 

133ResponseCreationOptions options = new();140CreateResponseOptions options = new() { Model = "gpt-5.6" };

134options.Tools.Add(ResponseTool.CreateFileSearchTool(["<vector_store_id>"]));141options.Tools.Add(

142 ResponseTool.CreateFileSearchTool(["<vector_store_id>"])

143);

144options.InputItems.Add(

145 ResponseItem.CreateUserMessageItem("What is deep research by OpenAI?")

146);

135 147 

136OpenAIResponse response = (OpenAIResponse)client.CreateResponse([148ResponseResult response = await client.CreateResponseAsync(options);

137 ResponseItem.CreateUserMessageItem([

138 ResponseContentPart.CreateInputTextPart("What is deep research by OpenAI?"),

139 ]),

140], options);

141 149 

142Console.WriteLine(response.GetOutputText());150Console.WriteLine(response.GetOutputText());

143```151```


161puts(response)169puts(response)

162```170```

163 171 

164 </div>172

165 <div data-content-switcher-pane data-value="tool-search" hidden>173 

166 <div class="hidden">Tool search</div>174

175 

176

177Tool search

178 

167 Load deferred tools at runtime179 Load deferred tools at runtime

168 180 

169```python181```python


278console.log(response.output);290console.log(response.output);

279```291```

280 292 

281 </div>293

282 <div data-content-switcher-pane data-value="function-calling" hidden>294 

283 <div class="hidden">Function calling</div>295

296 

297

298Function calling

299 

284 Call your own function300 Call your own function

285 301 

286```javascript302```javascript


357 373 

358```csharp374```csharp

359using System.Text.Json;375using System.Text.Json;

376using System.Text.Json.Serialization.Metadata;

360using OpenAI.Responses;377using OpenAI.Responses;

378#pragma warning disable CA1869

379#pragma warning disable OPENAI001

361 380 

362string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;381string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

363OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);382ResponsesClient client = new(key);

364 383 

365ResponseCreationOptions options = new();384CreateResponseOptions options = new() { Model = "gpt-5.6" };

366options.Tools.Add(ResponseTool.CreateFunctionTool(385options.Tools.Add(

386 ResponseTool.CreateFunctionTool(

367 functionName: "get_weather",387 functionName: "get_weather",

368 functionDescription: "Get current temperature for a given location.",388 functionDescription: "Get current temperature for a given location.",

369 functionParameters: BinaryData.FromObjectAsJson(new389 functionParameters: BinaryData.FromString(

370 {390 """

371 type = "object",

372 properties = new

373 {391 {

374 location = new392 "type": "object",

375 {393 "properties": {

376 type = "string",394 "location": {

377 description = "City and country e.g. Bogotá, Colombia"395 "type": "string",

396 "description": "City and country e.g. Bogotá, Colombia"

378 }397 }

379 },398 },

380 required = new[] { "location" },399 "required": ["location"],

381 additionalProperties = false400 "additionalProperties": false

382 }),401 }

402 """

403 ),

383 strictModeEnabled: true404 strictModeEnabled: true

384 )405 )

385);406);

407options.InputItems.Add(

408 ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?")

409);

386 410 

387OpenAIResponse response = (OpenAIResponse)client.CreateResponse([411ResponseResult response = client.CreateResponse(options);

388 ResponseItem.CreateUserMessageItem([412Console.WriteLine(

389 ResponseContentPart.CreateInputTextPart("What is the weather like in Paris today?")413 JsonSerializer.Serialize(

390 ])414 response.OutputItems[0],

391], options);415 new JsonSerializerOptions

392 416 {

393Console.WriteLine(JsonSerializer.Serialize(response.OutputItems[0]));417 TypeInfoResolver = new DefaultJsonTypeInfoResolver(),

418 }

419 )

420);

394```421```

395 422 

396```bash423```bash


460puts(response.output.first.to_json)487puts(response.output.first.to_json)

461```488```

462 489 

463 </div>490

464 <div data-content-switcher-pane data-value="remote-mcp" hidden>491 

465 <div class="hidden">Remote MCP</div>492

493 

494

495Remote MCP

496 

466 Call a remote MCP server497 Call a remote MCP server

467 498 

468```bash499```bash


530 561 

531```csharp562```csharp

532using OpenAI.Responses;563using OpenAI.Responses;

564#pragma warning disable OPENAI001

533 565 

534string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;566string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

535OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);567ResponsesClient client = new(key);

536 568 

537ResponseCreationOptions options = new();569CreateResponseOptions options = new() { Model = "gpt-5.6" };

538options.Tools.Add(ResponseTool.CreateMcpTool(570options.Tools.Add(

571 ResponseTool.CreateMcpTool(

539 serverLabel: "dmcp",572 serverLabel: "dmcp",

540 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),573 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

541 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)574 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

542));575 )

576);

577options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));

543 578 

544OpenAIResponse response = (OpenAIResponse)client.CreateResponse([579ResponseResult response = await client.CreateResponseAsync(options);

545 ResponseItem.CreateUserMessageItem([

546 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

547 ])

548], options);

549 580 

550Console.WriteLine(response.GetOutputText());581Console.WriteLine(response.GetOutputText());

551```582```


572puts(response.output_text)603puts(response.output_text)

573```604```

574 605 

575 </div>

576 

577 606 

578 607 

579## Available tools608## Available tools

580 609 

581Here's an overview of the tools available in the OpenAI platform—select one of them for further guidance on usage.610Here's an overview of the tools available in the OpenAI platform—select one of them for further guidance on usage.

582 611 

583<a href="/api/docs/guides/function-calling">612[Function calling

584

585 613 

586<span slot="icon">

587 </span>

588 Call custom code to give the model access to additional data and

589 capabilities.

590 614 

591 615 

592</a>616 Call custom code to give the model access to additional data and

617 capabilities.](https://developers.openai.com/api/docs/guides/function-calling)

593 618 

594<a href="/api/docs/guides/tools-web-search">619[Web search

595 620 

596 621 

597<span slot="icon">

598 </span>

599 Include data from the Internet in model response generation.

600 622 

623 Include data from the Internet in model response generation.](https://developers.openai.com/api/docs/guides/tools-web-search)

601 624 

602</a>625[Remote MCP servers

603 626 

604<a href="/api/docs/guides/tools-connectors-mcp">

605 627 

606 628 

607<span slot="icon">

608 </span>

609 Give the model access to new capabilities via Model Context Protocol (MCP)629 Give the model access to new capabilities via Model Context Protocol (MCP)

610 servers.630 servers.](https://developers.openai.com/api/docs/guides/tools-connectors-mcp)

611 

612 

613</a>

614 631 

615<a href="/api/docs/guides/tools-skills">632[Skills

616 633 

617 634 

618<span slot="icon">

619 </span>

620 Upload and reuse versioned skill bundles in hosted shell environments.

621 635 

636 Upload and reuse versioned skill bundles in hosted shell environments.](https://developers.openai.com/api/docs/guides/tools-skills)

622 637 

623</a>638[Shell

624 639 

625<a href="/api/docs/guides/tools-shell">

626 640 

627 641 

628<span slot="icon">642 Run shell commands in hosted containers or in your own local runtime.](https://developers.openai.com/api/docs/guides/tools-shell)

629 </span>

630 Run shell commands in hosted containers or in your own local runtime.

631 643 

644[Computer use

632 645 

633</a>

634 646 

635<a href="/api/docs/guides/tools-computer-use">

636 647 

637 

638<span slot="icon">

639 </span>

640 Create agentic workflows that enable a model to control a computer648 Create agentic workflows that enable a model to control a computer

641 interface.649 interface.](https://developers.openai.com/api/docs/guides/tools-computer-use)

642 

643 650 

644</a>651[Image generation

645 652 

646<a href="/api/docs/guides/tools-image-generation">

647 653 

648 654 

649<span slot="icon">655 Generate or edit images using GPT Image.](https://developers.openai.com/api/docs/guides/tools-image-generation)

650 </span>

651 Generate or edit images using GPT Image.

652 656 

657[File search

653 658 

654</a>

655 659 

656<a href="/api/docs/guides/tools-file-search">

657 660 

658 

659<span slot="icon">

660 </span>

661 Search the contents of uploaded files for context when generating a661 Search the contents of uploaded files for context when generating a

662 response.662 response.](https://developers.openai.com/api/docs/guides/tools-file-search)

663 

664 663 

665</a>664[Tool search

666 665 

667<a href="/api/docs/guides/tools-tool-search">

668 666 

669 667 

670<span slot="icon">

671 </span>

672 Dynamically load relevant tools into the model’s context to optimize token668 Dynamically load relevant tools into the model’s context to optimize token

673 usage.669 usage.](https://developers.openai.com/api/docs/guides/tools-tool-search)

674 

675 

676</a>

677 

678<a href="/api/docs/guides/tools-programmatic-tool-calling">

679 670 

671[Programmatic Tool Calling

680 672 

681<span slot="icon">

682 </span>

683 Let models compose and run JavaScript that orchestrates tool calls.

684 673 

685 674 

686</a>675 Let models compose and run JavaScript that orchestrates tool calls.](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling)

687 676 

688## Usage in the API677## Usage in the API

689 678 

690When making a request to generate a [model response](https://developers.openai.com/api/docs/api-reference/responses/create), you usually enable tool access by specifying configurations in the `tools` parameter. Each tool has its own unique configuration requirements—see the [Available tools](#available-tools) section for detailed instructions.679When making a request to generate a [model response](https://developers.openai.com/api/reference/resources/responses/methods/create), you usually enable tool access by specifying configurations in the `tools` parameter. Each tool has its own unique configuration requirements—see the [Available tools](#available-tools) section for detailed instructions.

691 680 

692Based on the provided [prompt](https://developers.openai.com/api/docs/guides/text), the model automatically decides whether to use a configured tool. For instance, if your prompt requests information beyond the model's training cutoff date and web search is enabled, the model will typically invoke the web search tool to retrieve relevant, up-to-date information.681Based on the provided [prompt](https://developers.openai.com/api/docs/guides/text), the model automatically decides whether to use a configured tool. For instance, if your prompt requests information beyond the model's training cutoff date and web search is enabled, the model will typically invoke the web search tool to retrieve relevant, up-to-date information.

693 682 

694Some advanced workflows can also load more tool definitions during the interaction. For example, [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) can defer function definitions until the model decides they're needed.683Some advanced workflows can also load more tool definitions during the interaction. For example, [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) can defer function definitions until the model decides they're needed.

695 684 

696You can explicitly control or guide this behavior by setting the `tool_choice` parameter [in the API request](https://developers.openai.com/api/docs/api-reference/responses/create).685You can explicitly control or guide this behavior by setting the `tool_choice` parameter [in the API request](https://developers.openai.com/api/reference/resources/responses/methods/create).

697 686 

698## Usage in the Agents SDK687## Usage in the Agents SDK

699 688 

Details

1# Apply Patch1# Apply Patch

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.

4 

3The `apply_patch` tool lets GPT-5.1 create, update, and delete files in your codebase using structured diffs. Instead of just suggesting edits, the model emits patch operations that your application applies and then reports back on, enabling iterative, multi-step code editing workflows.5The `apply_patch` tool lets GPT-5.1 create, update, and delete files in your codebase using structured diffs. Instead of just suggesting edits, the model emits patch operations that your application applies and then reports back on, enabling iterative, multi-step code editing workflows.

4 6 

5## When to use7## When to use


325 327 

326You can find full working examples on GitHub.328You can find full working examples on GitHub.

327 329 

328<a330[Apply patch tool example - TypeScript

329 href="https://github.com/openai/openai-agents-js/blob/main/examples/tools/applyPatch.ts"

330 target="_blank"

331 rel="noreferrer"

332>

333

334 331 

335<span slot="icon">

336 </span>

337 Example of how to use the apply patch tool with the Agents SDK in TypeScript

338 332 

339 333 

340</a>334 Example of how to use the apply patch tool with the Agents SDK in TypeScript](https://github.com/openai/openai-agents-js/blob/main/examples/tools/applyPatch.ts)

341 335 

342<a336[Apply patch tool example - Python

343 href="https://github.com/openai/openai-agents-python/blob/main/examples/tools/apply_patch.py"

344 target="_blank"

345 rel="noreferrer"

346>

347 337 

348 338 

349<span slot="icon">

350 </span>

351 Example of how to use the apply patch tool with the Agents SDK in Python

352 339 

353 340 Example of how to use the apply patch tool with the Agents SDK in Python](https://github.com/openai/openai-agents-python/blob/main/examples/tools/apply_patch.py)

354</a>

355 341 

356## Handling common errors342## Handling common errors

357 343 


359 345 

360 346 

361 347 

362<div data-content-switcher-pane data-value="file-missing">348File not found

363 <div class="hidden">File not found</div>349 

364 File not found error350 File not found error

365 351 

366```json352```json


372}358}

373```359```

374 360 

375 </div>361

376 <div data-content-switcher-pane data-value="patch-conflict" hidden>362 

377 <div class="hidden">Patch conflict</div>363

364 

365

366Patch conflict

367 

378 Patch conflict error368 Patch conflict error

379 369 

380```json370```json


386}376}

387```377```

388 378 

389 </div>

390 

391 379 

392 380 

393The model can then adjust future diffs (for example, by re-reading a file in your prompt or simplifying a change) based on these error messages.381The model can then adjust future diffs (for example, by re-reading a file in your prompt or simplifying a change) based on these error messages.


415 403 

416<tr>404<tr>

417 <td>405 <td>

418 <div className="mb-1 flex items-center gap-2">406

419 [Responses](https://developers.openai.com/api/docs/api-reference/responses)407 

420 </div>408 [Responses](https://developers.openai.com/api/reference/resources/responses)

421 <div className="mb-1 flex items-center gap-2">409

422 [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat)410 

423 </div>411

424 <div className="mb-1 flex items-center gap-2">412 

425 [Assistants](https://developers.openai.com/api/docs/api-reference/assistants)413 [Chat Completions](https://developers.openai.com/api/reference/resources/chat)

426 </div>414

415 

416

417 

418 [Assistants](https://developers.openai.com/api/reference/resources/beta/subresources/assistants)

419

420 

427 </td>421 </td>

428 <td style={{ maxWidth: "150px" }}>422 <td style={{ maxWidth: "150px" }}>

429 [GPT-5.5](https://developers.openai.com/api/docs/models/gpt-5.5)423 [GPT-5.5](https://developers.openai.com/api/docs/models/gpt-5.5)

430 <br />424

425 

431 [GPT-5.4](https://developers.openai.com/api/docs/models/gpt-5.4)426 [GPT-5.4](https://developers.openai.com/api/docs/models/gpt-5.4)

432 <br />427

428 

433 [GPT-5.2](https://developers.openai.com/api/docs/models/gpt-5.2)429 [GPT-5.2](https://developers.openai.com/api/docs/models/gpt-5.2)

434 <br />430

431 

435 [GPT-5.1](https://developers.openai.com/api/docs/models/gpt-5.1)432 [GPT-5.1](https://developers.openai.com/api/docs/models/gpt-5.1)

436 </td>433 </td>

437</tr>434</tr>

Details

1# Code Interpreter1# Code Interpreter

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.

4 

3The Code Interpreter tool allows models to write and run Python code in a sandboxed environment to solve complex problems in domains like data analysis, coding, and math. Use it for:5The Code Interpreter tool allows models to write and run Python code in a sandboxed environment to solve complex problems in domains like data analysis, coding, and math. Use it for:

4 6 

5- Processing files with diverse data and formatting7- Processing files with diverse data and formatting


7- 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

8- Boosting visual intelligence in our latest reasoning models (like [o3](https://developers.openai.com/api/docs/models/o3) and [o4-mini](https://developers.openai.com/api/docs/models/o4-mini)). The model can use this tool to crop, zoom, rotate, and otherwise process and transform images.10- Boosting visual intelligence in our latest reasoning models (like [o3](https://developers.openai.com/api/docs/models/o3) and [o4-mini](https://developers.openai.com/api/docs/models/o4-mini)). The model can use this tool to crop, zoom, rotate, and otherwise process and transform images.

9 11 

10Here's an example of calling the [Responses API](https://developers.openai.com/api/docs/api-reference/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:

11 13 

12Use the Responses API with Code Interpreter14Use the Responses API with Code Interpreter

13 15 


83 85 

84## Containers86## Containers

85 87 

86The Code Interpreter tool requires a [container object](https://developers.openai.com/api/docs/api-reference/containers/object). A container is a fully sandboxed virtual machine that the model can run Python code in. This container can contain files that you upload, or that it generates.88The Code Interpreter tool requires a [container object](https://developers.openai.com/api/reference/resources/containers). A container is a fully sandboxed virtual machine that the model can run Python code in. This container can contain files that you upload, or that it generates.

87 89 

88There are two ways to create containers:90There are two ways to create containers:

89 91 

901. Auto mode: as seen in the example above, you can do this by passing the `"container": { "type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"] }` property in the tool configuration while creating a new Response object. This automatically creates a new container, or reuses an active container that was used by a previous `code_interpreter_call` item in the model's context. Leaving out `memory_limit` keeps the default 1 GB tier for the container. Look for the `code_interpreter_call` item in the output of this API request to find the `container_id` that was generated or used.921. Auto mode: as seen in the example above, you can do this by passing the `"container": { "type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"] }` property in the tool configuration while creating a new Response object. This automatically creates a new container, or reuses an active container that was used by a previous `code_interpreter_call` item in the model's context. Leaving out `memory_limit` keeps the default 1 GB tier for the container. Look for the `code_interpreter_call` item in the output of this API request to find the `container_id` that was generated or used.

912. Explicit mode: here, you explicitly [create a container](https://developers.openai.com/api/docs/api-reference/containers/createContainers) using the `v1/containers` endpoint, including the `memory_limit` you need (for example `"memory_limit": "4g"`), and assign its `id` as the `container` value in the tool configuration in the Response object. For example:932. Explicit mode: here, you explicitly [create a container](https://developers.openai.com/api/reference/resources/containers/methods/create) using the `v1/containers` endpoint, including the `memory_limit` you need (for example `"memory_limit": "4g"`), and assign its `id` as the `container` value in the tool configuration in the Response object. For example:

92 94 

93Use explicit container creation95Use explicit container creation

94 96 


161 163 

162You can choose from `1g` (default), `4g`, `16g`, or `64g`. Higher tiers offer more RAM for the session and are billed at the [built-in tools rates](https://developers.openai.com/api/docs/pricing#built-in-tools) for Code Interpreter. The selected `memory_limit` applies for the entire life of that container, whether it was created automatically or via the containers API.164You can choose from `1g` (default), `4g`, `16g`, or `64g`. Higher tiers offer more RAM for the session and are billed at the [built-in tools rates](https://developers.openai.com/api/docs/pricing#built-in-tools) for Code Interpreter. The selected `memory_limit` applies for the entire life of that container, whether it was created automatically or via the containers API.

163 165 

164Note that containers created with the auto mode are also accessible using the [`/v1/containers`](https://developers.openai.com/api/docs/api-reference/containers) endpoint.166Note that containers created with the auto mode are also accessible using the [`/v1/containers`](https://developers.openai.com/api/reference/resources/containers) endpoint.

165 167 

166### Expiration168### Expiration

167 169 


202}204}

203```205```

204 206 

205You can download these constructed files by calling the [get container file content](https://developers.openai.com/api/docs/api-reference/container-files/retrieveContainerFileContent) method.207You can download these constructed files by calling the [get container file content](https://developers.openai.com/api/reference/resources/containers/subresources/files/subresources/content/methods/retrieve) method.

206 208 

207Any [files in the model input](https://developers.openai.com/api/docs/guides/file-inputs) get automatically uploaded to the container. You do not have to explicitly upload it to the container.209Any [files in the model input](https://developers.openai.com/api/docs/guides/file-inputs) get automatically uploaded to the container. You do not have to explicitly upload it to the container.

208 210 

209### Uploading and downloading files211### Uploading and downloading files

210 212 

211Add new files to your container using [Create container file](https://developers.openai.com/api/docs/api-reference/container-files/createContainerFile). This endpoint accepts either a multipart upload or a JSON body with a `file_id`.213Add new files to your container using [Create container file](https://developers.openai.com/api/reference/resources/containers/subresources/files/methods/create). This endpoint accepts either a multipart upload or a JSON body with a `file_id`.

212List existing container files with [List container files](https://developers.openai.com/api/docs/api-reference/container-files/listContainerFiles) and download bytes from [Retrieve container file content](https://developers.openai.com/api/docs/api-reference/container-files/retrieveContainerFileContent).214List existing container files with [List container files](https://developers.openai.com/api/reference/resources/containers/subresources/files/methods/list) and download bytes from [Retrieve container file content](https://developers.openai.com/api/reference/resources/containers/subresources/files/subresources/content/methods/retrieve).

213 215 

214### Dealing with citations216### Dealing with citations

215 217 


265 267 

266<tr>268<tr>

267 <td>269 <td>

268 <div className="mb-1 flex items-center gap-2">270

269 [Responses](https://developers.openai.com/api/docs/api-reference/responses)271 

270 </div>272 [Responses](https://developers.openai.com/api/reference/resources/responses)

271 <div className="mb-1 flex items-center gap-2">273

272 [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat)274 

273 </div>275

274 <div className="mb-1 flex items-center gap-2">276 

275 [Assistants](https://developers.openai.com/api/docs/api-reference/assistants)277 [Chat Completions](https://developers.openai.com/api/reference/resources/chat)

276 </div>278

279 

280

281 

282 [Assistants](https://developers.openai.com/api/reference/resources/beta/subresources/assistants)

283

284 

277 </td>285 </td>

278 <td style={{ maxWidth: "150px" }}>100 RPM per org</td>286 <td style={{ maxWidth: "150px" }}>100 RPM per org</td>

279 <td style={{ maxWidth: "150px" }}>287 <td style={{ maxWidth: "150px" }}>

280 [Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools) <br />288 [Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools)

289 

281 [ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)290 [ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)

282 </td>291 </td>

283</tr>292</tr>

Details

1# Computer use1# Computer use

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.

4 

3Computer use lets a model operate software through the user interface. It can inspect screenshots, return interface actions for your code to execute, or work through a custom harness that mixes visual and programmatic interaction with the UI.5Computer use lets a model operate software through the user interface. It can inspect screenshots, return interface actions for your code to execute, or work through a custom harness that mixes visual and programmatic interaction with the UI.

4 6 

5`gpt-5.4` includes new training for this kind of work, and future models will build on the same pattern. The model is designed to operate flexibly across a range of harness shapes, including the built-in Responses API `computer` tool, custom tools layered on top of existing automation harnesses, and code-execution environments that expose browser or desktop controls.7`gpt-5.4` includes new training for this kind of work, and future models will build on the same pattern. The model is designed to operate flexibly across a range of harness shapes, including the built-in Responses API `computer` tool, custom tools layered on top of existing automation harnesses, and code-execution environments that expose browser or desktop controls.


283 285 

284 286 

285 287 

286<div data-content-switcher-pane data-value="playwright">288Playwright

287 <div class="hidden">Playwright</div>289 

288 Normalization helpers290 Normalization helpers

289 291 

290```javascript292```javascript


449 return normalized451 return normalized

450```452```

451 453 

452 </div>454

453 <div data-content-switcher-pane data-value="docker" hidden>455 

454 <div class="hidden">Docker</div>456

457 

458

459Docker

460 

455 Normalization helpers461 Normalization helpers

456 462 

457```javascript463```javascript


647 return normalized653 return normalized

648```654```

649 655 

650 </div>

651 

652 656 

653 657 

654Batched actions in one turn658Batched actions in one turn


674 678 

675 679 

676 680 

677<div data-content-switcher-pane data-value="playwright">681Playwright

678 <div class="hidden">Playwright</div>682 

679 Execute Computer use actions683 Execute Computer use actions

680 684 

681```javascript685```javascript


815 raise ValueError(f"Unsupported action: {action.type}")819 raise ValueError(f"Unsupported action: {action.type}")

816```820```

817 821 

818 </div>822

819 <div data-content-switcher-pane data-value="docker" hidden>823 

820 <div class="hidden">Docker</div>824

825 

826

827Docker

828 

821 Execute Computer use actions829 Execute Computer use actions

822 830 

823```javascript831```javascript


1031 raise ValueError(f"Unsupported action: {action.type}")1039 raise ValueError(f"Unsupported action: {action.type}")

1032```1040```

1033 1041 

1034 </div>

1035 

1036 1042 

1037 1043 

1038For modifier-assisted mouse actions such as `Ctrl`+click or `Shift`+drag, see the examples below.1044For modifier-assisted mouse actions such as `Ctrl`+click or `Shift`+drag, see the examples below.


1069 1075 

1070 1076 

1071 1077 

1072<div data-content-switcher-pane data-value="playwright">1078Playwright

1073 <div class="hidden">Playwright</div>1079 

1074 Execute modifier-assisted Computer use actions1080 Execute modifier-assisted Computer use actions

1075 1081 

1076```javascript1082```javascript


1252 raise ValueError(f"Unsupported action: {action.type}")1258 raise ValueError(f"Unsupported action: {action.type}")

1253```1259```

1254 1260 

1255 </div>1261

1256 <div data-content-switcher-pane data-value="docker" hidden>1262 

1257 <div class="hidden">Docker</div>1263

1264 

1265

1266Docker

1267 

1258 Execute modifier-assisted Computer use actions1268 Execute modifier-assisted Computer use actions

1259 1269 

1260```javascript1270```javascript


1515 raise ValueError(f"Unsupported action: {action.type}")1525 raise ValueError(f"Unsupported action: {action.type}")

1516```1526```

1517 1527 

1518 </div>

1519 

1520 1528 

1521 1529 

1522### 4. Capture and return the updated screenshot1530### 4. Capture and return the updated screenshot


1525 1533 

1526 1534 

1527 1535 

1528<div data-content-switcher-pane data-value="playwright">1536Playwright

1529 <div class="hidden">Playwright</div>1537 

1530 Capture a screenshot1538 Capture a screenshot

1531 1539 

1532```javascript1540```javascript


1540 return page.screenshot(type="png")1548 return page.screenshot(type="png")

1541```1549```

1542 1550 

1543 </div>1551

1544 <div data-content-switcher-pane data-value="docker" hidden>1552 

1545 <div class="hidden">Docker</div>1553

1554 

1555

1556Docker

1557 

1546 Capture a screenshot1558 Capture a screenshot

1547 1559 

1548```javascript1560```javascript


1565 )1577 )

1566```1578```

1567 1579 

1568 </div>

1569 

1570 1580 

1571 1581 

1572Send that screenshot back as a `computer_call_output` item:1582Send that screenshot back as a `computer_call_output` item:


1773 1783 

1774 1784 

1775 1785 

1776<div data-content-switcher-pane data-value="javascript">1786JavaScript

1777 <div class="hidden">JavaScript</div>1787 

1778 Code-execution harness1788 Code-execution harness

1779 1789 

1780```javascript1790```javascript


2042await main(getCliPrompt());2052await main(getCliPrompt());

2043```2053```

2044 2054 

2045 </div>2055

2046 <div data-content-switcher-pane data-value="python" hidden>2056 

2047 <div class="hidden">Python</div>2057

2058 

2059

2060Python

2061 

2048 Code-execution harness2062 Code-execution harness

2049 2063 

2050```python2064```python


2333 asyncio.run(main(prompt=args.prompt) if args.prompt is not None else main())2347 asyncio.run(main(prompt=args.prompt) if args.prompt is not None else main())

2334```2348```

2335 2349 

2336 </div>

2337 

2338 2350 

2339 2351 

2340## Handle user confirmation and consent2352## Handle user confirmation and consent


2523 2535 

2524To see end-to-end examples in many environments, use the sample app:2536To see end-to-end examples in many environments, use the sample app:

2525 2537 

2526<a2538[CUA sample app

2527 href="https://github.com/openai/openai-cua-sample-app"

2528 target="_blank"

2529 rel="noreferrer"

2530>

2531

2532 2539 

2533<span slot="icon">

2534 </span>

2535 Examples of how to integrate the computer use tool in different environments

2536 2540 

2537 2541 

2538</a>2542 Examples of how to integrate the computer use tool in different environments](https://github.com/openai/openai-cua-sample-app)

Details

1# MCP and Connectors1# MCP and Connectors

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.

4 

3In addition to tools you make available to the model with [function calling](https://developers.openai.com/api/docs/guides/function-calling), you can give models new capabilities using **connectors** and **remote MCP servers**. These tools give the model the ability to connect to and control external services when needed to respond to a user's prompt. These tool calls can either be allowed automatically, or restricted with explicit approval required by you as the developer.5In addition to tools you make available to the model with [function calling](https://developers.openai.com/api/docs/guides/function-calling), you can give models new capabilities using **connectors** and **remote MCP servers**. These tools give the model the ability to connect to and control external services when needed to respond to a user's prompt. These tool calls can either be allowed automatically, or restricted with explicit approval required by you as the developer.

4 6 

5- **Connectors** are OpenAI-maintained MCP wrappers for popular services like Google Workspace or Dropbox, like the connectors available in [ChatGPT](https://chatgpt.com).7- **Connectors** are OpenAI-maintained MCP wrappers for popular services like Google Workspace or Dropbox, like the connectors available in [ChatGPT](https://chatgpt.com).


13 15 

14## Quickstart16## Quickstart

15 17 

16Check out the examples below to see how remote MCP servers and connectors work through the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create). Both connectors and remote MCP servers can be used with the `mcp` built-in tool type.18Check out the examples below to see how remote MCP servers and connectors work through the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create). Both connectors and remote MCP servers can be used with the `mcp` built-in tool type.

19 

20 

17 21 

22Using remote MCP servers

18 23 

19 24

20<div data-content-switcher-pane data-value="remote-mcp">25 

21 <div class="hidden">Using remote MCP servers</div>26 Remote MCP servers require a `server_url`. Depending on the server,

22 <p>27 you may also need an OAuth `authorization` parameter containing an

23 Remote MCP servers require a <code>server_url</code>. Depending on the server,

24 you may also need an OAuth <code>authorization</code> parameter containing an

25 access token.28 access token.

26 </p>29

30 

27 31 

28 Using a remote MCP server in the Responses API32 Using a remote MCP server in the Responses API

29 33 


92 96 

93```csharp97```csharp

94using OpenAI.Responses;98using OpenAI.Responses;

99#pragma warning disable OPENAI001

95 100 

96string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;101string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

97OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);102ResponsesClient client = new(key);

98 103 

99ResponseCreationOptions options = new();104CreateResponseOptions options = new() { Model = "gpt-5.6" };

100options.Tools.Add(ResponseTool.CreateMcpTool(105options.Tools.Add(

106 ResponseTool.CreateMcpTool(

101 serverLabel: "dmcp",107 serverLabel: "dmcp",

102 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),108 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

103 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)109 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

104));110 )

111);

112options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));

105 113 

106OpenAIResponse response = (OpenAIResponse)client.CreateResponse([114ResponseResult response = await client.CreateResponseAsync(options);

107 ResponseItem.CreateUserMessageItem([

108 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

109 ])

110], options);

111 115 

112Console.WriteLine(response.GetOutputText());116Console.WriteLine(response.GetOutputText());

113```117```


138 It is very important that developers trust any remote MCP server they use with142 It is very important that developers trust any remote MCP server they use with

139 the Responses API. A malicious server can exfiltrate sensitive data from143 the Responses API. A malicious server can exfiltrate sensitive data from

140 anything that enters the model's context. Carefully review the 144 anything that enters the model's context. Carefully review the

141 <strong>Risks and Safety</strong> section below before using this tool.145 **Risks and Safety** section below before using this tool.

146 

147

148 

149

150 

151

152Using connectors

153 

154

155 

156 Connectors require a `connector_id` parameter, and an OAuth access

157 token provided by your application in the `authorization` parameter.

158

142 159 

143 </div>

144 <div data-content-switcher-pane data-value="connector" hidden>

145 <div class="hidden">Using connectors</div>

146 <p>

147 Connectors require a <code>connector_id</code> parameter, and an OAuth access

148 token provided by your application in the <code>authorization</code> parameter.

149 </p>

150 160 

151 Using connectors in the Responses API161 Using connectors in the Responses API

152 162 


217 227 

218```csharp228```csharp

219using OpenAI.Responses;229using OpenAI.Responses;

230#pragma warning disable OPENAI001

220 231 

221string dropboxToken = Environment.GetEnvironmentVariable("DROPBOX_OAUTH_ACCESS_TOKEN")!;232string dropboxToken =

233 Environment.GetEnvironmentVariable("DROPBOX_OAUTH_ACCESS_TOKEN")!;

222string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;234string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

223OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);235ResponsesClient client = new(key);

224 236 

225ResponseCreationOptions options = new();237CreateResponseOptions options = new() { Model = "gpt-5.6" };

226options.Tools.Add(ResponseTool.CreateMcpTool(238options.Tools.Add(

239 ResponseTool.CreateMcpTool(

227 serverLabel: "Dropbox",240 serverLabel: "Dropbox",

228 connectorId: McpToolConnectorId.Dropbox,241 connectorId: McpToolConnectorId.Dropbox,

229 authorizationToken: dropboxToken,242 authorizationToken: dropboxToken,

230 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)243 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

231));244 )

245);

246options.InputItems.Add(

247 ResponseItem.CreateUserMessageItem("Summarize the Q2 earnings report.")

248);

232 249 

233OpenAIResponse response = (OpenAIResponse)client.CreateResponse([250ResponseResult response = await client.CreateResponseAsync(options);

234 ResponseItem.CreateUserMessageItem([

235 ResponseContentPart.CreateInputTextPart("Summarize the Q2 earnings report.")

236 ])

237], options);

238 251 

239Console.WriteLine(response.GetOutputText());252Console.WriteLine(response.GetOutputText());

240```253```

241 254 

242 255 

243 </div>

244 

245 

246 256 

247The API will return new items in the `output` array of the model response. If the model decides to use a Connector or MCP server, it will first make a request to list available tools from the server, which will create a `mcp_list_tools` output item. From the simple remote MCP server example above, it contains only one tool definition:257The API will return new items in the `output` array of the model response. If the model decides to use a Connector or MCP server, it will first make a request to list available tools from the server, which will create a `mcp_list_tools` output item. From the simple remote MCP server example above, it contains only one tool definition:

248 258 


291 301 

292## How it works302## How it works

293 303 

294The MCP tool (for both remote MCP servers and connectors) is available in the [Responses API](https://developers.openai.com/api/docs/api-reference/responses/create) in most recent models. Check MCP tool compatibility for your model [here](https://developers.openai.com/api/docs/models). When you're using the MCP tool, you only pay for [tokens](https://developers.openai.com/api/docs/pricing) used when importing tool definitions or making tool calls. There are no additional fees involved per tool call.304The MCP tool (for both remote MCP servers and connectors) is available in the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) in most recent models. Check MCP tool compatibility for your model [here](https://developers.openai.com/api/docs/models). When you're using the MCP tool, you only pay for [tokens](https://developers.openai.com/api/docs/pricing) used when importing tool definitions or making tool calls. There are no additional fees involved per tool call.

295 305 

296Below, we'll step through the process the API takes when calling an MCP tool.306Below, we'll step through the process the API takes when calling an MCP tool.

297 307 


407 417 

408```csharp418```csharp

409using OpenAI.Responses;419using OpenAI.Responses;

420#pragma warning disable OPENAI001

410 421 

411string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;422string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

412OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);423ResponsesClient client = new(key);

413 424 

414ResponseCreationOptions options = new();425CreateResponseOptions options = new() { Model = "gpt-5.6" };

415options.Tools.Add(ResponseTool.CreateMcpTool(426options.Tools.Add(

427 ResponseTool.CreateMcpTool(

416 serverLabel: "dmcp",428 serverLabel: "dmcp",

417 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),429 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

418 allowedTools: new McpToolFilter() { ToolNames = { "roll" } },430 allowedTools: new McpToolFilter() { ToolNames = { "roll" } },

419 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)431 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

420));432 )

433);

434options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));

421 435 

422OpenAIResponse response = (OpenAIResponse)client.CreateResponse([436ResponseResult response = await client.CreateResponseAsync(options);

423 ResponseItem.CreateUserMessageItem([

424 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

425 ])

426], options);

427 437 

428Console.WriteLine(response.GetOutputText());438Console.WriteLine(response.GetOutputText());

429```439```


553 563 

554```csharp564```csharp

555using OpenAI.Responses;565using OpenAI.Responses;

566#pragma warning disable OPENAI001

556 567 

557string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;568string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

558OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);569ResponsesClient client = new(key);

559 570 

560ResponseCreationOptions options = new();571CreateResponseOptions options = new() { Model = "gpt-5.6" };

561options.Tools.Add(ResponseTool.CreateMcpTool(572options.Tools.Add(

573 ResponseTool.CreateMcpTool(

562 serverLabel: "dmcp",574 serverLabel: "dmcp",

563 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),575 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

564 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval)576 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval

565));577 )

578);

566 579 

567// STEP 1: Create response that requests tool call approval580// STEP 1: Create a response that requests tool-call approval.

568OpenAIResponse response1 = (OpenAIResponse)client.CreateResponse([581options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));

569 ResponseItem.CreateUserMessageItem([582ResponseResult response1 = await client.CreateResponseAsync(options);

570 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

571 ])

572], options);

573 583 

574McpToolCallApprovalRequestItem? approvalRequestItem = response1.OutputItems.Last() as McpToolCallApprovalRequestItem;584McpToolCallApprovalRequestItem approvalRequest =

585 response1.OutputItems.OfType<McpToolCallApprovalRequestItem>().Single();

575 586 

576// STEP 2: Approve the tool call request and get final response587// STEP 2: Approve the tool call and get the final response.

577options.PreviousResponseId = response1.Id;588options.PreviousResponseId = response1.Id;

578OpenAIResponse response2 = (OpenAIResponse)client.CreateResponse([589options.InputItems.Clear();

579 ResponseItem.CreateMcpApprovalResponseItem(approvalRequestItem!.Id, approved: true),590options.InputItems.Add(

580], options);591 ResponseItem.CreateMcpApprovalResponseItem(approvalRequest.Id, approved: true)

592);

593ResponseResult response2 = await client.CreateResponseAsync(options);

581 594 

582Console.WriteLine(response2.GetOutputText());595Console.WriteLine(response2.GetOutputText());

583```596```


661 674 

662```csharp675```csharp

663using OpenAI.Responses;676using OpenAI.Responses;

677#pragma warning disable OPENAI001

664 678 

665string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;679string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

666OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);680ResponsesClient client = new(key);

667 681 

668ResponseCreationOptions options = new();682CreateResponseOptions options = new() { Model = "gpt-5.6" };

669options.Tools.Add(ResponseTool.CreateMcpTool(683options.Tools.Add(

684 ResponseTool.CreateMcpTool(

670 serverLabel: "deepwiki",685 serverLabel: "deepwiki",

671 serverUri: new Uri("https://mcp.deepwiki.com/mcp"),686 serverUri: new Uri("https://mcp.deepwiki.com/mcp"),

672 allowedTools: new McpToolFilter() { ToolNames = { "ask_question", "read_wiki_structure" } },687 toolCallApprovalPolicy: new CustomMcpToolCallApprovalPolicy

673 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)688 {

674));689 ToolsNeverRequiringApproval = new McpToolFilter

690 {

691 ToolNames = { "ask_question", "read_wiki_structure" },

692 },

693 }

694 )

695);

696options.InputItems.Add(

697 ResponseItem.CreateUserMessageItem(

698 "What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?"

699 )

700);

675 701 

676OpenAIResponse response = (OpenAIResponse)client.CreateResponse([702ResponseResult response = await client.CreateResponseAsync(options);

677 ResponseItem.CreateUserMessageItem([

678 ResponseContentPart.CreateInputTextPart("What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?")

679 ])

680], options);

681 703 

682Console.WriteLine(response.GetOutputText());704Console.WriteLine(response.GetOutputText());

683```705```


752 774 

753```csharp775```csharp

754using OpenAI.Responses;776using OpenAI.Responses;

777#pragma warning disable OPENAI001

755 778 

756string authToken = Environment.GetEnvironmentVariable("STRIPE_OAUTH_ACCESS_TOKEN")!;779string authToken =

780 Environment.GetEnvironmentVariable("STRIPE_OAUTH_ACCESS_TOKEN")!;

757string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;781string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

758OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);782ResponsesClient client = new(key);

759 783 

760ResponseCreationOptions options = new();784CreateResponseOptions options = new() { Model = "gpt-5.6" };

761options.Tools.Add(ResponseTool.CreateMcpTool(785options.Tools.Add(

786 ResponseTool.CreateMcpTool(

762 serverLabel: "stripe",787 serverLabel: "stripe",

763 serverUri: new Uri("https://mcp.stripe.com"),788 serverUri: new Uri("https://mcp.stripe.com"),

764 authorizationToken: authToken789 authorizationToken: authToken

765));790 )

791);

792options.InputItems.Add(

793 ResponseItem.CreateUserMessageItem("Create a payment link for $20")

794);

766 795 

767OpenAIResponse response = (OpenAIResponse)client.CreateResponse([796ResponseResult response = await client.CreateResponseAsync(options);

768 ResponseItem.CreateUserMessageItem([

769 ResponseContentPart.CreateInputTextPart("Create a payment link for $20")

770 ])

771], options);

772 797 

773Console.WriteLine(response.GetOutputText());798Console.WriteLine(response.GetOutputText());

774```799```


879 904 

880```csharp905```csharp

881using OpenAI.Responses;906using OpenAI.Responses;

907#pragma warning disable OPENAI001

882 908 

883string authToken = Environment.GetEnvironmentVariable("GOOGLE_CALENDAR_OAUTH_ACCESS_TOKEN")!;909string authToken =

910 Environment.GetEnvironmentVariable("GOOGLE_CALENDAR_OAUTH_ACCESS_TOKEN")!;

884string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;911string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

885OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);912ResponsesClient client = new(key);

886 913 

887ResponseCreationOptions options = new();914CreateResponseOptions options = new() { Model = "gpt-5.6" };

888options.Tools.Add(ResponseTool.CreateMcpTool(915options.Tools.Add(

916 ResponseTool.CreateMcpTool(

889 serverLabel: "google_calendar",917 serverLabel: "google_calendar",

890 connectorId: McpToolConnectorId.GoogleCalendar,918 connectorId: McpToolConnectorId.GoogleCalendar,

891 authorizationToken: authToken,919 authorizationToken: authToken,

892 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)920 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

893));921 )

922);

923options.InputItems.Add(

924 ResponseItem.CreateUserMessageItem("What's on my Google Calendar for today?")

925);

894 926 

895OpenAIResponse response = (OpenAIResponse)client.CreateResponse([927ResponseResult response = await client.CreateResponseAsync(options);

896 ResponseItem.CreateUserMessageItem([

897 ResponseContentPart.CreateInputTextPart("What's on my Google Calendar for today?")

898 ])

899], options);

900 928 

901Console.WriteLine(response.GetOutputText());929Console.WriteLine(response.GetOutputText());

902```930```


1290 1318 

1291<tr>1319<tr>

1292<td>1320<td>

1293<div className="mb-1 flex items-center gap-2">1321 

1294 [Responses](https://developers.openai.com/api/docs/api-reference/responses)1322 

1295</div>1323 [Responses](https://developers.openai.com/api/reference/resources/responses)

1296<div className="mb-1 flex items-center gap-2">1324 

1297 [Chat Completions](https://developers.openai.com/api/docs/api-reference/chat)1325 

1298</div>1326 

1299<div className="mb-1 flex items-center gap-2">1327 

1300 [Assistants](https://developers.openai.com/api/docs/api-reference/assistants)1328 [Chat Completions](https://developers.openai.com/api/reference/resources/chat)

1301</div>1329 

1330 

1331 

1332 

1333 [Assistants](https://developers.openai.com/api/reference/resources/beta/subresources/assistants)

1334 

1335 

1302</td>1336</td>

1303<td style={{"maxWidth": "150px"}}>1337<td style={{"maxWidth": "150px"}}>

1304**Tier 1**<br/>1338**Tier 1**

1339 

1305200 RPM1340200 RPM

1306 1341 

1307**Tier 2 and 3**<br/>1342**Tier 2 and 3**

1343 

13081000 RPM13441000 RPM

1309 1345 

1310**Tier 4 and 5**<br/>1346**Tier 4 and 5**

1347 

13112000 RPM13482000 RPM

1312 1349 

1313</td>1350</td>

1314<td style={{"maxWidth": "150px"}}>1351<td style={{"maxWidth": "150px"}}>

1315[Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools) <br/>1352[Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools)

1353 

1316[ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)1354[ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)

1317</td>1355</td>

1318</tr>1356</tr>

Details

1# Image generation1# Image generation

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.

4 

3The image generation tool allows you to generate images using a text prompt, and optionally image inputs. It uses GPT Image models, including `gpt-image-2`, `gpt-image-1.5`, `gpt-image-1`, and `gpt-image-1-mini`, and automatically optimizes text inputs for improved performance.5The image generation tool allows you to generate images using a text prompt, and optionally image inputs. It uses GPT Image models, including `gpt-image-2`, `gpt-image-1.5`, `gpt-image-1`, and `gpt-image-1-mini`, and automatically optimizes text inputs for improved performance.

4 6 

5To learn more about image generation, refer to our dedicated [image generation7To learn more about image generation, refer to our dedicated [image generation


68 70 

69### Tool options71### Tool options

70 72 

71You can configure the following output options as parameters for the [image generation tool](https://developers.openai.com/api/docs/api-reference/responses/create#responses-create-tools):73You can configure the following output options as parameters for the [image generation tool](https://developers.openai.com/api/reference/resources/responses/methods/create#responses-create-tools):

72 74 

73- Size: Image dimensions, for example, 1024 × 1024 or 1024 × 153675- Size: Image dimensions, for example, 1024 × 1024 or 1024 × 1536

74- Quality: Rendering quality, for example, low, medium, or high76- Quality: Rendering quality, for example, low, medium, or high


113 115 

114 116 

115 117 

116<div data-content-switcher-pane data-value="responseid">118Using previous response ID

117 <div class="hidden">Using previous response ID</div>119 

118 Multi-turn image generation120 Multi-turn image generation

119 121 

120```javascript122```javascript


207 f.write(base64.b64decode(image_base64))209 f.write(base64.b64decode(image_base64))

208```210```

209 211 

210 </div>212

211 <div data-content-switcher-pane data-value="imageid" hidden>213 

212 <div class="hidden">Using image ID</div>214

215 

216

217Using image ID

218 

213 Multi-turn image generation219 Multi-turn image generation

214 220 

215```javascript221```javascript


318 f.write(base64.b64decode(image_base64))324 f.write(base64.b64decode(image_base64))

319```325```

320 326 

321 </div>

322 

323 327 

324 328 

325## Streaming329## Streaming

Details

1# Local shell1# Local shell

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.

4 

3The local shell tool is outdated. For new use cases, use the5The local shell tool is outdated. For new use cases, use the

4 [`shell`](https://developers.openai.com/api/docs/guides/tools-shell) tool with GPT-5.1 instead. [Learn6 [`shell`](https://developers.openai.com/api/docs/guides/tools-shell) tool with GPT-5.1 instead. [Learn

5 more](https://developers.openai.com/api/docs/guides/tools-shell).7 more](https://developers.openai.com/api/docs/guides/tools-shell).

6 8 

7Local shell is a tool that allows agents to run shell commands locally on a machine you or the user provides. It's designed to work with [Codex CLI](https://github.com/openai/codex) and [`codex-mini-latest`](https://developers.openai.com/api/docs/models/codex-mini-latest). Commands are executed inside your own runtime, **you are fully in control of which commands actually run** —the API only returns the instructions, but does not execute them on OpenAI infrastructure.9Local shell is a tool that allows agents to run shell commands locally on a machine you or the user provides. It's designed to work with [Codex CLI](https://github.com/openai/codex) and [`codex-mini-latest`](https://developers.openai.com/api/docs/models/codex-mini-latest). Commands are executed inside your own runtime, **you are fully in control of which commands actually run** —the API only returns the instructions, but does not execute them on OpenAI infrastructure.

8 10 

9Local shell is available through the [Responses API](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions) for use with [`codex-mini-latest`](https://developers.openai.com/api/docs/models/codex-mini-latest). It is not available on other models, or via the Chat Completions API.11Local shell is available through the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) for use with [`codex-mini-latest`](https://developers.openai.com/api/docs/models/codex-mini-latest). It is not available on other models, or via the Chat Completions API.

10 12 

11Running arbitrary shell commands can be dangerous. Always sandbox execution13Running arbitrary shell commands can be dangerous. Always sandbox execution

12or add strict allow- / deny-lists before forwarding a command to the system14or add strict allow- / deny-lists before forwarding a command to the system

13shell.15shell.

14<br />16 

17 

15 18 

16See [Codex CLI](https://github.com/openai/codex) for reference implementation.19See [Codex CLI](https://github.com/openai/codex) for reference implementation.

17 20 

Details

1# Programmatic Tool Calling1# Programmatic Tool Calling

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.

4 

3Programmatic Tool Calling lets a model write and run JavaScript that coordinates the tools in a Responses API request. A program can call tools in parallel, use loops and conditions, and keep intermediate results in the hosted runtime. This is useful when a task needs a sequence of related tool calls or needs to process large tool outputs before returning a result.5Programmatic Tool Calling lets a model write and run JavaScript that coordinates the tools in a Responses API request. A program can call tools in parallel, use loops and conditions, and keep intermediate results in the hosted runtime. This is useful when a task needs a sequence of related tool calls or needs to process large tool outputs before returning a result.

4 6 

5Your application decides whether Programmatic Tool Calling is available and which eligible tools the model can call directly, from a program, or either way. It continues to run any client-owned tool calls.7Your application decides whether Programmatic Tool Calling is available and which eligible tools the model can call directly, from a program, or either way. It continues to run any client-owned tool calls.

Details

1# Shell1# Shell

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.

4 

3The shell tool gives models the ability to work inside a complete terminal environment. We support shell for local execution and for hosted execution through the Responses API.5The shell tool gives models the ability to work inside a complete terminal environment. We support shell for local execution and for hosted execution through the Responses API.

4 6 

5The shell tool lets models run commands through either:7The shell tool lets models run commands through either:


7- Hosted shell containers managed by OpenAI.9- Hosted shell containers managed by OpenAI.

8- [A local shell runtime](#local-shell-mode) that you host and execute yourself.10- [A local shell runtime](#local-shell-mode) that you host and execute yourself.

9 11 

10Shell is available through the [Responses API](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions). It's not available via the Chat Completions API.12Shell is available through the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses). It's not available via the Chat Completions API.

11 13 

12Running arbitrary shell commands can be dangerous. Always sandbox execution,14Running arbitrary shell commands can be dangerous. Always sandbox execution,

13 apply allowlists or denylists where possible, and log tool activity for15 apply allowlists or denylists where possible, and log tool activity for


1143 1145 

1144You can find working examples in the SDK repositories.1146You can find working examples in the SDK repositories.

1145 1147 

1146<a href="https://github.com/openai/openai-agents-js/blob/main/examples/tools/shell.ts" target="_blank" rel="noreferrer">1148[Shell tool example - TypeScript

1147

1148 

1149<span slot="icon">

1150 </span>

1151 TypeScript example for the shell tool in the Agents SDK.

1152 1149 

1153 1150 

1154</a>

1155 1151 

1156<a href="https://github.com/openai/openai-agents-python/blob/main/examples/tools/shell.py" target="_blank" rel="noreferrer">1152 TypeScript example for the shell tool in the Agents SDK.](https://github.com/openai/openai-agents-js/blob/main/examples/tools/shell.ts)

1157 1153 

1154[Shell tool example - Python

1158 1155 

1159<span slot="icon">

1160 </span>

1161 Python example for the shell tool in the Agents SDK.

1162 1156 

1163 1157 

1164</a>1158 Python example for the shell tool in the Agents SDK.](https://github.com/openai/openai-agents-python/blob/main/examples/tools/shell.py)

1165 1159 

1166## Handling common errors1160## Handling common errors

1167 1161 

Details

1# Skills1# Skills

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.

4 

3Agent Skills let you upload and reuse versioned bundles of files in hosted and local shell environments.5Agent Skills let you upload and reuse versioned bundles of files in hosted and local shell environments.

4 6 

5We support Skills in two form factors: local execution and hosted,7We support Skills in two form factors: local execution and hosted,

Details

1# Trace grading1# Trace grading

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.

4 

3Trace grading is the process of assigning structured scores or labels to an agent's trace—the end-to-end log of decisions, tool calls, and reasoning steps—to assess correctness, quality, or adherence to expectations. These annotations help identify where the agent did well or made mistakes, enabling targeted improvements in orchestration or behavior.5Trace grading is the process of assigning structured scores or labels to an agent's trace—the end-to-end log of decisions, tool calls, and reasoning steps—to assess correctness, quality, or adherence to expectations. These annotations help identify where the agent did well or made mistakes, enabling targeted improvements in orchestration or behavior.

4 6 

5Trace evals use those graded traces to systematically evaluate agent performance across many examples, helping to benchmark changes, identify regressions, or validate improvements. Unlike black-box evaluations, trace evals provide more data to better understand why an agent succeeds or fails.7Trace evals use those graded traces to systematically evaluate agent performance across many examples, helping to benchmark changes, identify regressions, or validate improvements. Unlike black-box evaluations, trace evals provide more data to better understand why an agent succeeds or fails.

guides/transcription.md +92 −0 created

Details

1# Transcription

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 

5Transcription converts speech into text. Choose a workflow based on whether your audio is already recorded or is arriving live. Each workflow has one recommended starting model.

6 

7## Choose a transcription workflow

8 

9<table>

10 <thead>

11 <tr>

12 <th>Workflow</th>

13 <th>Use when</th>

14 <th>Recommended model</th>

15 </tr>

16 </thead>

17 <tbody>

18 <tr>

19 <td>

20 [File transcription](https://developers.openai.com/api/docs/guides/speech-to-text)

21 </td>

22 <td>

23 You have a completed recording or a bounded audio request. Upload the

24 file and receive a final transcript, or stream text while the file is

25 processed.

26 </td>

27 <td>

28 [`gpt-transcribe`](https://developers.openai.com/api/docs/models/gpt-transcribe)

29 </td>

30 </tr>

31 <tr>

32 <td>

33 [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription)

34 </td>

35 <td>

36 You have a microphone, call, or other live audio stream and need text as

37 speech arrives.

38 </td>

39 <td>

40 [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe)

41 </td>

42 </tr>

43 </tbody>

44</table>

45 

46Streaming output and live audio are separate decisions. You can stream the transcription of a completed file without opening a Realtime session. Use Realtime only when your audio is arriving live or you need a persistent connection.

47 

48## Choose a specialized capability

49 

50Start with the recommended model for your workflow. Switch models only when your application requires a capability that the default doesn't provide.

51 

52| If you need | Use |

53| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |

54| Speaker-labeled transcripts | `gpt-4o-transcribe-diarize` with [file transcription](https://developers.openai.com/api/docs/guides/speech-to-text#speaker-diarization). |

55| Word timestamps or `srt` and `vtt` subtitles | `whisper-1` with [file transcription](https://developers.openai.com/api/docs/guides/speech-to-text#timestamps). |

56| Translation of a completed recording into English | `whisper-1` with the [audio translations endpoint](https://developers.openai.com/api/docs/guides/speech-to-text#translations). |

57| Detected input languages | `gpt-transcribe` with [file transcription](https://developers.openai.com/api/docs/guides/speech-to-text). |

58| Committed-turn transcription over WebSocket | `gpt-transcribe` with [realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription#transcribe-a-committed-turn). |

59 

60Existing integrations can continue to use [`gpt-4o-transcribe`](https://developers.openai.com/api/docs/models/gpt-4o-transcribe), [`gpt-4o-mini-transcribe`](https://developers.openai.com/api/docs/models/gpt-4o-mini-transcribe), or [`gpt-realtime-whisper`](https://developers.openai.com/api/docs/models/gpt-realtime-whisper) where supported. These aren't the recommended starting models for a new transcription integration.

61 

62See [transcription pricing](https://developers.openai.com/api/docs/pricing#transcription-and-speech) and test the recommended path with representative audio before moving production traffic.

63 

64## Improve transcription quality

65 

66`gpt-transcribe` and `gpt-live-transcribe` accept three kinds of context:

67 

68- `prompt`: Free-form context about the recording, such as its topic or setting.

69- `keywords`: Literal terms that may appear in the audio, such as product names, medications, or acronyms.

70- `languages`: A list of expected input languages when the recording may contain more than one language.

71 

72Use these inputs only for context relevant to the audio; don't restate the transcription task. Keywords are hints, not required output. The transcript should include a keyword only when the audio contains it.

73 

74These models use `languages` instead of the singular `language` field. Existing transcription models that accept one language hint continue to use `language`.

75 

76When `gpt-transcribe` performs input transcription in a Realtime API session or runs in a dedicated transcription session, it automatically uses earlier transcribed turns as context.

77 

78## Test with representative audio

79 

80Test transcription under the audio conditions your application will encounter. Include:

81 

82- Target languages, accents, and code-switching patterns.

83- Background noise, microphone quality, and telephony audio.

84- Names, numbers, dates, alphanumeric strings, and domain terminology.

85- Short utterances, long recordings, and interrupted speech.

86 

87Track errors that matter to the application instead of relying only on word error rate. For example, test medication names in a healthcare workflow or order numbers in a support workflow.

88 

89## Next steps

90 

91- [File transcription](https://developers.openai.com/api/docs/guides/speech-to-text).

92- [Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription).

Details

1# Upgrading to GPT-5.41# Upgrading to GPT-5.4

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.

4 

3# Upgrading to GPT-5.45# Upgrading to GPT-5.4

4 6 

5Use this guide when the user explicitly asks to upgrade an existing integration to GPT-5.4. Pair it with current OpenAI docs lookups. The default target string is `gpt-5.4`.7Use this guide when the user explicitly asks to upgrade an existing integration to GPT-5.4. Pair it with current OpenAI docs lookups. The default target string is `gpt-5.4`.

Details

1# Upgrading to GPT-5.51# Upgrading to GPT-5.5

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.

4 

3# Upgrading to GPT-5.55# Upgrading to GPT-5.5

4 6 

5Use this guide when the user explicitly asks to upgrade an existing integration to GPT-5.5. Pair it with current OpenAI docs lookups. The default target string is `gpt-5.5`.7Use this guide when the user explicitly asks to upgrade an existing integration to GPT-5.5. Pair it with current OpenAI docs lookups. The default target string is `gpt-5.5`.

Details

1# Upgrading to GPT-5.6 Sol1# Upgrading to GPT-5.6 Sol

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.

4 

3# Upgrading to GPT-5.6 Sol5# Upgrading to GPT-5.6 Sol

4 6 

5Use this guide when the user asks to migrate an existing OpenAI API integration, repository, prompt stack, agent, model router, or model picker to GPT-5.6 Sol or the GPT-5.6 family.7Use this guide when the user asks to migrate an existing OpenAI API integration, repository, prompt stack, agent, model router, or model picker to GPT-5.6 Sol or the GPT-5.6 family.

Details

1# Video generation with Sora1# Video generation with Sora

2 2 

3<div className="mt-6 mb-8">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 </div>

5 4 

6## Overview5## Overview

7 6 

Details

1# Vision fine-tuning1# Vision fine-tuning

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.

4 

3Vision fine-tuning uses image inputs for [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning) to improve the model's understanding of image inputs. This guide will take you through this subset of SFT, and outline some of the important considerations for fine-tuning with image inputs.5Vision fine-tuning uses image inputs for [supervised fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning) to improve the model's understanding of image inputs. This guide will take you through this subset of SFT, and outline some of the important considerations for fine-tuning with image inputs.

4 6 

5OpenAI is winding down the fine-tuning platform. The platform is no longer7OpenAI is winding down the fine-tuning platform. The platform is no longer

6 accessible to new users, but existing users of the fine-tuning platform will8 accessible to new users, but existing users of the fine-tuning platform will

7 be able to create training jobs for the coming months.9 be able to create training jobs for the coming months.

8 <br />10

11 

9 All fine-tuned models will remain available for inference until their base12 All fine-tuned models will remain available for inference until their base

10 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is13 models are [deprecated](https://developers.openai.com/api/docs/deprecations). The full timeline is

11 [here](https://developers.openai.com/api/docs/deprecations).14 [here](https://developers.openai.com/api/docs/deprecations).

12 15 

13<br />16 

17 

14 18 

15<table>19<table>

16<tbody>20<tbody>


37 41 

38## Data format42## Data format

39 43 

40Just as you can [send one or many image inputs and create model responses based on them](https://developers.openai.com/api/docs/guides/vision), you can include those same message types within your JSONL training data files. Images can be provided either as HTTP URLs or data URLs containing Base64-encoded images.44Just as you can [send one or many image inputs and create model responses based on them](https://developers.openai.com/api/docs/guides/images-vision), you can include those same message types within your JSONL training data files. Images can be provided either as HTTP URLs or data URLs containing Base64-encoded images.

41 45 

42Here's an example of an image message on a line of your JSONL file. Below, the JSON object is expanded for readability, but typically this JSON would appear on a single line in your data file:46Here's an example of an image message on a line of your JSONL file. Below, the JSON object is expanded for readability, but typically this JSON would appear on a single line in your data file:

43 47 


115 119 

116#### Reducing training cost120#### Reducing training cost

117 121 

118If you set the `detail` parameter for an image to `low`, the image is resized to 512 by 512 pixels and is only represented by 85 tokens regardless of its size. This will reduce the cost of training. [See here for more information.](https://developers.openai.com/api/docs/guides/vision#low-or-high-fidelity-image-understanding)122If you set the `detail` parameter for an image to `low`, the image is resized to 512 by 512 pixels and is only represented by 85 tokens regardless of its size. This will reduce the cost of training. [See here for more information.](https://developers.openai.com/api/docs/guides/images-vision#low-or-high-fidelity-image-understanding)

119 123 

120```json124```json

121{125{


129 133 

130#### Control image quality134#### Control image quality

131 135 

132To control the fidelity of image understanding, set the `detail` parameter of `image_url` to `low`, `high`, or `auto` for each image. This will also affect the number of tokens per image that the model sees during training time, and will affect the cost of training. [See here for more information](https://developers.openai.com/api/docs/guides/vision#low-or-high-fidelity-image-understanding).136To control the fidelity of image understanding, set the `detail` parameter of `image_url` to `low`, `high`, or `auto` for each image. This will also affect the number of tokens per image that the model sees during training time, and will affect the cost of training. [See here for more information](https://developers.openai.com/api/docs/guides/images-vision#low-or-high-fidelity-image-understanding).

133 137 

134## Safety checks138## Safety checks

135 139 


167 171 

168Now that you know the basics of vision fine-tuning, explore these other methods as well.172Now that you know the basics of vision fine-tuning, explore these other methods as well.

169 173 

170[174[Supervised fine-tuning

175 

176 

177 

178 Fine-tune a model by providing correct outputs for sample inputs.](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

171 179 

172<span slot="icon">180[Direct preference optimization

173 </span>

174 Fine-tune a model by providing correct outputs for sample inputs.

175 181 

176](https://developers.openai.com/api/docs/guides/supervised-fine-tuning)

177 182 

178[

179 183 

180<span slot="icon">184 Fine-tune a model using direct preference optimization (DPO).](https://developers.openai.com/api/docs/guides/direct-preference-optimization)

181 </span>

182 Fine-tune a model using direct preference optimization (DPO).

183 185 

184](https://developers.openai.com/api/docs/guides/direct-preference-optimization)186[Reinforcement fine-tuning

185 187 

186[

187 188 

188<span slot="icon">

189 </span>

190 Fine-tune a reasoning model by grading its outputs.

191 189 

192](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

190 Fine-tune a reasoning model by grading its outputs.](https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning)

Details

1# Voice agents1# Voice agents

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.

4 

3Voice agents turn the same agent concepts into spoken, low-latency interactions. The key design choice is deciding whether the model should work directly with live audio or whether your application should explicitly chain speech-to-text, text reasoning, and text-to-speech.5Voice agents turn the same agent concepts into spoken, low-latency interactions. The key design choice is deciding whether the model should work directly with live audio or whether your application should explicitly chain speech-to-text, text reasoning, and text-to-speech.

4 6 

5## Choose the right architecture7## Choose the right architecture


18- In TypeScript, the fastest path to a browser-based voice assistant is a `RealtimeAgent` and `RealtimeSession`.20- In TypeScript, the fastest path to a browser-based voice assistant is a `RealtimeAgent` and `RealtimeSession`.

19- In Python, the simplest path to extending an existing text agent into voice is a chained `VoicePipeline`.21- In Python, the simplest path to extending an existing text agent into voice is a chained `VoicePipeline`.

20 22 

21<span id="speech-to-speech-realtime-architecture"></span>23 

24 

25 

22 26 

23## Build a speech-to-speech voice agent27## Build a speech-to-speech voice agent

24 28 


123 127 

124## Next steps128## Next steps

125 129 

126<a href="/api/docs/guides/realtime">130[Realtime and audio overview

127

128 

129<span slot="icon">

130 </span>

131 Choose the right realtime or audio guide for your use case.

132 

133 

134</a>

135 131 

136<a href="/api/docs/guides/realtime-conversations">

137 132 

138 133 

139<span slot="icon">134 Choose the right realtime or audio guide for your use case.](https://developers.openai.com/api/docs/guides/realtime)

140 </span>

141 Work with the Realtime session lifecycle and event model.

142 135 

136[Managing conversations

143 137 

144</a>

145 138 

146<a href="/api/docs/guides/realtime-webrtc">

147 139 

140 Work with the Realtime session lifecycle and event model.](https://developers.openai.com/api/docs/guides/realtime-conversations)

148 141 

149<span slot="icon">142[WebRTC connection

150 </span>

151 Connect browser and mobile audio directly to a Realtime session.

152 143 

153 144 

154</a>

155 145 

156<a href="/api/docs/guides/realtime-models-prompting">146 Connect browser and mobile audio directly to a Realtime session.](https://developers.openai.com/api/docs/guides/realtime-webrtc)

157 147 

148[Realtime prompting guide

158 149 

159<span slot="icon">

160 </span>

161 Tune reasoning, preambles, tools, entity capture, and voice behavior.

162 150 

163 151 

164</a>152 Tune reasoning, preambles, tools, entity capture, and voice behavior.](https://developers.openai.com/api/docs/guides/realtime-models-prompting)

Details

1# Webhooks1# Webhooks

2 2 

3OpenAI [webhooks](http://chatgpt.com/?q=eli5+what+is+a+webhook?) allow you to receive real-time notifications about events in the API, such as when a batch completes, a background response is generated, or a fine-tuning job finishes. Webhooks are delivered to an HTTP endpoint you control, following the [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md). The full list of webhook events can be found in the [API reference](https://developers.openai.com/api/docs/api-reference/webhook-events).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 

5[5OpenAI [webhooks](http://chatgpt.com/?q=eli5+what+is+a+webhook?) allow you to receive real-time notifications about events in the API, such as when a batch completes, a background response is generated, or a fine-tuning job finishes. Webhooks are delivered to an HTTP endpoint you control, following the [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md). The full list of webhook events can be found in the [API reference](https://developers.openai.com/api/reference/resources/webhooks).

6 6 

7<span slot="icon">7[API reference for webhook events

8 </span>

9 View the full list of webhook events.

10 8 

11](https://developers.openai.com/api/docs/api-reference/webhook-events)

12 9 

13Below are examples of simple servers capable of ingesting webhooks from OpenAI, specifically for the [`response.completed`](https://developers.openai.com/api/docs/api-reference/webhook-events/response/completed) event.10 

11 View the full list of webhook events.](https://developers.openai.com/api/reference/resources/webhooks)

12 

13Below are examples of simple servers capable of ingesting webhooks from OpenAI, specifically for the [`response.completed`](https://developers.openai.com/api/reference/resources/webhooks) event.

14 14 

15Webhooks server15Webhooks server

16 16 

Details

1# WebSocket Mode1# WebSocket Mode

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.

4 

3The Responses API supports a WebSocket mode for long-running, tool-call-heavy workflows. In this mode, you keep a persistent connection to `/v1/responses` and continue each turn by sending only new input items plus `previous_response_id`.5The Responses API supports a WebSocket mode for long-running, tool-call-heavy workflows. In this mode, you keep a persistent connection to `/v1/responses` and continue each turn by sending only new input items plus `previous_response_id`.

4 6 

5WebSocket mode is compatible with both Zero Data Retention (ZDR) and `store=false`.7WebSocket mode is compatible with both Zero Data Retention (ZDR) and `store=false`.


105 107 

106### Standalone `/responses/compact`108### Standalone `/responses/compact`

107 109 

108The standalone [`/responses/compact` endpoint](https://developers.openai.com/api/docs/api-reference/responses/compact) returns a new compacted input window, not a response ID. After compaction, create a new response on your WebSocket connection using the compacted window as `input` (plus the next user/tool items).110The standalone [`/responses/compact` endpoint](https://developers.openai.com/api/reference/resources/responses/methods/compact) returns a new compacted input window, not a response ID. After compaction, create a new response on your WebSocket connection using the compacted window as `input` (plus the next user/tool items).

109 111 

110Start a new chain by omitting `previous_response_id` or setting it to `null`. Pass the compacted output as-is; do not prune the returned window.112Start a new chain by omitting `previous_response_id` or setting it to `null`. Pass the compacted output as-is; do not prune the returned window.

111 113 


187 189 

188- [Conversation state](https://developers.openai.com/api/docs/guides/conversation-state)190- [Conversation state](https://developers.openai.com/api/docs/guides/conversation-state)

189- [Streaming API responses](https://developers.openai.com/api/docs/guides/streaming-responses)191- [Streaming API responses](https://developers.openai.com/api/docs/guides/streaming-responses)

190- [Responses streaming events reference](https://developers.openai.com/api/docs/api-reference/responses-streaming)192- [Responses streaming events reference](https://developers.openai.com/api/reference/resources/responses)

Details

1# Workload identity federation1# Workload identity federation

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.

4 

3Workload identity federation lets trusted workloads exchange externally issued identity tokens for short-lived OpenAI access tokens. Use these guides to configure your external identity provider, create OpenAI service account mappings, and authenticate workloads without storing long-lived API keys.5Workload identity federation lets trusted workloads exchange externally issued identity tokens for short-lived OpenAI access tokens. Use these guides to configure your external identity provider, create OpenAI service account mappings, and authenticate workloads without storing long-lived API keys.

4 6 

5For token exchange request and response details, authorization behavior, and current limitations, see the [workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation).7For token exchange request and response details, authorization behavior, and current limitations, see the [workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation).


19 21 

20Start with the guide that matches where your workload runs:22Start with the guide that matches where your workload runs:

21 23 

22<div className="my-4 w-full max-w-full overflow-hidden">24 

23 </div>25 

26 - **[Kubernetes](https://developers.openai.com/api/docs/guides/workload-identity-federation/kubernetes)**: Use projected service account tokens in self-managed clusters.

27- **[AWS](https://developers.openai.com/api/docs/guides/workload-identity-federation/aws)**: Use outbound identity federation or Amazon EKS projected tokens.

28- **[Microsoft Azure](https://developers.openai.com/api/docs/guides/workload-identity-federation/microsoft-azure)**: Use managed identity tokens or AKS projected service account tokens.

29- **[Google Cloud](https://developers.openai.com/api/docs/guides/workload-identity-federation/google-cloud)**: Use metadata server identity tokens or GKE projected service account tokens.

30- **[Oracle Cloud Infrastructure](https://developers.openai.com/api/docs/guides/workload-identity-federation/oracle-cloud)**: Use instance principal tokens from an Oracle identity domain.

31- **[GitHub Actions](https://developers.openai.com/api/docs/guides/workload-identity-federation/github-actions)**: Use OIDC tokens in continuous integration workflows.

32- **[SPIFFE](https://developers.openai.com/api/docs/guides/workload-identity-federation/spiffe)**: Use SPIFFE JWT-SVIDs issued by SPIRE or a compatible provider.

33 

34 

24 35 

25OpenAI supports OIDC-compatible JWT subject tokens in the documented configurations, including SPIFFE JWT-SVIDs. If you need an OIDC provider that isn't listed, contact us.36OpenAI supports OIDC-compatible JWT subject tokens in the documented configurations, including SPIFFE JWT-SVIDs. If you need an OIDC provider that isn't listed, contact us.

26 37 

Details

1# Configuring workload identity federation for AWS1# Configuring workload identity federation for AWS

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.

4 

3Use AWS as a Workload Identity Provider in either of these scenarios:5Use AWS as a Workload Identity Provider in either of these scenarios:

4 6 

5- **AWS outbound identity federation:** Exchange an AWS STS-issued OIDC JWT from `GetWebIdentityToken` for a short-lived OpenAI access token.7- **AWS outbound identity federation:** Exchange an AWS STS-issued OIDC JWT from `GetWebIdentityToken` for a short-lived OpenAI access token.


12 14 

13 15 

14 16 

15<div data-content-switcher-pane data-value="outbound">

16 

17## AWS outbound identity federation17## AWS outbound identity federation

18 18 

19AWS outbound identity federation lets an AWS principal request a signed OIDC JWT from AWS STS and present that token to an external service. In OpenAI workload identity federation, the AWS-issued JWT is the subject token that OpenAI validates before issuing an OpenAI access token.19AWS outbound identity federation lets an AWS principal request a signed OIDC JWT from AWS STS and present that token to an external service. In OpenAI workload identity federation, the AWS-issued JWT is the subject token that OpenAI validates before issuing an OpenAI access token.


500```500```

501 501 

502 502 

503 </div>

504 503

505 <div data-content-switcher-pane data-value="eks" hidden>504 

505 

506

507 

506 508 

507## Amazon EKS projected service account tokens509## Amazon EKS projected service account tokens

508 510 


933```935```

934 936 

935 937 

936 </div>

937 

938 

939 938 

940## AWS best practices939## AWS best practices

941 940 

Details

1# Configuring workload identity federation for GitHub Actions1# Configuring workload identity federation for GitHub Actions

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.

4 

3Use GitHub Actions as a Workload Identity Provider by exchanging a GitHub-issued OIDC token for a short-lived OpenAI access token. This lets workflows authenticate to the OpenAI API without storing a long-lived API key in GitHub secrets.5Use GitHub Actions as a Workload Identity Provider by exchanging a GitHub-issued OIDC token for a short-lived OpenAI access token. This lets workflows authenticate to the OpenAI API without storing a long-lived API key in GitHub secrets.

4 6 

5GitHub can mint a signed OIDC JWT for a workflow job that has `id-token: write` permission and requests an identity token. OpenAI validates the token issuer, audience, signature, and mapping attributes before issuing an OpenAI access token.7GitHub can mint a signed OIDC JWT for a workflow job that has `id-token: write` permission and requests an identity token. OpenAI validates the token issuer, audience, signature, and mapping attributes before issuing an OpenAI access token.


101 103 

1022. **Add exact claim assertions.** Add one **Key** and **Value** row for each GitHub claim that must match. OpenAI requires every configured row to match before it issues an access token. For a production deploy workflow, use assertions like:1042. **Add exact claim assertions.** Add one **Key** and **Value** row for each GitHub claim that must match. OpenAI requires every configured row to match before it issues an access token. For a production deploy workflow, use assertions like:

103 105 

104 ```text106```text

105 iss == "https://token.actions.githubusercontent.com"107 iss == "https://token.actions.githubusercontent.com"

106 aud == "https://api.openai.com/v1"108 aud == "https://api.openai.com/v1"

107 repository == "my-org/my-repo"109 repository == "my-org/my-repo"

108 ref == "refs/heads/main"110 ref == "refs/heads/main"

109 workflow_ref == "my-org/my-repo/.github/workflows/deploy.yml@refs/heads/main"111 workflow_ref == "my-org/my-repo/.github/workflows/deploy.yml@refs/heads/main"

110 ```112```

111 113 

112 Prefer `workflow_ref` over `workflow` for privileged mappings because admins usually intend to trust a specific workflow file path and ref. Workflow names can be renamed, and multiple workflow files can share the same name.114 Prefer `workflow_ref` over `workflow` for privileged mappings because admins usually intend to trust a specific workflow file path and ref. Workflow names can be renamed, and multiple workflow files can share the same name.

113 115 

Details

1# Configuring workload identity federation for Google Cloud1# Configuring workload identity federation for Google Cloud

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.

4 

3Use Google Cloud as a Workload Identity Provider in either of these scenarios:5Use Google Cloud as a Workload Identity Provider in either of these scenarios:

4 6 

5- **Google workload identity:** Exchange a Google-signed OIDC token issued to an attached Google service account for a short-lived OpenAI access token.7- **Google workload identity:** Exchange a Google-signed OIDC token issued to an attached Google service account for a short-lived OpenAI access token.


7 9 

8 10 

9 11 

10<div data-content-switcher-pane data-value="workload-identity">

11 

12## Google workload identity12## Google workload identity

13 13 

14Google Cloud workloads can request signed OIDC identity tokens from the Google metadata server without storing long-lived service account keys. In OpenAI workload identity federation, the Google identity token is the subject token that OpenAI validates before issuing an OpenAI access token. This flow works on Compute Engine, Cloud Run, GKE workloads using attached Google service accounts, and other Google-managed runtimes that expose the metadata server identity endpoint.14Google Cloud workloads can request signed OIDC identity tokens from the Google metadata server without storing long-lived service account keys. In OpenAI workload identity federation, the Google identity token is the subject token that OpenAI validates before issuing an OpenAI access token. This flow works on Compute Engine, Cloud Run, GKE workloads using attached Google service accounts, and other Google-managed runtimes that expose the metadata server identity endpoint.


521```521```

522 522 

523 523 

524 </div>

525 524

526 <div data-content-switcher-pane data-value="gke" hidden>525 

526 

527

528 

527 529 

528## Google Kubernetes Engine530## Google Kubernetes Engine

529 531 


960```962```

961 963 

962 964 

963 </div>

964 

965 

966 965 

967## Google Cloud best practices966## Google Cloud best practices

968 967 

Details

1# Configuring workload identity federation for Kubernetes1# Configuring workload identity federation for Kubernetes

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.

4 

3Use Kubernetes as a Workload Identity Provider by exchanging a projected Kubernetes service account token for a short-lived OpenAI access token.5Use Kubernetes as a Workload Identity Provider by exchanging a projected Kubernetes service account token for a short-lived OpenAI access token.

4 6 

5## Setting up Kubernetes7## Setting up Kubernetes

Details

1# Configuring workload identity federation for Microsoft Azure1# Configuring workload identity federation for Microsoft Azure

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.

4 

3Use Microsoft Azure as a Workload Identity Provider in either of these scenarios:5Use Microsoft Azure as a Workload Identity Provider in either of these scenarios:

4 6 

5- **Azure managed identity:** Exchange a Microsoft Entra ID access token issued for a managed identity for a short-lived OpenAI access token.7- **Azure managed identity:** Exchange a Microsoft Entra ID access token issued for a managed identity for a short-lived OpenAI access token.


7 9 

8 10 

9 11 

10<div data-content-switcher-pane data-value="managed-identity">

11 

12## Azure managed identity12## Azure managed identity

13 13 

14Azure managed identities let Azure-hosted workloads request Microsoft Entra tokens without storing long-lived secrets. In OpenAI workload identity federation, the managed identity token is the subject token that OpenAI validates before issuing an OpenAI access token.14Azure managed identities let Azure-hosted workloads request Microsoft Entra tokens without storing long-lived secrets. In OpenAI workload identity federation, the managed identity token is the subject token that OpenAI validates before issuing an OpenAI access token.


546```546```

547 547 

548 548 

549 </div>

550 549

551 <div data-content-switcher-pane data-value="aks" hidden>550 

551 

552

553 

552 554 

553## Azure Kubernetes Service (AKS)555## Azure Kubernetes Service (AKS)

554 556 


994```996```

995 997 

996 998 

997 </div>

998 

999 

1000 999 

1001## Microsoft Azure best practices1000## Microsoft Azure best practices

1002 1001 

Details

1# Configuring workload identity federation for Oracle Cloud Infrastructure1# Configuring workload identity federation for Oracle Cloud Infrastructure

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.

4 

3Use Oracle Cloud Infrastructure (OCI) as a Workload Identity Provider by exchanging an Oracle Identity Cloud Service (IDCS) access token for a short-lived OpenAI access token. An OCI instance principal signs a token exchange request to an identity domain in the same tenancy. OpenAI validates the resulting token and authorizes the OCI workload to act as a mapped OpenAI service account.5Use Oracle Cloud Infrastructure (OCI) as a Workload Identity Provider by exchanging an Oracle Identity Cloud Service (IDCS) access token for a short-lived OpenAI access token. An OCI instance principal signs a token exchange request to an identity domain in the same tenancy. OpenAI validates the resulting token and authorizes the OCI workload to act as a mapped OpenAI service account.

4 6 

5This setup does not require an OpenAI API key, a custom Oracle OAuth resource application, or dynamic group grants to a custom application.7This setup does not require an OpenAI API key, a custom Oracle OAuth resource application, or dynamic group grants to a custom application.

Details

1# Configuring workload identity federation for SPIFFE1# Configuring workload identity federation for SPIFFE

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.

4 

3Use SPIFFE as a Workload Identity Provider by exchanging a SPIFFE JWT-SVID for a short-lived OpenAI access token. This lets workloads authenticated by SPIRE or another SPIFFE-compatible identity provider call the OpenAI API without storing long-lived API keys.5Use SPIFFE as a Workload Identity Provider by exchanging a SPIFFE JWT-SVID for a short-lived OpenAI access token. This lets workloads authenticated by SPIRE or another SPIFFE-compatible identity provider call the OpenAI API without storing long-lived API keys.

4 6 

5OpenAI supports SPIFFE JWT-SVIDs that can be validated as JWT subject tokens with an issuer, audience, expiration, issued-at timestamp, and JWKS-backed signature. OpenAI doesn't support SPIFFE X.509-SVIDs as workload identity federation subject tokens.7OpenAI supports SPIFFE JWT-SVIDs that can be validated as JWT subject tokens with an issuer, audience, expiration, issued-at timestamp, and JWKS-backed signature. OpenAI doesn't support SPIFFE X.509-SVIDs as workload identity federation subject tokens.

Details

1# Data controls in the OpenAI platform1# Data controls in the OpenAI platform

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.

4 

3Understand how OpenAI uses your data, and how you can control it.5Understand how OpenAI uses your data, and how you can control it.

4 6 

5Your data is your data. As of March 1, 2023, data sent to the OpenAI API is not used to train or improve OpenAI models (unless you explicitly opt in to share data with us).7Your data is your data. As of March 1, 2023, data sent to the OpenAI API is not used to train or improve OpenAI models (unless you explicitly opt in to share data with us).


95- Background mode stores response data to disk for roughly 10 minutes to enable polling.97- Background mode stores response data to disk for roughly 10 minutes to enable polling.

96- Audio outputs application state is stored for 1 hour to enable [multi-turn conversations](https://developers.openai.com/api/docs/guides/audio).98- Audio outputs application state is stored for 1 hour to enable [multi-turn conversations](https://developers.openai.com/api/docs/guides/audio).

97- See [image and file inputs](#image-and-file-inputs).99- See [image and file inputs](#image-and-file-inputs).

98- MCP servers (used with the [remote MCP server tool](https://developers.openai.com/api/docs/guides/tools-remote-mcp)) are third-party services, and data sent to an MCP server is subject to their data retention policies.100- 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.

99- Hosted containers used by [Hosted Shell](https://developers.openai.com/api/docs/guides/tools-shell#hosted-shell-quickstart) and [Code Interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter) may write temporary application state to the container filesystem (backed by ephemeral block storage) while the container is active. Container data is deleted when the container expires or is explicitly deleted.101- Hosted containers used by [Hosted Shell](https://developers.openai.com/api/docs/guides/tools-shell#hosted-shell-quickstart) and [Code Interpreter](https://developers.openai.com/api/docs/guides/tools-code-interpreter) may write temporary application state to the container filesystem (backed by ephemeral block storage) while the container is active. Container data is deleted when the container expires or is explicitly deleted.

100- Prompt caching may store encrypted key/value tensors in GPU-local storage as application state. This data is stored on the local GPU machines and is not retained after the 24-hour expiration. For `gpt-5.5` and `gpt-5.5-pro`, setting `prompt_cache_retention` to `in_memory` returns an error. For GPT-5.6 models and later model families, `prompt_cache_options.ttl` controls the minimum cache lifetime, not this maximum application-state retention period. To learn more, see the [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching#prompt-cache-retention).102- Prompt caching may store encrypted key/value tensors in GPU-local storage as application state. This data is stored on the local GPU machines and is not retained after the 24-hour expiration. For `gpt-5.5` and `gpt-5.5-pro`, setting `prompt_cache_retention` to `in_memory` returns an error. For GPT-5.6 models and later model families, `prompt_cache_options.ttl` controls the minimum cache lifetime, not this maximum application-state retention period. To learn more, see the [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching#prompt-cache-retention).

101- When Zero Data Retention is not enabled for an organization, all queries use extended prompt caching for all supported models.103- When Zero Data Retention is not enabled for an organization, all queries use extended prompt caching for all supported models.


113 115 

114#### `/v1/files`116#### `/v1/files`

115 117 

116- Files can be manually deleted via the API or the dashboard, or can be automatically deleted by setting the `expires_after` parameter. See [here](https://developers.openai.com/api/docs/api-reference/files/create#files_create-expires_after) for more information.118- Files can be manually deleted via the API or the dashboard, or can be automatically deleted by setting the `expires_after` parameter. See [here](https://developers.openai.com/api/reference/resources/files/methods/create#files_create-expires_after) for more information.

117 119 

118#### `/v1/videos`120#### `/v1/videos`

119 121 

libraries.md +334 −36

Details

1# SDKs and CLI1# SDKs and CLI

2 2 

3This page covers the main ways to build with the [OpenAI API](https://developers.openai.com/api/docs/api-reference): official SDKs for application code, the OpenAI CLI for shell-native workflows, the Agents SDK for orchestration, or your own preferred HTTP client.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 

5This page covers the main ways to build with the [OpenAI API](https://developers.openai.com/api/reference/overview): official SDKs for application code, the OpenAI CLI for shell-native workflows, the Agents SDK for orchestration, or your own preferred HTTP client.

4 6 

5## Create and export an API key7## Create and export an API key

6 8 

7Before you begin, [create an API key in the dashboard](https://platform.openai.com/api-keys), which you'll use to securely [access the API](https://developers.openai.com/api/docs/api-reference/authentication). Store the key in a safe location, like a [`.zshrc` file](https://www.freecodecamp.org/news/how-do-zsh-configuration-files-work/) or another text file on your computer. Once you've generated an API key, export it as an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) in your terminal.9Before you begin, [create an API key in the dashboard](https://platform.openai.com/api-keys), which you'll use to securely [access the API](https://developers.openai.com/api/reference/overview). Store the key in a safe location, like a [`.zshrc` file](https://www.freecodecamp.org/news/how-do-zsh-configuration-files-work/) or another text file on your computer. Once you've generated an API key, export it as an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) in your terminal.

10 

8 11 

9 12 

13macOS / Linux

10 14 

11<div data-content-switcher-pane data-value="macOS">

12 <div class="hidden">macOS / Linux</div>

13 Export an environment variable on macOS or Linux systems15 Export an environment variable on macOS or Linux systems

14 16 

15```bash17```bash

16export OPENAI_API_KEY="your_api_key_here"18export OPENAI_API_KEY="your_api_key_here"

17```19```

18 20 

19 </div>21

20 <div data-content-switcher-pane data-value="windows" hidden>22 

21 <div class="hidden">Windows</div>23

24 

25

26Windows

27 

22 Export an environment variable in PowerShell28 Export an environment variable in PowerShell

23 29 

24```bash30```bash

25setx OPENAI_API_KEY "your_api_key_here"31setx OPENAI_API_KEY "your_api_key_here"

26```32```

27 33 

28 </div>

29 

30 34 

31 35 

32OpenAI SDKs are configured to automatically read your API key from the system environment.36OpenAI SDKs are configured to automatically read your API key from the system environment.


35 39 

36 40 

37 41 

38<div data-content-switcher-pane data-value="javascript">42JavaScript

39 <div class="hidden">JavaScript</div>43 

40 </div>44

41 <div data-content-switcher-pane data-value="python" hidden>45 

42 <div class="hidden">Python</div>46To use the OpenAI API in server-side JavaScript environments like Node.js, Deno, or Bun, you can use the official [OpenAI SDK for TypeScript and JavaScript](https://github.com/openai/openai-node). Get started by installing the SDK using [npm](https://www.npmjs.com/) or your preferred package manager:

43 </div>47 

44 <div data-content-switcher-pane data-value="csharp" hidden>48Install the OpenAI SDK with npm

45 <div class="hidden">.NET</div>49 

46 </div>50```bash

47 <div data-content-switcher-pane data-value="java" hidden>51npm install openai

48 <div class="hidden">Java</div>52```

49 </div>53 

50 <div data-content-switcher-pane data-value="golang" hidden>54 

51 <div class="hidden">Go</div>55With the OpenAI SDK installed, create a file called `example.mjs` and copy the example code into it:

52 </div>56 

53 <div data-content-switcher-pane data-value="ruby" hidden>57Test a basic API request

54 <div class="hidden">Ruby</div>58 

55 </div>59```javascript

56 <div data-content-switcher-pane data-value="cli" hidden>60import OpenAI from "openai";

57 <div class="hidden">CLI</div>61const client = new OpenAI();

58 </div>62 

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

64 model: "gpt-5.6",

65 input: "Write a one-sentence bedtime story about a unicorn.",

66});

67 

68console.log(response.output_text);

69```

70 

71 

72Execute the code with `node example.mjs` (or the equivalent command for Deno or Bun). In a few moments, you should see the output of your API request.

73 

74[Learn more on GitHub

75 

76 

77 

78 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-node)

79 

80 

81

82 

83

84 

85

86Python

87 

88

89 

90To use the OpenAI API in Python, you can use the official [OpenAI SDK for Python](https://github.com/openai/openai-python). Get started by installing the SDK using [pip](https://pypi.org/project/pip/):

91 

92Install the OpenAI SDK with pip

93 

94```bash

95pip install openai

96```

97 

98 

99With the OpenAI SDK installed, create a file called `example.py` and copy the example code into it:

100 

101Test a basic API request

102 

103```python

104from openai import OpenAI

105 

106client = OpenAI()

107 

108response = client.responses.create(

109 model="gpt-5.6",

110 input="Write a one-sentence bedtime story about a unicorn.",

111)

112 

113print(response.output_text)

114```

115 

116 

117Execute the code with `python example.py`. In a few moments, you should see the output of your API request.

118 

119[Learn more on GitHub

120 

121 

122 

123 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-python)

124 

125 

126

127 

128

129 

130

131.NET

132 

133

134 

135In collaboration with Microsoft, OpenAI provides an officially supported API client for C#. You can install it with the .NET CLI from [NuGet](https://www.nuget.org/).

136 

137```

138dotnet add package OpenAI

139```

140 

141A simple API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

142 

143Test a basic API request

144 

145```csharp

146using OpenAI.Responses;

147#pragma warning disable OPENAI001

148 

149string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

150ResponsesClient client = new(key);

151 

152ResponseResult response = await client.CreateResponseAsync(

153 "gpt-5.6",

154 "Say 'this is a test.'"

155);

156 

157Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");

158```

159 

160 

161

162 

163

164 

165

166Java

167 

168

169 

170OpenAI provides an API helper for the Java programming language, currently in beta. You can include the Maven dependency using the following configuration:

171 

172```xml

173<dependency>

174 <groupId>com.openai</groupId>

175 <artifactId>openai-java</artifactId>

176 <version>4.0.0</version>

177</dependency>

178```

179 

180A simple API request to [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

181 

182Test a basic API request

183 

184```java

185import com.openai.client.OpenAIClient;

186import com.openai.client.okhttp.OpenAIOkHttpClient;

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

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

189 

190public class Main {

191 public static void main(String[] args) {

192 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

193 

194 ResponseCreateParams params =

195 ResponseCreateParams.builder().input("Say this is a test").model("gpt-5.6").build();

196 

197 Response response = client.responses().create(params);

198 response.output().stream()

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

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

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

202 .forEach(outputText -> System.out.println(outputText.text()));

203 }

204}

205```

206 

207 

208To learn more about using the OpenAI API in Java, check out the GitHub repo linked below!

209 

210[Learn more on GitHub

211 

212 

213 

214 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-java)

215 

216 

217

218 

219

220 

221

222Go

223 

224

225 

226OpenAI provides an API helper for the Go programming language, currently in beta. You can import the library using the code below:

227 

228```go

229import (

230 "github.com/openai/openai-go/v3" // imported as openai

231)

232```

233 

234 

235A first API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

236 

237Test a basic API request

238 

239```go

240package main

241 

242import (

243 "context"

244 "fmt"

245 

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

247 "github.com/openai/openai-go/v3/option"

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

249)

250 

251func main() {

252 client := openai.NewClient(

253 option.WithAPIKey("My API Key"), // or set OPENAI_API_KEY in your env

254 )

255 

256 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

257 Model: "gpt-5.6",

258 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

259 })

260 if err != nil {

261 panic(err.Error())

262 }

263 

264 fmt.Println(resp.OutputText())

265}

266```

267 

268 

269To learn more about using the OpenAI API in Go, check out the GitHub repo linked below!

270 

271[Learn more on GitHub

272 

273 

274 

275 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-go)

276 

277 

278

279 

280

281 

282

283Ruby

284 

285

286 

287To use the OpenAI API in Ruby, you can use the official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby). Get started by adding the gem to your application:

288 

289Install the OpenAI SDK with Bundler

290 

291```ruby

292gem "openai"

293```

294 

295 

296With the OpenAI SDK installed, create a file called `example.rb` and copy the example code into it:

297 

298Test a basic API request

299 

300```ruby

301require "openai"

302 

303openai = OpenAI::Client.new

304 

305response = openai.responses.create(

306 model: "gpt-5.6",

307 input: "Write a one-sentence bedtime story about a unicorn."

308)

309 

310puts(response.output_text)

311```

312 

313 

314Execute the code with `ruby example.rb`. In a few moments, you should see the output of your API request.

315 

316[Learn more on GitHub

317 

318 

319 

320 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-ruby)

321 

322 

323

324 

325

326 

327

328CLI

329 

330

331 

332To call the OpenAI API directly from your terminal, install the generated `openai` command-line tool:

333 

334Install the OpenAI CLI with Homebrew

335 

336```bash

337brew install openai/tools/openai

338```

339 

340 

341Then run a basic API request from your shell:

342 

343Test a basic API request

344 

345```bash

346openai responses create \

347 --model "gpt-5.6" \

348 --input "Write a one-sentence bedtime story about a unicorn." \

349 --raw-output \

350 --transform 'output.#(type=="message").content.0.text'

351```

352 

353 

354Use the CLI for repeatable terminal workflows such as extracting structured data from files, generating images, creating speech, and composing API calls with shell tools like `jq`.

355 

356[OpenAI CLI guide

357 

358 

359 

360 Learn more about CLI workflows and command patterns.](https://developers.openai.com/api/docs/libraries/openai-cli)

59 361 

60 362 

61 363 


68If you are deciding between direct API requests and code-first orchestration,370If you are deciding between direct API requests and code-first orchestration,

69see [how the Responses API compares with the Agents SDK](https://developers.openai.com/api/docs/guides/agents#agents-sdk-vs-responses-api).371see [how the Responses API compares with the Agents SDK](https://developers.openai.com/api/docs/guides/agents#agents-sdk-vs-responses-api).

70 372 

71<a href="/api/docs/guides/agents/quickstart">373[Agents SDK quickstart

72

73 374 

74<span slot="icon">

75 </span>

76 Build your first agent with the Agents SDK.

77 375 

78 376 

79</a>377 Build your first agent with the Agents SDK.](https://developers.openai.com/api/docs/guides/agents/quickstart)

80 378 

81- [OpenAI Agents SDK for TypeScript](https://github.com/openai/openai-agents-js)379- [OpenAI Agents SDK for TypeScript](https://github.com/openai/openai-agents-js)

82- [OpenAI Agents SDK for Python](https://github.com/openai/openai-agents-python)380- [OpenAI Agents SDK for Python](https://github.com/openai/openai-agents-python)

Details

1# OpenAI CLI1# OpenAI CLI

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.

4 

3Interact with the OpenAI API directly from your terminal with the `openai` command-line tool.5Interact with the OpenAI API directly from your terminal with the `openai` command-line tool.

4 6 

5## Installation7## Installation


59| `--transform` | Extract or reshape response data with a GJSON path before printing. |61| `--transform` | Extract or reshape response data with a GJSON path before printing. |

60| `--debug` | Print request and response details to stderr. Authorization is redacted; review headers before sharing logs. |62| `--debug` | Print request and response details to stderr. Authorization is redacted; review headers before sharing logs. |

61 63 

62This guide focuses on CLI patterns. For the latest arguments and response shapes for any API family, use the live [API reference](https://developers.openai.com/api/reference).64This guide focuses on CLI patterns. For the latest arguments and response shapes for any API family, use the live [API reference](https://developers.openai.com/api/reference/overview).

63 65 

64You can also change the base URL when you need to point the CLI at another compatible endpoint, such as a deployment that supports a different model set or only a subset of the API surface.66You can also change the base URL when you need to point the CLI at another compatible endpoint, such as a deployment that supports a different model set or only a subset of the API surface.

65 67 

mcp.md +4 −6

Details

1# Building MCP servers for plugins and API integrations1# Building MCP servers for plugins and API integrations

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.

4 

3[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open protocol that's becoming the industry standard for extending AI models with additional tools and knowledge. Remote MCP servers can be used to connect models over the Internet to new data sources and capabilities.5[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open protocol that's becoming the industry standard for extending AI models with additional tools and knowledge. Remote MCP servers can be used to connect models over the Internet to new data sources and capabilities.

4 6 

5In this guide, we'll cover how to build a remote MCP server that reads data from a private data source (a [vector store](https://developers.openai.com/api/docs/guides/retrieval)) and makes it available through a plugin in ChatGPT and Codex, through ChatGPT deep research and company knowledge, and [through the API](https://developers.openai.com/api/docs/guides/deep-research).7In this guide, we'll cover how to build a remote MCP server that reads data from a private data source (a [vector store](https://developers.openai.com/api/docs/guides/retrieval)) and makes it available through a plugin in ChatGPT and Codex, through ChatGPT deep research and company knowledge, and [through the API](https://developers.openai.com/api/docs/guides/deep-research).


152 154 

153You can try this example MCP server in a [browser-based development environment](https://replit.com/). Configure the sample with your own API credentials and vector store information.155You can try this example MCP server in a [browser-based development environment](https://replit.com/). Configure the sample with your own API credentials and vector store information.

154 156 

155<a href="https://replit.com/@kwhinnery-oai/DeepResearchServer?v=1#README.md">157[Example MCP server on Replit

156

157 158 

158<span slot="icon">

159 </span>

160 Remix the server example on Replit to test live.

161 159 

162 160 

163</a>161 Remix the server example on Replit to test live.](https://replit.com/@kwhinnery-oai/DeepResearchServer?v=1#README.md)

164 162 

165A full implementation of both the `search` and `fetch` tools in FastMCP is below also for convenience.163A full implementation of both the `search` and `fetch` tools in FastMCP is below also for convenience.

166 164 

models.md +119 −0 created

Details

1# Models

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 

5> Explore models available on the OpenAI API.

6 

7If you're not sure where to start, use [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol), our flagship model for complex reasoning and coding. Choose [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra) to balance intelligence and cost, or [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna) for cost-sensitive, high-volume workloads.

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).

10 

11## Recommended models

12 

13- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): Start here for complex reasoning and coding.

14- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): Balance intelligence and cost.

15- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): Optimize cost-sensitive, high-volume workloads.

16 

17## Browse our full catalog of models

18 

19Diverse models for a variety of tasks

20 

21See [how OpenAI uses your data](/api/docs/guides/your-data.md) and review [deprecated models](/api/docs/deprecations.md).

22 

23- [babbage-002](/api/docs/models/babbage-002.md): Replacement for the GPT-3 ada and babbage base models

24- [Chat Latest](/api/docs/models/chat-latest.md): Latest Instant model used in ChatGPT

25- [ChatGPT-4o](/api/docs/models/chatgpt-4o-latest.md): GPT-4o model used in ChatGPT

26- [chatgpt-image-latest](/api/docs/models/chatgpt-image-latest.md): Previous image model used in ChatGPT.

27- [codex-mini-latest](/api/docs/models/codex-mini-latest.md): Fast reasoning model optimized for the Codex CLI

28- [computer-use-preview](/api/docs/models/computer-use-preview.md): Specialized model for computer use tool

29- [DALL·E 2](/api/docs/models/dall-e-2.md): Our first image generation model

30- [DALL·E 3](/api/docs/models/dall-e-3.md): Previous generation image generation model

31- [davinci-002](/api/docs/models/davinci-002.md): Replacement for the GPT-3 curie and davinci base models

32- [GPT Image 1](/api/docs/models/gpt-image-1.md): Our previous image generation model

33- [GPT Image 1.5](/api/docs/models/gpt-image-1.5.md): Our previous image generation model

34- [GPT Image 2](/api/docs/models/gpt-image-2.md): State-of-the-art image generation model

35- [GPT Live Transcribe](/api/docs/models/gpt-live-transcribe.md): Low-latency speech-to-text model for realtime transcription

36- [GPT Transcribe](/api/docs/models/gpt-transcribe.md): High-accuracy speech-to-text model for file and Realtime input transcription

37- [GPT-3.5 Turbo](/api/docs/models/gpt-3.5-turbo.md): Legacy GPT model for cheaper chat and non-chat tasks

38- [gpt-3.5-turbo-16k-0613](/api/docs/models/gpt-3.5-turbo-16k-0613.md): Legacy GPT model for cheaper chat and non-chat tasks

39- [gpt-3.5-turbo-instruct](/api/docs/models/gpt-3.5-turbo-instruct.md): An older model only compatible with the legacy Completions endpoint

40- [GPT-4](/api/docs/models/gpt-4.md): An older high-intelligence GPT model

41- [GPT-4 Turbo](/api/docs/models/gpt-4-turbo.md): An older high-intelligence GPT model

42- [GPT-4 Turbo Preview](/api/docs/models/gpt-4-turbo-preview.md): An older fast GPT model

43- [GPT-4.1](/api/docs/models/gpt-4.1.md): Smartest non-reasoning model

44- [GPT-4.1 mini](/api/docs/models/gpt-4.1-mini.md): Smaller, faster version of GPT-4.1

45- [GPT-4.1 nano](/api/docs/models/gpt-4.1-nano.md): Fastest, most cost-efficient version of GPT-4.1

46- [GPT-4.5 Preview](/api/docs/models/gpt-4.5-preview.md): Deprecated large model.

47- [GPT-4o](/api/docs/models/gpt-4o.md): Fast, intelligent, flexible GPT model

48- [GPT-4o Audio](/api/docs/models/gpt-4o-audio-preview.md): GPT-4o models capable of audio inputs and outputs

49- [GPT-4o mini](/api/docs/models/gpt-4o-mini.md): Fast, affordable small model for focused tasks

50- [GPT-4o mini Audio](/api/docs/models/gpt-4o-mini-audio-preview.md): Smaller model capable of audio inputs and outputs

51- [GPT-4o mini Realtime](/api/docs/models/gpt-4o-mini-realtime-preview.md): Smaller realtime model for text and audio inputs and outputs

52- [GPT-4o mini Search Preview](/api/docs/models/gpt-4o-mini-search-preview.md): Fast, affordable small model for web search

53- [GPT-4o mini Transcribe](/api/docs/models/gpt-4o-mini-transcribe.md): Speech-to-text model powered by GPT-4o mini

54- [GPT-4o mini TTS](/api/docs/models/gpt-4o-mini-tts.md): Text-to-speech model powered by GPT-4o mini

55- [GPT-4o Realtime](/api/docs/models/gpt-4o-realtime-preview.md): Model capable of realtime text and audio inputs and outputs

56- [GPT-4o Search Preview](/api/docs/models/gpt-4o-search-preview.md): GPT model for web search in Chat Completions

57- [GPT-4o Transcribe](/api/docs/models/gpt-4o-transcribe.md): Speech-to-text model powered by GPT-4o

58- [GPT-4o Transcribe Diarize](/api/docs/models/gpt-4o-transcribe-diarize.md): Transcription model that identifies who's speaking when

59- [GPT-5](/api/docs/models/gpt-5.md): Previous intelligent reasoning model for coding and agentic tasks with configurable reasoning effort

60- [GPT-5 Chat](/api/docs/models/gpt-5-chat-latest.md): GPT-5 model used in ChatGPT

61- [GPT-5 mini](/api/docs/models/gpt-5-mini.md): Near-frontier intelligence for cost sensitive, low latency, high volume workloads

62- [GPT-5 nano](/api/docs/models/gpt-5-nano.md): Fastest, most cost-efficient version of GPT-5

63- [GPT-5 Pro](/api/docs/models/gpt-5-pro.md): Version of GPT-5 that produces smarter and more precise responses

64- [GPT-5-Codex](/api/docs/models/gpt-5-codex.md): A version of GPT-5 optimized for agentic coding in Codex

65- [GPT-5.1](/api/docs/models/gpt-5.1.md): The best model for coding and agentic tasks with configurable reasoning effort

66- [GPT-5.1 Chat](/api/docs/models/gpt-5.1-chat-latest.md): GPT-5.1 model used in ChatGPT

67- [GPT-5.1-Codex](/api/docs/models/gpt-5.1-codex.md): A version of GPT-5.1 optimized for agentic coding in Codex.

68- [GPT-5.1-Codex mini](/api/docs/models/gpt-5.1-codex-mini.md): Smaller, more cost-effective, less-capable version of GPT-5.1-Codex

69- [GPT-5.1-Codex-Max](/api/docs/models/gpt-5.1-codex-max.md): A version of GPT-5.1-codex optimized for long running tasks.

70- [GPT-5.2](/api/docs/models/gpt-5.2.md): Previous frontier model for professional work with configurable reasoning effort

71- [GPT-5.2 Chat](/api/docs/models/gpt-5.2-chat-latest.md): GPT-5.2 model used in ChatGPT

72- [GPT-5.2 Pro](/api/docs/models/gpt-5.2-pro.md): Previous pro model for professional work that produces smarter and more precise responses.

73- [GPT-5.2-Codex](/api/docs/models/gpt-5.2-codex.md): Our most intelligent coding model optimized for long-horizon, agentic coding tasks.

74- [GPT-5.3 Chat](/api/docs/models/gpt-5.3-chat-latest.md): GPT-5.3 Instant model used in ChatGPT

75- [GPT-5.3-Codex](/api/docs/models/gpt-5.3-codex.md): The most capable agentic coding model to date.

76- [GPT-5.4](/api/docs/models/gpt-5.4.md): A more affordable model for coding and professional work.

77- [GPT-5.4 mini](/api/docs/models/gpt-5.4-mini.md): Our strongest mini model yet for coding, computer use, and subagents

78- [GPT-5.4 nano](/api/docs/models/gpt-5.4-nano.md): Our cheapest GPT-5.4-class model for simple high-volume tasks

79- [GPT-5.4 Pro](/api/docs/models/gpt-5.4-pro.md): Version of GPT-5.4 that produces smarter and more precise responses.

80- [GPT-5.5](/api/docs/models/gpt-5.5.md): A new class of intelligence for coding and professional work.

81- [GPT-5.5 Pro](/api/docs/models/gpt-5.5-pro.md): Version of GPT-5.5 that produces smarter and more precise responses.

82- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): GPT-5.6 model optimized for cost-sensitive workloads

83- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): Frontier model for complex professional work

84- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost

85- [gpt-audio](/api/docs/models/gpt-audio.md): For audio inputs and outputs with Chat Completions API

86- [gpt-audio-1.5](/api/docs/models/gpt-audio-1.5.md): The best voice model for audio in, audio out with Chat Completions.

87- [gpt-audio-mini](/api/docs/models/gpt-audio-mini.md): A cost-efficient version of GPT Audio

88- [gpt-image-1-mini](/api/docs/models/gpt-image-1-mini.md): A cost-efficient version of GPT Image 1

89- [gpt-oss-120b](/api/docs/models/gpt-oss-120b.md): Most powerful open-weight model, fits into an H100 GPU

90- [gpt-oss-20b](/api/docs/models/gpt-oss-20b.md): Medium-sized open-weight model for low latency

91- [GPT-Realtime](/api/docs/models/gpt-realtime.md): Model capable of realtime text and audio inputs and outputs

92- [GPT-Realtime mini](/api/docs/models/gpt-realtime-mini.md): A cost-efficient version of GPT-Realtime

93- [GPT-Realtime-1.5](/api/docs/models/gpt-realtime-1.5.md): The best voice model for audio in, audio out

94- [GPT-Realtime-2](/api/docs/models/gpt-realtime-2.md): Reasoning model with tool use

95- [GPT-Realtime-2.1](/api/docs/models/gpt-realtime-2.1.md): Reasoning model with tool use

96- [GPT-Realtime-2.1 mini](/api/docs/models/gpt-realtime-2.1-mini.md): Reasoning model with tool use

97- [GPT-Realtime-Translate](/api/docs/models/gpt-realtime-translate.md): Streaming speech-to-speech translation model

98- [GPT-Realtime-Whisper](/api/docs/models/gpt-realtime-whisper.md): Streaming speech-to-text model for realtime transcription

99- [o1](/api/docs/models/o1.md): Previous full o-series reasoning model

100- [o1 Preview](/api/docs/models/o1-preview.md): Preview of our first o-series reasoning model

101- [o1-mini](/api/docs/models/o1-mini.md): A small model alternative to o1

102- [o1-pro](/api/docs/models/o1-pro.md): Version of o1 with more compute for better responses

103- [o3](/api/docs/models/o3.md): Reasoning model for complex tasks, succeeded by GPT-5

104- [o3-deep-research](/api/docs/models/o3-deep-research.md): Our most powerful deep research model

105- [o3-mini](/api/docs/models/o3-mini.md): A small model alternative to o3

106- [o3-pro](/api/docs/models/o3-pro.md): Version of o3 with more compute for better responses

107- [o4-mini](/api/docs/models/o4-mini.md): Fast, cost-efficient reasoning model, succeeded by GPT-5 mini

108- [o4-mini-deep-research](/api/docs/models/o4-mini-deep-research.md): Faster, more affordable deep research model

109- [omni-moderation](/api/docs/models/omni-moderation-latest.md): Identify potentially harmful content in text and images

110- [Sora 2](/api/docs/models/sora-2.md): Flagship video generation with synced audio

111- [Sora 2 Pro](/api/docs/models/sora-2-pro.md): Most advanced synced-audio video generation

112- [text-embedding-3-large](/api/docs/models/text-embedding-3-large.md): Most capable embedding model

113- [text-embedding-3-small](/api/docs/models/text-embedding-3-small.md): Small embedding model

114- [text-embedding-ada-002](/api/docs/models/text-embedding-ada-002.md): Older embedding model

115- [text-moderation](/api/docs/models/text-moderation-latest.md): Previous generation text-only moderation model

116- [text-moderation-stable](/api/docs/models/text-moderation-stable.md): Previous generation text-only moderation model

117- [TTS-1](/api/docs/models/tts-1.md): Text-to-speech model optimized for speed

118- [TTS-1 HD](/api/docs/models/tts-1-hd.md): Text-to-speech model optimized for quality

119- [Whisper](/api/docs/models/whisper-1.md): General-purpose speech recognition model

models/all.md +119 −0 created

Details

1# Models

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 

5> Explore models available on the OpenAI API.

6 

7If you're not sure where to start, use [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol), our flagship model for complex reasoning and coding. Choose [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra) to balance intelligence and cost, or [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna) for cost-sensitive, high-volume workloads.

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).

10 

11## Recommended models

12 

13- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): Start here for complex reasoning and coding.

14- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): Balance intelligence and cost.

15- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): Optimize cost-sensitive, high-volume workloads.

16 

17## Browse our full catalog of models

18 

19Diverse models for a variety of tasks

20 

21See [how OpenAI uses your data](/api/docs/guides/your-data.md) and review [deprecated models](/api/docs/deprecations.md).

22 

23- [babbage-002](/api/docs/models/babbage-002.md): Replacement for the GPT-3 ada and babbage base models

24- [Chat Latest](/api/docs/models/chat-latest.md): Latest Instant model used in ChatGPT

25- [ChatGPT-4o](/api/docs/models/chatgpt-4o-latest.md): GPT-4o model used in ChatGPT

26- [chatgpt-image-latest](/api/docs/models/chatgpt-image-latest.md): Previous image model used in ChatGPT.

27- [codex-mini-latest](/api/docs/models/codex-mini-latest.md): Fast reasoning model optimized for the Codex CLI

28- [computer-use-preview](/api/docs/models/computer-use-preview.md): Specialized model for computer use tool

29- [DALL·E 2](/api/docs/models/dall-e-2.md): Our first image generation model

30- [DALL·E 3](/api/docs/models/dall-e-3.md): Previous generation image generation model

31- [davinci-002](/api/docs/models/davinci-002.md): Replacement for the GPT-3 curie and davinci base models

32- [GPT Image 1](/api/docs/models/gpt-image-1.md): Our previous image generation model

33- [GPT Image 1.5](/api/docs/models/gpt-image-1.5.md): Our previous image generation model

34- [GPT Image 2](/api/docs/models/gpt-image-2.md): State-of-the-art image generation model

35- [GPT Live Transcribe](/api/docs/models/gpt-live-transcribe.md): Low-latency speech-to-text model for realtime transcription

36- [GPT Transcribe](/api/docs/models/gpt-transcribe.md): High-accuracy speech-to-text model for file and Realtime input transcription

37- [GPT-3.5 Turbo](/api/docs/models/gpt-3.5-turbo.md): Legacy GPT model for cheaper chat and non-chat tasks

38- [gpt-3.5-turbo-16k-0613](/api/docs/models/gpt-3.5-turbo-16k-0613.md): Legacy GPT model for cheaper chat and non-chat tasks

39- [gpt-3.5-turbo-instruct](/api/docs/models/gpt-3.5-turbo-instruct.md): An older model only compatible with the legacy Completions endpoint

40- [GPT-4](/api/docs/models/gpt-4.md): An older high-intelligence GPT model

41- [GPT-4 Turbo](/api/docs/models/gpt-4-turbo.md): An older high-intelligence GPT model

42- [GPT-4 Turbo Preview](/api/docs/models/gpt-4-turbo-preview.md): An older fast GPT model

43- [GPT-4.1](/api/docs/models/gpt-4.1.md): Smartest non-reasoning model

44- [GPT-4.1 mini](/api/docs/models/gpt-4.1-mini.md): Smaller, faster version of GPT-4.1

45- [GPT-4.1 nano](/api/docs/models/gpt-4.1-nano.md): Fastest, most cost-efficient version of GPT-4.1

46- [GPT-4.5 Preview](/api/docs/models/gpt-4.5-preview.md): Deprecated large model.

47- [GPT-4o](/api/docs/models/gpt-4o.md): Fast, intelligent, flexible GPT model

48- [GPT-4o Audio](/api/docs/models/gpt-4o-audio-preview.md): GPT-4o models capable of audio inputs and outputs

49- [GPT-4o mini](/api/docs/models/gpt-4o-mini.md): Fast, affordable small model for focused tasks

50- [GPT-4o mini Audio](/api/docs/models/gpt-4o-mini-audio-preview.md): Smaller model capable of audio inputs and outputs

51- [GPT-4o mini Realtime](/api/docs/models/gpt-4o-mini-realtime-preview.md): Smaller realtime model for text and audio inputs and outputs

52- [GPT-4o mini Search Preview](/api/docs/models/gpt-4o-mini-search-preview.md): Fast, affordable small model for web search

53- [GPT-4o mini Transcribe](/api/docs/models/gpt-4o-mini-transcribe.md): Speech-to-text model powered by GPT-4o mini

54- [GPT-4o mini TTS](/api/docs/models/gpt-4o-mini-tts.md): Text-to-speech model powered by GPT-4o mini

55- [GPT-4o Realtime](/api/docs/models/gpt-4o-realtime-preview.md): Model capable of realtime text and audio inputs and outputs

56- [GPT-4o Search Preview](/api/docs/models/gpt-4o-search-preview.md): GPT model for web search in Chat Completions

57- [GPT-4o Transcribe](/api/docs/models/gpt-4o-transcribe.md): Speech-to-text model powered by GPT-4o

58- [GPT-4o Transcribe Diarize](/api/docs/models/gpt-4o-transcribe-diarize.md): Transcription model that identifies who's speaking when

59- [GPT-5](/api/docs/models/gpt-5.md): Previous intelligent reasoning model for coding and agentic tasks with configurable reasoning effort

60- [GPT-5 Chat](/api/docs/models/gpt-5-chat-latest.md): GPT-5 model used in ChatGPT

61- [GPT-5 mini](/api/docs/models/gpt-5-mini.md): Near-frontier intelligence for cost sensitive, low latency, high volume workloads

62- [GPT-5 nano](/api/docs/models/gpt-5-nano.md): Fastest, most cost-efficient version of GPT-5

63- [GPT-5 Pro](/api/docs/models/gpt-5-pro.md): Version of GPT-5 that produces smarter and more precise responses

64- [GPT-5-Codex](/api/docs/models/gpt-5-codex.md): A version of GPT-5 optimized for agentic coding in Codex

65- [GPT-5.1](/api/docs/models/gpt-5.1.md): The best model for coding and agentic tasks with configurable reasoning effort

66- [GPT-5.1 Chat](/api/docs/models/gpt-5.1-chat-latest.md): GPT-5.1 model used in ChatGPT

67- [GPT-5.1-Codex](/api/docs/models/gpt-5.1-codex.md): A version of GPT-5.1 optimized for agentic coding in Codex.

68- [GPT-5.1-Codex mini](/api/docs/models/gpt-5.1-codex-mini.md): Smaller, more cost-effective, less-capable version of GPT-5.1-Codex

69- [GPT-5.1-Codex-Max](/api/docs/models/gpt-5.1-codex-max.md): A version of GPT-5.1-codex optimized for long running tasks.

70- [GPT-5.2](/api/docs/models/gpt-5.2.md): Previous frontier model for professional work with configurable reasoning effort

71- [GPT-5.2 Chat](/api/docs/models/gpt-5.2-chat-latest.md): GPT-5.2 model used in ChatGPT

72- [GPT-5.2 Pro](/api/docs/models/gpt-5.2-pro.md): Previous pro model for professional work that produces smarter and more precise responses.

73- [GPT-5.2-Codex](/api/docs/models/gpt-5.2-codex.md): Our most intelligent coding model optimized for long-horizon, agentic coding tasks.

74- [GPT-5.3 Chat](/api/docs/models/gpt-5.3-chat-latest.md): GPT-5.3 Instant model used in ChatGPT

75- [GPT-5.3-Codex](/api/docs/models/gpt-5.3-codex.md): The most capable agentic coding model to date.

76- [GPT-5.4](/api/docs/models/gpt-5.4.md): A more affordable model for coding and professional work.

77- [GPT-5.4 mini](/api/docs/models/gpt-5.4-mini.md): Our strongest mini model yet for coding, computer use, and subagents

78- [GPT-5.4 nano](/api/docs/models/gpt-5.4-nano.md): Our cheapest GPT-5.4-class model for simple high-volume tasks

79- [GPT-5.4 Pro](/api/docs/models/gpt-5.4-pro.md): Version of GPT-5.4 that produces smarter and more precise responses.

80- [GPT-5.5](/api/docs/models/gpt-5.5.md): A new class of intelligence for coding and professional work.

81- [GPT-5.5 Pro](/api/docs/models/gpt-5.5-pro.md): Version of GPT-5.5 that produces smarter and more precise responses.

82- [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md): GPT-5.6 model optimized for cost-sensitive workloads

83- [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md): Frontier model for complex professional work

84- [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md): GPT-5.6 model that balances intelligence and cost

85- [gpt-audio](/api/docs/models/gpt-audio.md): For audio inputs and outputs with Chat Completions API

86- [gpt-audio-1.5](/api/docs/models/gpt-audio-1.5.md): The best voice model for audio in, audio out with Chat Completions.

87- [gpt-audio-mini](/api/docs/models/gpt-audio-mini.md): A cost-efficient version of GPT Audio

88- [gpt-image-1-mini](/api/docs/models/gpt-image-1-mini.md): A cost-efficient version of GPT Image 1

89- [gpt-oss-120b](/api/docs/models/gpt-oss-120b.md): Most powerful open-weight model, fits into an H100 GPU

90- [gpt-oss-20b](/api/docs/models/gpt-oss-20b.md): Medium-sized open-weight model for low latency

91- [GPT-Realtime](/api/docs/models/gpt-realtime.md): Model capable of realtime text and audio inputs and outputs

92- [GPT-Realtime mini](/api/docs/models/gpt-realtime-mini.md): A cost-efficient version of GPT-Realtime

93- [GPT-Realtime-1.5](/api/docs/models/gpt-realtime-1.5.md): The best voice model for audio in, audio out

94- [GPT-Realtime-2](/api/docs/models/gpt-realtime-2.md): Reasoning model with tool use

95- [GPT-Realtime-2.1](/api/docs/models/gpt-realtime-2.1.md): Reasoning model with tool use

96- [GPT-Realtime-2.1 mini](/api/docs/models/gpt-realtime-2.1-mini.md): Reasoning model with tool use

97- [GPT-Realtime-Translate](/api/docs/models/gpt-realtime-translate.md): Streaming speech-to-speech translation model

98- [GPT-Realtime-Whisper](/api/docs/models/gpt-realtime-whisper.md): Streaming speech-to-text model for realtime transcription

99- [o1](/api/docs/models/o1.md): Previous full o-series reasoning model

100- [o1 Preview](/api/docs/models/o1-preview.md): Preview of our first o-series reasoning model

101- [o1-mini](/api/docs/models/o1-mini.md): A small model alternative to o1

102- [o1-pro](/api/docs/models/o1-pro.md): Version of o1 with more compute for better responses

103- [o3](/api/docs/models/o3.md): Reasoning model for complex tasks, succeeded by GPT-5

104- [o3-deep-research](/api/docs/models/o3-deep-research.md): Our most powerful deep research model

105- [o3-mini](/api/docs/models/o3-mini.md): A small model alternative to o3

106- [o3-pro](/api/docs/models/o3-pro.md): Version of o3 with more compute for better responses

107- [o4-mini](/api/docs/models/o4-mini.md): Fast, cost-efficient reasoning model, succeeded by GPT-5 mini

108- [o4-mini-deep-research](/api/docs/models/o4-mini-deep-research.md): Faster, more affordable deep research model

109- [omni-moderation](/api/docs/models/omni-moderation-latest.md): Identify potentially harmful content in text and images

110- [Sora 2](/api/docs/models/sora-2.md): Flagship video generation with synced audio

111- [Sora 2 Pro](/api/docs/models/sora-2-pro.md): Most advanced synced-audio video generation

112- [text-embedding-3-large](/api/docs/models/text-embedding-3-large.md): Most capable embedding model

113- [text-embedding-3-small](/api/docs/models/text-embedding-3-small.md): Small embedding model

114- [text-embedding-ada-002](/api/docs/models/text-embedding-ada-002.md): Older embedding model

115- [text-moderation](/api/docs/models/text-moderation-latest.md): Previous generation text-only moderation model

116- [text-moderation-stable](/api/docs/models/text-moderation-stable.md): Previous generation text-only moderation model

117- [TTS-1](/api/docs/models/tts-1.md): Text-to-speech model optimized for speed

118- [TTS-1 HD](/api/docs/models/tts-1-hd.md): Text-to-speech model optimized for quality

119- [Whisper](/api/docs/models/whisper-1.md): General-purpose speech recognition model

models/compare.md +12 −0 created

Details

1# Compare models

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 

5> Compare current model capabilities, context windows, and token pricing.

6 

7| Model | Context window | Max output | Supported endpoints |

8| --- | ---: | ---: | --- |

9| [GPT-5.6 Sol](/api/docs/models/gpt-5.6-sol.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

10| [GPT-5.6 Terra](/api/docs/models/gpt-5.6-terra.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

11| [GPT-5.6 Luna](/api/docs/models/gpt-5.6-luna.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

12| [GPT-5.5](/api/docs/models/gpt-5.5.md) | 1,050,000 | 128,000 | Chat Completions, Responses, Batch |

quickstart.md +496 −198

Details

1# Developer quickstart1# Developer quickstart

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.

4 

3The OpenAI API provides a consistent interface to state-of-the-art AI [models](https://developers.openai.com/api/docs/models) for text generation, natural language processing, computer vision, and more. Get started by creating an API Key and running your first API call. Discover how to generate text, analyze images, build agents, and more.5The OpenAI API provides a consistent interface to state-of-the-art AI [models](https://developers.openai.com/api/docs/models) for text generation, natural language processing, computer vision, and more. Get started by creating an API Key and running your first API call. Discover how to generate text, analyze images, build agents, and more.

4 6 

5## Create and export an API key7## Create and export an API key


12 Create an API Key14 Create an API Key

13 15 

14 16 

15<p></p>17 

18 

19 

16Before you begin, create an API key in the dashboard, which you'll use to20Before you begin, create an API key in the dashboard, which you'll use to

17securely [access the API](https://developers.openai.com/api/docs/api-reference/authentication). Store the key21securely [access the API](https://developers.openai.com/api/reference/overview). Store the key

18in a safe location, like a [`.zshrc`22in a safe location, like a [`.zshrc`

19file](https://www.freecodecamp.org/news/how-do-zsh-configuration-files-work/) or23file](https://www.freecodecamp.org/news/how-do-zsh-configuration-files-work/) or

20another text file on your computer. Once you've generated an API key, export it24another text file on your computer. Once you've generated an API key, export it


23 27 

24 28 

25 29 

26<div data-content-switcher-pane data-value="macOS">30macOS / Linux

27 <div class="hidden">macOS / Linux</div>31 

28 Export an environment variable on macOS or Linux systems32 Export an environment variable on macOS or Linux systems

29 33 

30```bash34```bash

31export OPENAI_API_KEY="your_api_key_here"35export OPENAI_API_KEY="your_api_key_here"

32```36```

33 37 

34 </div>38

35 <div data-content-switcher-pane data-value="windows" hidden>39 

36 <div class="hidden">Windows</div>40

41 

42

43Windows

44 

37 Export an environment variable in PowerShell45 Export an environment variable in PowerShell

38 46 

39```bash47```bash

40setx OPENAI_API_KEY "your_api_key_here"48setx OPENAI_API_KEY "your_api_key_here"

41```49```

42 50 

43 </div>

44 

45 51 

46 52 

47Each OpenAI SDK automatically reads your API key from the system environment.53Each OpenAI SDK automatically reads your API key from the system environment.


50 56 

51 57 

52 58 

53<div data-content-switcher-pane data-value="javascript">59JavaScript

54 <div class="hidden">JavaScript</div>60 

55 </div>61

56 <div data-content-switcher-pane data-value="python" hidden>62 

57 <div class="hidden">Python</div>63To use the OpenAI API in server-side JavaScript environments like Node.js, Deno, or Bun, you can use the official [OpenAI SDK for TypeScript and JavaScript](https://github.com/openai/openai-node). Get started by installing the SDK using [npm](https://www.npmjs.com/) or your preferred package manager:

58 </div>64 

59 <div data-content-switcher-pane data-value="csharp" hidden>65Install the OpenAI SDK with npm

60 <div class="hidden">.NET</div>66 

61 </div>67```bash

62 <div data-content-switcher-pane data-value="java" hidden>68npm install openai

63 <div class="hidden">Java</div>69```

64 </div>70 

65 <div data-content-switcher-pane data-value="golang" hidden>71 

66 <div class="hidden">Go</div>72With the OpenAI SDK installed, create a file called `example.mjs` and copy the example code into it:

67 </div>73 

68 <div data-content-switcher-pane data-value="ruby" hidden>74Test a basic API request

69 <div class="hidden">Ruby</div>75 

70 </div>76```javascript

71 77import OpenAI from "openai";

72 78const client = new OpenAI();

73<a79 

74 href="https://github.com/openai/openai-responses-starter-app"80const response = await client.responses.create({

75 target="_blank"81 model: "gpt-5.6",

76 rel="noreferrer"82 input: "Write a one-sentence bedtime story about a unicorn.",

77>83});

84 

85console.log(response.output_text);

86```

87 

88 

89Execute the code with `node example.mjs` (or the equivalent command for Deno or Bun). In a few moments, you should see the output of your API request.

90 

91[Learn more on GitHub

92 

93 

94 

95 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-node)

96 

97 

98

99 

100

101 

102

103Python

104 

105

106 

107To use the OpenAI API in Python, you can use the official [OpenAI SDK for Python](https://github.com/openai/openai-python). Get started by installing the SDK using [pip](https://pypi.org/project/pip/):

108 

109Install the OpenAI SDK with pip

110 

111```bash

112pip install openai

113```

114 

115 

116With the OpenAI SDK installed, create a file called `example.py` and copy the example code into it:

117 

118Test a basic API request

119 

120```python

121from openai import OpenAI

122 

123client = OpenAI()

124 

125response = client.responses.create(

126 model="gpt-5.6",

127 input="Write a one-sentence bedtime story about a unicorn.",

128)

129 

130print(response.output_text)

131```

132 

133 

134Execute the code with `python example.py`. In a few moments, you should see the output of your API request.

135 

136[Learn more on GitHub

137 

138 

139 

140 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-python)

141 

142 

143

144 

145

146 

147

148.NET

149 

150

151 

152In collaboration with Microsoft, OpenAI provides an officially supported API client for C#. You can install it with the .NET CLI from [NuGet](https://www.nuget.org/).

153 

154```

155dotnet add package OpenAI

156```

157 

158A simple API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

159 

160Test a basic API request

161 

162```csharp

163using OpenAI.Responses;

164#pragma warning disable OPENAI001

165 

166string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

167ResponsesClient client = new(key);

168 

169ResponseResult response = await client.CreateResponseAsync(

170 "gpt-5.6",

171 "Say 'this is a test.'"

172);

173 

174Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");

175```

176 

177 

178

179 

180

181 

182

183Java

184 

185

186 

187OpenAI provides an API helper for the Java programming language, currently in beta. You can include the Maven dependency using the following configuration:

188 

189```xml

190<dependency>

191 <groupId>com.openai</groupId>

192 <artifactId>openai-java</artifactId>

193 <version>4.0.0</version>

194</dependency>

195```

196 

197A simple API request to [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

198 

199Test a basic API request

200 

201```java

202import com.openai.client.OpenAIClient;

203import com.openai.client.okhttp.OpenAIOkHttpClient;

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

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

206 

207public class Main {

208 public static void main(String[] args) {

209 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

210 

211 ResponseCreateParams params =

212 ResponseCreateParams.builder().input("Say this is a test").model("gpt-5.6").build();

213 

214 Response response = client.responses().create(params);

215 response.output().stream()

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

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

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

219 .forEach(outputText -> System.out.println(outputText.text()));

220 }

221}

222```

223 

224 

225To learn more about using the OpenAI API in Java, check out the GitHub repo linked below!

226 

227[Learn more on GitHub

228 

229 

230 

231 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-java)

232 

233 

234

235 

236

237 

238

239Go

240 

241

242 

243OpenAI provides an API helper for the Go programming language, currently in beta. You can import the library using the code below:

244 

245```go

246import (

247 "github.com/openai/openai-go/v3" // imported as openai

248)

249```

250 

251 

252A first API request to the [Responses API](https://developers.openai.com/api/reference/resources/responses) would look like this:

253 

254Test a basic API request

255 

256```go

257package main

258 

259import (

260 "context"

261 "fmt"

262 

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

264 "github.com/openai/openai-go/v3/option"

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

266)

267 

268func main() {

269 client := openai.NewClient(

270 option.WithAPIKey("My API Key"), // or set OPENAI_API_KEY in your env

271 )

272 

273 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

274 Model: "gpt-5.6",

275 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

276 })

277 if err != nil {

278 panic(err.Error())

279 }

280 

281 fmt.Println(resp.OutputText())

282}

283```

284 

285 

286To learn more about using the OpenAI API in Go, check out the GitHub repo linked below!

287 

288[Learn more on GitHub

289 

290 

291 

292 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-go)

293 

78 294 

79 295

80<span slot="icon">

81 </span>

82 Start building with the Responses API.

83 296 

84 297

85</a>

86 298 

87[

88 299

89<span slot="icon">300Ruby

90 </span>

91 Learn more about prompting, message roles, and building conversational apps.

92 301 

93](https://developers.openai.com/api/docs/guides/text)302

303 

304To use the OpenAI API in Ruby, you can use the official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby). Get started by adding the gem to your application:

305 

306Install the OpenAI SDK with Bundler

307 

308```ruby

309gem "openai"

310```

311 

312 

313With the OpenAI SDK installed, create a file called `example.rb` and copy the example code into it:

314 

315Test a basic API request

316 

317```ruby

318require "openai"

319 

320openai = OpenAI::Client.new

321 

322response = openai.responses.create(

323 model: "gpt-5.6",

324 input: "Write a one-sentence bedtime story about a unicorn."

325)

326 

327puts(response.output_text)

328```

329 

330 

331Execute the code with `ruby example.rb`. In a few moments, you should see the output of your API request.

332 

333[Learn more on GitHub

334 

335 

336 

337 Discover more SDK capabilities and options on the library's GitHub README.](https://github.com/openai/openai-ruby)

338 

339 

340[Responses starter app

341 

342 

343 

344 Start building with the Responses API.](https://github.com/openai/openai-responses-starter-app)

345 

346[Text generation and prompting

347 

348 

349 

350 Learn more about prompting, message roles, and building conversational apps.](https://developers.openai.com/api/docs/guides/text)

94 351 

95## Add credits to keep building352## Add credits to keep building

96 353 


103 360 

104 361 

105{/* prettier-ignore */}362{/* prettier-ignore */}

106<div className="mt-2">Congrats on running a free test API request! Start building real applications with higher limits and use <a href="/api/docs/models" target="_blank">our models</a> to generate text, audio, images, videos and more.</div>

107 363 

108<div className="mt-2">364Congrats on running a free test API request! Start building real applications with higher limits and use [our models](https://developers.openai.com/api/docs/models) to generate text, audio, images, videos and more.

365 

366 

367 

368 

109 Explore tools and docs designed to help you ship faster:369 Explore tools and docs designed to help you ship faster:

110</div>370 

111<a371 

112 href="https://platform.openai.com/chat"372[StatsigClient.logEvent(

113 target="_blank"

114 rel="noreferrer"

115 onClick={() =>

116 StatsigClient.logEvent(

117 "quickstart_add_credits_chat_playground_click",373 "quickstart_add_credits_chat_playground_click",

118 null,374 null,

119 null375 null

120 )376 )

121 }377 }

122>378>

379 Chat Playground

123 380 

124 381 

125<span slot="icon">

126 </span>

127 Build & test conversational prompts and embed them in your app.

128 382 

383 Build & test conversational prompts and embed them in your app.](https://platform.openai.com/chat)

384[Build agents

129 385 

130</a>

131[

132 386 

133<span slot="icon">

134 </span>

135 Use the Agents SDK to build, run, and observe agent workflows.

136 387 

137](https://developers.openai.com/api/docs/guides/agents)388 Use the Agents SDK to build, run, and observe agent workflows.](https://developers.openai.com/api/docs/guides/agents)

138 389 

139## Analyze images and files390## Analyze images and files

140 391 


142 393 

143 394 

144 395 

145<div data-content-switcher-pane data-value="image-url">396Image URL

146 <div class="hidden">Image URL</div>397 

147 Analyze the content of an image398 Analyze the content of an image

148 399 

149```javascript400```javascript


242 493 

243```csharp494```csharp

244using OpenAI.Responses;495using OpenAI.Responses;

496#pragma warning disable OPENAI001

245 497 

246string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;498string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

247OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);499ResponsesClient client = new(key);

500 

501Uri imageUrl = new(

502 "https://openai-documentation.vercel.app/images/cat_and_otter.png"

503);

248 504 

249OpenAIResponse response = (OpenAIResponse)client.CreateResponse([505ResponseResult response = await client.CreateResponseAsync(

250 ResponseItem.CreateUserMessageItem([506 "gpt-5.6",

507 [

508 ResponseItem.CreateUserMessageItem(

509 [

251 ResponseContentPart.CreateInputTextPart("What is in this image?"),510 ResponseContentPart.CreateInputTextPart("What is in this image?"),

252 ResponseContentPart.CreateInputImagePart(new Uri("https://openai-documentation.vercel.app/images/cat_and_otter.png")),511 ResponseContentPart.CreateInputImagePart(imageUrl),

253 ]),512 ]

254]);513 ),

514 ]

515);

255 516 

256Console.WriteLine(response.GetOutputText());517Console.WriteLine(response.GetOutputText());

257```518```


283puts(response.output_text)544puts(response.output_text)

284```545```

285 546 

286 </div>547

287 <div data-content-switcher-pane data-value="file-url" hidden>548 

288 <div class="hidden">File URL</div>549

550 

551

552File URL

553 

289 Use a file URL as input554 Use a file URL as input

290 555 

291```bash556```bash


393```658```

394 659 

395```csharp660```csharp

396using OpenAI.Files;

397using OpenAI.Responses;661using OpenAI.Responses;

662#pragma warning disable OPENAI001

398 663 

399string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;664string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

400OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);665ResponsesClient client = new(key);

401 666 

402using HttpClient http = new();667Uri fileUrl = new(

403using Stream stream = await http.GetStreamAsync("https://www.berkshirehathaway.com/letters/2024ltr.pdf");668 "https://www.berkshirehathaway.com/letters/2024ltr.pdf"

404OpenAIFileClient files = new(key);669);

405OpenAIFile file = files.UploadFile(stream, "2024ltr.pdf", FileUploadPurpose.UserData);

406 670 

407OpenAIResponse response = (OpenAIResponse)client.CreateResponse([671ResponseResult response = await client.CreateResponseAsync(

408 ResponseItem.CreateUserMessageItem([672 "gpt-5.6",

409 ResponseContentPart.CreateInputTextPart("Analyze the letter and provide a summary of the key points."),673 [

410 ResponseContentPart.CreateInputFilePart(file.Id),674 ResponseItem.CreateUserMessageItem(

411 ]),675 [

412]);676 ResponseContentPart.CreateInputTextPart(

677 "Analyze the letter and provide a summary of the key points."

678 ),

679 ResponseContentPart.CreateInputFilePart(fileUrl),

680 ]

681 ),

682 ]

683);

413 684 

414Console.WriteLine(response.GetOutputText());685Console.WriteLine(response.GetOutputText());

415```686```

416 687 

417 </div>688

418 <div data-content-switcher-pane data-value="file-upload" hidden>689 

419 <div class="hidden">Upload file</div>690

691 

692

693Upload file

694 

420 Upload a file and use it as input695 Upload a file and use it as input

421 696 

422```bash697```bash


538```csharp813```csharp

539using OpenAI.Files;814using OpenAI.Files;

540using OpenAI.Responses;815using OpenAI.Responses;

816#pragma warning disable OPENAI001

541 817 

542string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;818string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

543OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);819ResponsesClient client = new(key);

544 820 

545OpenAIFileClient files = new(key);821OpenAIFileClient files = new(key);

546OpenAIFile file = files.UploadFile("draconomicon.pdf", FileUploadPurpose.UserData);

547 822 

548OpenAIResponse response = (OpenAIResponse)client.CreateResponse([823OpenAIFile file = await files.UploadFileAsync(

549 ResponseItem.CreateUserMessageItem([824 "draconomicon.pdf",

825 FileUploadPurpose.UserData

826);

827 

828ResponseResult response = await client.CreateResponseAsync(

829 "gpt-5.6",

830 [

831 ResponseItem.CreateUserMessageItem(

832 [

550 ResponseContentPart.CreateInputFilePart(file.Id),833 ResponseContentPart.CreateInputFilePart(file.Id),

551 ResponseContentPart.CreateInputTextPart("What is the first dragon in the book?"),834 ResponseContentPart.CreateInputTextPart(

552 ]),835 "What is the first dragon in the book?"

553]);836 ),

837 ]

838 ),

839 ]

840);

554 841 

555Console.WriteLine(response.GetOutputText());842Console.WriteLine(response.GetOutputText());

556```843```

557 844 

558 </div>

559 845 

560 846 

847[Image inputs guide

848 

561 849 

562[

563 850 

564<span slot="icon">851 Learn to use image inputs to the model and extract meaning from images.](https://developers.openai.com/api/docs/guides/images-vision)

565 </span>

566 Learn to use image inputs to the model and extract meaning from images.

567 852 

568](https://developers.openai.com/api/docs/guides/images)853[File inputs guide

569 854 

570[

571 855 

572<span slot="icon">

573 </span>

574 Learn to use file inputs to the model and extract meaning from documents.

575 856 

576](https://developers.openai.com/api/docs/guides/file-inputs)857 Learn to use file inputs to the model and extract meaning from documents.](https://developers.openai.com/api/docs/guides/file-inputs)

577 858 

578## Extend the model with tools859## Extend the model with tools

579 860 


581 862 

582 863 

583 864 

584<div data-content-switcher-pane data-value="web-search">865Web search

585 <div class="hidden">Web search</div>866 

586 Use web search in a response867 Use web search in a response

587 868 

588```javascript869```javascript


636 917 

637```csharp918```csharp

638using OpenAI.Responses;919using OpenAI.Responses;

920#pragma warning disable OPENAI001

639 921 

640string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;922string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

641OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);923ResponsesClient client = new(key);

642 924 

643ResponseCreationOptions options = new();925CreateResponseOptions options = new() { Model = "gpt-5.6" };

644options.Tools.Add(ResponseTool.CreateWebSearchTool());926options.Tools.Add(ResponseTool.CreateWebSearchTool());

927options.InputItems.Add(

928 ResponseItem.CreateUserMessageItem("What was a positive news story from today?")

929);

645 930 

646OpenAIResponse response = (OpenAIResponse)client.CreateResponse([931ResponseResult response = await client.CreateResponseAsync(options);

647 ResponseItem.CreateUserMessageItem([

648 ResponseContentPart.CreateInputTextPart("What was a positive news story from today?"),

649 ]),

650], options);

651 932 

652Console.WriteLine(response.GetOutputText());933Console.WriteLine(response.GetOutputText());

653```934```


666puts(response.output_text)947puts(response.output_text)

667```948```

668 949 

669 </div>950

670 <div data-content-switcher-pane data-value="file-search" hidden>951 

671 <div class="hidden">File search</div>952

953 

954

955File search

956 

672 Search your files in a response957 Search your files in a response

673 958 

674```python959```python


703 988 

704```csharp989```csharp

705using OpenAI.Responses;990using OpenAI.Responses;

991#pragma warning disable OPENAI001

706 992 

707string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;993string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

708OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);994ResponsesClient client = new(key);

709 995 

710ResponseCreationOptions options = new();996CreateResponseOptions options = new() { Model = "gpt-5.6" };

711options.Tools.Add(ResponseTool.CreateFileSearchTool(["<vector_store_id>"]));997options.Tools.Add(

998 ResponseTool.CreateFileSearchTool(["<vector_store_id>"])

999);

1000options.InputItems.Add(

1001 ResponseItem.CreateUserMessageItem("What is deep research by OpenAI?")

1002);

712 1003 

713OpenAIResponse response = (OpenAIResponse)client.CreateResponse([1004ResponseResult response = await client.CreateResponseAsync(options);

714 ResponseItem.CreateUserMessageItem([

715 ResponseContentPart.CreateInputTextPart("What is deep research by OpenAI?"),

716 ]),

717], options);

718 1005 

719Console.WriteLine(response.GetOutputText());1006Console.WriteLine(response.GetOutputText());

720```1007```


738puts(response)1025puts(response)

739```1026```

740 1027 

741 </div>1028

742 <div data-content-switcher-pane data-value="code-interpreter" hidden>1029 

743 <div class="hidden">Code Interpreter</div>1030

1031 

1032

1033Code Interpreter

1034 

744 Use Code Interpreter in a response1035 Use Code Interpreter in a response

745 1036 

746```javascript1037```javascript


815puts(response.output_text)1106puts(response.output_text)

816```1107```

817 1108 

818 </div>1109

819 <div data-content-switcher-pane data-value="function-calling" hidden>1110 

820 <div class="hidden">Function calling</div>1111

1112 

1113

1114Function calling

1115 

821 Call your own function1116 Call your own function

822 1117 

823```javascript1118```javascript


894 1189 

895```csharp1190```csharp

896using System.Text.Json;1191using System.Text.Json;

1192using System.Text.Json.Serialization.Metadata;

897using OpenAI.Responses;1193using OpenAI.Responses;

1194#pragma warning disable CA1869

1195#pragma warning disable OPENAI001

898 1196 

899string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1197string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

900OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);1198ResponsesClient client = new(key);

901 1199 

902ResponseCreationOptions options = new();1200CreateResponseOptions options = new() { Model = "gpt-5.6" };

903options.Tools.Add(ResponseTool.CreateFunctionTool(1201options.Tools.Add(

1202 ResponseTool.CreateFunctionTool(

904 functionName: "get_weather",1203 functionName: "get_weather",

905 functionDescription: "Get current temperature for a given location.",1204 functionDescription: "Get current temperature for a given location.",

906 functionParameters: BinaryData.FromObjectAsJson(new1205 functionParameters: BinaryData.FromString(

907 {1206 """

908 type = "object",

909 properties = new

910 {1207 {

911 location = new1208 "type": "object",

912 {1209 "properties": {

913 type = "string",1210 "location": {

914 description = "City and country e.g. Bogotá, Colombia"1211 "type": "string",

1212 "description": "City and country e.g. Bogotá, Colombia"

915 }1213 }

916 },1214 },

917 required = new[] { "location" },1215 "required": ["location"],

918 additionalProperties = false1216 "additionalProperties": false

919 }),1217 }

1218 """

1219 ),

920 strictModeEnabled: true1220 strictModeEnabled: true

921 )1221 )

922);1222);

1223options.InputItems.Add(

1224 ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?")

1225);

923 1226 

924OpenAIResponse response = (OpenAIResponse)client.CreateResponse([1227ResponseResult response = client.CreateResponse(options);

925 ResponseItem.CreateUserMessageItem([1228Console.WriteLine(

926 ResponseContentPart.CreateInputTextPart("What is the weather like in Paris today?")1229 JsonSerializer.Serialize(

927 ])1230 response.OutputItems[0],

928], options);1231 new JsonSerializerOptions

929 1232 {

930Console.WriteLine(JsonSerializer.Serialize(response.OutputItems[0]));1233 TypeInfoResolver = new DefaultJsonTypeInfoResolver(),

1234 }

1235 )

1236);

931```1237```

932 1238 

933```bash1239```bash


997puts(response.output.first.to_json)1303puts(response.output.first.to_json)

998```1304```

999 1305 

1000 </div>1306

1001 <div data-content-switcher-pane data-value="remote-mcp" hidden>1307 

1002 <div class="hidden">Remote MCP</div>1308

1309 

1310

1311Remote MCP

1312 

1003 Call a remote MCP server1313 Call a remote MCP server

1004 1314 

1005```bash1315```bash


1067 1377 

1068```csharp1378```csharp

1069using OpenAI.Responses;1379using OpenAI.Responses;

1380#pragma warning disable OPENAI001

1070 1381 

1071string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1382string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1072OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);1383ResponsesClient client = new(key);

1073 1384 

1074ResponseCreationOptions options = new();1385CreateResponseOptions options = new() { Model = "gpt-5.6" };

1075options.Tools.Add(ResponseTool.CreateMcpTool(1386options.Tools.Add(

1387 ResponseTool.CreateMcpTool(

1076 serverLabel: "dmcp",1388 serverLabel: "dmcp",

1077 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),1389 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

1078 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)1390 toolCallApprovalPolicy: GlobalMcpToolCallApprovalPolicy.NeverRequireApproval

1079));1391 )

1392);

1393options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));

1080 1394 

1081OpenAIResponse response = (OpenAIResponse)client.CreateResponse([1395ResponseResult response = await client.CreateResponseAsync(options);

1082 ResponseItem.CreateUserMessageItem([

1083 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

1084 ])

1085], options);

1086 1396 

1087Console.WriteLine(response.GetOutputText());1397Console.WriteLine(response.GetOutputText());

1088```1398```


1109puts(response.output_text)1419puts(response.output_text)

1110```1420```

1111 1421 

1112 </div>

1113 1422 

1114 1423 

1424[Use built-in tools

1425 

1115 1426 

1116[

1117 1427 

1118<span slot="icon">1428 Learn about powerful built-in tools like web search and file search.](https://developers.openai.com/api/docs/guides/tools)

1119 </span>

1120 Learn about powerful built-in tools like web search and file search.

1121 1429 

1122](https://developers.openai.com/api/docs/guides/tools)1430[Function calling guide

1123 1431 

1124[

1125 1432 

1126<span slot="icon">

1127 </span>

1128 Learn to enable the model to call your own custom code.

1129 1433 

1130](https://developers.openai.com/api/docs/guides/function-calling)1434 Learn to enable the model to call your own custom code.](https://developers.openai.com/api/docs/guides/function-calling)

1131 1435 

1132## Stream responses and build real-time apps1436## Stream responses and build real-time apps

1133 1437 


1177 1481 

1178```csharp1482```csharp

1179using OpenAI.Responses;1483using OpenAI.Responses;

1484#pragma warning disable OPENAI001

1180 1485 

1181string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1486string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1182OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);1487ResponsesClient client = new(key);

1183 1488 

1184var responses = client.CreateResponseStreamingAsync([1489var responses = client.CreateResponseStreamingAsync(

1185 ResponseItem.CreateUserMessageItem([1490 "gpt-5.6",

1186 ResponseContentPart.CreateInputTextPart("Say 'double bubble bath' ten times fast."),1491 "Say 'double bubble bath' ten times fast."

1187 ]),1492);

1188]);

1189 1493 

1190await foreach (var response in responses)1494await foreach (StreamingResponseUpdate response in responses)

1191{1495{

1192 if (response is StreamingResponseOutputTextDeltaUpdate delta)1496 if (response is StreamingResponseOutputTextDeltaUpdate delta)

1193 {1497 {


1217```1521```

1218 1522 

1219 1523 

1220[1524[Use streaming events

1525 

1221 1526 

1222<span slot="icon">

1223 </span>

1224 Use server-sent events to stream model responses to users fast.

1225 1527 

1226](https://developers.openai.com/api/docs/guides/streaming-responses)1528 Use server-sent events to stream model responses to users fast.](https://developers.openai.com/api/docs/guides/streaming-responses)

1227 1529 

1228[1530[Get started with the Realtime API

1229 1531 

1230<span slot="icon">

1231 </span>

1232 Use WebRTC or WebSockets for super fast speech-to-speech AI apps.

1233 1532 

1234](https://developers.openai.com/api/docs/guides/realtime)1533 

1534 Use WebRTC or WebSockets for super fast speech-to-speech AI apps.](https://developers.openai.com/api/docs/guides/realtime)

1235 1535 

1236## Build agents1536## Build agents

1237 1537 


1294```1594```

1295 1595 

1296 1596 

1297[1597[Build agents that can take action

1598 

1298 1599 

1299<span slot="icon">

1300 </span>

1301 Learn how to use the OpenAI platform to build powerful, capable AI agents.

1302 1600 

1303](https://developers.openai.com/api/docs/guides/agents)1601 Learn how to use the OpenAI platform to build powerful, capable AI agents.](https://developers.openai.com/api/docs/guides/agents)

Details

1# Supported countries and territories1# Supported countries and territories

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.

4 

3Accessing or offering access to our services outside of the countries and territories listed below may result in your account being blocked or suspended.5Accessing or offering access to our services outside of the countries and territories listed below may result in your account being blocked or suspended.

4 6 

5- Albania7- Albania

Details

1# Meeting minutes1# Meeting minutes

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.

4 

3In this tutorial, we'll harness the power of OpenAI's Whisper and GPT models to develop an automated meeting minutes generator. The application transcribes audio from a meeting, provides a summary of the discussion, extracts key points and action items, and performs a sentiment analysis.5In this tutorial, we'll harness the power of OpenAI's Whisper and GPT models to develop an automated meeting minutes generator. The application transcribes audio from a meeting, provides a summary of the discussion, extracts key points and action items, and performs a sentiment analysis.

4 6 

5## Getting started7## Getting started


19 21 

20## Transcribing audio with Whisper22## Transcribing audio with Whisper

21 23 

22<div className="sandbox-preview">24 

23 <div className="sandbox-screenshot-small">25 

24 </div>26

25 <div className="preview-info">27 

26 <div className="description">

27 The first step in transcribing the audio from a meeting is to pass the28 The first step in transcribing the audio from a meeting is to pass the

28 audio file of the meeting into our 29 audio file of the meeting into our

29 <a href="/api/docs/api-reference/audio">/v1/audio API</a>. Whisper, the30 [/v1/audio API](https://developers.openai.com/api/reference/resources/audio). Whisper, the

30 model that powers the audio API, is capable of converting spoken language31 model that powers the audio API, is capable of converting spoken language

31 into written text. To start, we will avoid passing a 32 into written text. To start, we will avoid passing a

32 <a href="/api/docs/api-reference/audio/createTranscription#audio/createTranscription-prompt">33 [prompt](https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create#audio/createTranscription-prompt)

33 prompt

34 </a>

35 or 34 or

36 <a href="/api/docs/api-reference/audio/createTranscription#audio/createTranscription-temperature-4">35 [temperature](https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create#audio/createTranscription-temperature-4)

37 temperature

38 </a>

39 (optional parameters to control the model's output) and stick with the36 (optional parameters to control the model's output) and stick with the

40 default values.37 default values.

41 </div>38

42 <div className="actions">39 

40

41 

43 42

44 43 

45Download sample audio44Download sample audio

46 45 

47 46 

48 </div>

49 </div>

50</div>

51 47

52<br />48 

49

50 

51 

52 

53 

54 

55 

53 56 

54Next, we import the required packages and define a function that uses the Whisper model to take in the audio file and57Next, we import the required packages and define a function that uses the Whisper model to take in the audio file and

55transcribe it:58transcribe it:


75 78 

76## Summarizing and analyzing the transcript with a GPT model79## Summarizing and analyzing the transcript with a GPT model

77 80 

78Having obtained the transcript, we now pass it to a GPT model via the [Chat Completions API](https://developers.openai.com/api/docs/api-reference/chat/create). The snippets below use a tested model to generate a summary, extract key points, action items, and perform sentiment analysis. For new projects, start with [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol).81Having obtained the transcript, we now pass it to a GPT model via the [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). The snippets below use a tested model to generate a summary, extract key points, action items, and perform sentiment analysis. For new projects, start with [`gpt-5.6`](https://developers.openai.com/api/docs/models/gpt-5.6-sol).

79 82 

80This tutorial uses distinct functions for each task we want the model to perform. This is not the most efficient way to do this task - you can put these instructions into one function, however, splitting them up can lead to higher quality summarization.83This tutorial uses distinct functions for each task we want the model to perform. This is not the most efficient way to do this task - you can put these instructions into one function, however, splitting them up can lead to higher quality summarization.

81 84 


182 185 

183## Exporting meeting minutes186## Exporting meeting minutes

184 187 

185<div className="sandbox-preview">188 

186 <div className="sandbox-screenshot-small">189 

187 </div>190

188 <div className="preview-info">191 

189 <div className="description">

190 Once we've generated the meeting minutes, it's beneficial to save them192 Once we've generated the meeting minutes, it's beneficial to save them

191 into a readable format that can be easily distributed. One common format193 into a readable format that can be easily distributed. One common format

192 for such reports is Microsoft Word. The Python docx library is a popular194 for such reports is Microsoft Word. The Python docx library is a popular

193 open source library for creating Word documents. If you wanted to build an195 open source library for creating Word documents. If you wanted to build an

194 end-to-end meeting minute application, you might consider removing this196 end-to-end meeting minute application, you might consider removing this

195 export step in favor of sending the summary inline as an email followup.197 export step in favor of sending the summary inline as an email followup.

196 </div>

197 </div>

198</div>

199 198

200<br></br>199 

200

201 

202 

203 

204 

205 

206</br>

201 207 

202To handle the exporting process, define a function `save_as_docx` that converts the raw text to a Word document:208To handle the exporting process, define a function `save_as_docx` that converts the raw text to a Word document:

203 209 

Details

1# Web QA with embeddings1# Web QA with embeddings

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.

4 

3This tutorial walks through a simple example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the [Embeddings API](https://developers.openai.com/api/docs/guides/embeddings), and then creating a basic search functionality that allows a user to ask questions about the embedded information. This is intended to be a starting point for more sophisticated applications that make use of custom knowledge bases.5This tutorial walks through a simple example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the [Embeddings API](https://developers.openai.com/api/docs/guides/embeddings), and then creating a basic search functionality that allows a user to ask questions about the embedded information. This is intended to be a starting point for more sophisticated applications that make use of custom knowledge bases.

4 6 

5# Getting started7# Getting started

6 8 

7Some basic knowledge of Python and GitHub is helpful for this tutorial. Before diving in, make sure to [set up an OpenAI API key](https://developers.openai.com/api/docs/api-reference/introduction) and walk through the [quickstart tutorial](https://developers.openai.com/api/docs/quickstart). This will give a good intuition on how to use the API to its full potential.9Some basic knowledge of Python and GitHub is helpful for this tutorial. Before diving in, make sure to [set up an OpenAI API key](https://developers.openai.com/api/reference/overview) and walk through the [quickstart tutorial](https://developers.openai.com/api/docs/quickstart). This will give a good intuition on how to use the API to its full potential.

8 10 

9Python is used as the main programming language along with the OpenAI, Pandas, transformers, NumPy, and other popular packages. If you run into any issues working through this tutorial, please ask a question on the [OpenAI Community Forum](https://community.openai.com).11Python is used as the main programming language along with the OpenAI, Pandas, transformers, NumPy, and other popular packages. If you run into any issues working through this tutorial, please ask a question on the [OpenAI Community Forum](https://community.openai.com).

10 12 


24 26 

25Learn how to build a web crawler27Learn how to build a web crawler

26 28 

27<div className="sandbox-preview">29 

28 <div className="sandbox-screenshot">30 

29 </div>31

30 <div className="preview-info">32 

31 <div className="description">

32 Acquiring data in text form is the first step to use embeddings. This33 Acquiring data in text form is the first step to use embeddings. This

33 tutorial creates a new set of data by crawling the OpenAI website, a34 tutorial creates a new set of data by crawling the OpenAI website, a

34 technique that you can also use for your own company or personal website.35 technique that you can also use for your own company or personal website.

35 </div>36

36 <div className="actions">37 

38

39 

37 40

38 41 

39View source code42View source code

40 43 

41 44 

42 </div>45

43 </div>46 

44</div>47

48 

49 

50 

45 51 

46While this crawler is written from scratch, open source packages like [Scrapy](https://github.com/scrapy/scrapy) can also help with these operations.52While this crawler is written from scratch, open source packages like [Scrapy](https://github.com/scrapy/scrapy) can also help with these operations.

47 53 


210 216 

211## Building an embeddings index217## Building an embeddings index

212 218 

213<div className="sandbox-preview">219 

214 <div className="sandbox-screenshot">220 

215 </div>221

216 <div className="preview-info">222 

217 <div className="description">

218 CSV is a common format for storing embeddings. You can use this format223 CSV is a common format for storing embeddings. You can use this format

219 with Python by converting the raw text files (which are in the text224 with Python by converting the raw text files (which are in the text

220 directory) into Pandas data frames. Pandas is a popular open source225 directory) into Pandas data frames. Pandas is a popular open source

221 library that helps you work with tabular data (data stored in rows and226 library that helps you work with tabular data (data stored in rows and

222 columns).227 columns).

223 </div>228

224 <div className="description">229 

230

231 

225 Blank empty lines can clutter the text files and make them harder to232 Blank empty lines can clutter the text files and make them harder to

226 process. A simple function can remove those lines and tidy up the files.233 process. A simple function can remove those lines and tidy up the files.

227 </div>234

228 </div>235 

229</div>236

237 

238 

239 

230 240 

231```python241```python

232def remove_newlines(serie):242def remove_newlines(serie):


305```315```

306 316 

307 317 

308<div className="sandbox-preview">318 

309 <div className="sandbox-screenshot">319 

320

321 

310 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-initial-histrogram.png"322 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-initial-histrogram.png"

311 alt="Embeddings histogram"323 alt="Embeddings histogram"

312 width="553"324 width="553"

313 height="413"325 height="413"

314 />326 />

315 </div>327

316</div>328 

329 

330 

317 331 

318The newest embeddings model can handle inputs with up to 8191 input tokens so most of the rows would not need any chunking, but this may not be the case for every subpage scraped so the next code chunk will split the longer lines into smaller chunks.332The newest embeddings model can handle inputs with up to 8191 input tokens so most of the rows would not need any chunking, but this may not be the case for every subpage scraped so the next code chunk will split the longer lines into smaller chunks.

319 333 


383```397```

384 398 

385 399 

386<div className="sandbox-preview">400 

387 <div className="sandbox-screenshot">401 

402

403 

388 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-tokenized-output.png"404 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-tokenized-output.png"

389 alt="Embeddings tokenized output"405 alt="Embeddings tokenized output"

390 width="552"406 width="552"

391 height="418"407 height="418"

392 />408 />

393 </div>409

394</div>410 

411 

412 

395 413 

396The content is now broken down into smaller chunks and a simple request can be sent to the OpenAI API specifying the use of the new text-embedding-ada-002 model to create the embeddings:414The content is now broken down into smaller chunks and a simple request can be sent to the OpenAI API specifying the use of the new text-embedding-ada-002 model to create the embeddings:

397 415 


415 433 

416## Building a question answer system with your embeddings434## Building a question answer system with your embeddings

417 435 

418<div className="sandbox-preview">436 

419 <div className="sandbox-screenshot">437 

420 </div>438

421 <div className="preview-info">439 

422 <div className="description">

423 The embeddings are ready and the final step of this process is to create a440 The embeddings are ready and the final step of this process is to create a

424 simple question and answer system. This will take a user's question,441 simple question and answer system. This will take a user's question,

425 create an embedding of it, and compare it with the existing embeddings to442 create an embedding of it, and compare it with the existing embeddings to

426 retrieve the most relevant text from the scraped website. The443 retrieve the most relevant text from the scraped website. The

427 gpt-3.5-turbo-instruct model will then generate a natural sounding answer444 gpt-3.5-turbo-instruct model will then generate a natural sounding answer

428 based on the retrieved text.445 based on the retrieved text.

429 </div>446

430 </div>447 

431</div>448

449 

450 

451 

432 452 

433---453---

434 454 

ui-kit-demo.md +0 −5 deleted

File Deleted View Diff

1# UI Kit Demo

2 

3# UI Kit Demo

4 

5## hello