@depup/ai-sdk__openai 3.0.41-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +3101 -0
  2. package/LICENSE +13 -0
  3. package/README.md +25 -0
  4. package/changes.json +5 -0
  5. package/dist/index.d.mts +1107 -0
  6. package/dist/index.d.ts +1107 -0
  7. package/dist/index.js +6408 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +6493 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/internal/index.d.mts +1137 -0
  12. package/dist/internal/index.d.ts +1137 -0
  13. package/dist/internal/index.js +6256 -0
  14. package/dist/internal/index.js.map +1 -0
  15. package/dist/internal/index.mjs +6306 -0
  16. package/dist/internal/index.mjs.map +1 -0
  17. package/docs/03-openai.mdx +2396 -0
  18. package/internal.d.ts +1 -0
  19. package/package.json +96 -0
  20. package/src/chat/convert-openai-chat-usage.ts +57 -0
  21. package/src/chat/convert-to-openai-chat-messages.ts +225 -0
  22. package/src/chat/get-response-metadata.ts +15 -0
  23. package/src/chat/map-openai-finish-reason.ts +19 -0
  24. package/src/chat/openai-chat-api.ts +198 -0
  25. package/src/chat/openai-chat-language-model.ts +703 -0
  26. package/src/chat/openai-chat-options.ts +192 -0
  27. package/src/chat/openai-chat-prepare-tools.ts +84 -0
  28. package/src/chat/openai-chat-prompt.ts +70 -0
  29. package/src/completion/convert-openai-completion-usage.ts +46 -0
  30. package/src/completion/convert-to-openai-completion-prompt.ts +93 -0
  31. package/src/completion/get-response-metadata.ts +15 -0
  32. package/src/completion/map-openai-finish-reason.ts +19 -0
  33. package/src/completion/openai-completion-api.ts +81 -0
  34. package/src/completion/openai-completion-language-model.ts +336 -0
  35. package/src/completion/openai-completion-options.ts +61 -0
  36. package/src/embedding/openai-embedding-api.ts +13 -0
  37. package/src/embedding/openai-embedding-model.ts +95 -0
  38. package/src/embedding/openai-embedding-options.ts +30 -0
  39. package/src/image/openai-image-api.ts +35 -0
  40. package/src/image/openai-image-model.ts +349 -0
  41. package/src/image/openai-image-options.ts +31 -0
  42. package/src/index.ts +23 -0
  43. package/src/internal/index.ts +19 -0
  44. package/src/openai-config.ts +18 -0
  45. package/src/openai-error.ts +22 -0
  46. package/src/openai-language-model-capabilities.ts +52 -0
  47. package/src/openai-provider.ts +270 -0
  48. package/src/openai-tools.ts +126 -0
  49. package/src/responses/convert-openai-responses-usage.ts +53 -0
  50. package/src/responses/convert-to-openai-responses-input.ts +735 -0
  51. package/src/responses/map-openai-responses-finish-reason.ts +22 -0
  52. package/src/responses/openai-responses-api.ts +1260 -0
  53. package/src/responses/openai-responses-language-model.ts +2098 -0
  54. package/src/responses/openai-responses-options.ts +299 -0
  55. package/src/responses/openai-responses-prepare-tools.ts +408 -0
  56. package/src/responses/openai-responses-provider-metadata.ts +62 -0
  57. package/src/speech/openai-speech-api.ts +38 -0
  58. package/src/speech/openai-speech-model.ts +137 -0
  59. package/src/speech/openai-speech-options.ts +26 -0
  60. package/src/tool/apply-patch.ts +141 -0
  61. package/src/tool/code-interpreter.ts +104 -0
  62. package/src/tool/custom.ts +64 -0
  63. package/src/tool/file-search.ts +145 -0
  64. package/src/tool/image-generation.ts +126 -0
  65. package/src/tool/local-shell.ts +72 -0
  66. package/src/tool/mcp.ts +125 -0
  67. package/src/tool/shell.ts +203 -0
  68. package/src/tool/web-search-preview.ts +141 -0
  69. package/src/tool/web-search.ts +181 -0
  70. package/src/transcription/openai-transcription-api.ts +37 -0
  71. package/src/transcription/openai-transcription-model.ts +232 -0
  72. package/src/transcription/openai-transcription-options.ts +53 -0
  73. package/src/transcription/transcription-test.mp3 +0 -0
  74. package/src/version.ts +6 -0
