Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequest,
5 decide,
6 memoryStream,
7 resumeServerSentEventsResponse,
8 subagentRoute,
9 toServerSentEventsResponse,
10} from '@tanstack/ai'
11import {
12 memoryPersistence,
13 reconstructChat,
14 withPersistence,
15} from '@tanstack/ai-persistence'
16import {
17 createOpenRouterDecider,
18 createOpenRouterText,
19} from '@tanstack/ai-openrouter'
20import { openrouterByok } from '@tanstack/ai-openrouter/byok'
21import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
22import { createBlogAgents } from '@/lib/agents'
23
24const FIRST_CHUNK_MS = 30_000
25
26const persistence = memoryPersistence()
27
28export const Route = createFileRoute('/api/chat')({
29 server: {
30 handlers: {
31 POST: async ({ request }) => {
32 const params = await chatParamsFromRequest(request)
33 // The id reads only the header. The provider object would also read
34 // OPENROUTER_API_KEY, and this example has no login.
35 const apiKey = getByokKey(request, openrouterByok.id)
36 if (!apiKey) return byokMissing(openrouterByok)
37 const agents = createBlogAgents(apiKey)
38 const stream = chat({
39 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
40 messages: params.messages,
41 threadId: params.threadId,
42 runId: params.runId,
43 middleware: [withPersistence(persistence)],
44 ...(params.parentRunId !== undefined
45 ? { parentRunId: params.parentRunId }
46 : {}),
47 ...(params.resume !== undefined ? { resume: params.resume } : {}),
48 subagents: {
49 agents,
50 strategy: 'exclusive',
51 router: async ({ messages, agents: routed, abortSignal }) => {
52 const state = messages.at(-1)
53 if (state === undefined) return 'main'
54 const route = subagentRoute(routed, { then: ['writer'] })
55 const result = await decide({
56 adapter: createOpenRouterDecider(
57 '~typesafe/jev-latest',
58 apiKey,
59 ),
60 state,
61 questions: route.questions,
62 abortSignal,
63 })
64 return route.pick(result)
65 },
66 },
67 })
68 return toServerSentEventsResponse(stream, {
69 durability: { adapter: memoryStream(request) },
70 })
71 },
72 GET: ({ request }) => {
73 const durability = memoryStream(request, {
74 firstChunkDeadlineMs: FIRST_CHUNK_MS,
75 })
76 if (durability.resumeFrom() !== null) {
77 return resumeServerSentEventsResponse({ adapter: durability })
78 }
79 return reconstructChat(persistence, request)
80 },
81 },
82 },
83})