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

middleware-advanced.md

1,351 lines52.6 KB

1---
2title: "Middleware: Advanced"
3id: middleware-advanced
4description: "Every chat() middleware hook in detail: the lifecycle, the context object, composition rules, capabilities, recipes, and the types."
5keywords:
6 - tanstack ai
7 - middleware
8 - lifecycle hooks
9 - capabilities
10 - onConfig
11 - onChunk
12 - onBeforeToolCall
13 - structured output
14---
15​
16This page covers each middleware hook in detail. Set up your first middleware with [Middleware](./middleware).
17​
18## Lifecycle
19​
20Each `chat()` call goes through the same steps. The hooks fire at these steps:
21​
22```mermaid
23graph TD
24 A["chat() called"] --> B["onConfig (phase: init)"]
25 B --> C[onStart]
26 C --> D["onConfig (phase: beforeModel)"]
27 D --> E["Adapter streams response"]
28 E --> F["onChunk (for each chunk)"]
29 F --> G{Tool calls?}
30 G -->|No| H[onUsage]
31 G -->|Yes| I[onBeforeToolCall]
32 I --> J[Tool executes]
33 J --> K[onAfterToolCall]
34 K --> L{Continue loop?}
35 L -->|Yes| D
36 L -->|No| H
37 H --> SO{"Structured output path?"}
38 SO -->|None| M{Outcome}
39 SO -->|"Native combined"| SOH["Post-loop structured-output harvest (onChunk)"]
40 SOH --> M
41 SO -->|"Separate finalization"| SOC[onStructuredOutputConfig]
42 SOC --> SOM["onConfig (phase: structuredOutput)"]
43 SOM --> SOS["Structured-output finalization (onChunk, onUsage)"]
44 SOS --> M
45 M -->|Success| N[onFinish]
46 M -->|Abort| O[onAbort]
47 M -->|Error| P[onError]
48​
49 style I fill:#e1f5ff
50 style J fill:#ffe1e1
51 style SOC fill:#e1f5ff
52 style SOM fill:#e1f5ff
53 style SOS fill:#e1f5ff
54 style SOH fill:#e1f5ff
55 style N fill:#e1ffe1
56 style O fill:#fff4e1
57 style P fill:#ffe1e1
58```
59​
60### Phase transitions
61​
62The `phase` field of the context tells you where the run is:
63​
64| Phase | When | Hooks called |
65| --- | --- | --- |
66| `init` | Once at startup | `onConfig` |
67| `beforeModel` | Before each model call (one time per iteration) | `onConfig` |
68| `modelStream` | While the adapter streams chunks | `onChunk`, `onUsage` |
69| `beforeTools` | Before the tools run | `onBeforeToolCall` |
70| `afterTools` | After the tools run | `onAfterToolCall` |
71| `structuredOutput` | During the separate structured-output call (see below) | `onStructuredOutputConfig`, `onConfig`, `onChunk`, `onUsage` |
72​
73### The two structured-output paths
74​
75When you call `chat()` with `outputSchema`, the adapter takes one of two paths.
76​
77- **Separate finalization.** `supportsCombinedToolsAndSchema()` does not return `true` for the current model and options. After the agent loop, the engine makes one more call to the adapter. The chunks from `adapter.structuredOutputStream` (or the non-streaming fallback) go through `onChunk` with the `structuredOutput` phase. `onUsage` fires for the tokens of that call.
78- **Native combined.** The adapter sends tools and the schema in one streaming call. The `structuredOutput` phase does not fire. Middleware sees the run through `beforeModel` and `modelStream` as usual. These adapters do this (see issue #605):
79 - Modern OpenAI Chat Completions and OpenAI Responses.
80 - Claude 4.5+, Gemini 3.x, and the Grok 4.x family.
81 - OpenRouter, when every routed model is in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`.
82​
83## Hooks reference
84​
85### onConfig
86​
87`onConfig` runs once in the `init` phase, and once per iteration in the `beforeModel` phase. Use it to change the config that the model gets.
88​
89On the separate-finalization path, `onConfig` runs one more time at the structured-output step, with `ctx.phase === 'structuredOutput'`. It gets the config after `onStructuredOutputConfig`. So a separate-finalization run with one iteration calls `onConfig` three times (`init`, `beforeModel`, `structuredOutput`). Native-combined output does not add this third call.
90​
91Return a **partial** config with only the fields you want to change. The engine merges it into the current config (a shallow merge). You do not have to spread the existing config.
92​
93```typescript
94import { type ChatMiddleware } from "@tanstack/ai";
95​
96const dynamicTemperature: ChatMiddleware = {
97 name: "dynamic-temperature",
98 onConfig: (ctx, config) => {
99 if (ctx.phase === "init") {
100 // Add a system prompt at startup. Only systemPrompts changes.
101 return {
102 systemPrompts: [
103 ...config.systemPrompts,
104 "You are a helpful assistant.",
105 ],
106 };
107 }
108​
109 if (ctx.phase === "beforeModel" && ctx.iteration > 0) {
110 // Increase the temperature on later calls. Sampling params live in
111 // the provider-native modelOptions object. `temperature` has the same
112 // key on all providers. Spread modelOptions to keep the other options.
113 const current =
114 typeof config.modelOptions?.temperature === "number"
115 ? config.modelOptions.temperature
116 : 0.7;
117 return {
118 modelOptions: {
119 ...config.modelOptions,
120 temperature: Math.min(current + 0.1, 1.0),
121 },
122 };
123 }
124 },
125};
126```
127​
128> [!NOTE]
129> Sampling parameters (`temperature`, `top_p` / `topP`, the `max*Tokens` keys) live in `modelOptions`, under the native name of each provider. `temperature` has the same name on all providers. A token limit does not. For example, OpenAI uses `max_output_tokens`, and Ollama uses `num_predict` inside `modelOptions.options`.
130​
131Config fields you can change:
132​
133| Field | Type | Description |
134| --- | --- | --- |
135| `messages` | `ModelMessage[]` | The canonical conversation history. Persistence and `ctx.messages` use this field. |
136| `providerMessages` | `ModelMessage[]` | Temporary context sent to the provider. Defaults to `messages`. |
137| `systemPrompts` | `SystemPrompt[]` | System prompts |
138| `tools` | `Tool[]` | The tools the model can call |
139| `metadata` | `Record<string, unknown>` | Request metadata |
140| `modelOptions` | `Record<string, unknown>` | Provider-native options, including the sampling params |
141| `reasoning` | `ReasoningRequest \| undefined` | How hard the model thinks at this call |
142| `toolChoice` | `ToolChoice \| undefined` | How the model uses the tools at the next model call. See [Change the tool choice of a call](./middleware#change-the-tool-choice-of-a-call). |
143| `wrapFetch` | `FetchWrapper \| undefined` | Wraps the HTTP fetch of the next model call. See [Change the HTTP requests of a call](./middleware#change-the-http-requests-of-a-call). |
144| `promptCache` | `ResolvedPromptCache \| undefined` | The prompt cache of the next model call: its `retention` and `key`. See [Change the prompt cache of a call](./middleware#change-the-prompt-cache-of-a-call). |
145​
146When more than one middleware has `onConfig`, the config is **piped** through them in order. Each one gets the merged config from the one before it.
147​
148If a change must affect only the model call, return `providerMessages`. Returning `messages` also changes the provider input, unless the same result sets `providerMessages`.
149​
150### onStructuredOutputConfig
151​
152This hook runs once, at the start of the separate structured-output call. It runs only when `chat()` has `outputSchema` **and** `supportsCombinedToolsAndSchema()` does not return `true` for the current model and options.
153​
154It pipes through the middleware in order, like `onConfig`. It also gets the **JSON Schema** that goes to the provider. Use it to:
155​
156- Change the schema. For example, add `$defs`, or remove keywords that a provider does not accept.
157- Change only the final call. For example, remove the system prompts from it.
158​
159> [!NOTE]
160> Native-combined adapters (modern OpenAI, Claude 4.5+, Gemini 3.x, Grok 4.x, see issue #605) make no separate call, so this hook never runs. The engine sends the converted schema to `chatStream` after `onConfig`. Middleware cannot change the schema on that path.
161​
162Return a **partial** `StructuredOutputMiddlewareConfig` with the fields you want to change. The engine merges it (a shallow merge). Return nothing to pass the config through.
163​
164```typescript
165import { type ChatMiddleware } from "@tanstack/ai";
166import { sharedDefs } from "./defs";
167​
168const injectDefs: ChatMiddleware = {
169 name: "inject-defs",
170 onStructuredOutputConfig: (_ctx, config) => {
171 // `config.outputSchema` is the JSON Schema that goes to the provider
172 return {
173 outputSchema: {
174 ...config.outputSchema,
175 $defs: { ...sharedDefs },
176 },
177 };
178 },
179};
180```
181​
182Config fields you can change:
183​
184| Field | Type | Description |
185| --- | --- | --- |
186| `messages` | `ModelMessage[]` | The canonical conversation history |
187| `providerMessages` | `ModelMessage[]` | Temporary context sent to the final call |
188| `systemPrompts` | `SystemPrompt[]` | System prompts on the final call |
189| `metadata` | `Record<string, unknown>` | Request metadata |
190| `modelOptions` | `Record<string, unknown>` | Provider-native options, including the sampling params |
191| `outputSchema` | `JSONSchema` | The JSON Schema that goes to the provider |
192​
193The order at the structured-output step:
194​
1951. `onStructuredOutputConfig` runs first, through each middleware in array order.
1962. `onConfig` runs again with `ctx.phase === 'structuredOutput'`. It gets the config after step 1, without `outputSchema`.
197​
198Use `onConfig` for changes that apply to every adapter call. If you need the schema, use `onStructuredOutputConfig`.
199​
200### onStart
201​
202`onStart` runs once, after the first `onConfig`. Use it to start timers or write a log line.
203​
204```typescript
205import { type ChatMiddleware } from "@tanstack/ai";
206​
207const timer: ChatMiddleware = {
208 name: "timer",
209 onStart: (ctx) => {
210 console.log(`Request ${ctx.requestId} started at iteration ${ctx.iteration}`);
211 },
212};
213```
214​
215### onIteration
216​
217`onIteration` runs at the start of each agent-loop iteration, after the engine creates the new assistant message ID. It gets `{ iteration, messageId }`. Use it to see the iteration boundaries. It does not run for the separate structured-output call.
218​
219### onChunk
220​
221`onChunk` runs for each chunk from the adapter. It can read, change, split, or drop the chunk.
222​
223```typescript ignore
224import { type ChatMiddleware } from "@tanstack/ai";
225​
226const redactor: ChatMiddleware = {
227 name: "redactor",
228 onChunk: (ctx, chunk) => {
229 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
230 // Redact numbers that look like an SSN
231 return {
232 ...chunk,
233 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
234 };
235 }
236 // Return nothing to pass the chunk through
237 },
238};
239```
240​
241Return values:
242​
243| Return | Effect |
244| --- | --- |
245| `void` / `undefined` | The chunk passes through unchanged |
246| `StreamChunk` | Replaces the chunk |
247| `StreamChunk[]` | Splits it into more chunks |
248| `null` | Drops the chunk |
249​
250When more than one middleware has `onChunk`, chunks flow through them in order. If one middleware drops a chunk, the middleware after it never see it.
251​
252#### Chunk types you see
253​
254`onChunk` gets every [AG-UI event](https://docs.ag-ui.com/introduction) of the run, not only text. Narrow on `chunk.type` (a discriminated union) before you read the fields of a type. The common types:
255​
256| `chunk.type` | Meaning | Key fields |
257| --- | --- | --- |
258| `RUN_STARTED` / `RUN_FINISHED` / `RUN_ERROR` | Start and end of the run | `runId`, `finishReason`, `usage` (on finish), `message` (on error) |
259| `TEXT_MESSAGE_START` / `TEXT_MESSAGE_CONTENT` / `TEXT_MESSAGE_END` | Assistant text | `messageId`, `delta` (content) |
260| `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END` | Tool calls | `toolCallId`, `toolCallName`, `delta` (args), result on end |
261| `REASONING_START` / `REASONING_MESSAGE_CONTENT` / `REASONING_END` | Thinking or reasoning | `messageId`, `delta`. The signature comes on `REASONING_ENCRYPTED_VALUE` |
262| `STATE_SNAPSHOT` / `STATE_DELTA` | Agent state sync | `snapshot`, `delta` |
263| `CUSTOM` | Extension events, including structured output (see below) | `name`, `value` |
264​
265For the full list of events and their fields, see the [AG-UI protocol docs](https://docs.ag-ui.com/introduction).
266​
267#### Change structured-output chunks
268​
269Structured-output chunks go through the same `onChunk` hook as all other chunks. There is no separate chunk hook. When `chat()` has `outputSchema`, these chunks flow through `onChunk`:
270​
271- The JSON `TEXT_MESSAGE_CONTENT` deltas.
272- The `structured-output.start` and `structured-output.complete` CUSTOM events.
273- Any `RUN_ERROR` from the final step.
274​
275How you find them depends on the path of the adapter:
276​
277- **Separate finalization:** `ctx.phase === 'structuredOutput'` during the final call. Check the phase.
278- **Native combined:** the model writes the JSON on its natural last turn, so **`ctx.phase` stays `'modelStream'`**. The `'structuredOutput'` phase never fires. Check the CUSTOM event name (`structured-output.start` / `structured-output.complete`).
279​
280```typescript ignore
281import { type ChatMiddleware } from "@tanstack/ai";
282​
283const redactStructuredOutput: ChatMiddleware = {
284 name: "redact-structured-output",
285 onChunk: (ctx, chunk) => {
286 // Separate-finalization path: the JSON streams as TEXT_MESSAGE_CONTENT
287 // in the 'structuredOutput' phase. Change the delta like any other text
288 // chunk. Here, redact numbers that look like an SSN.
289 if (
290 ctx.phase === "structuredOutput" &&
291 chunk.type === "TEXT_MESSAGE_CONTENT"
292 ) {
293 return {
294 ...chunk,
295 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
296 };
297 }
298​
299 // Both paths: the complete typed payload comes as a CUSTOM
300 // `structured-output.complete` event. On the native-combined path this
301 // is the only signal (ctx.phase never becomes 'structuredOutput'), so
302 // check the event name, not the phase. `chunk.value` has { object, raw }.
303 if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
304 console.log("final structured output:", chunk.value);
305 }
306​
307 // Return nothing to pass all other chunks through.
308 },
309};
310```
311​
312The config hooks are different because the config at the structured-output step has an `outputSchema` field that `ChatMiddlewareConfig` does not have (see [onStructuredOutputConfig](#onstructuredoutputconfig)). Chunks are always `StreamChunk`, in every phase. So one `onChunk` plus `ctx.phase` (or the CUSTOM event name) covers all cases.
313​
314### onShouldContinue
315​
316`onShouldContinue` runs when the engine decides if it starts another agent-loop iteration (after a tool phase, or between model turns). It gets the same `AgentLoopState` as the loop strategies (`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, and more).
317​
318- Return `false` to stop the loop.
319- Return `true`, `void`, or `undefined` to let it continue.
320- The results combine with AND, across all middleware and with `agentLoopStrategy`. One `false` stops the loop.
321​
322This hook does **not** abort the run. The stream finishes normally with the current messages. Use `ctx.abort()` only for a hard stop.
323​
324```typescript
325import { type ChatMiddleware } from "@tanstack/ai";
326​
327const budget: ChatMiddleware = {
328 name: "tool-budget",
329 onShouldContinue: (_ctx, state) => {
330 // Stop more turns after the model makes 20 tool calls
331 if (state.toolCallCount >= 20) return false;
332 },
333};
334```
335​
336For a full budget per turn and per run, see [Tool-call budgets](../chat/agentic-cycle#tool-call-budgets-middleware-recipe).
337​
338### onModelError
339​
340Some model calls fail for a reason that your middleware can fix. For example, the prompt is too long for the model. `onModelError` gets the `RUN_ERROR` before anyone else sees it. Fix the request and call `ctx.retry()`. While the call has retries left, the run goes on as if the call never failed.
341​
342Say your app sends retrieved documents as a second system prompt. When the call is too long, this middleware drops them and tries again:
343​
344```typescript
345import { CONTEXT_OVERFLOW_CODE } from "@tanstack/ai";
346import type { ChatMiddleware, ChatMiddlewareContext } from "@tanstack/ai";
347​
348// The runs that go on without the documents.
349const withoutDocs = new WeakSet<ChatMiddlewareContext>();
350​
351const dropDocsWhenTooLong: ChatMiddleware = {
352 name: "drop-docs-when-too-long",
353 onModelError: (ctx, error) => {
354 if (error.code !== CONTEXT_OVERFLOW_CODE) return;
355 withoutDocs.add(ctx);
356 ctx.retry();
357 },
358 onConfig: (ctx, config) => {
359 if (ctx.phase !== "beforeModel" || !withoutDocs.has(ctx)) return;
360 // Keep the main system prompt. Drop the documents after it.
361 return { systemPrompts: config.systemPrompts.slice(0, 1) };
362 },
363};
364```
365​
366What `ctx.retry()` does while the call has retries left:
367​
368- It drops the failed call. `onChunk` and the caller never see its `RUN_STARTED` or `RUN_ERROR`.
369- It runs `onConfig` again (phase `beforeModel`), then calls the model again.
370- It works only inside `onModelError`. In any other hook it throws.
371​
372When the hook runs:
373​
374- Only when the adapter sends a `RUN_ERROR` before any output. A call that already sent text is not retried, so no output repeats.
375- Not for an exception that the adapter throws. That error goes to `onError`.
376- Not for the separate structured-output call after the agent loop. The model calls of the agent loop get the hook as usual.
377- Every time, also after the last retry. A model call retries at most 2 times. After that, the error goes to the caller.
378​
379`withCompaction` uses this hook to [compact and retry after a context overflow](./compaction#when-the-chat-is-still-too-long).
380​
381### onInterruptBoundary and onInterruptResolution
382​
383Use these hooks when middleware needs data from the client. Define the request with `defineInterrupt()`. Register it with `chat({ interrupts })` and `useChat({ interrupts })`. Do not send raw AG-UI events from middleware.
384​
385`onInterruptBoundary` runs at four points in an agent iteration:
386​
387- `beforeModel`, before the adapter starts.
388- `afterModel`, after the model response is complete.
389- `beforeTools`, before the tools start.
390- `afterTools`, after the tool phase is complete.
391​
392Each middleware can return requests from one boundary. The engine puts all requests from that boundary into one AG-UI interrupt batch. The batch ends the run with one interrupt outcome.
393​
394This hook cannot change the config. It can return only `{ interrupts }` or nothing. The continuation is a new `chat()` call, so the hook runs again. If `ctx.parentRunId` is set and the pause belongs to the first request only, return nothing.
395​
396For what `ctx` has at each phase, and when to use each phase, see [Lifecycle Boundaries](../interrupts/boundaries).
397​
398Create one shared definition. The server and the client both import this value, so the definition ID and the response shape are the same on both sides.
399​
400```typescript title="review-plan.ts"
401import { defineInterrupt, type ChatMiddleware } from '@tanstack/ai'
402import { z } from 'zod'
403​
404export const reviewPlan = defineInterrupt({
405 id: 'review-plan',
406 payloadSchema: z.object({ title: z.string() }),
407 responseSchema: z.object({ approved: z.boolean() }),
408})
409​
410export const reviewMiddleware: ChatMiddleware<unknown, typeof reviewPlan> = {
411 name: 'review-plan',
412 onInterruptBoundary(ctx) {
413 if (ctx.phase !== 'beforeTools') return
414 if (ctx.parentRunId) return
415 return {
416 interrupts: [
417 reviewPlan.interrupt({
418 key: 'release-plan',
419 reason: 'review-required',
420 message: 'Approve this plan?',
421 payload: { title: 'Release plan' },
422 }),
423 ],
424 }
425 },
426 onInterruptResolution(_ctx, resumedInterrupts) {
427 for (const result of resumedInterrupts.for(reviewPlan)) {
428 if (result.status === 'resolved' && !result.response.approved) {
429 return { toolResume: 'stop' }
430 }
431 }
432 },
434```
435​
436Register the definition on the server. Forward `parentRunId` and `resume`, so that a client answer starts the continuation with its full context.
437​
438```typescript title="route.ts"
439import {
440 chat,
441 chatParamsFromRequestBody,
442 toServerSentEventsResponse,
443} from '@tanstack/ai'
444import { openaiText } from '@tanstack/ai-openai'
445import { reviewMiddleware, reviewPlan } from './review-plan'
446​
447export async function POST(request: Request) {
448 const params = await chatParamsFromRequestBody(await request.json())
449 const stream = chat({
450 adapter: openaiText('gpt-6.1-sol'),
451 messages: params.messages,
452 threadId: params.threadId,
453 runId: params.runId,
454 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
455 ...(params.resume ? { resume: params.resume } : {}),
456 interrupts: [reviewPlan],
457 middleware: [reviewMiddleware],
458 })
459​
460 return toServerSentEventsResponse(stream)
462```
463​
464Register the same definition on the client. Check `kind` and `definitionId`. TypeScript then treats the item as `GenericInterrupt<typeof reviewPlan>`. `resolveInterrupt` uses the response shape from `reviewPlan.responseSchema`.
465​
466```tsx title="review-plan-panel.tsx"
467import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
468import type { GenericInterrupt } from '@tanstack/ai-react'
469import { reviewPlan } from './review-plan'
470​
471function ReviewCard({
472 interrupt,
473}: {
474 interrupt: GenericInterrupt<typeof reviewPlan>
475}) {
476 return (
477 <button
478 onClick={() => interrupt.resolveInterrupt({ approved: true })}
479 >
480 Approve plan
481 </button>
482 )
484​
485export function ReviewPlanPanel() {
486 const { interrupts, sendMessage } = useChat({
487 connection: fetchServerSentEvents('/api/chat'),
488 threadId: 'support-chat',
489 interrupts: [reviewPlan],
490 })
491​
492 return (
493 <>
494 <button onClick={() => sendMessage('Review the release plan')}>
495 Start review
496 </button>
497 {interrupts.map((interrupt) => {
498 if (interrupt.kind !== 'generic') return null
499 if (!('definitionId' in interrupt)) return null
500 if (interrupt.definitionId !== reviewPlan.id) return null
501 return <ReviewCard key={interrupt.id} interrupt={interrupt} />
502 })}
503 </>
504 )
506```
507​
508`onInterruptResolution` does not run in the `chat()` call that paused. It runs once at the start of the next `chat()` call, after the client answers:
509​
510```
511setup
512onConfig (phase is init)
513onInterruptResolution (phase is still init)
514onStart
515then stop, or continue the agent loop
516```
517​
518`useChat` sends `parentRunId` and `resume` on that second request. Each generic resume item has the original request in `metadata`. If `resume` is present and `parentRunId` is missing, the server throws.
519​
520To read the answers:
521​
522- `resumedInterrupts.for(definition)` reads one typed definition.
523- `resumedInterrupts.all()` reads every registered definition.
524- `resumedInterrupts.all(definitionA, definitionB)` reads a typed subset.
525​
526The hook can return `toolResume: 'continue'`, `'cancel'`, or `'stop'`. The results from all middleware combine by the most restrictive rule: `stop` wins over `cancel`, and `cancel` wins over `continue`.
527​
528This hook cannot change prompts, tools, or messages. Store the answer on a capability. Then return those fields from `onConfig` when `ctx.phase === 'beforeModel'`.
529​
530| Hook | Can change |
531| --- | --- |
532| `onInterruptBoundary` | Nothing. It can only pause. |
533| `onInterruptResolution` | Pending-tool policy (`toolResume`) |
534| `onConfig` | `messages`, `systemPrompts`, `tools`, `modelOptions`, `metadata`, `toolChoice` |
535​
536The full resume order, and an example that writes a user note into the system prompt, is in [Apply Answers](../interrupts/apply-answers).
537​
538### onBeforeToolCall
539​
540`onBeforeToolCall` runs before a server tool runs, and before a client tool goes to the client. The first middleware that returns a decision skips the other middleware for that call.
541​
542Each tool call goes through these steps:
543​
5441. The engine parses the JSON arguments from the model.
5452. `onBeforeToolCall` gets the parsed input.
5463. The `inputSchema` of the tool checks the final input. The engine awaits an async validator. A schema transform applies once, here.
5474. The server tool runs, or the client gets the call, with the checked input.
548​
549The schema checks the input after your hook:
550​
551- `hookCtx.args` has no schema defaults or transforms yet, and it can be invalid. Check its shape before you read it.
552- A `transformArgs` value or an in-place edit must fit the schema. If it does not fit, the call gets a tool error, `onAfterToolCall` runs with `ok: false`, and the tool does not run.
553​
554When the hook runs:
555​
556- For a client tool, the hook runs before the server sends the call to the client. The hook does not run when the client result comes back.
557- A client tool gets `onAfterToolCall` only when the hook skips the call or the schema check fails. The result from the client does not run it. If your middleware pairs the two hooks and `hookCtx.tool?.execute` is missing, return early.
558- A call that waits for approval does not run the hook. A denied call does not run it either.
559- After approval, the hook gets the approved input, including any `editedArgs`. See [Tool Approval](../interrupts/tool-approval).
560​
561```typescript
562import { type ChatMiddleware } from "@tanstack/ai";
563​
564function isRecord(v: unknown): v is Record<string, unknown> {
565 return typeof v === "object" && v !== null;
567​
568const guard: ChatMiddleware = {
569 name: "guard",
570 onBeforeToolCall: (ctx, hookCtx) => {
571 // Block dangerous tools
572 if (hookCtx.toolName === "deleteDatabase") {
573 return { type: "abort", reason: "Dangerous operation blocked" };
574 }
575​
576 // Add a default argument
577 if (hookCtx.toolName === "search" && isRecord(hookCtx.args) && !hookCtx.args.limit) {
578 return {
579 type: "transformArgs",
580 args: { ...hookCtx.args, limit: 10 },
581 };
582 }
583 },
584};
585```
586​
587Decisions:
588​
589| Decision | Effect |
590| --- | --- |
591| `void` / `undefined` | Go on as usual. The next middleware can decide. |
592| `{ type: 'transformArgs', args }` | Replace the tool arguments before the tool runs |
593| `{ type: 'skip', result }` | Do not run the tool. Use `result` instead. |
594| `{ type: 'abort', reason? }` | Abort the whole chat run |
595​
596The `hookCtx` fields:
597​
598| Field | Type | Description |
599| --- | --- | --- |
600| `toolCall` | `ToolCall` | The raw tool call object |
601| `tool` | `Tool \| undefined` | The resolved tool definition |
602| `args` | `unknown` | The parsed arguments |
603| `toolName` | `string` | The tool name |
604| `toolCallId` | `string` | The tool call ID |
605​
606### onAfterToolCall
607​
608`onAfterToolCall` runs after each tool runs (or is skipped). Every middleware runs, in array order.
609​
610```typescript
611import { type ChatMiddleware } from "@tanstack/ai";
612​
613const toolLogger: ChatMiddleware = {
614 name: "tool-logger",
615 onAfterToolCall: (ctx, info) => {
616 if (info.ok) {
617 console.log(`${info.toolName} completed in ${info.duration}ms`);
618 } else {
619 console.error(`${info.toolName} failed:`, info.error);
620 }
621 },
622};
623```
624​
625The `info` fields:
626​
627| Field | Type | Description |
628| --- | --- | --- |
629| `toolCall` | `ToolCall` | The raw tool call object |
630| `tool` | `Tool \| undefined` | The resolved tool definition |
631| `toolName` | `string` | The tool name |
632| `toolCallId` | `string` | The tool call ID |
633| `ok` | `boolean` | `true` when the tool succeeded |
634| `duration` | `number` | Run time in milliseconds |
635| `result` | `unknown` | The result (when `ok` is true). After a `replaceResult` from an earlier middleware, the new result. |
636| `error` | `unknown` | The error (when `ok` is false) |
637​
638#### Replace a tool result
639​
640Some tools return much more than the model needs: 500 rows, a huge log, a secret you want to hide. The model reads every token of it. Return `{ type: 'replaceResult', result }`, and the model gets your version:
641​
642```typescript
643import { type ChatMiddleware } from "@tanstack/ai";
644​
645const firstTwentyRows: ChatMiddleware = {
646 name: "first-twenty-rows",
647 onAfterToolCall: (ctx, info) => {
648 if (!info.ok || !Array.isArray(info.result)) return;
649 if (info.result.length <= 20) return;
650 return {
651 type: "replaceResult",
652 result: {
653 rows: info.result.slice(0, 20),
654 omitted: info.result.length - 20,
655 },
656 };
657 },
658};
659```
660​
661| Return | What happens |
662| --- | --- |
663| nothing | The result stays the same. |
664| `{ type: 'replaceResult', result }` | The model gets `result`. The stream sends it in `TOOL_CALL_RESULT`, so the client shows it too. |
665​
666Good to know:
667​
668- Each middleware gets the result of the one before it as `info.result`. The last replacement wins.
669- A failed call stays failed. Your replacement becomes the error that the model reads.
670- A `skip` result from `onBeforeToolCall` goes through this hook too. `info.result` is the parsed skip result, the same value that the model gets.
671- A call that the output limit cut goes through this hook too. It did not run, so `ok` is false, and `error` has the code `max_tokens`. See [When the output limit cuts a tool call](../chat/agentic-cycle#when-the-output-limit-cuts-a-tool-call).
672​
673### Tool hook order in one turn
674​
675When the model calls more than one server tool in one turn, the tools run at the same time:
676​
677- `onBeforeToolCall` runs for each call in call order, before any tool starts.
678- `onAfterToolCall` runs for each tool when it finishes, so in finish order.
679- A call that `onBeforeToolCall` skips gets its `onAfterToolCall` immediately, before the tools start.
680- If the run aborts before the tools start, no tool runs. Each call gets `onAfterToolCall` with `ok: false` and the error "Operation aborted".
681- If `onBeforeToolCall` aborts or throws for a call, the calls before it still run. The error is thrown after they finish.
682​
683With `toolExecution: 'sequential'`, each call finishes its `onBeforeToolCall`, its run, and its `onAfterToolCall` before the next call starts. See [Run tools one at a time](../tools/tools#run-tools-one-at-a-time).
684​
685### onToolPhaseComplete
686​
687`onToolPhaseComplete` runs once after all tool calls of an iteration are processed. Its `info` has:
688​
689- `toolCalls`: the tool calls of the assistant message.
690- `results`: the completed results.
691- `needsApproval`: the calls that wait for user approval.
692- `needsClientExecution`: the calls that the client must run.
693​
694### onUsage
695​
696`onUsage` runs once per model call when the `RUN_FINISHED` chunk has usage data. It gets the usage object.
697​
698```typescript
699import { type ChatMiddleware } from "@tanstack/ai";
700​
701const usageTracker: ChatMiddleware = {
702 name: "usage-tracker",
703 onUsage: (ctx, usage) => {
704 console.log(
705 `Iteration ${ctx.iteration}: ${usage.totalTokens} tokens`
706 );
707 },
708};
709```
710​
711The main `usage` fields:
712​
713| Field | Type | Description |
714| --- | --- | --- |
715| `promptTokens` | `number` | Input tokens |
716| `completionTokens` | `number` | Output tokens |
717| `totalTokens` | `number` | Total tokens |
718| `cost` | `number \| undefined` | The cost that the provider reports, when it reports one |
719​
720The object can also have `promptTokensDetails`, `completionTokensDetails`, `costDetails`, and `providerUsageDetails`.
721​
722### Terminal hooks: onFinish, onAbort, onError
723​
724Exactly **one** terminal hook runs per `chat()` call:
725​
726| Hook | When it runs |
727| --- | --- |
728| `onFinish` | The run completed normally |
729| `onAbort` | The run was aborted: by `ctx.abort()`, by an external `AbortSignal`, or by an `abort` decision from `onBeforeToolCall` |
730| `onError` | An error was not handled |
731​
732`onFinish` also runs when the call pauses for a client tool or an approval. The run is not complete yet. To tell a pause from a completion, look in `onChunk` for a `RUN_FINISHED` chunk with `outcome.type === 'interrupt'`.
733​
734`onAbort` gets `info.cancelRequested`. It is `true` only when an explicit cancel aborted the run, never when the client only disconnected.
735​
736```typescript
737import { type ChatMiddleware } from "@tanstack/ai";
738​
739const terminal: ChatMiddleware = {
740 name: "terminal",
741 onFinish: (ctx, info) => {
742 console.log(`Finished: ${info.finishReason}, ${info.duration}ms`);
743 console.log(`Content: ${info.content}`);
744 if (info.usage) {
745 console.log(`Tokens: ${info.usage.totalTokens}`);
746 }
747 },
748 onAbort: (ctx, info) => {
749 console.log(`Aborted: ${info.reason}, ${info.duration}ms`);
750 },
751 onError: (ctx, info) => {
752 console.error(`Error after ${info.duration}ms:`, info.error);
753 },
754};
755```
756​
757The `info` fields for `onFinish` (`FinishInfo`):
758​
759| Field | Type | Description |
760| --- | --- | --- |
761| `finishReason` | `string \| null` | The last `finishReason` of the agent loop. `null` when no agent-loop iteration sent `RUN_FINISHED` (for example, a `chat({ outputSchema })` run with no tools). |
762| `duration` | `number` | The total run time in milliseconds, including any structured-output call. |
763| `content` | `string` | The text of the agent loop. Includes native-combined structured JSON. Excludes separate-finalization JSON. |
764| `usage` | `TokenUsage \| undefined` | **Optional.** The last `RUN_FINISHED.usage` of the agent loop. **Does not include the tokens of the separate structured-output call.** Always guard with `if (info.usage)` or `info.usage?.`. |
765​
766To count the usage of the whole run, add up the values from `onUsage`. Do not use `info.usage` for that.
767​
768#### Terminal hooks and structured output
769​
770On the **separate-finalization** path, the adapter makes one more provider call after the agent loop:
771​
772- `onStructuredOutputConfig` runs before that call. `ctx.phase` is `'structuredOutput'` for its chunks.
773- `onIteration` does **not** run for that call. It runs only for agent-loop iterations.
774- `onFinish` runs after that call completes. Its `info` shows the end state of the **agent loop**.
775- `info.content` does not have the JSON deltas. Read the result from the `structured-output.complete` CUSTOM event in `onChunk`.
776- `info.usage` is `undefined` for a structured-output run with no tools. Use `onUsage` to get the tokens of the final call. `onUsage` runs for **every** `RUN_FINISHED` with usage.
777​
778On the **native-combined** path, the JSON comes in the normal agent-loop stream:
779​
780- `onStructuredOutputConfig` does not run, and `ctx.phase` stays `'modelStream'`.
781- `onIteration` runs for the iteration that writes the JSON.
782- `info.content` includes the JSON.
783- `onChunk` gets the `structured-output.complete` event in the same phase.
784​
785On both paths, a successful `onFinish` gets the complete canonical transcript in `ctx.messages`:
786​
787- Native-combined output keeps the structured result on its last assistant message.
788- The separate-finalization path can keep the plain-text assistant message of the agent loop, then add a separate structured-output assistant message.
789​
790This transcript is separate from the fields on `info`.
791​
792## Context object
793​
794Each hook gets a `ChatMiddlewareContext` as its first argument. The fields you use most:
795​
796| Field | Type | Description |
797| --- | --- | --- |
798| `requestId` | `string` | A unique ID for this chat request |
799| `streamId` | `string` | A unique ID for this stream |
800| `runId` | `string` | The AG-UI run ID |
801| `threadId` | `string` | The AG-UI thread ID: the `threadId` that you pass to `chat()`. Use it to correlate events. |
802| `parentRunId` | `string \| undefined` | The paused run that this continuation belongs to |
803| `provider`, `model` | `string` | The provider name and the model ID |
804| `phase` | `ChatMiddlewarePhase` | The current lifecycle phase |
805| `iteration` | `number` | The agent-loop iteration (starts at 0) |
806| `chunkIndex` | `number` | How many chunks the run sent so far |
807| `callMetadata` | `Readonly<TanStackMessageMetadata>` | The `metadata.tanstack` of the current model call (`source`, `stopReason`, `responseId`, and more). It changes as chunks arrive. Each assistant message of the call gets a copy. |
808| `messages` | `ReadonlyArray<ModelMessage>` | The current messages (read-only) |
809| `signal` | `AbortSignal \| undefined` | The external abort signal |
810| `abort(reason?)` | `function` | Abort the run from middleware |
811| `retry()` | `function` | Call the model again. Works only in [`onModelError`](#onmodelerror). |
812| `emitCustomEvent(name, value, options?)` | `function` | Push a `CUSTOM` chunk onto the stream now. See [Live custom events](#live-custom-events). |
813| `context` | `TContext` | The runtime context that you pass to `chat()` |
814| `defer(promise)` | `function` | Register a side effect that does not block the stream |
815​
816### Typed runtime context
817​
818`ChatMiddleware` takes a context generic. Middleware that you declare outside `chat()` then reads the same typed runtime context as your tools.
819​
820```typescript
821import { chat, type ChatMiddleware } from "@tanstack/ai";
822import { openaiText } from "@tanstack/ai-openai";
823import { session, audit } from "./server";
824​
825type AppContext = {
826 userId: string;
827 audit: {
828 write(event: { userId: string; requestId: string }): Promise<void>;
829 };
830};
831​
832export const auditMiddleware: ChatMiddleware<AppContext> = {
833 name: "audit",
834 onStart(ctx) {
835 ctx.defer(
836 ctx.context.audit.write({
837 userId: ctx.context.userId,
838 requestId: ctx.requestId,
839 })
840 );
841 },
842};
843​
844chat({
845 adapter: openaiText("gpt-6.1-sol"),
846 messages: [{ role: "user", content: "Hello" }],
847 threadId: "thread-1",
848 middleware: [auditMiddleware],
849 context: {
850 userId: session.user.id,
851 audit,
852 },
853});
854```
855​
856- When typed middleware or typed tools are present, `chat()` checks that `context` has the required shape.
857- Middleware typed as plain `ChatMiddleware` still works. Its `ctx.context` is `unknown`, and it does not require a `context` option.
858- Runtime context is application state in the process. AG-UI `RunAgentInput.context` is a different thing: protocol metadata that `chatParamsFromRequest` parses.
859​
860See [Runtime Context](./runtime-context) for the server, the client, and how to send values from the client to the server.
861​
862### Abort from middleware
863​
864Call `ctx.abort()` to stop the run. The `onAbort` terminal hook then runs:
865​
866```typescript
867import { type ChatMiddleware } from "@tanstack/ai";
868​
869const timeout: ChatMiddleware = {
870 name: "timeout",
871 onChunk: (ctx) => {
872 if (ctx.chunkIndex > 1000) {
873 ctx.abort("Too many chunks");
874 }
875 },
876};
877```
878​
879### Deferred side effects
880​
881Use `ctx.defer()` to register promises that do not block the stream. The engine awaits them after the terminal hook:
882​
883```typescript
884import { type ChatMiddleware } from "@tanstack/ai";
885​
886const analytics: ChatMiddleware = {
887 name: "analytics",
888 onFinish: (ctx, info) => {
889 ctx.defer(
890 fetch("/api/analytics", {
891 method: "POST",
892 body: JSON.stringify({
893 requestId: ctx.requestId,
894 duration: info.duration,
895 tokens: info.usage?.totalTokens,
896 }),
897 })
898 );
899 },
900};
901```
902​
903## Composing multiple middleware
904​
905Middleware runs in array order. The order matters for hooks that pipe or stop early:
906​
907```typescript
908import { chat } from "@tanstack/ai";
909import { openaiText } from "@tanstack/ai-openai";
910import { authMiddleware, loggingMiddleware, cachingMiddleware } from "./middleware";
911​
912const stream = chat({
913 adapter: openaiText("gpt-6.1-sol"),
914 messages: [{ role: "user", content: "Hello" }],
915 threadId: "thread-1",
916 middleware: [authMiddleware, loggingMiddleware, cachingMiddleware],
917});
918```
919​
920### Composition rules
921​
922| Hook | Composition | Effect of the order |
923| --- | --- | --- |
924| `onConfig` | **Piped.** Each gets the output of the one before it. | The earlier middleware changes the config first. |
925| `onStructuredOutputConfig` | **Piped.** Each gets the output of the one before it. | The earlier middleware changes the config first. |
926| `onStart` | Sequential | All run in order. |
927| `onChunk` | **Piped.** Chunks flow through each middleware. | If the first one drops a chunk, the later ones never see it. |
928| `onBeforeToolCall` | **First wins.** The first decision wins. | The earlier middleware has priority. |
929| `onShouldContinue` | **AND.** One `false` stops the loop. | The order changes only which middleware runs first. |
930| `onModelError` | Sequential. If any middleware calls `ctx.retry()` and the call has retries left, the model is called again. | All run in order, so each one sees the error. |
931| `onAfterToolCall` | **Piped.** Each gets the result of the previous `replaceResult`. | The last replacement wins. |
932| `onUsage` | Sequential | All run in order. |
933| `onFinish` / `onAbort` / `onError` | Sequential | All run in order. |
934​
935## Capabilities
936​
937Middleware often needs to **share state**. A provider middleware creates something (a database handle, a counter for the request, a sandbox). A consumer middleware reads it later in the same run.
938​
939Capabilities make this hand-off type-safe and check the order:
940​
941- The consumer declares what it needs.
942- The provider declares what it gives.
943- `chat()` refuses to run if no middleware provides a required capability. It checks at compile time _and_ at runtime.
944​
945### Create a capability
946​
947Create a capability with `createCapability<TValue>()('name')`. It is a **curried** call:
948​
949```typescript
950import { createCapability } from "@tanstack/ai";
951​
952const counterCapability = createCapability<{ value: number }>()("counter");
953const [getCounter, provideCounter] = counterCapability;
954```
955​
956You give the **value type** explicitly (`<{ value: number }>`). TypeScript infers the **name literal** from the argument (`"counter"`). One call cannot do both. If you give `T` explicitly, TypeScript stops inferring the name and makes it `string`. Then the compile-time coverage check, which uses the literal name, does not work.
957​
958The returned `counterCapability` has two roles:
959​
960- It **destructures to `[get, provide]`**, the two accessors that you use in hooks.
961- It **is the identity** that you list in `requires` and `provides`. There is no separate token to import.
962​
963The accessors:
964​
965| Accessor | Behavior |
966| --- | --- |
967| `getCounter(ctx)` | Returns the value. **Throws** if no middleware provided the capability. |
968| `getCounter(ctx, { optional: true })` | Returns `TValue \| undefined`. Does not throw. |
969| `provideCounter(ctx, value)` | Sets the value for this run. Call it from `setup`. |
970​
971The context has the same accessors: `ctx.get(capability)`, `ctx.getOptional(capability)`, and `ctx.provide(capability, value)`. Pass the capability handle. The handle gives the type, so `getCounter(ctx)` and `ctx.get(counterCapability)` do the same thing.
972​
973> [!WARNING]
974> Use a unique capability name across your app. The compile-time check uses the name literal. The runtime check uses the handle reference. Two capabilities with the same name get mixed up in the type check.
975​
976### The `setup` hook
977​
978You provide capabilities in a `setup(ctx)` hook. `setup` **runs first**, before any `onConfig` (init), across all middleware in array order. So every capability is in place when the rest of the run starts.
979​
980- `setup` gets the stable `ChatMiddlewareContext`, not the config.
981- `setup` can be async.
982​
983### `requires`, `provides`, `optionalRequires`
984​
985Three array fields declare the capability contract of a middleware. Each one is a `ReadonlyArray<CapabilityHandle>`. List the capability handles:
986​
987| Field | Meaning |
988| --- | --- |
989| `provides` | Capabilities that this middleware sets up. Each one **must** be provided in `setup`, or `chat()` throws after the setup phase. |
990| `requires` | Capabilities that this middleware reads. `chat()` checks (at compile time and at runtime) that an earlier middleware provides each one. |
991| `optionalRequires` | Capabilities that this middleware uses **if present**. They never cause a validation error. Read them with `getX(ctx, { optional: true })`. |
992​
993### Array example
994​
995Write middleware with `defineChatMiddleware`. It gives exact tuple types to `requires` and `provides`, so the coverage check and the builder can read them. Here a **provider** sets up a counter in `setup`, and a **consumer** reads it in a hook:
996​
997```typescript
998import {
999 chat,
1000 createCapability,
1001 defineChatMiddleware,
1002} from "@tanstack/ai";
1003import { openaiText } from "@tanstack/ai-openai";
1004​
1005const counterCapability = createCapability<{ value: number }>()("counter");
1006const [getCounter, provideCounter] = counterCapability;
1007​
1008// Provider: declares `provides` and sets the value in `setup`.
1009const withCounter = defineChatMiddleware({
1010 name: "with-counter",
1011 provides: [counterCapability],
1012 setup(ctx) {
1013 provideCounter(ctx, { value: 0 });
1014 },
1015});
1016​
1017// Consumer: declares `requires` and reads the value with `get` in a hook.
1018const countsChunks = defineChatMiddleware({
1019 name: "counts-chunks",
1020 requires: [counterCapability],
1021 onChunk(ctx) {
1022 getCounter(ctx).value++;
1023 },
1024 onFinish(ctx) {
1025 console.log(`Saw ${getCounter(ctx).value} chunks`);
1026 },
1027});
1028​
1029const stream = chat({
1030 adapter: openaiText("gpt-6.1-sol"),
1031 messages: [{ role: "user", content: "Hello" }],
1032 threadId: "thread-1",
1033 // The provider must come before the consumer.
1034 middleware: [withCounter, countsChunks],
1035});
1036```
1037​
1038If you remove `withCounter` from the array, TypeScript shows an error at the `middleware` option. The error names the missing `"counter"` capability. At runtime, `chat()` throws before it calls the adapter.
1039​
1040### Builder example
1041​
1042`createChatMiddleware()` builds the array with chained `.use()` calls. It checks the **provider-before-consumer order at compile time**. Each `.use()` requires that earlier `.use()` calls provide the `requires` of the new middleware.
1043​
1044```typescript
1045import {
1046 chat,
1047 createCapability,
1048 createChatMiddleware,
1049 defineChatMiddleware,
1050} from "@tanstack/ai";
1051import { openaiText } from "@tanstack/ai-openai";
1052​
1053const counterCapability = createCapability<{ value: number }>()("counter");
1054const [getCounter, provideCounter] = counterCapability;
1055​
1056const withCounter = defineChatMiddleware({
1057 name: "with-counter",
1058 provides: [counterCapability],
1059 setup(ctx) {
1060 provideCounter(ctx, { value: 0 });
1061 },
1062});
1063​
1064const countsChunks = defineChatMiddleware({
1065 name: "counts-chunks",
1066 requires: [counterCapability],
1067 onChunk(ctx) {
1068 getCounter(ctx).value++;
1069 },
1070});
1071​
1072const middleware = createChatMiddleware()
1073 .use(withCounter) // provides "counter"
1074 .use(countsChunks) // requires "counter", which the line above provides
1075 .build();
1076​
1077const stream = chat({
1078 adapter: openaiText("gpt-6.1-sol"),
1079 messages: [{ role: "user", content: "Hello" }],
1080 threadId: "thread-1",
1081 middleware,
1082});
1083```
1084​
1085If you swap the two `.use()` calls (`.use(countsChunks).use(withCounter)`), the builder rejects the `.use(countsChunks)` line. The consumer comes before its provider, so `"counter"` is not in the provided set yet.
1086​
1087### Validation guarantees
1088​
1089The capability system fails early, with a clear error:
1090​
1091- **Compile-time coverage.** A required capability that no middleware provides is a type error at the `middleware` option. Two checks do this: an **array coverage check** on `middleware: [...]`, and the **`createChatMiddleware()` builder**, which also checks the order.
1092- **Runtime coverage.** If the types are bypassed, `chat()` still checks coverage. It **throws before the adapter runs** when a required capability is missing.
1093- **Check after `setup`.** If a middleware lists a capability in `provides` but does not provide it in `setup`, `chat()` throws after the setup phase.
1094- **Duplicate provide.** If two middleware provide the same capability, the last write wins, and you get a development warning.
1095- **Unique names.** Capability names must be unique across your app. The compile-time check uses the name literal. The runtime check uses the handle reference.
1096​
1097### Append records to the session log
1098​
1099A host is a middleware that keeps a session log and provides `LogRecordsCapability`. `chat()` does not provide it, so without a host there is no log. With a host, your middleware can write its own records to that log. For example, a note that a run started. Read the writer with `getLogRecords`:
1100​
1101```typescript
1102import {
1103 LogRecordsCapability,
1104 defineChatMiddleware,
1105 getLogRecords,
1106} from "@tanstack/ai";
1107​
1108const noteStart = defineChatMiddleware({
1109 name: "note-start",
1110 optionalRequires: [LogRecordsCapability],
1111 async onStart(ctx) {
1112 const log = getLogRecords(ctx, { optional: true });
1113 await log?.append([{ type: "app.note", text: "run started" }]);
1114 },
1115});
1116```
1117​
1118- Each record needs a `type`. The other fields are yours.
1119- The host decides which record types it accepts. If the host refuses a record, `append` rejects.
1120- Without a host log, `getLogRecords(ctx, { optional: true })` returns `undefined`. If your middleware also runs without a log, use the optional read.
1121- If your middleware cannot work without the log, list the capability in `requires` and call `getLogRecords(ctx)`. Then `chat()` throws when no host provides the log.
1122​
1123If you write a host, provide the log in `setup` and list it in `provides`:
1124​
1125```typescript
1126import {
1127 LogRecordsCapability,
1128 defineChatMiddleware,
1129 provideLogRecords,
1130} from "@tanstack/ai";
1131​
1132const withSessionLog = defineChatMiddleware({
1133 name: "with-session-log",
1134 provides: [LogRecordsCapability],
1135 setup(ctx) {
1136 // One log per run. A real host writes to its durable store here.
1137 const records: Array<{ type: string }> = [];
1138 provideLogRecords(ctx, {
1139 append: async (batch) => {
1140 records.push(...batch);
1141 },
1142 });
1143 },
1144});
1145```
1146​
1147## Recipes
1148​
1149### Live custom events
1150​
1151A long `onConfig` hook can send progress to the client while it waits. Call `ctx.emitCustomEvent` when the work starts, then again when it finishes:
1152​
1153```typescript
1154import { type ChatMiddleware } from "@tanstack/ai";
1155​
1156async function prepare() {
1157 await new Promise<void>((resolve) => {
1158 setTimeout(resolve, 1);
1159 });
1161​
1162const progress: ChatMiddleware = {
1163 name: "progress",
1164 async onConfig(ctx) {
1165 if (ctx.phase !== "beforeModel") return;
1166 ctx.emitCustomEvent("job:started", { step: "prepare" });
1167 await prepare();
1168 ctx.emitCustomEvent("job:ended", { step: "prepare" });
1169 },
1171```
1172​
1173- The engine sends each `CUSTOM` chunk as soon as you call `emitCustomEvent`, also while the hook still runs.
1174- If `RUN_STARTED` is not on the wire yet, the engine sends it first.
1175- Durability flushes the event immediately, so the client can show a live indicator. Pass `{ batch: true }` to keep it in the durability batch.
1176​
1177Read these events on the client the same way as `emitCustomEvent` calls from tools. See [Custom Events](../protocol/custom-events).
1178​
1179### Rate limiting
1180​
1181Limit the number of tool calls per request:
1182​
1183```typescript
1184import { type ChatMiddleware } from "@tanstack/ai";
1185​
1186function rateLimitMiddleware(maxCalls: number): ChatMiddleware {
1187 let toolCallCount = 0;
1188 return {
1189 name: "rate-limit",
1190 onBeforeToolCall: (ctx, hookCtx) => {
1191 toolCallCount++;
1192 if (toolCallCount > maxCalls) {
1193 return {
1194 type: "abort",
1195 reason: `Rate limit: exceeded ${maxCalls} tool calls`,
1196 };
1198 },
1199 };
1201```
1202​
1203The counter lives in the middleware object. Call `rateLimitMiddleware()` in the request handler, so each request gets its own counter.
1204​
1205### Audit trail
1206​
1207Log each action for compliance:
1208​
1209```typescript
1210import { type ChatMiddleware } from "@tanstack/ai";
1211import { db } from "./db";
1212​
1213const auditTrail: ChatMiddleware = {
1214 name: "audit-trail",
1215 onStart: (ctx) => {
1216 ctx.defer(
1217 db.auditLog.create({
1218 requestId: ctx.requestId,
1219 event: "chat_started",
1220 timestamp: Date.now(),
1221 })
1222 );
1223 },
1224 onAfterToolCall: (ctx, info) => {
1225 ctx.defer(
1226 db.auditLog.create({
1227 requestId: ctx.requestId,
1228 event: "tool_executed",
1229 toolName: info.toolName,
1230 success: info.ok,
1231 duration: info.duration,
1232 timestamp: Date.now(),
1233 })
1234 );
1235 },
1236 onFinish: (ctx, info) => {
1237 ctx.defer(
1238 db.auditLog.create({
1239 requestId: ctx.requestId,
1240 event: "chat_finished",
1241 duration: info.duration,
1242 tokens: info.usage?.totalTokens,
1243 timestamp: Date.now(),
1244 })
1245 );
1246 },
1248```
1249​
1250### Different tools per iteration
1251​
1252Give the model different tools at different steps of the agent loop:
1253​
1254```typescript
1255import { type ChatMiddleware } from "@tanstack/ai";
1256​
1257const toolSwapper: ChatMiddleware = {
1258 name: "tool-swapper",
1259 onConfig: (ctx, config) => {
1260 if (ctx.phase !== "beforeModel") return;
1261​
1262 if (ctx.iteration === 0) {
1263 // First iteration: only allow search
1264 return {
1265 tools: config.tools.filter((t) => t.name === "search"),
1266 };
1268 // Later iterations: allow all tools
1269 },
1271```
1272​
1273### Content filtering
1274​
1275Drop or change chunks before they reach the consumer:
1276​
1277```typescript ignore
1278import { type ChatMiddleware } from "@tanstack/ai";
1279import { containsProfanity } from "./filters";
1280​
1281const contentFilter: ChatMiddleware = {
1282 name: "content-filter",
1283 onChunk: (ctx, chunk) => {
1284 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
1285 if (containsProfanity(chunk.delta)) {
1286 // Drop the chunk
1287 return null;
1290 },
1292```
1293​
1294For a ready-made version, see [`contentGuardMiddleware`](./built-in-middleware#contentguardmiddleware).
1295​
1296### Alert on errors
1297​
1298```typescript
1299import { type ChatMiddleware } from "@tanstack/ai";
1300import { alertService } from "./services";
1301​
1302const errorAlerts: ChatMiddleware = {
1303 name: "error-alerts",
1304 onError: (ctx, info) => {
1305 ctx.defer(
1306 alertService.send({
1307 level: "error",
1308 message: `Chat ${ctx.requestId} failed after ${info.duration}ms`,
1309 error: String(info.error),
1310 })
1311 );
1312 },
1314```
1315​
1316## TypeScript types
1317​
1318The core middleware types come from `@tanstack/ai`:
1319​
1320```typescript
1321import type {
1322 ChatMiddleware,
1323 ChatMiddlewareContext,
1324 ChatMiddlewarePhase,
1325 ChatMiddlewareConfig,
1326 StructuredOutputMiddlewareConfig,
1327 ToolCallHookContext,
1328 BeforeToolCallDecision,
1329 AfterToolCallInfo,
1330 AfterToolCallDecision,
1331 IterationInfo,
1332 ToolPhaseCompleteInfo,
1333 UsageInfo,
1334 FinishInfo,
1335 AbortInfo,
1336 ErrorInfo,
1337} from "@tanstack/ai";
1338```
1339​
1340The option types of the [built-in middleware](./built-in-middleware) come from the `@tanstack/ai/middlewares` subpath:
1341​
1342```typescript
1343import type {
1344 ToolCacheMiddlewareOptions,
1345 ToolCacheStorage,
1346 ToolCacheEntry,
1347 ContentGuardMiddlewareOptions,
1348 ContentGuardRule,
1349 ContentFilteredInfo,
1350} from "@tanstack/ai/middlewares";
1351```