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

api.generic-interrupts.ts

134 lines3.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { createOpenaiChat } from '@tanstack/ai-openai'
9import {
10 AUDIENCE_OPTIONS,
11 chooseAudience,
12 inspectPlan,
13 playgroundInterrupts,
14 readPlaygroundForwarded,
15 reviewPlan,
16} from '@/lib/generic-interrupt-playground'
17import type {
18 ChatMiddleware,
19 InterruptBoundaryPhase,
20 InterruptToolResume,
21} from '@tanstack/ai'
22​
23const SYSTEM_PROMPT =
24 'You are a planning assistant. When the user asks you to inspect a plan, ' +
25 'call inspectPlan with the plan id from their message. Keep spoken replies short.'
26​
27function createLifecycleMiddleware(
28 boundary: InterruptBoundaryPhase,
29 policy: InterruptToolResume,
30): ChatMiddleware<unknown, (typeof playgroundInterrupts)[number]> {
31 return {
32 name: 'generic-interrupt-playground',
33 onInterruptBoundary(ctx) {
34 if (ctx.phase !== boundary || ctx.parentRunId) return
35 return {
36 interrupts: [
37 reviewPlan.interrupt({
38 key: `${boundary}-review`,
39 reason: 'review_required',
40 message: `Review the plan at ${ctx.phase}.`,
41 payload: {
42 title: 'Playground review plan',
43 boundary: ctx.phase,
44 },
45 }),
46 chooseAudience.interrupt({
47 key: `${boundary}-audience`,
48 reason: 'audience_required',
49 message: 'Pick who this reply is for.',
50 payload: {
51 question: 'Who should the next reply speak to?',
52 options: Array.from(AUDIENCE_OPTIONS),
53 },
54 }),
55 ],
56 }
57 },
58 onInterruptResolution(_ctx, resolutions) {
59 for (const resolution of resolutions.for(reviewPlan)) {
60 if (resolution.status === 'resolved' && !resolution.response.approved) {
61 return { toolResume: 'stop' }
62 }
63 }
64 return { toolResume: policy }
65 },
66 }
68​
69async function handle(request: Request): Promise<Response> {
70 const apiKey = process.env.OPENAI_API_KEY
71 if (!apiKey) {
72 return new Response(
73 JSON.stringify({
74 error: 'Set OPENAI_API_KEY in examples/ts-react-chat/.env',
75 }),
76 { status: 500, headers: { 'content-type': 'application/json' } },
77 )
78 }
79​
80 let params
81 try {
82 params = await chatParamsFromRequestBody(await request.json())
83 } catch (error) {
84 return new Response(
85 error instanceof Error ? error.message : 'Bad request',
86 { status: 400 },
87 )
88 }
89​
90 const { boundary, policy } = readPlaygroundForwarded(params.forwardedProps)
91 const isResume = (params.resume?.length ?? 0) > 0
92 const needsTool = boundary === 'beforeTools' || boundary === 'afterTools'
93 const tools = needsTool
94 ? [
95 inspectPlan.server(async ({ planId }) => ({
96 inspected: true,
97 planId,
98 })),
99 ]
100 : []
101 const abortController = new AbortController()
102​
103 const stream = chat({
104 adapter: createOpenaiChat('gpt-5.5', apiKey),
105 messages: params.messages,
106 tools,
107 systemPrompts: [SYSTEM_PROMPT],
108 agentLoopStrategy: maxIterations(8),
109 threadId: params.threadId,
110 runId: params.runId,
111 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
112 ...(params.resume ? { resume: params.resume } : {}),
113 interrupts: playgroundInterrupts,
114 middleware: [createLifecycleMiddleware(boundary, policy)],
115 ...(!isResume && needsTool
116 ? {
117 modelOptions: {
118 tool_choice: { type: 'function', name: inspectPlan.name },
119 },
120 }
121 : {}),
122 abortController,
123 })
124​
125 return toServerSentEventsResponse(stream, { abortController })
127​
128export const Route = createFileRoute('/api/generic-interrupts')({
129 server: {
130 handlers: {
131 POST: ({ request }) => handle(request),
132 },
133 },
134})