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

api.subagent-brief.ts

68 lines2.1 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 defineAgent,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { openaiText } from '@tanstack/ai-openai'
9import { z } from 'zod'
10​
11/**
12 * The parent model writes the researcher's brief. The researcher's only
13 * message is that brief, not the parent conversation.
14 */
15const researcher = defineAgent({
16 name: 'researcher',
17 description:
18 'Researches one focused question and returns short findings. It cannot see this chat, so the task must hold every detail it needs.',
19 inputSchema: z.object({
20 task: z
21 .string()
22 .describe(
23 'What to find and what to return. The researcher sees only this text.',
24 ),
25 }),
26 run: (ctx) => {
27 console.log(
28 '[subagent-brief] child input:',
29 JSON.stringify(ctx.input),
30 '| parent messages available:',
31 ctx.messages.length,
32 )
33 return chat({
34 adapter: openaiText('gpt-5.6'),
35 messages: [{ role: 'user', content: ctx.input.task }],
36 threadId: ctx.threadId,
37 runId: ctx.runId,
38 parentRunId: ctx.parentRunId,
39 subagentRunId: ctx.subagentRunId,
40 resume: ctx.resume,
41 })
42 },
43})
44​
45export const Route = createFileRoute('/api/subagent-brief')({
46 server: {
47 handlers: {
48 POST: async ({ request }) => {
49 const abortController = new AbortController()
50 const params = await chatParamsFromRequestBody(await request.json())
51 const stream = chat({
52 adapter: openaiText('gpt-5.6'),
53 messages: params.messages,
54 threadId: params.threadId,
55 runId: params.runId,
56 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
57 ...(params.resume ? { resume: params.resume } : {}),
58 systemPrompts: [
59 'For any research question, call the researcher tool. Then answer the user from its result.',
60 ],
61 subagents: { agents: [researcher] },
62 abortController,
63 })
64 return toServerSentEventsResponse(stream, { abortController })
65 },
66 },
67 },
68})