Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import { openaiText } from '@tanstack/ai-openai'
8import { z } from 'zod'
9import type { StreamChunk } from '@tanstack/ai'
10
11// Schema shared by every turn in this conversation. The point of this example
12// is to demonstrate that *every* assistant message carries its own typed
13// structured-output part — old turns don't get blown away by new ones.
14//
15// Constraints (`min`, `int`, `default`) are intentionally avoided here:
16// OpenAI's strict structured outputs reject `integer`, `minimum`/`maximum`,
17// `minLength`/`maxLength`, `minItems`/`maxItems`, and `default`. The system
18// prompt asks the model to satisfy these informally.
19export const RecipeSchema = z.object({
20 title: z.string().describe('A short title for the recipe'),
21 cuisine: z.string().describe('Cuisine label, e.g. "Italian", "Mexican"'),
22 servings: z.number().describe('Number of servings (a positive integer)'),
23 estimatedCostUsd: z.number().describe('Rough total grocery cost in USD'),
24 ingredients: z
25 .array(
26 z.object({
27 item: z.string(),
28 amount: z.string().describe('Quantity with unit, e.g. "200 g"'),
29 }),
30 )
31 .describe('At least one ingredient'),
32 steps: z.array(z.string()).describe('Numbered cooking steps'),
33 tips: z.array(z.string()).describe('Optional list of tips; empty if none'),
34})
35
36export type Recipe = z.infer<typeof RecipeSchema>
37
38const SYSTEM_PROMPT = `You are a chef assistant that always responds with a single recipe matching the provided JSON schema. When the user asks for modifications, produce a new recipe in the same shape that reflects the change. Stay terse — short titles, short steps.`
39
40export const Route = createFileRoute('/api/structured-chat')({
41 server: {
42 handlers: {
43 POST: async ({ request }) => {
44 if (request.signal.aborted) {
45 return new Response(null, { status: 499 })
46 }
47
48 // Use { once: true } and re-check `aborted` after attaching the
49 // listener: between the early-return above and addEventListener the
50 // signal can fire and we'd miss the event otherwise.
51 const abortController = new AbortController()
52 const onAbort = () => abortController.abort()
53 request.signal.addEventListener('abort', onAbort, { once: true })
54 if (request.signal.aborted) {
55 onAbort()
56 }
57
58 let params
59 try {
60 params = await chatParamsFromRequestBody(await request.json())
61 } catch (error) {
62 return new Response(
63 error instanceof Error ? error.message : 'Bad request',
64 { status: 400 },
65 )
66 }
67
68 try {
69 // Cast to AsyncIterable<StreamChunk> for the SSE serializer; the
70 // structured-output stream variant carries the extra `start` /
71 // `complete` custom events that don't appear in the AGUIEvent
72 // union but are valid StreamChunks at runtime.
73 const stream = chat({
74 adapter: openaiText('gpt-4o'),
75 messages: params.messages,
76 systemPrompts: [SYSTEM_PROMPT],
77 outputSchema: RecipeSchema,
78 stream: true,
79 threadId: params.threadId,
80 runId: params.runId,
81 abortController,
82 }) as AsyncIterable<StreamChunk>
83 return toServerSentEventsResponse(stream, { abortController })
84 } catch (error) {
85 // Log full error server-side; return generic message to the client
86 // so provider/internal details (auth failures, model names, stack
87 // traces) don't leak through the 500 response body.
88 console.error('[api/structured-chat] Error:', error)
89 return new Response(
90 JSON.stringify({ error: 'Internal server error' }),
91 {
92 status: 500,
93 headers: { 'Content-Type': 'application/json' },
94 },
95 )
96 }
97 },
98 },
99 },
100})