Open History to see the last commit
1---
2title: Subagents
3id: subagents
4order: 4
5description: "Give some turns to a named child agent, such as a researcher or a writer. The parent chat stays one conversation, and the UI shows the child as a card."
6keywords:
7 - tanstack ai
8 - subagents
9 - defineAgent
10 - router
11 - sandbox
12 - AG-UI
13---
14
15A subagent runs one job, such as research or a sandbox task, inside the same conversation. The user still sees one thread.
16
17A subagent is a named child agent. Give it to `chat({ subagents })`, and the parent model can start it like a tool. The client shows the work of the child as a card inside the assistant message.
18
19Want a full TanStack Start app with a researcher, an SEO agent, and a writer? Open the [Subagents tutorial](../tutorials/subagents).
20
21## Quick setup
22
23### 1. Define a child and give it to `chat()`
24
25`run` is the work of the child. Here it is a chat call with its own model. `ctx.chat` fills in the ids, the parent conversation, and the abort signal for you.
26
27```ts
28// api/chat.ts
29import {
30 chat,
31 chatParamsFromRequest,
32 defineAgent,
33 toServerSentEventsResponse,
34} from '@tanstack/ai'
35import { openaiText } from '@tanstack/ai-openai'
36
37const researcher = defineAgent({
38 name: 'researcher',
39 description: 'Looks up facts and sources',
40 run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol') }),
41})
42
43export async function POST(request: Request) {
44 const params = await chatParamsFromRequest(request)
45 const stream = chat({
46 adapter: openaiText('gpt-6.1-sol'),
47 messages: params.messages,
48 threadId: params.threadId,
49 runId: params.runId,
50 subagents: { agents: [researcher] },
51 })
52 return toServerSentEventsResponse(stream)
53}
54```
55
56### 2. Show the child in the client
57
58A child arrives as a part with `type: 'subagent'`. Show its name, its status, and its text:
59
60```tsx
61import { useState } from 'react'
62import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
63
64export function Chat() {
65 const [input, setInput] = useState('')
66 const { messages, sendMessage } = useChat({
67 connection: fetchServerSentEvents('/api/chat'),
68 threadId: 'support-chat',
69 })
70
71 return (
72 <>
73 {messages.map((message) => (
74 <div key={message.id}>
75 {message.parts.map((part, index) => {
76 if (part.type === 'text') {
77 return <p key={index}>{part.content}</p>
78 }
79 if (part.type === 'subagent') {
80 return (
81 <section key={part.subagent.id}>
82 <strong>
83 {part.subagent.name} ({part.subagent.status})
84 </strong>
85 {part.subagent.messages.flatMap((child) =>
86 child.parts.map((childPart, childIndex) =>
87 childPart.type === 'text' ? (
88 <p key={`${child.id}-${childIndex}`}>
89 {childPart.content}
90 </p>
91 ) : null,
92 ),
93 )}
94 </section>
95 )
96 }
97 return null
98 })}
99 </div>
100 ))}
101 <form
102 onSubmit={(event) => {
103 event.preventDefault()
104 if (input.trim() === '') {
105 return
106 }
107 sendMessage(input)
108 setInput('')
109 }}
110 >
111 <input value={input} onChange={(event) => setInput(event.target.value)} />
112 <button type="submit">Send</button>
113 </form>
114 </>
115 )
116}
117```
118
119### 3. Try it
120
121Send "Find three facts about squids". The parent model calls the `researcher` tool. A `researcher` card appears with the status `running`, fills with the text of the child, and then shows `finished`.
122
123## How it works
124
125- The library adds one server tool for each agent. The parent model decides when to call it, and it can also skip it.
126- The model can pass the task as `prompt`. The child gets it as the last user message, after the conversation as it is at that tool call.
127- The events of the child stream while the tool runs. Each event carries `subagentRunId`, between `SUBAGENT_STARTED` and `SUBAGENT_FINISHED` (or `SUBAGENT_ERROR`).
128- The client puts that work in a `type: 'subagent'` part. The UI does not show it as a normal tool card.
129- The text of the child becomes the tool result, and the parent model continues from there.
130- The parent `RUN_FINISHED.usage` includes the token usage of every child.
131
132A child can use tools, MCP, interrupts, and its own nested `subagents`. It can also return a plain value or make an image. See [Return a value, or call any activity](./subagents-advanced#return-a-value-or-call-any-activity).
133
134## Route, or let the model pick
135
136Without a router, the parent model picks the child. With a router, your code picks it, and the library sends no subagent tools to the model.
137
138Put all spawn options on `subagents`. Do not put `agents` or `router` on the root of `chat()`.
139
140Here a Jev decider picks the target. Its `choice` options must include `main` plus every agent name:
141
142```ts
143import { chat, choice, decide, defineAgent } from '@tanstack/ai'
144import { openaiText } from '@tanstack/ai-openai'
145import { typesafeDecider } from '@tanstack/ai-typesafe'
146
147const messages = [{ role: 'user' as const, content: 'Capital of France?' }]
148
149const researcher = defineAgent({
150 name: 'researcher',
151 description: 'Looks up facts and sources',
152 run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol') }),
153})
154
155const stream = chat({
156 adapter: openaiText('gpt-6.1-sol'),
157 messages,
158 threadId: 'thread-1',
159 subagents: {
160 agents: [researcher],
161 strategy: 'exclusive',
162 router: async ({ agents }) => {
163 const result = await decide({
164 adapter: typesafeDecider('jev-latest'),
165 state: messages,
166 questions: {
167 target: choice({
168 instructions: 'Who must handle this turn?',
169 options: {
170 main: 'General chat',
171 ...Object.fromEntries(
172 agents.map((agent) => [agent.name, agent.description]),
173 ),
174 },
175 }),
176 },
177 })
178 return result.target.value
179 },
180 },
181})
182```
183
184The router returns `'main'` to keep the turn on the parent, or an agent name. `strategy` sets what happens after the child:
185
186- `exclusive` (default): the chosen child owns the turn. Main does not answer after it.
187- `handoff`: the child streams first. Then main runs with the new child text in the messages.
188
189A router can also start several agents, in parallel or one after another, and give each one an input. See [Router picks](./subagents-advanced#router-picks).
190
191## Let the model write the brief
192
193In a long thread, the child gets the full conversation at the tool call, with every earlier tool result. Each parallel child gets its own copy, and the child must find its task in it.
194
195Add `inputSchema` to the agent. The parent model then writes the input of the child when it calls the tool. `run` reads that input as `ctx.input`:
196
197```ts
198import { chat, defineAgent } from '@tanstack/ai'
199import { openaiText } from '@tanstack/ai-openai'
200import { z } from 'zod'
201
202const messages = [
203 { role: 'user' as const, content: 'Compare pricing for the vendors we picked' },
204]
205
206const researcher = defineAgent({
207 name: 'researcher',
208 description: 'Researches one focused question and returns sourced findings',
209 inputSchema: z.object({
210 task: z
211 .string()
212 .describe('What to find and what to return. The researcher sees only this text.'),
213 }),
214 run: (ctx) =>
215 chat({
216 adapter: openaiText('gpt-6.1-sol'),
217 messages: [{ role: 'user', content: ctx.input.task }],
218 threadId: ctx.threadId,
219 runId: ctx.runId,
220 parentRunId: ctx.parentRunId,
221 subagentRunId: ctx.subagentRunId,
222 resume: ctx.resume,
223 }),
224})
225
226const stream = chat({
227 adapter: openaiText('gpt-6.1-sol'),
228 messages,
229 threadId: 'thread-1',
230 subagents: { agents: [researcher] },
231})
232```
233
234- `ctx.input` has the type of the schema. Here it is `{ task: string }`.
235- If the input does not match the schema, the model gets a tool error and can call the tool again. The child does not start.
236- `ctx.messages` still holds the parent conversation. If the child needs more context, add parts of it.
237- A resumed child gets the same `ctx.input` as the first run.
238
239When you call the plain `chat()` in `run`, pass every `ctx` id and `resume` to it, as in this sample. A child that stops for an approval needs `parentRunId` and `resume` to continue. `...ctx.forward` passes all of them in one spread.
240
241To show the brief on the card, see [Show the brief on a card](./subagents-advanced#show-the-brief-on-a-card).
242
243## Continue a child
244
245Each tool call starts a new child. Sometimes the model must send a follow-up to a child that already answered, like "make it shorter".
246
247Add `withPersistence` to the parent `chat()`. Each result then gives the model the `subagentRunId` of the child, and the model continues that child with `sessionId`:
248
249```ts
250import {
251 chat,
252 chatParamsFromRequest,
253 defineAgent,
254 toServerSentEventsResponse,
255} from '@tanstack/ai'
256import { openaiText } from '@tanstack/ai-openai'
257import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
258
259const writer = defineAgent({
260 name: 'writer',
261 description: 'Writes and edits drafts',
262 run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol') }),
263})
264
265// A continued child loads from this store. Use a durable backend in production.
266const persistence = memoryPersistence()
267
268export async function POST(request: Request) {
269 const params = await chatParamsFromRequest(request)
270 const stream = chat({
271 adapter: openaiText('gpt-6.1-sol'),
272 messages: params.messages,
273 threadId: params.threadId,
274 runId: params.runId,
275 middleware: [withPersistence(persistence)],
276 subagents: { agents: [writer] },
277 })
278 return toServerSentEventsResponse(stream)
279}
280```
281
282The model continues the writer like this:
283
2841. The model calls `writer` with `{ "prompt": "Draft a post about tides" }`.
2852. It gets `{ "subagentRunId": "subagent-1767225600000-x7k2m9q", "result": "Tides rise twice a day..." }`.
2863. In a later turn, it calls `writer` with `{ "sessionId": "subagent-1767225600000-x7k2m9q", "prompt": "Make it shorter" }`.
287
288The writer gets the task of its first call, its stored transcript, then `Make it shorter` as the last user message. The stream uses the same `subagentRunId`, so the client shows the new work on the same card.
289
290For every field of the tool input, and the errors a wrong call gets, see [The tool input](./subagents-advanced#the-tool-input).
291
292## Interrupts in a child
293
294Some child work needs a person first, for example deleting a file. Give that child tool `needsApproval: true`. The child stops, and the parent run ends with the interrupt of the child. The client answers it like any other interrupt, and the next run continues the same child.
295
2961. Share one tool definition between the server and the client:
297
298```typescript title="tools.ts"
299import { toolDefinition } from '@tanstack/ai'
300import { z } from 'zod'
301
302export const deleteFile = toolDefinition({
303 name: 'deleteFile',
304 description: 'Delete a file',
305 needsApproval: true,
306 inputSchema: z.object({ path: z.string() }),
307})
308```
309
3102. Give the child the server tool. Pass the resume fields from the request to the parent `chat()`:
311
312```typescript title="route.ts"
313import {
314 chat,
315 chatParamsFromRequest,
316 defineAgent,
317 toServerSentEventsResponse,
318} from '@tanstack/ai'
319import { openaiText } from '@tanstack/ai-openai'
320import { deleteFile } from './tools'
321
322const cleaner = defineAgent({
323 name: 'cleaner',
324 description: 'Deletes old files',
325 run: (ctx) =>
326 chat({
327 adapter: openaiText('gpt-6.1-sol'),
328 messages: ctx.messages,
329 threadId: ctx.threadId,
330 runId: ctx.runId,
331 parentRunId: ctx.parentRunId,
332 subagentRunId: ctx.subagentRunId,
333 resume: ctx.resume,
334 tools: [deleteFile.server(({ path }: { path: string }) => ({ deleted: path }))],
335 }),
336})
337
338export async function POST(request: Request) {
339 const params = await chatParamsFromRequest(request)
340 const stream = chat({
341 adapter: openaiText('gpt-6.1-sol'),
342 messages: params.messages,
343 threadId: params.threadId,
344 runId: params.runId,
345 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
346 ...(params.resume ? { resume: params.resume } : {}),
347 subagents: { agents: [cleaner], router: () => 'cleaner' },
348 })
349
350 return toServerSentEventsResponse(stream)
351}
352```
353
3543. Register the same definition on the client, and answer the interrupt:
355
356```tsx title="cleanup-panel.tsx"
357import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
358import { deleteFile } from './tools'
359
360export function CleanupPanel() {
361 const chat = useChat({
362 connection: fetchServerSentEvents('/api/chat'),
363 threadId: 'support-chat',
364 tools: [deleteFile.client()],
365 })
366
367 return (
368 <section>
369 <button onClick={() => chat.sendMessage('Clean up old files')}>
370 Clean up
371 </button>
372 {chat.interrupts.map((interrupt) =>
373 interrupt.kind === 'tool-approval' ? (
374 <button key={interrupt.id} onClick={() => interrupt.resolveInterrupt(true)}>
375 Approve delete
376 </button>
377 ) : null,
378 )}
379 </section>
380 )
381}
382```
383
384While the child waits, its card has `status: 'suspended'` and `interruptIds`. After you approve, the card shows the tool result and the reply of the child. Client tools in a child work the same way.
385
386How the resume continues:
387
388- With a router, the resume uses the plan that the router picked in the first run. It does not call the router again. If the router gave an agent of that plan an input, the resume fails.
389- Without a router, the tool call of the child stays open until the resume. Then the parent model reads the result of the child.
390- The result content carries the output or the error of the child. It carries `subagentRunId` only when the model can continue the child: with a persistence store, or for a background child. Otherwise the id stays in the subagent events.
391
392## Limit the tree
393
394A child can have children of its own, and a model can call a child many times. Set `limits` so one request cannot start a tree with no end:
395
396```ts
397import { chat, defineAgent } from '@tanstack/ai'
398import { openaiText } from '@tanstack/ai-openai'
399
400const researcher = defineAgent({
401 name: 'researcher',
402 description: 'Looks up facts',
403 run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol') }),
404})
405
406const stream = chat({
407 adapter: openaiText('gpt-6.1-sol'),
408 messages: [{ role: 'user', content: 'Research squids in depth' }],
409 threadId: 'thread-1',
410 subagents: {
411 agents: [researcher],
412 limits: { maxDepth: 2, maxConcurrent: 3, maxCalls: 12, timeoutMs: 120_000 },
413 },
414})
415```
416
417- `maxDepth`: how deep the tree can grow. The first chat is depth 0.
418- `maxCalls`: how many children the whole tree can start.
419- `maxConcurrent`: how many children one run can have running at the same time.
420- `timeoutMs`: how long one child can run. A child never gets more time than its parent has left.
421
422A refused start reaches the model as a tool error, for example `subagent limit reached (maxCalls 12)`. For the full list, see [Limit details](./subagents-advanced#limit-details).
423
424## Persistence
425
426Put `withPersistence` on the parent `chat()` only. The parent stores each child:
427
428- the child run, linked to the parent run
429- the full child transcript
430- the pending interrupts of the child
431- the card status
432
433A reload then shows every card, and a resume continues a waiting child. See [Subagent cards on reload](../persistence/chat-persistence-advanced#subagent-cards-on-reload).
434
435> [!WARNING]
436> Do not add `withPersistence` to a child `chat()` too. The child does not know that it runs as a subagent, so it stores the same child again under its own run and thread ids. Its interrupt records then conflict with the records of the parent, and a reload can lose the pending approval.
437
438## Advanced
439
440For router plans, the tool input, value results, keys, middleware, sandboxes, and custom cards with `createChatHook`, see [Subagents: Advanced](./subagents-advanced).