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

api.subagents-test.ts

153 lines5.1 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 defineAgent,
6 maxIterations,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import { z } from 'zod'
10import type { DefinedAgent, Tool } from '@tanstack/ai'
11import { createTextAdapter } from '@/lib/providers'
12import {
13 deleteLogs,
14 isSubagentScenario,
15 lookupFacts,
16} from '@/lib/subagents-test'
17import type { SubagentScenario } from '@/lib/subagents-test'
18​
19/**
20 * Subagent harness. Every child is a real `chat()` on the OpenAI adapter
21 * against aimock, so the child's reasoning, tool calls, and approval go
22 * through the same path as an app.
23 *
24 * - `route`: a router picks `researcher`. The child thinks, calls a server
25 * tool, then answers.
26 * - `approval`: a router picks `cleaner`. The child's tool needs approval,
27 * so the parent run ends with the child's interrupt. The resume continues
28 * the same child.
29 * - `tool`: no router. The parent model calls the `researcher` tool, the
30 * child answers, and the parent reads its result.
31 * - `brief`: no router. The parent model writes a `task` for `researcher`,
32 * and the child's only message is that task.
33 */
34function subagentsFor(
35 scenario: SubagentScenario,
36 aimockPort: number | undefined,
37 testId: string | undefined,
38) {
39 const child = (
40 name: string,
41 tools: Array<Tool>,
42 model?: string,
43 modelOptions?: Record<string, unknown>,
44 ) =>
45 defineAgent({
46 name,
47 description: `${name} agent`,
48 run: (ctx) =>
49 chat({
50 ...createTextAdapter('openai', model, aimockPort, testId),
51 messages: ctx.messages,
52 threadId: ctx.threadId,
53 runId: ctx.runId,
54 parentRunId: ctx.parentRunId,
55 subagentRunId: ctx.subagentRunId,
56 resume: ctx.resume,
57 tools,
58 ...(modelOptions ? { modelOptions } : {}),
59 agentLoopStrategy: maxIterations(4),
60 }),
61 })
62​
63 if (scenario === 'route') {
64 const researcher = child(
65 'researcher',
66 [lookupFacts.server(({ topic }) => ({ topic, facts: ['three hearts'] }))],
67 'o3',
68 { reasoning: { effort: 'high' } },
69 )
70 return { agents: [researcher], router: () => 'researcher' }
71 }
72 if (scenario === 'approval') {
73 const cleaner = child('cleaner', [
74 deleteLogs.server(({ folder }) => ({ deleted: folder })),
75 ])
76 return { agents: [cleaner], router: () => 'cleaner' }
77 }
78 if (scenario === 'brief') {
79 const researcher = defineAgent({
80 name: 'researcher',
81 description: 'Researches one focused task',
82 inputSchema: z.object({ task: z.string() }),
83 run: (ctx) =>
84 chat({
85 ...createTextAdapter('openai', undefined, aimockPort, testId),
86 messages: [{ role: 'user', content: ctx.input.task }],
87 threadId: ctx.threadId,
88 runId: ctx.runId,
89 parentRunId: ctx.parentRunId,
90 subagentRunId: ctx.subagentRunId,
91 resume: ctx.resume,
92 }),
93 })
94 // Each branch returns its own bag, so give them one agent type.
95 const agents: Array<DefinedAgent> = [researcher]
96 return { agents }
97 }
98 return { agents: [child('researcher', [])] }
100​
101export const Route = createFileRoute('/api/subagents-test')({
102 server: {
103 handlers: {
104 POST: async ({ request }) => {
105 if (request.signal?.aborted) return new Response(null, { status: 499 })
106 let params
107 try {
108 params = await chatParamsFromRequestBody(await request.json())
109 } catch (error) {
110 return new Response(
111 error instanceof Error ? error.message : 'Bad request',
112 { status: 400 },
113 )
114 }
115​
116 const fp = params.forwardedProps
117 const scenario = isSubagentScenario(fp.scenario) ? fp.scenario : 'route'
118 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
119 const aimockPort =
120 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
121 const abortController = new AbortController()
122​
123 try {
124 const stream = chat({
125 ...createTextAdapter('openai', undefined, aimockPort, testId),
126 messages: params.messages,
127 threadId: params.threadId,
128 runId: params.runId,
129 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
130 ...(params.resume ? { resume: params.resume } : {}),
131 subagents: subagentsFor(scenario, aimockPort, testId),
132 agentLoopStrategy: maxIterations(4),
133 abortController,
134 })
135 return toServerSentEventsResponse(stream, { abortController })
136 } catch (error) {
137 if (
138 (error instanceof Error && error.name === 'AbortError') ||
139 abortController.signal.aborted
140 ) {
141 return new Response(null, { status: 499 })
142 }
143 const message =
144 error instanceof Error ? error.message : 'An error occurred'
145 return new Response(JSON.stringify({ error: message }), {
146 status: 500,
147 headers: { 'Content-Type': 'application/json' },
148 })
149 }
150 },
151 },
152 },
153})