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

subagents.md

865 lines28.1 KB

1---
2title: Subagents
3id: subagents-tutorial
4order: 5
5description: "Create a TanStack Start blog-writing chat. Three named agents handle research, drafts, and SEO. Jev on OpenRouter picks who runs, and can start research and SEO together. createChatHook draws a nested card."
6keywords:
7 - tanstack ai
8 - tutorial
9 - subagents
10 - defineAgent
11 - jev
12 - openrouter
13 - createChatHook
14 - tanstack start
15---
16​
17You want a blog-writing chat. Some turns need facts. Some turns need a draft. Some turns need SEO titles. One main model is a poor fit for every turn.
18​
19This tutorial adds three named agents. Jev on OpenRouter picks who runs. Research and SEO can start together. `createChatHook` draws a nested card for each child.
20​
21This tutorial is React + Start. For the API, open [Subagents](../chat/subagents).
22​
23You can skip the scaffold and paste a key in the sandbox at the end of this page.
24​
25## 1. Create a Start app
26​
27```bash
28npx @tanstack/cli@latest create
29```
30​
31Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
32​
33## 2. Install packages
34​
35You need the core SDK, the React UI factory, and OpenRouter for chat and for Jev.
36​
37<!-- ::start:tabs variant="package-manager" mode="install" -->
38​
39react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openrouter @tanstack/react-devtools @tanstack/react-ai-devtools
40​
41<!-- ::end:tabs -->
42​
43## 3. Client and server
44​
45A chat has two sides.
46​
47The **client** runs in the browser. It holds the OpenRouter key, draws messages, and POSTs to your route.
48​
49The **server** route reads that key, asks Jev who must run, and streams tokens back.
50​
51The next steps build the client pieces. Then they add the agents and the route.
52​
53## 4. Set up BYOK on the client
54​
55Create `src/lib/byok.ts`. `memoryStorage()` keeps the OpenRouter key in this tab.
56​
57```typescript
58import { defineByok, memoryStorage } from '@tanstack/ai-react/byok'
59import { openrouterByok } from '@tanstack/ai-openrouter/byok'
60​
61export const byok = defineByok({
62 storage: memoryStorage(),
63 providers: [openrouterByok],
64})
65```
66​
67Get an OpenRouter key from [openrouter.ai](https://openrouter.ai). Chat and Jev both use this key.
68​
69## 5. Add the key form
70​
71Create `src/components/open-router-key-form.tsx`. Export `OpenRouterKeyForm` from that file. `byok.update` saves the key. `useByok` reads the status.
72​
73```tsx ignore
74import { useState } from 'react'
75import { openrouterByok } from '@tanstack/ai-openrouter/byok'
76import { useByok } from '@tanstack/ai-react'
77import { byok } from '@/lib/byok'
78​
79export function OpenRouterKeyForm() {
80 const snapshot = useByok(byok)
81 const [draft, setDraft] = useState('')
82 const [error, setError] = useState('')
83 const status = snapshot.status[openrouterByok.id]
84 const masked = status && 'masked' in status ? status.masked : undefined
85 const missingKey = snapshot.prompt?.reason === 'missing'
86​
87 return (
88 <form
89 className="flex flex-col gap-2 sm:flex-row sm:items-center"
90 onSubmit={(event) => {
91 event.preventDefault()
92 const next = draft.trim()
93 if (!next) return
94 setError('')
95 void byok
96 .update(openrouterByok.id, next)
97 .then(() => setDraft(''))
98 .catch((caught: unknown) =>
99 setError(
100 caught instanceof Error ? caught.message : 'Could not save key',
101 ),
102 )
103 }}
104 >
105 <label className="sr-only" htmlFor="openrouter-key">
106 OpenRouter API key
107 </label>
108 <input
109 id="openrouter-key"
110 type="password"
111 autoComplete="off"
112 spellCheck={false}
113 placeholder={masked ? `Saved ${masked}` : 'Paste your OpenRouter key'}
114 value={draft}
115 onChange={(event) => setDraft(event.target.value)}
116 className="min-w-0 flex-1 rounded-lg border border-orange-500/20 bg-gray-900 px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500/50"
117 />
118 <div className="flex gap-2">
119 <button
120 type="submit"
121 disabled={!draft.trim()}
122 className="rounded-lg bg-orange-500 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
123 >
124 Save key
125 </button>
126 {masked ? (
127 <button
128 type="button"
129 className="rounded-lg border border-gray-600 px-3 py-2 text-sm text-gray-200"
130 onClick={() => {
131 setError('')
132 void byok
133 .clear(openrouterByok.id)
134 .catch((caught: unknown) =>
135 setError(
136 caught instanceof Error
137 ? caught.message
138 : 'Could not clear key',
139 ),
140 )
141 }}
142 >
143 Clear
144 </button>
145 ) : null}
146 </div>
147 {missingKey ? (
148 <p className="text-xs text-amber-400">
149 Paste an OpenRouter key, then send again.
150 </p>
151 ) : null}
152 {error ? <p className="text-xs text-red-400">{error}</p> : null}
153 </form>
154 )
156```
157​
158If you want passkeys, open [Bring Your Own Key](../advanced/byok).
159​
160## 6. Define three agents
161​
162Create `src/lib/blog-agents.ts`. It declares each agent once: `name` is the id the router returns, and `description` is the text Jev reads. The file holds no server code, so the browser can import it too.
163​
164```typescript ignore
165// Shared by the server and the browser, so it holds no server code. The
166// server adds `run` in `agents.ts`. The browser passes the list to the chat
167// UI factory for types.
168export const researcher = {
169 name: 'researcher',
170 description:
171 'Does this turn need facts or sources? Answer yes when the user asks to look something up, even if they also ask for a draft or for SEO. Answer no when they do not ask to look anything up.',
172} as const
173​
174export const writer = {
175 name: 'writer',
176 description:
177 'Does this turn need a written article, post, or rewrite? Answer yes only when the user asks for an article, post, draft, or rewrite. Answer no when they ask for research or SEO and do not ask for an article.',
178} as const
179​
180export const seo = {
181 name: 'seo',
182 description:
183 'Does this turn need SEO work? Answer yes when the user asks for SEO, search titles, a meta description, or tags. Answer no when they do not mention SEO, titles, a meta description, or tags.',
184} as const
185​
186export const blogAgents = [researcher, writer, seo] as const
187```
188​
189Create `src/lib/agents.ts`. `defineAgent` spreads each declaration and adds `run`, a full `chat()` call. Pass `ctx.threadId`, `ctx.runId`, `ctx.parentRunId`, `ctx.subagentRunId`, and `ctx.resume` into that call.
190​
191The parent `chat({ subagents: { agents } })` owns the list. It does not call `run` until a turn picks that name.
192​
193```typescript ignore
194import { chat, defineAgent } from '@tanstack/ai'
195import { createOpenRouterText } from '@tanstack/ai-openrouter'
196import { researcher, seo, writer } from '@/lib/blog-agents'
197​
198function linkAbort(signal: AbortSignal | undefined) {
199 const abortController = new AbortController()
200 if (signal === undefined) return abortController
201 if (signal.aborted) {
202 abortController.abort()
203 return abortController
204 }
205 signal.addEventListener(
206 'abort',
207 () => {
208 abortController.abort()
209 },
210 { once: true },
211 )
212 return abortController
214​
215export function createBlogAgents(apiKey: string) {
216 const researcherAgent = defineAgent({
217 ...researcher,
218 run: (ctx) =>
219 chat({
220 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
221 messages: ctx.messages,
222 threadId: ctx.threadId,
223 runId: ctx.runId,
224 parentRunId: ctx.parentRunId,
225 subagentRunId: ctx.subagentRunId,
226 resume: ctx.resume,
227 abortController: linkAbort(ctx.abortSignal),
228 systemPrompts: [
229 'You research for a blog desk. Reply in Markdown with short notes and sources. Use a list. Do not write the full post.',
230 ],
231 }),
232 })
233​
234 const writerAgent = defineAgent({
235 ...writer,
236 run: (ctx) =>
237 chat({
238 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
239 messages: ctx.messages,
240 threadId: ctx.threadId,
241 runId: ctx.runId,
242 parentRunId: ctx.parentRunId,
243 subagentRunId: ctx.subagentRunId,
244 resume: ctx.resume,
245 abortController: linkAbort(ctx.abortSignal),
246 systemPrompts: [
247 'You write blog posts in Markdown. Start with one # title. Use short ## sections and a closing line. When earlier messages contain research notes or SEO text, write only from those messages. Do not add facts that are not in those messages.',
248 ],
249 }),
250 })
251​
252 const seoAgent = defineAgent({
253 ...seo,
254 run: (ctx) =>
255 chat({
256 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
257 messages: ctx.messages,
258 threadId: ctx.threadId,
259 runId: ctx.runId,
260 parentRunId: ctx.parentRunId,
261 subagentRunId: ctx.subagentRunId,
262 resume: ctx.resume,
263 abortController: linkAbort(ctx.abortSignal),
264 systemPrompts: [
265 'You prepare SEO for a blog post. Reply in Markdown. Give 5 title options, one meta description under 160 characters, and a short tag list. Do not write the full article.',
266 ],
267 }),
268 })
269​
270 return [researcherAgent, writerAgent, seoAgent] as const
272```
273​
274## 7. Add the server route
275​
276Create `src/routes/api.chat.ts` in the `src/routes` folder, next to `index.tsx`. Start maps that file name to the `/api/chat` path.
277​
278The page sends the key in the `x-byok-openrouter` header. `getByokKey` reads that header. If the header is empty, `byokMissing` returns HTTP 401.
279​
280Import `openrouterByok` from `@tanstack/ai-openrouter/byok`, not from the adapter main entry.
281​
282Pass the agents into `chat({ subagents })`. This first route has no router. The main model gets one synthetic tool per agent.
283​
284```typescript ignore
285import { createFileRoute } from '@tanstack/react-router'
286import {
287 chat,
288 chatParamsFromRequest,
289 toServerSentEventsResponse,
290} from '@tanstack/ai'
291import { createOpenRouterText } from '@tanstack/ai-openrouter'
292import { openrouterByok } from '@tanstack/ai-openrouter/byok'
293import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
294import { createBlogAgents } from '@/lib/agents'
295​
296export async function POST({ request }: { request: Request }) {
297 const params = await chatParamsFromRequest(request)
298 const apiKey = getByokKey(request, openrouterByok)
299 if (!apiKey) return byokMissing(openrouterByok)
300​
301 const agents = createBlogAgents(apiKey)
302 const stream = chat({
303 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
304 messages: params.messages,
305 threadId: params.threadId,
306 runId: params.runId,
307 subagents: {
308 agents,
309 },
310 })
311 return toServerSentEventsResponse(stream)
313​
314export const Route = createFileRoute('/api/chat')({
315 server: {
316 handlers: {
317 POST,
318 },
319 },
320})
321```
322​
323The next steps replace that tool list with Jev. `strategy: 'exclusive'` belongs with the router. It means the chosen child owns the turn.
324​
325## 8. How routing works
326​
327A router is a function. The library calls it before the main model. It can return:
328​
329- `'main'`: the parent `chat()` runs as usual
330- one agent name, such as `'researcher'`, `'writer'`, or `'seo'`: that child's `run` starts
331- an array of names: those children use `subagents.order`
332- `{ names, order }`: this turn overrides `subagents.order`
333- `{ steps }`: one group runs, then the next group. The next group reads the earlier text
334​
335`order: 'parallel'` starts the names together. No agent reads another agent text. `order: 'sequence'` runs them one after another. Each later child reads the earlier child text. Omit `order` to get `parallel`.
336​
337Pass the router's `agents` argument to `subagentRoute`. Each yes/no question uses that agent's `description`. You can pass `when` to replace those questions. `when` must include every agent name. `then: ['writer']` runs the writer after the other selected agents. Those other agents start together. The writer reads their text. `pick` returns `main`, one name, `{ names, order }`, or `{ steps }`. Names follow that `agents` array.
338​
339`createOpenRouterDecider('~typesafe/jev-latest', apiKey)` uses the same OpenRouter key as chat.
340​
341## 9. Add Jev as the router
342​
343Replace the `subagents` bag. Pass `then: ['writer']`. `strategy: 'exclusive'` means the chosen child owns the turn. Main does not answer after it.
344​
345If `messages` is empty, return `'main'`. Otherwise pass the last message as `state`. Pass `abortSignal` so Stop cancels Jev. `subagentRoute` asks Jev which agents run. When the writer is one of them, the other agents start together, and the writer runs after them.
346​
347```typescript ignore
348subagents: {
349 agents,
350 strategy: 'exclusive',
351 router: async ({ messages, agents, abortSignal }) => {
352 const state = messages.at(-1)
353 if (state === undefined) return 'main'
354 const route = subagentRoute(agents, { then: ['writer'] })
355 const result = await decide({
356 adapter: createOpenRouterDecider('~typesafe/jev-latest', apiKey),
357 state,
358 questions: route.questions,
359 abortSignal,
360 })
361 return route.pick(result)
362 },
363},
364```
365​
366If the user asks for sources, Jev returns `researcher`. If the user asks for a post, Jev returns `writer`. If the user says hello, Jev returns `main`.
367​
368If the user asks for research and SEO, Jev returns `{ names: ['researcher', 'seo'], order: 'parallel' }`. The two cards start together.
369​
370If the user asks for research, SEO, and an article, Jev returns `{ steps }`. Research and SEO start together. The writer starts after both finish and reads both texts.
371​
372If the user asks for research and an article, with no SEO, the researcher runs first. The writer then reads those notes.
373​
374Add these imports:
375​
376```typescript
377import {
378 chat,
379 chatParamsFromRequest,
380 decide,
381 subagentRoute,
382 toServerSentEventsResponse,
383} from '@tanstack/ai'
384import {
385 createOpenRouterDecider,
386 createOpenRouterText,
387} from '@tanstack/ai-openrouter'
388```
389​
390## 10. Abort the run from the client
391​
392The browser abort signal fires when the user clicks Stop. The server must pass that into `chat()`. Each agent links `ctx.abortSignal` to its own `chat({ abortController })`. Stop then cancels the OpenRouter request, and `SUBAGENT_ERROR` can emit.
393​
394Add an `AbortController`. Link it to `request.signal`. If the request is already aborted, abort the controller at once, because the listener then never fires. Pass it to `chat()` and to `toServerSentEventsResponse`.
395​
396```typescript ignore
397const abortController = new AbortController()
398if (request.signal.aborted) abortController.abort()
399request.signal.addEventListener(
400 'abort',
401 () => {
402 abortController.abort()
403 },
404 { once: true },
406```
407​
408Then pass `abortController` into `chat({ abortController })` and `toServerSentEventsResponse(stream, { abortController })`.
409​
410The finished route is `src/routes/api.chat.ts`:
411​
412```typescript ignore
413import { createFileRoute } from '@tanstack/react-router'
414import {
415 chat,
416 chatParamsFromRequest,
417 decide,
418 subagentRoute,
419 toServerSentEventsResponse,
420} from '@tanstack/ai'
421import {
422 createOpenRouterDecider,
423 createOpenRouterText,
424} from '@tanstack/ai-openrouter'
425import { openrouterByok } from '@tanstack/ai-openrouter/byok'
426import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
427import { createBlogAgents } from '@/lib/agents'
428​
429export async function POST({ request }: { request: Request }) {
430 const params = await chatParamsFromRequest(request)
431 const apiKey = getByokKey(request, openrouterByok)
432 if (!apiKey) return byokMissing(openrouterByok)
433​
434 const abortController = new AbortController()
435 if (request.signal.aborted) abortController.abort()
436 request.signal.addEventListener(
437 'abort',
438 () => {
439 abortController.abort()
440 },
441 { once: true },
442 )
443​
444 const agents = createBlogAgents(apiKey)
445 const stream = chat({
446 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
447 messages: params.messages,
448 threadId: params.threadId,
449 runId: params.runId,
450 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
451 ...(params.resume ? { resume: params.resume } : {}),
452 abortController,
453 subagents: {
454 agents,
455 strategy: 'exclusive',
456 router: async ({ messages, agents, abortSignal }) => {
457 const state = messages.at(-1)
458 if (state === undefined) return 'main'
459 const route = subagentRoute(agents, { then: ['writer'] })
460 const result = await decide({
461 adapter: createOpenRouterDecider('~typesafe/jev-latest', apiKey),
462 state,
463 questions: route.questions,
464 abortSignal,
465 })
466 return route.pick(result)
467 },
468 },
469 })
470 return toServerSentEventsResponse(stream, { abortController })
472​
473export const Route = createFileRoute('/api/chat')({
474 server: {
475 handlers: {
476 POST,
477 },
478 },
479})
480```
481​
482## 11. Create the chat UI factory
483​
484The public factory is `createChatHook` from `@tanstack/ai-react/ui`. It calls `createChatUI` and binds `useChat`.
485​
486Create `src/chat-ui.tsx`. Register `layout`, `message`, and `input`. The layout props type is `LayoutProps`. Render `Messages` and `Input`. The subagent card is a part of the assistant message. `input` calls `useChatContext()` to send.
487​
488```tsx ignore
489import { fetchServerSentEvents } from '@tanstack/ai-react'
490import { createChatHook, type LayoutProps } from '@tanstack/ai-react/ui'
491import { OpenRouterKeyForm } from '@/components/open-router-key-form'
492import { byok } from '@/lib/byok'
493​
494const chatOptions = {
495 connection: fetchServerSentEvents('/api/chat'),
496 byok,
498​
499export const { useAppChat, useChatContext } = createChatHook({
500 options: chatOptions,
501 components: {
502 layout: function Layout({
503 Messages,
504 Input,
505 }: LayoutProps<typeof chatOptions>) {
506 return (
507 <div className="flex h-screen flex-col bg-gray-900">
508 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
509 <OpenRouterKeyForm />
510 </div>
511 <div className="flex-1 overflow-y-auto px-4 py-4">
512 <Messages />
513 </div>
514 <Input />
515 </div>
516 )
517 },
518 message: function Message({ message, Parts }) {
519 return (
520 <article data-role={message.role}>
521 <Parts />
522 </article>
523 )
524 },
525 input: function Input() {
526 const chat = useChatContext()
527 return (
528 <form
529 onSubmit={(event) => {
530 event.preventDefault()
531 const field = event.currentTarget.elements.namedItem('message')
532 if (!(field instanceof HTMLTextAreaElement)) return
533 const text = field.value.trim()
534 if (!text) return
535 field.value = ''
536 void chat.sendMessage(text).catch(() => undefined)
537 }}
538 >
539 <textarea name="message" disabled={chat.isLoading} />
540 <button type="submit" disabled={chat.isLoading}>
541 Send
542 </button>
543 </form>
544 )
545 },
546 },
547 partsComponents: {
548 fallback: ({ part }) => (
549 <p className="text-xs text-gray-400">{part.type}</p>
550 ),
551 },
552})
553```
554​
555`Parts` walks one message and picks a component per part. The next steps add those components.
556​
557## 12. Pass in the text part
558​
559Add `partsComponents.text`. The factory now draws assistant text.
560​
561```tsx ignore
562import { TextPart } from '@tanstack/ai-react/ui'
563​
564partsComponents: {
565 text: ({ part }) => (
566 <TextPart className="chat-markdown" content={part.content} />
567 ),
568 fallback: ({ part }) => (
569 <p className="text-xs text-gray-400">{part.type}</p>
570 ),
571},
572```
573​
574`TextPart` renders Markdown. Research notes and the article both use it. A `type: 'subagent'` part still needs a named component. The next step adds those.
575​
576## 13. Create the subagent components
577​
578Create `src/components/subagent-card.tsx`. Each agent name gets a component. The props type is `SubagentProps`. It gives you `subagent` and `Parts`.
579​
580The researcher card keeps the notes in a closed `<details>` section. The writer card is an article. `<Parts />` renders `subagent.messages`. `stop()` aborts the current parent run.
581​
582```tsx ignore
583import type { SubagentProps } from '@tanstack/ai-react/ui'
584import type { BlogChatOptions } from '@/chat-ui'
585​
586function AgentHeader({
587 name,
588 status,
589 onStop,
590}: {
591 name: string
592 status: string
593 onStop?: () => void
594}) {
595 return (
596 <header className="mb-3 flex flex-wrap items-center gap-2">
597 <strong className="text-sm uppercase tracking-wide">{name}</strong>
598 <span className="text-xs opacity-70">{status}</span>
599 {status === 'running' && onStop ? (
600 <button
601 type="button"
602 onClick={onStop}
603 className="rounded bg-red-600 px-2 py-1 text-xs font-medium text-white hover:bg-red-700"
604 >
605 Stop
606 </button>
607 ) : null}
608 </header>
609 )
611​
612export function Researcher({
613 subagent,
614 Parts,
615}: SubagentProps<BlogChatOptions, 'researcher'>) {
616 return (
617 <section className="mt-3 rounded-lg border border-orange-500/30 bg-gray-900/80 p-3 text-gray-100">
618 <AgentHeader
619 name={subagent.name}
620 status={subagent.status}
621 onStop={subagent.stop}
622 />
623 {subagent.error ? (
624 <p className="text-xs text-red-400">{subagent.error.message}</p>
625 ) : null}
626 <details className="mt-2">
627 <summary className="cursor-pointer text-xs opacity-70">
628 Research notes
629 </summary>
630 <div className="mt-2">
631 <Parts />
632 </div>
633 </details>
634 </section>
635 )
637​
638export function Seo({
639 subagent,
640 Parts,
641}: SubagentProps<BlogChatOptions, 'seo'>) {
642 return (
643 <section className="mt-3 rounded-lg border border-sky-500/40 bg-gray-900/80 p-3 text-gray-100">
644 <AgentHeader
645 name={subagent.name}
646 status={subagent.status}
647 onStop={subagent.stop}
648 />
649 {subagent.error ? (
650 <p className="text-xs text-red-400">{subagent.error.message}</p>
651 ) : null}
652 <div className="mt-2">
653 <Parts />
654 </div>
655 </section>
656 )
658​
659export function Writer({
660 subagent,
661 Parts,
662}: SubagentProps<BlogChatOptions, 'writer'>) {
663 return (
664 <article className="writer-article">
665 <AgentHeader
666 name={subagent.name}
667 status={subagent.status}
668 onStop={subagent.stop}
669 />
670 {subagent.error ? (
671 <p className="text-sm text-red-700">{subagent.error.message}</p>
672 ) : null}
673 <Parts />
674 </article>
675 )
677```
678​
679## 14. Register every named subagent
680​
681Put `blogAgents` on `options.subagents`. The factory reads each agent name from that list. Then pass `subagentsComponents` with one component per name. TypeScript requires every name. The factory throws if a spawned name is missing.
682​
683Create `src/components/chat-input.tsx`. The form calls `useChatContext()` to send. It has no return type.
684​
685```tsx ignore
686import { useChatContext } from '@/chat-ui'
687​
688export function ChatInput() {
689 const chat = useChatContext()
690 return (
691 <>
692 {chat.error ? (
693 <div className="mx-4 mt-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
694 {chat.error.message}
695 </div>
696 ) : null}
697 {chat.isLoading ? (
698 <div className="mb-3 flex items-center justify-center">
699 <button
700 type="button"
701 onClick={chat.stop}
702 className="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
703 >
704 Stop
705 </button>
706 </div>
707 ) : null}
708 <form
709 className="border-t border-orange-500/10 bg-gray-900/80 px-4 py-3"
710 onSubmit={(event) => {
711 event.preventDefault()
712 const field = event.currentTarget.elements.namedItem('message')
713 if (!(field instanceof HTMLTextAreaElement)) return
714 const text = field.value.trim()
715 if (!text) return
716 field.value = ''
717 void chat.sendMessage(text).catch(() => undefined)
718 }}
719 >
720 <div className="flex items-end gap-2">
721 <textarea
722 name="message"
723 rows={1}
724 disabled={chat.isLoading}
725 placeholder="Ask for research, a draft, or SEO titles..."
726 onKeyDown={(event) => {
727 // Enter also confirms an IME composition. Do not send then.
728 if (
729 event.key !== 'Enter' ||
730 event.shiftKey ||
731 event.nativeEvent.isComposing
732 ) {
733 return
734 }
735 event.preventDefault()
736 event.currentTarget.form?.requestSubmit()
737 }}
738 className="w-full resize-none rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/50"
739 />
740 <button
741 type="submit"
742 disabled={chat.isLoading}
743 className="rounded-lg bg-orange-500 px-4 py-3 text-sm font-medium text-white disabled:opacity-50"
744 >
745 Send
746 </button>
747 </div>
748 </form>
749 </>
750 )
752```
753​
754The finished factory is `src/chat-ui.tsx`:
755​
756```tsx ignore
757import { fetchServerSentEvents } from '@tanstack/ai-react'
758import {
759 createChatHook,
760 TextPart,
761 type LayoutProps,
762} from '@tanstack/ai-react/ui'
763import { ChatInput } from '@/components/chat-input'
764import { OpenRouterKeyForm } from '@/components/open-router-key-form'
765import { Researcher, Seo, Writer } from '@/components/subagent-card'
766import { blogAgents } from '@/lib/blog-agents'
767import { byok } from '@/lib/byok'
768​
769export const chatOptions = {
770 connection: fetchServerSentEvents('/api/chat'),
771 byok,
772 subagents: blogAgents,
774​
775export type BlogChatOptions = typeof chatOptions
776​
777export const { useAppChat, useChatContext } = createChatHook({
778 options: chatOptions,
779 components: {
780 layout: function Layout({
781 Messages,
782 Input,
783 }: LayoutProps<typeof chatOptions>) {
784 return (
785 <div className="flex h-screen flex-col bg-gray-900">
786 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
787 <h1 className="mb-2 text-sm font-semibold text-white">Blog desk</h1>
788 <OpenRouterKeyForm />
789 </div>
790 <div className="flex-1 overflow-y-auto px-4 py-4">
791 <Messages />
792 </div>
793 <Input />
794 </div>
795 )
796 },
797 message: function Message({ message, Parts }) {
798 return (
799 <article
800 data-role={message.role}
801 className={`mb-2 rounded-lg p-4 text-gray-100 ${
802 message.role === 'assistant'
803 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
804 : 'bg-transparent'
805 }`}
806 >
807 <Parts />
808 </article>
809 )
810 },
811 input: ChatInput,
812 },
813 partsComponents: {
814 text: ({ part }) => (
815 <TextPart className="chat-markdown" content={part.content} />
816 ),
817 fallback: ({ part }) => (
818 <p className="text-xs text-gray-400">{part.type}</p>
819 ),
820 },
821 subagentsComponents: {
822 researcher: Researcher,
823 writer: Writer,
824 seo: Seo,
825 },
826})
827```
828​
829Create `src/routes/index.tsx`. Call `useAppChat()` and render `<chat.AppChat />`.
830​
831```tsx ignore
832import { createFileRoute } from '@tanstack/react-router'
833import { useAppChat } from '@/chat-ui'
834​
835function ChatPage() {
836 const chat = useAppChat()
837 return <chat.AppChat />
839​
840export const Route = createFileRoute('/')({
841 component: ChatPage,
842})
843```
844​
845## 15. Try it
846​
8471. Run the app.
8482. Paste an OpenRouter key.
8493. Send `What are three facts about durable streams?` The researcher card opens.
8504. Send `Write a short blog post about durable streams.` The writer card opens.
8515. Send `do research and seo`. The researcher card and the SEO card open together.
8526. Send `research octopuses and squids, suggest SEO, and write the article`. Research and SEO open together. The writer card opens after both finish.
8537. After the research and SEO cards finish, send `write an article with that info`. The writer uses the notes from those cards.
854​
855The same app is on the Examples tab at `/ai/latest/docs/framework/react/examples/subagents`.
856​
857<!-- ::client-example library=ai framework=react slug=subagents -->
858​
859You have a blog desk. Jev picks the specialist. The nested card shows the child as it streams.
860​
861A refresh drops these cards. Keep them in [Persisted subagents](./subagents-persisted).
862​
863The full example is on GitHub: [TanStack/ai `examples/react/subagents`](https://github.com/TanStack/ai/tree/main/examples/react/subagents).
864​
865For the API, open [Subagents](../chat/subagents).