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

api.subagent-brief.ts

59 lines1.8 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 { researcher as researcherDeclaration } from '../lib/researcher-agent'
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 ...researcherDeclaration,
17 run: (ctx) => {
18 console.log(
19 '[subagent-brief] child input:',
20 JSON.stringify(ctx.input),
21 '| parent messages available:',
22 ctx.messages.length,
23 )
24 return chat({
25 adapter: openaiText('gpt-5.6'),
26 messages: [{ role: 'user', content: ctx.input.task }],
27 threadId: ctx.threadId,
28 runId: ctx.runId,
29 parentRunId: ctx.parentRunId,
30 subagentRunId: ctx.subagentRunId,
31 resume: ctx.resume,
32 })
33 },
34})
35​
36export const Route = createFileRoute('/api/subagent-brief')({
37 server: {
38 handlers: {
39 POST: async ({ request }) => {
40 const abortController = new AbortController()
41 const params = await chatParamsFromRequestBody(await request.json())
42 const stream = chat({
43 adapter: openaiText('gpt-5.6'),
44 messages: params.messages,
45 threadId: params.threadId,
46 runId: params.runId,
47 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
48 ...(params.resume ? { resume: params.resume } : {}),
49 systemPrompts: [
50 'For any research question, call the researcher tool. Then answer the user from its result.',
51 ],
52 subagents: { agents: [researcher] },
53 abortController,
54 })
55 return toServerSentEventsResponse(stream, { abortController })
56 },
57 },
58 },
59})