Open History to see the last commit
1---
2title: OpenAI
3id: openai-adapter
4order: 1
5description: "Use OpenAI models with TanStack AI — GPT-4o, GPT-5, DALL-E image generation, TTS, and Whisper transcription via @tanstack/ai-openai."
6keywords:
7 - tanstack ai
8 - openai
9 - gpt-4o
10 - gpt-5
11 - dall-e
12 - whisper
13 - openai tts
14 - adapter
15 - chatgpt
16---
17
18The OpenAI adapter provides access to OpenAI's models, including GPT-4o, GPT-5, image generation (DALL-E), text-to-speech (TTS), and audio transcription (Whisper).
19
20> Using a third-party provider that speaks the OpenAI API (DeepSeek, Moonshot/Kimi, Together, Fireworks, a local LM Studio/vLLM server, …)? See the [OpenAI-Compatible Adapter](./openai-compatible) for a generic `openaiCompatible({ baseURL, apiKey, models })` factory.
21
22## Installation
23
24<!-- ::start:tabs variant="package-manager" mode="install" -->
25
26react: @tanstack/ai-openai
27vue: @tanstack/ai-openai
28solid: @tanstack/ai-openai
29svelte: @tanstack/ai-openai
30preact: @tanstack/ai-openai
31angular: @tanstack/ai-openai
32vanilla: @tanstack/ai-openai
33octane: @tanstack/ai-openai
34
35<!-- ::end:tabs -->
36
37## Basic Usage
38
39```typescript
40import { chat } from "@tanstack/ai";
41import { openaiText } from "@tanstack/ai-openai";
42
43const stream = chat({
44 adapter: openaiText("gpt-5.2"),
45 messages: [{ role: "user", content: "Hello!" }],
46});
47```
48
49## Chat Completions API
50
51`@tanstack/ai-openai` ships two text adapters that hit different OpenAI endpoints. `openaiText` (default) calls the Responses API (`/v1/responses`). `openaiChatCompletions` calls the older Chat Completions API (`/v1/chat/completions`).
52
53Pick whichever fits your wire format and feature needs:
54
55| | `openaiText` (Responses) | `openaiChatCompletions` (Chat Completions) |
56|---|---|---|
57| Endpoint | `/v1/responses` | `/v1/chat/completions` |
58| Reasoning summaries | Yes. With `reasoning` set, the summary text streams as `REASONING_*` events | No. `reasoning` goes out as `reasoning_effort`, and no text streams back |
59| Wire-format compatibility | OpenAI-only | Matches the older de-facto industry shape (Grok, Groq, OpenRouter, many local model servers) |
60| Structured output streaming | `text.format: { type: 'json_schema', strict: true }` + `stream: true` | `response_format: { type: 'json_schema', strict: true }` + `stream: true` |
61
62Use `openaiText` when you want reasoning-summary streaming or OpenAI-specific Responses features. Use `openaiChatCompletions` when you're migrating off a Chat-Completions-style provider, share request-building code with other Chat-Completions adapters in your stack, or want the more battle-tested wire format.
63
64```typescript
65import { chat } from "@tanstack/ai";
66import { openaiChatCompletions } from "@tanstack/ai-openai";
67
68const stream = chat({
69 adapter: openaiChatCompletions("gpt-5.2"),
70 messages: [{ role: "user", content: "Hello!" }],
71});
72```
73
74With an explicit API key:
75
76```typescript
77import { chat } from "@tanstack/ai";
78import { createOpenaiChatCompletions } from "@tanstack/ai-openai";
79
80const adapter = createOpenaiChatCompletions("gpt-5.2", process.env.OPENAI_API_KEY!, {
81 // organization, baseURL, headers — all optional
82});
83
84const stream = chat({
85 adapter,
86 messages: [{ role: "user", content: "Hello!" }],
87});
88```
89
90Both adapters work the same with [Structured Outputs](../structured-outputs/overview), including `stream: true`, and accept the same `modelOptions` (temperature, top_p, max_tokens, stop, and more). Both take [`reasoning`](#reasoning). `openaiChatCompletions` cannot stream the thinking text.
91
92## Azure OpenAI
93
94Your OpenAI model runs as a deployment in Azure? Use `createAzureOpenaiText`. It calls the Azure Responses API and sends your key in the `api-key` header.
95
96```typescript
97import { chat, toServerSentEventsResponse } from "@tanstack/ai";
98import { createAzureOpenaiText } from "@tanstack/ai-openai";
99
100export async function POST(request: Request) {
101 const { messages } = await request.json();
102
103 const stream = chat({
104 adapter: createAzureOpenaiText("gpt-5.6", process.env.AZURE_OPENAI_API_KEY!, {
105 resourceName: "my-resource",
106 deploymentName: "production-chat",
107 }),
108 messages,
109 });
110
111 return toServerSentEventsResponse(stream);
112}
113```
114
115Azure gets `production-chat` as the model. Your code still uses `gpt-5.6`. The client does not change: it reads this route like any other chat route.
116
117`reasoning` takes the levels of the OpenAI model name, here `gpt-5.6`. A model name that is not an OpenAI model, such as a bare deployment name, takes no `reasoning`. See [Reasoning](#reasoning).
118
119`createAzureOpenaiText` reads nothing from the environment. You pass the key, and you pass the endpoint as `resourceName` or `baseURL`.
120
121Rather keep it all in the environment? Use `azureOpenaiText`. Like `openaiText`, it reads the key from the environment:
122
123```sh
124AZURE_OPENAI_API_KEY=your-key
125AZURE_OPENAI_RESOURCE_NAME=my-resource
126AZURE_OPENAI_DEPLOYMENT_NAME_MAP=gpt-5.6=production-chat
127```
128
129```typescript
130import { azureOpenaiText } from "@tanstack/ai-openai";
131
132const adapter = azureOpenaiText("gpt-5.6");
133```
134
135`azureOpenaiText` always reads the key from `AZURE_OPENAI_API_KEY`, and it throws when that is not set. For the other values, the config wins over the environment:
136
137- **Endpoint:** `baseURL`, then `resourceName`, then `AZURE_OPENAI_BASE_URL`, then `AZURE_OPENAI_RESOURCE_NAME`. You must set one of them.
138- **API version:** `apiVersion`, then `AZURE_OPENAI_API_VERSION`, then `v1`.
139- **Deployment:** `deploymentName`, then `deploymentNameMap`, then `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`, then the model name. A `deploymentNameMap` in the config replaces the environment map. The two maps do not merge.
140
141An Azure resource URL always goes to the `/openai/v1` path. A proxy URL keeps its own path.
142
143## Basic Usage - Custom API Key
144
145```typescript
146import { chat } from "@tanstack/ai";
147import { createOpenaiChat } from "@tanstack/ai-openai";
148
149const adapter = createOpenaiChat("gpt-5.2", process.env.OPENAI_API_KEY!, {
150 // ... your config options
151});
152
153const stream = chat({
154 adapter,
155 messages: [{ role: "user", content: "Hello!" }],
156});
157```
158
159## Sign in with ChatGPT (BYOK)
160
161Many of your users have a ChatGPT plan but no API key. Let them sign in with ChatGPT. The token bills their ChatGPT plan, not your account.
162
163The helpers in `@tanstack/ai-openai/siwc` put the access token into the `openai` [BYOK](../advanced/byok) slot. Your relay reads it like a pasted key.
164
165Before you start, check these limits:
166
167- OpenAI allows this sign-in only for open-source and locally hosted apps. For a hosted app, fill in the [interest form](https://openai.com/form/sign-in-with-chatgpt-interest/).
168- OpenAI redirects only to `127.0.0.1`. Something must answer on that address. Vite listens on `::1` by default. The `ts-react-chat` example runs a small script on `127.0.0.1:3000` that redirects to `localhost:3000`.
169- Keep the app on `localhost`, because passkey storage does not work on an IP address. The callback lands on `127.0.0.1`, then `completeChatGptSignIn` sends the browser back to `localhost`.
170- The callback page must be at `/auth/callback`.
171
172### 1. Add the sign-in button
173
174Call `startChatGptSignIn` from a click. `agentName` is your app name. OpenAI shows it on the consent screen.
175
176```tsx
177import { startChatGptSignIn } from "@tanstack/ai-openai/siwc";
178
179export function ChatGptButton() {
180 return (
181 <button
182 type="button"
183 onClick={() => {
184 void startChatGptSignIn({ agentName: "My App" });
185 }}
186 >
187 Continue with ChatGPT
188 </button>
189 );
190}
191```
192
193### 2. Finish on `/auth/callback`
194
195Render this component on the `/auth/callback` route. It exchanges the code when the page loads. Then the user clicks to save.
196
197```tsx
198import { useEffect, useRef, useState } from "react";
199import {
200 completeChatGptSignIn,
201 saveChatGptSignIn,
202} from "@tanstack/ai-openai/siwc";
203import type { ChatGptSignIn } from "@tanstack/ai-openai/siwc";
204import { byok } from "./byok";
205
206export function ChatGptCallback() {
207 const started = useRef(false);
208 const [signIn, setSignIn] = useState<ChatGptSignIn | null>(null);
209 const [error, setError] = useState("");
210
211 useEffect(() => {
212 // The code works one time. Strict Mode runs effects two times.
213 if (started.current) return;
214 started.current = true;
215 completeChatGptSignIn().then(setSignIn, (caught: unknown) => {
216 setError(caught instanceof Error ? caught.message : "Sign-in failed");
217 });
218 }, []);
219
220 if (error) return <p>{error}</p>;
221 if (!signIn) return <p>Finishing sign-in...</p>;
222 return (
223 <button
224 type="button"
225 onClick={() => {
226 void saveChatGptSignIn(byok, signIn);
227 }}
228 >
229 Save ChatGPT sign-in
230 </button>
231 );
232}
233```
234
235The save needs a click because passkey storage shows a browser prompt. The refresh token goes into a second keyring slot. No send attaches that slot, so the refresh token stays in the browser.
236
237### 3. Refresh the token
238
239The access token lasts one hour. Call `refreshChatGptSignIn` on a timer:
240
241```tsx
242import { useEffect } from "react";
243import { refreshChatGptSignIn } from "@tanstack/ai-openai/siwc";
244import { byok } from "./byok";
245
246export function useChatGptRefresh() {
247 useEffect(() => {
248 const refresh = () => {
249 refreshChatGptSignIn(byok).catch(console.error);
250 };
251 refresh();
252 const timer = setInterval(refresh, 60_000);
253 return () => clearInterval(timer);
254 }, []);
255}
256```
257
258The call does nothing until the token has less than five minutes left. If OpenAI rejects the refresh token, the call clears the sign-in. Then the user must sign in again.
259
260### 4. Read the token on the relay
261
262The relay code is the same as for a pasted key. Add `store: false`, because the ChatGPT route requires it.
263
264```typescript
265import {
266 chat,
267 chatParamsFromRequest,
268 toServerSentEventsResponse,
269} from "@tanstack/ai";
270import { createOpenaiChat } from "@tanstack/ai-openai";
271import { openaiByok } from "@tanstack/ai-openai/byok";
272import { byokMissing, getByokKey } from "@tanstack/ai/byok/server";
273
274export async function POST(request: Request) {
275 const params = await chatParamsFromRequest(request);
276 const apiKey = getByokKey(request, openaiByok);
277 if (!apiKey) return byokMissing(openaiByok);
278
279 const stream = chat({
280 adapter: createOpenaiChat("gpt-6-astra", apiKey),
281 messages: params.messages,
282 threadId: params.threadId,
283 runId: params.runId,
284 modelOptions: { store: false },
285 });
286 return toServerSentEventsResponse(stream);
287}
288```
289
290`store: false` also works with an API key. A ChatGPT token does not start with `sk-`, so use that test if you must send different options.
291
292The ChatGPT route has these limits:
293
294- Use a model that the user's ChatGPT plan includes.
295- Do not send `temperature`, `top_p`, `max_output_tokens`, `metadata`, or `previous_response_id`.
296- Hosted tools do not work. This includes image generation, file search, code interpreter, computer use, and hosted MCP.
297- Audio input and transcription do not work.
298
299Click **Continue with ChatGPT**, approve, save, then send a message. The relay calls OpenAI on the user's ChatGPT plan.
300
301The `ts-react-chat` example has this flow in its key dialog.
302
303## Configuration
304
305```typescript
306import { createOpenaiChat, type OpenAITextConfig } from "@tanstack/ai-openai";
307
308const config: Omit<OpenAITextConfig, "apiKey"> = {
309 organization: "org-...", // Optional
310 baseURL: "https://api.openai.com/v1", // Optional, for custom endpoints
311};
312
313const adapter = createOpenaiChat("gpt-5.2", process.env.OPENAI_API_KEY!, config);
314```
315
316Need a header on each request, or a log of each model call? The chat adapters on this page support [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call).
317
318### Tools that cannot use strict mode
319
320OpenAI holds tool arguments to the schema only when the tool is sent with `strict: true`. Some schemas cannot be strict, for example a schema that uses `$ref`, `z.any()`, or `z.record()`. The adapter sends these tools with `strict: false`, so the tool still works. The model can then return arguments that do not match the schema.
321
322In development, the adapter logs a warning once for each of these tools:
323
324```txt
325tool "lookup_user" sent with strict: false: schema uses $ref, which strict mode does not support
326```
327
328To get strict mode back, change the schema so that the reason goes away. If you accept a non-strict tool, turn the warning off in the adapter config:
329
330```typescript
331import { createOpenaiChat } from "@tanstack/ai-openai";
332
333const adapter = createOpenaiChat("gpt-6-astra", process.env.OPENAI_API_KEY!, {
334 strictFallbackWarning: false,
335});
336```
337
338The warning never runs when `NODE_ENV` is `production`. The same option works on every adapter built on the OpenAI API, for example Groq, Bedrock, and Vercel AI Gateway.
340## Example: Chat Completion
341
342```typescript
343import { chat, toServerSentEventsResponse } from "@tanstack/ai";
344import { openaiText } from "@tanstack/ai-openai";
345
346export async function POST(request: Request) {
347 const { messages } = await request.json();
348
349 const stream = chat({
350 adapter: openaiText("gpt-5.2"),
351 messages,
352 });
353
354 return toServerSentEventsResponse(stream);
355}
356```
357
358## Example: With Tools
359
360```typescript
361import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
362import { openaiText } from "@tanstack/ai-openai";
363import { z } from "zod";
364
365const getWeatherDef = toolDefinition({
366 name: "get_weather",
367 description: "Get the current weather",
368 inputSchema: z.object({
369 location: z.string(),
370 }),
371});
372
373const getWeather = getWeatherDef.server(async ({ location }) => {
374 // Fetch weather data
375 return { temperature: 72, conditions: "sunny" };
376});
377
378export async function POST(request: Request) {
379 const { messages } = await request.json();
380
381 const stream = chat({
382 adapter: openaiText("gpt-5.2"),
383 messages,
384 tools: [getWeather],
385 });
386
387 return toServerSentEventsResponse(stream);
388}
389```
390
391## Model Options
392
393OpenAI supports various provider-specific options. Sampling parameters live here too — `temperature`, `top_p`, and `max_output_tokens` (the Responses API token-limit key) — rather than as root-level props on `chat()`:
394
395```typescript
396import { chat } from "@tanstack/ai";
397import { openaiText } from "@tanstack/ai-openai";
398
399const stream = chat({
400 adapter: openaiText("gpt-5.2"),
401 messages: [{ role: "user", content: "Hello!" }],
402 modelOptions: {
403 temperature: 0.7,
404 max_output_tokens: 1000,
405 top_p: 0.9,
406 },
407});
408```
409
410> The `openaiChatCompletions` adapter targets `/v1/chat/completions`, where the token-limit key is `max_tokens` (not `max_output_tokens`). If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
411
412## Reasoning
413
414Want GPT to think harder, or skip it? Set `reasoning` on `chat()`:
415
416```typescript
417import { chat } from "@tanstack/ai";
418import { openaiText } from "@tanstack/ai-openai";
419
420const stream = chat({
421 adapter: openaiText("gpt-6.1-sol"),
422 messages: [{ role: "user", content: "Plan a database migration." }],
423 reasoning: "xhigh",
424});
425```
426
427What goes on the wire:
428
429- `openaiText` and `azureOpenaiText`: `reasoning: { effort, summary: "auto" }`. The summary text streams as thinking parts. `summary: false` drops the summary.
430- `openaiChatCompletions`: `reasoning_effort`. No thinking text streams back.
431- `off` sends `effort: "none"` on the models that can stop thinking.
432
433The levels of each model:
434
435| Model | Levels |
436| --- | --- |
437| `gpt-6.1-sol`, `gpt-6.1-sol-pro`, `gpt-6-astra`, `gpt-6-astra-pro` | `low` to `max` |
438| `gpt-6-sol`, `gpt-6-luna`, the `gpt-5.6` models, and their `-pro` versions | `off`, `low` to `max` |
439| `gpt-5.5`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.4-image-2`, `gpt-5.2` | `off`, `low` to `xhigh` |
440| `gpt-5.5-pro`, `gpt-5.2-pro` | `medium`, `high`, `xhigh` |
441| `gpt-5.1` | `off`, `low`, `medium`, `high` |
442| `gpt-5`, `gpt-5-mini`, `gpt-5-nano` | `minimal` to `high` |
443| `gpt-chat-latest`, the `o` models, and the `codex` models | `low`, `medium`, `high` |
444| `gpt-5.2-chat-latest` | `medium` |
445| `gpt-5-pro` | `high` |
446
447The other models, such as `gpt-4.1` and `gpt-4o`, take no `reasoning`.
448
449### Native compaction
450
451OpenAI can compact a long conversation on its side, with `POST /responses/compact`. The Responses adapters (`openaiText` and `createOpenaiChat`) have a `compact` method for it. Turn it on with the `native` option of `withCompaction`:
452
453```typescript
454import { chat } from "@tanstack/ai";
455import { openaiText } from "@tanstack/ai-openai";
456import { withCompaction } from "@tanstack/ai-compaction";
457
458const adapter = openaiText("gpt-6.1-sol");
459
460const stream = chat({
461 adapter,
462 messages: [{ role: "user", content: "Hello!" }],
463 middleware: [withCompaction({ maxTokens: 100_000, native: adapter })],
464});
465```
466
467- The result holds your user messages and one encrypted `compaction` item.
468- The adapter sends that item back as it is on each later request to the same model.
469- `openaiChatCompletions` has no `compact` method, so `withCompaction` uses its `strategy`.
470
471See [Let the provider compact](../advanced/compaction#let-the-provider-compact).
472
473### Answers on the next request
474
475OpenAI gives each answer item an `id` and a `phase`: `commentary` for text before a tool call, and `final_answer` for the answer. The Responses adapters (`openaiText` and `createOpenaiChat`) keep both in the assistant message, in `metadata.tanstack.responseItems`. When the same model gets that message again, for example on the next turn, the adapter sends each item back with its `id` and `phase`. Another model gets the plain text.
476
477### Prompt caching
478
479`chat()` sends `prompt_cache_key` by default, set to the `threadId` that you pass. OpenAI uses the key to send requests with the same start to the same cache. With `promptCache: 'long'`, it also asks for the long retention. See [Prompt Caching](../advanced/prompt-caching).
480
481Want your own key? Set it in `modelOptions`. Your value wins:
482
483```typescript
484import { chat } from "@tanstack/ai";
485import { openaiText } from "@tanstack/ai-openai";
486
487const stream = chat({
488 adapter: openaiText("gpt-6.1-sol"),
489 messages: [{ role: "user", content: "Hello!" }],
490 modelOptions: {
491 prompt_cache_key: "acme-support",
492 },
493});
494```
495
496On gpt-5.6 and later, `modelOptions.prompt_cache_options` wins over the automatic options. On earlier models, `modelOptions.prompt_cache_retention` wins over the automatic retention. `openaiChatCompletions` sends the key only to `api.openai.com` and its regional hosts (such as `eu.api.openai.com`), unless you pass `promptCache: 'long'`.
497
498#### Tools and prompts added during a conversation
499
500On `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `gpt-6-luna`, and `gpt-6-sol`, a tool or a system prompt that you add between model calls goes into the conversation. The cached start stays the same.
501
502What `openaiText` sends on these models:
503
504- `tools` and `instructions` keep the tools and the system prompts of the first call.
505- An added tool goes into `input` as `{ type: "additional_tools", role: "developer", tools: [...] }`.
506- An added system prompt goes into `input` as a `developer` message, at its place in the conversation.
507- With a provider tool such as `webSearchTool()`, `tools` is the full list for that request.
508
509The channels are on by default with OpenAI's own API. A custom `baseURL`, a custom `fetch`, or `OPENAI_BASE_URL` turns them off. Set `midConversationChannels` to choose:
510
511```typescript
512import { openaiText } from "@tanstack/ai-openai";
513
514export const fullLists = openaiText("gpt-6-astra", { midConversationChannels: false });
515
516export const throughProxy = openaiText("gpt-6-astra", {
517 baseURL: "https://llm-proxy.example.com/v1",
518 midConversationChannels: true,
519});
520```
521
522If that endpoint sends the request on to OpenAI as it is, set `true`. See [Mid-Conversation Changes](../advanced/mid-conversation-changes).
523
524## Summarization
525
526Summarize long text content:
527
528```typescript
529import { summarize } from "@tanstack/ai";
530import { openaiSummarize } from "@tanstack/ai-openai";
531
532const result = await summarize({
533 adapter: openaiSummarize("gpt-5-mini"),
534 text: "Your long text to summarize...",
535 maxLength: 100,
536 style: "concise", // "concise" | "bullet-points" | "paragraph"
537});
538
539console.log(result.summary);
540```
541
542## Embeddings
543
544Generate embedding vectors with the text-embedding-3 models:
545
546```typescript
547import { embed } from "@tanstack/ai";
548import { openaiEmbedding } from "@tanstack/ai-openai";
549
550const result = await embed({
551 adapter: openaiEmbedding("text-embedding-3-small"),
552 input: ["a red guitar", "a blue drum kit"],
553});
554
555console.log(result.embeddings[0]?.vector);
556console.log(result.usage?.promptTokens);
557```
558
559Both models support Matryoshka dimension reduction via the top-level `dimensions` option:
560
561```typescript
562import { embed } from "@tanstack/ai";
563import { openaiEmbedding } from "@tanstack/ai-openai";
564
565const result = await embed({
566 adapter: openaiEmbedding("text-embedding-3-large"),
567 input: "a red guitar",
568 dimensions: 1024,
569});
570```
571
572See the [Embeddings guide](../embeddings.md) for the full API.
573
574## Image Generation
575
576Generate images:
577
578```typescript
579import { generateImage } from "@tanstack/ai";
580import { openaiImage } from "@tanstack/ai-openai";
581
582const result = await generateImage({
583 adapter: openaiImage("gpt-image-2"),
584 prompt: "A futuristic cityscape at sunset",
585 numberOfImages: 1,
586 size: "1024x1024",
587});
588
589console.log(result.images);
590```
591
592### Image Model Options
593
594```typescript
595import { generateImage } from "@tanstack/ai";
596import { openaiImage } from "@tanstack/ai-openai";
597
598const result = await generateImage({
599 adapter: openaiImage("gpt-image-2"),
600 prompt: "...",
601 modelOptions: {
602 quality: "high", // "high" | "medium" | "low" | "auto"
603 },
604});
605```
606
607## Text-to-Speech
608
609Generate speech from text:
610
611```typescript
612import { generateSpeech } from "@tanstack/ai";
613import { openaiSpeech } from "@tanstack/ai-openai";
614
615const result = await generateSpeech({
616 adapter: openaiSpeech("tts-1"),
617 text: "Hello, welcome to TanStack AI!",
618 voice: "alloy",
619 format: "mp3",
620});
621
622// result.audio contains base64-encoded audio
623console.log(result.format); // "mp3"
624```
625
626### TTS Voices
627
628Available voices: `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, `ash`, `ballad`, `coral`, `sage`, `verse`
629
630### TTS Model Options
631
632```typescript
633import { generateSpeech } from "@tanstack/ai";
634import { openaiSpeech } from "@tanstack/ai-openai";
635
636const result = await generateSpeech({
637 adapter: openaiSpeech("tts-1-hd"),
638 text: "High quality speech",
639 modelOptions: {
640 instructions: "Speak slowly and clearly.", // voice instructions (not supported by tts-1/tts-1-hd)
641 },
642});
643```
644
645## Transcription
646
647Transcribe audio to text:
648
649```typescript
650import { generateTranscription } from "@tanstack/ai";
651import { openaiTranscription } from "@tanstack/ai-openai";
652import { audioFile } from "./audio";
653
654const result = await generateTranscription({
655 adapter: openaiTranscription("whisper-1"),
656 audio: audioFile, // File object or base64 string
657 language: "en",
658});
659
660console.log(result.text); // Transcribed text
661```
662
663### Transcription Model Options
664
665```typescript
666import { generateTranscription } from "@tanstack/ai";
667import { openaiTranscription } from "@tanstack/ai-openai";
668import { audioFile } from "./audio";
669
670const result = await generateTranscription({
671 adapter: openaiTranscription("whisper-1"),
672 audio: audioFile,
673 responseFormat: "verbose_json",
674 prompt: "Technical terms: API, SDK",
675 modelOptions: {
676 temperature: 0,
677 timestamp_granularities: ["word", "segment"],
678 },
679});
680
681// Access the transcribed text
682console.log(result.text);
683```
684
685### Speaker Diarization
686
687Use `gpt-4o-transcribe-diarize` for speaker-labeled transcripts:
688
689```typescript
690import { generateTranscription } from "@tanstack/ai";
691import { openaiTranscription } from "@tanstack/ai-openai";
692import { meetingAudioFile } from "./audio";
693
694const result = await generateTranscription({
695 adapter: openaiTranscription("gpt-4o-transcribe-diarize"),
696 audio: meetingAudioFile,
697 modelOptions: {
698 known_speaker_names: ["agent", "customer"],
699 known_speaker_references: [
700 "data:audio/wav;base64,...",
701 "data:audio/wav;base64,...",
702 ],
703 },
704});
705
706for (const segment of result.segments ?? []) {
707 console.log(segment.speaker, segment.start, segment.end, segment.text);
708}
709```
710
711When no response format is specified, `gpt-4o-transcribe-diarize` requests default to `response_format: "diarized_json"` and `chunking_strategy: "auto"`; passing a top-level `responseFormat` of `"json"` or `"text"` opts out of speaker segments. `known_speaker_names` and `known_speaker_references` must be provided together (up to 4, matching lengths). OpenAI does not support `prompt`, `include`, or `timestamp_granularities` with diarized transcription.
712
713## Evaluate
714
715Sometimes you need an answer that your code can branch on, not chat text. Examples are a queue name, an urgency level, or a yes or no.
716Use `openaiDecider` with `decide()` to ask typed questions about one shared `state`. The adapter calls the OpenAI Decisions API (`/v1/decisions`):
717
718```typescript
719import { decide, choice, score, boolean } from "@tanstack/ai";
720import { openaiDecider } from "@tanstack/ai-openai";
721
722const ticket = {
723 subject: "Charged twice for the same invoice",
724 body: "Please refund the extra payment.",
725};
726
727const result = await decide({
728 adapter: openaiDecider("gpt-6-luna"),
729 state: ticket,
730 questions: {
731 queue: choice({
732 instructions: "Which team should handle this ticket?",
733 options: {
734 billing: "Payments, invoices, refunds",
735 tech: "Bugs, outages, integrations",
736 sales: "Pricing, upgrades, new accounts",
737 },
738 }),
739 urgency: score({
740 instructions: "How urgent is this ticket?",
741 levels: ["low", "medium", "high"],
742 }),
743 refund: boolean({
744 instructions: "Is the customer asking for a refund?",
745 }),
746 },
747});
748
749console.log(result.queue.value); // "billing"
750console.log(result.urgency.value); // "medium"
751console.log(result.refund.value); // true
752console.log(result.meta.usage);
753```
754
755`openaiDecider` reads `OPENAI_API_KEY` from the environment. To pass a key yourself, use `createOpenaiDecider("gpt-6-luna", "sk-...")`.
756
757Good to know:
758
759- `gpt-6-luna` is the only Decisions model.
760- An object `state` goes to OpenAI as JSON text.
761- If OpenAI refuses to answer a question, `decide()` throws an error with the name of that question.
762- `boolean()` criteria work. The adapter adds the true and false meanings to the instructions.
763
764See the [Evaluate guide](../evaluate/evaluate) for question helpers, the result shape, abort, and middleware.
765
766## Environment Variables
767
768Set your API key in environment variables:
769
770```bash
771OPENAI_API_KEY=sk-...
772```
773
774## API Reference
775
776Every factory pair follows the same shape: the short factory (`openaiText`, `openaiImage`, …) reads `OPENAI_API_KEY` from the environment, while the `create*` variant takes an explicit API key. Both take `model` as the first argument.
777
778### `openaiText(model, config?)`
779
780Creates an OpenAI text adapter against the Responses API (`/v1/responses`) using `OPENAI_API_KEY` from the environment.
781
782`adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
783
784**Parameters:**
785
786- `model` - OpenAI chat model id (e.g. `"gpt-5.2"`, `"gpt-4o-mini"`)
787- `config?.organization` - Organization ID (optional)
788- `config?.baseURL` - Custom base URL (optional)
789
790### `createOpenaiChat(model, apiKey, config?)`
791
792Creates an OpenAI text adapter (Responses API) with an explicit API key.
793
794### `openaiChatCompletions(model, config?)`
795
796Creates an OpenAI text adapter that targets `/v1/chat/completions` instead of the Responses API. See [Chat Completions API](#chat-completions-api) for when to use this over `openaiText`.
797
798### `createOpenaiChatCompletions(model, apiKey, config?)`
799
800Creates an OpenAI chat-completions adapter with an explicit API key.
801
802### `openaiSummarize(model, config?)` / `createOpenaiSummarize(model, apiKey, config?)`
803
804Creates an OpenAI summarization adapter.
805
806### `openaiImage(model, config?)` / `createOpenaiImage(model, apiKey, config?)`
807
808Creates an OpenAI image generation adapter (DALL-E, gpt-image).
809
810### `openaiSpeech(model, config?)` / `createOpenaiSpeech(model, apiKey, config?)`
811
812Creates an OpenAI text-to-speech adapter.
813
814### `openaiTranscription(model, config?)` / `createOpenaiTranscription(model, apiKey, config?)`
815
816Creates an OpenAI transcription adapter for Whisper, GPT-4o transcription, and GPT-4o diarized transcription models.
817
818### `openaiVideo(model, config?)` / `createOpenaiVideo(model, apiKey, config?)`
819
820Creates an OpenAI video generation adapter (Sora). _Experimental._
821
822### `openaiDecider(model, config?)` / `createOpenaiDecider(model, apiKey, config?)`
823
824Creates an OpenAI evaluate adapter for `decide()`. See [Evaluate](#evaluate) for usage.
825
826### `openaiRealtime(...)` / `openaiRealtimeToken(...)`
827
828Realtime voice adapters. See [Realtime Voice Chat](../media/realtime-chat) for usage.
829
830## Next Steps
831
832- [Getting Started](../getting-started/quick-start) - Learn the basics
833- [Tools Guide](../tools/tools) - Learn about tools
834- [Other Adapters](./anthropic) - Explore other providers
835
836## Provider Tools
837
838OpenAI exposes several native tools beyond user-defined function calls.
839Import them from `@tanstack/ai-openai/tools` and pass them into
840`chat({ tools: [...] })`.
841
842> For the full concept, a comparison matrix, and type-gating details, see
843> [Provider Tools](../tools/provider-tools.md).
844
845### `webSearchTool`
846
847Enables the model to run a web search and return grounded results with
848citations. Pass a `WebSearchToolConfig` object (typed from the OpenAI SDK)
849to configure the tool.
850
851```typescript
852import { chat } from "@tanstack/ai";
853import { openaiText } from "@tanstack/ai-openai";
854import { webSearchTool } from "@tanstack/ai-openai/tools";
855
856const stream = chat({
857 adapter: openaiText("gpt-5.2"),
858 messages: [{ role: "user", content: "What's new in AI this week?" }],
859 tools: [webSearchTool({ type: "web_search" })],
860});
861```
862
863**Supported models:** GPT-4o, GPT-5, and Responses API-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
864
865### `webSearchPreviewTool`
866
867The preview variant of web search with additional options for controlling
868search context size and user location. Use this when you want fine-grained
869control over the search context sent to the model.
870
871```typescript
872import { chat } from "@tanstack/ai";
873import { openaiText } from "@tanstack/ai-openai";
874import { webSearchPreviewTool } from "@tanstack/ai-openai/tools";
875
876const stream = chat({
877 adapter: openaiText("gpt-5.2"),
878 messages: [{ role: "user", content: "Latest news about TypeScript" }],
879 tools: [
880 webSearchPreviewTool({
881 type: "web_search_preview_2025_03_11",
882 search_context_size: "high",
883 }),
884 ],
885});
886```
887
888**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
889
890When the model uses hosted web search, the assistant tool-call part includes
891`metadata.providerExecuted: true` and the normalized `metadata.sources` array.
892OpenAI's raw search call and URL citations stay under `metadata.openai`. The
893agent loop does not execute this call in your application, and the adapter
894replays the raw response items on the next turn.
895
896### `fileSearchTool`
897
898Searches OpenAI vector stores that you have pre-populated, letting the model
899retrieve relevant document chunks. Provide the `vector_store_ids` to search
900and optionally limit results with `max_num_results` (1–50).
901
902```typescript
903import { chat } from "@tanstack/ai";
904import { openaiText } from "@tanstack/ai-openai";
905import { fileSearchTool } from "@tanstack/ai-openai/tools";
906
907const stream = chat({
908 adapter: openaiText("gpt-5.2"),
909 messages: [{ role: "user", content: "What does the handbook say about PTO?" }],
910 tools: [
911 fileSearchTool({
912 type: "file_search",
913 vector_store_ids: ["vs_abc123"],
914 max_num_results: 5,
915 }),
916 ],
917});
918```
919
920**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
921
922### `imageGenerationTool`
923
924Allows the model to generate images inline during a conversation using
925DALL-E/GPT-Image. Pass quality, size, and style options via the config object.
926
927```typescript
928import { chat } from "@tanstack/ai";
929import { openaiText } from "@tanstack/ai-openai";
930import { imageGenerationTool } from "@tanstack/ai-openai/tools";
931
932const stream = chat({
933 adapter: openaiText("gpt-5.2"),
934 messages: [{ role: "user", content: "Draw a logo for my app" }],
935 tools: [
936 imageGenerationTool({
937 quality: "high",
938 size: "1024x1024",
939 }),
940 ],
941});
942```
943
944**Supported models:** GPT-5 and GPT-Image-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
945
946### `codeInterpreterTool`
947
948Gives the model a sandboxed Python execution environment. The `container`
949field configures the execution environment; pass the full
950`CodeInterpreterToolConfig` object.
951
952```typescript
953import { chat } from "@tanstack/ai";
954import { openaiText } from "@tanstack/ai-openai";
955import { codeInterpreterTool } from "@tanstack/ai-openai/tools";
956
957const stream = chat({
958 adapter: openaiText("gpt-5.2"),
959 messages: [{ role: "user", content: "Analyse this CSV and plot a chart" }],
960 tools: [
961 codeInterpreterTool({ type: "code_interpreter", container: { type: "auto" } }),
962 ],
963});
964```
965
966**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
967
968### `mcpTool`
969
970Connects the model to a remote MCP (Model Context Protocol) server, exposing
971all its capabilities as callable tools. Provide either `server_url` or
972`connector_id` — not both.
973
974```typescript
975import { chat } from "@tanstack/ai";
976import { openaiText } from "@tanstack/ai-openai";
977import { mcpTool } from "@tanstack/ai-openai/tools";
978
979const stream = chat({
980 adapter: openaiText("gpt-5.2"),
981 messages: [{ role: "user", content: "List my GitHub issues" }],
982 tools: [
983 mcpTool({
984 server_url: "https://mcp.example.com",
985 server_label: "github",
986 }),
987 ],
988});
989```
990
991**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
992
993### `computerUseTool`
994
995The model can look at a screen and use the mouse and the keyboard. Your app runs each action and sends back a screenshot. `createComputerUse` from `@tanstack/ai-computer-use` does this on a Playwright browser or an E2B desktop. Each thread gets its own machine:
996
997```typescript
998import { chat } from "@tanstack/ai";
999import { openaiText } from "@tanstack/ai-openai";
1000import { createComputerUse } from "@tanstack/ai-computer-use";
1001import { playwrightComputer } from "@tanstack/ai-computer-playwright";
1002
1003declare const threadId: string;
1004
1005const computerUse = createComputerUse({
1006 driver: playwrightComputer({ startUrl: "https://tanstack.com" }),
1007});
1008
1009const stream = chat({
1010 adapter: openaiText("gpt-6.1-sol"),
1011 messages: [{ role: "user", content: "Find the TanStack AI docs" }],
1012 threadId,
1013 tools: computerUse.tools,
1014 middleware: [computerUse.middleware],
1015 interrupts: [computerUse.interrupt],
1016});
1017```
1018
1019The adapter sends the `computer` tool to OpenAI as its native computer tool.
1020
1021- For the setup, the threads, and how to close the machines, see [Computer use](../computer-use/computer-use.md).
1022- For the approval of OpenAI safety checks, see [Safety checks](../computer-use/safety-checks.md).
1023- For your own machine, see [Custom driver](../computer-use/custom-driver.md).
1024
1025#### The raw tool
1026
1027`computerUseTool` from `@tanstack/ai-openai/tools` is the native tool with no `execute`. Use it when your app runs the actions itself:
1028
1029```typescript
1030import { computerUseTool } from "@tanstack/ai-openai/tools";
1031
1032const computer = computerUseTool({ type: "computer" });
1033```
1034
1035Add an `execute` that runs the actions and returns a screenshot as an image part. The input of each call has two fields:
1036
1037- `actions`: the actions to run, in order, as OpenAI sends them. For example `[{ type: "click", button: "left", x: 120, y: 340 }, { type: "type", text: "ada@example.com" }]`.
1038- `pending_safety_checks`: the safety checks that OpenAI attached to the actions.
1039
1040The adapter sends the first image of the result back as the screenshot. When the call does not fail, the adapter also tells OpenAI that the safety checks are accepted. When the call fails, they stay unaccepted.
1041
1042The `computer-use-preview` model takes the older tool type. Give it the display size and the environment. Each call then has one `action` field in place of `actions`:
1043
1044```typescript
1045import { computerUseTool } from "@tanstack/ai-openai/tools";
1046
1047const previewTool = computerUseTool({
1048 type: "computer_use_preview",
1049 display_width: 1024,
1050 display_height: 768,
1051 environment: "browser",
1052});
1053```
1054
1055**Supported models:** `type: "computer"` works with the models that list computer use, for example `gpt-6.1-sol`. `type: "computer_use_preview"` works with `computer-use-preview`. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
1056
1057### `localShellTool`
1058
1059The model returns a `local_shell` tool call. Your app runs the command. Then your app sends the output back on the next request. `localShellTool()` takes no arguments. Add it to `tools`.
1060
1061Match `toolName` on `TOOL_CALL_START`. Read `input` on the `TOOL_CALL_END` with the same `toolCallId`. `input.command` is the command. `input.env` is the environment variables.
1062
1063```typescript
1064import { chat } from "@tanstack/ai";
1065import { openaiText } from "@tanstack/ai-openai";
1066import { localShellTool } from "@tanstack/ai-openai/tools";
1067
1068const stream = chat({
1069 adapter: openaiText("gpt-5.6"),
1070 messages: [{ role: "user", content: "Run the test suite and summarise failures" }],
1071 tools: [localShellTool()],
1072});
1073
1074let localShellCallId: string | undefined;
1075for await (const chunk of stream) {
1076 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "local_shell") {
1077 localShellCallId = chunk.toolCallId;
1078 }
1079 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === localShellCallId) {
1080 console.log(chunk.input);
1081 }
1082}
1083```
1084
1085Send the command output as the tool result. Use `{ output: string }`, or a string. The next request sends `local_shell_call_output`.
1086
1087**Supported models:** GPT-5.x and other agent-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
1088
1089### `shellTool`
1090
1091`shellTool()` gives the model a shell. A container environment runs on OpenAI. A local environment runs in your app.
1092
1093When your app must run the commands, pass `environment: { type: "local" }`. Match `toolName` on `TOOL_CALL_START`. Read `input` on the `TOOL_CALL_END` with the same `toolCallId`. `input.commands` is the command list. `input.timeout_ms` is the time limit. `input.max_output_length` is the output limit.
1094
1095```typescript
1096import { chat } from "@tanstack/ai";
1097import { openaiText } from "@tanstack/ai-openai";
1098import { shellTool } from "@tanstack/ai-openai/tools";
1099
1100const stream = chat({
1101 adapter: openaiText("gpt-5.6"),
1102 messages: [{ role: "user", content: "Count lines in all JS files" }],
1103 tools: [shellTool({ environment: { type: "local" } })],
1104});
1105
1106let shellCallId: string | undefined;
1107for await (const chunk of stream) {
1108 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "shell") {
1109 shellCallId = chunk.toolCallId;
1110 }
1111 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === shellCallId) {
1112 console.log(chunk.input);
1113 }
1114}
1115```
1116
1117Return one result per command:
1118
1119```typescript
1120const shellResult = {
1121 output: [
1122 {
1123 stdout: "12\n",
1124 stderr: "",
1125 outcome: { type: "exit" as const, exit_code: 0 },
1126 },
1127 ],
1128};
1129```
1130
1131`outcome.type` is `"exit"` or `"timeout"`. The next request sends `shell_call_output`. If the same response has no `shell_call_output`, a shell call with no environment comes back to your app.
1132
1133A container environment does not come back as a tool call. Pass `environment` to attach that container and hosted skills.
1134
1135**Supported models:** GPT-5.x and other agent-capable models. Responses API
1136only — Chat Completions does not support the shell tool. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
1137
1138#### Attaching hosted skills
1139
1140Pass `environment.skills` to load provider-managed skill bundles into the
1141shell's container (Responses API only).
1142
1143```typescript
1144import { chat, toServerSentEventsResponse } from "@tanstack/ai";
1145import { openaiText } from "@tanstack/ai-openai";
1146import { shellTool } from "@tanstack/ai-openai/tools";
1147
1148export async function POST(request: Request) {
1149 const { messages } = await request.json();
1150
1151 const stream = chat({
1152 adapter: openaiText("gpt-5.2"),
1153 messages,
1154 tools: [
1155 shellTool({
1156 environment: {
1157 type: "container_auto",
1158 skills: [
1159 { type: "skill_reference", skill_id: "skill_abc", version: "2" },
1160 ],
1161 },
1162 }),
1163 ],
1164 });
1165
1166 return toServerSentEventsResponse(stream);
1167}
1168```
1169
1170For the full reference — skill shape, `version` string format, and the
1171Anthropic equivalent — see [Provider Skills](../tools/provider-skills.md).
1172
1173### `applyPatchTool`
1174
1175The model returns an `apply_patch` tool call. Your app applies the diff. Then your app sends the result back. `applyPatchTool()` takes no arguments. Add it to `tools`.
1176
1177Match `toolName` on `TOOL_CALL_START`. Read `input` on the `TOOL_CALL_END` with the same `toolCallId`. `input.operation` is one file change. `operation.type` is `create_file`, `update_file`, or `delete_file`. `operation.path` is the file path. `create_file` and `update_file` also include `operation.diff`.
1178
1179```typescript
1180import { chat } from "@tanstack/ai";
1181import { openaiText } from "@tanstack/ai-openai";
1182import { applyPatchTool } from "@tanstack/ai-openai/tools";
1183
1184const stream = chat({
1185 adapter: openaiText("gpt-5.6"),
1186 messages: [{ role: "user", content: "Fix the import paths in src/index.ts" }],
1187 tools: [applyPatchTool()],
1188});
1189
1190let patchCallId: string | undefined;
1191for await (const chunk of stream) {
1192 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "apply_patch") {
1193 patchCallId = chunk.toolCallId;
1194 }
1195 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === patchCallId) {
1196 console.log(chunk.input);
1197 }
1198}
1199```
1200
1201Send this object as the tool result. The next request sends `apply_patch_call_output`.
1202
1203```typescript
1204const patchResult = {
1205 status: "completed" as const,
1206 output: "Updated src/index.ts",
1207};
1208```
1209
1210If the patch fails, set `status` to `"failed"`. Put the error text in `output`. Keep `applyPatchTool()` in `tools` on the next request. A patch-only turn has no text. If you use `chat({ stream: false })`, `text` is empty. Read the `apply_patch` tool call from `chunks` with the same checks as the loop above.
1211
1212**Supported models:** GPT-5.x and other agent-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
1213
1214### `customTool`
1215
1216Defines a custom Responses API tool with an explicit name, description, and
1217format. Use this when none of the structured tool types fits your use case.
1218Unlike branded provider tools, `customTool` returns a plain `Tool` and is
1219accepted by any chat model.
1220
1221```typescript
1222import { chat } from "@tanstack/ai";
1223import { openaiText } from "@tanstack/ai-openai";
1224import { customTool } from "@tanstack/ai-openai/tools";
1225
1226const stream = chat({
1227 adapter: openaiText("gpt-5.2"),
1228 messages: [{ role: "user", content: "Look up order #1234" }],
1229 tools: [
1230 customTool({
1231 type: "custom",
1232 name: "lookup_order",
1233 description: "Look up the status of a customer order by order ID",
1234 }),
1235 ],
1236});
1237```
1238
1239**Supported models:** all Responses API models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).