Open History to see the last commit
1---
2title: "@tanstack/ai"
3id: tanstack-ai-api
4order: 1
5description: "API reference for @tanstack/ai, the core server library: chat(), toolDefinition(), decide(), the generation functions, response helpers, and BYOK."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai"
9 - api reference
10 - chat
11 - toolDefinition
12 - generateImage
13 - decide
14 - core library
15---
16
17The core library. It runs chats and generations on the server, defines tools, and turns streams into HTTP responses. To build your first chat, start with the [Quick Start](../getting-started/quick-start).
18
19## Installation
20
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22
23react: @tanstack/ai
24vue: @tanstack/ai
25solid: @tanstack/ai
26svelte: @tanstack/ai
27preact: @tanstack/ai
28angular: @tanstack/ai
29vanilla: @tanstack/ai
30octane: @tanstack/ai
31
32<!-- ::end:tabs -->
33
34You also need an adapter package, for example `@tanstack/ai-openai`. See [Adapters](../adapters/openai).
35
36## `chat`
37
38Runs a chat with a model, including tool calls, and streams the result. See [Streaming](../chat/streaming).
39
40```typescript
41import { chat, maxIterations } from "@tanstack/ai";
42import { openaiText } from "@tanstack/ai-openai";
43import { myTool } from "./tools";
44
45const stream = chat({
46 adapter: openaiText("gpt-6.1-sol"),
47 messages: [{ role: "user", content: "Hello!" }],
48 threadId: "thread-1",
49 tools: [myTool],
50 systemPrompts: ["You are a helpful assistant"],
51 agentLoopStrategy: maxIterations(20),
52});
53```
54
55### Options
56
57Required:
58
59| Option | What it does |
60| --- | --- |
61| `adapter` | A text adapter with a model, for example `openaiText("gpt-6.1-sol")`. |
62| `messages` | The conversation. Accepts `UIMessage` and `ModelMessage` items, mixed in one array. |
63| `threadId` | The id of the conversation. Use a stable id, for example `params.threadId` from `chatParamsFromRequest`. |
64
65Common:
66
67| Option | What it does |
68| --- | --- |
69| `tools` | Tools from `toolDefinition()`, or provider tools such as `webSearchTool`. See [Tools](../tools/tools). |
70| `systemPrompts` | Strings, or `{ content, metadata }` objects, put before the messages. |
71| `outputSchema` | A Standard Schema. The call resolves to the parsed object. See [Structured Outputs](../structured-outputs/overview). |
72| `stream` | `false` to get one result when the run ends. See [Returns](#returns). |
73| `modelOptions` | Provider options, typed by the adapter. Sampling settings go here, under the name that each provider uses (`temperature`, `max_output_tokens`, and so on). See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). |
74| `reasoning` | How hard the model thinks: a level such as `"low"` or `"high"`, or `{ level, summary?, budgetTokens? }`. `"off"` turns it off. See [Reasoning](../chat/reasoning). |
75| `context` | Typed runtime context for server tools and middleware. If a tool or middleware declares a context type, this option is required. See [Runtime Context](../advanced/runtime-context). |
76| `middleware` | Chat middleware, called in array order. See [Middleware](../advanced/middleware). |
77| `abortController` | Cancels the run. |
78
79Agent loop and tools:
80
81| Option | What it does |
82| --- | --- |
83| `agentLoopStrategy` | When the loop stops. Default: `combineStrategies([maxIterations(5), untilFinishReason(["length"])])`. See [Agent loop strategies](#agent-loop-strategies). |
84| `toolChoice` | `"auto"`, `"none"`, `"required"`, or `{ type: "tool", name }`. Applies to every model call of the run. |
85| `toolExecution` | `"parallel"` (default) or `"sequential"`: how the server tools of one model turn run. |
86| `repairToolInput` | How a tool input that fails the final check is repaired. `false` turns repair off. A function replaces it. |
87| `retry` | Retries a rate-limited model call after the wait the provider asks for, for example `{ maxRetries: 3 }`. |
88| `lazyToolsConfig` | How much of each lazy tool description goes into the discovery catalog. See [Lazy Tool Discovery](../tools/lazy-tool-discovery). |
89| `mcp` | MCP clients or pools. Their tools join the run. See [MCP](../tools/mcp). |
90| `interrupts` | Definitions from `defineInterrupt()`. See [Generic Interrupts](../interrupts/generic). |
91| `subagents` | Named child agents from `defineAgent()`. See [Subagents](../chat/subagents). |
92
93Run identity and other options:
94
95| Option | What it does |
96| --- | --- |
97| `runId`, `parentRunId` | AG-UI ids for the run and a parent run. They are made for you when you omit them. |
98| `resume` | AG-UI interrupt resume answers, from `chatParamsFromRequest`. |
99| `state` | App state put in a `STATE_SNAPSHOT` before an interrupt ends the run. |
100| `promptCache` | Automatic prompt caching. Default `"short"`. `"none"` turns it off. See [Prompt Caching](../advanced/prompt-caching). |
101| `wrapFetch` | Wraps the fetch of each model call. The adapter must support it. |
102| `metadata` | Extra metadata for the request. |
103| `debug` | `true`, `false`, or a `DebugConfig`. By default only errors log. See [Debug Logging](../advanced/debug-logging). |
104
105### Returns
106
107By default, `chat()` returns an async iterable of `StreamChunk`. Pass it to a [response helper](#response-helpers).
108
109With `stream: false`, it returns `Promise<ChatResult>`:
110
111- `text`: the full reply as one string.
112- `chunks`: every chunk of the run, in order. This includes tool calls, tool results, reasoning, usage, and the `RUN_FINISHED` chunk with any interrupts.
113
114With `outputSchema`, it returns a promise of the parsed object. If the run fails, the promise rejects with the error from `RUN_ERROR`.
115
116```typescript
117import { chat } from "@tanstack/ai";
118import { openaiText } from "@tanstack/ai-openai";
119
120const { text, chunks } = await chat({
121 adapter: openaiText("gpt-6.1-sol"),
122 messages: [{ role: "user", content: "What is the capital of France?" }],
123 threadId: "thread-1",
124 stream: false,
125});
126
127console.log(text);
128
129for (const chunk of chunks) {
130 if (chunk.type === "RUN_FINISHED") {
131 console.log("Usage:", chunk.usage);
132 }
133}
134```
135
136## `createChatOptions`
137
138Returns `chat()` options unchanged, with full type inference. Use it to define a configuration once and spread it into `chat()`. See [Typed Options](../advanced/typed-options).
139
140```typescript
141import { chat, createChatOptions } from "@tanstack/ai";
142import { openaiText } from "@tanstack/ai-openai";
143
144const chatOptions = createChatOptions({
145 adapter: openaiText("gpt-6.1-sol"),
146});
147
148const stream = chat({
149 ...chatOptions,
150 messages: [{ role: "user", content: "Hello!" }],
151 threadId: "thread-1",
152});
153```
154
155Each activity has a matching helper: `createSummarizeOptions`, `createImageOptions`, `createAudioOptions`, `createVideoOptions`, `createSpeechOptions`, `createVoiceOptions`, `createTranscriptionOptions`, `createEmbedOptions`, `createRerankOptions`, `createWorldOptions`, and `createLiveVideoOptions`.
156
157## `toolDefinition`
158
159Defines a tool once. Then you make a server or a client implementation from it. See [Tools](../tools/tools).
160
161```typescript
162import { chat, toolDefinition } from "@tanstack/ai";
163import { openaiText } from "@tanstack/ai-openai";
164import { z } from "zod";
165
166const getWeatherDef = toolDefinition({
167 name: "get_weather",
168 description: "Get the current weather for a city",
169 inputSchema: z.object({ city: z.string() }),
170 outputSchema: z.object({ temperature: z.number() }),
171});
172
173const getWeather = getWeatherDef.server(async ({ city }) => {
174 return { temperature: city.length };
175});
176
177const stream = chat({
178 adapter: openaiText("gpt-6.1-sol"),
179 messages: [{ role: "user", content: "Weather in Paris?" }],
180 threadId: "thread-1",
181 tools: [getWeather],
182});
183```
184
185| Field | What it does |
186| --- | --- |
187| `name` | The tool name. Must be unique in a run. |
188| `description` | Tells the model when to use the tool. |
189| `inputSchema`, `outputSchema` | Standard Schema (Zod, Valibot, ArkType) or JSON Schema. |
190| `needsApproval` | `true` pauses the run for a user decision. See [Tool Approval](../interrupts/tool-approval). |
191| `approvalSchema` | The shape of the approve or reject payload. Only with `needsApproval: true`. |
192| `lazy` | The model finds the tool through discovery. See [Lazy Tool Discovery](../tools/lazy-tool-discovery). |
193| `metadata` | Extra data for your own code. |
194| `replay` | `"safe"` lets a host run the tool again after a crash. `"never"` (or no value) does not. |
195| `execution` | `"task"` makes an MCP server call return a task handle. See [MCP Server Tasks](../mcp/server-tasks). |
196
197The result has two methods:
198
199- `.server(execute)`: a tool that runs on the server.
200- `.client(execute?)`: a tool that runs in the browser. See [Client Tools](../tools/client-tools).
201
202You can also pass the definition itself to `chat()`. Then the client runs it.
203
204`execute` gets the input and a `ToolExecutionContext`. Declare a context type with `.server<AppContext>(...)`. Then `chat()` requires a matching `context`:
205
206```typescript
207import { chat, toolDefinition, toServerSentEventsResponse } from "@tanstack/ai";
208import { openaiText } from "@tanstack/ai-openai";
209import { session, db } from "./app";
210
211type AppContext = {
212 userId: string;
213 db: { users: { findName(id: string): Promise<string> } };
214};
215
216const currentUser = toolDefinition({
217 name: "current_user",
218 description: "Get the current user",
219}).server<AppContext>(async (_input: unknown, ctx) => {
220 return { name: await ctx.context.db.users.findName(ctx.context.userId) };
221});
222
223export async function POST(request: Request) {
224 const { messages, threadId } = await request.json();
225 const stream = chat({
226 adapter: openaiText("gpt-6.1-sol"),
227 messages,
228 threadId,
229 tools: [currentUser],
230 context: { userId: session.user.id, db },
231 });
232 return toServerSentEventsResponse(stream);
233}
234```
235
236## Agent loop strategies
237
238An agent loop strategy decides, between model turns, if the loop goes on. It gets `{ iterationCount, finishReason, messages, toolCallCount, lastTurnToolCallCount }` and returns `true` to go on. See [Agentic Cycle](../chat/agentic-cycle).
239
240| Function | What it does |
241| --- | --- |
242| `maxIterations(max)` | Stops after `max` model turns. |
243| `untilFinishReason(reasons)` | Stops when the finish reason is in `reasons`. |
244| `combineStrategies(strategies)` | Goes on only while every strategy returns `true`. |
245
246```typescript
247import { chat, maxIterations } from "@tanstack/ai";
248import { openaiText } from "@tanstack/ai-openai";
249
250const stream = chat({
251 adapter: openaiText("gpt-6.1-sol"),
252 messages: [{ role: "user", content: "Hello!" }],
253 threadId: "thread-1",
254 agentLoopStrategy: maxIterations(20),
255});
256```
257
258An iteration is one model turn, not one tool call. One turn can call many tools in parallel. For a tool-call budget, use middleware (`onBeforeToolCall` and `onShouldContinue`). See [Tool-call budgets](../chat/agentic-cycle#tool-call-budgets-middleware-recipe).
259
260A strategy that goes on after a `length` answer makes the model send the [cut tool call](../chat/agentic-cycle#when-the-output-limit-cuts-a-tool-call) again.
261
262## Response helpers
263
264Each helper turns a `chat()` stream into a response for one transport. Pick the one that matches the client connection adapter. See [Transports](../transports/overview).
265
266| Helper | Returns | Client adapter |
267| --- | --- | --- |
268| `toServerSentEventsResponse(stream, init?)` | `Response` with SSE headers | `fetchServerSentEvents`, `xhrServerSentEvents` |
269| `toServerSentEventsStream(stream, abortController?)` | `ReadableStream<Uint8Array>` of SSE events | Same |
270| `toHttpResponse(stream, init?)` | `Response` with newline-delimited JSON | `fetchHttpStream`, `xhrHttpStream` |
271| `toHttpStream(stream, abortController?)` | `ReadableStream<Uint8Array>` of NDJSON | Same |
272| `toJsonResponse(input, init?)` | `Promise<Response>` with one JSON body | `fetchJson` |
273| `toWebSocketResponse`, `toWebSocketStream` | WebSocket frames | `webSocket` |
274
275```typescript
276import { chat, toServerSentEventsResponse } from "@tanstack/ai";
277import { openaiText } from "@tanstack/ai-openai";
278
279export async function POST() {
280 const stream = chat({
281 adapter: openaiText("gpt-6.1-sol"),
282 messages: [{ role: "user", content: "Hello!" }],
283 threadId: "thread-1",
284 });
285 return toServerSentEventsResponse(stream);
286}
287```
288
289- `toServerSentEventsResponse` sets `Content-Type: text/event-stream`, `Cache-Control: no-cache`, and `Connection: keep-alive`.
290- `init` is a `ResponseInit`, plus `abortController` and `durability`. See [Resumable Streams](../resumable-streams/overview).
291- Each SSE event is `data: <json>\n\n`. The last event is `RUN_FINISHED` or `RUN_ERROR`.
292- `resumeServerSentEventsResponse`, `resumeHttpResponse`, and `resumeJsonResponse` serve a resumed stream from a durable log.
293
294## `chatParamsFromRequest`
295
296`chatParamsFromRequest(req)` reads a `Request`, parses the JSON body, and checks it against the AG-UI `RunAgentInput` schema. You get params ready for `chat()`.
297
298```typescript
299import {
300 chat,
301 chatParamsFromRequest,
302 toServerSentEventsResponse,
303} from "@tanstack/ai";
304import { openaiText } from "@tanstack/ai-openai";
305import { serverTools } from "./tools";
306
307export async function POST(req: Request) {
308 const params = await chatParamsFromRequest(req);
309 const stream = chat({
310 adapter: openaiText("gpt-6.1-sol"),
311 messages: params.messages,
312 threadId: params.threadId,
313 tools: serverTools,
314 });
315 return toServerSentEventsResponse(stream);
316}
317```
318
319It resolves to `{ messages, threadId, runId, parentRunId?, tools, forwardedProps, state, resume?, aguiContext }`.
320
321- `aguiContext` is the AG-UI `RunAgentInput.context` field. It is not the runtime `chat({ context })`. To give these values to tools or middleware, check them and map them yourself.
322- On a bad body, it throws a `400` `Response`. TanStack Start, SolidStart, Remix, and React Router 7 return that response for you.
323
324> [!NOTE]
325> Next.js route handlers, SvelteKit, Hono, and raw Node do not handle a thrown `Response`. Wrap the call in `try`/`catch`, or use `chatParamsFromRequestBody`.
326
327## `chatParamsFromRequestBody`
328
329`chatParamsFromRequestBody(body)` checks a body that you already parsed. It rejects with an `AGUIError` on a bad body, so you control the error response.
330
331```typescript
332import { chatParamsFromRequestBody } from "@tanstack/ai";
333
334export async function POST(req: Request): Promise<Response> {
335 try {
336 const params = await chatParamsFromRequestBody(await req.json());
337 return new Response(`thread ${params.threadId}`);
338 } catch (error) {
339 const message = error instanceof Error ? error.message : String(error);
340 return new Response(message, { status: 400 });
341 }
342}
343```
344
345## `mergeAgentTools`
346
347`mergeAgentTools(serverTools, clientTools)` merges your server tools with the tools that the client declared in the request. See [Client Tools](../tools/client-tools).
348
349```typescript
350import {
351 chat,
352 chatParamsFromRequest,
353 mergeAgentTools,
354 toServerSentEventsResponse,
355} from "@tanstack/ai";
356import { openaiText } from "@tanstack/ai-openai";
357import { serverTools } from "./tools";
358
359export async function POST(req: Request) {
360 const params = await chatParamsFromRequest(req);
361 const stream = chat({
362 adapter: openaiText("gpt-6.1-sol"),
363 messages: params.messages,
364 threadId: params.threadId,
365 tools: mergeAgentTools(serverTools, params.tools),
366 });
367 return toServerSentEventsResponse(stream);
368}
369```
370
371- `serverTools` is an array of tools.
372- `clientTools` is the `tools` array from `chatParamsFromRequest`.
373- A server tool wins when both have the same name.
374- A client-only tool becomes an entry with no `execute`. The client runs it.
375- It returns an array for `chat({ tools })`.
376
377## `streamToText`
378
379`streamToText(stream)` reads a stream to the end and resolves to the same `ChatResult` as `stream: false`: `{ text, chunks }`. It rejects with the error of a `RUN_ERROR` chunk.
380
381## `summarize`
382
383Summarizes text with a summarize adapter.
384
385```typescript
386import { summarize } from "@tanstack/ai";
387import { openaiSummarize } from "@tanstack/ai-openai";
388
389const result = await summarize({
390 adapter: openaiSummarize("gpt-6.1-sol"),
391 text: "Long text to summarize...",
392 threadId: "thread-1",
393 maxLength: 100,
394 style: "concise",
395});
396
397console.log(result.summary);
398```
399
400| Option | What it does |
401| --- | --- |
402| `adapter` | A summarize adapter with a model. |
403| `text` | The text to summarize. |
404| `maxLength` | The longest summary you want. |
405| `style` | `"bullet-points"`, `"paragraph"`, or `"concise"`. |
406| `focus` | Topics to focus on. |
407| `stream` | `true` to stream the summary. |
408| `threadId` | Required. The id of the thread that the run belongs to. |
409| `modelOptions`, `middleware`, `abortSignal`, `timeout`, `runId`, `debug` | Same meaning as for the other activities. |
410
411It resolves to a `SummarizationResult`: `{ id, model, summary, usage }`.
412
413## `decide`
414
415Asks typed questions about one shared state and returns answers your code can branch on. It is async and does not stream. See [Evaluate](../evaluate/evaluate).
416
417```typescript
418import { decide, choice, score, boolean } from "@tanstack/ai";
419import { typesafeDecider } from "@tanstack/ai-typesafe";
420
421const ticket = {
422 subject: "Charged twice for the same invoice",
423 body: "Please refund the extra payment.",
424};
425
426const result = await decide({
427 adapter: typesafeDecider("jev-latest"),
428 state: ticket,
429 questions: {
430 queue: choice({
431 instructions: "Which team should handle this ticket?",
432 options: {
433 billing: "Payments, invoices, refunds",
434 tech: "Bugs, outages, integrations",
435 sales: "Pricing, upgrades, new accounts",
436 },
437 }),
438 urgency: score({
439 instructions: "How urgent is this ticket?",
440 levels: ["low", "medium", "high"],
441 }),
442 refund: boolean({
443 instructions: "Is the customer asking for a refund?",
444 }),
445 },
446});
447
448console.log(result.queue.value, result.urgency.value, result.refund.value);
449```
450
451| Option | What it does |
452| --- | --- |
453| `adapter` | Required. An evaluate adapter with a model, for example `typesafeDecider("jev-latest")`. |
454| `state` | Required. The content that every question judges: a string, an object, or an array. An array is one state, not a batch. |
455| `questions` | Required. A map of `choice`, `score`, and `boolean` questions. The key `meta` is reserved. |
456| `abortSignal` | Cancels the request. |
457| `modelOptions` | Provider options. |
458| `middleware` | Observe-only generation middleware. |
459| `debug` | Debug logging. |
460
461Question helpers:
462
463- `choice({ instructions, options })`: picks one key from `options`. The answer has `value` (the key), `probability`, `confidence` (0 to 1), and `probabilities`.
464- `score({ instructions, levels })`: rates the state on two or more ordered `levels`. The answer has `value` (the nearest level), `score` (the raw fraction), `probability`, `confidence`, `legend` (level index to label), and `probabilities` (by level index).
465- `boolean({ instructions, criteria? })`: yes or no. `value` is `true` when `probability` is 0.5 or more. There is no `confidence`.
466
467`result.meta` holds `model` and `usage`. When the adapter returns them, it also holds `id` (the provider response id) and `provider`.
468
469## Generation functions
470
471Each function runs one generation with a matching adapter. The guide for each one shows the server and the client side.
472
473The generate functions need a `threadId`, the same as `chat()`. `getVideoJobStatus` needs it only when you pass middleware, for example persistence.
474
475| Function | What it makes | Guide |
476| --- | --- | --- |
477| `generateImage` | Images | [Image Generation](../media/image-generation) |
478| `generateAudio` | Music and sound effects | [Audio Generation](../media/audio-generation) |
479| `generateSpeech` | Speech from text | [Text to Speech](../media/text-to-speech) |
480| `listVoices`, `generateVoice` | Voice lists and new voices | [Voice Creation](../media/voice-creation) |
481| `generateTranscription` | Text from audio | [Transcription](../media/transcription) |
482| `generateVideo`, `getVideoJobStatus` | Video jobs and their status | [Video Generation](../media/video-generation) |
483| `generateWorld` | 3D worlds | [World Generation](../media/world-generation) |
484| `generateLiveVideo` | Live video sessions | [Live Generation](../media/live-generation) |
485| `embed` | Embeddings | [Embeddings](../embeddings) |
486| `rerank` | Ranked documents | [Rerank](../rerank/rerank) |
487| `uploadFile`, `getFile`, `deleteFile`, `fileSourceFromHandle` | Provider file uploads | [Files API](../advanced/files-api) |
488
489## BYOK
490
491Bring Your Own Key helpers. Import them from `@tanstack/ai/byok`. The functions that read `process.env` are on `@tanstack/ai/byok/server`. See [Bring Your Own Key](../advanced/byok).
492
493### `defineByokProvider`
494
495`defineByokProvider({ id, label, env?, with? })` declares a BYOK provider. Adapter packages use it.
496
497```typescript
498import { defineByokProvider } from "@tanstack/ai/byok";
499
500export const openaiByok = defineByokProvider({
501 id: "openai",
502 label: "OpenAI",
503 env: "OPENAI_API_KEY",
504});
505```
506
507| Field | What it does |
508| --- | --- |
509| `id` | Required. The slug (`[a-z][a-z0-9-]{0,63}`) in the `x-byok-<id>` header. |
510| `label` | The display name. |
511| `env` | The name of an env var, or a list of names to try in order. Names only: this object is imported on the client, so never put `process.env` values here. |
512| `with` | Other descriptors that this credential needs, for example an account id next to a token. A keyring from `defineByok({ providers })` sends and asks for them together. Read them with `getByokKeys`. |
513
514It returns `{ id, label, env?, with? }`, with `id` as a literal type. A string `env` is stored as a one-item array.
515
516Import a descriptor from the adapter `/byok` subpath, for example `openaiByok` from `@tanstack/ai-openai/byok`. The adapter main entry pulls in the provider SDK.
517
518### `getByokKey`
519
520`getByokKey(request, provider)` reads a key on your relay route. It works in any API route. Import it from `@tanstack/ai/byok/server`.
521
522```typescript
523import { getByokKey } from "@tanstack/ai/byok/server";
524import { openaiByok } from "@tanstack/ai-openai/byok";
525
526export async function POST(request: Request) {
527 const apiKey = getByokKey(request, openaiByok);
528 return new Response(apiKey ? "ok" : "missing");
529}
530```
531
532- `provider` is a `ByokProvider` or a slug.
533- The `x-byok-<slug>` header wins.
534- Then a `ByokProvider` tries its `env` names in order. A slug reads only the header.
535- It returns `null` when nothing is found. It never reads the JSON body.
536
537### `getByokKeys`
538
539`getByokKeys(request, providers)` reads several keys at once. When one credential has more than one value, use it. Each entry follows the `getByokKey` rules.
540
541```typescript
542import { byokMissing, getByokKeys } from "@tanstack/ai/byok/server";
543import {
544 cloudflareAccountByok,
545 cloudflareByok,
546} from "@tanstack/ai-cloudflare/byok";
547
548export async function POST(request: Request) {
549 const { apiKey, accountId } = getByokKeys(request, {
550 apiKey: cloudflareByok,
551 accountId: cloudflareAccountByok,
552 });
553 if (!apiKey) return byokMissing(cloudflareByok);
554 if (!accountId) return byokMissing(cloudflareAccountByok);
555 return new Response("ok");
556}
557```
558
559It returns an object with the same keys, each `string | null`.
560
561### `byokMissing`
562
563`byokMissing(provider)` returns a `401` JSON `Response`: `{ error: { type: "byok_missing", provider, message } }`. The chat and generation clients read this body and set `snapshot.prompt`. Import it from `@tanstack/ai/byok` or `@tanstack/ai/byok/server`.
564
565```typescript
566import { byokMissing, getByokKey } from "@tanstack/ai/byok/server";
567import { openaiByok } from "@tanstack/ai-openai/byok";
568
569export async function POST(request: Request) {
570 const apiKey = getByokKey(request, openaiByok);
571 if (!apiKey) return byokMissing(openaiByok);
572 return new Response("ok");
573}
574```
575
576### `maskKey`
577
578`maskKey(key)` returns the last four characters of a key. A key of four characters or fewer becomes `"••"`.
579
580```typescript
581import { maskKey } from "@tanstack/ai/byok";
582
583maskKey("sk-abcdefghij"); // "ghij"
584```
585
586### `scrubSecrets`
587
588`scrubSecrets(input, secrets)` replaces each secret in `input` with `[redacted]`. Use it before you log an error string.
589
590```typescript
591import { scrubSecrets } from "@tanstack/ai/byok";
592
593scrubSecrets("failed sk-live extra", ["sk-live"]);
594// "failed [redacted] extra"
595```
596
597### Keyed adapters
598
599`keyedAdapter`, `keyedAdapters`, and `keyedAdapterFromRequest` (server) build the adapter of the first provider that has a key. `keyedAdapterFromRequest` returns `null` when no provider has a key, so the route can answer with `byokMissing`. See [Bring Your Own Key](../advanced/byok).
600
601## Other exports
602
603The package exports more building blocks. Each group has a guide.
604
605| Group | Main exports | Guide |
606| --- | --- | --- |
607| Middleware | `defineChatMiddleware`, `createChatMiddleware`, capabilities | [Middleware](../advanced/middleware-advanced) |
608| Interrupts | `defineInterrupt` | [Generic Interrupts](../interrupts/generic) |
609| Subagents | `defineAgent`, `subagentRoute`, `runAgentStream` | [Subagents](../chat/subagents), [Subagents: Advanced](../chat/subagents-advanced) |
610| Durable streams | `memoryStream`, `replayRunStream` | [Resumable Streams](../resumable-streams/overview) |
611| Run cancel | `requestRunCancel`, `wasCancelRequested` | [Takeover](../sandbox/takeover) |
612| Custom adapters | `extendAdapter`, `createModel` | [Extend an Adapter](../advanced/extend-adapter) |
613| Realtime | `realtimeToken` | [Realtime Chat](../media/realtime-chat) |
614| Message converters | `convertMessagesToModelMessages`, `uiMessageToModelMessages`, `modelMessagesToUIMessages` | [Generated reference](../reference/index) |
615
616Subpath entries:
617
618| Subpath | What it holds | Guide |
619| --- | --- | --- |
620| `@tanstack/ai/middlewares` | Built-in middleware | [Built-in Middleware](../advanced/built-in-middleware) |
621| `@tanstack/ai/middlewares/otel` | OpenTelemetry middleware | [OpenTelemetry](../advanced/otel) |
622| `@tanstack/ai/locks` | Locks across instances | [Locks](../advanced/locks) |
623| `@tanstack/ai/testing` | Test helpers | [Testing](../advanced/testing) |
624| `@tanstack/ai/adapters`, `@tanstack/ai/adapter-internals` | Base classes for adapter authors | [Community Adapters](../community-adapters/guide) |
625| `@tanstack/ai/client` | Browser-safe types and helpers | [`@tanstack/ai-client`](./ai-client) |
626
627## Types
628
629Each type links to its full definition in the generated reference.
630
631| Type | What it is |
632| --- | --- |
633| [`ModelMessage`](../reference/interfaces/ModelMessage) | A message in model format: `role` (`"user"`, `"assistant"`, or `"tool"`), `content`, `toolCalls`, `toolCallId`, `thinking`, and more. |
634| [`StreamChunk`](../reference/type-aliases/StreamChunk) | One AG-UI event: `RUN_STARTED`, `TEXT_MESSAGE_CONTENT`, `TOOL_CALL_START`, `RUN_FINISHED`, `RUN_ERROR`, and the others. See [Stream Events](../chat/stream-events). |
635| [`Tool`](../reference/interfaces/Tool) | A tool: `name`, `description`, `inputSchema`, `outputSchema`, `execute`, `needsApproval`, `lazy`, `metadata`. |
636| [`ToolExecutionContext`](../reference/type-aliases/ToolExecutionContext) | The second argument of `execute`: `context`, `toolCallId`, `threadId`, `abortSignal`, `emitCustomEvent`, and more. `threadId` is the thread id of the chat run, so a tool can keep its own state for each conversation. It is missing when the tool runs outside a chat, for example from an MCP server, WebMCP, or a direct `execute()` call. |
637| [`ChatMiddleware`](../reference/interfaces/ChatMiddleware) | Middleware hooks: `onConfig`, `onStart`, `onChunk`, `onBeforeToolCall`, `onAfterToolCall`, `onShouldContinue`, `onFinish`, `onAbort`, `onError`, and more. See [Middleware](../advanced/middleware). |
638
639In a tool, `context` is the value from `chat({ context })`. In a client tool, it comes from the `ChatClient` or hook options. It is required when the tool declares a context type.