Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

openai.md

849 lines27.1 KB

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 — set `modelOptions.reasoning.summary: 'auto'` to surface reasoning text via `REASONING_*` events | No — reasoning tokens are still consumed but cannot be exposed |
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 identically with [Structured Outputs](../structured-outputs/overview) — including `stream: true` — and accept the same `modelOptions` (temperature, top_p, max_tokens, stop, …). The reasoning section below applies to `openaiText`; `openaiChatCompletions` accepts `modelOptions.reasoning.effort` but cannot stream summary text.
91​
92## Basic Usage - Custom API Key
93​
94```typescript
95import { chat } from "@tanstack/ai";
96import { createOpenaiChat } from "@tanstack/ai-openai";
97​
98const adapter = createOpenaiChat("gpt-5.2", process.env.OPENAI_API_KEY!, {
99 // ... your config options
100});
101​
102const stream = chat({
103 adapter,
104 messages: [{ role: "user", content: "Hello!" }],
105});
106```
107​
108## Configuration
109​
110```typescript
111import { createOpenaiChat, type OpenAITextConfig } from "@tanstack/ai-openai";
112​
113const config: Omit<OpenAITextConfig, "apiKey"> = {
114 organization: "org-...", // Optional
115 baseURL: "https://api.openai.com/v1", // Optional, for custom endpoints
116};
117​
118const adapter = createOpenaiChat("gpt-5.2", process.env.OPENAI_API_KEY!, config);
119```
120​
121### Tools that cannot use strict mode
122​
123OpenAI 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.
124​
125In development, the adapter logs a warning once for each of these tools:
126​
127```txt
128tool "lookup_user" sent with strict: false: schema uses $ref, which strict mode does not support
129```
130​
131To 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:
132​
133```typescript
134import { createOpenaiChat } from "@tanstack/ai-openai";
135​
136const adapter = createOpenaiChat("gpt-6-astra", process.env.OPENAI_API_KEY!, {
137 strictFallbackWarning: false,
138});
139```
140​
141The 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.
143## Example: Chat Completion
144​
145```typescript
146import { chat, toServerSentEventsResponse } from "@tanstack/ai";
147import { openaiText } from "@tanstack/ai-openai";
148​
149export async function POST(request: Request) {
150 const { messages } = await request.json();
151​
152 const stream = chat({
153 adapter: openaiText("gpt-5.2"),
154 messages,
155 });
156​
157 return toServerSentEventsResponse(stream);
159```
160​
161## Example: With Tools
162​
163```typescript
164import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
165import { openaiText } from "@tanstack/ai-openai";
166import { z } from "zod";
167​
168const getWeatherDef = toolDefinition({
169 name: "get_weather",
170 description: "Get the current weather",
171 inputSchema: z.object({
172 location: z.string(),
173 }),
174});
175​
176const getWeather = getWeatherDef.server(async ({ location }) => {
177 // Fetch weather data
178 return { temperature: 72, conditions: "sunny" };
179});
180​
181export async function POST(request: Request) {
182 const { messages } = await request.json();
183​
184 const stream = chat({
185 adapter: openaiText("gpt-5.2"),
186 messages,
187 tools: [getWeather],
188 });
189​
190 return toServerSentEventsResponse(stream);
192```
193​
194## Model Options
195​
196OpenAI 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()`:
197​
198```typescript
199import { chat } from "@tanstack/ai";
200import { openaiText } from "@tanstack/ai-openai";
201​
202const stream = chat({
203 adapter: openaiText("gpt-5.2"),
204 messages: [{ role: "user", content: "Hello!" }],
205 modelOptions: {
206 temperature: 0.7,
207 max_output_tokens: 1000,
208 top_p: 0.9,
209 },
210});
211```
212​
213> 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).
214​
215### Reasoning
216​
217Enable reasoning for models that support it (e.g., GPT-5, O3). This allows the model to show its reasoning process, which is streamed as `thinking` chunks:
218​
219```typescript ignore
220modelOptions: {
221 reasoning: {
222 effort: "medium", // "none" | "minimal" | "low" | "medium" | "high"
223 summary: "detailed", // "auto" | "detailed" (optional)
224 },
226```
227​
228When reasoning is enabled, the model's reasoning process is streamed separately from the response text and appears as a collapsible thinking section in the UI.
229​
230## Summarization
231​
232Summarize long text content:
233​
234```typescript
235import { summarize } from "@tanstack/ai";
236import { openaiSummarize } from "@tanstack/ai-openai";
237​
238const result = await summarize({
239 adapter: openaiSummarize("gpt-5-mini"),
240 text: "Your long text to summarize...",
241 maxLength: 100,
242 style: "concise", // "concise" | "bullet-points" | "paragraph"
243});
244​
245console.log(result.summary);
246```
247​
248## Embeddings
249​
250Generate embedding vectors with the text-embedding-3 models:
251​
252```typescript
253import { embed } from "@tanstack/ai";
254import { openaiEmbedding } from "@tanstack/ai-openai";
255​
256const result = await embed({
257 adapter: openaiEmbedding("text-embedding-3-small"),
258 input: ["a red guitar", "a blue drum kit"],
259});
260​
261console.log(result.embeddings[0]?.vector);
262console.log(result.usage?.promptTokens);
263```
264​
265Both models support Matryoshka dimension reduction via the top-level `dimensions` option:
266​
267```typescript
268import { embed } from "@tanstack/ai";
269import { openaiEmbedding } from "@tanstack/ai-openai";
270​
271const result = await embed({
272 adapter: openaiEmbedding("text-embedding-3-large"),
273 input: "a red guitar",
274 dimensions: 1024,
275});
276```
277​
278See the [Embeddings guide](../embeddings.md) for the full API.
279​
280## Image Generation
281​
282Generate images:
283​
284```typescript
285import { generateImage } from "@tanstack/ai";
286import { openaiImage } from "@tanstack/ai-openai";
287​
288const result = await generateImage({
289 adapter: openaiImage("gpt-image-2"),
290 prompt: "A futuristic cityscape at sunset",
291 numberOfImages: 1,
292 size: "1024x1024",
293});
294​
295console.log(result.images);
296```
297​
298### Image Model Options
299​
300```typescript
301import { generateImage } from "@tanstack/ai";
302import { openaiImage } from "@tanstack/ai-openai";
303​
304const result = await generateImage({
305 adapter: openaiImage("gpt-image-2"),
306 prompt: "...",
307 modelOptions: {
308 quality: "high", // "high" | "medium" | "low" | "auto"
309 },
310});
311```
312​
313## Text-to-Speech
314​
315Generate speech from text:
316​
317```typescript
318import { generateSpeech } from "@tanstack/ai";
319import { openaiSpeech } from "@tanstack/ai-openai";
320​
321const result = await generateSpeech({
322 adapter: openaiSpeech("tts-1"),
323 text: "Hello, welcome to TanStack AI!",
324 voice: "alloy",
325 format: "mp3",
326});
327​
328// result.audio contains base64-encoded audio
329console.log(result.format); // "mp3"
330```
331​
332### TTS Voices
333​
334Available voices: `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, `ash`, `ballad`, `coral`, `sage`, `verse`
335​
336### TTS Model Options
337​
338```typescript
339import { generateSpeech } from "@tanstack/ai";
340import { openaiSpeech } from "@tanstack/ai-openai";
341​
342const result = await generateSpeech({
343 adapter: openaiSpeech("tts-1-hd"),
344 text: "High quality speech",
345 modelOptions: {
346 instructions: "Speak slowly and clearly.", // voice instructions (not supported by tts-1/tts-1-hd)
347 },
348});
349```
350​
351## Transcription
352​
353Transcribe audio to text:
354​
355```typescript
356import { generateTranscription } from "@tanstack/ai";
357import { openaiTranscription } from "@tanstack/ai-openai";
358import { audioFile } from "./audio";
359​
360const result = await generateTranscription({
361 adapter: openaiTranscription("whisper-1"),
362 audio: audioFile, // File object or base64 string
363 language: "en",
364});
365​
366console.log(result.text); // Transcribed text
367```
368​
369### Transcription Model Options
370​
371```typescript
372import { generateTranscription } from "@tanstack/ai";
373import { openaiTranscription } from "@tanstack/ai-openai";
374import { audioFile } from "./audio";
375​
376const result = await generateTranscription({
377 adapter: openaiTranscription("whisper-1"),
378 audio: audioFile,
379 responseFormat: "verbose_json",
380 prompt: "Technical terms: API, SDK",
381 modelOptions: {
382 temperature: 0,
383 timestamp_granularities: ["word", "segment"],
384 },
385});
386​
387// Access the transcribed text
388console.log(result.text);
389```
390​
391### Speaker Diarization
392​
393Use `gpt-4o-transcribe-diarize` for speaker-labeled transcripts:
394​
395```typescript
396import { generateTranscription } from "@tanstack/ai";
397import { openaiTranscription } from "@tanstack/ai-openai";
398import { meetingAudioFile } from "./audio";
399​
400const result = await generateTranscription({
401 adapter: openaiTranscription("gpt-4o-transcribe-diarize"),
402 audio: meetingAudioFile,
403 modelOptions: {
404 known_speaker_names: ["agent", "customer"],
405 known_speaker_references: [
406 "data:audio/wav;base64,...",
407 "data:audio/wav;base64,...",
408 ],
409 },
410});
411​
412for (const segment of result.segments ?? []) {
413 console.log(segment.speaker, segment.start, segment.end, segment.text);
415```
416​
417When 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.
418​
419## Environment Variables
420​
421Set your API key in environment variables:
422​
423```bash
424OPENAI_API_KEY=sk-...
425```
426​
427## API Reference
428​
429Every 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.
430​
431### `openaiText(model, config?)`
432​
433Creates an OpenAI text adapter against the Responses API (`/v1/responses`) using `OPENAI_API_KEY` from the environment.
434​
435**Parameters:**
436​
437- `model` - OpenAI chat model id (e.g. `"gpt-5.2"`, `"gpt-4o-mini"`)
438- `config?.organization` - Organization ID (optional)
439- `config?.baseURL` - Custom base URL (optional)
440​
441### `createOpenaiChat(model, apiKey, config?)`
442​
443Creates an OpenAI text adapter (Responses API) with an explicit API key.
444​
445### `openaiChatCompletions(model, config?)`
446​
447Creates 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`.
448​
449### `createOpenaiChatCompletions(model, apiKey, config?)`
450​
451Creates an OpenAI chat-completions adapter with an explicit API key.
452​
453### `openaiSummarize(model, config?)` / `createOpenaiSummarize(model, apiKey, config?)`
454​
455Creates an OpenAI summarization adapter.
456​
457### `openaiImage(model, config?)` / `createOpenaiImage(model, apiKey, config?)`
458​
459Creates an OpenAI image generation adapter (DALL-E, gpt-image).
460​
461### `openaiSpeech(model, config?)` / `createOpenaiSpeech(model, apiKey, config?)`
462​
463Creates an OpenAI text-to-speech adapter.
464​
465### `openaiTranscription(model, config?)` / `createOpenaiTranscription(model, apiKey, config?)`
466​
467Creates an OpenAI transcription adapter for Whisper, GPT-4o transcription, and GPT-4o diarized transcription models.
468​
469### `openaiVideo(model, config?)` / `createOpenaiVideo(model, apiKey, config?)`
470​
471Creates an OpenAI video generation adapter (Sora). _Experimental._
472​
473### `openaiRealtime(...)` / `openaiRealtimeToken(...)`
474​
475Realtime voice adapters. See [Realtime Voice Chat](../media/realtime-chat) for usage.
476​
477## Next Steps
478​
479- [Getting Started](../getting-started/quick-start) - Learn the basics
480- [Tools Guide](../tools/tools) - Learn about tools
481- [Other Adapters](./anthropic) - Explore other providers
482​
483## Provider Tools
484​
485OpenAI exposes several native tools beyond user-defined function calls.
486Import them from `@tanstack/ai-openai/tools` and pass them into
487`chat({ tools: [...] })`.
488​
489> For the full concept, a comparison matrix, and type-gating details, see
490> [Provider Tools](../tools/provider-tools.md).
491​
492### `webSearchTool`
493​
494Enables the model to run a web search and return grounded results with
495citations. Pass a `WebSearchToolConfig` object (typed from the OpenAI SDK)
496to configure the tool.
497​
498```typescript
499import { chat } from "@tanstack/ai";
500import { openaiText } from "@tanstack/ai-openai";
501import { webSearchTool } from "@tanstack/ai-openai/tools";
502​
503const stream = chat({
504 adapter: openaiText("gpt-5.2"),
505 messages: [{ role: "user", content: "What's new in AI this week?" }],
506 tools: [webSearchTool({ type: "web_search" })],
507});
508```
509​
510**Supported models:** GPT-4o, GPT-5, and Responses API-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
511​
512### `webSearchPreviewTool`
513​
514The preview variant of web search with additional options for controlling
515search context size and user location. Use this when you want fine-grained
516control over the search context sent to the model.
517​
518```typescript
519import { chat } from "@tanstack/ai";
520import { openaiText } from "@tanstack/ai-openai";
521import { webSearchPreviewTool } from "@tanstack/ai-openai/tools";
522​
523const stream = chat({
524 adapter: openaiText("gpt-5.2"),
525 messages: [{ role: "user", content: "Latest news about TypeScript" }],
526 tools: [
527 webSearchPreviewTool({
528 type: "web_search_preview_2025_03_11",
529 search_context_size: "high",
530 }),
531 ],
532});
533```
534​
535**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
536​
537When the model uses hosted web search, the assistant tool-call part includes
538`metadata.providerExecuted: true` and the normalized `metadata.sources` array.
539OpenAI's raw search call and URL citations stay under `metadata.openai`. The
540agent loop does not execute this call in your application, and the adapter
541replays the raw response items on the next turn.
542​
543### `fileSearchTool`
544​
545Searches OpenAI vector stores that you have pre-populated, letting the model
546retrieve relevant document chunks. Provide the `vector_store_ids` to search
547and optionally limit results with `max_num_results` (1–50).
548​
549```typescript
550import { chat } from "@tanstack/ai";
551import { openaiText } from "@tanstack/ai-openai";
552import { fileSearchTool } from "@tanstack/ai-openai/tools";
553​
554const stream = chat({
555 adapter: openaiText("gpt-5.2"),
556 messages: [{ role: "user", content: "What does the handbook say about PTO?" }],
557 tools: [
558 fileSearchTool({
559 type: "file_search",
560 vector_store_ids: ["vs_abc123"],
561 max_num_results: 5,
562 }),
563 ],
564});
565```
566​
567**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
568​
569### `imageGenerationTool`
570​
571Allows the model to generate images inline during a conversation using
572DALL-E/GPT-Image. Pass quality, size, and style options via the config object.
573​
574```typescript
575import { chat } from "@tanstack/ai";
576import { openaiText } from "@tanstack/ai-openai";
577import { imageGenerationTool } from "@tanstack/ai-openai/tools";
578​
579const stream = chat({
580 adapter: openaiText("gpt-5.2"),
581 messages: [{ role: "user", content: "Draw a logo for my app" }],
582 tools: [
583 imageGenerationTool({
584 quality: "high",
585 size: "1024x1024",
586 }),
587 ],
588});
589```
590​
591**Supported models:** GPT-5 and GPT-Image-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
592​
593### `codeInterpreterTool`
594​
595Gives the model a sandboxed Python execution environment. The `container`
596field configures the execution environment; pass the full
597`CodeInterpreterToolConfig` object.
598​
599```typescript
600import { chat } from "@tanstack/ai";
601import { openaiText } from "@tanstack/ai-openai";
602import { codeInterpreterTool } from "@tanstack/ai-openai/tools";
603​
604const stream = chat({
605 adapter: openaiText("gpt-5.2"),
606 messages: [{ role: "user", content: "Analyse this CSV and plot a chart" }],
607 tools: [
608 codeInterpreterTool({ type: "code_interpreter", container: { type: "auto" } }),
609 ],
610});
611```
612​
613**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
614​
615### `mcpTool`
616​
617Connects the model to a remote MCP (Model Context Protocol) server, exposing
618all its capabilities as callable tools. Provide either `server_url` or
619`connector_id` — not both.
620​
621```typescript
622import { chat } from "@tanstack/ai";
623import { openaiText } from "@tanstack/ai-openai";
624import { mcpTool } from "@tanstack/ai-openai/tools";
625​
626const stream = chat({
627 adapter: openaiText("gpt-5.2"),
628 messages: [{ role: "user", content: "List my GitHub issues" }],
629 tools: [
630 mcpTool({
631 server_url: "https://mcp.example.com",
632 server_label: "github",
633 }),
634 ],
635});
636```
637​
638**Supported models:** GPT-4o and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
639​
640### `computerUseTool`
641​
642Lets the model observe a virtual desktop via screenshots and interact with
643it using keyboard and mouse events. Provide the display dimensions and the
644execution environment type.
645​
646```typescript
647import { chat } from "@tanstack/ai";
648import { openaiText } from "@tanstack/ai-openai";
649import { computerUseTool } from "@tanstack/ai-openai/tools";
650​
651const stream = chat({
652 adapter: openaiText("computer-use-preview"),
653 messages: [{ role: "user", content: "Open Chrome and navigate to example.com" }],
654 tools: [
655 computerUseTool({
656 type: "computer_use_preview",
657 display_width: 1024,
658 display_height: 768,
659 environment: "browser",
660 }),
661 ],
662});
663```
664​
665**Supported models:** `computer-use-preview`. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
666​
667### `localShellTool`
668​
669The 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`.
670​
671Match `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.
672​
673```typescript
674import { chat } from "@tanstack/ai";
675import { openaiText } from "@tanstack/ai-openai";
676import { localShellTool } from "@tanstack/ai-openai/tools";
677​
678const stream = chat({
679 adapter: openaiText("gpt-5.6"),
680 messages: [{ role: "user", content: "Run the test suite and summarise failures" }],
681 tools: [localShellTool()],
682});
683​
684let localShellCallId: string | undefined;
685for await (const chunk of stream) {
686 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "local_shell") {
687 localShellCallId = chunk.toolCallId;
688 }
689 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === localShellCallId) {
690 console.log(chunk.input);
691 }
693```
694​
695Send the command output as the tool result. Use `{ output: string }`, or a string. The next request sends `local_shell_call_output`.
696​
697**Supported models:** GPT-5.x and other agent-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
698​
699### `shellTool`
700​
701`shellTool()` gives the model a shell. A container environment runs on OpenAI. A local environment runs in your app.
702​
703When 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.
704​
705```typescript
706import { chat } from "@tanstack/ai";
707import { openaiText } from "@tanstack/ai-openai";
708import { shellTool } from "@tanstack/ai-openai/tools";
709​
710const stream = chat({
711 adapter: openaiText("gpt-5.6"),
712 messages: [{ role: "user", content: "Count lines in all JS files" }],
713 tools: [shellTool({ environment: { type: "local" } })],
714});
715​
716let shellCallId: string | undefined;
717for await (const chunk of stream) {
718 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "shell") {
719 shellCallId = chunk.toolCallId;
720 }
721 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === shellCallId) {
722 console.log(chunk.input);
723 }
725```
726​
727Return one result per command:
728​
729```typescript
730const shellResult = {
731 output: [
732 {
733 stdout: "12\n",
734 stderr: "",
735 outcome: { type: "exit" as const, exit_code: 0 },
736 },
737 ],
738};
739```
740​
741`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.
742​
743A container environment does not come back as a tool call. Pass `environment` to attach that container and hosted skills.
744​
745**Supported models:** GPT-5.x and other agent-capable models. Responses API
746only — Chat Completions does not support the shell tool. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
747​
748#### Attaching hosted skills
749​
750Pass `environment.skills` to load provider-managed skill bundles into the
751shell's container (Responses API only).
752​
753```typescript
754import { chat, toServerSentEventsResponse } from "@tanstack/ai";
755import { openaiText } from "@tanstack/ai-openai";
756import { shellTool } from "@tanstack/ai-openai/tools";
757​
758export async function POST(request: Request) {
759 const { messages } = await request.json();
760​
761 const stream = chat({
762 adapter: openaiText("gpt-5.2"),
763 messages,
764 tools: [
765 shellTool({
766 environment: {
767 type: "container_auto",
768 skills: [
769 { type: "skill_reference", skill_id: "skill_abc", version: "2" },
770 ],
771 },
772 }),
773 ],
774 });
775​
776 return toServerSentEventsResponse(stream);
778```
779​
780For the full reference — skill shape, `version` string format, and the
781Anthropic equivalent — see [Provider Skills](../tools/provider-skills.md).
782​
783### `applyPatchTool`
784​
785The 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`.
786​
787Match `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`.
788​
789```typescript
790import { chat } from "@tanstack/ai";
791import { openaiText } from "@tanstack/ai-openai";
792import { applyPatchTool } from "@tanstack/ai-openai/tools";
793​
794const stream = chat({
795 adapter: openaiText("gpt-5.6"),
796 messages: [{ role: "user", content: "Fix the import paths in src/index.ts" }],
797 tools: [applyPatchTool()],
798});
799​
800let patchCallId: string | undefined;
801for await (const chunk of stream) {
802 if (chunk.type === "TOOL_CALL_START" && chunk.toolName === "apply_patch") {
803 patchCallId = chunk.toolCallId;
804 }
805 if (chunk.type === "TOOL_CALL_END" && chunk.toolCallId === patchCallId) {
806 console.log(chunk.input);
807 }
809```
810​
811Send this object as the tool result. The next request sends `apply_patch_call_output`.
812​
813```typescript
814const patchResult = {
815 status: "completed" as const,
816 output: "Updated src/index.ts",
817};
818```
819​
820If the patch fails, set `status` to `"failed"`. Put the error text in `output`. Keep `applyPatchTool()` in `tools` on the next request. Use the stream. `chat({ stream: false })` returns only text. A patch-only turn then looks empty.
821​
822**Supported models:** GPT-5.x and other agent-capable models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
823​
824### `customTool`
825​
826Defines a custom Responses API tool with an explicit name, description, and
827format. Use this when none of the structured tool types fits your use case.
828Unlike branded provider tools, `customTool` returns a plain `Tool` and is
829accepted by any chat model.
830​
831```typescript
832import { chat } from "@tanstack/ai";
833import { openaiText } from "@tanstack/ai-openai";
834import { customTool } from "@tanstack/ai-openai/tools";
835​
836const stream = chat({
837 adapter: openaiText("gpt-5.2"),
838 messages: [{ role: "user", content: "Look up order #1234" }],
839 tools: [
840 customTool({
841 type: "custom",
842 name: "lookup_order",
843 description: "Look up the status of a customer order by order ID",
844 }),
845 ],
846});
847```
848​
849**Supported models:** all Responses API models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).