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

middleware.md

255 lines8.6 KB

1---
2title: Middleware
3id: middleware
4order: 1
5description: "Run your own code at each step of a chat() call. Log runs, count tokens, change the request, guard tool calls, and filter the stream."
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 runs around every `chat()` call. Use it to log a run, count tokens, or block a tool, without copying that code into each route.
18​
19Write it once as middleware. A middleware is an object with hooks. `chat()` calls each hook at a fixed step of the run.
20​
21## Quick setup
22​
23### 1. Write the middleware
24​
25```typescript
26// logger.ts
27import { type ChatMiddleware } from "@tanstack/ai";
28​
29export const logger: ChatMiddleware = {
30 name: "logger",
31 onStart: (ctx) => {
32 console.log(`[${ctx.requestId}] started with ${ctx.model}`);
33 },
34 onAfterToolCall: (ctx, info) => {
35 console.log(`[${ctx.requestId}] ${info.toolName} took ${info.duration} ms`);
36 },
37 onFinish: (ctx, info) => {
38 console.log(
39 `[${ctx.requestId}] done in ${info.duration} ms, ${info.usage?.totalTokens ?? 0} tokens`,
40 );
41 },
42};
43```
44​
45### 2. Add it to `chat()`
46​
47```typescript
48// api/chat.ts
49import {
50 chat,
51 chatParamsFromRequest,
52 toServerSentEventsResponse,
53} from "@tanstack/ai";
54import { openaiText } from "@tanstack/ai-openai";
55import { logger } from "./logger";
56​
57export async function POST(request: Request) {
58 const { messages, threadId, runId } = await chatParamsFromRequest(request);
59​
60 const stream = chat({
61 adapter: openaiText("gpt-6.1-sol"),
62 messages,
63 threadId,
64 runId,
65 middleware: [logger],
66 });
67​
68 return toServerSentEventsResponse(stream);
70```
71​
72### 3. Send a message
73​
74Send a message from your chat UI. The server console shows one line when the run starts, one line for each tool call, and one line when the run finishes:
75​
76```text
77[chat-1760000000000-k3j9x2a] started with gpt-6.1-sol
78[chat-1760000000000-k3j9x2a] done in 1840 ms, 312 tokens
79```
80​
81The client code does not change. Middleware runs on the server only.
82​
83> [!TIP]
84> Do you only want to see the chunks during development? Set `debug: { middleware: true }` on `chat()`. You do not need your own middleware for that. See [Debug Logging](./debug-logging).
85​
86## How it works
87​
88Every hook is optional. Add only the hooks you need. The ones you use most:
89​
90| Hook | When it runs | What it can do |
91| --- | --- | --- |
92| `onConfig` | At the start, and before each model call | Change messages, system prompts, tools, model options |
93| `onStart` | Once, after the first `onConfig` | Start timers, write a log line |
94| `onChunk` | For each chunk of the stream | Change, split, or drop the chunk |
95| `onBeforeToolCall` | Before a tool runs | Change the input, skip the tool, or stop the run |
96| `onAfterToolCall` | After a tool runs | Read the result, or replace it |
97| `onUsage` | When a model call reports token usage | Count tokens and cost |
98| `onFinish`, `onAbort`, `onError` | Once, at the end | Exactly one of the three runs |
99​
100More hooks exist for the agent loop, model errors, and interrupts. See [Middleware: Advanced](./middleware-advanced#hooks-reference).
101​
102The middleware run in array order:
103​
104- `onConfig` and `onChunk` pipe. Each middleware gets the output of the one before it.
105- `onBeforeToolCall` stops at the first middleware that returns a decision.
106- The other hooks run one after another, in order.
107​
108Each hook gets a context object (`ctx`) as its first argument. It has the IDs of the run, the current phase and iteration, and helpers like `ctx.abort()` and `ctx.defer()`.
109​
110## Common changes
111​
112### Change the tool choice of a call
113​
114Your agent hits its last model call, and the model calls a tool again. The run ends after the tool result, and the user gets no answer. Return `toolChoice: 'none'` on that last call, and the model answers in text:
115​
116```typescript
117import {
118 chat,
119 maxIterations,
120 toolDefinition,
121 type ChatMiddleware,
122} from "@tanstack/ai";
123import { openaiText } from "@tanstack/ai-openai";
124import { z } from "zod";
125​
126const MAX_CALLS = 10;
127​
128const search = toolDefinition({
129 name: "search",
130 description: "Search the docs",
131 inputSchema: z.object({ query: z.string() }),
132}).server(async ({ query }) => ({ hits: [`A page about ${query}`] }));
133​
134const answerOnLastCall: ChatMiddleware = {
135 name: "answer-on-last-call",
136 onConfig: (ctx) => {
137 if (ctx.phase === "beforeModel" && ctx.iteration === MAX_CALLS - 1) {
138 return { toolChoice: "none" };
139 }
140 },
141};
142​
143const stream = chat({
144 adapter: openaiText("gpt-6.1-sol"),
145 messages: [{ role: "user", content: "How do I add a tool?" }],
146 threadId: "thread-1",
147 tools: [search],
148 agentLoopStrategy: maxIterations(MAX_CALLS),
149 middleware: [answerOnLastCall],
150});
151```
152​
153- `config.toolChoice` is the `chat()` option.
154- The value you return applies to the next model call only. The call after it starts again from the `chat()` option.
155- Return it in the `beforeModel` phase. A value from the `init` phase does not reach a model call.
156- For the values, and what each provider does with them, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
157​
158### Change the HTTP requests of a call
159​
160Your proxy wants a header on each request. Or you want to log each model call. You do not need your own client for that. Return `wrapFetch` from `onConfig`:
161​
162```typescript
163import { type ChatMiddleware } from "@tanstack/ai";
164​
165const traceHeader: ChatMiddleware = {
166 name: "trace-header",
167 onConfig: (ctx) => {
168 if (ctx.phase !== "beforeModel") return;
169 return {
170 wrapFetch: (next) => (input, init) => {
171 const headers = new Headers(init?.headers);
172 headers.set("x-trace-id", `${ctx.requestId}-${ctx.iteration}`);
173 return next(input, { ...init, headers });
174 },
175 };
176 },
177};
178```
179​
180Do you want the same wrapper on every call of the run? Pass it to `chat()`:
181​
182```typescript
183import { chat } from "@tanstack/ai";
184import { openaiText } from "@tanstack/ai-openai";
185​
186const stream = chat({
187 adapter: openaiText("gpt-6.1-sol"),
188 messages: [{ role: "user", content: "Hi" }],
189 threadId: "thread-1",
190 wrapFetch: (next) => async (input, init) => {
191 const started = Date.now();
192 const response = await next(input, init);
193 console.log(`model call: ${response.status} in ${Date.now() - started} ms`);
194 return response;
195 },
196});
197```
198​
199- A wrapper gets the next `fetch` and gives back a new one. It can change the URL, the headers, the request, or the response.
200- A wrapper from `onConfig` applies to the next model call only.
201- Wrappers chain. The `chat()` wrapper runs first, then the middleware wrappers in middleware order, then the fetch of the adapter.
202- Each adapter page says if that adapter supports `wrapFetch`.
203​
204### Change the prompt cache of a call
205​
206A slow tool, like a build or a test run, can pause your agent for more than 5 minutes. The short Claude cache is gone by then. Return `promptCache` from `onConfig` to keep the cache longer from the next call on:
207​
208```typescript
209import { type ChatMiddleware } from "@tanstack/ai";
210​
211const longCacheAfterTools: ChatMiddleware = {
212 name: "long-cache-after-tools",
213 onConfig: (ctx, config) => {
214 if (ctx.phase !== "beforeModel" || ctx.iteration === 0) return;
215 return { promptCache: { ...config.promptCache, retention: "long" } };
216 },
217};
218```
219​
220- `config.promptCache` is the current value, with its `retention` and its `key`.
221- The value you return goes to the adapter on the next model call. It stays until a middleware returns another one.
222- For the retention values and what they cost, see [Prompt Caching](./prompt-caching#turn-it-off-or-keep-it-longer).
223​
224### Block a tool call
225​
226Some tools must never run from a chat. Return an `abort` decision from `onBeforeToolCall`, and the run stops before the tool runs:
227​
228```typescript
229import { type ChatMiddleware } from "@tanstack/ai";
230​
231const guard: ChatMiddleware = {
232 name: "guard",
233 onBeforeToolCall: (ctx, hookCtx) => {
234 if (hookCtx.toolName === "deleteDatabase") {
235 return { type: "abort", reason: "Dangerous operation blocked" };
236 }
237 },
238};
239```
240​
241To change the input or skip the tool with your own result, see [onBeforeToolCall](./middleware-advanced#onbeforetoolcall).
242​
243## Ready-made middleware
244​
245You do not have to write the common cases yourself:
246​
247- `toolCacheMiddleware`: cache tool results.
248- `contentGuardMiddleware`: redact or block text in the stream.
249- `otelMiddleware`: send OpenTelemetry traces and metrics.
250​
251See [Built-in Middleware](./built-in-middleware). To keep long chats under the context limit, see [Compaction](./compaction).
252​
253## Advanced
254​
255Every hook in detail, the context object, capabilities, recipes, and the types are in [Middleware: Advanced](./middleware-advanced).