@@ -0,0 +1,2396 @@
1
+ ---
2
+ title: OpenAI
3
+ description: Learn how to use the OpenAI provider for the AI SDK.
4
+ ---
5
+
6
+ # OpenAI Provider
7
+
8
+ The [OpenAI](https://openai.com/) provider contains language model support for the OpenAI responses, chat, and completion APIs, as well as embedding model support for the OpenAI embeddings API.
9
+
10
+ ## Setup
11
+
12
+ The OpenAI provider is available in the `@ai-sdk/openai` module. You can install it with
13
+
14
+ <Tabs items={['pnpm', 'npm', 'yarn', 'bun']}>
15
+ <Tab>
16
+ <Snippet text="pnpm add @ai-sdk/openai" dark />
17
+ </Tab>
18
+ <Tab>
19
+ <Snippet text="npm install @ai-sdk/openai" dark />
20
+ </Tab>
21
+ <Tab>
22
+ <Snippet text="yarn add @ai-sdk/openai" dark />
23
+ </Tab>
24
+
25
+ <Tab>
26
+ <Snippet text="bun add @ai-sdk/openai" dark />
27
+ </Tab>
28
+ </Tabs>
29
+
30
+ ## Provider Instance
31
+
32
+ You can import the default provider instance `openai` from `@ai-sdk/openai`:
33
+
34
+ ```ts
35
+ import { openai } from '@ai-sdk/openai';
36
+ ```
37
+
38
+ If you need a customized setup, you can import `createOpenAI` from `@ai-sdk/openai` and create a provider instance with your settings:
39
+
40
+ ```ts
41
+ import { createOpenAI } from '@ai-sdk/openai';
42
+
43
+ const openai = createOpenAI({
44
+ // custom settings, e.g.
45
+ headers: {
46
+ 'header-name': 'header-value',
47
+ },
48
+ });
49
+ ```
50
+
51
+ You can use the following optional settings to customize the OpenAI provider instance:
52
+
53
+ - **baseURL** _string_
54
+
55
+ Use a different URL prefix for API calls, e.g. to use proxy servers.
56
+ The default prefix is `https://api.openai.com/v1`.
57
+
58
+ - **apiKey** _string_
59
+
60
+ API key that is being sent using the `Authorization` header.
61
+ It defaults to the `OPENAI_API_KEY` environment variable.
62
+
63
+ - **name** _string_
64
+
65
+ The provider name. You can set this when using OpenAI compatible providers
66
+ to change the model provider property. Defaults to `openai`.
67
+
68
+ - **organization** _string_
69
+
70
+ OpenAI Organization.
71
+
72
+ - **project** _string_
73
+
74
+ OpenAI project.
75
+
76
+ - **headers** _Record&lt;string,string&gt;_
77
+
78
+ Custom headers to include in the requests.
79
+
80
+ - **fetch** _(input: RequestInfo, init?: RequestInit) => Promise&lt;Response&gt;_
81
+
82
+ Custom [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) implementation.
83
+ Defaults to the global `fetch` function.
84
+ You can use it as a middleware to intercept requests,
85
+ or to provide a custom fetch implementation for e.g. testing.
86
+
87
+ ## Language Models
88
+
89
+ The OpenAI provider instance is a function that you can invoke to create a language model:
90
+
91
+ ```ts
92
+ const model = openai('gpt-5');
93
+ ```
94
+
95
+ It automatically selects the correct API based on the model id.
96
+ You can also pass additional settings in the second argument:
97
+
98
+ ```ts
99
+ const model = openai('gpt-5', {
100
+ // additional settings
101
+ });
102
+ ```
103
+
104
+ The available options depend on the API that's automatically chosen for the model (see below).
105
+ If you want to explicitly select a specific model API, you can use `.responses`, `.chat`, or `.completion`.
106
+
107
+ <Note>
108
+ Since AI SDK 5, the OpenAI responses API is called by default (unless you
109
+ specify e.g. 'openai.chat')
110
+ </Note>
111
+
112
+ ### Example
113
+
114
+ You can use OpenAI language models to generate text with the `generateText` function:
115
+
116
+ ```ts
117
+ import { openai } from '@ai-sdk/openai';
118
+ import { generateText } from 'ai';
119
+
120
+ const { text } = await generateText({
121
+ model: openai('gpt-5'),
122
+ prompt: 'Write a vegetarian lasagna recipe for 4 people.',
123
+ });
124
+ ```
125
+
126
+ OpenAI language models can also be used in the `streamText` function
127
+ and support structured data generation with [`Output`](/docs/reference/ai-sdk-core/output)
128
+ (see [AI SDK Core](/docs/ai-sdk-core)).
129
+
130
+ ### Responses Models
131
+
132
+ 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).
133
+
134
+ ```ts
135
+ const model = openai('gpt-5');
136
+ ```
137
+
138
+ Further configuration can be done using OpenAI provider options.
139
+ You can validate the provider options using the `OpenAILanguageModelResponsesOptions` type.
140
+
141
+ ```ts
142
+ import { openai, OpenAILanguageModelResponsesOptions } from '@ai-sdk/openai';
143
+ import { generateText } from 'ai';
144
+
145
+ const result = await generateText({
146
+ model: openai('gpt-5'), // or openai.responses('gpt-5')
147
+ providerOptions: {
148
+ openai: {
149
+ parallelToolCalls: false,
150
+ store: false,
151
+ user: 'user_123',
152
+ // ...
153
+ } satisfies OpenAILanguageModelResponsesOptions,
154
+ },
155
+ // ...
156
+ });
157
+ ```
158
+
159
+ The following provider options are available:
160
+
161
+ - **parallelToolCalls** _boolean_
162
+ Whether to use parallel tool calls. Defaults to `true`.
163
+
164
+ - **store** _boolean_
165
+
166
+ Whether to store the generation. Defaults to `true`.
167
+
168
+ - **maxToolCalls** _integer_
169
+ The maximum number of total calls to built-in tools that can be processed in a response.
170
+ This maximum number applies across all built-in tool calls, not per individual tool.
171
+ Any further attempts to call a tool by the model will be ignored.
172
+
173
+ - **metadata** _Record&lt;string, string&gt;_
174
+ Additional metadata to store with the generation.
175
+
176
+ - **conversation** _string_
177
+ The ID of the OpenAI Conversation to continue.
178
+ You must create a conversation first via the [OpenAI API](https://platform.openai.com/docs/api-reference/conversations/create).
179
+ Cannot be used in conjunction with `previousResponseId`.
180
+ Defaults to `undefined`.
181
+
182
+ - **previousResponseId** _string_
183
+ The ID of the previous response. You can use it to continue a conversation. Defaults to `undefined`.
184
+
185
+ - **instructions** _string_
186
+ Instructions for the model.
187
+ They can be used to change the system or developer message when continuing a conversation using the `previousResponseId` option.
188
+ Defaults to `undefined`.
189
+
190
+ - **logprobs** _boolean | number_
191
+ 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` returns 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.
192
+
193
+ - **user** _string_
194
+ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Defaults to `undefined`.
195
+
196
+ - **reasoningEffort** _'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'_
197
+ Reasoning effort for reasoning models. Defaults to `medium`. If you use `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored.
198
+
199
+ <Note>
200
+ The 'none' type for `reasoningEffort` is only available for OpenAI's GPT-5.1
201
+ models. Also, the 'xhigh' type for `reasoningEffort` is only available for
202
+ OpenAI's GPT-5.1-Codex-Max model. Setting `reasoningEffort` to 'none' or
203
+ 'xhigh' with unsupported models will result in an error.
204
+ </Note>
205
+
206
+ - **reasoningSummary** _'auto' | 'detailed'_
207
+ Controls whether the model returns its reasoning process. Set to `'auto'` for a condensed summary, `'detailed'` for more comprehensive reasoning. Defaults to `undefined` (no reasoning summaries). When enabled, reasoning summaries appear in the stream as events with type `'reasoning'` and in non-streaming responses within the `reasoning` field.
208
+
209
+ - **strictJsonSchema** _boolean_
210
+ Whether to use strict JSON schema validation. Defaults to `true`.
211
+
212
+ <Note type="warning">
213
+ OpenAI structured outputs have several
214
+ [limitations](https://openai.com/index/introducing-structured-outputs-in-the-api),
215
+ in particular around the [supported
216
+ schemas](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas),
217
+ and are therefore opt-in. For example, optional schema properties are not
218
+ supported. You need to change Zod `.nullish()` and `.optional()` to
219
+ `.nullable()`.
220
+ </Note>
221
+
222
+ - **serviceTier** _'auto' | 'flex' | 'priority' | 'default'_
223
+ Service tier for the request. Set to 'flex' for 50% cheaper processing
224
+ at the cost of increased latency (available for o3, o4-mini, and gpt-5 models).
225
+ 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).
226
+
227
+ Defaults to 'auto'.
228
+
229
+ - **textVerbosity** _'low' | 'medium' | 'high'_
230
+ Controls the verbosity of the model's response. Lower values result in more concise responses,
231
+ while higher values result in more verbose responses. Defaults to `'medium'`.
232
+
233
+ - **include** _Array&lt;string&gt;_
234
+ Specifies additional content to include in the response. Supported values:
235
+ `['file_search_call.results']` for including file search results in responses.
236
+ `['message.output_text.logprobs']` for logprobs.
237
+ Defaults to `undefined`.
238
+
239
+ - **truncation** _string_
240
+ The truncation strategy to use for the model response.
241
+
242
+ - 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.
243
+ - disabled (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error.
244
+
245
+ - **promptCacheKey** _string_
246
+ A cache key for manual prompt caching control. Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
247
+
248
+ - **promptCacheRetention** _'in_memory' | '24h'_
249
+ The retention policy for the prompt cache. Set to `'24h'` to enable extended prompt caching, which keeps cached prefixes active for up to 24 hours. Defaults to `'in_memory'` for standard prompt caching. Note: `'24h'` is currently only available for the 5.1 series of models.
250
+
251
+ - **safetyIdentifier** _string_
252
+ 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.
253
+
254
+ - **systemMessageMode** _'system' | 'developer' | 'remove'_
255
+ Controls the role of the system message when making requests. By default (when omitted), for models that support reasoning the `system` message is automatically converted to a `developer` message. Setting `systemMessageMode` to `system` passes the system message as a system-level instruction; `developer` passes it as a developer message; `remove` omits the system message from the request.
256
+
257
+ - **forceReasoning** _boolean_
258
+ 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 `systemMessageMode` to `developer` unless overridden.
259
+
260
+ The OpenAI responses provider also returns provider-specific metadata:
261
+
262
+ For Responses models, you can type this metadata using `OpenaiResponsesProviderMetadata`:
263
+
264
+ ```ts
265
+ import { openai, type OpenaiResponsesProviderMetadata } from '@ai-sdk/openai';
266
+ import { generateText } from 'ai';
267
+
268
+ const result = await generateText({
269
+ model: openai('gpt-5'),
270
+ });
271
+
272
+ const providerMetadata = result.providerMetadata as
273
+ | OpenaiResponsesProviderMetadata
274
+ | undefined;
275
+
276
+ const { responseId, logprobs, serviceTier } = providerMetadata?.openai ?? {};
277
+
278
+ // responseId can be used to continue a conversation (previousResponseId).
279
+ console.log(responseId);
280
+ ```
281
+
282
+ The following OpenAI-specific metadata may be returned:
283
+
284
+ - **responseId** _string | null | undefined_
285
+ The ID of the response. Can be used to continue a conversation.
286
+ - **logprobs** _(optional)_
287
+ Log probabilities of output tokens (when enabled).
288
+ - **serviceTier** _(optional)_
289
+ Service tier information returned by the API.
290
+
291
+ #### Reasoning Output
292
+
293
+ For reasoning models like `gpt-5`, 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.
294
+
295
+ ```ts highlight="8-9,16"
296
+ import {
297
+ openai,
298
+ type OpenAILanguageModelResponsesOptions,
299
+ } from '@ai-sdk/openai';
300
+ import { streamText } from 'ai';
301
+
302
+ const result = streamText({
303
+ model: openai('gpt-5'),
304
+ prompt: 'Tell me about the Mission burrito debate in San Francisco.',
305
+ providerOptions: {
306
+ openai: {
307
+ reasoningSummary: 'detailed', // 'auto' for condensed or 'detailed' for comprehensive
308
+ } satisfies OpenAILanguageModelResponsesOptions,
309
+ },
310
+ });
311
+
312
+ for await (const part of result.fullStream) {
313
+ if (part.type === 'reasoning') {
314
+ console.log(`Reasoning: ${part.textDelta}`);
315
+ } else if (part.type === 'text-delta') {
316
+ process.stdout.write(part.textDelta);
317
+ }
318
+ }
319
+ ```
320
+
321
+ For non-streaming calls with `generateText`, the reasoning summaries are available in the `reasoning` field of the response:
322
+
323
+ ```ts highlight="8-9,13"
324
+ import {
325
+ openai,
326
+ type OpenAILanguageModelResponsesOptions,
327
+ } from '@ai-sdk/openai';
328
+ import { generateText } from 'ai';
329
+
330
+ const result = await generateText({
331
+ model: openai('gpt-5'),
332
+ prompt: 'Tell me about the Mission burrito debate in San Francisco.',
333
+ providerOptions: {
334
+ openai: {
335
+ reasoningSummary: 'auto',
336
+ } satisfies OpenAILanguageModelResponsesOptions,
337
+ },
338
+ });
339
+ console.log('Reasoning:', result.reasoning);
340
+ ```
341
+
342
+ Learn more about reasoning summaries in the [OpenAI documentation](https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries).
343
+
344
+ #### WebSocket Transport
345
+
346
+ OpenAI's [WebSocket API](https://developers.openai.com/api/docs/guides/websocket-mode) keeps a persistent connection open, which can significantly
347
+ reduce Time-to-First-Byte (TTFB) in agentic workflows with many tool calls.
348
+ After the initial connection, subsequent requests skip TCP/TLS/HTTP negotiation entirely.
349
+
350
+ The [`ai-sdk-openai-websocket-fetch`](https://www.npmjs.com/package/ai-sdk-openai-websocket-fetch)
351
+ package provides a drop-in `fetch` replacement that routes streaming requests
352
+ through a persistent WebSocket connection.
353
+
354
+ <Tabs items={['pnpm', 'npm', 'yarn', 'bun']}>
355
+ <Tab>
356
+ <Snippet text="pnpm add ai-sdk-openai-websocket-fetch" dark />
357
+ </Tab>
358
+ <Tab>
359
+ <Snippet text="npm install ai-sdk-openai-websocket-fetch" dark />
360
+ </Tab>
361
+ <Tab>
362
+ <Snippet text="yarn add ai-sdk-openai-websocket-fetch" dark />
363
+ </Tab>
364
+ <Tab>
365
+ <Snippet text="bun add ai-sdk-openai-websocket-fetch" dark />
366
+ </Tab>
367
+ </Tabs>
368
+
369
+ Pass the WebSocket fetch to `createOpenAI` via the `fetch` option:
370
+
371
+ ```ts highlight="2,6-7,15"
372
+ import { createOpenAI } from '@ai-sdk/openai';
373
+ import { createWebSocketFetch } from 'ai-sdk-openai-websocket-fetch';
374
+ import { streamText } from 'ai';
375
+
376
+ // Create a WebSocket-backed fetch instance
377
+ const wsFetch = createWebSocketFetch();
378
+ const openai = createOpenAI({ fetch: wsFetch });
379
+
380
+ const result = streamText({
381
+ model: openai('gpt-4.1-mini'),
382
+ prompt: 'Hello!',
383
+ tools: {
384
+ // ...
385
+ },
386
+ onFinish: () => wsFetch.close(), // close the WebSocket when done
387
+ });
388
+ ```
389
+
390
+ The first request will be slower because it must establish the WebSocket connection
391
+ (DNS + TCP + TLS + WebSocket upgrade). After that, subsequent steps in a
392
+ multi-step tool-calling loop reuse the open connection, resulting in lower TTFB
393
+ per step.
394
+
395
+ <Note>
396
+ The WebSocket transport only routes streaming requests to the OpenAI Responses
397
+ API (`POST /responses` with `stream: true`) through the WebSocket. All other
398
+ requests (non-streaming, embeddings, etc.) fall through to the standard
399
+ `fetch` implementation.
400
+ </Note>
401
+
402
+ You can see a live side-by-side comparison of HTTP vs WebSocket streaming performance
403
+ in the [demo app](https://github.com/vercel-labs/ai-sdk-openai-websocket).
404
+
405
+ #### Verbosity Control
406
+
407
+ You can control the length and detail of model responses using the `textVerbosity` parameter:
408
+
409
+ ```ts
410
+ import {
411
+ openai,
412
+ type OpenAILanguageModelResponsesOptions,
413
+ } from '@ai-sdk/openai';
414
+ import { generateText } from 'ai';
415
+
416
+ const result = await generateText({
417
+ model: openai('gpt-5-mini'),
418
+ prompt: 'Write a poem about a boy and his first pet dog.',
419
+ providerOptions: {
420
+ openai: {
421
+ textVerbosity: 'low', // 'low' for concise, 'medium' (default), or 'high' for verbose
422
+ } satisfies OpenAILanguageModelResponsesOptions,
423
+ },
424
+ });
425
+ ```
426
+
427
+ The `textVerbosity` parameter scales output length without changing the underlying prompt:
428
+
429
+ - `'low'`: Produces terse, minimal responses
430
+ - `'medium'`: Balanced detail (default)
431
+ - `'high'`: Verbose responses with comprehensive detail
432
+
433
+ #### Web Search Tool
434
+
435
+ The OpenAI responses API supports web search through the `openai.tools.webSearch` tool.
436
+
437
+ ```ts
438
+ const result = await generateText({
439
+ model: openai('gpt-5'),
440
+ prompt: 'What happened in San Francisco last week?',
441
+ tools: {
442
+ web_search: openai.tools.webSearch({
443
+ // optional configuration:
444
+ externalWebAccess: true,
445
+ searchContextSize: 'high',
446
+ userLocation: {
447
+ type: 'approximate',
448
+ city: 'San Francisco',
449
+ region: 'California',
450
+ },
451
+ filters: {
452
+ allowedDomains: ['sfchronicle.com', 'sfgate.com'],
453
+ },
454
+ }),
455
+ },
456
+ // Force web search tool (optional):
457
+ toolChoice: { type: 'tool', toolName: 'web_search' },
458
+ });
459
+
460
+ // URL sources directly from `results`
461
+ const sources = result.sources;
462
+
463
+ // Or access sources from tool results
464
+ for (const toolResult of result.toolResults) {
465
+ if (toolResult.toolName === 'web_search') {
466
+ console.log('Query:', toolResult.output.action.query);
467
+ console.log('Sources:', toolResult.output.sources);
468
+ // `sources` is an array of object: { type: 'url', url: string }
469
+ }
470
+ }
471
+ ```
472
+
473
+ The web search tool supports the following configuration options:
474
+
475
+ - **externalWebAccess** _boolean_ - Whether to use external web access for fetching live content. Defaults to `true`.
476
+ - **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.
477
+ - **userLocation** - Optional location information to provide geographically relevant results. Includes `type` (always `'approximate'`), `country`, `city`, `region`, and `timezone`.
478
+ - **filters** - Optional filter configuration to restrict search results.
479
+ - **allowedDomains** _string[]_ - Array of allowed domains for the search. Subdomains of the provided domains are automatically included.
480
+
481
+ For detailed information on configuration options see the [OpenAI Web Search Tool documentation](https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses).
482
+
483
+ #### File Search Tool
484
+
485
+ The OpenAI responses API supports file search through the `openai.tools.fileSearch` tool.
486
+
487
+ You can force the use of the file search tool by setting the `toolChoice` parameter to `{ type: 'tool', toolName: 'file_search' }`.
488
+
489
+ ```ts
490
+ const result = await generateText({
491
+ model: openai('gpt-5'),
492
+ prompt: 'What does the document say about user authentication?',
493
+ tools: {
494
+ file_search: openai.tools.fileSearch({
495
+ vectorStoreIds: ['vs_123'],
496
+ // configuration below is optional:
497
+ maxNumResults: 5,
498
+ filters: {
499
+ key: 'author',
500
+ type: 'eq',
501
+ value: 'Jane Smith',
502
+ },
503
+ ranking: {
504
+ ranker: 'auto',
505
+ scoreThreshold: 0.5,
506
+ },
507
+ }),
508
+ },
509
+ providerOptions: {
510
+ openai: {
511
+ // optional: include results
512
+ include: ['file_search_call.results'],
513
+ } satisfies OpenAILanguageModelResponsesOptions,
514
+ },
515
+ });
516
+ ```
517
+
518
+ The file search tool supports filtering with both comparison and compound filters:
519
+
520
+ **Comparison filters** - Filter by a single attribute:
521
+
522
+ - `eq` - Equal to
523
+ - `ne` - Not equal to
524
+ - `gt` - Greater than
525
+ - `gte` - Greater than or equal to
526
+ - `lt` - Less than
527
+ - `lte` - Less than or equal to
528
+ - `in` - Value is in array
529
+ - `nin` - Value is not in array
530
+
531
+ ```ts
532
+ // Single comparison filter
533
+ filters: { key: 'year', type: 'gte', value: 2023 }
534
+
535
+ // Filter with array values
536
+ filters: { key: 'status', type: 'in', value: ['published', 'reviewed'] }
537
+ ```
538
+
539
+ **Compound filters** - Combine multiple filters with `and` or `or`:
540
+
541
+ ```ts
542
+ // Compound filter with AND
543
+ filters: {
544
+ type: 'and',
545
+ filters: [
546
+ { key: 'author', type: 'eq', value: 'Jane Smith' },
547
+ { key: 'year', type: 'gte', value: 2023 },
548
+ ],
549
+ }
550
+
551
+ // Compound filter with OR
552
+ filters: {
553
+ type: 'or',
554
+ filters: [
555
+ { key: 'department', type: 'eq', value: 'Engineering' },
556
+ { key: 'department', type: 'eq', value: 'Research' },
557
+ ],
558
+ }
559
+ ```
560
+
561
+ #### Image Generation Tool
562
+
563
+ OpenAI's Responses API supports multi-modal image generation as a provider-defined tool.
564
+ Availability is restricted to specific models (for example, `gpt-5` variants).
565
+
566
+ You can use the image tool with either `generateText` or `streamText`:
567
+
568
+ ```ts
569
+ import { openai } from '@ai-sdk/openai';
570
+ import { generateText } from 'ai';
571
+
572
+ const result = await generateText({
573
+ model: openai('gpt-5'),
574
+ prompt:
575
+ 'Generate an image of an echidna swimming across the Mozambique channel.',
576
+ tools: {
577
+ image_generation: openai.tools.imageGeneration({ outputFormat: 'webp' }),
578
+ },
579
+ });
580
+
581
+ for (const toolResult of result.staticToolResults) {
582
+ if (toolResult.toolName === 'image_generation') {
583
+ const base64Image = toolResult.output.result;
584
+ }
585
+ }
586
+ ```
587
+
588
+ ```ts
589
+ import { openai } from '@ai-sdk/openai';
590
+ import { streamText } from 'ai';
591
+
592
+ const result = streamText({
593
+ model: openai('gpt-5'),
594
+ prompt:
595
+ 'Generate an image of an echidna swimming across the Mozambique channel.',
596
+ tools: {
597
+ image_generation: openai.tools.imageGeneration({
598
+ outputFormat: 'webp',
599
+ quality: 'low',
600
+ }),
601
+ },
602
+ });
603
+
604
+ for await (const part of result.fullStream) {
605
+ if (part.type == 'tool-result' && !part.dynamic) {
606
+ const base64Image = part.output.result;
607
+ }
608
+ }
609
+ ```
610
+
611
+ <Note>
612
+ When you set `store: false`, then previously generated images will not be
613
+ accessible by the model. We recommend using the image generation tool without
614
+ setting `store: false`.
615
+ </Note>
616
+
617
+ For complete details on model availability, image quality controls, supported sizes, and tool-specific parameters,
618
+ refer to the OpenAI documentation:
619
+
620
+ - Image generation overview and models: [OpenAI Image Generation](https://platform.openai.com/docs/guides/image-generation)
621
+ - Image generation tool parameters (background, size, quality, format, etc.): [Image Generation Tool Options](https://platform.openai.com/docs/guides/tools-image-generation#tool-options)
622
+
623
+ #### Code Interpreter Tool
624
+
625
+ The OpenAI responses API supports the code interpreter tool through the `openai.tools.codeInterpreter` tool.
626
+ This allows models to write and execute Python code.
627
+
628
+ ```ts
629
+ import { openai } from '@ai-sdk/openai';
630
+ import { generateText } from 'ai';
631
+
632
+ const result = await generateText({
633
+ model: openai('gpt-5'),
634
+ prompt: 'Write and run Python code to calculate the factorial of 10',
635
+ tools: {
636
+ code_interpreter: openai.tools.codeInterpreter({
637
+ // optional configuration:
638
+ container: {
639
+ fileIds: ['file-123', 'file-456'], // optional file IDs to make available
640
+ },
641
+ }),
642
+ },
643
+ });
644
+ ```
645
+
646
+ The code interpreter tool can be configured with:
647
+
648
+ - **container**: Either a container ID string or an object with `fileIds` to specify uploaded files that should be available to the code interpreter
649
+
650
+ <Note>
651
+ When working with files generated by the Code Interpreter, reference
652
+ information can be obtained from both [annotations in Text
653
+ Parts](#typed-providermetadata-in-text-parts) and [`providerMetadata` in
654
+ Source Document Parts](#typed-providermetadata-in-source-document-parts).
655
+ </Note>
656
+
657
+ #### MCP Tool
658
+
659
+ The OpenAI responses API supports connecting to [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers through the `openai.tools.mcp` tool. This allows models to call tools exposed by remote MCP servers or service connectors.
660
+
661
+ ```ts
662
+ import { openai } from '@ai-sdk/openai';
663
+ import { generateText } from 'ai';
664
+
665
+ const result = await generateText({
666
+ model: openai('gpt-5'),
667
+ prompt: 'Search the web for the latest news about AI developments',
668
+ tools: {
669
+ mcp: openai.tools.mcp({
670
+ serverLabel: 'web-search',
671
+ serverUrl: 'https://mcp.exa.ai/mcp',
672
+ serverDescription: 'A web-search API for AI agents',
673
+ }),
674
+ },
675
+ });
676
+ ```
677
+
678
+ The MCP tool can be configured with:
679
+
680
+ - **serverLabel** _string_ (required)
681
+
682
+ A label to identify the MCP server. This label is used in tool calls to distinguish between multiple MCP servers.
683
+
684
+ - **serverUrl** _string_ (required if `connectorId` is not provided)
685
+
686
+ The URL for the MCP server. Either `serverUrl` or `connectorId` must be provided.
687
+
688
+ - **connectorId** _string_ (required if `serverUrl` is not provided)
689
+
690
+ Identifier for a service connector. Either `serverUrl` or `connectorId` must be provided.
691
+
692
+ - **serverDescription** _string_ (optional)
693
+
694
+ Optional description of the MCP server that helps the model understand its purpose.
695
+
696
+ - **allowedTools** _string[] | object_ (optional)
697
+
698
+ Controls which tools from the MCP server are available. Can be:
699
+
700
+ - An array of tool names: `['tool1', 'tool2']`
701
+ - An object with filters:
702
+ ```ts
703
+ {
704
+ readOnly: true, // Only allow read-only tools
705
+ toolNames: ['tool1', 'tool2'] // Specific tool names
706
+ }
707
+ ```
708
+
709
+ - **authorization** _string_ (optional)
710
+
711
+ OAuth access token for authenticating with the MCP server or connector.
712
+
713
+ - **headers** _Record&lt;string, string&gt;_ (optional)
714
+
715
+ Optional HTTP headers to include in requests to the MCP server.
716
+
717
+ - **requireApproval** _'always' | 'never' | object_ (optional)
718
+
719
+ Controls which MCP tool calls require user approval before execution. Can be:
720
+
721
+ - `'always'`: All MCP tool calls require approval
722
+ - `'never'`: No MCP tool calls require approval (default)
723
+ - An object with filters:
724
+ ```ts
725
+ {
726
+ never: {
727
+ toolNames: ['safe_tool', 'another_safe_tool']; // Skip approval for these tools
728
+ }
729
+ }
730
+ ```
731
+
732
+ When approval is required, the model will return a `tool-approval-request` content part that you can use to prompt the user for approval. See [Human in the Loop](/cookbook/next/human-in-the-loop) for more details on implementing approval workflows.
733
+
734
+ <Note>
735
+ When `requireApproval` is not set, tool calls are approved by default. Be sure
736
+ to connect to only trusted MCP servers, who you trust to share your data with.
737
+ </Note>
738
+
739
+ <Note>
740
+ The OpenAI MCP tool is different from the general MCP client approach
741
+ documented in [MCP Tools](/docs/ai-sdk-core/mcp-tools). The OpenAI MCP tool is
742
+ a built-in provider-defined tool that allows OpenAI models to directly connect
743
+ to MCP servers, while the general MCP client requires you to convert MCP tools
744
+ to AI SDK tools first.
745
+ </Note>
746
+
747
+ #### Local Shell Tool
748
+
749
+ The OpenAI responses API support the local shell tool for Codex models through the `openai.tools.localShell` tool.
750
+ Local shell is a tool that allows agents to run shell commands locally on a machine you or the user provides.
751
+
752
+ ```ts
753
+ import { openai } from '@ai-sdk/openai';
754
+ import { generateText } from 'ai';
755
+
756
+ const result = await generateText({
757
+ model: openai.responses('gpt-5-codex'),
758
+ tools: {
759
+ local_shell: openai.tools.localShell({
760
+ execute: async ({ action }) => {
761
+ // ... your implementation, e.g. sandbox access ...
762
+ return { output: stdout };
763
+ },
764
+ }),
765
+ },
766
+ prompt: 'List the files in my home directory.',
767
+ stopWhen: stepCountIs(2),
768
+ });
769
+ ```
770
+
771
+ #### Shell Tool
772
+
773
+ The OpenAI Responses API supports the shell tool through the `openai.tools.shell` tool.
774
+ The shell tool allows running bash commands and interacting with a command line.
775
+ The model proposes shell commands; your integration executes them and returns the outputs.
776
+
777
+ <Note type="warning">
778
+ Running arbitrary shell commands can be dangerous. Always sandbox execution or
779
+ add strict allow-/deny-lists before forwarding a command to the system shell.
780
+ </Note>
781
+
782
+ The shell tool supports three environment modes that control where commands are executed:
783
+
784
+ ##### Local Execution (default)
785
+
786
+ When no `environment` is specified (or `type: 'local'` is used), commands are executed locally via your `execute` callback:
787
+
788
+ ```ts
789
+ import { openai } from '@ai-sdk/openai';
790
+ import { generateText } from 'ai';
791
+
792
+ const result = await generateText({
793
+ model: openai('gpt-5.2'),
794
+ tools: {
795
+ shell: openai.tools.shell({
796
+ execute: async ({ action }) => {
797
+ // ... your implementation, e.g. sandbox access ...
798
+ return { output: results };
799
+ },
800
+ }),
801
+ },
802
+ prompt: 'List the files in the current directory and show disk usage.',
803
+ });
804
+ ```
805
+
806
+ ##### Hosted Container (auto)
807
+
808
+ Set `environment.type` to `'containerAuto'` to run commands in an OpenAI-hosted container. No `execute` callback is needed — OpenAI handles execution server-side:
809
+
810
+ ```ts
811
+ const result = await generateText({
812
+ model: openai('gpt-5.2'),
813
+ tools: {
814
+ shell: openai.tools.shell({
815
+ environment: {
816
+ type: 'containerAuto',
817
+ // optional configuration:
818
+ memoryLimit: '4g',
819
+ fileIds: ['file-abc123'],
820
+ networkPolicy: {
821
+ type: 'allowlist',
822
+ allowedDomains: ['example.com'],
823
+ },
824
+ },
825
+ }),
826
+ },
827
+ prompt: 'Install numpy and compute the eigenvalues of a 3x3 matrix.',
828
+ });
829
+ ```
830
+
831
+ The `containerAuto` environment supports:
832
+
833
+ - **fileIds** _string[]_ - File IDs to make available in the container
834
+ - **memoryLimit** _'1g' | '4g' | '16g' | '64g'_ - Memory limit for the container
835
+ - **networkPolicy** - Network access policy:
836
+ - `{ type: 'disabled' }` — no network access
837
+ - `{ type: 'allowlist', allowedDomains: string[], domainSecrets?: Array<{ domain, name, value }> }` — allow specific domains with optional secrets
838
+
839
+ ##### Existing Container Reference
840
+
841
+ Set `environment.type` to `'containerReference'` to use an existing container by ID:
842
+
843
+ ```ts
844
+ const result = await generateText({
845
+ model: openai('gpt-5.2'),
846
+ tools: {
847
+ shell: openai.tools.shell({
848
+ environment: {
849
+ type: 'containerReference',
850
+ containerId: 'cntr_abc123',
851
+ },
852
+ }),
853
+ },
854
+ prompt: 'Check the status of running processes.',
855
+ });
856
+ ```
857
+
858
+ ##### Execute Callback
859
+
860
+ For local execution (default or `type: 'local'`), your execute function must return an output array with results for each command:
861
+
862
+ - **stdout** _string_ - Standard output from the command
863
+ - **stderr** _string_ - Standard error from the command
864
+ - **outcome** - Either `{ type: 'timeout' }` or `{ type: 'exit', exitCode: number }`
865
+
866
+ ##### Skills
867
+
868
+ [Skills](https://platform.openai.com/docs/guides/tools-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.
869
+
870
+ **Container skills** support two formats — by reference (for skills uploaded to OpenAI) or inline (as a base64-encoded zip):
871
+
872
+ ```ts
873
+ const result = await generateText({
874
+ model: openai('gpt-5.2'),
875
+ tools: {
876
+ shell: openai.tools.shell({
877
+ environment: {
878
+ type: 'containerAuto',
879
+ skills: [
880
+ // By reference:
881
+ { type: 'skillReference', skillId: 'skill_abc123' },
882
+ // Or inline:
883
+ {
884
+ type: 'inline',
885
+ name: 'my-skill',
886
+ description: 'What this skill does',
887
+ source: {
888
+ type: 'base64',
889
+ mediaType: 'application/zip',
890
+ data: readFileSync('./my-skill.zip').toString('base64'),
891
+ },
892
+ },
893
+ ],
894
+ },
895
+ }),
896
+ },
897
+ prompt: 'Use the skill to solve this problem.',
898
+ });
899
+ ```
900
+
901
+ **Local skills** point to a directory on disk containing a `SKILL.md` file:
902
+
903
+ ```ts
904
+ const result = await generateText({
905
+ model: openai('gpt-5.2'),
906
+ tools: {
907
+ shell: openai.tools.shell({
908
+ execute: async ({ action }) => {
909
+ // ... your local execution implementation ...
910
+ return { output: results };
911
+ },
912
+ environment: {
913
+ type: 'local',
914
+ skills: [
915
+ {
916
+ name: 'my-skill',
917
+ description: 'What this skill does',
918
+ path: resolve('path/to/skill-directory'),
919
+ },
920
+ ],
921
+ },
922
+ }),
923
+ },
924
+ prompt: 'Use the skill to solve this problem.',
925
+ stopWhen: stepCountIs(5),
926
+ });
927
+ ```
928
+
929
+ For more details on creating skills, see the [OpenAI Skills documentation](https://platform.openai.com/docs/guides/tools-skills).
930
+
931
+ #### Apply Patch Tool
932
+
933
+ The OpenAI Responses API supports the apply patch tool for GPT-5.1 models through the `openai.tools.applyPatch` tool.
934
+ The apply patch tool lets the model create, update, and delete files in your codebase using structured diffs.
935
+ Instead of just suggesting edits, the model emits patch operations that your application applies and reports back on,
936
+ enabling iterative, multi-step code editing workflows.
937
+
938
+ ```ts
939
+ import { openai } from '@ai-sdk/openai';
940
+ import { generateText, stepCountIs } from 'ai';
941
+
942
+ const result = await generateText({
943
+ model: openai('gpt-5.1'),
944
+ tools: {
945
+ apply_patch: openai.tools.applyPatch({
946
+ execute: async ({ callId, operation }) => {
947
+ // ... your implementation for applying the diffs.
948
+ },
949
+ }),
950
+ },
951
+ prompt: 'Create a python file that calculates the factorial of a number',
952
+ stopWhen: stepCountIs(5),
953
+ });
954
+ ```
955
+
956
+ Your execute function must return:
957
+
958
+ - **status** _'completed' | 'failed'_ - Whether the patch was applied successfully
959
+ - **output** _string_ (optional) - Human-readable log text (e.g., results or error messages)
960
+
961
+ #### Custom Tool
962
+
963
+ The OpenAI Responses API supports
964
+ [custom tools](https://developers.openai.com/api/docs/guides/function-calling/#custom-tools)
965
+ through the `openai.tools.customTool` tool.
966
+ Custom tools return a raw string instead of JSON, optionally constrained to a grammar
967
+ (regex or Lark syntax). This makes them useful for generating structured text like
968
+ SQL queries, code snippets, or any output that must match a specific pattern.
969
+
970
+ ```ts
971
+ import { openai } from '@ai-sdk/openai';
972
+ import { generateText, stepCountIs } from 'ai';
973
+
974
+ const result = await generateText({
975
+ model: openai.responses('gpt-5.2-codex'),
976
+ tools: {
977
+ write_sql: openai.tools.customTool({
978
+ name: 'write_sql',
979
+ description: 'Write a SQL SELECT query to answer the user question.',
980
+ format: {
981
+ type: 'grammar',
982
+ syntax: 'regex',
983
+ definition: 'SELECT .+',
984
+ },
985
+ execute: async input => {
986
+ // input is a raw string matching the grammar, e.g. "SELECT * FROM users WHERE age > 25"
987
+ const rows = await db.query(input);
988
+ return JSON.stringify(rows);
989
+ },
990
+ }),
991
+ },
992
+ toolChoice: 'required',
993
+ prompt: 'Write a SQL query to get all users older than 25.',
994
+ stopWhen: stepCountIs(3),
995
+ });
996
+ ```
997
+
998
+ Custom tools also work with `streamText`:
999
+
1000
+ ```ts
1001
+ import { openai } from '@ai-sdk/openai';
1002
+ import { streamText } from 'ai';
1003
+
1004
+ const result = streamText({
1005
+ model: openai.responses('gpt-5.2-codex'),
1006
+ tools: {
1007
+ write_sql: openai.tools.customTool({
1008
+ name: 'write_sql',
1009
+ description: 'Write a SQL SELECT query to answer the user question.',
1010
+ format: {
1011
+ type: 'grammar',
1012
+ syntax: 'regex',
1013
+ definition: 'SELECT .+',
1014
+ },
1015
+ }),
1016
+ },
1017
+ toolChoice: 'required',
1018
+ prompt: 'Write a SQL query to get all users older than 25.',
1019
+ });
1020
+
1021
+ for await (const chunk of result.fullStream) {
1022
+ if (chunk.type === 'tool-call') {
1023
+ console.log(`Tool: ${chunk.toolName}`);
1024
+ console.log(`Input: ${chunk.input}`);
1025
+ }
1026
+ }
1027
+ ```
1028
+
1029
+ The custom tool can be configured with:
1030
+
1031
+ - **name** _string_ (required) - The name of the custom tool. Used to identify the tool in tool calls.
1032
+ - **description** _string_ (optional) - A description of what the tool does, to help the model understand when to use it.
1033
+ - **format** _object_ (optional) - The output format constraint. Omit for unconstrained text output.
1034
+ - **type** _'grammar' | 'text'_ - The format type. Use `'grammar'` for constrained output or `'text'` for explicit unconstrained text.
1035
+ - **syntax** _'regex' | 'lark'_ - (grammar only) The grammar syntax. Use `'regex'` for regular expression patterns or `'lark'` for [Lark parser grammar](https://lark-parser.readthedocs.io/).
1036
+ - **definition** _string_ - (grammar only) The grammar definition string (a regex pattern or Lark grammar).
1037
+ - **execute** _function_ (optional) - An async function that receives the raw string input and returns a string result. Enables multi-turn tool calling.
1038
+
1039
+ #### Image Inputs
1040
+
1041
+ The OpenAI Responses API supports Image inputs for appropriate models.
1042
+ You can pass Image files as part of the message content using the 'image' type:
1043
+
1044
+ ```ts
1045
+ const result = await generateText({
1046
+ model: openai('gpt-5'),
1047
+ messages: [
1048
+ {
1049
+ role: 'user',
1050
+ content: [
1051
+ {
1052
+ type: 'text',
1053
+ text: 'Please describe the image.',
1054
+ },
1055
+ {
1056
+ type: 'image',
1057
+ image: readFileSync('./data/image.png'),
1058
+ },
1059
+ ],
1060
+ },
1061
+ ],
1062
+ });
1063
+ ```
1064
+
1065
+ The model will have access to the image and will respond to questions about it.
1066
+ The image should be passed using the `image` field.
1067
+
1068
+ You can also pass a file-id from the OpenAI Files API.
1069
+
1070
+ ```ts
1071
+ {
1072
+ type: 'image',
1073
+ image: 'file-8EFBcWHsQxZV7YGezBC1fq'
1074
+ }
1075
+ ```
1076
+
1077
+ You can also pass the URL of an image.
1078
+
1079
+ ```ts
1080
+ {
1081
+ type: 'image',
1082
+ image: 'https://sample.edu/image.png',
1083
+ }
1084
+ ```
1085
+
1086
+ #### PDF Inputs
1087
+
1088
+ The OpenAI Responses API supports reading PDF files.
1089
+ You can pass PDF files as part of the message content using the `file` type:
1090
+
1091
+ ```ts
1092
+ const result = await generateText({
1093
+ model: openai('gpt-5'),
1094
+ messages: [
1095
+ {
1096
+ role: 'user',
1097
+ content: [
1098
+ {
1099
+ type: 'text',
1100
+ text: 'What is an embedding model?',
1101
+ },
1102
+ {
1103
+ type: 'file',
1104
+ data: readFileSync('./data/ai.pdf'),
1105
+ mediaType: 'application/pdf',
1106
+ filename: 'ai.pdf', // optional
1107
+ },
1108
+ ],
1109
+ },
1110
+ ],
1111
+ });
1112
+ ```
1113
+
1114
+ You can also pass a file-id from the OpenAI Files API.
1115
+
1116
+ ```ts
1117
+ {
1118
+ type: 'file',
1119
+ data: 'file-8EFBcWHsQxZV7YGezBC1fq',
1120
+ mediaType: 'application/pdf',
1121
+ }
1122
+ ```
1123
+
1124
+ You can also pass the URL of a pdf.
1125
+
1126
+ ```ts
1127
+ {
1128
+ type: 'file',
1129
+ data: 'https://sample.edu/example.pdf',
1130
+ mediaType: 'application/pdf',
1131
+ filename: 'ai.pdf', // optional
1132
+ }
1133
+ ```
1134
+
1135
+ The model will have access to the contents of the PDF file and
1136
+ respond to questions about it.
1137
+ The PDF file should be passed using the `data` field,
1138
+ and the `mediaType` should be set to `'application/pdf'`.
1139
+
1140
+ #### Structured Outputs
1141
+
1142
+ The OpenAI Responses API supports structured outputs. You can use `generateText` or `streamText` with [`Output`](/docs/reference/ai-sdk-core/output) to enforce structured outputs.
1143
+
1144
+ ```ts
1145
+ const result = await generateText({
1146
+ model: openai('gpt-4.1'),
1147
+ output: Output.object({
1148
+ schema: z.object({
1149
+ recipe: z.object({
1150
+ name: z.string(),
1151
+ ingredients: z.array(
1152
+ z.object({
1153
+ name: z.string(),
1154
+ amount: z.string(),
1155
+ }),
1156
+ ),
1157
+ steps: z.array(z.string()),
1158
+ }),
1159
+ }),
1160
+ }),
1161
+ prompt: 'Generate a lasagna recipe.',
1162
+ });
1163
+ ```
1164
+
1165
+ #### Typed providerMetadata in Text Parts
1166
+
1167
+ When using the OpenAI Responses API, the SDK attaches OpenAI-specific metadata to output parts via `providerMetadata`.
1168
+
1169
+ This metadata can be used on the client side for tasks such as rendering citations or downloading files generated by the Code Interpreter.
1170
+ To enable type-safe handling of this metadata, the AI SDK exports dedicated TypeScript types.
1171
+
1172
+ For text parts, when `part.type === 'text'`, the `providerMetadata` is provided in the form of `OpenaiResponsesTextProviderMetadata`.
1173
+
1174
+ This metadata includes the following fields:
1175
+
1176
+ - `itemId`
1177
+ The ID of the output item in the Responses API.
1178
+ - `annotations` (optional)
1179
+ An array of annotation objects generated by the model.
1180
+ If no annotations are present, this property itself may be omitted (`undefined`).
1181
+
1182
+ Each element in `annotations` is a discriminated union with a required `type` field. Supported types include, for example:
1183
+
1184
+ - `url_citation`
1185
+ - `file_citation`
1186
+ - `container_file_citation`
1187
+ - `file_path`
1188
+
1189
+ These annotations directly correspond to the annotation objects defined by the Responses API and can be used for inline reference rendering or output analysis.
1190
+ For details, see the official OpenAI documentation:
1191
+ [Responses API – output text annotations](https://platform.openai.com/docs/api-reference/responses/object?lang=javascript#responses-object-output-output_message-content-output_text-annotations).
1192
+
1193
+ ```ts
1194
+ import {
1195
+ openai,
1196
+ type OpenaiResponsesTextProviderMetadata,
1197
+ } from '@ai-sdk/openai';
1198
+ import { generateText } from 'ai';
1199
+
1200
+ const result = await generateText({
1201
+ model: openai('gpt-4.1-mini'),
1202
+ prompt:
1203
+ 'Create a program that generates five random numbers between 1 and 100 with two decimal places, and show me the execution results. Also save the result to a file.',
1204
+ tools: {
1205
+ code_interpreter: openai.tools.codeInterpreter(),
1206
+ web_search: openai.tools.webSearch(),
1207
+ file_search: openai.tools.fileSearch({ vectorStoreIds: ['vs_1234'] }), // requires a configured vector store
1208
+ },
1209
+ });
1210
+
1211
+ for (const part of result.content) {
1212
+ if (part.type === 'text') {
1213
+ const providerMetadata = part.providerMetadata as
1214
+ | OpenaiResponsesTextProviderMetadata
1215
+ | undefined;
1216
+ if (!providerMetadata) continue;
1217
+ const { itemId: _itemId, annotations } = providerMetadata.openai;
1218
+
1219
+ if (!annotations) continue;
1220
+ for (const annotation of annotations) {
1221
+ switch (annotation.type) {
1222
+ case 'url_citation':
1223
+ // url_citation is returned from web_search and provides:
1224
+ // properties: type, url, title, start_index and end_index
1225
+ break;
1226
+ case 'file_citation':
1227
+ // file_citation is returned from file_search and provides:
1228
+ // properties: type, file_id, filename and index
1229
+ break;
1230
+ case 'container_file_citation':
1231
+ // container_file_citation is returned from code_interpreter and provides:
1232
+ // properties: type, container_id, file_id, filename, start_index and end_index
1233
+ break;
1234
+ case 'file_path':
1235
+ // file_path provides:
1236
+ // properties: type, file_id and index
1237
+ break;
1238
+ default: {
1239
+ const _exhaustiveCheck: never = annotation;
1240
+ throw new Error(
1241
+ `Unhandled annotation: ${JSON.stringify(_exhaustiveCheck)}`,
1242
+ );
1243
+ }
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+ ```
1249
+
1250
+ <Note>
1251
+ When implementing file downloads for files generated by the Code Interpreter,
1252
+ the `container_id` and `file_id` available in `providerMetadata` can be used
1253
+ to retrieve the file content. For details, see the [Retrieve container file
1254
+ content](https://platform.openai.com/docs/api-reference/container-files/retrieveContainerFileContent)
1255
+ API.
1256
+ </Note>
1257
+
1258
+ #### Typed providerMetadata in Reasoning Parts
1259
+
1260
+ When using the OpenAI Responses API, reasoning output parts can include provider metadata.
1261
+ To handle this metadata in a type-safe way, use `OpenaiResponsesReasoningProviderMetadata`.
1262
+
1263
+ For reasoning parts, when `part.type === 'reasoning'`, the `providerMetadata` is provided in the form of `OpenaiResponsesReasoningProviderMetadata`.
1264
+
1265
+ This metadata includes the following fields:
1266
+
1267
+ - `itemId`
1268
+ The ID of the reasoning item in the Responses API.
1269
+ - `reasoningEncryptedContent` (optional)
1270
+ Encrypted reasoning content (only returned when requested via `include: ['reasoning.encrypted_content']`).
1271
+
1272
+ ```ts
1273
+ import {
1274
+ openai,
1275
+ type OpenaiResponsesReasoningProviderMetadata,
1276
+ type OpenAILanguageModelResponsesOptions,
1277
+ } from '@ai-sdk/openai';
1278
+ import { generateText } from 'ai';
1279
+
1280
+ const result = await generateText({
1281
+ model: openai('gpt-5'),
1282
+ prompt: 'How many "r"s are in the word "strawberry"?',
1283
+ providerOptions: {
1284
+ openai: {
1285
+ store: false,
1286
+ include: ['reasoning.encrypted_content'],
1287
+ } satisfies OpenAILanguageModelResponsesOptions,
1288
+ },
1289
+ });
1290
+
1291
+ for (const part of result.content) {
1292
+ if (part.type === 'reasoning') {
1293
+ const providerMetadata = part.providerMetadata as
1294
+ | OpenaiResponsesReasoningProviderMetadata
1295
+ | undefined;
1296
+
1297
+ const { itemId, reasoningEncryptedContent } =
1298
+ providerMetadata?.openai ?? {};
1299
+ console.log(itemId, reasoningEncryptedContent);
1300
+ }
1301
+ }
1302
+ ```
1303
+
1304
+ #### Typed providerMetadata in Source Document Parts
1305
+
1306
+ For source document parts, when `part.type === 'source'` and `sourceType === 'document'`, the `providerMetadata` is provided as `OpenaiResponsesSourceDocumentProviderMetadata`.
1307
+
1308
+ This metadata is also a discriminated union with a required `type` field. Supported types include:
1309
+
1310
+ - `file_citation`
1311
+ - `container_file_citation`
1312
+ - `file_path`
1313
+
1314
+ Each type includes the identifiers required to work with the referenced resource, such as `fileId` and `containerId`.
1315
+
1316
+ ```ts
1317
+ import {
1318
+ openai,
1319
+ type OpenaiResponsesSourceDocumentProviderMetadata,
1320
+ } from '@ai-sdk/openai';
1321
+ import { generateText } from 'ai';
1322
+
1323
+ const result = await generateText({
1324
+ model: openai('gpt-4.1-mini'),
1325
+ prompt:
1326
+ 'Create a program that generates five random numbers between 1 and 100 with two decimal places, and show me the execution results. Also save the result to a file.',
1327
+ tools: {
1328
+ code_interpreter: openai.tools.codeInterpreter(),
1329
+ web_search: openai.tools.webSearch(),
1330
+ file_search: openai.tools.fileSearch({ vectorStoreIds: ['vs_1234'] }), // requires a configured vector store
1331
+ },
1332
+ });
1333
+
1334
+ for (const part of result.content) {
1335
+ if (part.type === 'source') {
1336
+ if (part.sourceType === 'document') {
1337
+ const providerMetadata = part.providerMetadata as
1338
+ | OpenaiResponsesSourceDocumentProviderMetadata
1339
+ | undefined;
1340
+ if (!providerMetadata) continue;
1341
+ const annotation = providerMetadata.openai;
1342
+ switch (annotation.type) {
1343
+ case 'file_citation':
1344
+ // file_citation is returned from file_search and provides:
1345
+ // properties: type, fileId and index
1346
+ // The filename can be accessed via part.filename.
1347
+ break;
1348
+ case 'container_file_citation':
1349
+ // container_file_citation is returned from code_interpreter and provides:
1350
+ // properties: type, containerId and fileId
1351
+ // The filename can be accessed via part.filename.
1352
+ break;
1353
+ case 'file_path':
1354
+ // file_path provides:
1355
+ // properties: type, fileId and index
1356
+ break;
1357
+ default: {
1358
+ const _exhaustiveCheck: never = annotation;
1359
+ throw new Error(
1360
+ `Unhandled annotation: ${JSON.stringify(_exhaustiveCheck)}`,
1361
+ );
1362
+ }
1363
+ }
1364
+ }
1365
+ }
1366
+ }
1367
+ ```
1368
+
1369
+ <Note>
1370
+ Annotations in text parts follow the OpenAI Responses API specification and
1371
+ therefore use snake_case properties (e.g. `file_id`, `container_id`). In
1372
+ contrast, `providerMetadata` for source document parts is normalized by the
1373
+ SDK to camelCase (e.g. `fileId`, `containerId`). Fields that depend on the
1374
+ original text content, such as `start_index` and `end_index`, are omitted, as
1375
+ are fields like `filename` that are directly available on the source object.
1376
+ </Note>
1377
+
1378
+ ### Chat Models
1379
+
1380
+ You can create models that call the [OpenAI chat API](https://platform.openai.com/docs/api-reference/chat) using the `.chat()` factory method.
1381
+ The first argument is the model id, e.g. `gpt-4`.
1382
+ The OpenAI chat models support tool calls and some have multi-modal capabilities.
1383
+
1384
+ ```ts
1385
+ const model = openai.chat('gpt-5');
1386
+ ```
1387
+
1388
+ OpenAI chat models support also some model specific provider options that are not part of the [standard call settings](/docs/ai-sdk-core/settings).
1389
+ You can pass them in the `providerOptions` argument:
1390
+
1391
+ ```ts
1392
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1393
+
1394
+ const model = openai.chat('gpt-5');
1395
+
1396
+ await generateText({
1397
+ model,
1398
+ providerOptions: {
1399
+ openai: {
1400
+ logitBias: {
1401
+ // optional likelihood for specific tokens
1402
+ '50256': -100,
1403
+ },
1404
+ user: 'test-user', // optional unique user identifier
1405
+ } satisfies OpenAILanguageModelChatOptions,
1406
+ },
1407
+ });
1408
+ ```
1409
+
1410
+ The following optional provider options are available for OpenAI chat models:
1411
+
1412
+ - **logitBias** _Record&lt;number, number&gt;_
1413
+
1414
+ Modifies the likelihood of specified tokens appearing in the completion.
1415
+
1416
+ Accepts a JSON object that maps tokens (specified by their token ID in
1417
+ the GPT tokenizer) to an associated bias value from -100 to 100. You
1418
+ can use this tokenizer tool to convert text to token IDs. Mathematically,
1419
+ the bias is added to the logits generated by the model prior to sampling.
1420
+ The exact effect will vary per model, but values between -1 and 1 should
1421
+ decrease or increase likelihood of selection; values like -100 or 100
1422
+ should result in a ban or exclusive selection of the relevant token.
1423
+
1424
+ As an example, you can pass `{"50256": -100}` to prevent the token from being generated.
1425
+
1426
+ - **logprobs** _boolean | number_
1427
+
1428
+ Return the log probabilities of the tokens. Including logprobs will increase
1429
+ the response size and can slow down response times. However, it can
1430
+ be useful to better understand how the model is behaving.
1431
+
1432
+ Setting to true will return the log probabilities of the tokens that
1433
+ were generated.
1434
+
1435
+ Setting to a number will return the log probabilities of the top n
1436
+ tokens that were generated.
1437
+
1438
+ - **parallelToolCalls** _boolean_
1439
+
1440
+ Whether to enable parallel function calling during tool use. Defaults to `true`.
1441
+
1442
+ - **user** _string_
1443
+
1444
+ A unique identifier representing your end-user, which can help OpenAI to
1445
+ monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids).
1446
+
1447
+ - **reasoningEffort** _'minimal' | 'low' | 'medium' | 'high' | 'xhigh'_
1448
+
1449
+ Reasoning effort for reasoning models. Defaults to `medium`. If you use
1450
+ `providerOptions` to set the `reasoningEffort` option, this
1451
+ model setting will be ignored.
1452
+
1453
+ - **maxCompletionTokens** _number_
1454
+
1455
+ Maximum number of completion tokens to generate. Useful for reasoning models.
1456
+
1457
+ - **store** _boolean_
1458
+
1459
+ Whether to enable persistence in Responses API.
1460
+
1461
+ - **metadata** _Record&lt;string, string&gt;_
1462
+
1463
+ Metadata to associate with the request.
1464
+
1465
+ - **prediction** _Record&lt;string, any&gt;_
1466
+
1467
+ Parameters for prediction mode.
1468
+
1469
+ - **serviceTier** _'auto' | 'flex' | 'priority' | 'default'_
1470
+
1471
+ Service tier for the request. Set to 'flex' for 50% cheaper processing
1472
+ at the cost of increased latency (available for o3, o4-mini, and gpt-5 models).
1473
+ 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).
1474
+
1475
+ Defaults to 'auto'.
1476
+
1477
+ - **strictJsonSchema** _boolean_
1478
+
1479
+ Whether to use strict JSON schema validation.
1480
+ Defaults to `true`.
1481
+
1482
+ - **textVerbosity** _'low' | 'medium' | 'high'_
1483
+
1484
+ 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.
1485
+
1486
+ - **promptCacheKey** _string_
1487
+
1488
+ A cache key for manual prompt caching control. Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
1489
+
1490
+ - **promptCacheRetention** _'in_memory' | '24h'_
1491
+
1492
+ The retention policy for the prompt cache. Set to `'24h'` to enable extended prompt caching, which keeps cached prefixes active for up to 24 hours. Defaults to `'in_memory'` for standard prompt caching. Note: `'24h'` is currently only available for the 5.1 series of models.
1493
+
1494
+ - **safetyIdentifier** _string_
1495
+
1496
+ 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.
1497
+
1498
+ - **systemMessageMode** _'system' | 'developer' | 'remove'_
1499
+
1500
+ Override the system message mode for this model. If not specified, the mode is automatically determined based on the model. `system` uses the 'system' role for system messages (default for most models); `developer` uses the 'developer' role (used by reasoning models); `remove` removes system messages entirely.
1501
+
1502
+ - **forceReasoning** _boolean_
1503
+
1504
+ 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 `systemMessageMode` to `developer` unless overridden.
1505
+
1506
+ #### Reasoning
1507
+
1508
+ OpenAI has introduced the `o1`,`o3`, and `o4` series of [reasoning models](https://platform.openai.com/docs/guides/reasoning).
1509
+ Currently, `o4-mini`, `o3`, `o3-mini`, and `o1` are available via both the chat and responses APIs. The
1510
+ model `gpt-5.1-codex-mini` is available only via the [responses API](#responses-models).
1511
+
1512
+ Reasoning models currently only generate text, have several limitations, and are only supported using `generateText` and `streamText`.
1513
+
1514
+ They support additional settings and response metadata:
1515
+
1516
+ - You can use `providerOptions` to set
1517
+
1518
+ - the `reasoningEffort` option (or alternatively the `reasoningEffort` model setting), which determines the amount of reasoning the model performs.
1519
+
1520
+ - You can use response `providerMetadata` to access the number of reasoning tokens that the model generated.
1521
+
1522
+ ```ts highlight="4,7-11,17"
1523
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1524
+ import { generateText } from 'ai';
1525
+
1526
+ const { text, usage, providerMetadata } = await generateText({
1527
+ model: openai.chat('gpt-5'),
1528
+ prompt: 'Invent a new holiday and describe its traditions.',
1529
+ providerOptions: {
1530
+ openai: {
1531
+ reasoningEffort: 'low',
1532
+ } satisfies OpenAILanguageModelChatOptions,
1533
+ },
1534
+ });
1535
+
1536
+ console.log(text);
1537
+ console.log('Usage:', {
1538
+ ...usage,
1539
+ reasoningTokens: providerMetadata?.openai?.reasoningTokens,
1540
+ });
1541
+ ```
1542
+
1543
+ <Note>
1544
+ System messages are automatically converted to OpenAI developer messages for
1545
+ reasoning models when supported.
1546
+ </Note>
1547
+
1548
+ - You can control how system messages are handled by providerOptions `systemMessageMode`:
1549
+
1550
+ - `developer`: treat the prompt as a developer message (default for reasoning models).
1551
+ - `system`: keep the system message as a system-level instruction.
1552
+ - `remove`: remove the system message from the messages.
1553
+
1554
+ ```ts highlight="12"
1555
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1556
+ import { generateText } from 'ai';
1557
+
1558
+ const result = await generateText({
1559
+ model: openai.chat('gpt-5'),
1560
+ messages: [
1561
+ { role: 'system', content: 'You are a helpful assistant.' },
1562
+ { role: 'user', content: 'Tell me a joke.' },
1563
+ ],
1564
+ providerOptions: {
1565
+ openai: {
1566
+ systemMessageMode: 'system',
1567
+ } satisfies OpenAILanguageModelChatOptions,
1568
+ },
1569
+ });
1570
+ ```
1571
+
1572
+ <Note>
1573
+ Reasoning models require additional runtime inference to complete their
1574
+ reasoning phase before generating a response. This introduces longer latency
1575
+ compared to other models.
1576
+ </Note>
1577
+
1578
+ <Note>
1579
+ `maxOutputTokens` is automatically mapped to `max_completion_tokens` for
1580
+ reasoning models.
1581
+ </Note>
1582
+
1583
+ #### Strict Structured Outputs
1584
+
1585
+ Strict structured outputs are enabled by default.
1586
+ You can disable them by setting the `strictJsonSchema` option to `false`.
1587
+
1588
+ ```ts highlight="7"
1589
+ import { openai, OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1590
+ import { generateText, Output } from 'ai';
1591
+ import { z } from 'zod';
1592
+
1593
+ const result = await generateText({
1594
+ model: openai.chat('gpt-4o-2024-08-06'),
1595
+ providerOptions: {
1596
+ openai: {
1597
+ strictJsonSchema: false,
1598
+ } satisfies OpenAILanguageModelChatOptions,
1599
+ },
1600
+ output: Output.object({
1601
+ schema: z.object({
1602
+ name: z.string(),
1603
+ ingredients: z.array(
1604
+ z.object({
1605
+ name: z.string(),
1606
+ amount: z.string(),
1607
+ }),
1608
+ ),
1609
+ steps: z.array(z.string()),
1610
+ }),
1611
+ schemaName: 'recipe',
1612
+ schemaDescription: 'A recipe for lasagna.',
1613
+ }),
1614
+ prompt: 'Generate a lasagna recipe.',
1615
+ });
1616
+
1617
+ console.log(JSON.stringify(result.output, null, 2));
1618
+ ```
1619
+
1620
+ <Note type="warning">
1621
+ OpenAI structured outputs have several
1622
+ [limitations](https://openai.com/index/introducing-structured-outputs-in-the-api),
1623
+ in particular around the [supported schemas](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas),
1624
+ and are therefore opt-in.
1625
+
1626
+ For example, optional schema properties are not supported.
1627
+ You need to change Zod `.nullish()` and `.optional()` to `.nullable()`.
1628
+
1629
+ </Note>
1630
+
1631
+ #### Logprobs
1632
+
1633
+ OpenAI provides logprobs information for completion/chat models.
1634
+ You can access it in the `providerMetadata` object.
1635
+
1636
+ ```ts highlight="11"
1637
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1638
+ import { generateText } from 'ai';
1639
+
1640
+ const result = await generateText({
1641
+ model: openai.chat('gpt-5'),
1642
+ prompt: 'Write a vegetarian lasagna recipe for 4 people.',
1643
+ providerOptions: {
1644
+ openai: {
1645
+ // this can also be a number,
1646
+ // refer to logprobs provider options section for more
1647
+ logprobs: true,
1648
+ } satisfies OpenAILanguageModelChatOptions,
1649
+ },
1650
+ });
1651
+
1652
+ const openaiMetadata = (await result.providerMetadata)?.openai;
1653
+
1654
+ const logprobs = openaiMetadata?.logprobs;
1655
+ ```
1656
+
1657
+ #### Image Support
1658
+
1659
+ The OpenAI Chat API supports Image inputs for appropriate models.
1660
+ You can pass Image files as part of the message content using the 'image' type:
1661
+
1662
+ ```ts
1663
+ const result = await generateText({
1664
+ model: openai.chat('gpt-5'),
1665
+ messages: [
1666
+ {
1667
+ role: 'user',
1668
+ content: [
1669
+ {
1670
+ type: 'text',
1671
+ text: 'Please describe the image.',
1672
+ },
1673
+ {
1674
+ type: 'image',
1675
+ image: readFileSync('./data/image.png'),
1676
+ },
1677
+ ],
1678
+ },
1679
+ ],
1680
+ });
1681
+ ```
1682
+
1683
+ The model will have access to the image and will respond to questions about it.
1684
+ The image should be passed using the `image` field.
1685
+
1686
+ You can also pass the URL of an image.
1687
+
1688
+ ```ts
1689
+ {
1690
+ type: 'image',
1691
+ image: 'https://sample.edu/image.png',
1692
+ }
1693
+ ```
1694
+
1695
+ #### PDF support
1696
+
1697
+ The OpenAI Chat API supports reading PDF files.
1698
+ You can pass PDF files as part of the message content using the `file` type:
1699
+
1700
+ ```ts
1701
+ const result = await generateText({
1702
+ model: openai.chat('gpt-5'),
1703
+ messages: [
1704
+ {
1705
+ role: 'user',
1706
+ content: [
1707
+ {
1708
+ type: 'text',
1709
+ text: 'What is an embedding model?',
1710
+ },
1711
+ {
1712
+ type: 'file',
1713
+ data: readFileSync('./data/ai.pdf'),
1714
+ mediaType: 'application/pdf',
1715
+ filename: 'ai.pdf', // optional
1716
+ },
1717
+ ],
1718
+ },
1719
+ ],
1720
+ });
1721
+ ```
1722
+
1723
+ The model will have access to the contents of the PDF file and
1724
+ respond to questions about it.
1725
+ The PDF file should be passed using the `data` field,
1726
+ and the `mediaType` should be set to `'application/pdf'`.
1727
+
1728
+ You can also pass a file-id from the OpenAI Files API.
1729
+
1730
+ ```ts
1731
+ {
1732
+ type: 'file',
1733
+ data: 'file-8EFBcWHsQxZV7YGezBC1fq',
1734
+ mediaType: 'application/pdf',
1735
+ }
1736
+ ```
1737
+
1738
+ You can also pass the URL of a PDF.
1739
+
1740
+ ```ts
1741
+ {
1742
+ type: 'file',
1743
+ data: 'https://sample.edu/example.pdf',
1744
+ mediaType: 'application/pdf',
1745
+ filename: 'ai.pdf', // optional
1746
+ }
1747
+ ```
1748
+
1749
+ #### Predicted Outputs
1750
+
1751
+ OpenAI supports [predicted outputs](https://platform.openai.com/docs/guides/latency-optimization#use-predicted-outputs) for `gpt-4o` and `gpt-4o-mini`.
1752
+ Predicted outputs help you reduce latency by allowing you to specify a base text that the model should modify.
1753
+ You can enable predicted outputs by adding the `prediction` option to the `providerOptions.openai` object:
1754
+
1755
+ ```ts highlight="15-18"
1756
+ const result = streamText({
1757
+ model: openai.chat('gpt-5'),
1758
+ messages: [
1759
+ {
1760
+ role: 'user',
1761
+ content: 'Replace the Username property with an Email property.',
1762
+ },
1763
+ {
1764
+ role: 'user',
1765
+ content: existingCode,
1766
+ },
1767
+ ],
1768
+ providerOptions: {
1769
+ openai: {
1770
+ prediction: {
1771
+ type: 'content',
1772
+ content: existingCode,
1773
+ },
1774
+ } satisfies OpenAILanguageModelChatOptions,
1775
+ },
1776
+ });
1777
+ ```
1778
+
1779
+ OpenAI provides usage information for predicted outputs (`acceptedPredictionTokens` and `rejectedPredictionTokens`).
1780
+ You can access it in the `providerMetadata` object.
1781
+
1782
+ ```ts highlight="11"
1783
+ const openaiMetadata = (await result.providerMetadata)?.openai;
1784
+
1785
+ const acceptedPredictionTokens = openaiMetadata?.acceptedPredictionTokens;
1786
+ const rejectedPredictionTokens = openaiMetadata?.rejectedPredictionTokens;
1787
+ ```
1788
+
1789
+ <Note type="warning">
1790
+ OpenAI Predicted Outputs have several
1791
+ [limitations](https://platform.openai.com/docs/guides/predicted-outputs#limitations),
1792
+ e.g. unsupported API parameters and no tool calling support.
1793
+ </Note>
1794
+
1795
+ #### Image Detail
1796
+
1797
+ You can use the `openai` provider option to set the [image input detail](https://platform.openai.com/docs/guides/images-vision?api-mode=responses#specify-image-input-detail-level) to `high`, `low`, or `auto`:
1798
+
1799
+ ```ts highlight="13-16"
1800
+ const result = await generateText({
1801
+ model: openai.chat('gpt-5'),
1802
+ messages: [
1803
+ {
1804
+ role: 'user',
1805
+ content: [
1806
+ { type: 'text', text: 'Describe the image in detail.' },
1807
+ {
1808
+ type: 'image',
1809
+ image:
1810
+ 'https://github.com/vercel/ai/blob/main/examples/ai-functions/data/comic-cat.png?raw=true',
1811
+
1812
+ // OpenAI specific options - image detail:
1813
+ providerOptions: {
1814
+ openai: { imageDetail: 'low' },
1815
+ },
1816
+ },
1817
+ ],
1818
+ },
1819
+ ],
1820
+ });
1821
+ ```
1822
+
1823
+ <Note type="warning">
1824
+ Because the `UIMessage` type (used by AI SDK UI hooks like `useChat`) does not
1825
+ support the `providerOptions` property, you can use `convertToModelMessages`
1826
+ first before passing the messages to functions like `generateText` or
1827
+ `streamText`. For more details on `providerOptions` usage, see
1828
+ [here](/docs/foundations/prompts#provider-options).
1829
+ </Note>
1830
+
1831
+ #### Distillation
1832
+
1833
+ OpenAI supports model distillation for some models.
1834
+ If you want to store a generation for use in the distillation process, you can add the `store` option to the `providerOptions.openai` object.
1835
+ This will save the generation to the OpenAI platform for later use in distillation.
1836
+
1837
+ ```typescript highlight="9-16"
1838
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1839
+ import { generateText } from 'ai';
1840
+ import 'dotenv/config';
1841
+
1842
+ async function main() {
1843
+ const { text, usage } = await generateText({
1844
+ model: openai.chat('gpt-4o-mini'),
1845
+ prompt: 'Who worked on the original macintosh?',
1846
+ providerOptions: {
1847
+ openai: {
1848
+ store: true,
1849
+ metadata: {
1850
+ custom: 'value',
1851
+ },
1852
+ } satisfies OpenAILanguageModelChatOptions,
1853
+ },
1854
+ });
1855
+
1856
+ console.log(text);
1857
+ console.log();
1858
+ console.log('Usage:', usage);
1859
+ }
1860
+
1861
+ main().catch(console.error);
1862
+ ```
1863
+
1864
+ #### Prompt Caching
1865
+
1866
+ OpenAI has introduced [Prompt Caching](https://platform.openai.com/docs/guides/prompt-caching) for supported models
1867
+ including `gpt-4o` and `gpt-4o-mini`.
1868
+
1869
+ - Prompt caching is automatically enabled for these models, when the prompt is 1024 tokens or longer. It does
1870
+ not need to be explicitly enabled.
1871
+ - You can use response `providerMetadata` to access the number of prompt tokens that were a cache hit.
1872
+ - Note that caching behavior is dependent on load on OpenAI's infrastructure. Prompt prefixes generally remain in the
1873
+ cache following 5-10 minutes of inactivity before they are evicted, but during off-peak periods they may persist for up
1874
+ to an hour.
1875
+
1876
+ ```ts highlight="11"
1877
+ import { openai } from '@ai-sdk/openai';
1878
+ import { generateText } from 'ai';
1879
+
1880
+ const { text, usage, providerMetadata } = await generateText({
1881
+ model: openai.chat('gpt-4o-mini'),
1882
+ prompt: `A 1024-token or longer prompt...`,
1883
+ });
1884
+
1885
+ console.log(`usage:`, {
1886
+ ...usage,
1887
+ cachedPromptTokens: providerMetadata?.openai?.cachedPromptTokens,
1888
+ });
1889
+ ```
1890
+
1891
+ To improve cache hit rates, you can manually control caching using the `promptCacheKey` option:
1892
+
1893
+ ```ts highlight="7-11"
1894
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1895
+ import { generateText } from 'ai';
1896
+
1897
+ const { text, usage, providerMetadata } = await generateText({
1898
+ model: openai.chat('gpt-5'),
1899
+ prompt: `A 1024-token or longer prompt...`,
1900
+ providerOptions: {
1901
+ openai: {
1902
+ promptCacheKey: 'my-custom-cache-key-123',
1903
+ } satisfies OpenAILanguageModelChatOptions,
1904
+ },
1905
+ });
1906
+
1907
+ console.log(`usage:`, {
1908
+ ...usage,
1909
+ cachedPromptTokens: providerMetadata?.openai?.cachedPromptTokens,
1910
+ });
1911
+ ```
1912
+
1913
+ For GPT-5.1 models, you can enable extended prompt caching that keeps cached prefixes active for up to 24 hours:
1914
+
1915
+ ```ts highlight="7-12"
1916
+ import { openai, type OpenAILanguageModelChatOptions } from '@ai-sdk/openai';
1917
+ import { generateText } from 'ai';
1918
+
1919
+ const { text, usage, providerMetadata } = await generateText({
1920
+ model: openai.chat('gpt-5.1'),
1921
+ prompt: `A 1024-token or longer prompt...`,
1922
+ providerOptions: {
1923
+ openai: {
1924
+ promptCacheKey: 'my-custom-cache-key-123',
1925
+ promptCacheRetention: '24h', // Extended caching for GPT-5.1
1926
+ } satisfies OpenAILanguageModelChatOptions,
1927
+ },
1928
+ });
1929
+
1930
+ console.log(`usage:`, {
1931
+ ...usage,
1932
+ cachedPromptTokens: providerMetadata?.openai?.cachedPromptTokens,
1933
+ });
1934
+ ```
1935
+
1936
+ #### Audio Input
1937
+
1938
+ With the `gpt-4o-audio-preview` model, you can pass audio files to the model.
1939
+
1940
+ <Note type="warning">
1941
+ The `gpt-4o-audio-preview` model is currently in preview and requires at least
1942
+ some audio inputs. It will not work with non-audio data.
1943
+ </Note>
1944
+
1945
+ ```ts highlight="12-14"
1946
+ import { openai } from '@ai-sdk/openai';
1947
+ import { generateText } from 'ai';
1948
+
1949
+ const result = await generateText({
1950
+ model: openai.chat('gpt-4o-audio-preview'),
1951
+ messages: [
1952
+ {
1953
+ role: 'user',
1954
+ content: [
1955
+ { type: 'text', text: 'What is the audio saying?' },
1956
+ {
1957
+ type: 'file',
1958
+ mediaType: 'audio/mpeg',
1959
+ data: readFileSync('./data/galileo.mp3'),
1960
+ },
1961
+ ],
1962
+ },
1963
+ ],
1964
+ });
1965
+ ```
1966
+
1967
+ ### Completion Models
1968
+
1969
+ You can create models that call the [OpenAI completions API](https://platform.openai.com/docs/api-reference/completions) using the `.completion()` factory method.
1970
+ The first argument is the model id.
1971
+ Currently only `gpt-3.5-turbo-instruct` is supported.
1972
+
1973
+ ```ts
1974
+ const model = openai.completion('gpt-3.5-turbo-instruct');
1975
+ ```
1976
+
1977
+ OpenAI completion models support also some model specific settings that are not part of the [standard call settings](/docs/ai-sdk-core/settings).
1978
+ You can pass them as an options argument:
1979
+
1980
+ ```ts
1981
+ const model = openai.completion('gpt-3.5-turbo-instruct');
1982
+
1983
+ await model.doGenerate({
1984
+ providerOptions: {
1985
+ openai: {
1986
+ echo: true, // optional, echo the prompt in addition to the completion
1987
+ logitBias: {
1988
+ // optional likelihood for specific tokens
1989
+ '50256': -100,
1990
+ },
1991
+ suffix: 'some text', // optional suffix that comes after a completion of inserted text
1992
+ user: 'test-user', // optional unique user identifier
1993
+ } satisfies OpenAILanguageModelCompletionOptions,
1994
+ },
1995
+ });
1996
+ ```
1997
+
1998
+ The following optional provider options are available for OpenAI completion models:
1999
+
2000
+ - **echo**: _boolean_
2001
+
2002
+ Echo back the prompt in addition to the completion.
2003
+
2004
+ - **logitBias** _Record&lt;number, number&gt;_
2005
+
2006
+ Modifies the likelihood of specified tokens appearing in the completion.
2007
+
2008
+ Accepts a JSON object that maps tokens (specified by their token ID in
2009
+ the GPT tokenizer) to an associated bias value from -100 to 100. You
2010
+ can use this tokenizer tool to convert text to token IDs. Mathematically,
2011
+ the bias is added to the logits generated by the model prior to sampling.
2012
+ The exact effect will vary per model, but values between -1 and 1 should
2013
+ decrease or increase likelihood of selection; values like -100 or 100
2014
+ should result in a ban or exclusive selection of the relevant token.
2015
+
2016
+ As an example, you can pass `{"50256": -100}` to prevent the &lt;|endoftext|&gt;
2017
+ token from being generated.
2018
+
2019
+ - **logprobs** _boolean | number_
2020
+
2021
+ Return the log probabilities of the tokens. Including logprobs will increase
2022
+ the response size and can slow down response times. However, it can
2023
+ be useful to better understand how the model is behaving.
2024
+
2025
+ Setting to true will return the log probabilities of the tokens that
2026
+ were generated.
2027
+
2028
+ Setting to a number will return the log probabilities of the top n
2029
+ tokens that were generated.
2030
+
2031
+ - **suffix** _string_
2032
+
2033
+ The suffix that comes after a completion of inserted text.
2034
+
2035
+ - **user** _string_
2036
+
2037
+ A unique identifier representing your end-user, which can help OpenAI to
2038
+ monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids).
2039
+
2040
+ ### Model Capabilities
2041
+
2042
+ | Model | Image Input | Audio Input | Object Generation | Tool Usage |
2043
+ | --------------------- | ------------------- | ------------------- | ------------------- | ------------------- |
2044
+ | `gpt-5.2-pro` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2045
+ | `gpt-5.2-chat-latest` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2046
+ | `gpt-5.2` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2047
+ | `gpt-5.1-codex-mini` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2048
+ | `gpt-5.1-codex` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2049
+ | `gpt-5.1-chat-latest` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2050
+ | `gpt-5.1` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2051
+ | `gpt-5-pro` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2052
+ | `gpt-5` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2053
+ | `gpt-5-mini` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2054
+ | `gpt-5-nano` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2055
+ | `gpt-5-codex` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2056
+ | `gpt-5-chat-latest` | <Check size={18} /> | <Cross size={18} /> | <Cross size={18} /> | <Cross size={18} /> |
2057
+ | `gpt-4.1` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2058
+ | `gpt-4.1-mini` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2059
+ | `gpt-4.1-nano` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2060
+ | `gpt-4o` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2061
+ | `gpt-4o-mini` | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
2062
+
2063
+ <Note>
2064
+ The table above lists popular models. Please see the [OpenAI
2065
+ docs](https://platform.openai.com/docs/models) for a full list of available
2066
+ models. The table above lists popular models. You can also pass any available
2067
+ provider model ID as a string if needed.
2068
+ </Note>
2069
+
2070
+ ## Embedding Models
2071
+
2072
+ You can create models that call the [OpenAI embeddings API](https://platform.openai.com/docs/api-reference/embeddings)
2073
+ using the `.embedding()` factory method.
2074
+
2075
+ ```ts
2076
+ const model = openai.embedding('text-embedding-3-large');
2077
+ ```
2078
+
2079
+ OpenAI embedding models support several additional provider options.
2080
+ You can pass them as an options argument:
2081
+
2082
+ ```ts
2083
+ import { openai, type OpenAIEmbeddingModelOptions } from '@ai-sdk/openai';
2084
+ import { embed } from 'ai';
2085
+
2086
+ const { embedding } = await embed({
2087
+ model: openai.embedding('text-embedding-3-large'),
2088
+ value: 'sunny day at the beach',
2089
+ providerOptions: {
2090
+ openai: {
2091
+ dimensions: 512, // optional, number of dimensions for the embedding
2092
+ user: 'test-user', // optional unique user identifier
2093
+ } satisfies OpenAIEmbeddingModelOptions,
2094
+ },
2095
+ });
2096
+ ```
2097
+
2098
+ The following optional provider options are available for OpenAI embedding models:
2099
+
2100
+ - **dimensions**: _number_
2101
+
2102
+ The number of dimensions the resulting output embeddings should have.
2103
+ Only supported in text-embedding-3 and later models.
2104
+
2105
+ - **user** _string_
2106
+
2107
+ A unique identifier representing your end-user, which can help OpenAI to
2108
+ monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids).
2109
+
2110
+ ### Model Capabilities
2111
+
2112
+ | Model | Default Dimensions | Custom Dimensions |
2113
+ | ------------------------ | ------------------ | ------------------- |
2114
+ | `text-embedding-3-large` | 3072 | <Check size={18} /> |
2115
+ | `text-embedding-3-small` | 1536 | <Check size={18} /> |
2116
+ | `text-embedding-ada-002` | 1536 | <Cross size={18} /> |
2117
+
2118
+ ## Image Models
2119
+
2120
+ You can create models that call the [OpenAI image generation API](https://platform.openai.com/docs/api-reference/images)
2121
+ using the `.image()` factory method.
2122
+
2123
+ ```ts
2124
+ const model = openai.image('dall-e-3');
2125
+ ```
2126
+
2127
+ <Note>
2128
+ Dall-E models do not support the `aspectRatio` parameter. Use the `size`
2129
+ parameter instead.
2130
+ </Note>
2131
+
2132
+ ### Image Editing
2133
+
2134
+ OpenAI's `gpt-image-1` model supports powerful image editing capabilities. Pass input images via `prompt.images` to transform, combine, or edit existing images.
2135
+
2136
+ #### Basic Image Editing
2137
+
2138
+ Transform an existing image using text prompts:
2139
+
2140
+ ```ts
2141
+ const imageBuffer = readFileSync('./input-image.png');
2142
+
2143
+ const { images } = await generateImage({
2144
+ model: openai.image('gpt-image-1'),
2145
+ prompt: {
2146
+ text: 'Turn the cat into a dog but retain the style of the original image',
2147
+ images: [imageBuffer],
2148
+ },
2149
+ });
2150
+ ```
2151
+
2152
+ #### Inpainting with Mask
2153
+
2154
+ Edit specific parts of an image using a mask. Transparent areas in the mask indicate where the image should be edited:
2155
+
2156
+ ```ts
2157
+ const image = readFileSync('./input-image.png');
2158
+ const mask = readFileSync('./mask.png'); // Transparent areas = edit regions
2159
+
2160
+ const { images } = await generateImage({
2161
+ model: openai.image('gpt-image-1'),
2162
+ prompt: {
2163
+ text: 'A sunlit indoor lounge area with a pool containing a flamingo',
2164
+ images: [image],
2165
+ mask: mask,
2166
+ },
2167
+ });
2168
+ ```
2169
+
2170
+ #### Background Removal
2171
+
2172
+ Remove the background from an image by setting `background` to `transparent`:
2173
+
2174
+ ```ts
2175
+ const imageBuffer = readFileSync('./input-image.png');
2176
+
2177
+ const { images } = await generateImage({
2178
+ model: openai.image('gpt-image-1'),
2179
+ prompt: {
2180
+ text: 'do not change anything',
2181
+ images: [imageBuffer],
2182
+ },
2183
+ providerOptions: {
2184
+ openai: {
2185
+ background: 'transparent',
2186
+ output_format: 'png',
2187
+ },
2188
+ },
2189
+ });
2190
+ ```
2191
+
2192
+ #### Multi-Image Combining
2193
+
2194
+ Combine multiple reference images into a single output. `gpt-image-1` supports up to 16 input images:
2195
+
2196
+ ```ts
2197
+ const cat = readFileSync('./cat.png');
2198
+ const dog = readFileSync('./dog.png');
2199
+ const owl = readFileSync('./owl.png');
2200
+ const bear = readFileSync('./bear.png');
2201
+
2202
+ const { images } = await generateImage({
2203
+ model: openai.image('gpt-image-1'),
2204
+ prompt: {
2205
+ text: 'Combine these animals into a group photo, retaining the original style',
2206
+ images: [cat, dog, owl, bear],
2207
+ },
2208
+ });
2209
+ ```
2210
+
2211
+ <Note>
2212
+ Input images can be provided as `Buffer`, `ArrayBuffer`, `Uint8Array`, or
2213
+ base64-encoded strings. For `gpt-image-1`, each image should be a `png`,
2214
+ `webp`, or `jpg` file less than 50MB.
2215
+ </Note>
2216
+
2217
+ ### Model Capabilities
2218
+
2219
+ | Model | Sizes |
2220
+ | ------------------ | ------------------------------- |
2221
+ | `gpt-image-1.5` | 1024x1024, 1536x1024, 1024x1536 |
2222
+ | `gpt-image-1-mini` | 1024x1024, 1536x1024, 1024x1536 |
2223
+ | `gpt-image-1` | 1024x1024, 1536x1024, 1024x1536 |
2224
+ | `dall-e-3` | 1024x1024, 1792x1024, 1024x1792 |
2225
+ | `dall-e-2` | 256x256, 512x512, 1024x1024 |
2226
+
2227
+ 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-1` model supports the `quality` option:
2228
+
2229
+ ```ts
2230
+ const { image, providerMetadata } = await generateImage({
2231
+ model: openai.image('gpt-image-1.5'),
2232
+ prompt: 'A salamander at sunrise in a forest pond in the Seychelles.',
2233
+ providerOptions: {
2234
+ openai: { quality: 'high' },
2235
+ },
2236
+ });
2237
+ ```
2238
+
2239
+ For more on `generateImage()` see [Image Generation](/docs/ai-sdk-core/image-generation).
2240
+
2241
+ OpenAI's image models return additional metadata in the response that can be
2242
+ accessed via `providerMetadata.openai`. The following OpenAI-specific metadata
2243
+ is available:
2244
+
2245
+ - **images** _Array&lt;object&gt;_
2246
+
2247
+ Array of image-specific metadata. Each image object may contain:
2248
+
2249
+ - `revisedPrompt` _string_ - The revised prompt that was actually used to generate the image (OpenAI may modify your prompt for safety or clarity)
2250
+ - `created` _number_ - The Unix timestamp (in seconds) of when the image was created
2251
+ - `size` _string_ - The size of the generated image. One of `1024x1024`, `1024x1536`, or `1536x1024`
2252
+ - `quality` _string_ - The quality of the generated image. One of `low`, `medium`, or `high`
2253
+ - `background` _string_ - The background parameter used for the image generation. Either `transparent` or `opaque`
2254
+ - `outputFormat` _string_ - The output format of the generated image. One of `png`, `webp`, or `jpeg`
2255
+
2256
+ For more information on the available OpenAI image model options, see the [OpenAI API reference](https://platform.openai.com/docs/api-reference/images/create).
2257
+
2258
+ ## Transcription Models
2259
+
2260
+ You can create models that call the [OpenAI transcription API](https://platform.openai.com/docs/api-reference/audio/transcribe)
2261
+ using the `.transcription()` factory method.
2262
+
2263
+ The first argument is the model id e.g. `whisper-1`.
2264
+
2265
+ ```ts
2266
+ const model = openai.transcription('whisper-1');
2267
+ ```
2268
+
2269
+ 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.
2270
+
2271
+ ```ts highlight="6"
2272
+ import { experimental_transcribe as transcribe } from 'ai';
2273
+ import { openai, type OpenAITranscriptionModelOptions } from '@ai-sdk/openai';
2274
+
2275
+ const result = await transcribe({
2276
+ model: openai.transcription('whisper-1'),
2277
+ audio: new Uint8Array([1, 2, 3, 4]),
2278
+ providerOptions: {
2279
+ openai: { language: 'en' } satisfies OpenAITranscriptionModelOptions,
2280
+ },
2281
+ });
2282
+ ```
2283
+
2284
+ To get word-level timestamps, specify the granularity:
2285
+
2286
+ ```ts highlight="8-9"
2287
+ import { experimental_transcribe as transcribe } from 'ai';
2288
+ import { openai, type OpenAITranscriptionModelOptions } from '@ai-sdk/openai';
2289
+
2290
+ const result = await transcribe({
2291
+ model: openai.transcription('whisper-1'),
2292
+ audio: new Uint8Array([1, 2, 3, 4]),
2293
+ providerOptions: {
2294
+ openai: {
2295
+ //timestampGranularities: ['word'],
2296
+ timestampGranularities: ['segment'],
2297
+ } satisfies OpenAITranscriptionModelOptions,
2298
+ },
2299
+ });
2300
+
2301
+ // Access word-level timestamps
2302
+ console.log(result.segments); // Array of segments with startSecond/endSecond
2303
+ ```
2304
+
2305
+ The following provider options are available:
2306
+
2307
+ - **timestampGranularities** _string[]_
2308
+ The granularity of the timestamps in the transcription.
2309
+ Defaults to `['segment']`.
2310
+ Possible values are `['word']`, `['segment']`, and `['word', 'segment']`.
2311
+ Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.
2312
+
2313
+ - **language** _string_
2314
+ The language of the input audio. Supplying the input language in ISO-639-1 format (e.g. 'en') will improve accuracy and latency.
2315
+ Optional.
2316
+
2317
+ - **prompt** _string_
2318
+ An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.
2319
+ Optional.
2320
+
2321
+ - **temperature** _number_
2322
+ 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.
2323
+ Defaults to 0.
2324
+ Optional.
2325
+
2326
+ - **include** _string[]_
2327
+ Additional information to include in the transcription response.
2328
+
2329
+ ### Model Capabilities
2330
+
2331
+ | Model | Transcription | Duration | Segments | Language |
2332
+ | ------------------------ | ------------------- | ------------------- | ------------------- | ------------------- |
2333
+ | `whisper-1` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
2334
+ | `gpt-4o-mini-transcribe` | <Check size={18} /> | <Cross size={18} /> | <Cross size={18} /> | <Cross size={18} /> |
2335
+ | `gpt-4o-transcribe` | <Check size={18} /> | <Cross size={18} /> | <Cross size={18} /> | <Cross size={18} /> |
2336
+
2337
+ ## Speech Models
2338
+
2339
+ You can create models that call the [OpenAI speech API](https://platform.openai.com/docs/api-reference/audio/speech)
2340
+ using the `.speech()` factory method.
2341
+
2342
+ The first argument is the model id e.g. `tts-1`.
2343
+
2344
+ ```ts
2345
+ const model = openai.speech('tts-1');
2346
+ ```
2347
+
2348
+ The `voice` argument can be set to one of OpenAI's available voices: `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, or `shimmer`.
2349
+
2350
+ ```ts highlight="6"
2351
+ import { experimental_generateSpeech as generateSpeech } from 'ai';
2352
+ import { openai } from '@ai-sdk/openai';
2353
+
2354
+ const result = await generateSpeech({
2355
+ model: openai.speech('tts-1'),
2356
+ text: 'Hello, world!',
2357
+ voice: 'alloy', // OpenAI voice ID
2358
+ });
2359
+ ```
2360
+
2361
+ You can also pass additional provider-specific options using the `providerOptions` argument:
2362
+
2363
+ ```ts highlight="7-9"
2364
+ import { experimental_generateSpeech as generateSpeech } from 'ai';
2365
+ import { openai, type OpenAISpeechModelOptions } from '@ai-sdk/openai';
2366
+
2367
+ const result = await generateSpeech({
2368
+ model: openai.speech('tts-1'),
2369
+ text: 'Hello, world!',
2370
+ voice: 'alloy',
2371
+ providerOptions: {
2372
+ openai: {
2373
+ speed: 1.2,
2374
+ } satisfies OpenAISpeechModelOptions,
2375
+ },
2376
+ });
2377
+ ```
2378
+
2379
+ - **instructions** _string_
2380
+ Control the voice of your generated audio with additional instructions e.g. "Speak in a slow and steady tone".
2381
+ Does not work with `tts-1` or `tts-1-hd`.
2382
+ Optional.
2383
+
2384
+ - **speed** _number_
2385
+ The speed of the generated audio.
2386
+ Select a value from 0.25 to 4.0.
2387
+ Defaults to 1.0.
2388
+ Optional.
2389
+
2390
+ ### Model Capabilities
2391
+
2392
+ | Model | Instructions |
2393
+ | ----------------- | ------------------- |
2394
+ | `tts-1` | <Check size={18} /> |
2395
+ | `tts-1-hd` | <Check size={18} /> |
2396
+ | `gpt-4o-mini-tts` | <Check size={18} /> |