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

middleware.md

1,193 lines48.9 KB

1---
2title: Middleware
3id: middleware
4order: 1
5description: "Hook into every stage of TanStack AI's chat() lifecycle with middleware — logging, analytics, stream transforms, tool interception, and side effects."
6keywords:
7 - tanstack ai
8 - middleware
9 - chat middleware
10 - lifecycle hooks
11 - observability
12 - logging
13 - tool interception
14 - stream transform
15---
16​
17Middleware lets you hook into every stage of the `chat()` lifecycle — from configuration to streaming, tool execution, usage tracking, and completion. You can observe, transform, or short-circuit behavior at each stage without modifying your adapter or tool implementations.
18​
19Common use cases include:
20​
21- **Logging and observability** — track token usage, tool execution timing, errors
22- **Configuration transforms** — inject system prompts, adjust temperature per iteration, filter tools
23- **Stream processing** — redact sensitive content, transform chunks, drop unwanted events
24- **Tool call interception** — validate arguments, cache results, abort on dangerous calls
25- **Side effects** — send analytics, update databases, trigger notifications
26​
27## Quick Start
28​
29Pass an array of middleware to the `chat()` function:
30​
31```typescript
32import { chat, type ChatMiddleware } from "@tanstack/ai";
33import { openaiText } from "@tanstack/ai-openai";
34​
35const logger: ChatMiddleware = {
36 name: "logger",
37 onStart: (ctx) => {
38 console.log(`[${ctx.requestId}] Chat started`);
39 },
40 onFinish: (ctx, info) => {
41 console.log(`[${ctx.requestId}] Finished in ${info.duration}ms`);
42 },
43};
44​
45const stream = chat({
46 adapter: openaiText("gpt-5.5"),
47 messages: [{ role: "user", content: "Hello" }],
48 middleware: [logger],
49});
50```
51​
52> **Just want to see chunks flowing through your middleware during development?**
53> Use `debug: { middleware: true }` on your `chat()` call — no custom middleware required. See [Debug Logging](./debug-logging).
54​
55## Lifecycle Overview
56​
57Every `chat()` invocation follows a predictable lifecycle. Middleware hooks fire at specific phases:
58​
59```mermaid
60graph TD
61 A["chat() called"] --> B["onConfig (phase: init)"]
62 B --> C[onStart]
63 C --> D["onConfig (phase: beforeModel)"]
64 D --> E["Adapter streams response"]
65 E --> F["onChunk (for each chunk)"]
66 F --> G{Tool calls?}
67 G -->|No| H[onUsage]
68 G -->|Yes| I[onBeforeToolCall]
69 I --> J[Tool executes]
70 J --> K[onAfterToolCall]
71 K --> L{Continue loop?}
72 L -->|Yes| D
73 L -->|No| H
74 H --> SO{"Structured output path?"}
75 SO -->|None| M{Outcome}
76 SO -->|"Native combined"| SOH["Post-loop structured-output harvest (onChunk)"]
77 SOH --> M
78 SO -->|"Separate finalization"| SOC[onStructuredOutputConfig]
79 SOC --> SOM["onConfig (phase: structuredOutput)"]
80 SOM --> SOS["Structured-output finalization (onChunk, onUsage)"]
81 SOS --> M
82 M -->|Success| N[onFinish]
83 M -->|Abort| O[onAbort]
84 M -->|Error| P[onError]
85​
86 style I fill:#e1f5ff
87 style J fill:#ffe1e1
88 style SOC fill:#e1f5ff
89 style SOM fill:#e1f5ff
90 style SOS fill:#e1f5ff
91 style SOH fill:#e1f5ff
92 style N fill:#e1ffe1
93 style O fill:#fff4e1
94 style P fill:#ffe1e1
95```
96​
97### Phase Transitions
98​
99The context's `phase` field tracks where you are in the lifecycle:
100​
101| Phase | When | Hooks Called |
102|-------|------|-------------|
103| `init` | Once at startup | `onConfig` |
104| `beforeModel` | Before each model call (per iteration) | `onConfig` |
105| `modelStream` | While adapter streams chunks | `onChunk`, `onUsage` |
106| `beforeTools` | Before tool execution | `onBeforeToolCall` |
107| `afterTools` | After tool execution | `onAfterToolCall` |
108| `structuredOutput` | During the final structured-output adapter call (when `outputSchema` is set **and** `supportsCombinedToolsAndSchema()` does not return `true` for the current model/options). Chunks from `adapter.structuredOutputStream` (or the synthesized non-streaming fallback) flow through `onChunk` with this phase, and `onUsage` fires for the final call's tokens. **Does not fire** for adapters that natively combine tools + schema in one streaming call (modern OpenAI Chat Completions, OpenAI Responses, Claude 4.5+, Gemini 3.x, Grok 4.x family, and OpenRouter when every routed model is in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`; see issue #605). On that path middleware observes the run through `beforeModel` / `modelStream` as usual. | `onStructuredOutputConfig`, `onConfig`, `onChunk`, `onUsage` |
109​
110## Hooks Reference
111​
112### onConfig
113​
114Called once during `init` (startup) and once per iteration during `beforeModel` (before each model call). On the separate-finalization path, `onConfig` additionally re-fires at the structured-output boundary with `ctx.phase === 'structuredOutput'`, receiving the post-`onStructuredOutputConfig` view of the config. A single-iteration separate-finalization run therefore fires `onConfig` three times (`init` + `beforeModel` + `structuredOutput`). Native-combined output does not add this third call. Use `onConfig` to transform the configuration that the model receives.
115​
116Return a **partial** config object with only the fields you want to change — they are shallow-merged with the current config automatically. No need to spread the existing config.
117​
118```typescript
119import { type ChatMiddleware } from "@tanstack/ai";
120​
121const dynamicTemperature: ChatMiddleware = {
122 name: "dynamic-temperature",
123 onConfig: (ctx, config) => {
124 if (ctx.phase === "init") {
125 // Add a system prompt at startup — only systemPrompts is overwritten
126 return {
127 systemPrompts: [
128 ...config.systemPrompts,
129 "You are a helpful assistant.",
130 ],
131 };
132 }
133​
134 if (ctx.phase === "beforeModel" && ctx.iteration > 0) {
135 // Increase temperature on retries. Sampling params live in the
136 // provider-native modelOptions object — `temperature` is universal,
137 // so it's the same key across providers. Spread the existing
138 // modelOptions so other model options stay unchanged.
139 const current =
140 typeof config.modelOptions?.temperature === "number"
141 ? config.modelOptions.temperature
142 : 0.7;
143 return {
144 modelOptions: {
145 ...config.modelOptions,
146 temperature: Math.min(current + 0.1, 1.0),
147 },
148 };
149 }
150 },
151};
152```
153​
154> Sampling parameters (`temperature`, `top_p` / `topP`, the various `max*Tokens` keys) live inside `modelOptions` under each provider's native name — they are no longer root config fields. `temperature` happens to be spelled the same across every provider, so the example above is provider-agnostic; if you mutate a token limit instead, use the provider-native key (e.g. `max_output_tokens` for OpenAI, `num_predict` nested under `modelOptions.options` for Ollama). See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
155​
156**Config fields you can transform:**
157​
158| Field | Type | Description |
159|-------|------|-------------|
160| `messages` | `ModelMessage[]` | Canonical conversation history. Persistence and `ctx.messages` use this field. |
161| `providerMessages` | `ModelMessage[]` | Temporary context sent to the provider. Defaults to `messages`. |
162| `systemPrompts` | `string[]` | System prompts |
163| `tools` | `Tool[]` | Available tools |
164| `metadata` | `Record<string, unknown>` | Request metadata |
165| `modelOptions` | `Record<string, unknown>` | Provider-native options — this is where sampling params (`temperature`, `top_p` / `topP`, the provider's `max*Tokens` key) now live, alongside every other model-specific knob. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). |
166​
167When multiple middleware define `onConfig`, the config is **piped** through them in order — each receives the merged config from the previous middleware.
168​
169Return `providerMessages` when a transform must affect only the model call. For
170compatibility, returning `messages` also updates provider input unless the same
171result sets `providerMessages` explicitly.
172​
173### onStructuredOutputConfig
174​
175Called once at the start of the final structured-output adapter call — only when `chat()` was invoked with `outputSchema` **and** `supportsCombinedToolsAndSchema()` does not return `true` for the current model/options. Pipes through middleware in order, like `onConfig`, but with access to the **JSON Schema** being sent to the provider. Use this hook when you need to transform the schema (e.g., inject `$defs`, strip vendor-incompatible keywords) or apply structured-output-specific behavior (e.g., suppress system prompts on the final call).
176​
177> Native-combined adapters (modern OpenAI, Claude 4.5+, Gemini 3.x, Grok 4.x — see issue #605) skip the separate finalization call and never invoke this hook. The engine passes the converted schema directly to `chatStream` after `onConfig` runs, so middleware cannot transform the native-combined schema.
178​
179Return a **partial** `StructuredOutputMiddlewareConfig` with only the fields you want to change — they are shallow-merged with the current config. Return `void` to pass through.
180​
181```typescript
182import { type ChatMiddleware } from "@tanstack/ai";
183import { sharedDefs } from "./defs";
184​
185const injectDefs: ChatMiddleware = {
186 name: "inject-defs",
187 onStructuredOutputConfig: (_ctx, config) => {
188 // `config.outputSchema` is the JSON Schema being sent to the provider
189 return {
190 outputSchema: {
191 ...config.outputSchema,
192 $defs: { ...sharedDefs },
193 },
194 };
195 },
196};
197```
198​
199**Config fields you can transform:**
200​
201| Field | Type | Description |
202|-------|------|-------------|
203| `messages` | `ModelMessage[]` | Canonical conversation history |
204| `providerMessages` | `ModelMessage[]` | Temporary context sent to the final call |
205| `systemPrompts` | `SystemPrompt[]` | System prompts on the final call |
206| `metadata` | `Record<string, unknown>` | Request metadata |
207| `modelOptions` | `Record<string, unknown>` | Provider-native options — this is where sampling params (`temperature`, `top_p` / `topP`, the provider's `max*Tokens` key) now live, alongside every other model-specific knob. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). |
208| `outputSchema` | `JSONSchema` | JSON Schema being sent to the provider for structured output |
209​
210**Ordering at the structured-output boundary:**
211​
2121. `onStructuredOutputConfig` fires first, piping through every middleware in array order.
2132. `onConfig` then re-fires at the same boundary with `ctx.phase === 'structuredOutput'`, receiving the post-`onStructuredOutputConfig` view of the config (minus `outputSchema`). Use `onConfig` for general-purpose transforms that apply to every adapter call; use `onStructuredOutputConfig` when you need access to the schema.
214​
215When multiple middleware define `onStructuredOutputConfig`, the config is **piped** through them in order — each receives the merged config from the previous middleware.
216​
217### onStart
218​
219Called once after the initial `onConfig` completes. Use it for setup tasks like initializing timers or logging.
220​
221```typescript
222import { type ChatMiddleware } from "@tanstack/ai";
223​
224const timer: ChatMiddleware = {
225 name: "timer",
226 onStart: (ctx) => {
227 console.log(`Request ${ctx.requestId} started at iteration ${ctx.iteration}`);
228 },
229};
230```
231​
232### onChunk
233​
234Called for every chunk streamed from the adapter. You can observe, transform, expand, or drop chunks.
235​
236```typescript ignore
237import { type ChatMiddleware } from "@tanstack/ai";
238​
239const redactor: ChatMiddleware = {
240 name: "redactor",
241 onChunk: (ctx, chunk) => {
242 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
243 // Transform: redact sensitive content
244 return {
245 ...chunk,
246 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
247 };
248 }
249 // Return void to pass through unchanged
250 },
251};
252```
253​
254**Return values:**
255​
256| Return | Effect |
257|--------|--------|
258| `void` / `undefined` | Chunk passes through unchanged |
259| `StreamChunk` | Replaces the original chunk |
260| `StreamChunk[]` | Expands into multiple chunks |
261| `null` | Drops the chunk entirely |
262​
263When multiple middleware define `onChunk`, chunks flow through them in order. If one middleware drops a chunk (returns `null`), subsequent middleware never see it.
264​
265#### Chunk types you'll see
266​
267`onChunk` receives every [AG-UI event](https://docs.ag-ui.com/introduction) the run produces — not just text. Narrow on `chunk.type` (a discriminated union) before reading type-specific fields. The common ones:
268​
269| `chunk.type` | Meaning | Key fields |
270|--------------|---------|-----------|
271| `RUN_STARTED` / `RUN_FINISHED` / `RUN_ERROR` | Run lifecycle boundaries | `runId`, `finishReason`, `usage` (on finish), `message` (on error) |
272| `TEXT_MESSAGE_START` / `TEXT_MESSAGE_CONTENT` / `TEXT_MESSAGE_END` | Assistant text streaming | `messageId`, `delta` (content) |
273| `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END` | Tool invocation streaming | `toolCallId`, `toolCallName`, `delta` (args), result on end |
274| `STEP_STARTED` / `STEP_FINISHED` | Thinking / reasoning steps | `delta`, `signature` |
275| `STATE_SNAPSHOT` / `STATE_DELTA` | Agent state sync | `snapshot`, `delta` |
276| `CUSTOM` | Extensibility events (incl. structured-output — see below) | `name`, `value` |
277​
278See the [AG-UI protocol docs](https://docs.ag-ui.com/introduction) for the full event catalogue and exact field shapes.
279​
280#### Transforming structured-output chunks
281​
282There is **no separate `onStructuredOutputChunk` hook** — and you don't need one. When `chat()` is invoked with `outputSchema`, the structured-output chunks (the JSON `TEXT_MESSAGE_CONTENT` deltas, plus the `structured-output.start` / `structured-output.complete` CUSTOM events and any finalization `RUN_ERROR`) flow through the **same `onChunk` hook** as everything else. You transform, expand, or drop them exactly like any other chunk.
283​
284How you distinguish them depends on which finalization path the adapter takes:
285​
286- **Separate-finalization adapters** (`supportsCombinedToolsAndSchema()` does not return `true` for the current model/options): `ctx.phase === 'structuredOutput'` during the finalization call. Discriminate on the phase.
287- **Native-combined adapters** (modern OpenAI Chat Completions / Responses, Claude 4.5+, Gemini 3.x, Grok 4.x — see issue #605): the schema-constrained JSON is produced on the model's natural final turn, so **`ctx.phase` stays `'modelStream'`** — the `'structuredOutput'` phase never fires. Discriminate on the CUSTOM event name (`structured-output.start` / `structured-output.complete`) instead.
288​
289```typescript ignore
290import { type ChatMiddleware } from "@tanstack/ai";
291​
292const redactStructuredOutput: ChatMiddleware = {
293 name: "redact-structured-output",
294 onChunk: (ctx, chunk) => {
295 // Separate-finalization path: the JSON streams as TEXT_MESSAGE_CONTENT
296 // during the 'structuredOutput' phase. Transform the delta like any
297 // other text chunk — here, redact anything that looks like an SSN before
298 // it reaches the client.
299 if (
300 ctx.phase === "structuredOutput" &&
301 chunk.type === "TEXT_MESSAGE_CONTENT"
302 ) {
303 return {
304 ...chunk,
305 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
306 };
307 }
308​
309 // Both paths: the completed typed payload arrives as a CUSTOM
310 // `structured-output.complete` event. On the native-combined path this is
311 // your only signal (ctx.phase never flips to 'structuredOutput'), so key
312 // off the event name, not the phase. `chunk.value` carries { object, raw }.
313 if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
314 console.log("final structured output:", chunk.value);
315 }
316​
317 // Return void to pass everything else through unchanged.
318 },
319};
320```
321​
322> Why is there `onStructuredOutputConfig` but no `onStructuredOutputChunk`? Because the **config** shape genuinely differs at the structured-output boundary — it carries an `outputSchema` field that plain `ChatMiddlewareConfig` doesn't (see [onStructuredOutputConfig](#onstructuredoutputconfig)). **Chunks** are all just `StreamChunk` regardless of phase, so one `onChunk` plus `ctx.phase` (or the CUSTOM event name) covers every case — a parallel chunk hook would be redundant.
323​
324### onShouldContinue
325​
326Called when the engine is deciding whether to start another agent-loop iteration (after a tool phase or between model turns). Combined with AND semantics across middleware **and** with `agentLoopStrategy` — any explicit `false` stops the loop. Return `true`, `void`, or `undefined` to allow continuation.
327​
328Does **not** abort the run: the stream finishes normally with the current messages. Use `ctx.abort()` only for a hard abort.
329​
330```typescript
331import { type ChatMiddleware } from "@tanstack/ai";
332​
333const budget: ChatMiddleware = {
334 name: "tool-budget",
335 onShouldContinue: (_ctx, state) => {
336 // Stop further turns once 20 tool calls have been emitted
337 if (state.toolCallCount >= 20) return false;
338 },
339};
340```
341​
342For a full per-turn + cumulative tool budget recipe, see [Tool-call budgets](../chat/agentic-cycle#tool-call-budgets-middleware-recipe).
343​
344### onInterruptBoundary and onInterruptResolution
345​
346Use these hooks when middleware needs data from the client. Define the request
347with `defineInterrupt()` and register it with `chat({ interrupts })` and
348`useChat({ interrupts })`. Do not emit raw AG-UI events from middleware.
349​
350`onInterruptBoundary` runs at four points in an agent iteration:
351​
352- `beforeModel`, before the adapter starts.
353- `afterModel`, after the model response is complete.
354- `beforeTools`, before tool execution starts.
355- `afterTools`, after the tool phase is complete.
356​
357Each middleware can return requests from one boundary. The engine combines all
358requests from that boundary into one AG-UI interrupt batch. The batch ends the
359run with one interrupt outcome.
360​
361This hook cannot change config. Its only legal return is `{ interrupts }` or
362nothing. The continuation is a new `chat()` call, so the hook runs again. Skip
363the emit when `ctx.parentRunId` is set if this pause belongs to the original
364request only.
365​
366What is in `ctx` at each phase, and when to use each phase, is in
367[Lifecycle Boundaries](../interrupts/boundaries).
368​
369Create one shared definition. Both the server and the client import this value,
370so the definition ID and response shape stay the same on both sides.
371​
372```typescript title="review-plan.ts"
373import { defineInterrupt, type ChatMiddleware } from '@tanstack/ai'
374import { z } from 'zod'
375​
376export const reviewPlan = defineInterrupt({
377 id: 'review-plan',
378 payloadSchema: z.object({ title: z.string() }),
379 responseSchema: z.object({ approved: z.boolean() }),
380})
381​
382export const reviewMiddleware: ChatMiddleware<unknown, typeof reviewPlan> = {
383 name: 'review-plan',
384 onInterruptBoundary(ctx) {
385 if (ctx.phase !== 'beforeTools') return
386 if (ctx.parentRunId) return
387 return {
388 interrupts: [
389 reviewPlan.interrupt({
390 key: 'release-plan',
391 reason: 'review-required',
392 message: 'Approve this plan?',
393 payload: { title: 'Release plan' },
394 }),
395 ],
396 }
397 },
398 onInterruptResolution(_ctx, resumedInterrupts) {
399 for (const result of resumedInterrupts.for(reviewPlan)) {
400 if (result.status === 'resolved' && !result.response.approved) {
401 return { toolResume: 'stop' }
402 }
403 }
404 },
406```
407​
408Register the definition on the server. Forward `parentRunId` and `resume` so
409a client resolution starts the continuation with its full context.
410​
411```typescript title="route.ts"
412import {
413 chat,
414 chatParamsFromRequestBody,
415 toServerSentEventsResponse,
416} from '@tanstack/ai'
417import { openaiText } from '@tanstack/ai-openai'
418import { reviewMiddleware, reviewPlan } from './review-plan'
419​
420export async function POST(request: Request) {
421 const params = await chatParamsFromRequestBody(await request.json())
422 const stream = chat({
423 adapter: openaiText('gpt-5.5'),
424 messages: params.messages,
425 threadId: params.threadId,
426 runId: params.runId,
427 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
428 ...(params.resume ? { resume: params.resume } : {}),
429 interrupts: [reviewPlan],
430 middleware: [reviewMiddleware],
431 })
432​
433 return toServerSentEventsResponse(stream)
435```
436​
437Register the same definition on the client. Check `kind` and `definitionId`.
438TypeScript then treats the item as `GenericInterrupt<typeof reviewPlan>`.
439`resolveInterrupt` uses the response shape from `reviewPlan.responseSchema`.
440​
441```tsx title="review-plan-panel.tsx"
442import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
443import type { GenericInterrupt } from '@tanstack/ai-react'
444import { reviewPlan } from './review-plan'
445​
446function ReviewCard({
447 interrupt,
448}: {
449 interrupt: GenericInterrupt<typeof reviewPlan>
450}) {
451 return (
452 <button
453 onClick={() => interrupt.resolveInterrupt({ approved: true })}
454 >
455 Approve plan
456 </button>
457 )
459​
460export function ReviewPlanPanel() {
461 const { interrupts, sendMessage } = useChat({
462 connection: fetchServerSentEvents('/api/chat'),
463 interrupts: [reviewPlan],
464 })
465​
466 return (
467 <>
468 <button onClick={() => sendMessage('Review the release plan')}>
469 Start review
470 </button>
471 {interrupts.map((interrupt) => {
472 if (interrupt.kind !== 'generic') return null
473 if (!('definitionId' in interrupt)) return null
474 if (interrupt.definitionId !== reviewPlan.id) return null
475 return <ReviewCard key={interrupt.id} interrupt={interrupt} />
476 })}
477 </>
478 )
480```
481​
482`onInterruptResolution` does not run in the `chat()` call that paused. It
483runs once at the start of the next `chat()` call, after the client answers.
484​
485```
486setup
487onConfig (phase is init)
488onInterruptResolution (phase is still init)
489onStart
490then stop, or continue the agent loop
491```
492​
493`useChat` sends `parentRunId` and `resume` on that second request. Each
494generic resume item includes the original request in `metadata`. If `resume`
495is present and `parentRunId` is missing, the server throws.
496​
497Use `resumedInterrupts.for(definition)` for one typed definition. Use
498`resumedInterrupts.all()` for every registered definition. Use
499`resumedInterrupts.all(definitionA, definitionB)` to read a typed subset.
500​
501The hook can return `toolResume: 'continue'`, `'cancel'`, or `'stop'`. Results
502from all middleware combine by the most restrictive rule: `stop` wins over
503`cancel`, and `cancel` wins over `continue`.
504​
505This hook cannot change prompts, tools, or messages. Store the answer on a
506capability, then return those fields from `onConfig` when
507`ctx.phase === 'beforeModel'`.
508​
509| Hook | Can change |
510| --- | --- |
511| `onInterruptBoundary` | Nothing. It can only pause. |
512| `onInterruptResolution` | Pending-tool policy (`toolResume`) |
513| `onConfig` | `messages`, `systemPrompts`, `tools`, `modelOptions`, `metadata` |
514​
515The full resume order, plus an example that writes a user note into the
516system prompt, is in [Apply Answers](../interrupts/apply-answers).
517​
518### onBeforeToolCall
519​
520Called before each tool executes. The first middleware that returns a non-void decision short-circuits — remaining middleware are skipped for that tool call.
521​
522```typescript
523import { type ChatMiddleware } from "@tanstack/ai";
524​
525function isRecord(v: unknown): v is Record<string, unknown> {
526 return typeof v === "object" && v !== null;
528​
529const guard: ChatMiddleware = {
530 name: "guard",
531 onBeforeToolCall: (ctx, hookCtx) => {
532 // Block dangerous tools
533 if (hookCtx.toolName === "deleteDatabase") {
534 return { type: "abort", reason: "Dangerous operation blocked" };
535 }
536​
537 // Validate and transform arguments
538 if (hookCtx.toolName === "search" && isRecord(hookCtx.args) && !hookCtx.args.limit) {
539 return {
540 type: "transformArgs",
541 args: { ...hookCtx.args, limit: 10 },
542 };
543 }
544 },
545};
546```
547​
548**Decision types:**
549​
550| Decision | Effect |
551|----------|--------|
552| `void` / `undefined` | Continue normally, next middleware can decide |
553| `{ type: 'transformArgs', args }` | Replace tool arguments before execution |
554| `{ type: 'skip', result }` | Skip execution entirely, use provided result |
555| `{ type: 'abort', reason? }` | Abort the entire chat run |
556​
557The `hookCtx` provides:
558​
559| Field | Type | Description |
560|-------|------|-------------|
561| `toolCall` | `ToolCall` | Raw tool call object |
562| `tool` | `Tool \| undefined` | Resolved tool definition |
563| `args` | `unknown` | Parsed arguments |
564| `toolName` | `string` | Tool name |
565| `toolCallId` | `string` | Tool call ID |
566​
567### onAfterToolCall
568​
569Called after each tool execution (or skip). All middleware run — there is no short-circuiting.
570​
571```typescript
572import { type ChatMiddleware } from "@tanstack/ai";
573​
574const toolLogger: ChatMiddleware = {
575 name: "tool-logger",
576 onAfterToolCall: (ctx, info) => {
577 if (info.ok) {
578 console.log(`${info.toolName} completed in ${info.duration}ms`);
579 } else {
580 console.error(`${info.toolName} failed:`, info.error);
581 }
582 },
583};
584```
585​
586The `info` object provides:
587​
588| Field | Type | Description |
589|-------|------|-------------|
590| `toolCall` | `ToolCall` | Raw tool call object |
591| `tool` | `Tool \| undefined` | Resolved tool definition |
592| `toolName` | `string` | Tool name |
593| `toolCallId` | `string` | Tool call ID |
594| `ok` | `boolean` | Whether execution succeeded |
595| `duration` | `number` | Execution time in milliseconds |
596| `result` | `unknown` | Result (when `ok` is true) |
597| `error` | `unknown` | Error (when `ok` is false) |
598​
599### Tool hook order in one turn
600​
601When the model calls several server tools in one turn, the tools run at the same time:
602​
603- `onBeforeToolCall` runs for each call in call order, before any tool starts.
604- `onAfterToolCall` runs for each tool when it finishes, so in finish order.
605- A call that `onBeforeToolCall` skips gets its `onAfterToolCall` right away, before the tools start.
606- If the run aborts before the tools start, no tool runs. Each call gets `onAfterToolCall` with `ok: false` and the error "Operation aborted".
607- If `onBeforeToolCall` aborts or throws for a call, the calls before it still run. The error is thrown after they finish.
608​
609With `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).
610​
611### onUsage
612​
613Called once per model iteration when the `RUN_FINISHED` chunk includes usage data. Receives the usage object directly.
614​
615```typescript
616import { type ChatMiddleware } from "@tanstack/ai";
617​
618const usageTracker: ChatMiddleware = {
619 name: "usage-tracker",
620 onUsage: (ctx, usage) => {
621 console.log(
622 `Iteration ${ctx.iteration}: ${usage.totalTokens} tokens`
623 );
624 },
625};
626```
627​
628The `usage` object:
629​
630| Field | Type | Description |
631|-------|------|-------------|
632| `promptTokens` | `number` | Input tokens |
633| `completionTokens` | `number` | Output tokens |
634| `totalTokens` | `number` | Total tokens |
635​
636### Terminal Hooks: onFinish, onAbort, onError
637​
638Exactly **one** terminal hook fires per `chat()` invocation. They are mutually exclusive:
639​
640| Hook | When it fires |
641|------|--------------|
642| `onFinish` | Run completed normally |
643| `onAbort` | Run was aborted (via `ctx.abort()`, an external `AbortSignal`, or a `{ type: 'abort' }` decision from `onBeforeToolCall`) |
644| `onError` | An unhandled error occurred |
645​
646`onFinish` also fires when the invocation pauses at a client-tool or approval wait. 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'`.
647​
648> **Separate-finalization path:** Adapters without native-combined support make a separate structured-output provider call after the agent loop.
650> - `onStructuredOutputConfig` fires before the separate provider call, and `ctx.phase` is `'structuredOutput'` for its chunks.
651> - `onIteration` does **not** fire for finalization; it only fires for agent-loop iterations.
652> - `onFinish` fires after finalization completes. Its `info` object reflects the **agent loop's** terminal state.
653> - `info.content` — the agent loop's accumulated text. Separate-finalization JSON deltas are **not** included. Middleware can observe the completed result through the `structured-output.complete` CUSTOM event in `onChunk`.
654> - `info.usage` — the agent loop's last `RUN_FINISHED.usage`. For a tools-less structured-output run (no agent-loop iteration produces `RUN_FINISHED`), this is `undefined`. To capture finalization tokens, use `onUsage` — that hook fires for **every** `RUN_FINISHED` carrying usage, including the finalization call.
655> - `info.finishReason` — the agent loop's last `finishReason`. `null` when no agent-loop iteration produced `RUN_FINISHED` (e.g. a tools-less structured-output run).
656> - `info.duration` — wall-clock duration of the entire `chat()` invocation, including finalization.
658> **Native-combined output:** Adapters with native-combined support produce the schema-constrained JSON in the regular agent-loop stream. `onStructuredOutputConfig` does not fire, `ctx.phase` remains `'modelStream'`, and `onIteration` fires for the iteration that produces the JSON. The JSON is agent-loop text, so `info.content` includes it. Middleware observes the `structured-output.complete` event in `onChunk` during the same phase.
660> On successful completion in either path, `onFinish` receives the complete canonical transcript in `ctx.messages`. Native-combined output keeps the structured result on its terminal assistant message. The separate-finalization path can preserve the agent loop's plain-text assistant message followed by a distinct structured-output assistant message. This transcript is separate from the path-specific fields on `info`.
662> To aggregate usage across the whole run, accumulate from `onUsage` callbacks rather than relying on `info.usage`.
663​
664```typescript
665import { type ChatMiddleware } from "@tanstack/ai";
666​
667const terminal: ChatMiddleware = {
668 name: "terminal",
669 onFinish: (ctx, info) => {
670 console.log(`Finished: ${info.finishReason}, ${info.duration}ms`);
671 console.log(`Content: ${info.content}`);
672 if (info.usage) {
673 console.log(`Tokens: ${info.usage.totalTokens}`);
674 }
675 },
676 onAbort: (ctx, info) => {
677 console.log(`Aborted: ${info.reason}, ${info.duration}ms`);
678 },
679 onError: (ctx, info) => {
680 console.error(`Error after ${info.duration}ms:`, info.error);
681 },
682};
683```
684​
685The `info` object for `onFinish` (`FinishInfo`):
686​
687| Field | Type | Description |
688|-------|------|-------------|
689| `finishReason` | `string \| null` | The agent loop's last `finishReason`. `null` when no agent-loop iteration produced `RUN_FINISHED` (e.g. a tools-less `chat({ outputSchema })` run). |
690| `duration` | `number` | Total run duration in milliseconds, including any structured-output finalization. |
691| `content` | `string` | The agent loop's accumulated text content. Includes native-combined structured JSON; excludes separate-finalization JSON. Observe the completed result through the `structured-output.complete` CUSTOM event via `onChunk`. |
692| `usage` | `{ promptTokens; completionTokens; totalTokens } \| undefined` | **Optional.** The agent loop's last `RUN_FINISHED.usage`. **Does not include finalization tokens** — use `onUsage` to observe those. Always guard with `if (info.usage)` or `info.usage?.`. |
693​
694## Context Object
695​
696Every hook receives a `ChatMiddlewareContext` as its first argument. It provides request-scoped information and control functions:
697​
698| Field | Type | Description |
699|-------|------|-------------|
700| `requestId` | `string` | Unique ID for this chat request |
701| `streamId` | `string` | Unique ID for this stream |
702| `threadId` | `string` | AG-UI thread identifier. Resolves to caller-provided `threadId` (or legacy `conversationId`), or an auto-generated value if neither is supplied. Use this for event correlation. |
703| `conversationId` | `string \| undefined` | **Deprecated** alias of `threadId`. Always equals `ctx.threadId`; retained so middleware written before the AG-UI rename keeps working. New middleware should read `ctx.threadId`. |
704| `phase` | `ChatMiddlewarePhase` | Current lifecycle phase |
705| `iteration` | `number` | Agent loop iteration (0-indexed) |
706| `chunkIndex` | `number` | Running count of chunks yielded |
707| `signal` | `AbortSignal \| undefined` | External abort signal |
708| `abort(reason?)` | `function` | Abort the run from within middleware |
709| `emitCustomEvent(name, value, options?)` | `function` | Push a `CUSTOM` chunk onto the chat stream now. The engine yields it while the current hook is still running, including during `onConfig`. Durability flushes it immediately. Pass `{ batch: true }` to keep it in the durability batch. |
710| `context` | `TContext` | User-provided runtime context value |
711| `defer(promise)` | `function` | Register a non-blocking side-effect |
712​
713## Typed Runtime Context
714​
715`ChatMiddleware` accepts a context generic. This lets reusable middleware declared outside `chat()` access the same typed runtime context as your tools.
716​
717```typescript
718import { chat, type ChatMiddleware } from "@tanstack/ai";
719import { openaiText } from "@tanstack/ai-openai";
720import { session, audit } from "./server";
721​
722type AppContext = {
723 userId: string;
724 audit: {
725 write(event: { userId: string; requestId: string }): Promise<void>;
726 };
727};
728​
729export const auditMiddleware: ChatMiddleware<AppContext> = {
730 name: "audit",
731 onStart(ctx) {
732 ctx.defer(
733 ctx.context.audit.write({
734 userId: ctx.context.userId,
735 requestId: ctx.requestId,
736 })
737 );
738 },
739};
740​
741chat({
742 adapter: openaiText("gpt-5.5"),
743 messages: [{ role: "user", content: "Hello" }],
744 middleware: [auditMiddleware],
745 context: {
746 userId: session.user.id,
747 audit,
748 },
749});
750```
751​
752When typed middleware or typed tools are present, `chat()` checks that the provided `context` matches the required shape. Existing middleware typed as plain `ChatMiddleware` still works; its `ctx.context` remains `unknown` and does not force a `context` option.
753​
754Runtime context is process-local application state. It is separate from AG-UI `RunAgentInput.context`, which is protocol metadata parsed by `chatParamsFromRequest`. See [Runtime Context](./runtime-context) for server, client, and client-to-server handoff patterns.
755​
756### Aborting from Middleware
757​
758Call `ctx.abort()` to gracefully stop the run. This triggers the `onAbort` terminal hook:
759​
760```typescript
761import { type ChatMiddleware } from "@tanstack/ai";
762​
763const timeout: ChatMiddleware = {
764 name: "timeout",
765 onChunk: (ctx) => {
766 if (ctx.chunkIndex > 1000) {
767 ctx.abort("Too many chunks");
768 }
769 },
770};
771```
772​
773### Deferred Side Effects
774​
775Use `ctx.defer()` to register promises that run after the terminal hook without blocking the stream:
776​
777```typescript
778import { type ChatMiddleware } from "@tanstack/ai";
779​
780const analytics: ChatMiddleware = {
781 name: "analytics",
782 onFinish: (ctx, info) => {
783 ctx.defer(
784 fetch("/api/analytics", {
785 method: "POST",
786 body: JSON.stringify({
787 requestId: ctx.requestId,
788 duration: info.duration,
789 tokens: info.usage?.totalTokens,
790 }),
791 })
792 );
793 },
794};
795```
796​
797## Composing Multiple Middleware
798​
799Middleware execute in array order. The ordering matters for hooks that pipe or short-circuit:
800​
801```typescript
802import { chat, type ChatMiddleware } from "@tanstack/ai";
803import { openaiText } from "@tanstack/ai-openai";
804import { authMiddleware, loggingMiddleware, cachingMiddleware } from "./middleware";
805​
806const stream = chat({
807 adapter: openaiText("gpt-5.5"),
808 messages: [{ role: "user", content: "Hello" }],
809 middleware: [authMiddleware, loggingMiddleware, cachingMiddleware],
810});
811```
812​
813### Composition Rules
814​
815| Hook | Composition | Effect of Order |
816|------|------------|----------------|
817| `onConfig` | **Piped** — each receives previous output | Earlier middleware transforms first |
818| `onStructuredOutputConfig` | **Piped** — each receives previous output | Earlier middleware transforms first |
819| `onStart` | Sequential | All run in order |
820| `onChunk` | **Piped** — chunks flow through each middleware | If first drops a chunk, later middleware never see it |
821| `onBeforeToolCall` | **First-win** — first non-void decision wins | Earlier middleware has priority |
822| `onShouldContinue` | **AND** — any explicit `false` stops the loop | Order only affects which middleware runs first when short-circuiting |
823| `onAfterToolCall` | Sequential | All run in order |
824| `onUsage` | Sequential | All run in order |
825| `onFinish/onAbort/onError` | Sequential | All run in order |
826​
827## Capabilities
828​
829Middleware often need to **share state**. A provider middleware sets something up (a database handle, a per-request counter, a sandbox), and a consumer middleware reads it back later in the same run. Capabilities make that hand-off **type-safe and order-checked**: the consumer declares what it needs, the provider declares what it offers, and `chat()` refuses to run (at compile time _and_ at runtime) if a required capability was never provided.
830​
831### Creating a capability
832​
833A capability is created with `createCapability<TValue>()('name')` — a **curried** call:
834​
835```typescript
836import { createCapability } from "@tanstack/ai";
837​
838const counterCapability = createCapability<{ value: number }>()("counter");
839const [getCounter, provideCounter] = counterCapability;
840```
841​
842The currying is deliberate: you supply the **value type** explicitly (`<{ value: number }>`) while the **name literal** is inferred from the argument (`"counter"`). A single `createCapability<T>('name')` call can't do both — supplying `T` explicitly stops TypeScript inferring the name, collapsing it to `string` and defeating the compile-time coverage check that keys on the literal name.
843​
844The returned `counterCapability` is a hybrid value:
845​
846- It **destructures to `[get, provide]`** — the two accessors you use inside hooks.
847- It **is itself the identity** you list in `requires` / `provides`. There is no separate token to import.
848​
849The accessors:
850​
851| Accessor | Behavior |
852|----------|----------|
853| `getCounter(ctx)` | Returns the value. **Throws** if the capability was never provided. |
854| `getCounter(ctx, { optional: true })` | Returns `TValue \| undefined` — no throw when absent. |
855| `provideCounter(ctx, value)` | Sets the value for this run. Call it from `setup`. |
856​
857Equivalently, the context exposes `ctx.get(capability)`, `ctx.getOptional(capability)`, and `ctx.provide(capability, value)` — pass the capability handle directly. These are typed by the handle you pass (`ctx.get(counterCapability)` returns the value type), so `getCounter(ctx)` and `ctx.get(counterCapability)` are interchangeable — use whichever reads better in your hook.
858​
859> **Capability names must be unique across your app.** The compile-time coverage check keys on the name literal (runtime keys on the handle reference), so two capabilities sharing a name will conflate in the type-level check.
860​
861### The `setup` hook
862​
863Provisioning happens in a dedicated `setup(ctx)` hook. It **runs first** — before any `onConfig` (init), across all middleware in array order — so that by the time the rest of the lifecycle begins, every capability is in place. `setup` receives the stable `ChatMiddlewareContext` (not the mutable config), and may be async.
864​
865### `requires` / `provides` / `optionalRequires`
866​
867Three array fields on a middleware declare its capability contract. Each is a `ReadonlyArray<CapabilityHandle>` — you list the capability handles themselves:
868​
869| Field | Meaning |
870|-------|---------|
871| `provides` | Capabilities this middleware sets up. Each one **must** be `provide`d inside `setup`, or `chat()` throws after the setup phase. |
872| `requires` | Capabilities this middleware reads. `chat()` validates (compile time + runtime) that some earlier middleware provides each one. |
873| `optionalRequires` | Capabilities used **if present** but not required. Non-gating — never causes a validation error. Read with `getX(ctx, { optional: true })`. |
874​
875### Array example
876​
877Author middleware with `defineChatMiddleware` — it sharpens the `requires` / `provides` tuple types so the coverage check and builder can read them precisely. Here a **provider** sets up a counter in `setup`, and a **consumer** reads it in a hook:
878​
879```typescript
880import {
881 chat,
882 createCapability,
883 createChatMiddleware,
884 defineChatMiddleware,
885} from "@tanstack/ai";
886import { openaiText } from "@tanstack/ai-openai";
887​
888const counterCapability = createCapability<{ value: number }>()("counter");
889const [getCounter, provideCounter] = counterCapability;
890​
891// Provider: declares `provides` and provisions the value in `setup`.
892const withCounter = defineChatMiddleware({
893 name: "with-counter",
894 provides: [counterCapability],
895 setup(ctx) {
896 provideCounter(ctx, { value: 0 });
897 },
898});
899​
900// Consumer: declares `requires` and reads the value via `get` in a hook.
901const countsChunks = defineChatMiddleware({
902 name: "counts-chunks",
903 requires: [counterCapability],
904 onChunk(ctx) {
905 getCounter(ctx).value++;
906 },
907 onFinish(ctx) {
908 console.log(`Saw ${getCounter(ctx).value} chunks`);
909 },
910});
911​
912const stream = chat({
913 adapter: openaiText("gpt-5.5"),
914 messages: [{ role: "user", content: "Hello" }],
915 // Provider must come before the consumer.
916 middleware: [withCounter, countsChunks],
917});
918```
919​
920If you drop `withCounter` from the array, `chat()` reports a compile-time error at the `middleware` option naming the missing `"counter"` capability — and throws at runtime before the adapter is ever called.
921​
922### Builder example
923​
924`createChatMiddleware()` builds the array through chained `.use()` calls and enforces **provider-before-consumer ordering at compile time**: each `.use()` requires that the middleware's `requires` are already covered by capabilities provided by earlier `.use()` calls.
925​
926```typescript
927import {
928 chat,
929 createCapability,
930 createChatMiddleware,
931 defineChatMiddleware,
932} from "@tanstack/ai";
933import { openaiText } from "@tanstack/ai-openai";
934​
935const counterCapability = createCapability<{ value: number }>()("counter");
936const [getCounter, provideCounter] = counterCapability;
937​
938const withCounter = defineChatMiddleware({
939 name: "with-counter",
940 provides: [counterCapability],
941 setup(ctx) {
942 provideCounter(ctx, { value: 0 });
943 },
944});
945​
946const countsChunks = defineChatMiddleware({
947 name: "counts-chunks",
948 requires: [counterCapability],
949 onChunk(ctx) {
950 getCounter(ctx).value++;
951 },
952});
953​
954const middleware = createChatMiddleware()
955 .use(withCounter) // provides "counter"
956 .use(countsChunks) // requires "counter" — OK, already provided above
957 .build();
958​
959const stream = chat({
960 adapter: openaiText("gpt-5.5"),
961 messages: [{ role: "user", content: "Hello" }],
962 middleware,
963});
964```
965​
966Swap the two `.use()` calls (`.use(countsChunks).use(withCounter)`) and the builder rejects it at the `.use(countsChunks)` line — the consumer is ordered before its provider, so `"counter"` isn't in the provided set yet.
967​
968### Validation guarantees
969​
970The capability system fails loudly and early:
971​
972- **Compile-time coverage.** A required capability that nothing provides surfaces as a type error at the `middleware` option. This is enforced two ways: an **array coverage check** on `middleware: [...]`, and the order-aware **`createChatMiddleware()` builder** (which additionally enforces ordering).
973- **Runtime coverage.** Even if types are bypassed, `chat()` validates coverage and **throws before the adapter runs** if a required capability is missing.
974- **Post-`setup` assertion.** If a middleware declares a capability in `provides` but never calls its `provide` accessor during `setup`, `chat()` throws after the setup phase — you can't silently forget to provision.
975- **Duplicate provide → last-wins + warning.** If two middleware provide the same capability, the last write wins and a development warning is emitted.
976- **Unique names.** Capability `name`s must be unique across your app; the compile-time coverage check keys on the name literal (runtime keys on the handle reference).
977​
978## Built-in Middleware
979​
980TanStack AI ships ready-made middleware for common cases — caching tool results, redacting streamed text, and OpenTelemetry tracing:
981​
982| Middleware | Import | What it does |
983|------------|--------|--------------|
984| `toolCacheMiddleware` | `@tanstack/ai/middlewares` | Cache tool-call results by name + arguments |
985| `contentGuardMiddleware` | `@tanstack/ai/middlewares` | Redact / transform / block streamed text content |
986| `otelMiddleware` | `@tanstack/ai/middlewares/otel` | Emit OpenTelemetry spans + GenAI metrics |
987​
988See [Built-in Middleware](./built-in-middleware) for full options and examples for each. The recipes below show how to build your own.
989​
990## Recipes
991​
992### Live custom events
993​
994A long `onConfig` hook can send progress to the client while it waits. Call `ctx.emitCustomEvent` when the work starts, then again when it finishes:
995​
996```typescript
997import { type ChatMiddleware } from "@tanstack/ai";
998​
999async function prepare() {
1000 await new Promise<void>((resolve) => {
1001 setTimeout(resolve, 1);
1002 });
1004​
1005const progress: ChatMiddleware = {
1006 name: "progress",
1007 async onConfig(ctx) {
1008 if (ctx.phase !== "beforeModel") return;
1009 ctx.emitCustomEvent("job:started", { step: "prepare" });
1010 await prepare();
1011 ctx.emitCustomEvent("job:ended", { step: "prepare" });
1012 },
1014```
1015​
1016The engine yields each `CUSTOM` chunk as soon as you call `emitCustomEvent`. If `RUN_STARTED` is not on the wire yet, the engine sends it first. Durability then flushes the event so the client can render a live indicator. Read these events on the client the same way as tool `emitCustomEvent` calls. See [Custom Events](../protocol/custom-events).
1017​
1018### Rate Limiting
1019​
1020Limit the number of tool calls per request:
1021​
1022```typescript
1023import { type ChatMiddleware } from "@tanstack/ai";
1024​
1025function rateLimitMiddleware(maxCalls: number): ChatMiddleware {
1026 let toolCallCount = 0;
1027 return {
1028 name: "rate-limit",
1029 onBeforeToolCall: (ctx, hookCtx) => {
1030 toolCallCount++;
1031 if (toolCallCount > maxCalls) {
1032 return {
1033 type: "abort",
1034 reason: `Rate limit: exceeded ${maxCalls} tool calls`,
1035 };
1037 },
1038 };
1040```
1041​
1042### Audit Trail
1043​
1044Log every action for compliance:
1045​
1046```typescript
1047import { type ChatMiddleware } from "@tanstack/ai";
1048import { db } from "./db";
1049​
1050const auditTrail: ChatMiddleware = {
1051 name: "audit-trail",
1052 onStart: (ctx) => {
1053 ctx.defer(
1054 db.auditLog.create({
1055 requestId: ctx.requestId,
1056 event: "chat_started",
1057 timestamp: Date.now(),
1058 })
1059 );
1060 },
1061 onAfterToolCall: (ctx, info) => {
1062 ctx.defer(
1063 db.auditLog.create({
1064 requestId: ctx.requestId,
1065 event: "tool_executed",
1066 toolName: info.toolName,
1067 success: info.ok,
1068 duration: info.duration,
1069 timestamp: Date.now(),
1070 })
1071 );
1072 },
1073 onFinish: (ctx, info) => {
1074 ctx.defer(
1075 db.auditLog.create({
1076 requestId: ctx.requestId,
1077 event: "chat_finished",
1078 duration: info.duration,
1079 tokens: info.usage?.totalTokens,
1080 timestamp: Date.now(),
1081 })
1082 );
1083 },
1085```
1086​
1087### Per-Iteration Tool Swapping
1088​
1089Expose different tools at different stages of the agent loop:
1090​
1091```typescript
1092import { type ChatMiddleware } from "@tanstack/ai";
1093​
1094const toolSwapper: ChatMiddleware = {
1095 name: "tool-swapper",
1096 onConfig: (ctx, config) => {
1097 if (ctx.phase !== "beforeModel") return;
1098​
1099 if (ctx.iteration === 0) {
1100 // First iteration: only allow search
1101 return {
1102 tools: config.tools.filter((t) => t.name === "search"),
1103 };
1105 // Later iterations: allow all tools
1106 },
1108```
1109​
1110### Content Filtering
1111​
1112Drop or transform chunks before they reach the consumer:
1113​
1114```typescript ignore
1115import { type ChatMiddleware } from "@tanstack/ai";
1116import { containsProfanity } from "./filters";
1117​
1118const contentFilter: ChatMiddleware = {
1119 name: "content-filter",
1120 onChunk: (ctx, chunk) => {
1121 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
1122 if (containsProfanity(chunk.delta)) {
1123 // Drop the chunk entirely
1124 return null;
1127 },
1129```
1130​
1131### Error Recovery with Retry Logging
1132​
1133```typescript
1134import { type ChatMiddleware } from "@tanstack/ai";
1135import { alertService } from "./services";
1136​
1137const errorRecovery: ChatMiddleware = {
1138 name: "error-recovery",
1139 onError: (ctx, info) => {
1140 ctx.defer(
1141 alertService.send({
1142 level: "error",
1143 message: `Chat ${ctx.requestId} failed after ${info.duration}ms`,
1144 error: String(info.error),
1145 })
1146 );
1147 },
1149```
1150​
1151## TypeScript Types
1152​
1153The core middleware types are exported from `@tanstack/ai`:
1154​
1155```typescript
1156import type {
1157 ChatMiddleware,
1158 ChatMiddlewareContext,
1159 ChatMiddlewarePhase,
1160 ChatMiddlewareConfig,
1161 StructuredOutputMiddlewareConfig,
1162 ToolCallHookContext,
1163 BeforeToolCallDecision,
1164 AfterToolCallInfo,
1165 IterationInfo,
1166 ToolPhaseCompleteInfo,
1167 UsageInfo,
1168 FinishInfo,
1169 AbortInfo,
1170 ErrorInfo,
1171} from "@tanstack/ai";
1172```
1173​
1174The option/type surfaces for the [built-in middleware](./built-in-middleware) are exported from the `@tanstack/ai/middlewares` subpath (not the main barrel):
1175​
1176```typescript
1177import type {
1178 ToolCacheMiddlewareOptions,
1179 ToolCacheStorage,
1180 ToolCacheEntry,
1181 ContentGuardMiddlewareOptions,
1182 ContentGuardRule,
1183 ContentFilteredInfo,
1184} from "@tanstack/ai/middlewares";
1185```
1186​
1187## Next Steps
1188​
1189- [Built-in Middleware](./built-in-middleware) — `toolCacheMiddleware`, `contentGuardMiddleware`, `otelMiddleware`
1190- [Compaction](./compaction): keep long chats under the context limit with `withCompaction`
1191- [OpenTelemetry](./otel) — emit traces and metrics via `otelMiddleware`- [Tools](../tools/tools) — Learn about the isomorphic tool system
1192- [Agentic Cycle](../chat/agentic-cycle) — Understand the multi-step agent loop
1193- [Streaming](../chat/streaming) — How streaming works in TanStack AI