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

ChatMiddleware.md

623 lines15.4 KB

1---
2id: ChatMiddleware
3title: ChatMiddleware
4---
5​
6Defined in: [packages/ai/src/activities/chat/middleware/types.ts:621](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L621)
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:626](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L626)
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:820](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L820)
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) => void | Promise<void>;
99```
100​
101Defined in: [packages/ai/src/activities/chat/middleware/types.ts:784](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L784)
102​
103Called after a tool execution completes (success or failure).
104​
105#### Parameters
106​
107##### ctx
108​
109[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
110​
111##### info
112​
113[`AfterToolCallInfo`](AfterToolCallInfo.md)
114​
115#### Returns
116​
117`void` \| `Promise`\<`void`\>
118​
119***
120​
121### onBeforeToolCall?
122​
123```ts
124optional onBeforeToolCall?: (ctx, hookCtx) =>
125 | BeforeToolCallDecision
126| Promise<BeforeToolCallDecision>;
127```
128​
129Defined in: [packages/ai/src/activities/chat/middleware/types.ts:776](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L776)
130​
131Called before a tool is executed.
132Can observe, transform args, skip execution, or abort the run.
133​
134#### Parameters
135​
136##### ctx
137​
138[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
139​
140##### hookCtx
141​
142[`ToolCallHookContext`](ToolCallHookContext.md)
143​
144#### Returns
145​
146 \| [`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)
147 \| `Promise`\<[`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)\>
148​
149***
150​
151### onChunk?
152​
153```ts
154optional onChunk?: (ctx, chunk) =>
155 | void
156 | AGUIEvent
157 | AGUIEvent[]
158 | Promise<void | AGUIEvent | AGUIEvent[] | null>
159 | null;
160```
161​
162Defined in: [packages/ai/src/activities/chat/middleware/types.ts:762](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L762)
163​
164Called for every chunk yielded by chat().
165Can observe, transform, expand, or drop chunks.
166​
167#### Parameters
168​
169##### ctx
170​
171[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
172​
173##### chunk
174​
175[`AGUIEvent`](../type-aliases/AGUIEvent.md)
176​
177#### Returns
178​
179 \| `void`
180 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)
181 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)[]
182 \| `Promise`\<void \| AGUIEvent \| AGUIEvent\[\] \| null\>
183 \| `null`
184​
185void (pass through), chunk (replace), chunk[] (expand), null (drop)
186​
187***
188​
189### onConfig?
190​
191```ts
192optional onConfig?: (ctx, config) =>
193 | void
194 | Partial<ChatMiddlewareConfig>
195 | Promise<
196 | void
197 | Partial<ChatMiddlewareConfig>
198 | null>
199 | null;
200```
201​
202Defined in: [packages/ai/src/activities/chat/middleware/types.ts:690](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L690)
203​
204Called to observe or transform the chat configuration.
205Called at init and at the beginning of each agent iteration.
206​
207Return a partial config to merge with the current config, or void to pass through.
208Only the fields you return are overwritten — everything else is preserved.
209​
210#### Parameters
211​
212##### ctx
213​
214[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
215​
216##### config
217​
218[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)
219​
220#### Returns
221​
222 \| `void`
223 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
224 \| `Promise`\<
225 \| `void`
226 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
227 \| `null`\>
228 \| `null`
229​
230***
231​
232### onError?
233​
234```ts
235optional onError?: (ctx, info) => void | Promise<void>;
236```
237​
238Defined in: [packages/ai/src/activities/chat/middleware/types.ts:829](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L829)
239​
240Called when the chat run encounters an unhandled error.
241Exactly one of onFinish/onAbort/onError will be called per run.
242​
243#### Parameters
244​
245##### ctx
246​
247[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
248​
249##### info
250​
251[`ErrorInfo`](ErrorInfo.md)
252​
253#### Returns
254​
255`void` \| `Promise`\<`void`\>
256​
257***
258​
259### onFinish?
260​
261```ts
262optional onFinish?: (ctx, info) => void | Promise<void>;
263```
264​
265Defined in: [packages/ai/src/activities/chat/middleware/types.ts:811](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L811)
266​
267Called when the chat run completes normally.
268Exactly one of onFinish/onAbort/onError will be called per run.
269​
270#### Parameters
271​
272##### ctx
273​
274[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
275​
276##### info
277​
278[`FinishInfo`](FinishInfo.md)
279​
280#### Returns
281​
282`void` \| `Promise`\<`void`\>
283​
284***
285​
286### onInterruptBoundary?
287​
288```ts
289optional onInterruptBoundary?: (ctx) =>
290 | InterruptBoundaryResult<TInterruptDefinitions>
291| Promise<InterruptBoundaryResult<TInterruptDefinitions>>;
292```
293​
294Defined in: [packages/ai/src/activities/chat/middleware/types.ts:638](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L638)
295​
296Called at a lifecycle boundary. Return interrupt requests to pause the run.
297Requests from every middleware in the same boundary form one batch.
298​
299#### Parameters
300​
301##### ctx
302​
303[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\> & `object`
304​
305#### Returns
306​
307 \| [`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>
308 \| `Promise`\<[`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>\>
309​
310***
311​
312### onInterruptResolution?
313​
314```ts
315optional onInterruptResolution?: (ctx, resolutions) =>
316 | InterruptResolutionResult
317| Promise<InterruptResolutionResult>;
318```
319​
320Defined in: [packages/ai/src/activities/chat/middleware/types.ts:648](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L648)
321​
322Called on a continuation run after the client answers registered interrupts.
323Return `toolResume` to decide whether pending tools continue, cancel, or stop.
324​
325#### Parameters
326​
327##### ctx
328​
329[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
330​
331##### resolutions
332​
333[`InterruptResolutionCollection`](InterruptResolutionCollection.md)\<`TInterruptDefinitions`\>
334​
335#### Returns
336​
337 \| [`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)
338 \| `Promise`\<[`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)\>
339​
340***
341​
342### onIteration?
343​
344```ts
345optional onIteration?: (ctx, info) => void | Promise<void>;
346```
347​
348Defined in: [packages/ai/src/activities/chat/middleware/types.ts:732](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L732)
349​
350Called at the start of each agent loop iteration, after a new assistant message ID
351is created. Use this to observe iteration boundaries.
352​
353#### Parameters
354​
355##### ctx
356​
357[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
358​
359##### info
360​
361[`IterationInfo`](IterationInfo.md)
362​
363#### Returns
364​
365`void` \| `Promise`\<`void`\>
366​
367***
368​
369### onShouldContinue?
370​
371```ts
372optional onShouldContinue?: (ctx, state) => boolean | void | Promise<boolean | void>;
373```
374​
375Defined in: [packages/ai/src/activities/chat/middleware/types.ts:751](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L751)
376​
377Called when the engine is deciding whether to start another agent-loop
378iteration (after a tool phase or between model turns).
379​
380Return `false` to stop further iterations. Return `true`, `void`, or
381`undefined` to allow continuation. Combined with AND semantics across
382middleware and with `agentLoopStrategy` — any `false` stops the loop.
383​
384Does not abort the run: the stream finishes normally with the current
385messages. Use `ctx.abort()` only when you need a hard abort.
386​
387Receives the same [AgentLoopState](AgentLoopState.md) passed to strategies
388(`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).
389​
390#### Parameters
391​
392##### ctx
393​
394[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
395​
396##### state
397​
398[`AgentLoopState`](AgentLoopState.md)
399​
400#### Returns
401​
402`boolean` \| `void` \| `Promise`\<`boolean` \| `void`\>
403​
404***
405​
406### onStart?
407​
408```ts
409optional onStart?: (ctx) => void | Promise<void>;
410```
411​
412Defined in: [packages/ai/src/activities/chat/middleware/types.ts:726](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L726)
413​
414Called when the chat run starts (after initial onConfig).
415​
416#### Parameters
417​
418##### ctx
419​
420[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
421​
422#### Returns
423​
424`void` \| `Promise`\<`void`\>
425​
426***
427​
428### onStructuredOutputConfig?
429​
430```ts
431optional onStructuredOutputConfig?: (ctx, config) =>
432 | void
433 | Partial<StructuredOutputMiddlewareConfig>
434 | Promise<
435 | void
436 | Partial<StructuredOutputMiddlewareConfig>
437 | null>
438 | null;
439```
440​
441Defined in: [packages/ai/src/activities/chat/middleware/types.ts:714](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L714)
442​
443Called at the start of the final structured-output call (when the chat
444was invoked with outputSchema). Pipes through middleware in order, like
445onConfig, but with access to the JSON Schema being sent to the provider.
446​
447Return a partial to shallow-merge into the current config, or void to
448pass through.
449​
450Fires BEFORE onConfig at the structured-output boundary. onConfig also
451re-fires at the same boundary with ctx.phase === 'structuredOutput',
452receiving the post-onStructuredOutputConfig view of the config (minus
453outputSchema). Use onConfig for general-purpose transforms that apply
454to every adapter call; use this hook when you need to transform the
455outputSchema or apply structured-output-specific behavior.
456​
457#### Parameters
458​
459##### ctx
460​
461[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
462​
463##### config
464​
465[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)
466​
467#### Returns
468​
469 \| `void`
470 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
471 \| `Promise`\<
472 \| `void`
473 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
474 \| `null`\>
475 \| `null`
476​
477***
478​
479### onToolPhaseComplete?
480​
481```ts
482optional onToolPhaseComplete?: (ctx, info) => void | Promise<void>;
483```
484​
485Defined in: [packages/ai/src/activities/chat/middleware/types.ts:793](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L793)
486​
487Called after all tool calls in an iteration have been processed.
488Provides aggregate data about tool execution results, approvals, and client tools.
489​
490#### Parameters
491​
492##### ctx
493​
494[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
495​
496##### info
497​
498[`ToolPhaseCompleteInfo`](ToolPhaseCompleteInfo.md)
499​
500#### Returns
501​
502`void` \| `Promise`\<`void`\>
503​
504***
505​
506### onUsage?
507​
508```ts
509optional onUsage?: (ctx, usage) => void | Promise<void>;
510```
511​
512Defined in: [packages/ai/src/activities/chat/middleware/types.ts:802](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L802)
513​
514Called when usage data is available from a RUN_FINISHED chunk.
515Called once per model iteration that reports usage.
516​
517#### Parameters
518​
519##### ctx
520​
521[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
522​
523##### usage
524​
525[`UsageInfo`](UsageInfo.md)
526​
527#### Returns
528​
529`void` \| `Promise`\<`void`\>
530​
531***
532​
533### optionalRequires?
534​
535```ts
536optional optionalRequires?: readonly CapabilityHandle[];
537```
538​
539Defined in: [packages/ai/src/activities/chat/middleware/types.ts:673](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L673)
540​
541Capabilities this middleware uses if present but does not require.
542Non-gating: never causes a validation error. Read with
543`getX(ctx, { optional: true })`.
544​
545***
546​
547### provides?
548​
549```ts
550optional provides?: readonly CapabilityHandle[];
551```
552​
553Defined in: [packages/ai/src/activities/chat/middleware/types.ts:666](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L666)
554​
555Capabilities this middleware provides. Each declared capability MUST be
556provided (via its `provide` accessor) inside `setup`, or `chat()` throws
557after the setup phase.
558​
559***
560​
561### requires?
562​
563```ts
564optional requires?: readonly CapabilityHandle[];
565```
566​
567Defined in: [packages/ai/src/activities/chat/middleware/types.ts:659](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L659)
568​
569Capabilities this middleware requires. `chat()` validates that some
570middleware (or the adapter) provides each one; unsatisfied requirements are
571a compile-time error (array coverage / builder) and a runtime error before
572the adapter runs.
573​
574***
575​
576### routedSubagentPersistence?
577​
578```ts
579optional routedSubagentPersistence?: RoutedSubagentPersistence;
580```
581​
582Defined in: [packages/ai/src/activities/chat/middleware/types.ts:632](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L632)
583​
584Present when this middleware stores subagent runs.
585The router calls it. An app does not set it.
586​
587***
588​
589### sandbox?
590​
591```ts
592optional sandbox?: ChatSandboxHooks<TContext>;
593```
594​
595Defined in: [packages/ai/src/activities/chat/middleware/types.ts:838](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L838)
596​
597Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is
598active during the run and a file is created/changed/deleted. Server-side.
599​
600***
601​
602### setup?
603​
604```ts
605optional setup?: (ctx) => void | Promise<void>;
606```
607​
608Defined in: [packages/ai/src/activities/chat/middleware/types.ts:681](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L681)
609​
610Provisioning hook. Runs FIRST — before `onConfig` (init) — across all
611middleware in array order. Use it to call `provide` accessors so later
612middleware (`onConfig` onward) can consume the capabilities. Receives the
613stable context; does NOT receive the mutable config.
614​
615#### Parameters
616​
617##### ctx
618​
619[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
620​
621#### Returns
622​
623`void` \| `Promise`\<`void`\>