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

ChatMiddleware.md

669 lines14.6 KB

1---
2id: ChatMiddleware
3title: ChatMiddleware
4---
5​
6Defined in: packages/ai/src/activities/chat/middleware/types.ts:676
7​
8Chat middleware interface.
9​
10All hooks are optional. Middleware is composed in array order:
11- `onConfig`: config piped through middlewares in order (first transform influences later)
12- `onChunk`: each output chunk is fed into the next middleware in order
13​
14## Examples
15​
16**Logging middleware**
17​
18```ts
19const loggingMiddleware: ChatMiddleware = {
20 name: 'logging',
21 onStart(ctx) { console.log('Chat started', ctx.requestId) },
22 onChunk(ctx, chunk) { console.log('Chunk:', chunk.type) },
23 onFinish(ctx, info) { console.log('Done:', info.duration, 'ms') },
25```
26​
27**Redaction middleware**
28​
29```ts
30const redactionMiddleware: ChatMiddleware = {
31 name: 'redaction',
32 onChunk(ctx, chunk) {
33 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
34 return { ...chunk, delta: redact(chunk.delta) }
35 }
36 },
38```
39​
40## Extended by
41​
42- [`DefinedChatMiddleware`](DefinedChatMiddleware.md)
43​
44## Type Parameters
45​
46### TContext
47​
48`TContext` = `unknown`
49​
50### TInterruptDefinitions
51​
52`TInterruptDefinitions` *extends* `AnyInterruptDefinition` = `never`
53​
54## Properties
55​
56### name?
57​
58```ts
59optional name?: string;
60```
61​
62Defined in: packages/ai/src/activities/chat/middleware/types.ts:681
63​
64Optional name for debugging and identification
65​
66***
67​
68### onAbort?
69​
70```ts
71optional onAbort?: (ctx, info) => void | Promise<void>;
72```
73​
74Defined in: packages/ai/src/activities/chat/middleware/types.ts:900
75​
76Called when the chat run is aborted.
77Exactly one of onFinish/onAbort/onError will be called per run.
78​
79#### Parameters
80​
81##### ctx
82​
83[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
84​
85##### info
86​
87[`AbortInfo`](AbortInfo.md)
88​
89#### Returns
90​
91`void` \| `Promise`\<`void`\>
92​
93***
94​
95### onAfterToolCall?
96​
97```ts
98optional onAfterToolCall?: (ctx, info) =>
99 | AfterToolCallDecision
100| Promise<AfterToolCallDecision>;
101```
102​
103Defined in: packages/ai/src/activities/chat/middleware/types.ts:864
104​
105Called after a tool execution completes (success or failure).
106Return `{ type: 'replaceResult', result }` to change the result that the
107model and the stream see. Middleware run in order. Each one sees the
108result of the one before it.
109​
110Also called for a tool call that did not run because the output limit
111cut its answer. Then `ok` is false, and `error` is an `Error` with the
112code `'max_tokens'`.
113​
114#### Parameters
115​
116##### ctx
117​
118[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
119​
120##### info
121​
122[`AfterToolCallInfo`](AfterToolCallInfo.md)
123​
124#### Returns
125​
126 \| [`AfterToolCallDecision`](../type-aliases/AfterToolCallDecision.md)
127 \| `Promise`\<[`AfterToolCallDecision`](../type-aliases/AfterToolCallDecision.md)\>
128​
129***
130​
131### onBeforeToolCall?
132​
133```ts
134optional onBeforeToolCall?: (ctx, hookCtx) =>
135 | BeforeToolCallDecision
136| Promise<BeforeToolCallDecision>;
137```
138​
139Defined in: packages/ai/src/activities/chat/middleware/types.ts:849
140​
141Called before a server tool runs and before a client tool is sent to the
142client. Not called while the call waits for approval.
143Can observe, transform args, skip execution, or abort the run.
144The tool's `inputSchema` checks the args after this hook.
145​
146#### Parameters
147​
148##### ctx
149​
150[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
151​
152##### hookCtx
153​
154[`ToolCallHookContext`](ToolCallHookContext.md)
155​
156#### Returns
157​
158 \| [`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)
159 \| `Promise`\<[`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)\>
160​
161***
162​
163### onChunk?
164​
165```ts
166optional onChunk?: (ctx, chunk) =>
167 | void
168 | AGUIEvent
169 | AGUIEvent[]
170 | Promise<void | AGUIEvent | AGUIEvent[] | null>
171 | null;
172```
173​
174Defined in: packages/ai/src/activities/chat/middleware/types.ts:833
175​
176Called for every chunk yielded by chat().
177Can observe, transform, expand, or drop chunks.
178​
179#### Parameters
180​
181##### ctx
182​
183[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
184​
185##### chunk
186​
187[`AGUIEvent`](../type-aliases/AGUIEvent.md)
188​
189#### Returns
190​
191 \| `void`
192 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)
193 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)[]
194 \| `Promise`\<void \| AGUIEvent \| AGUIEvent\[\] \| null\>
195 \| `null`
196​
197void (pass through), chunk (replace), chunk[] (expand), null (drop)
198​
199***
200​
201### onConfig?
202​
203```ts
204optional onConfig?: (ctx, config) =>
205 | void
206 | Partial<ChatMiddlewareConfig>
207 | Promise<
208 | void
209 | Partial<ChatMiddlewareConfig>
210 | null>
211 | null;
212```
213​
214Defined in: packages/ai/src/activities/chat/middleware/types.ts:745
215​
216Called to observe or transform the chat configuration.
217Called at init and at the beginning of each agent iteration.
218​
219Return a partial config to merge with the current config, or void to pass through.
220Only the fields you return are overwritten — everything else is preserved.
221​
222#### Parameters
223​
224##### ctx
225​
226[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
227​
228##### config
229​
230[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)
231​
232#### Returns
233​
234 \| `void`
235 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
236 \| `Promise`\<
237 \| `void`
238 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
239 \| `null`\>
240 \| `null`
241​
242***
243​
244### onError?
245​
246```ts
247optional onError?: (ctx, info) => void | Promise<void>;
248```
249​
250Defined in: packages/ai/src/activities/chat/middleware/types.ts:909
251​
252Called when the chat run encounters an unhandled error.
253Exactly one of onFinish/onAbort/onError will be called per run.
254​
255#### Parameters
256​
257##### ctx
258​
259[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
260​
261##### info
262​
263[`ErrorInfo`](ErrorInfo.md)
264​
265#### Returns
266​
267`void` \| `Promise`\<`void`\>
268​
269***
270​
271### onFinish?
272​
273```ts
274optional onFinish?: (ctx, info) => void | Promise<void>;
275```
276​
277Defined in: packages/ai/src/activities/chat/middleware/types.ts:891
278​
279Called when the chat run completes normally.
280Exactly one of onFinish/onAbort/onError will be called per run.
281​
282#### Parameters
283​
284##### ctx
285​
286[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
287​
288##### info
289​
290[`FinishInfo`](FinishInfo.md)
291​
292#### Returns
293​
294`void` \| `Promise`\<`void`\>
295​
296***
297​
298### onInterruptBoundary?
299​
300```ts
301optional onInterruptBoundary?: (ctx) =>
302 | InterruptBoundaryResult<TInterruptDefinitions>
303| Promise<InterruptBoundaryResult<TInterruptDefinitions>>;
304```
305​
306Defined in: packages/ai/src/activities/chat/middleware/types.ts:693
307​
308Called at a lifecycle boundary. Return interrupt requests to pause the run.
309Requests from every middleware in the same boundary form one batch.
310​
311#### Parameters
312​
313##### ctx
314​
315[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\> & `object`
316​
317#### Returns
318​
319 \| [`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>
320 \| `Promise`\<[`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>\>
321​
322***
323​
324### onInterruptResolution?
325​
326```ts
327optional onInterruptResolution?: (ctx, resolutions) =>
328 | InterruptResolutionResult
329| Promise<InterruptResolutionResult>;
330```
331​
332Defined in: packages/ai/src/activities/chat/middleware/types.ts:703
333​
334Called on a continuation run after the client answers registered interrupts.
335Return `toolResume` to decide whether pending tools continue, cancel, or stop.
336​
337#### Parameters
338​
339##### ctx
340​
341[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
342​
343##### resolutions
344​
345[`InterruptResolutionCollection`](InterruptResolutionCollection.md)\<`TInterruptDefinitions`\>
346​
347#### Returns
348​
349 \| [`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)
350 \| `Promise`\<[`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)\>
351​
352***
353​
354### onIteration?
355​
356```ts
357optional onIteration?: (ctx, info) => void | Promise<void>;
358```
359​
360Defined in: packages/ai/src/activities/chat/middleware/types.ts:787
361​
362Called at the start of each agent loop iteration, after a new assistant message ID
363is created. Use this to observe iteration boundaries.
364​
365#### Parameters
366​
367##### ctx
368​
369[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
370​
371##### info
372​
373[`IterationInfo`](IterationInfo.md)
374​
375#### Returns
376​
377`void` \| `Promise`\<`void`\>
378​
379***
380​
381### onModelError?
382​
383```ts
384optional onModelError?: (ctx, error) => void | Promise<void>;
385```
386​
387Defined in: packages/ai/src/activities/chat/middleware/types.ts:822
388​
389Called when the adapter sends a `RUN_ERROR` before any output of the
390model call. The error does not reach `onChunk` or the caller yet. An
391exception that the adapter throws goes to `onError`, not here.
392​
393Call `ctx.retry()` to call the model again. Then `onConfig` runs again
394(phase `beforeModel`), so the middleware can change the request first,
395and the failed call is dropped from the stream. Without `ctx.retry()`,
396the error goes on as usual. A model call retries at most 2 times this
397way. The structured-output call is not retried.
398​
399#### Parameters
400​
401##### ctx
402​
403[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
404​
405##### error
406​
407[`RunErrorEvent`](RunErrorEvent.md)
408​
409#### Returns
410​
411`void` \| `Promise`\<`void`\>
412​
413***
414​
415### onShouldContinue?
416​
417```ts
418optional onShouldContinue?: (ctx, state) => boolean | void | Promise<boolean | void>;
419```
420​
421Defined in: packages/ai/src/activities/chat/middleware/types.ts:806
422​
423Called when the engine is deciding whether to start another agent-loop
424iteration (after a tool phase or between model turns).
425​
426Return `false` to stop further iterations. Return `true`, `void`, or
427`undefined` to allow continuation. Combined with AND semantics across
428middleware and with `agentLoopStrategy` — any `false` stops the loop.
429​
430Does not abort the run: the stream finishes normally with the current
431messages. Use `ctx.abort()` only when you need a hard abort.
432​
433Receives the same [AgentLoopState](AgentLoopState.md) passed to strategies
434(`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).
435​
436#### Parameters
437​
438##### ctx
439​
440[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
441​
442##### state
443​
444[`AgentLoopState`](AgentLoopState.md)
445​
446#### Returns
447​
448`boolean` \| `void` \| `Promise`\<`boolean` \| `void`\>
449​
450***
451​
452### onStart?
453​
454```ts
455optional onStart?: (ctx) => void | Promise<void>;
456```
457​
458Defined in: packages/ai/src/activities/chat/middleware/types.ts:781
459​
460Called when the chat run starts (after initial onConfig).
461​
462#### Parameters
463​
464##### ctx
465​
466[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
467​
468#### Returns
469​
470`void` \| `Promise`\<`void`\>
471​
472***
473​
474### onStructuredOutputConfig?
475​
476```ts
477optional onStructuredOutputConfig?: (ctx, config) =>
478 | void
479 | Partial<StructuredOutputMiddlewareConfig>
480 | Promise<
481 | void
482 | Partial<StructuredOutputMiddlewareConfig>
483 | null>
484 | null;
485```
486​
487Defined in: packages/ai/src/activities/chat/middleware/types.ts:769
488​
489Called at the start of the final structured-output call (when the chat
490was invoked with outputSchema). Pipes through middleware in order, like
491onConfig, but with access to the JSON Schema being sent to the provider.
492​
493Return a partial to shallow-merge into the current config, or void to
494pass through.
495​
496Fires BEFORE onConfig at the structured-output boundary. onConfig also
497re-fires at the same boundary with ctx.phase === 'structuredOutput',
498receiving the post-onStructuredOutputConfig view of the config (minus
499outputSchema). Use onConfig for general-purpose transforms that apply
500to every adapter call; use this hook when you need to transform the
501outputSchema or apply structured-output-specific behavior.
502​
503#### Parameters
504​
505##### ctx
506​
507[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
508​
509##### config
510​
511[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)
512​
513#### Returns
514​
515 \| `void`
516 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
517 \| `Promise`\<
518 \| `void`
519 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
520 \| `null`\>
521 \| `null`
522​
523***
524​
525### onToolPhaseComplete?
526​
527```ts
528optional onToolPhaseComplete?: (ctx, info) => void | Promise<void>;
529```
530​
531Defined in: packages/ai/src/activities/chat/middleware/types.ts:873
532​
533Called after all tool calls in an iteration have been processed.
534Provides aggregate data about tool execution results, approvals, and client tools.
535​
536#### Parameters
537​
538##### ctx
539​
540[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
541​
542##### info
543​
544[`ToolPhaseCompleteInfo`](ToolPhaseCompleteInfo.md)
545​
546#### Returns
547​
548`void` \| `Promise`\<`void`\>
549​
550***
551​
552### onUsage?
553​
554```ts
555optional onUsage?: (ctx, usage) => void | Promise<void>;
556```
557​
558Defined in: packages/ai/src/activities/chat/middleware/types.ts:882
559​
560Called when usage data is available from a RUN_FINISHED chunk.
561Called once per model iteration that reports usage.
562​
563#### Parameters
564​
565##### ctx
566​
567[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
568​
569##### usage
570​
571[`UsageInfo`](UsageInfo.md)
572​
573#### Returns
574​
575`void` \| `Promise`\<`void`\>
576​
577***
578​
579### optionalRequires?
580​
581```ts
582optional optionalRequires?: readonly CapabilityHandle[];
583```
584​
585Defined in: packages/ai/src/activities/chat/middleware/types.ts:728
586​
587Capabilities this middleware uses if present but does not require.
588Non-gating: never causes a validation error. Read with
589`getX(ctx, { optional: true })`.
590​
591***
592​
593### provides?
594​
595```ts
596optional provides?: readonly CapabilityHandle[];
597```
598​
599Defined in: packages/ai/src/activities/chat/middleware/types.ts:721
600​
601Capabilities this middleware provides. Each declared capability MUST be
602provided (via its `provide` accessor) inside `setup`, or `chat()` throws
603after the setup phase.
604​
605***
606​
607### requires?
608​
609```ts
610optional requires?: readonly CapabilityHandle[];
611```
612​
613Defined in: packages/ai/src/activities/chat/middleware/types.ts:714
614​
615Capabilities this middleware requires. `chat()` validates that some
616middleware (or the adapter) provides each one; unsatisfied requirements are
617a compile-time error (array coverage / builder) and a runtime error before
618the adapter runs.
619​
620***
621​
622### routedSubagentPersistence?
623​
624```ts
625optional routedSubagentPersistence?: RoutedSubagentPersistence;
626```
627​
628Defined in: packages/ai/src/activities/chat/middleware/types.ts:687
629​
630Present when this middleware stores subagent runs.
631The router calls it. An app does not set it.
632​
633***
634​
635### sandbox?
636​
637```ts
638optional sandbox?: ChatSandboxHooks<TContext>;
639```
640​
641Defined in: packages/ai/src/activities/chat/middleware/types.ts:918
642​
643Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is
644active during the run and a file is created/changed/deleted. Server-side.
645​
646***
647​
648### setup?
649​
650```ts
651optional setup?: (ctx) => void | Promise<void>;
652```
653​
654Defined in: packages/ai/src/activities/chat/middleware/types.ts:736
655​
656Provisioning hook. Runs FIRST — before `onConfig` (init) — across all
657middleware in array order. Use it to call `provide` accessors so later
658middleware (`onConfig` onward) can consume the capabilities. Receives the
659stable context; does NOT receive the mutable config.
660​
661#### Parameters
662​
663##### ctx
664​
665[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
666​
667#### Returns
668​
669`void` \| `Promise`\<`void`\>