Open History to see the last commit
1---
2title: OpenAI
3id: openai-adapter
4order: 1
5description: "Use OpenAI models in TanStack AI with @tanstack/ai-openai: GPT chat, gpt-image images, speech, Whisper transcription, embeddings, and Sora video."
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 calls GPT for chat, and it calls image, speech, transcription, embedding, and video models from the same package.
19
20Does your provider speak the OpenAI API, for example DeepSeek, Kimi, or a local vLLM server? Use the [OpenAI-Compatible adapter](./openai-compatible).
21
22## 1. Install
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## 2. Set the API key
38
39Put the key in the environment of your server:
40
41```bash
42OPENAI_API_KEY=sk-...
43```
44
45`openaiText` and the other short factories read `OPENAI_API_KEY`. To pass the key in code, use the `create*` factory of the same adapter:
46
47```typescript
48import { createOpenaiChat } from "@tanstack/ai-openai";
49
50const adapter = createOpenaiChat("gpt-6.1-sol", process.env.OPENAI_API_KEY!);
51```
52
53## 3. Stream a chat from the server
54
55```typescript
56import {
57 chat,
58 chatParamsFromRequest,
59 toServerSentEventsResponse,
60} from "@tanstack/ai";
61import { openaiText } from "@tanstack/ai-openai";
62
63export async function POST(request: Request) {
64 const { messages, threadId, runId } = await chatParamsFromRequest(request);
65
66 const stream = chat({
67 adapter: openaiText("gpt-6.1-sol"),
68 messages,
69 threadId,
70 runId,
71 });
72
73 return toServerSentEventsResponse(stream);
74}
75```
76
77## 4. Render the chat
78
79The client is the same for every provider. Point `useChat` at your route:
80
81```tsx
82import { useState } from "react";
83import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
84
85export function Chat() {
86 const [input, setInput] = useState("");
87 const { messages, sendMessage } = useChat({
88 connection: fetchServerSentEvents("/api/chat"),
89 threadId: "support-chat",
90 });
91
92 return (
93 <form
94 onSubmit={(event) => {
95 event.preventDefault();
96 sendMessage(input);
97 setInput("");
98 }}
99 >
100 {messages.map((message) => (
101 <p key={message.id}>
102 {message.parts
103 .map((part) => (part.type === "text" ? part.content : ""))
104 .join("")}
105 </p>
106 ))}
107 <input value={input} onChange={(event) => setInput(event.target.value)} />
108 </form>
109 );
110}
111```
112
113For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
114
115You now have a streaming GPT chat. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter.
116
117## Images
118
119```typescript
120import { generateImage } from "@tanstack/ai";
121import { openaiImage } from "@tanstack/ai-openai";
122
123const result = await generateImage({
124 adapter: openaiImage("gpt-image-2.5-flare"),
125 prompt: "A futuristic cityscape at sunset",
126 threadId: "thread-1",
127 numberOfImages: 1,
128 size: "1024x1024",
129 modelOptions: {
130 quality: "high",
131 },
132});
133
134console.log(result.images);
135```
136
137`quality` takes `low`, `medium`, `high`, or `auto`. The `gpt-image-2.5` models also take `xhigh` and `max`. See [Image Generation](../media/image-generation).
138
139## Speech
140
141```typescript
142import { generateSpeech } from "@tanstack/ai";
143import { openaiSpeech } from "@tanstack/ai-openai";
144
145const result = await generateSpeech({
146 adapter: openaiSpeech("tts-1"),
147 text: "Hello, welcome to TanStack AI!",
148 threadId: "thread-1",
149 voice: "alloy",
150 format: "mp3",
151});
152
153// result.audio holds base64-encoded audio
154console.log(result.format); // "mp3"
155```
156
157- Voices: `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, `shimmer`, `verse`.
158- `modelOptions.instructions` sets how the voice speaks. It does not work with `tts-1` or `tts-1-hd`.
159
160See [Text-to-Speech](../media/text-to-speech).
161
162## Transcription
163
164```typescript
165import { generateTranscription } from "@tanstack/ai";
166import { openaiTranscription } from "@tanstack/ai-openai";
167import { audioFile } from "./audio";
168
169const result = await generateTranscription({
170 adapter: openaiTranscription("whisper-1"),
171 audio: audioFile, // File object or base64 string
172 language: "en",
173 threadId: "thread-1",
174});
175
176console.log(result.text);
177```
178
179For speaker labels, use `gpt-4o-transcribe-diarize`. See [Speaker diarization](./openai-advanced#speaker-diarization).
180
181## Embeddings
182
183```typescript
184import { embed } from "@tanstack/ai";
185import { openaiEmbedding } from "@tanstack/ai-openai";
186
187const result = await embed({
188 adapter: openaiEmbedding("text-embedding-3-small"),
189 input: ["a red guitar", "a blue drum kit"],
190});
191
192console.log(result.embeddings[0]?.vector);
193console.log(result.usage?.promptTokens);
194```
195
196Both models (`text-embedding-3-small` and `text-embedding-3-large`) take the top-level `dimensions` option to make the vectors shorter:
197
198```typescript
199import { embed } from "@tanstack/ai";
200import { openaiEmbedding } from "@tanstack/ai-openai";
201
202const result = await embed({
203 adapter: openaiEmbedding("text-embedding-3-large"),
204 input: "a red guitar",
205 dimensions: 1024,
206});
207```
208
209See the [Embeddings guide](../embeddings.md).
210
211## Summarization
212
213```typescript
214import { summarize } from "@tanstack/ai";
215import { openaiSummarize } from "@tanstack/ai-openai";
216
217const result = await summarize({
218 adapter: openaiSummarize("gpt-5-mini"),
219 text: "Your long text to summarize...",
220 threadId: "thread-1",
221 maxLength: 100,
222 style: "concise", // "concise" | "bullet-points" | "paragraph"
223});
224
225console.log(result.summary);
226```
227
228## Video
229
230`openaiVideo` makes Sora videos with `sora-2` and `sora-2-pro`. Video generation is experimental. See [Video Generation](../media/video-generation).
231
232## Realtime voice
233
234`openaiRealtime` and `openaiRealtimeToken` run a live voice chat. See [Realtime Voice Chat](../media/realtime-chat).
235
236## Files
237
238`openaiFiles` uploads media to the OpenAI Files API, so a message can point to the file. See [Files API](../advanced/files-api).
239
240## Evaluate
241
242Sometimes you need an answer that your code can branch on, not chat text: a queue name, an urgency level, or a yes or no. Use `openaiDecider` with `decide()` to ask typed questions about one shared `state`. The adapter calls the OpenAI Decisions API (`/v1/decisions`):
243
244```typescript
245import { decide, choice, score, boolean } from "@tanstack/ai";
246import { openaiDecider } from "@tanstack/ai-openai";
247
248const ticket = {
249 subject: "Charged twice for the same invoice",
250 body: "Please refund the extra payment.",
251};
252
253const result = await decide({
254 adapter: openaiDecider("gpt-6-luna"),
255 state: ticket,
256 questions: {
257 queue: choice({
258 instructions: "Which team should handle this ticket?",
259 options: {
260 billing: "Payments, invoices, refunds",
261 tech: "Bugs, outages, integrations",
262 sales: "Pricing, upgrades, new accounts",
263 },
264 }),
265 urgency: score({
266 instructions: "How urgent is this ticket?",
267 levels: ["low", "medium", "high"],
268 }),
269 refund: boolean({
270 instructions: "Is the customer asking for a refund?",
271 }),
272 },
273});
274
275console.log(result.queue.value); // "billing"
276console.log(result.urgency.value); // "medium"
277console.log(result.refund.value); // true
278console.log(result.meta.usage);
279```
280
281`openaiDecider` reads `OPENAI_API_KEY`. To pass a key yourself, use `createOpenaiDecider("gpt-6-luna", "sk-...")`.
282
283- `gpt-6-luna` is the only Decisions model.
284- An object `state` goes to OpenAI as JSON text.
285- If OpenAI refuses to answer a question, `decide()` throws an error with the name of that question.
286- `boolean()` questions work. The adapter adds the meaning of true and false to the instructions.
287
288See the [Evaluate guide](../evaluate/evaluate) for the question helpers, the result shape, abort, and middleware.
289
290## Provider tools
291
292OpenAI runs some tools itself, such as web search and a code sandbox. Import them from `@tanstack/ai-openai/tools` and add them to `tools`:
293
294```typescript
295import { chat } from "@tanstack/ai";
296import { openaiText } from "@tanstack/ai-openai";
297import { webSearchTool } from "@tanstack/ai-openai/tools";
298
299const stream = chat({
300 adapter: openaiText("gpt-6.1-sol"),
301 messages: [{ role: "user", content: "What's new in AI this week?" }],
302 threadId: "thread-1",
303 tools: [webSearchTool({ type: "web_search" })],
304});
305```
306
307Tools that OpenAI runs:
308
309- `webSearchTool` and `webSearchPreviewTool`: search the web, with citations.
310- `fileSearchTool`: search your OpenAI vector stores.
311- `imageGenerationTool`: make images inside the chat.
312- `codeInterpreterTool`: run Python in a sandbox.
313- `mcpTool`: connect a remote MCP server.
314
315Tools that your app runs when the model asks:
316
317- `localShellTool` and `shellTool`: run shell commands.
318- `applyPatchTool`: apply a file diff.
319- `computerUseTool`: control a virtual desktop.
320- `customTool`: a Responses API tool with your own name and format.
321
322Each tool, with a full sample, is on [OpenAI: Advanced](./openai-advanced#provider-tools). For which models take which tool, see [Provider Tools](../tools/provider-tools.md).
323
324## Models and options
325
326### Model options
327
328Provider options go in `modelOptions`. This includes the sampling options `temperature`, `top_p`, and `max_output_tokens`:
329
330```typescript
331import { chat } from "@tanstack/ai";
332import { openaiText } from "@tanstack/ai-openai";
333
334const stream = chat({
335 adapter: openaiText("gpt-4.1"),
336 messages: [{ role: "user", content: "Hello!" }],
337 threadId: "thread-1",
338 modelOptions: {
339 temperature: 0.7,
340 max_output_tokens: 1000,
341 top_p: 0.9,
342 },
343});
344```
345
346- OpenAI rejects `temperature` and `top_p` on the reasoning models. `openaiText` drops the two options for these model ids:
347 - The `o` models (`o1`, `o3`, `o4-mini`, and so on).
348 - Every id that starts with `gpt-5`, except ids that end in `-chat-latest`.
349 - `codex-mini-latest`.
350- With `openaiChatCompletions`, the token limit is `max_tokens`.
351- Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
352
353### Reasoning
354
355Want GPT to think harder, or not at all? Set `reasoning` on `chat()`:
356
357```typescript
358import { chat } from "@tanstack/ai";
359import { openaiText } from "@tanstack/ai-openai";
360
361const stream = chat({
362 adapter: openaiText("gpt-6.1-sol"),
363 messages: [{ role: "user", content: "Plan a database migration." }],
364 threadId: "thread-1",
365 reasoning: "xhigh",
366});
367```
368
369What goes to OpenAI:
370
371- `openaiText` and `azureOpenaiText`: `reasoning: { effort, summary: "auto" }`. The summary text streams as thinking parts. `summary: false` drops the summary.
372- `openaiChatCompletions`: `reasoning_effort`. No thinking text streams back.
373- `off` sends `effort: "none"` on the models that can stop thinking.
374
375The levels of each model:
376
377| Model | Levels |
378| --- | --- |
379| `gpt-6.1-sol`, `gpt-6.1-sol-pro`, `gpt-6-astra`, `gpt-6-astra-pro` | `low` to `max` |
380| `gpt-6-sol`, `gpt-6-luna`, the `gpt-5.6` models, and their `-pro` versions | `off`, `low` to `max` |
381| `gpt-5.5`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.4-image-2`, `gpt-5.2` | `off`, `low` to `xhigh` |
382| `gpt-5.5-pro`, `gpt-5.2-pro` | `medium`, `high`, `xhigh` |
383| `gpt-5.1` | `off`, `low`, `medium`, `high` |
384| `gpt-5`, `gpt-5-mini`, `gpt-5-nano` | `minimal` to `high` |
385| `gpt-chat-latest`, the `o` models, and the `codex` models | `low`, `medium`, `high` |
386| `gpt-5.2-chat-latest` | `medium` |
387| `gpt-5-pro` | `high` |
388
389The other models, such as `gpt-4.1` and `gpt-4o`, take no `reasoning`. See [Reasoning](../chat/reasoning).
390
391### Models
392
393Newest first. The package exports the full lists, for example `OPENAI_CHAT_MODELS`.
394
395| Activity | Factory | Models |
396| --- | --- | --- |
397| Chat | `openaiText` | `gpt-6.1-sol`, `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.6`, `gpt-5.5`, `gpt-4.1`, `gpt-4o`, the `o` models, and more |
398| Images | `openaiImage` | `gpt-image-2.5-flare`, `gpt-image-2.5-sunburst`, `gpt-image-2`, `gpt-image-1`, `gpt-image-1-mini`, `dall-e-3`, `dall-e-2` |
399| Speech | `openaiSpeech` | `tts-1`, `tts-1-hd`, `gpt-4o-audio-preview` |
400| Transcription | `openaiTranscription` | `whisper-1`, `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe-diarize` |
401| Embeddings | `openaiEmbedding` | `text-embedding-3-small`, `text-embedding-3-large` |
402| Video | `openaiVideo` | `sora-2`, `sora-2-pro` |
403| Evaluate | `openaiDecider` | `gpt-6-luna` |
404
405`adapter.inputModalities` lists the input kinds of the selected model. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
406
407## Advanced
408
409These topics are on [OpenAI: Advanced](./openai-advanced):
410
411- The Chat Completions API (`openaiChatCompletions`) and Azure OpenAI.
412- Sign in with ChatGPT, so users pay with their ChatGPT plan.
413- Prompt caching, native compaction, and tools added during a conversation.
414- Every provider tool, with a full sample.
415- The configuration options and the API reference.