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