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

generic.md

253 lines8.1 KB

1---
2title: Generic Interrupts
3id: interrupts-generic
4order: 4
5description: "Pause the run to ask the user for typed data, even when no tool call caused the question."
6keywords:
7 - tanstack ai
8 - generic interrupt
9 - defineInterrupt
10 - onInterruptBoundary
11 - onInterruptResolution
12 - INTERRUPT_BOUNDARY_PHASES
13---
14​
15`defineInterrupt` pauses a run for a user answer that is not a tool call. The run continues after the answer.
16​
17A generic interrupt pauses the run with a typed question. `defineInterrupt`
18describes the data that the client sees and the data that it sends back. The
19server and the client register the same definition, so both sides share the
20types.
21​
22## Quick setup
23​
24### 1. Define the interrupt
25​
26Put the definition in a module that the route and the client can both import.
27The schemas must be able to export JSON Schema:
28​
29```ts
30// app/interrupts.ts
31import { defineInterrupt } from '@tanstack/ai'
32import { z } from 'zod'
33​
34export const reviewPlan = defineInterrupt({
35 id: 'review-plan',
36 payloadSchema: z.object({ title: z.string(), changes: z.array(z.string()) }),
37 responseSchema: z.object({ approved: z.boolean(), note: z.string().optional() }),
38})
39```
40​
41- `payloadSchema`: display data from the server to the client. Optional.
42- `responseSchema`: the answer from the client to the server. Required.
43​
44### 2. Emit it from middleware
45​
46Return the request from `onInterruptBoundary`. Guard on `ctx.phase` to pick
47when it runs. If `ctx.parentRunId` is set, return nothing. Without that guard,
48the continuation pauses again:
49​
50```ts
51// app/chat-middleware.ts
52import type { ChatMiddleware } from '@tanstack/ai'
53import { reviewPlan } from './interrupts'
54​
55export const requestReview: ChatMiddleware<unknown, typeof reviewPlan> = {
56 name: 'request-review',
57 onInterruptBoundary(ctx) {
58 if (ctx.phase !== 'beforeModel') return
59 if (ctx.parentRunId) return
60 if (ctx.iteration !== 0) return
61 return {
62 interrupts: [
63 reviewPlan.interrupt({
64 key: 'initial-plan',
65 reason: 'review-required',
66 message: 'Review the proposed plan.',
67 payload: { title: 'Release plan', changes: ['Add search', 'Add tests'] },
68 }),
69 ],
70 }
71 },
73```
74​
75To pick a different phase, see [Lifecycle Boundaries](./boundaries).
76​
77### 3. Register it on the server
78​
79Pass the definitions to `chat({ interrupts })` and the middleware to
80`chat({ middleware })`. Forward `parentRunId` and `resume` from the request:
81​
82```ts
83// app/api/chat/route.ts
84import { chat, chatParamsFromRequest, toServerSentEventsResponse } from '@tanstack/ai'
85import { openaiText } from '@tanstack/ai-openai'
86import { requestReview } from '../../chat-middleware'
87import { reviewPlan } from '../../interrupts'
88​
89export async function POST(request: Request) {
90 const params = await chatParamsFromRequest(request)
91 const stream = chat({
92 adapter: openaiText('gpt-6.1-sol'),
93 messages: params.messages,
94 threadId: params.threadId,
95 runId: params.runId,
96 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
97 ...(params.resume ? { resume: params.resume } : {}),
98 interrupts: [reviewPlan],
99 middleware: [requestReview],
100 })
101 return toServerSentEventsResponse(stream)
103```
104​
105### 4. Resolve it in React
106​
107Register the same definitions with `useChat`. Check `kind` and `definitionId`,
108then pass the item to a card typed as `GenericInterrupt<typeof reviewPlan>`:
109​
110```tsx
111// app/plan-review.tsx
112import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
113import type { GenericInterrupt } from '@tanstack/ai-react'
114import { reviewPlan } from './interrupts'
115​
116function ReviewCard({
117 interrupt,
118}: {
119 interrupt: GenericInterrupt<typeof reviewPlan>
120}) {
121 return (
122 <article>
123 <h2>{interrupt.payload?.title}</h2>
124 <button onClick={() => interrupt.resolveInterrupt({ approved: true })}>
125 Approve
126 </button>
127 <button onClick={() => interrupt.cancel()}>Cancel</button>
128 </article>
129 )
131​
132export function PlanReview() {
133 const { interrupts } = useChat({
134 threadId: 'release-42',
135 connection: fetchServerSentEvents('/api/chat'),
136 interrupts: [reviewPlan],
137 })
138​
139 return (
140 <>
141 {interrupts.map((interrupt) => {
142 if (interrupt.kind !== 'generic') return null
143 if (!('definitionId' in interrupt)) return null
144 if (interrupt.definitionId !== reviewPlan.id) return null
145 return <ReviewCard key={interrupt.id} interrupt={interrupt} />
146 })}
147 </>
148 )
150```
151​
152### 5. Try it
153​
154Send any message. The run stops before the model call and shows the "Release
155plan" card. Click Approve. The run continues, and the model answers.
156​
157## How it works
158​
159- `resolveInterrupt` stages the answer. The client sends one continuation when
160 every bound interrupt in the batch is resolved or cancelled.
161- Use `cancel()` when the user does not want to give the data.
162- The interrupt ends the current AG-UI run with one `RUN_FINISHED` event. Its
163 outcome is `interrupt`.
164- The answer starts a new run. Its `parentRunId` is the interrupted run, and it
165 carries the answer to the registered middleware.
166​
167## Read the answer on the server
168​
169`onInterruptResolution` runs once at the start of the continuation, after the
170client answers. It does not run in the `chat()` call that paused:
171​
172```ts
173import type { ChatMiddleware } from '@tanstack/ai'
174import { reviewPlan } from './interrupts'
175​
176export const applyReview: ChatMiddleware<unknown, typeof reviewPlan> = {
177 name: 'apply-review',
178 onInterruptResolution(_ctx, resumedInterrupts) {
179 for (const result of resumedInterrupts.for(reviewPlan)) {
180 if (result.status === 'resolved' && !result.response.approved) {
181 return { toolResume: 'stop' }
182 }
183 }
184 },
186```
187​
188This hook cannot change prompts, tools, or messages. To use the answer in the
189next model call, see [Apply Answers](./apply-answers).
190​
191## Try all four phases
192​
193The React chat example has a playground for `beforeModel`, `afterModel`,
194`beforeTools`, and `afterTools`. Each pause shows two typed cards:
195`reviewPlan` and `chooseAudience`.
196​
1971. Start `examples/ts-react-chat`.
1982. Open `/generic-interrupts`.
1993. Pick a phase, resolve both cards, and look at the selected policy.
200​
201## Advanced
202​
203### Request rules
204​
205- `interrupt()` accepts only `key`, `reason`, `message`, `expiresAt`, and
206 `payload` (when the definition declares a payload).
207- It returns an immutable request.
208- Do not put secrets in the payload. The client gets it, and persistence can
209 store it.
210- Requests from every middleware at the same boundary form one interrupt batch.
211- A duplicate definition id in `chat({ interrupts })` fails before the adapter
212 starts.
213​
214### Boundary phases
215​
216`onInterruptBoundary` can run at each value in `INTERRUPT_BOUNDARY_PHASES`:
217​
218- `beforeModel`: before the adapter call.
219- `afterModel`: after the model stream ends.
220- `beforeTools`: before the tools run.
221- `afterTools`: after the tool results are in `messages`.
222​
223When to use each phase, and what `ctx` holds there, is in
224[Lifecycle Boundaries](./boundaries).
225​
226### Resume details
227​
228- `useChat` sends `parentRunId` and `resume` on the continuation.
229- Each generic resume item carries the original request in `metadata`.
230- `onInterruptResolution` runs after init `onConfig` and before `onStart`.
231 `ctx.phase` is still `'init'`.
232- `resumedInterrupts.for(definition)` keeps the response type for that
233 definition.
234- `resumedInterrupts.all()` reads every registered definition.
235 `all(definitionA, definitionB)` narrows the result to those definitions.
236​
237Middleware can return `toolResume: 'continue'`, `'cancel'`, or `'stop'`. When
238more than one middleware returns a value, `stop` wins over `cancel`, and
239`cancel` wins over `continue`.
240​
241### External generic interrupts
242​
243An external system can emit a standard AG-UI generic interrupt. Without a valid
244TanStack binding, the client shows it as `kind: 'unbound'`. It stays visible,
245but it has no resolve or cancel method. Then your client never sends a
246continuation for a pause that a different system owns. See
247[Interrupts from other systems](./overview#interrupts-from-other-systems).
248​
249### Related pages
250​
251- Mix generic interrupts with tool approvals: [Multiple Interrupts](./multiple).
252- Keep an interrupt across a server restart:
253 [Chat persistence](../persistence/chat-persistence).