OpenAI
Learn how to use the OpenAI provider for the AI SDK.
The OpenAI provider contains language model support for the OpenAI responses, chat, and completion APIs, as well as embedding model support for the OpenAI embeddings API.
Setup
The OpenAI provider is available in the @ai-sdk/openai module. You can install it with
$ pnpm add @ai-sdk/openai
$ npm install @ai-sdk/openai
$ yarn add @ai-sdk/openai
$ bun add @ai-sdk/openai
Provider Instance
You can import the default provider instance openai from @ai-sdk/openai:
If you need a customized setup, you can import createOpenAI from @ai-sdk/openai and create a provider instance with your settings:
You can use the following optional settings to customize the OpenAI provider instance:
-
batchResultDownloads object
Settings for downloading JSON Lines batch results.
-
maxLineBytes number
Maximum UTF-8 bytes per row, excluding the LF delimiter. Defaults to 64 MiB (67,108,864 bytes). Must be a positive safe integer. Oversized rows throw a
DownloadErrorand cancel the download.
-
-
baseURL string
Use a different URL prefix for API calls, e.g. to use proxy servers. It defaults to the
OPENAI_BASE_URLenvironment variable, and then tohttps://api.openai.com/v1. The default OpenAI model factory (openai('model-id')) uses the Responses API. If your custom base URL only supports the Chat Completions API, create chat models withopenai.chat('model-id')instead, or use the OpenAI-compatible provider. -
apiKey string
API key that is being sent using the
Authorizationheader. It defaults to theOPENAI_API_KEYenvironment variable. -
name string
The provider name. You can set this when using OpenAI compatible providers to change the model provider property. Defaults to
openai. -
organization string
OpenAI Organization.
-
project string
OpenAI project.
-
headers Record<string,string>
Custom headers to include in the requests.
-
fetch (input: RequestInfo, init?: RequestInit) => Promise<Response>
Custom fetch implementation. Defaults to the global
fetchfunction. You can use it as a middleware to intercept requests, or to provide a custom fetch implementation for e.g. testing.
Language Models
The OpenAI provider instance is a function that you can invoke to create a language model:
It automatically selects the correct API based on the model id. You can also pass additional settings in the second argument:
The available options depend on the API that's automatically chosen for the model (see below).
If you want to explicitly select a specific model API, you can use .responses, .chat, or .completion.
Since AI SDK 5, the OpenAI responses API is called by default (unless you specify e.g. 'openai.chat')
Example
You can use OpenAI language models to generate text with the generateText function:
OpenAI language models can also be used in the streamText function
and support structured data generation with Output
(see AI SDK Core).
Responses Models
You can use the OpenAI responses API with the openai(modelId) or openai.responses(modelId) factory methods. It is the default API that is used by the OpenAI provider (since AI SDK 5).
Further configuration can be done using OpenAI provider options.
You can validate the provider options using the OpenAILanguageModelResponsesOptions type.
The following provider options are available:
-
parallelToolCalls boolean Whether to use parallel tool calls. Defaults to
true. -
store boolean
Whether to store the generation. Defaults to
true. -
passThroughUnsupportedFiles boolean
Whether to pass through non-image file types as generic input files. Defaults to
false, which restricts inline file inputs to images and PDFs. Enable this when the target OpenAI Responses model supports additional file media types. -
maxToolCalls integer The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.
-
metadata Record<string, string> Additional metadata to store with the generation.
-
conversation string The ID of the OpenAI Conversation to continue. You must create a conversation first via the OpenAI API. Cannot be used in conjunction with
previousResponseId. Defaults toundefined. -
previousResponseId string The ID of the previous response. You can use it to continue a conversation. Defaults to
undefined. -
instructions string Instructions for the model. They can be used to change the system or developer message when continuing a conversation using the
previousResponseIdoption. Defaults toundefined. -
logprobs boolean | number Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to better understand how the model is behaving. Setting to
truereturns the log probabilities of the tokens that were generated. Setting to a number (1-20) returns the log probabilities of the top n tokens that were generated. -
user string A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Defaults to
undefined. -
reasoningEffort 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' Reasoning effort for reasoning models. Defaults to
medium. If you useproviderOptionsto set thereasoningEffortoption, this model setting will be ignored.
Supported reasoning efforts vary by model. GPT-5.6, GPT-6 Sol, and GPT-6 Luna
support 'none', 'low', 'medium', 'high', 'xhigh', and 'max'. GPT-6
Astra and GPT-6.1 Sol do not support 'none'.
GPT-6 and later models do not support temperature, topP, logprobs, or
the legacy promptCacheRetention option. The provider removes these settings
and returns a warning. Use the Responses API for GPT-6 tool calling.
-
reasoningEffortUpdate 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' Updates the reasoning effort for GPT-6 and later models starting with the current response without changing the request-level effort. Use this with
previousResponseIdto preserve the original prompt prefix for caching. Configuration updates require standard, single-agent mode and cannot be combined with automatic compaction or automatic truncation.The SDK checks effort values against the selected model for both request-level and message-level updates. For example, GPT-6 Sol and Luna support
none, while GPT-6 Astra does not. -
reasoningMode 'standard' | 'pro' Controls how much model work GPT-5.6 performs before returning a final answer.
'standard'is the default. Use'pro'for difficult tasks where quality matters more than latency and token usage. -
reasoningContext 'auto' | 'current_turn' | 'all_turns' Controls which available reasoning items GPT-5.6 can reuse.
'auto'uses the model default,'current_turn'excludes reasoning from earlier turns, and'all_turns'makes compatible earlier reasoning available. The effective context is returned asproviderMetadata.openai.reasoningContext. -
reasoningSummary 'auto' | 'detailed' | null Controls whether the model returns its reasoning process. Set to
'auto'for a condensed summary,'detailed'for more comprehensive reasoning, ornullto omit reasoning summaries. Defaults to'detailed'whenreasoningEffortis set to a value other than'none', and to no reasoning summaries otherwise. When enabled, reasoning summaries appear in the stream as events with type'reasoning'and in non-streaming responses within thereasoningfield. -
strictJsonSchema boolean Whether to use strict JSON schema validation. Defaults to
true.
OpenAI structured outputs have several
limitations,
in particular around the supported
schemas,
and are therefore opt-in. For example, optional schema properties are not
supported. You need to change Zod .nullish() and .optional() to
.nullable().
-
serviceTier 'auto' | 'flex' | 'priority' | 'fast' | 'ultrafast' | 'default' Service tier for the request. Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models). Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported). 'fast' is OpenAI's newer name for the 'priority' tier; the two are interchangeable, and responses from gpt-5.6 and earlier report
serviceTier: 'priority'for either. Set to 'ultrafast' for access-controlled Ultrafast processing (available only for gpt-5.6-sol).Defaults to 'auto'.
-
textVerbosity 'low' | 'medium' | 'high' Controls the verbosity of the model's response. Lower values result in more concise responses, while higher values result in more verbose responses. Defaults to
'medium'. -
include Array<string> Specifies additional content to include in the response. Supported values:
['file_search_call.results']for including file search results in responses.['message.output_text.logprobs']for logprobs. Defaults toundefined. -
truncation string The truncation strategy to use for the model response.
- Auto: If the input to this Response exceeds the model's context window size, the model will truncate the response to fit the context window by dropping items from the beginning of the conversation.
- disabled (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error.
-
promptCacheKey string A cache key for manual prompt caching control. Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
-
promptCacheOptions object Configures prompt caching for GPT-5.6 and later models.
modecan be'implicit'or'explicit', andttlcurrently only supports'30m'. In explicit mode, only content blocks marked with a prompt cache breakpoint are cached. -
promptCacheRetention 'in_memory' | '24h' The legacy retention policy for models before GPT-5.6. Set to
'24h'to enable extended prompt caching on supported models. For GPT-5.6 and later models, usepromptCacheOptions.ttlinstead. -
safetyIdentifier string A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies each user.
-
systemMessageMode 'system' | 'developer' | 'remove' Controls the role of the system message when making requests. By default (when omitted), for models that support reasoning the
systemmessage is automatically converted to adevelopermessage. SettingsystemMessageModetosystempasses the system message as a system-level instruction;developerpasses it as a developer message;removeomits the system message from the request. -
forceReasoning boolean Force treating this model as a reasoning model. This is useful for "stealth" reasoning models (e.g. via a custom baseURL) where the model ID is not recognized by the SDK's allowlist. When enabled, the SDK applies reasoning-model parameter compatibility rules and defaults
systemMessageModetodeveloperunless overridden. -
contextManagement Array<object> Enable server-side context management (compaction). When configured, the server automatically compresses conversation context when token usage crosses a specified threshold. Each object in the array should have:
type:'compaction'compactThreshold: number — the token count at which compaction is triggered
-
compactionTrigger boolean Request explicit server-side compaction. When
true, the provider appends a terminal{ type: 'compaction_trigger' }item to the Responses input. Support depends on the configured Responses-compatible endpoint and model.
The OpenAI responses provider also returns provider-specific metadata:
For Responses models, you can type this metadata using OpenaiResponsesProviderMetadata:
The following OpenAI-specific metadata may be returned:
- responseId string | null | undefined The ID of the response. Can be used to continue a conversation.
- logprobs (optional) Log probabilities of output tokens (when enabled).
- serviceTier (optional) Service tier information returned by the API.
- reasoningContext (optional)
Effective persisted-reasoning context returned by GPT-5.6 (
'current_turn'or'all_turns').
Changing Reasoning Effort Mid-Conversation
You can increase reasoning effort for difficult work or reduce it for routine follow-ups while preserving the conversation prefix for prompt caching:
- Set the initial effort with request-level
reasoningand keep that setting unchanged throughout the conversation. - For later changes, add a message-level
reasoningEffortUpdatebefore the next user message, following OpenAI's configuration update guidance.
The new effort applies until another update changes it. When sending conversation
history in messages, include earlier effort updates along with the other messages.
Represent an update as an empty system message with
providerOptions.openai.reasoningEffortUpdate.
You must set allowSystemInMessages: true to allow these trusted system messages.
In this example, the conversation starts at low effort and switches to high
effort for the follow-up. Both requests keep reasoning: 'low'.
The OpenAI Responses provider sends each message-level effort update as a
configuration_update input item.
Message-level updates also work with streamText and previousResponseId.
Restrictions
Effort updates are supported on GPT-6-family models with these settings:
| Setting | Required value |
|---|---|
reasoningMode | 'standard' (default) |
contextManagement | Omitted |
truncation | 'disabled' (default) |
- Each update must use exactly
content: ''. - Updates cannot be consecutive, even with the same effort. This also applies across the boundary with history referenced by previousResponseId or conversation.
Requests that violate these restrictions are rejected.
Effort update messages are sent even if systemMessageMode is set to
remove.
Compaction
Effort updates are incompatible with automatic compaction through
providerOptions.openai.contextManagement or compaction through OpenAI's
/responses/compact endpoint.
To compact conversations containing effort updates, use explicit
compaction with
providerOptions.openai.compactionTrigger.
After compaction, add a fresh effort update before the next user message,
as OpenAI recommends. Keep request-level reasoning unchanged.
Request-Level Update Option
The request-level providerOptions.openai.reasoningEffortUpdate option is a
convenience that prepends a configuration update to the input. When using
message-level updates, omit this option.
The request-level option continues to warn and omit updates for unsupported models or configurations.
Reasoning Output
For reasoning models like gpt-6-astra, you can enable reasoning summaries to see the model's thought process. Different models support different summarizers—for example, o4-mini supports detailed summaries. Set reasoningSummary: "auto" to automatically receive the richest level available. When reasoningEffort is set to a value other than 'none', the OpenAI Responses provider defaults reasoningSummary to 'detailed'; set reasoningSummary: null to omit reasoning summaries.
For non-streaming calls with generateText, the reasoning summaries are available in the reasoning field of the response:
Learn more about reasoning summaries in the OpenAI documentation.
WebSocket Transport
OpenAI's WebSocket API keeps a persistent connection open, which can significantly reduce Time-to-First-Byte (TTFB) in agentic workflows with many tool calls. After the initial connection, subsequent requests skip TCP/TLS/HTTP negotiation entirely.
The ai-sdk-openai-websocket-fetch
package provides a drop-in fetch replacement that routes streaming requests
through a persistent WebSocket connection.
$ pnpm add ai-sdk-openai-websocket-fetch
$ npm install ai-sdk-openai-websocket-fetch
$ yarn add ai-sdk-openai-websocket-fetch
$ bun add ai-sdk-openai-websocket-fetch
Pass the WebSocket fetch to createOpenAI via the fetch option:
The first request will be slower because it must establish the WebSocket connection (DNS + TCP + TLS + WebSocket upgrade). After that, subsequent steps in a multi-step tool-calling loop reuse the open connection, resulting in lower TTFB per step.
The WebSocket transport only routes streaming requests to the OpenAI Responses
API (POST /responses with stream: true) through the WebSocket. All other
requests (non-streaming, embeddings, etc.) fall through to the standard
fetch implementation.
You can see a live side-by-side comparison of HTTP vs WebSocket streaming performance in the demo app.
Verbosity Control
You can control the length and detail of model responses using the textVerbosity parameter:
The textVerbosity parameter scales output length without changing the underlying prompt:
'low': Produces terse, minimal responses'medium': Balanced detail (default)'high': Verbose responses with comprehensive detail
Namespaced Function Calls
OpenAI supports grouping related function tools into
namespaces.
When the Responses API returns a function_call with a namespace, the OpenAI provider
exposes this value on the generated tool-call part as
providerMetadata.openai.namespace.
When using streamText, the namespace is available on the tool-input-end event and on
the final tool-call event:
If you persist or reconstruct messages for later turns, preserve the OpenAI provider
metadata on tool-call parts. The SDK uses providerMetadata.openai.namespace or
providerOptions.openai.namespace to round-trip the namespace back to OpenAI on
subsequent requests.
Async Tool Calling
GPT-6 Astra and later Responses models support async tool calling. An async tool lets the model continue generating independent output after issuing the call instead of waiting for its result. Your application still executes the tool and sends its result in a later request using the original tool call ID.
Enable async calling on a function tool with providerOptions.openai.async:
The generated tool call exposes the provider marker as
providerMetadata.openai.async. Use providerMetadata.openai.responseId as the
next request's previousResponseId, and submit the result in a tool message with
the original toolCallId.
With streamText, OpenAI can continue streaming text after the completed
tool-call part. Use the tool's onInputAvailable callback to start work as soon
as that part arrives. If execute returns the same already-running promise, tool
execution overlaps the rest of the model stream. Omit execute when the job
should outlive the current generation and submit its result in a later request.
Async calling applies to directly called function and custom tools. It does not apply to hosted tools and should not be combined with programmatic tool calling.
Programmatic Tool Calling
OpenAI Programmatic Tool Calling lets supported Responses models generate and run
hosted JavaScript that coordinates client-side function tools. Add the hosted tool
with openai.tools.programmaticToolCalling(), then opt each eligible function into
programmatic calls with allowedCallers.
allowedCallers supports:
['direct'](or omitted): only direct model tool calls['programmatic']: only calls from hosted JavaScript['direct', 'programmatic']: both invocation modes
Use outputSchema to describe the JSON value returned by the function. This schema
is sent to OpenAI as output_schema so generated JavaScript can safely use the
returned fields. It does not replace the tool's AI SDK output validation or execution
logic.
The provider preserves program code, replay fingerprints, program outputs, and nested
function caller metadata across the generateText and streamText tool loops,
including stateless requests with store: false. Programmatic invocation is
currently supported for AI SDK function tools; other OpenAI tool types remain
direct-only through this integration.
Treat generated programs and tool arguments as untrusted. Enforce authorization and approval inside every tool, avoid programmatic access to side-effecting tools unless the operation is idempotent, and set explicit step limits.
Web Search Tool
The OpenAI responses API supports web search through the openai.tools.webSearch tool.
result.sources and source stream events expose the URLs returned in
web_search_call.action.sources. These may include uncited URLs. Inline
references are available separately on text.citations and text-end.citations,
including titles and provider-supplied text ranges. Raw annotations remain in
text provider metadata. Citation-only responses and web_search_preview
responses without retrieval data retain citation-derived sources.
The web search tool supports the following configuration options:
- externalWebAccess boolean - Whether to use external web access for fetching live content. Defaults to
true. - searchContextSize 'low' | 'medium' | 'high' - Controls the amount of context used for the search. Higher values provide more comprehensive results but may have higher latency and cost.
- userLocation - Optional location information to provide geographically relevant results. Includes
type(always'approximate'),country,city,region, andtimezone. - filters - Optional filter configuration to restrict search results.
- allowedDomains string[] - Up to 100 allowed domains for the search.
- blockedDomains string[] - Up to 100 blocked domains for the search.
Omit the HTTP or HTTPS prefix from domain filters. Subdomains of configured domains are automatically included or excluded.
For detailed information on configuration options see the OpenAI Web Search Tool documentation.
File Search Tool
The OpenAI responses API supports file search through the openai.tools.fileSearch tool.
You can force the use of the file search tool by setting the toolChoice parameter to { type: 'tool', toolName: 'file_search' }.
The file search tool supports filtering with both comparison and compound filters:
Comparison filters - Filter by a single attribute:
eq- Equal tone- Not equal togt- Greater thangte- Greater than or equal tolt- Less thanlte- Less than or equal toin- Value is in arraynin- Value is not in array
Compound filters - Combine multiple filters with and or or:
Image Generation Tool
OpenAI's Responses API supports multi-modal image generation as a provider-defined tool.
Availability is restricted to specific models (for example, gpt-5 variants).
You can use the image tool with either generateText or streamText:
When you set store: false, then previously generated images will not be
accessible by the model. We recommend using the image generation tool without
setting store: false.
To use xhigh or max quality, select gpt-image-2.5-flare or
gpt-image-2.5-sunburst as the image generation tool's model:
For complete details on model availability, image quality controls, supported sizes, and tool-specific parameters, refer to the OpenAI documentation:
- Image generation overview and models: OpenAI Image Generation
- Image generation tool parameters (background, size, quality, format, etc.): Image Generation Tool Options
Code Interpreter Tool
The OpenAI responses API supports the code interpreter tool through the openai.tools.codeInterpreter tool.
This allows models to write and execute Python code.
The code interpreter tool can be configured with:
- container: Either a container ID string or an object with
fileIdsto specify uploaded files that should be available to the code interpreter
When working with files generated by the Code Interpreter, reference
information can be obtained from both annotations in Text
Parts and providerMetadata in
Source Document Parts.
MCP Tool
The OpenAI responses API supports connecting to Model Context Protocol (MCP) servers through the openai.tools.mcp tool. This allows models to call tools exposed by remote MCP servers or service connectors.
The MCP tool can be configured with:
-
serverLabel string (required)
A label to identify the MCP server. This label is used in tool calls to distinguish between multiple MCP servers.
-
serverUrl string (required if
connectorIdis not provided)The URL for the MCP server. Either
serverUrlorconnectorIdmust be provided. -
connectorId string (required if
serverUrlis not provided)Identifier for a service connector. Either
serverUrlorconnectorIdmust be provided. -
serverDescription string (optional)
Optional description of the MCP server that helps the model understand its purpose.
-
allowedTools string[] | object (optional)
Controls which tools from the MCP server are available. Can be:
- An array of tool names:
['tool1', 'tool2'] - An object with filters:
- An array of tool names:
-
authorization string (optional)
OAuth access token for authenticating with the MCP server or connector.
-
headers Record<string, string> (optional)
Optional HTTP headers to include in requests to the MCP server.
-
requireApproval 'always' | 'never' | object (optional)
Controls which MCP tool calls require user approval before execution. Can be:
'always': All MCP tool calls require approval'never': No MCP tool calls require approval (default)- An object with filters:
When approval is required, the model will return a
tool-approval-requestcontent part that you can use to prompt the user for approval. See Human in the Loop for more details on implementing approval workflows.
When requireApproval is not set, tool calls are approved by default. Be sure
to connect to only trusted MCP servers, who you trust to share your data with.
The OpenAI MCP tool is different from the general MCP client approach documented in MCP Tools. The OpenAI MCP tool is a built-in provider-defined tool that allows OpenAI models to directly connect to MCP servers, while the general MCP client requires you to convert MCP tools to AI SDK tools first.
Computer Tool
The OpenAI Responses API supports the GA computer tool through
openai.tools.computer. The model returns an ordered batch of browser or
desktop actions for your application to execute, and your application returns
an updated screenshot.
The execute callback receives:
- actions - An ordered array of
click,double_click,drag,keypress,move,screenshot,scroll,type, andwaitactions. Execute every action in order before capturing the next screenshot. - pendingSafetyChecks - Safety checks returned by OpenAI. Review these
before continuing and include accepted checks in
acknowledgedSafetyChecks. - status - The computer call status.
The action union is also exported as OpenAIComputerAction. Action-specific
fields are:
| Action | Fields |
|---|---|
click | button, x, y, optional keys |
double_click | x, y, optional keys |
drag | path containing { x, y } points, optional keys |
keypress | keys |
move | x, y, optional keys |
screenshot | No additional fields |
scroll | x, y, scrollX, scrollY, optional keys |
type | text |
wait | No additional fields |
Safety checks use the exported OpenAIComputerSafetyCheck type.
Return a computer_screenshot with either:
- imageUrl - A fully qualified URL or image data URL.
- fileId - The ID of an uploaded screenshot file.
detail can be auto, low, high, or original. original preserves the
captured resolution and is recommended when accurate coordinates are
important.
Computer calls and computer_call_output screenshot results are carried
through multi-step generations when using store, previousResponseId, or
OpenAI conversations. You can also set store: false; the provider will
serialize the complete call and screenshot result into each follow-up request.
Run computer use in an isolated browser or VM. Restrict reachable domains, accounts, credentials, environment variables, and file-system access. Treat on-screen content as untrusted prompt-injection input, require confirmation immediately before consequential actions, and avoid exposing sensitive information in screenshots.
Local Shell Tool
The OpenAI responses API support the local shell tool for Codex models through the openai.tools.localShell tool.
Local shell is a tool that allows agents to run shell commands locally on a machine you or the user provides.
Shell Tool
The OpenAI Responses API supports the shell tool through the openai.tools.shell tool.
The shell tool allows running bash commands and interacting with a command line.
The model proposes shell commands; your integration executes them and returns the outputs.
Running arbitrary shell commands can be dangerous. Always sandbox execution or add strict allow-/deny-lists before forwarding a command to the system shell.
The shell tool supports three environment modes that control where commands are executed:
Local Execution (default)
When no environment is specified (or type: 'local' is used), commands are executed locally via your execute callback:
Hosted Container (auto)
Set environment.type to 'containerAuto' to run commands in an OpenAI-hosted container. No execute callback is needed — OpenAI handles execution server-side:
The containerAuto environment supports:
- fileIds string[] - File IDs to make available in the container
- memoryLimit '1g' | '4g' | '16g' | '64g' - Memory limit for the container
- networkPolicy - Network access policy:
{ type: 'disabled' }— no network access{ type: 'allowlist', allowedDomains: string[], domainSecrets?: Array<{ domain, name, value }> }— allow specific domains with optional secrets
Existing Container Reference
Set environment.type to 'containerReference' to use an existing container by ID:
Execute Callback
For local execution (default or type: 'local'), your execute function must return an output array with results for each command:
- stdout string - Standard output from the command
- stderr string - Standard error from the command
- outcome - Either
{ type: 'timeout' }or{ type: 'exit', exitCode: number }
Skills
Skills are versioned bundles of files with a SKILL.md manifest that extend the shell tool's capabilities. They can be attached to both containerAuto and local environments.
Container skills support two formats — by reference (for skills uploaded to OpenAI) or inline (as a base64-encoded zip):
Local skills point to a directory on disk containing a SKILL.md file:
For more details on creating skills, see the OpenAI Skills documentation.
Apply Patch Tool
The OpenAI Responses API supports the apply patch tool for GPT-5.1 models through the openai.tools.applyPatch tool.
The apply patch tool lets the model 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 reports back on,
enabling iterative, multi-step code editing workflows.
Your execute function must return:
- status 'completed' | 'failed' - Whether the patch was applied successfully
- output string (optional) - Human-readable log text (e.g., results or error messages)
Tool Search
Tool search allows the model to dynamically search for and load tools into context as needed,
rather than loading all tool definitions up front. This can reduce token usage, cost, and latency
when you have many tools. Mark the tools you want to make searchable with deferLoading: true
in their providerOptions.
There are two execution modes:
- Server-executed (hosted): OpenAI searches across the deferred tools declared in the request and returns the loaded subset in the same response. No extra round-trip is needed.
- Client-executed: The model emits a
tool_search_call, your application performs the lookup, and you return the matching tools via theexecutecallback.
Server-Executed (Hosted) Tool Search
Use hosted tool search when the candidate tools are already known at request time.
Add openai.tools.toolSearch() with no arguments and mark your tools with deferLoading: true:
In hosted mode, the model internally searches the deferred tools, loads the relevant ones, and
proceeds to call them — all within a single response. The tool_search_call and
tool_search_output items appear in the response with execution: 'server' and call_id: null.
Namespaces
Use providerOptions.openai.namespace to group related function tools for OpenAI.
The SDK keeps each tool executable as a normal AI SDK tool, but serializes grouped
tools as OpenAI namespace entries in the request:
Tools in the same namespace must use the same namespace name and description.
For best results with tool search, keep namespace descriptions concise and put
detailed usage guidance on the individual function tools.
Client-Executed Tool Search
Use client-executed tool search when tool discovery depends on runtime state — for example,
tools that vary per tenant, project, or external system. Pass execution: 'client' along with
a description, parameters schema, and an execute callback:
In client mode, the flow spans two steps:
- Step 1: The model emits a
tool_search_callwithexecution: 'client'and a non-nullcall_id. The SDK calls yourexecutecallback with the search arguments. Your callback returns the discovered tools. - Step 2: The SDK sends the
tool_search_output(with the matchingcall_id) back to the model. The model can now call the loaded tools as normal function calls.
For more details, see the OpenAI Tool Search documentation.
Custom Tool
The OpenAI Responses API supports
custom tools
through the openai.tools.customTool tool.
Custom tools return a raw string instead of JSON, optionally constrained to a grammar
(regex or Lark syntax). This makes them useful for generating structured text like
SQL queries, code snippets, or any output that must match a specific pattern.
Custom tools also work with streamText:
The custom tool can be configured with:
- description string (optional) - A description of what the tool does, to help the model understand when to use it.
- format object (optional) - The output format constraint. Omit for unconstrained text output.
- type 'grammar' | 'text' - The format type. Use
'grammar'for constrained output or'text'for explicit unconstrained text. - syntax 'regex' | 'lark' - (grammar only) The grammar syntax. Use
'regex'for regular expression patterns or'lark'for Lark parser grammar. - definition string - (grammar only) The grammar definition string (a regex pattern or Lark grammar).
- type 'grammar' | 'text' - The format type. Use
- execute function (optional) - An async function that receives the raw string input and returns a string result. Enables multi-turn tool calling.
Restricting Callable Tools
The allowedTools provider option restricts which of the tools you declared the model is allowed to
call, while still sending the full tools list to OpenAI. Because the tools list stays byte-identical
across requests, the prompt cache is preserved — unlike activeTools, which removes tools from the
request and invalidates the cache whenever the allow-list changes.
allowedTools is only supported by the Responses API, and it overrides the request-level toolChoice.
- toolNames string[] - The tools the model may call, named as you declared them in
tools. For provider-defined tools you may also use the canonical OpenAI name (for exampleweb_search). - mode 'auto' | 'required' (optional) -
'auto'(default) lets the model pick one of the allowed tools or answer with a message;'required'forces it to call at least one of them.
Both function tools and provider-defined tools can be allow-listed, including web search, file search, image generation, code interpreter, computer, apply patch, shell, programmatic tool calling, custom tools, and MCP servers.
If a name matches both a tool you declared and the canonical OpenAI name of a different tool, the tool you declared under that name wins, and a warning reports the ambiguity. If several tools share the same canonical name — two MCP servers, for example — that name is ambiguous, so it is dropped with a warning; name those tools as you declared them instead.
Three kinds of tools cannot be allow-listed, because OpenAI's allowed_tools
only sees the eagerly-loaded tool list: the tool search tool,
tools marked with deferLoading, and tools grouped into a namespace. Naming
one of these in allowedTools removes it from the allow-list and emits a
warning; if that leaves no tools at all, the request fails with an error
instead of silently sending no restriction.
An MCP server is allow-listed as a whole: the entry carries the server label,
so every tool on that server is callable. To restrict which tools on a server
the model may call, use the MCP tool's own allowedTools argument.
Image Inputs
The OpenAI Responses API supports Image inputs for appropriate models.
You can pass Image files as part of the message content using the file type with an image media type:
The model will have access to the image and will respond to questions about it.
The image should be passed using the data field.
You can also pass a file-id from the OpenAI Files API.
You can also pass the URL of an image.
PDF Inputs
The OpenAI Responses API supports reading PDF files.
You can pass PDF files as part of the message content using the file type:
You can also pass a file-id from the OpenAI Files API.
You can also pass the URL of a pdf.
The model will have access to the contents of the PDF file and
respond to questions about it.
The PDF file should be passed using the data field,
and the mediaType should be set to 'application/pdf'.
Structured Outputs
The OpenAI Responses API supports structured outputs. You can use generateText or streamText with Output to enforce structured outputs.
Typed providerMetadata in Text Parts
When using the OpenAI Responses API, the SDK attaches OpenAI-specific metadata to output parts via providerMetadata.
This metadata can be used on the client side for tasks such as rendering citations or downloading files generated by the Code Interpreter. To enable type-safe handling of this metadata, the AI SDK exports dedicated TypeScript types.
For text parts, when part.type === 'text', the providerMetadata is provided in the form of OpenaiResponsesTextProviderMetadata.
This metadata includes the following fields:
-
itemIdThe ID of the output item in the Responses API. -
annotations(optional) An array of annotation objects generated by the model. If no annotations are present, this property itself may be omitted (undefined).Each element in
annotationsis a discriminated union with a requiredtypefield. Supported types include, for example:url_citationfile_citationcontainer_file_citationfile_path
These annotations directly correspond to the annotation objects defined by the Responses API and can be used for inline reference rendering or output analysis. For details, see the official OpenAI documentation: Responses API – output text annotations.
When implementing file downloads for files generated by the Code Interpreter,
the container_id and file_id available in providerMetadata can be used
to retrieve the file content. For details, see the Retrieve container file
content
API.
Typed providerMetadata in Reasoning Parts
When using the OpenAI Responses API, reasoning output parts can include provider metadata.
To handle this metadata in a type-safe way, use OpenaiResponsesReasoningProviderMetadata.
For reasoning parts, when part.type === 'reasoning', the providerMetadata is provided in the form of OpenaiResponsesReasoningProviderMetadata.
This metadata includes the following fields:
itemId
The ID of the reasoning item in the Responses API.reasoningEncryptedContent(optional)
Encrypted reasoning content (only returned when requested viainclude: ['reasoning.encrypted_content']).
When file-search results are included in the API response, each retrieved file
is exposed once as a document source, even if it has multiple matching passages
or is not cited. Inline file citations are available on text.citations and
text-end.citations. If the response omits file-search results, file citations
also remain document sources for compatibility. Generated file paths remain
source parts and are not treated as citations.
Typed providerMetadata in Source Document Parts
For source document parts, when part.type === 'source' and sourceType === 'document', the providerMetadata is provided as OpenaiResponsesSourceDocumentProviderMetadata.
This metadata is also a discriminated union with a required type field. Supported types include:
file_search(retrieved file; includesfileId)file_citationcontainer_file_citationfile_path
Each type includes the identifiers required to work with the referenced resource, such as fileId and containerId.
Annotations in text parts follow the OpenAI Responses API specification and
therefore use snake_case properties (e.g. file_id, container_id). In
contrast, providerMetadata for source document parts is normalized by the
SDK to camelCase (e.g. fileId, containerId). Fields that depend on the
original text content, such as start_index and end_index, are omitted, as
are fields like filename that are directly available on the source object.
Compaction
The OpenAI Responses API supports server-side context compaction. When enabled, the server automatically compresses conversation context when token usage crosses a configured threshold. This is useful for long-running conversations or agent loops where you want to stay within token limits without manually managing context.
The compaction item returned by the server is opaque and encrypted — it carries forward key prior state and reasoning into the next turn using fewer tokens. The AI SDK handles this automatically: compaction items are returned as text parts with special providerMetadata, and when passed back in subsequent requests they are sent as compaction input items.
Configuration:
- type — Must be
'compaction' - compactThreshold — The token count at which compaction is triggered. When the rendered input token count crosses this threshold, the server runs a compaction pass before continuing inference.
Server-side compaction is ZDR-friendly when you set store: false on your
requests.
Explicit Compaction
For Responses-compatible endpoints that support explicit compaction, set
compactionTrigger: true. The provider appends the required
{ type: 'compaction_trigger' } request control after all converted messages
and input items.
This is distinct from contextManagement, which configures automatic,
threshold-based compaction. When omitted or false, compactionTrigger does
not add an input item. The resulting compaction output uses the existing
openai.compaction custom part representation. Endpoint and model support can
vary.
Detecting Compaction in Streams
When using streamText, you can detect compaction by checking the providerMetadata on text-start and text-end events:
Compaction in UI Applications
When using useChat or other UI hooks, compaction items appear as text parts with providerMetadata. You can detect and style them differently in your UI:
The metadata includes the following fields:
- type — Always
'compaction' - itemId string — The ID of the compaction item in the Responses API
- encryptedContent string (optional) — The encrypted compaction state. This is automatically sent back to the API when the message is included in subsequent requests.
Batch
Batch support is experimental and the API may change in patch releases.
The OpenAI provider supports asynchronous text generation through the Batch API. Pass the OpenAI provider to the AI SDK's Batch API for the complete workflow, including polling, persistence, and result handling.
Each request specifies its type and model. OpenAI requires every text
request in a batch to use the same model and throws before submission when the
models differ.
Webhooks
The OpenAI Batch API does not support per-batch webhooks. When you provide a
webhookUrl, the provider returns an unsupported warning and starts the batch
without a webhook.
Chat Models
You can create models that call the OpenAI chat API using the .chat() factory method.
The first argument is the model id, e.g. gpt-6-astra.
The OpenAI chat models support tool calls and some have multi-modal capabilities.
Use this factory when a custom baseURL points at an OpenAI-compatible endpoint
that implements Chat Completions but not the Responses API.
OpenAI chat models support also some model specific provider options that are not part of the standard call settings.
You can pass them in the providerOptions argument:
The following optional provider options are available for OpenAI chat models:
-
logitBias Record<number, number>
Modifies the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
As an example, you can pass
{"50256": -100}to prevent the token from being generated. -
logprobs boolean | number
Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that were generated.
Setting to a number will return the log probabilities of the top n tokens that were generated.
-
parallelToolCalls boolean
Whether to enable parallel function calling during tool use. Defaults to
true. -
user string
A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more.
-
reasoningEffort 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
Reasoning effort for reasoning models. Defaults to
medium. If you useproviderOptionsto set thereasoningEffortoption, this model setting will be ignored.Supported reasoning efforts vary by model. GPT-5.6 supports
'none','low','medium','high','xhigh', and'max'. -
maxCompletionTokens number
Maximum number of completion tokens to generate. Useful for reasoning models.
-
store boolean
Whether to enable persistence in Responses API.
-
metadata Record<string, string>
Metadata to associate with the request.
-
prediction Record<string, any>
Parameters for prediction mode.
-
serviceTier 'auto' | 'flex' | 'priority' | 'fast' | 'ultrafast' | 'default'
Service tier for the request. Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models). Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported). 'fast' is OpenAI's newer name for the 'priority' tier; the two are interchangeable, and responses from gpt-5.6 and earlier report
serviceTier: 'priority'for either. Set to 'ultrafast' for access-controlled Ultrafast processing (available only for gpt-5.6-sol).Defaults to 'auto'.
-
strictJsonSchema boolean
Whether to use strict JSON schema validation. Defaults to
true. -
textVerbosity 'low' | 'medium' | 'high'
Controls the verbosity of the model's responses. Lower values will result in more concise responses, while higher values will result in more verbose responses.
-
promptCacheKey string
A cache key for manual prompt caching control. Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
-
promptCacheOptions object
Configures prompt caching for GPT-5.6 and later models.
modecan be'implicit'or'explicit', andttlcurrently only supports'30m'. In explicit mode, only content blocks marked with a prompt cache breakpoint are cached. -
promptCacheRetention 'in_memory' | '24h'
The legacy retention policy for models before GPT-5.6. Set to
'24h'to enable extended prompt caching on supported models. For GPT-5.6 and later models, usepromptCacheOptions.ttlinstead. -
safetyIdentifier string
A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies each user.
-
systemMessageMode 'system' | 'developer' | 'remove'
Override the system message mode for this model. If not specified, the mode is automatically determined based on the model.
systemuses the 'system' role for system messages (default for most models);developeruses the 'developer' role (used by reasoning models);removeremoves system messages entirely. -
forceReasoning boolean
Force treating this model as a reasoning model. This is useful for "stealth" reasoning models (e.g. via a custom baseURL) where the model ID is not recognized by the SDK's allowlist. When enabled, the SDK applies reasoning-model parameter compatibility rules and defaults
systemMessageModetodeveloperunless overridden.
Reasoning
OpenAI has introduced the o1,o3, and o4 series of reasoning models.
Currently, o4-mini, o3, o3-mini, and o1 are available via both the chat and responses APIs. The
model gpt-5.1-codex-mini is available only via the responses API.
Reasoning models currently only generate text, have several limitations, and are only supported using generateText and streamText.
They support additional settings and response metadata:
-
You can use
providerOptionsto set- the
reasoningEffortoption (or alternatively thereasoningEffortmodel setting), which determines the amount of reasoning the model performs.
- the
-
You can use the response
usageto access the number of reasoning tokens that the model generated viausage.outputTokenDetails.reasoningTokens.
System messages are automatically converted to OpenAI developer messages for reasoning models when supported.
- You can control how system messages are handled by providerOptions
systemMessageMode:developer: treat the prompt as a developer message (default for reasoning models).system: keep the system message as a system-level instruction.remove: remove the system message from the messages.
Reasoning models require additional runtime inference to complete their reasoning phase before generating a response. This introduces longer latency compared to other models.
maxOutputTokens is automatically mapped to max_completion_tokens for
reasoning models.
Strict Structured Outputs
Strict structured outputs are enabled by default.
You can disable them by setting the strictJsonSchema option to false.
OpenAI structured outputs have several limitations, in particular around the supported schemas, and are therefore opt-in.
For example, optional schema properties are not supported.
You need to change Zod .nullish() and .optional() to .nullable().
Logprobs
OpenAI provides logprobs information for completion/chat models.
You can access it in the providerMetadata object.
Image Support
The OpenAI Chat API supports Image inputs for appropriate models.
You can pass Image files as part of the message content using the file type with an image media type:
The model will have access to the image and will respond to questions about it.
The image should be passed using the data field.
You can also pass the URL of an image.
PDF support
The OpenAI Chat API supports reading PDF files.
You can pass PDF files as part of the message content using the file type:
The model will have access to the contents of the PDF file and
respond to questions about it.
The PDF file should be passed using the data field,
and the mediaType should be set to 'application/pdf'.
You can also pass a file-id from the OpenAI Files API.
You can also pass the URL of a PDF.
Predicted Outputs
OpenAI supports predicted outputs for gpt-4o and gpt-4o-mini.
Predicted outputs help you reduce latency by allowing you to specify a base text that the model should modify.
You can enable predicted outputs by adding the prediction option to the providerOptions.openai object:
OpenAI provides usage information for predicted outputs (acceptedPredictionTokens and rejectedPredictionTokens).
You can access it in the providerMetadata object.
OpenAI Predicted Outputs have several limitations, e.g. unsupported API parameters and no tool calling support.
Image Detail
You can use the openai provider option to set the image input detail to high, low, original, or auto:
For GPT-5.6, original preserves the input dimensions without resizing to a patch budget or pixel-dimension limit. auto and an omitted detail setting use the same sizing behavior as original, which can increase input token usage for large images.
Because the UIMessage type (used by AI SDK UI hooks like useChat) does not
support the providerOptions property, you can use convertToModelMessages
first before passing the messages to functions like generateText or
streamText. For more details on providerOptions usage, see
here.
Distillation
OpenAI supports model distillation for some models.
If you want to store a generation for use in the distillation process, you can add the store option to the providerOptions.openai object.
This will save the generation to the OpenAI platform for later use in distillation.
Prompt Caching
OpenAI has introduced Prompt Caching for supported models
including gpt-4o and gpt-4o-mini.
- Prompt caching is automatically enabled for these models, when the prompt is 1024 tokens or longer. It does not need to be explicitly enabled.
- You can use the response
usageto access the number of prompt tokens that were a cache hit viausage.inputTokenDetails.cacheReadTokens. - For GPT-5.6 and later models,
usage.inputTokenDetails.cacheWriteTokensreports tokens written to the cache. - For GPT-5.6 and later models,
promptCacheOptions.ttlsets a minimum cache lifetime of 30 minutes. Earlier models generally retain in-memory prefixes for 5-10 minutes of inactivity, up to one hour.
To improve cache hit rates, you can manually control caching using the promptCacheKey option:
GPT-5.6 and later models support explicit cache breakpoints on text, image, and file content blocks. Set a request-level cache key and mark the end of each reusable prefix with promptCacheBreakpoint:
In 'implicit' mode, OpenAI places an automatic breakpoint on the latest message and also honors explicit breakpoints. In 'explicit' mode, only marked content blocks are eligible for caching; a request without any explicit breakpoint does not use prompt caching.
For models before GPT-5.6 that support extended caching, you can keep cached prefixes active for up to 24 hours:
Audio Input
With the gpt-4o-audio-preview model, you can pass audio files to the model.
The gpt-4o-audio-preview model is currently in preview and requires at least
some audio inputs. It will not work with non-audio data.
Completion Models
You can create models that call the OpenAI completions API using the .completion() factory method.
The first argument is the model id.
Currently only gpt-3.5-turbo-instruct is supported.
OpenAI completion models support also some model specific settings that are not part of the standard call settings. You can pass them as an options argument:
The following optional provider options are available for OpenAI completion models:
-
echo: boolean
Echo back the prompt in addition to the completion.
-
logitBias Record<number, number>
Modifies the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
As an example, you can pass
{"50256": -100}to prevent the <|endoftext|> token from being generated. -
logprobs boolean | number
Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that were generated.
Setting to a number will return the log probabilities of the top n tokens that were generated.
-
suffix string
The suffix that comes after a completion of inserted text.
-
user string
A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more.
Model Capabilities
| Model | Image Input | Audio Input | Object Generation | Tool Usage |
|---|---|---|---|---|
gpt-6-astra | ||||
gpt-6.1-sol | ||||
gpt-6-luna | ||||
gpt-6-sol | ||||
gpt-5.6 | ||||
gpt-5.6-luna | ||||
gpt-5.6-sol | ||||
gpt-5.6-terra | ||||
gpt-5.5 | ||||
gpt-5.4-pro | ||||
gpt-5.4 | ||||
gpt-5.4-mini | ||||
gpt-5.4-nano | ||||
gpt-5.3-chat-latest | ||||
gpt-5.2-pro | ||||
gpt-5.2-chat-latest | ||||
gpt-5.2 | ||||
gpt-5.1-codex-mini | ||||
gpt-5.1-codex | ||||
gpt-5.1-chat-latest | ||||
gpt-5.1 | ||||
gpt-5-pro | ||||
gpt-5 | ||||
gpt-5-mini | ||||
gpt-5-nano | ||||
gpt-5-codex | ||||
gpt-5-chat-latest | ||||
gpt-4.1 | ||||
gpt-4.1-mini | ||||
gpt-4.1-nano | ||||
gpt-4o | ||||
gpt-4o-mini |
The table above lists popular models. Please see the OpenAI docs for a full list of available models. The table above lists popular models. You can also pass any available provider model ID as a string if needed.
Realtime Models
Use .experimental_realtime() for both OpenAI Realtime
and OpenAI Live models.
The OpenAI-only api option accepts 'live' or 'realtime' and takes precedence
over model-ID selection. Without it, the known gpt-live-1 ID uses Live and other
IDs retain the Realtime default. The provider does not switch APIs after a failed
request. Both model implementations use the existing experimental realtime interface.
Live supports browser WSS sessions through an application-owned relay with client
delegation, using experimental_useRealtime for the browser runtime, and optional
browser-direct WebRTC. Your application owns the agent and tool execution; Live
delegations do not invoke onToolCall. For a low-level server adapter, obtain server-only connection
settings with liveModel.getServerWebSocketConfig() and serialize commands with
liveModel.serializeClientEvent(). Create one parser per connection with
liveModel.createServerEventParser() and pass incoming JSON to the returned
function. It returns arrays of normalized events and retains each original event
in raw.
For a token-based Realtime API session, create a short-lived token on your
server with openai.experimental_realtime.getToken():
Live does not use Realtime client-secret minting. Calling getToken for a known
Live model or with api: 'live' rejects before a mint request. Live's WebSocket
connection authenticates on a trusted server; keep the provider API key out of
browser code. The API selector chooses a protocol, not a different authentication
capability for the same model.
Browser authentication to an application-owned relay is separate from OpenAI authentication. Protect that relay with your application's session or short-lived credential; an origin check alone is not user authentication. The relay uses its server-held OpenAI key upstream. Selecting a Live model does not make the Realtime client-secret endpoint compatible with the Live API.
For browser-direct Live WebRTC, an authenticated application endpoint performs the
SDP exchange through liveModel.doCreateWebRTCSession({ sdp, sessionConfig, abortSignal })
using the server's project key. The browser receives the
session connection answer, not the project key or a Realtime client secret. This
setup endpoint still needs application authentication. See the
experimental_useRealtime reference
for the api.session setup contract and the runnable example.
Live session options
Configure Live-specific settings through sessionConfig.providerOptions.openai,
typed with Experimental_OpenAIRealtimeModelLiveOptions. For example:
delegation: use{ type: 'client' }for application-owned work. Omission ornullalso selects client mode. Other delegation modes are unsupported.input: prior text messages with developer, user or assistant roles.voice: an authorized custom voice reference{ id }, mutually exclusive with the ordinarysessionConfig.voicestring.store: requests provider-side session storage; availability depends on the OpenAI project configuration.client.dataChannel: WebRTC startup permission policy withallowedClientEventsandallowedServerEvents. Set it on the application server, not from trusted-looking browser input. Omission retains the provider default;[]allows none and'all'allows all. Response event selectors use{ type: 'response.event', responseEvent: 'response.completed' }to select native nested events, which remain rawcustomevents rather than managed SDK responses. Keep readiness, errors, and terminal usage observable for the session features your application enables.
Send the initial WebSocket configuration with session-start; WebRTC starts the
session during SDP setup and negotiates audio formats through SDP. Live startup settings are
immutable: session-update is rejected. Use input-audio-mute and
input-audio-unmute for remote input processing; these commands do not release the
local microphone. Return application context through
context-append, using the opaque delegationId from delegation-created, or
null for context without a delegation. Its providerOptions.openai.channel
accepts instructions, thinking (the default), or commentary.
For graceful shutdown, install a session-closed listener before sending session-close;
that event confirms final voice usage. session-usage contains cumulative seconds,
so replace earlier snapshots rather than adding them.
For the browser integration, see the
experimental_useRealtime reference.
It covers the JSON/PCM16 WebSocket relay runtime, optional WebRTC setup and permission
policy, microphone and playback ownership, session.delegations, sendEvent for
application context, and close() for bounded finalization. Use wss: for production
relays. Continuous conversation semantics do not imply browser support for every
provider codec or transport. The Realtime guide covers
legacy token-based, turn-based sessions.
Embedding Models
You can create models that call the OpenAI embeddings API
using the .embedding() factory method.
OpenAI embedding models support several additional provider options. You can pass them as an options argument:
The following optional provider options are available for OpenAI embedding models:
-
dimensions: number
The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.
-
user string
A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more.
Model Capabilities
| Model | Default Dimensions | Custom Dimensions |
|---|---|---|
text-embedding-3-large | 3072 | |
text-embedding-3-small | 1536 | |
text-embedding-ada-002 | 1536 |
Image Models
You can create models that call the OpenAI image generation API
using the .image() factory method.
Dall-E models do not support the aspectRatio parameter. Use the size
parameter instead.
Image Editing
OpenAI's gpt-image-* models support powerful image editing capabilities. Pass input images via prompt.images to transform, combine, or edit existing images.
Basic Image Editing
Transform an existing image using text prompts:
Inpainting with Mask
Edit specific parts of an image using a mask. Transparent areas in the mask indicate where the image should be edited:
Background Removal
Remove the background from an image by setting background to transparent on a model that supports transparent backgrounds:
Multi-Image Combining
Combine multiple reference images into a single output. gpt-image-* models support up to 16 input images:
Input images can be provided as Buffer, ArrayBuffer, Uint8Array, or
base64-encoded strings. For gpt-image-* models, each image should be a
png, webp, or jpg file less than 50MB.
Model Capabilities
| Model | Sizes |
|---|---|
gpt-image-2.5-flare | Standard presets and custom dimensions |
gpt-image-2.5-sunburst | Standard presets and custom dimensions |
gpt-image-2 | 1024x1024, 1536x1024, 1024x1536 |
gpt-image-1.5 | 1024x1024, 1536x1024, 1024x1536 |
gpt-image-1-mini | 1024x1024, 1536x1024, 1024x1536 |
gpt-image-1 | 1024x1024, 1536x1024, 1024x1536 |
dall-e-3 | 1024x1024, 1792x1024, 1024x1792 |
dall-e-2 | 256x256, 512x512, 1024x1024 |
Use gpt-image-2.5-flare for fast, general-purpose image generation and
gpt-image-2.5-sunburst when editing precision and instruction following are
the priority. Both models accept custom WIDTHxHEIGHT sizes whose dimensions
are multiples of 16, with aspect ratios from 1:3 through 3:1, no edge longer
than 3840 pixels, and a total area from 655,360 through 8,294,400 pixels.
Resolutions above 2560x1440 are experimental.
You can pass optional providerOptions to the image model. These are prone to change by OpenAI and are model dependent. For example, the gpt-image-* models support the quality option:
The gpt-image-2.5-flare and gpt-image-2.5-sunburst models also support
quality: 'xhigh' and quality: 'max' for both image generation and editing:
For more on generateImage() see Image Generation.
OpenAI's image models return additional metadata in the response that can be
accessed via providerMetadata.openai. The following OpenAI-specific metadata
is available:
-
images Array<object>
Array of image-specific metadata. Each image object may contain:
revisedPromptstring - The revised prompt that was actually used to generate the image (OpenAI may modify your prompt for safety or clarity)creatednumber - The Unix timestamp (in seconds) of when the image was createdsizestring - The size of the generated image. One of1024x1024,1024x1536, or1536x1024qualitystring - The quality of the generated image. One oflow,medium,high,xhigh, ormaxbackgroundstring - The background parameter used for the image generation. EithertransparentoropaqueoutputFormatstring - The output format of the generated image. One ofpng,webp, orjpeg
For more information on the available OpenAI image model options, see the OpenAI API reference.
Transcription Models
You can create models that call the OpenAI transcription API
using the .transcription() factory method.
The first argument is the model id e.g. gpt-4o-transcribe.
You can also pass additional provider-specific options using the providerOptions argument. For example, supplying the input language in ISO-639-1 (e.g. en) format will improve accuracy and latency.
To get word-level timestamps, specify the granularity:
gpt-4o-transcribe-diarize identifies speakers in a recording. It defaults to
the diarized_json response format and automatic chunking:
The following provider options are available:
-
timestampGranularities string[] The granularity of the timestamps in the transcription. Defaults to
['segment']. Possible values are['word'],['segment'], and['word', 'segment']. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. -
language string The language of the input audio. Supplying the input language in ISO-639-1 format (e.g. 'en') will improve accuracy and latency. Optional.
-
prompt string An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language. Optional.
-
temperature number The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. Defaults to 0. Optional.
-
include string[] Additional information to include in the transcription response.
-
responseFormat 'json' | 'verbose_json' | 'diarized_json' The format of the transcription response.
gpt-4o-transcribe-diarizedefaults todiarized_json. -
chunkingStrategy 'auto' | object Controls how the audio is split into chunks.
gpt-4o-transcribe-diarizedefaults to'auto'; provide this option to override the default. The object form configures OpenAI server-side VAD withtype: 'server_vad'and optionalthreshold,prefixPaddingMs, andsilenceDurationMsfields. -
streaming object Options for streaming transcription models such as
gpt-realtime-whisper. Use withexperimental_streamTranscribe.-
delay 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' Latency/accuracy tradeoff for realtime transcription.
-
include string[] Additional fields to include in realtime transcription events, such as
item.input_audio_transcription.logprobs.
-
Model Capabilities
| Model | Transcription | Streaming | Duration | Segments | Language |
|---|---|---|---|---|---|
whisper-1 | |||||
gpt-4o-mini-transcribe | |||||
gpt-4o-transcribe | |||||
gpt-4o-transcribe-diarize | |||||
gpt-realtime-whisper |
Translation Models
You can create models that translate live speech over the OpenAI Realtime
translations WebSocket using the .translation() factory method. Translation
models are streaming-only and are used with
experimental_streamTranslate.
The first argument is the model id e.g. gpt-realtime-translate.
The OpenAI Realtime translation API auto-detects the source language
(sourceLanguage is not supported), accepts 24kHz 16-bit PCM input, and always
outputs 24kHz 16-bit PCM audio (outputAudioFormat is not supported).
Unsupported source and output settings surface as call warnings.
Model Capabilities
| Model | Translated Audio | Translated Text | Source Transcript |
|---|---|---|---|
gpt-realtime-translate |
Speech Models
You can create models that call the OpenAI speech API
using the .speech() factory method.
The first argument is the model id e.g. gpt-4o-mini-tts.
The voice argument can be set to one of OpenAI's available voices: alloy, ash, coral, echo, fable, onyx, nova, sage, or shimmer.
You can also pass additional provider-specific options using the providerOptions argument:
-
instructions string Control the voice of your generated audio with additional instructions e.g. "Speak in a slow and steady tone". Does not work with
tts-1ortts-1-hd. Optional. -
speed number The speed of the generated audio. Select a value from 0.25 to 4.0. Defaults to 1.0. Optional.
Model Capabilities
| Model | Instructions |
|---|---|
tts-1 | |
tts-1-hd | |
gpt-4o-mini-tts |
Decision Models
Create an experimental decision model with openai.decisionModel(modelId).
It uses the native Decisions API
to answer Choice, Score, and Boolean questions with gpt-6-luna.
Scores are probability-weighted fractional positions on the ordered rubric, starting
at zero. Choice labels are returned exactly as supplied. Choice and Score answers
include probability distributions. Boolean questions use the API's predicate
primitive and return P(true). Apply thresholds in application code, for example
answers.requestsRefund.probability >= 0.5.
Structured state, instructions, and criterion descriptions are serialized as JSON
text. Score levels receive zero-based index labels. Non-null Boolean criteria are
appended to predicate instructions under Criteria for true: and Criteria for false:.
String criteria are passed through; structured criteria are serialized as JSON text.
Image file parts in state are sent as inline images. Set imageDetail in a file
part's providerOptions.openai to 'low', 'high', 'auto', or 'original' to
choose its detail level:
The factory respects createOpenAI settings, including custom fetch and base URL.
Set providerOptions.openai.safetyIdentifier to an opaque end-user identifier for
safety monitoring (up to 128 characters). For example:
Import OpenAIDecisionModelOptions from @ai-sdk/openai when using the type above.
Other OpenAI options are unsupported and produce warnings. Native confidence
values are available in providerMetadata.openai.confidence, keyed by question ID.
Input and output token counts are available in usage. The full native token usage
(including cache, reasoning, and total counts) is preserved in
providerMetadata.openai.usage. Response headers, the returned model ID, and the
raw response body are preserved. If OpenAI refuses a question, the entire call
throws InvalidResponseDataError with the question name and the raw response in
error.data. Invalid answers also fail the entire decision.
See Decisions.
Decision models can also be accessed through customProvider aliases or
createProviderRegistry().decisionModel('provider:model'). Direct string IDs
use Gateway by default, or an explicitly configured default provider with an
decisionModel method. See
model aliases and registries.