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

api.interrupts.ts

237 lines7.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 canonicalInterruptJson,
5 chat,
6 chatParamsFromRequestBody,
7 digestInterruptJson,
8 maxIterations,
9 toServerSentEventsResponse,
10} from '@tanstack/ai'
11import { createOpenaiChat } from '@tanstack/ai-openai'
12import { z } from 'zod'
13import {
14 admitRescue,
15 assignEnclosure,
16 feedingScheduleResponseSchema,
17 finalizeAdoption,
18 logFieldSighting,
19 printCertificate,
20 printIntakeTag,
21 scheduleVetCheck,
22 shareAdoptionStory,
23} from '@/lib/interrupt-tools'
24import type { ChatMiddleware } from '@tanstack/ai'
25​
26const SYSTEM_PROMPT =
27 'You are the coordinator at Willowbrook Wildlife Sanctuary. When the keeper ' +
28 'asks for an action, call exactly the tool that matches it with sensible ' +
29 'arguments drawn from their message. When you confirm a completed action, ' +
30 'describe it using the values in the tool result (which may differ from the ' +
31 'original request if the keeper edited them). Keep spoken replies short.'
32​
33// Server tools run on the server once approved. The client tools are passed as
34// bare definitions so the server pauses on them (client-tool-execution) and the
35// browser runs them after approval.
36const tools = [
37 admitRescue.server(async ({ name }) => ({
38 intakeId: `intake_${name.toLowerCase()}`,
39 status: 'admitted to intake ward',
40 })),
41 scheduleVetCheck.server(async ({ animal, urgency }) => ({
42 visitId: `visit_${animal.toLowerCase()}_${urgency}`,
43 })),
44 finalizeAdoption.server(async ({ animal, adopter }) => ({
45 certificateId: `cert_${animal.toLowerCase()}_${adopter.split(' ')[0]?.toLowerCase() ?? 'home'}`,
46 })),
47 assignEnclosure.server(async ({ animal, enclosure, sizeSqm }) => ({
48 assignmentId: `${enclosure.toLowerCase()}_${animal.toLowerCase()}`,
49 enclosure,
50 sizeSqm,
51 })),
52 printIntakeTag,
53 logFieldSighting,
54 shareAdoptionStory,
55 printCertificate,
57​
58export const feedingInterruptId = (runId: string): string => `feeding_${runId}`
59​
60/**
61 * Decide the provider tool_choice for a run. Only the FIRST turn is shaped:
62 * a button may force one tool, or the generic scenario forbids tools ('none').
63 * A continuation (resume) never forces a choice, otherwise the model would
64 * re-call the approved tool instead of answering.
65 */
66export function resolveToolChoice(input: {
67 isResume: boolean
68 generic?: boolean
69 forceTool?: string
70}): 'none' | { type: 'function'; name: string } | undefined {
71 if (input.isResume) return undefined
72 if (input.generic) return 'none'
73 if (typeof input.forceTool === 'string') {
74 return { type: 'function', name: input.forceTool }
75 }
76 return undefined
78​
79/**
80 * Emits the generic "feeding schedule" interrupt: a non-tool application pause.
81 * The plain success terminal of the run is replaced with an interrupt outcome
82 * carrying a wire responseSchema, and on the continuation the keeper's answer is
83 * validated here (the library does not validate generic values) and appended.
84 */
85export function createFeedingMiddleware(): ChatMiddleware {
86 const responseSchemaHash = digestInterruptJson(
87 canonicalInterruptJson(feedingScheduleResponseSchema),
88 )
89 const validate = z.fromJSONSchema(
90 feedingScheduleResponseSchema as unknown as Parameters<
91 typeof z.fromJSONSchema
92 >[0],
93 )
94 let isContinuation = false
95​
96 return {
97 name: 'sanctuary-feeding-schedule',
98 onConfig(ctx, config) {
99 if (ctx.phase !== 'init' || (config.resume?.length ?? 0) === 0) return
100 isContinuation = true
101 const interruptedRunId = ctx.parentRunId
102 if (!interruptedRunId) {
103 throw new Error('Feeding continuation requires parentRunId.')
104 }
105 const expectedId = feedingInterruptId(interruptedRunId)
106 const resolution = config.resume?.[0]
107 if (
108 config.resume?.length !== 1 ||
109 resolution?.interruptId !== expectedId
110 ) {
111 throw new Error(`Feeding continuation must resolve only ${expectedId}.`)
112 }
113​
114 let prompt: string
115 if (resolution.status === 'cancelled') {
116 prompt =
117 'The keeper cancelled the feeding schedule. Acknowledge briefly.'
118 } else {
119 const parsed = validate.safeParse(resolution.payload)
120 if (!parsed.success) {
121 throw new Error(
122 `Invalid feeding schedule: ${parsed.error.issues
123 .map((issue) => issue.message)
124 .join('; ')}`,
125 )
126 }
127 prompt = `The keeper set this feeding schedule: ${JSON.stringify(parsed.data)}. Confirm it briefly.`
128 }
129​
130 return {
131 messages: [...config.messages, { role: 'user', content: prompt }],
132 resume: undefined,
133 }
134 },
135 onChunk(ctx, chunk) {
136 if (
137 isContinuation ||
138 chunk.type !== EventType.RUN_FINISHED ||
139 (chunk.outcome !== undefined && chunk.outcome.type !== 'success')
140 ) {
141 return
142 }
143 // Correlate on the client's request run id (`ctx.runId`), which is what
144 // the client sends back as `parentRunId` on the continuation. A provider
145 // may stamp `chunk.runId` with its own id (e.g. `openai-…`) that differs.
146 const interruptedRunId = ctx.runId
147 const interruptId = feedingInterruptId(interruptedRunId)
148 return {
149 ...chunk,
150 outcome: {
151 type: 'interrupt',
152 interrupts: [
153 {
154 id: interruptId,
155 reason: 'sanctuary:feeding_schedule',
156 message: 'Choose a feeding schedule for this animal.',
157 responseSchema: feedingScheduleResponseSchema,
158 metadata: {
159 kind: 'generic',
160 'tanstack:interruptBinding': {
161 kind: 'generic',
162 interruptId,
163 interruptedRunId,
164 generation: 0,
165 responseSchemaHash,
166 },
167 },
168 },
169 ],
170 },
171 }
172 },
173 }
175​
176async function handle(request: Request): Promise<Response> {
177 const apiKey = process.env.OPENAI_API_KEY
178 if (!apiKey) {
179 return new Response(
180 JSON.stringify({
181 error: 'Set OPENAI_API_KEY in examples/ts-react-chat/.env',
182 }),
183 { status: 500, headers: { 'content-type': 'application/json' } },
184 )
185 }
186​
187 let params
188 try {
189 params = await chatParamsFromRequestBody(await request.json())
190 } catch (error) {
191 return new Response(
192 error instanceof Error ? error.message : 'Bad request',
193 {
194 status: 400,
195 },
196 )
197 }
198​
199 const forwarded = params.forwardedProps as {
200 forceTool?: string
201 generic?: boolean
202 }
203 const abortController = new AbortController()
204​
205 const toolChoice = resolveToolChoice({
206 isResume: (params.resume?.length ?? 0) > 0,
207 generic: forwarded.generic,
208 forceTool: forwarded.forceTool,
209 })
210​
211 const stream = chat({
212 adapter: createOpenaiChat('gpt-5.5', apiKey),
213 messages: params.messages,
214 tools,
215 systemPrompts: [SYSTEM_PROMPT],
216 agentLoopStrategy: maxIterations(8),
217 threadId: params.threadId,
218 runId: params.runId,
219 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
220 ...(params.resume ? { resume: params.resume } : {}),
221 ...(forwarded.generic ? { middleware: [createFeedingMiddleware()] } : {}),
222 ...(toolChoice !== undefined
223 ? { modelOptions: { tool_choice: toolChoice } }
224 : {}),
225 abortController,
226 })
227​
228 return toServerSentEventsResponse(stream)
230​
231export const Route = createFileRoute('/api/interrupts')({
232 server: {
233 handlers: {
234 POST: ({ request }) => handle(request),
235 },
236 },
237})