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

generations.structured-chat.tsx

382 lines14.6 KB

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 '๐Ÿฝ๏ธ'
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 threadId: 'structured-chat',
73 outputSchema: RecipeSchema,
74 connection: fetchServerSentEvents('/api/structured-chat'),
75 })
76โ€‹
77 const handleSubmit = async (text: string) => {
78 if (!text.trim() || isLoading) return
79 setInput('')
80 await sendMessage(text.trim())
81 }
82โ€‹
83 // Show the "Cooking up your recipeโ€ฆ" placeholder only while we're between
84 // sendMessage() and the first assistant chunk on a fresh turn.
85 const isAwaitingFirstChunk =
86 isLoading && messages[messages.length - 1]?.role === 'user'
87โ€‹
88 return (
89 <div className="flex flex-col h-[calc(100vh-72px)] bg-gradient-to-b from-stone-50 to-amber-50 text-stone-900">
90 <div className="border-b border-amber-200/60 bg-white/70 backdrop-blur px-6 py-5">
91 <div className="max-w-3xl mx-auto flex items-center gap-3">
92 <div className="text-3xl">๐Ÿ‘จโ€๐Ÿณ</div>
93 <div>
94 <h2 className="text-xl font-semibold tracking-tight text-stone-900">
95 Sous Chef
96 </h2>
97 <p className="text-sm text-stone-600">
98 Tell me what you're in the mood for. I'll plate up a recipe โ€” and
99 I'll remember the last one if you want me to tweak it.
100 </p>
101 </div>
102 </div>
103 </div>
104โ€‹
105 <div className="flex-1 overflow-y-auto px-6 py-8">
106 <div className="max-w-3xl mx-auto space-y-8">
107 {messages.length === 0 && <EmptyState onPick={handleSubmit} />}
108โ€‹
109 {messages.map((m) => {
110 if (m.role === 'user') {
111 const text = m.parts
112 .filter((p) => p.type === 'text')
113 .map((p) => p.content)
114 .join('')
115 return <UserPrompt key={m.id} text={text} />
116 }
117 if (m.role === 'assistant') {
118 const recipePart = m.parts.find(
119 (p): p is RecipePart => p.type === 'structured-output',
120 )
121 if (!recipePart) return null
122 return <RecipeCard key={m.id} part={recipePart} />
123 }
124 return null
125 })}
126โ€‹
127 {isAwaitingFirstChunk && <CookingPlaceholder />}
128โ€‹
129 {messages.length > 0 && (
130 <div className="rounded-xl border border-amber-200/60 bg-white/50 px-4 py-3 text-xs text-stone-500 font-mono">
131 <div className="flex justify-between gap-4">
132 <span>
133 <span className="text-stone-400">latest final โ†’</span>{' '}
134 {final ? (
135 <span className="text-stone-800">{final.title}</span>
136 ) : (
137 <em className="text-stone-400">null</em>
138 )}
139 </span>
140 <span>
141 <span className="text-stone-400">partial.title โ†’</span>{' '}
142 {partial.title ? (
143 <span className="text-stone-800">{partial.title}</span>
144 ) : (
145 <em className="text-stone-400">โ€”</em>
146 )}
147 </span>
148 </div>
149 </div>
150 )}
151 </div>
152 </div>
153โ€‹
154 <div className="border-t border-amber-200/60 bg-white/70 backdrop-blur px-6 py-4">
155 <div className="max-w-3xl mx-auto flex gap-3">
156 <input
157 type="text"
158 value={input}
159 onChange={(e) => setInput(e.target.value)}
160 onKeyDown={(e) => {
161 if (e.key === 'Enter' && !e.shiftKey) {
162 e.preventDefault()
163 void handleSubmit(input)
164 }
165 }}
166 placeholder="What should we cook?"
167 disabled={isLoading}
168 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"
169 />
170 <button
171 onClick={() => handleSubmit(input)}
172 disabled={!input.trim() || isLoading}
173 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"
174 >
175 {isLoading ? 'Cookingโ€ฆ' : 'Cook'}
176 </button>
177 </div>
178 </div>
179 </div>
180 )
182โ€‹
183function EmptyState({ onPick }: { onPick: (text: string) => void }) {
184 return (
185 <div className="text-center py-8">
186 <div className="text-6xl mb-3">๐Ÿฅ˜</div>
187 <h3 className="text-2xl font-semibold tracking-tight text-stone-900">
188 What's for dinner?
189 </h3>
190 <p className="text-sm text-stone-600 mt-1">
191 Try one of these, or describe what you're in the mood for below.
192 </p>
193 <div className="mt-6 grid grid-cols-1 sm:grid-cols-2 gap-3">
194 {SUGGESTIONS.map((s) => (
195 <button
196 key={s.text}
197 onClick={() => onPick(s.text)}
198 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"
199 >
200 <span className="text-2xl shrink-0">{s.emoji}</span>
201 <span className="flex-1">
202 <span className="block text-sm text-stone-900 group-hover:text-amber-700 transition-colors">
203 {s.text}
204 </span>
205 <span className="block text-[11px] uppercase tracking-wider text-stone-400 mt-0.5">
206 {s.tag}
207 </span>
208 </span>
209 </button>
210 ))}
211 </div>
212 </div>
213 )
215โ€‹
216function UserPrompt({ text }: { text: string }) {
217 return (
218 <div className="flex justify-end">
219 <div className="max-w-[80%] rounded-2xl rounded-tr-md bg-amber-600 text-white px-4 py-2.5 shadow-sm">
220 <div className="text-[10px] uppercase tracking-wider text-amber-100/80 mb-0.5">
221 You asked
222 </div>
223 <div className="text-sm leading-relaxed">{text}</div>
224 </div>
225 </div>
226 )
228โ€‹
229function CookingPlaceholder() {
230 return (
231 <div className="rounded-3xl border border-amber-200/60 bg-white/60 px-6 py-8 text-center">
232 <div className="text-3xl animate-bounce">๐Ÿณ</div>
233 <p className="text-sm text-stone-600 mt-2">Cooking up your recipeโ€ฆ</p>
234 </div>
235 )
237โ€‹
238function RecipeCard({ part }: { part: RecipePart }) {
239 // `partial` is always populated during streaming; `data` lands on complete.
240 // Read whichever is freshest โ€” they converge once `status === 'complete'`.
241 // Both fields are typed via the schema, so `recipe.title` etc. accesses
242 // below are checked at compile time.
243 const recipe = part.data ?? part.partial ?? ({} as Partial<Recipe>)
244 const streaming = part.status === 'streaming'
245 const errored = part.status === 'error'
246โ€‹
247 const emoji = cuisineEmoji(recipe.cuisine)
248โ€‹
249 return (
250 <article
251 className={`relative overflow-hidden rounded-3xl border bg-white shadow-sm transition ${
252 streaming
253 ? 'border-amber-300/80 shadow-amber-100'
254 : errored
255 ? 'border-red-300/80'
256 : 'border-stone-200'
257 }`}
258 >
259 {/* Hero banner โ€” stands in for a food photo. The cuisine emoji moves
260 into the gradient once the model lands the cuisine field. */}
261 <div className="relative h-32 bg-gradient-to-br from-amber-200 via-orange-200 to-rose-200 flex items-center justify-center">
262 <span className="text-6xl drop-shadow-sm">{emoji}</span>
263 {streaming && (
264 <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">
265 <span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />
266 Streaming
267 </div>
268 )}
269 {errored && (
270 <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">
271 Failed
272 </div>
273 )}
274 </div>
275โ€‹
276 <div className="p-6">
277 <h3 className="text-2xl font-serif font-semibold tracking-tight text-stone-900">
278 {recipe.title || (
279 <span className="text-stone-400 italic">Plating upโ€ฆ</span>
280 )}
281 </h3>
282โ€‹
283 {(recipe.cuisine ||
284 recipe.servings ||
285 recipe.estimatedCostUsd !== undefined) && (
286 <div className="mt-3 flex flex-wrap items-center gap-2 text-xs">
287 {recipe.cuisine && (
288 <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 text-amber-800 px-2.5 py-1 font-medium">
289 {recipe.cuisine}
290 </span>
291 )}
292 {recipe.servings !== undefined && (
293 <span className="inline-flex items-center gap-1.5 rounded-full bg-stone-100 text-stone-700 px-2.5 py-1">
294 <span>๐Ÿ‘ฅ</span>
295 Serves {recipe.servings}
296 </span>
297 )}
298 {recipe.estimatedCostUsd !== undefined && (
299 <span className="inline-flex items-center gap-1.5 rounded-full bg-stone-100 text-stone-700 px-2.5 py-1">
300 <span>๐Ÿ’ต</span>~${recipe.estimatedCostUsd.toFixed(2)}
301 </span>
302 )}
303 </div>
304 )}
305โ€‹
306 {recipe.ingredients && recipe.ingredients.length > 0 && (
307 <section className="mt-6">
308 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-stone-500 flex items-center gap-2">
309 <span>๐Ÿง‚</span> Ingredients
310 </h4>
311 <ul className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1.5">
312 {recipe.ingredients.map((ing, i) => (
313 <li
314 key={i}
315 className="flex items-baseline gap-2 text-sm text-stone-700"
316 >
317 <span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0 translate-y-[-2px]" />
318 <span>
319 <span className="font-medium text-stone-900">
320 {ing?.amount}
321 </span>{' '}
322 <span>{ing?.item}</span>
323 </span>
324 </li>
325 ))}
326 </ul>
327 </section>
328 )}
329โ€‹
330 {recipe.steps && recipe.steps.length > 0 && (
331 <section className="mt-6">
332 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-stone-500 flex items-center gap-2">
333 <span>๐Ÿ“</span> Method
334 </h4>
335 <ol className="mt-3 space-y-3">
336 {recipe.steps.map((step, i) => (
337 <li key={i} className="flex gap-3">
338 <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">
339 {i + 1}
340 </span>
341 <span className="text-sm leading-relaxed text-stone-700">
342 {step}
343 </span>
344 </li>
345 ))}
346 </ol>
347 </section>
348 )}
349โ€‹
350 {recipe.tips && recipe.tips.length > 0 && (
351 <section className="mt-6 rounded-2xl bg-amber-50 border border-amber-100 px-4 py-3">
352 <h4 className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700 flex items-center gap-2">
353 <span>๐Ÿ’ก</span> Chef's Tips
354 </h4>
355 <ul className="mt-2 space-y-1.5">
356 {recipe.tips.map((tip, i) => (
357 <li
358 key={i}
359 className="text-sm text-stone-700 flex items-start gap-2"
360 >
361 <span className="text-amber-500 mt-0.5">โ€ข</span>
362 <span>{tip}</span>
363 </li>
364 ))}
365 </ul>
366 </section>
367 )}
368โ€‹
369 {errored && (
370 <div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
371 <span className="font-medium">Failed:</span>{' '}
372 {part.errorMessage ?? 'Stream failed'}
373 </div>
374 )}
375 </div>
376 </article>
377 )
379โ€‹
380export const Route = createFileRoute('/generations/structured-chat')({
381 component: StructuredChatPage,
382})