Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import type { StructuredOutputPart } from '@tanstack/ai-client'
5import { RecipeSchema, type Recipe } from './api.structured-chat'
6โ
7// Structured-output part typed by the schema we passed to `useChat`. Pulled
8// out of the loop's lambda to keep the find() predicate readable.
9type RecipePart = StructuredOutputPart<Recipe>
10โ
11const SUGGESTIONS: ReadonlyArray<{ emoji: string; text: string; tag: string }> =
12 [
13 {
14 emoji: '๐',
15 text: 'Pasta dinner for two, under $15 total',
16 tag: 'Italian',
17 },
18 {
19 emoji: '๐ฎ',
20 text: 'A quick weeknight taco bowl',
21 tag: 'Mexican',
22 },
23 {
24 emoji: '๐ฅ',
25 text: 'High-protein vegetarian lunch, 20 minutes',
26 tag: 'Healthy',
27 },
28 {
29 emoji: '๐',
30 text: 'Comforting noodle soup for a rainy day',
31 tag: 'Asian',
32 },
33 ]
34โ
35/**
36 * Pick a food emoji per cuisine label. Defaults to a generic plate when the
37 * model returns something we haven't mapped.
38 */
39function cuisineEmoji(cuisine: string | undefined): string {
40 if (!cuisine) return '๐ฝ๏ธ'
41 const c = cuisine.toLowerCase()
42 if (c.includes('italian')) return '๐'
43 if (c.includes('mexican')) return '๐ฎ'
44 if (c.includes('japanese') || c.includes('sushi')) return '๐ฃ'
45 if (c.includes('chinese')) return '๐ฅก'
46 if (c.includes('thai')) return '๐'
47 if (c.includes('indian')) return '๐'
48 if (c.includes('french')) return '๐ฅ'
49 if (c.includes('greek') || c.includes('mediterranean')) return '๐ซ'
50 if (c.includes('spanish')) return '๐ฅ'
51 if (c.includes('american') || c.includes('bbq') || c.includes('barbecue'))
52 return '๐'
53 if (c.includes('vietnamese')) return '๐ฒ'
54 if (c.includes('korean')) return '๐ฑ'
55 if (c.includes('middle eastern') || c.includes('lebanese')) return '๐ง'
56 return '๐ฝ๏ธ'
57}
58โ
59/**
60 * Multi-turn structured chat โ every assistant message carries its own typed
61 * structured-output part, so old turns stay renderable as history and the
62 * latest one streams progressively.
63 *
64 * Reads `messages` directly rather than the hook-level `partial`/`final`
65 * sugar; those two are derived from the latest assistant message's part, so
66 * walking `messages` is the path that exposes history.
67 */
68function StructuredChatPage() {
69 const [input, setInput] = useState('')
70โ
71 const { messages, sendMessage, isLoading, partial, final } = useChat({
72 outputSchema: RecipeSchema,
73 connection: fetchServerSentEvents('/api/structured-chat'),
74 })
75โ
76 const handleSubmit = async (text: string) => {
77 if (!text.trim() || isLoading) return
78 setInput('')
79 await sendMessage(text.trim())
80 }
81โ
82 // Show the "Cooking up your recipeโฆ" placeholder only while we're between
83 // sendMessage() and the first assistant chunk on a fresh turn.
84 const isAwaitingFirstChunk =
85 isLoading && messages[messages.length - 1]?.role === 'user'
86โ
87 return (
88 <div className="flex flex-col h-[calc(100vh-72px)] bg-gradient-to-b from-stone-50 to-amber-50 text-stone-900">
89 <div className="border-b border-amber-200/60 bg-white/70 backdrop-blur px-6 py-5">
90 <div className="max-w-3xl mx-auto flex items-center gap-3">
91 <div className="text-3xl">๐จโ๐ณ</div>
92 <div>
93 <h2 className="text-xl font-semibold tracking-tight text-stone-900">
94 Sous Chef
95 </h2>
96 <p className="text-sm text-stone-600">
97 Tell me what you're in the mood for. I'll plate up a recipe โ and
98 I'll remember the last one if you want me to tweak it.
99 </p>
100 </div>
101 </div>
102 </div>
103โ
104 <div className="flex-1 overflow-y-auto px-6 py-8">
105 <div className="max-w-3xl mx-auto space-y-8">
106 {messages.length === 0 && <EmptyState onPick={handleSubmit} />}
107โ
108 {messages.map((m) => {
109 if (m.role === 'user') {
110 const text = m.parts
111 .filter((p) => p.type === 'text')
112 .map((p) => p.content)
113 .join('')
114 return <UserPrompt key={m.id} text={text} />
115 }
116 if (m.role === 'assistant') {
117 const recipePart = m.parts.find(
118 (p): p is RecipePart => p.type === 'structured-output',
119 )
120 if (!recipePart) return null
121 return <RecipeCard key={m.id} part={recipePart} />
122 }
123 return null
124 })}
125โ
126 {isAwaitingFirstChunk && <CookingPlaceholder />}
127โ
128 {messages.length > 0 && (
129 <div className="rounded-xl border border-amber-200/60 bg-white/50 px-4 py-3 text-xs text-stone-500 font-mono">
130 <div className="flex justify-between gap-4">
131 <span>
132 <span className="text-stone-400">latest final โ</span>{' '}
133 {final ? (
134 <span className="text-stone-800">{final.title}</span>
135 ) : (
136 <em className="text-stone-400">null</em>
137 )}
138 </span>
139 <span>
140 <span className="text-stone-400">partial.title โ</span>{' '}
141 {partial.title ? (
142 <span className="text-stone-800">{partial.title}</span>
143 ) : (
144 <em className="text-stone-400">โ</em>
145 )}
146 </span>
147 </div>
148 </div>
149 )}
150 </div>
151 </div>
152โ
153 <div className="border-t border-amber-200/60 bg-white/70 backdrop-blur px-6 py-4">
154 <div className="max-w-3xl mx-auto flex gap-3">
155 <input
156 type="text"
157 value={input}
158 onChange={(e) => setInput(e.target.value)}
159 onKeyDown={(e) => {
160 if (e.key === 'Enter' && !e.shiftKey) {
161 e.preventDefault()
162 void handleSubmit(input)
163 }
164 }}
165 placeholder="What should we cook?"
166 disabled={isLoading}
167 className="flex-1 rounded-full border border-stone-200 bg-white px-5 py-3 text-sm text-stone-900 placeholder-stone-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-amber-400/60 focus:border-amber-300 disabled:opacity-50 transition"
168 />
169 <button
170 onClick={() => handleSubmit(input)}
171 disabled={!input.trim() || isLoading}
172 className="px-6 py-3 bg-amber-600 hover:bg-amber-700 disabled:bg-stone-200 disabled:text-stone-400 text-white rounded-full text-sm font-medium shadow-sm transition-colors"
173 >
174 {isLoading ? 'Cookingโฆ' : 'Cook'}
175 </button>
176 </div>
177 </div>
178 </div>
179 )
180}
181โ
182function EmptyState({ onPick }: { onPick: (text: string) => void }) {
183 return (
184 <div className="text-center py-8">
185 <div className="text-6xl mb-3">๐ฅ</div>
186 <h3 className="text-2xl font-semibold tracking-tight text-stone-900">
187 What's for dinner?
188 </h3>
189 <p className="text-sm text-stone-600 mt-1">
190 Try one of these, or describe what you're in the mood for below.
191 </p>
192 <div className="mt-6 grid grid-cols-1 sm:grid-cols-2 gap-3">
193 {SUGGESTIONS.map((s) => (
194 <button
195 key={s.text}
196 onClick={() => onPick(s.text)}
197 className="group flex items-start gap-3 text-left rounded-2xl border border-stone-200 bg-white px-4 py-3 shadow-sm hover:border-amber-300 hover:shadow-md transition"
198 >
199 <span className="text-2xl shrink-0">{s.emoji}</span>
200 <span className="flex-1">
201 <span className="block text-sm text-stone-900 group-hover:text-amber-700 transition-colors">
202 {s.text}
203 </span>
204 <span className="block text-[11px] uppercase tracking-wider text-stone-400 mt-0.5">
205 {s.tag}
206 </span>
207 </span>
208 </button>
209 ))}
210 </div>
211 </div>
212 )
213}
214โ
215function UserPrompt({ text }: { text: string }) {
216 return (
217 <div className="flex justify-end">
218 <div className="max-w-[80%] rounded-2xl rounded-tr-md bg-amber-600 text-white px-4 py-2.5 shadow-sm">
219 <div className="text-[10px] uppercase tracking-wider text-amber-100/80 mb-0.5">
220 You asked
221 </div>
222 <div className="text-sm leading-relaxed">{text}</div>
223 </div>
224 </div>
225 )
226}
227โ
228function CookingPlaceholder() {
229 return (
230 <div className="rounded-3xl border border-amber-200/60 bg-white/60 px-6 py-8 text-center">
231 <div className="text-3xl animate-bounce">๐ณ</div>
232 <p className="text-sm text-stone-600 mt-2">Cooking up your recipeโฆ</p>
233 </div>
234 )
235}
236โ
237function RecipeCard({ part }: { part: RecipePart }) {
238 // `partial` is always populated during streaming; `data` lands on complete.
239 // Read whichever is freshest โ they converge once `status === 'complete'`.
240 // Both fields are typed via the schema, so `recipe.title` etc. accesses
241 // below are checked at compile time.
242 const recipe = part.data ?? part.partial ?? ({} as Partial<Recipe>)
243 const streaming = part.status === 'streaming'
244 const errored = part.status === 'error'
245โ
246 const emoji = cuisineEmoji(recipe.cuisine)
247โ
248 return (
249 <article
250 className={`relative overflow-hidden rounded-3xl border bg-white shadow-sm transition ${
251 streaming
252 ? 'border-amber-300/80 shadow-amber-100'
253 : errored
254 ? 'border-red-300/80'
255 : 'border-stone-200'
256 }`}
257 >
258 {/* Hero banner โ stands in for a food photo. The cuisine emoji moves
259 into the gradient once the model lands the cuisine field. */}
260 <div className="relative h-32 bg-gradient-to-br from-amber-200 via-orange-200 to-rose-200 flex items-center justify-center">
261 <span className="text-6xl drop-shadow-sm">{emoji}</span>
262 {streaming && (
263 <div className="absolute top-3 right-3 flex items-center gap-1.5 rounded-full bg-white/90 px-2.5 py-1 text-[10px] uppercase tracking-wider text-amber-700 font-medium shadow-sm">
264 <span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />
265 Streaming
266 </div>
267 )}
268 {errored && (
269 <div className="absolute top-3 right-3 rounded-full bg-red-500/90 px-2.5 py-1 text-[10px] uppercase tracking-wider text-white font-medium shadow-sm">
270 Failed
271 </div>
272 )}
273 </div>
274โ
275 <div className="p-6">
276 <h3 className="text-2xl font-serif font-semibold tracking-tight text-stone-900">
277 {recipe.title || (
278 <span className="text-stone-400 italic">Plating upโฆ</span>
279 )}
280 </h3>
281โ
282 {(recipe.cuisine ||
283 recipe.servings ||
284 recipe.estimatedCostUsd !== undefined) && (
285 <div className="mt-3 flex flex-wrap items-center gap-2 text-xs">
286 {recipe.cuisine && (
287 <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 text-amber-800 px-2.5 py-1 font-medium">
288 {recipe.cuisine}
289 </span>
290 )}
291 {recipe.servings !== undefined && (
292 <span className="inline-flex items-center gap-1.5 rounded-full bg-stone-100 text-stone-700 px-2.5 py-1">
293 <span>๐ฅ</span>
294 Serves {recipe.servings}
295 </span>
296 )}
297 {recipe.estimatedCostUsd !== undefined && (
298 <span className="inline-flex items-center gap-1.5 rounded-full bg-stone-100 text-stone-700 px-2.5 py-1">
299 <span>๐ต</span>~${recipe.estimatedCostUsd.toFixed(2)}
300 </span>
301 )}
302 </div>
303 )}
304โ
305 {recipe.ingredients && recipe.ingredients.length > 0 && (
306 <section className="mt-6">
307 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-stone-500 flex items-center gap-2">
308 <span>๐ง</span> Ingredients
309 </h4>
310 <ul className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1.5">
311 {recipe.ingredients.map((ing, i) => (
312 <li
313 key={i}
314 className="flex items-baseline gap-2 text-sm text-stone-700"
315 >
316 <span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0 translate-y-[-2px]" />
317 <span>
318 <span className="font-medium text-stone-900">
319 {ing?.amount}
320 </span>{' '}
321 <span>{ing?.item}</span>
322 </span>
323 </li>
324 ))}
325 </ul>
326 </section>
327 )}
328โ
329 {recipe.steps && recipe.steps.length > 0 && (
330 <section className="mt-6">
331 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-stone-500 flex items-center gap-2">
332 <span>๐</span> Method
333 </h4>
334 <ol className="mt-3 space-y-3">
335 {recipe.steps.map((step, i) => (
336 <li key={i} className="flex gap-3">
337 <span className="shrink-0 mt-0.5 inline-flex items-center justify-center w-6 h-6 rounded-full bg-amber-600 text-white text-xs font-semibold">
338 {i + 1}
339 </span>
340 <span className="text-sm leading-relaxed text-stone-700">
341 {step}
342 </span>
343 </li>
344 ))}
345 </ol>
346 </section>
347 )}
348โ
349 {recipe.tips && recipe.tips.length > 0 && (
350 <section className="mt-6 rounded-2xl bg-amber-50 border border-amber-100 px-4 py-3">
351 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700 flex items-center gap-2">
352 <span>๐ก</span> Chef's Tips
353 </h4>
354 <ul className="mt-2 space-y-1.5">
355 {recipe.tips.map((tip, i) => (
356 <li
357 key={i}
358 className="text-sm text-stone-700 flex items-start gap-2"
359 >
360 <span className="text-amber-500 mt-0.5">โข</span>
361 <span>{tip}</span>
362 </li>
363 ))}
364 </ul>
365 </section>
366 )}
367โ
368 {errored && (
369 <div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
370 <span className="font-medium">Failed:</span>{' '}
371 {part.errorMessage ?? 'Stream failed'}
372 </div>
373 )}
374 </div>
375 </article>
376 )
377}
378โ
379export const Route = createFileRoute('/generations/structured-chat')({
380 component: StructuredChatPage,
381})