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

api.chat.ts

218 lines8.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import type { StreamChunk } from '@tanstack/ai'
9import type { Feature, Provider } from '@/lib/types'
10import { createTextAdapter } from '@/lib/providers'
11import { featureConfigs } from '@/lib/features'
12import { guitarRecommendationSchema, recipeSchema } from '@/lib/schemas'
13​
14const DEFAULT_SYSTEM_PROMPT = 'You are a helpful assistant for a guitar store.'
15​
16export const Route = createFileRoute('/api/chat')({
17 server: {
18 handlers: {
19 POST: async ({ request }) => {
20 await import('@/lib/llmock-server').then((m) => m.ensureLLMock())
21 if (request.signal.aborted) {
22 return new Response(null, { status: 499 })
23 }
24​
25 const abortController = new AbortController()
26​
27 let params
28 try {
29 params = await chatParamsFromRequestBody(await request.json())
30 } catch (error) {
31 return new Response(
32 error instanceof Error ? error.message : 'Bad request',
33 { status: 400 },
34 )
35 }
36​
37 const fp = params.forwardedProps as Record<string, unknown>
38 const provider: Provider = (
39 typeof fp.provider === 'string' ? fp.provider : 'openai'
40 ) as Provider
41 const feature: Feature = (
42 typeof fp.feature === 'string' ? fp.feature : 'chat'
43 ) as Feature
44 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
45 const aimockPort =
46 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
47 const previousInteractionId: string | undefined =
48 typeof fp.previousInteractionId === 'string'
49 ? fp.previousInteractionId
50 : undefined
51​
52 const config = featureConfigs[feature]
53 const modelOverride = config.modelOverrides?.[provider]
54 const adapterOptions = createTextAdapter(
55 provider,
56 modelOverride,
57 aimockPort,
58 testId,
59 feature,
60 )
61​
62 const modelOptions = previousInteractionId
63 ? {
64 ...config.modelOptions,
65 previous_interaction_id: previousInteractionId,
66 }
67 : config.modelOptions
68​
69 try {
70 const systemPrompt = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT
71​
72 // Test-only flag — when truthy, the route promotes the system
73 // prompt to object-form and attaches Anthropic `cache_control`
74 // metadata. Enables system-prompt-metadata.spec.ts to verify
75 // cache_control reaches the wire via the aimock journal.
76 const systemPromptCacheControl =
77 fp.systemPromptCacheControl === true
78 ? ({ type: 'ephemeral' as const } as const)
79 : undefined
80 const systemPrompts = systemPromptCacheControl
81 ? [
82 {
83 content: systemPrompt,
84 metadata: { cache_control: systemPromptCacheControl },
85 // The route is provider-generic; the metadata type is
86 // adapter-narrowed and only meaningful for Anthropic, so
87 // a single bridge cast lives here at the test entry.
88 // eslint-disable-next-line @typescript-eslint/no-explicit-any
89 } as any,
90 ]
91 : [systemPrompt]
92​
93 // Test-only flag — when set to `true`, the route passes
94 // structured root-level observability `metadata` (objects,
95 // arrays) to `chat()`. Enables root-metadata-wire.spec.ts to
96 // verify the call still completes: the adapter keeps root
97 // metadata off the provider request, so the OpenRouter SDK's
98 // Record<string, string> outbound validation never sees it
99 // (regression coverage for #735). Wire-absence itself is
100 // asserted by the adapter unit tests.
101 const rootObservabilityMetadata =
102 fp.structuredRootMetadata === true
103 ? {
104 observationName: 'e2e-root-metadata',
105 tags: ['a', 'b'],
106 prompt: { name: 'p', version: 1 },
107 }
108 : undefined
109​
110 // Two structured-output-streaming features differ only in which
111 // schema they bind to. Branched per-feature so TS can pick the
112 // right `chat<TSchema>()` overload without a `never` cast.
113 const stream =
114 feature === 'structured-output-stream'
115 ? chat({
116 ...adapterOptions,
117 modelOptions,
118 ...(config.reasoning && { reasoning: config.reasoning }),
119 systemPrompts,
120 messages: params.messages,
121 threadId: params.threadId,
122 runId: params.runId,
123 ...(params.parentRunId && {
124 parentRunId: params.parentRunId,
125 }),
126 ...(params.resume && { resume: params.resume }),
127 outputSchema: guitarRecommendationSchema,
128 stream: true,
129 abortController,
130 })
131 : feature === 'multi-turn-structured'
132 ? chat({
133 ...adapterOptions,
134 modelOptions,
135 ...(config.reasoning && { reasoning: config.reasoning }),
136 systemPrompts,
137 messages: params.messages,
138 threadId: params.threadId,
139 runId: params.runId,
140 ...(params.parentRunId && {
141 parentRunId: params.parentRunId,
142 }),
143 ...(params.resume && { resume: params.resume }),
144 outputSchema: recipeSchema,
145 stream: true,
146 abortController,
147 })
148 : feature === 'agentic-structured-stream'
149 ? chat({
150 ...adapterOptions,
151 tools: config.tools,
152 modelOptions,
153 ...(config.reasoning && { reasoning: config.reasoning }),
154 systemPrompts,
155 agentLoopStrategy: maxIterations(5),
156 messages: params.messages,
157 threadId: params.threadId,
158 runId: params.runId,
159 ...(params.parentRunId && {
160 parentRunId: params.parentRunId,
161 }),
162 ...(params.resume && { resume: params.resume }),
163 outputSchema: guitarRecommendationSchema,
164 stream: true,
165 abortController,
166 })
167 : chat({
168 ...adapterOptions,
169 tools: config.tools,
170 ...(config.toolChoice && {
171 toolChoice: config.toolChoice,
172 }),
173 modelOptions,
174 ...(config.reasoning && { reasoning: config.reasoning }),
175 systemPrompts,
176 agentLoopStrategy: maxIterations(5),
177 messages: params.messages,
178 threadId: params.threadId,
179 runId: params.runId,
180 ...(params.parentRunId && {
181 parentRunId: params.parentRunId,
182 }),
183 ...(params.resume && { resume: params.resume }),
184 ...(rootObservabilityMetadata && {
185 metadata: rootObservabilityMetadata,
186 }),
187 abortController,
188 })
189​
190 // Cast: `chat()` returns `AsyncIterable<StreamChunk> |
191 // StructuredOutputStream<T>`. Both yield AG-UI events at runtime
192 // but the typed-CUSTOM-events variants on `StructuredOutputStream`
193 // aren't structurally assignable to the bare `StreamChunk` union
194 // (zod-passthrough index-signature variance). The runtime is fine
195 // either way.
196 return toServerSentEventsResponse(
197 stream as AsyncIterable<StreamChunk>,
198 { abortController },
199 )
200 } catch (error) {
201 console.error('[api.chat] Error:', error)
202 if (
203 (error instanceof Error && error.name === 'AbortError') ||
204 abortController.signal.aborted
205 ) {
206 return new Response(null, { status: 499 })
207 }
208 const message =
209 error instanceof Error ? error.message : 'An error occurred'
210 return new Response(JSON.stringify({ error: message }), {
211 status: 500,
212 headers: { 'Content-Type': 'application/json' },
213 })
214 }
215 },
216 },
217 },
218})