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

api.tanchat.ts

528 lines18.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createChatOptions,
6 maxIterations,
7 mergeAgentTools,
8 toServerSentEventsResponse,
9} from '@tanstack/ai'
10import { OPENAI_CHAT_MODELS, createOpenaiChat } from '@tanstack/ai-openai'
11import { openaiByok } from '@tanstack/ai-openai/byok'
12import { OllamaTextModels, ollamaText } from '@tanstack/ai-ollama'
13import { ANTHROPIC_MODELS, createAnthropicChat } from '@tanstack/ai-anthropic'
14import { anthropicByok } from '@tanstack/ai-anthropic/byok'
15import { GEMINI_MODELS, createGeminiChat } from '@tanstack/ai-gemini'
16import { geminiByok } from '@tanstack/ai-gemini/byok'
17import { createGeminiTextInteractions } from '@tanstack/ai-gemini/experimental'
18import { createOpenRouterText } from '@tanstack/ai-openrouter'
19import { OPENROUTER_CHAT_MODELS } from '@tanstack/ai-openrouter/model-meta'
20import { openrouterByok } from '@tanstack/ai-openrouter/byok'
21import { GROK_CHAT_MODELS, createGrokText } from '@tanstack/ai-grok'
22import { grokByok } from '@tanstack/ai-grok/byok'
23import { GROQ_CHAT_MODELS, createGroqText } from '@tanstack/ai-groq'
24import { groqByok } from '@tanstack/ai-groq/byok'
25import { createCloudflareText } from '@tanstack/ai-cloudflare'
26import {
27 cloudflareAccountByok,
28 cloudflareByok,
29} from '@tanstack/ai-cloudflare/byok'
30import { BEDROCK_CONVERSE_MODELS, bedrockText } from '@tanstack/ai-bedrock'
31import { BYTEPLUS_CHAT_MODELS, createBytePlusText } from '@tanstack/ai-byteplus'
32import { byteplusByok } from '@tanstack/ai-byteplus/byok'
33import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
34import { z } from 'zod'
35import type { AnyTextAdapter, ChatMiddleware } from '@tanstack/ai'
36import type { ByokProvider } from '@tanstack/ai/byok'
37import {
38 addToCartToolDef,
39 addToWishListToolDef,
40 calculateFinancing,
41 compareGuitars,
42 getGuitars,
43 getPersonalGuitarPreferenceToolDef,
44 inspectServerRuntimeContextToolDef,
45 recommendGuitarToolDef,
46 runtimeLoyaltyTiers,
47 runtimePreferredStyles,
48 searchGuitars,
49 type ServerRuntimeContext,
50} from '@/lib/guitar-tools'
51import { viaCloudflareGateway } from '@/lib/cloudflare-gateway'
52​
53/**
54 * Client-supplied provider + model, validated once per request. An unknown
55 * provider falls back to OpenAI and an unknown model falls back to that
56 * provider's default, so arbitrary client strings never reach an adapter.
57 * The parsed `model` is narrowed to each adapter's literal model union.
58 */
59const modelSelectionSchema = z
60 .discriminatedUnion('provider', [
61 z.object({
62 provider: z.literal('openai'),
63 model: z.enum(OPENAI_CHAT_MODELS).catch('gpt-5.2'),
64 }),
65 z.object({
66 provider: z.literal('anthropic'),
67 model: z.enum(ANTHROPIC_MODELS).catch('claude-sonnet-4-6'),
68 }),
69 z.object({
70 provider: z.literal('gemini'),
71 model: z.enum(GEMINI_MODELS).catch('gemini-3.1-pro-preview'),
72 }),
73 z.object({
74 provider: z.literal('gemini-interactions'),
75 model: z.enum(GEMINI_MODELS).catch('gemini-3.1-pro-preview'),
76 }),
77 z.object({
78 provider: z.literal('ollama'),
79 model: z.enum(OllamaTextModels).catch('gpt-oss:20b'),
80 }),
81 z.object({
82 provider: z.literal('grok'),
83 model: z.enum(GROK_CHAT_MODELS).catch('grok-build-0.1'),
84 }),
85 z.object({
86 provider: z.literal('groq'),
87 model: z.enum(GROQ_CHAT_MODELS).catch('openai/gpt-oss-120b'),
88 }),
89 z.object({
90 provider: z.literal('openrouter'),
91 model: z.enum(OPENROUTER_CHAT_MODELS).catch('openai/gpt-5.1'),
92 }),
93 z.object({
94 provider: z.literal('bedrock'),
95 model: z
96 .enum(BEDROCK_CONVERSE_MODELS)
97 .catch('us.anthropic.claude-haiku-4-5-20251001-v1:0'),
98 }),
99 z.object({
100 provider: z.literal('byteplus'),
101 model: z.enum(BYTEPLUS_CHAT_MODELS).catch('seed-2-0-lite-260428'),
102 }),
103 z.object({
104 provider: z.literal('cloudflare'),
105 model: z.string().catch('@cf/zai-org/glm-5.3-flash'),
106 }),
107 ])
108 .catch({ provider: 'openai', model: 'gpt-5.2' })
109​
110type ModelSelection = z.infer<typeof modelSelectionSchema>
111type Provider = ModelSelection['provider']
112​
113const BYOK_PROVIDERS: Partial<Record<Provider, ByokProvider>> = {
114 openai: openaiByok,
115 anthropic: anthropicByok,
116 gemini: geminiByok,
117 openrouter: openrouterByok,
118 groq: groqByok,
119 grok: grokByok,
120 byteplus: byteplusByok,
121 cloudflare: cloudflareByok,
123​
124function chatByokProvider(provider: Provider): ByokProvider | undefined {
125 if (provider === 'gemini-interactions') return geminiByok
126 return BYOK_PROVIDERS[provider]
128​
129function resolveByokApiKey(
130 request: Request,
131 provider: Provider,
132):
133 | { missing: false; apiKey: string | null }
134 | { missing: true; provider: ByokProvider } {
135 const byokProvider = chatByokProvider(provider)
136 if (!byokProvider) return { missing: false, apiKey: null }
137 const apiKey = getByokKey(request, byokProvider)
138 if (!apiKey) return { missing: true, provider: byokProvider }
139 return { missing: false, apiKey }
141​
142function requireApiKey(apiKey: string | null): string {
143 if (!apiKey) {
144 throw new Error('API key is required')
145 }
146 return apiKey
148​
149const SYSTEM_PROMPT = `You are a helpful assistant for a guitar store.
150​
151CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THIS EXACT WORKFLOW:
152​
153When a user asks for a guitar recommendation:
1541. FIRST: Use the getGuitars tool (no parameters needed)
1552. SECOND: Use the recommendGuitar tool with the ID of the guitar you want to recommend
1563. NEVER write a recommendation directly - ALWAYS use the recommendGuitar tool
157​
158IMPORTANT:
159- The recommendGuitar tool will display the guitar in a special, appealing format
160- You MUST use recommendGuitar for ANY guitar recommendation
161- ONLY recommend guitars from our inventory (use getGuitars first)
162- The recommendGuitar tool has a buy button - this is how customers purchase
163- Do NOT describe the guitar yourself - let the recommendGuitar tool do it
164- When the user asks about runtime context, call the inspectClientRuntimeContext
165 and/or inspectServerRuntimeContext tool named in the request.
166​
167Example workflow:
168User: "I want an acoustic guitar"
169Step 1: Call getGuitars()
170Step 2: Call recommendGuitar(id: "6")
171Step 3: Done - do NOT add any text after calling recommendGuitar
172​
174function isAllowedValue<T extends string>(
175 value: unknown,
176 allowedValues: ReadonlyArray<T>,
177): value is T {
178 return (
179 typeof value === 'string' &&
180 allowedValues.some((allowedValue) => allowedValue === value)
181 )
183​
184function readForwardedString(value: unknown, fallback: string) {
185 return typeof value === 'string' ? value : fallback
187​
188const addToCartToolServer = addToCartToolDef.server((args, context) => {
189 context?.emitCustomEvent('tool:progress', {
190 tool: 'addToCart',
191 message: `Adding ${args.quantity}x guitar ${args.guitarId} to cart`,
192 })
193 const cartId = 'CART_' + Date.now()
194 context?.emitCustomEvent('tool:progress', {
195 tool: 'addToCart',
196 message: `Cart ${cartId} created successfully`,
197 })
198 return {
199 success: true,
200 cartId,
201 guitarId: args.guitarId,
202 quantity: args.quantity,
203 totalItems: args.quantity,
204 }
205})
206​
207const inspectServerRuntimeContextToolServer =
208 inspectServerRuntimeContextToolDef.server<ServerRuntimeContext>(
209 (_, executionContext) => {
210 executionContext.emitCustomEvent('runtime-context:server', {
211 userId: executionContext.context.userId,
212 tenantId: executionContext.context.tenantId,
213 })
214​
215 return {
216 ...executionContext.context,
217 source: 'server' as const,
218 }
219 },
220 )
221​
222const serverTools = [
223 getGuitars, // Server tool
224 recommendGuitarToolDef, // No server execute - client will handle
225 addToCartToolServer,
226 addToWishListToolDef,
227 getPersonalGuitarPreferenceToolDef,
228 inspectServerRuntimeContextToolServer,
229 // Lazy tools - discovered on demand
230 compareGuitars,
231 calculateFinancing,
232 searchGuitars,
234​
235const loggingMiddleware: ChatMiddleware = {
236 name: 'logging',
237 onConfig(ctx, config) {
238 console.log(
239 `[logging] onConfig iteration=${ctx.iteration} model=${ctx.model} tools=${config.tools.length}`,
240 )
241 },
242 onStart(ctx) {
243 console.log(`[logging] onStart requestId=${ctx.requestId}`)
244 },
245 onIteration(_ctx, info) {
246 console.log(`[logging] onIteration iteration=${info.iteration}`)
247 },
248 onBeforeToolCall(_ctx, toolCtx) {
249 console.log(`[logging] onBeforeToolCall tool=${toolCtx.toolName}`)
250 },
251 onAfterToolCall(_ctx, info) {
252 console.log(
253 `[logging] onAfterToolCall tool=${info.toolName} result=${JSON.stringify(info.result).slice(0, 100)}`,
254 )
255 },
256 onFinish(ctx, info) {
257 console.log(
258 `[logging] onFinish reason=${info.finishReason} iterations=${ctx.iteration}`,
259 )
260 },
261 onUsage(_ctx, usage) {
262 console.log(
263 `[logging] onUsage tokens=${usage.totalTokens} input=${usage.promptTokens} output=${usage.completionTokens}, total: ${usage.totalTokens}`,
264 )
265 },
267​
268function maskIdentifier(value: string): string {
269 if (!value) return '<empty>'
270 if (value.length <= 4) return '***'
271 return `${value.slice(0, 2)}***${value.slice(-2)}`
273​
274const runtimeContextMiddleware: ChatMiddleware<ServerRuntimeContext> = {
275 name: 'runtime-context',
276 onStart(ctx) {
277 console.log(
278 `[runtime-context] onStart user=${maskIdentifier(ctx.context.userId)} tenant=${maskIdentifier(ctx.context.tenantId)} tier=${ctx.context.loyaltyTier}`,
279 )
280 },
281 onBeforeToolCall(ctx, toolCtx) {
282 if (toolCtx.toolName.includes('RuntimeContext')) {
283 console.log(
284 `[runtime-context] onBeforeToolCall tool=${toolCtx.toolName} source=${ctx.context.requestSource}`,
285 )
286 }
287 },
289​
290export const Route = createFileRoute('/api/tanchat')({
291 server: {
292 handlers: {
293 POST: async ({ request }) => {
294 // Capture request signal before reading body (it may be aborted after body is consumed)
295 const requestSignal = request.signal
296​
297 // If request is already aborted, return early
298 if (requestSignal.aborted) {
299 return new Response(null, { status: 499 }) // 499 = Client Closed Request
300 }
301​
302 const abortController = new AbortController()
303​
304 let params
305 try {
306 params = await chatParamsFromRequestBody(await request.json())
307 } catch (error) {
308 return new Response(
309 error instanceof Error ? error.message : 'Bad request',
310 { status: 400 },
311 )
312 }
313​
314 // Validate the client-supplied provider + model (see the schema).
315 const selection = modelSelectionSchema.parse({
316 provider: params.forwardedProps.provider,
317 model: params.forwardedProps.model,
318 })
319 const runtimeContext: ServerRuntimeContext = {
320 userId: readForwardedString(
321 params.forwardedProps.runtimeUserId,
322 'user_guest',
323 ),
324 tenantId: readForwardedString(
325 params.forwardedProps.runtimeTenantId,
326 'public-store',
327 ),
328 loyaltyTier: isAllowedValue(
329 params.forwardedProps.runtimeLoyaltyTier,
330 runtimeLoyaltyTiers,
331 )
332 ? params.forwardedProps.runtimeLoyaltyTier
333 : 'standard',
334 preferredStyle: isAllowedValue(
335 params.forwardedProps.runtimePreferredStyle,
336 runtimePreferredStyles,
337 )
338 ? params.forwardedProps.runtimePreferredStyle
339 : 'acoustic',
340 requestSource: 'react-chat',
341 serverRegion: 'local-dev',
342 }
343 const previousInteractionId: string | undefined =
344 typeof params.forwardedProps.previousInteractionId === 'string'
345 ? params.forwardedProps.previousInteractionId
346 : undefined
347​
348 // Build typed adapter options from the validated selection. Each case
349 // sees `model` narrowed to that adapter's model union.
350 const buildChatOptions = (
351 { provider, model }: ModelSelection,
352 apiKey: string | null,
353 cloudflareAccountId: string | null,
354 ): { adapter: AnyTextAdapter } => {
355 switch (provider) {
356 case 'anthropic':
357 return createChatOptions({
358 adapter: createAnthropicChat(
359 model,
360 requireApiKey(apiKey),
361 viaCloudflareGateway('anthropic'),
362 ),
363 })
364 case 'openrouter':
365 return createChatOptions({
366 adapter: createOpenRouterText(model, requireApiKey(apiKey)),
367 reasoning: 'medium',
368 })
369 case 'gemini':
370 return createChatOptions({
371 adapter: createGeminiChat(model, requireApiKey(apiKey)),
372 reasoning: 'high',
373 })
374 case 'gemini-interactions':
375 return createChatOptions({
376 adapter: createGeminiTextInteractions(
377 model,
378 requireApiKey(apiKey),
379 ),
380 modelOptions: {
381 previous_interaction_id: previousInteractionId,
382 store: true,
383 },
384 })
385 case 'grok':
386 return createChatOptions({
387 adapter: createGrokText(model, requireApiKey(apiKey)),
388 modelOptions: {},
389 })
390 case 'groq':
391 return createChatOptions({
392 adapter: createGroqText(
393 model,
394 requireApiKey(apiKey),
395 viaCloudflareGateway('groq'),
396 ),
397 })
398 case 'bedrock':
399 return createChatOptions({
400 // Default Converse API. Auth is 'auto' (BEDROCK_API_KEY /
401 // AWS_BEARER_TOKEN_BEDROCK, then the SigV4 credential chain) unless
402 // BEDROCK_AUTH=sigv4 forces SigV4 via the AWS credential chain
403 // (env vars or `aws configure` profile). Region defaults to us-east-1.
404 adapter: bedrockText(model, {
405 region: process.env.AWS_REGION || 'us-east-1',
406 ...(process.env.BEDROCK_AUTH === 'sigv4' && {
407 auth: 'sigv4' as const,
408 }),
409 }),
410 })
411 case 'byteplus':
412 return createChatOptions({
413 // BytePlus ModelArk. Keys are region-isolated — an EU key will
414 // not work against the Asia-Pacific host.
415 adapter: createBytePlusText(model, requireApiKey(apiKey)),
416 })
417 case 'cloudflare':
418 return createChatOptions({
419 // Workers AI over REST. Account id and token both come from
420 // BYOK, with CLOUDFLARE_ACCOUNT_ID / CLOUDFLARE_API_TOKEN as
421 // the env fallback. With CLOUDFLARE_AI_GATEWAY_ID set,
422 // requests (including `provider/model` ids such as
423 // openai/gpt-5.5) go through that AI Gateway.
424 adapter: createCloudflareText(model, {
425 accountId: requireApiKey(cloudflareAccountId),
426 apiKey: requireApiKey(apiKey),
427 ...(process.env.CLOUDFLARE_AI_GATEWAY_ID && {
428 gateway: { id: process.env.CLOUDFLARE_AI_GATEWAY_ID },
429 }),
430 }),
431 })
432 case 'ollama':
433 return createChatOptions({
434 adapter: ollamaText(model),
435 modelOptions: { options: { top_k: 1 } },
436 reasoning: 'low',
437 })
438 case 'openai':
439 return createChatOptions({
440 adapter: createOpenaiChat(
441 model,
442 requireApiKey(apiKey),
443 viaCloudflareGateway('openai'),
444 ),
445 // A Sign in with ChatGPT token is not an `sk-` key. That
446 // route needs store: false and rejects prompt_cache_retention.
447 modelOptions: apiKey?.startsWith('sk-')
448 ? {
449 prompt_cache_key: 'user-session-12345',
450 prompt_cache_retention: '24h',
451 }
452 : { store: false },
453 })
454 }
455 }
456​
457 try {
458 const provider: Provider = selection.provider
459 const resolvedKey = resolveByokApiKey(request, provider)
460 if (resolvedKey.missing) {
461 return byokMissing(resolvedKey.provider)
462 }
463 // Get typed adapter options using createChatOptions pattern
464 // Cloudflare needs a second BYOK value: the account the token belongs to.
465 const cloudflareAccountId =
466 provider === 'cloudflare'
467 ? getByokKey(request, cloudflareAccountByok)
468 : null
469 if (provider === 'cloudflare' && !cloudflareAccountId) {
470 return byokMissing(cloudflareAccountByok)
471 }
472 const options = buildChatOptions(
473 selection,
474 resolvedKey.apiKey,
475 cloudflareAccountId,
476 )
477​
478 // All providers (including gemini-interactions) get the full
479 // server-tool set merged with whatever client-side tools the
480 // request brought. Historical note: gemini-interactions used
481 // to be excluded because of an assumed `anyOf` incompatibility
482 // and an empty-`required: []` rejection. The first turned out
483 // to be a non-issue against the live API and the second is now
484 // sanitized inside `@tanstack/ai-gemini/experimental`.
485 const mergedTools = mergeAgentTools(serverTools, params.tools)
486​
487 const stream = chat({
488 ...options,
489 tools: mergedTools,
490 middleware: [loggingMiddleware, runtimeContextMiddleware],
491 context: runtimeContext,
492 systemPrompts: [SYSTEM_PROMPT],
493 agentLoopStrategy: maxIterations(20),
494 messages: params.messages,
495 threadId: params.threadId,
496 runId: params.runId,
497 abortController,
498 })
499 return toServerSentEventsResponse(stream, { abortController })
500 } catch (error: any) {
501 console.error('[API Route] Error in chat request:', {
502 message: error?.message,
503 name: error?.name,
504 status: error?.status,
505 statusText: error?.statusText,
506 code: error?.code,
507 type: error?.type,
508 stack: error?.stack,
509 error: error,
510 })
511 // If request was aborted, return early (don't send error response)
512 if (error.name === 'AbortError' || abortController.signal.aborted) {
513 return new Response(null, { status: 499 }) // 499 = Client Closed Request
514 }
515 return new Response(
516 JSON.stringify({
517 error: error.message || 'An error occurred',
518 }),
519 {
520 status: 500,
521 headers: { 'Content-Type': 'application/json' },
522 },
523 )
524 }
525 },
526 },
527 },
528})