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

generations.structured-output.tsx

620 lines24.6 KB

1import { useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { parsePartialJSON } from '@tanstack/ai'
4import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
5import { GuitarRecommendationSchema } from './api.structured-output'
6import type { StreamChunk } from '@tanstack/ai'
7​
8const SAMPLE_PROMPT =
9 'I play indie rock and have a $1500 budget. Recommend two electric guitars and one acoustic to round out my rig.'
10​
11type Provider =
12 | 'openai'
13 | 'openai-chat'
14 | 'anthropic'
15 | 'gemini'
16 | 'grok'
17 | 'groq'
18 | 'openrouter'
19 | 'openrouter-responses'
20​
21const PROVIDER_MODELS: Record<
22 Provider,
23 Array<{ value: string; label: string }>
24> = {
25 openai: [
26 { value: 'gpt-5.2', label: 'GPT-5.2 (frontier)' },
27 { value: 'gpt-5.2-pro', label: 'GPT-5.2 Pro' },
28 { value: 'gpt-5.1', label: 'GPT-5.1' },
29 { value: 'gpt-5', label: 'GPT-5' },
30 { value: 'gpt-5-mini', label: 'GPT-5 Mini' },
31 { value: 'gpt-4o', label: 'GPT-4o' },
32 ],
33 // OpenAI Chat Completions: same model surface, older `/v1/chat/completions`
34 // wire format. The reasoning-summary opt-in isn't available here, so
35 // streaming reasoning won't be surfaced for gpt-5.x even though the model
36 // is still doing it under the hood.
37 'openai-chat': [
38 { value: 'gpt-4o', label: 'GPT-4o' },
39 { value: 'gpt-5-mini', label: 'GPT-5 Mini' },
40 { value: 'gpt-5', label: 'GPT-5' },
41 { value: 'gpt-5.1', label: 'GPT-5.1' },
42 { value: 'gpt-5.2', label: 'GPT-5.2 (frontier)' },
43 ],
44 // Anthropic: Claude 4.5+ models stream the schema-constrained JSON
45 // natively via the #605 combined-mode path
46 // (`output_config.format` + `tools` in one beta Messages call). Older
47 // models fall back to the forced-tool-use workaround in
48 // `structuredOutput` (no real streaming), so they're omitted here.
49 //
50 // Default entries do NOT enable thinking — most demo flows just want
51 // the structured output. The `:thinking-max` synthetic suffix is a
52 // dropdown-only marker (stripped before the model id reaches the
53 // adapter) that opts into thinking with `reasoning: 'max'` plus a
54 // bumped `maxTokens` budget so the reasoning + JSON both fit.
55 anthropic: [
56 { value: 'claude-sonnet-5', label: 'Claude Sonnet 5' },
57 { value: 'claude-fable-5', label: 'Claude Fable 5' },
58 { value: 'claude-opus-4-8', label: 'Claude Opus 4.8' },
59 { value: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
60 { value: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },
61 { value: 'claude-opus-4-5', label: 'Claude Opus 4.5' },
62 { value: 'claude-opus-4-6', label: 'Claude Opus 4.6' },
63 { value: 'claude-opus-4-7', label: 'Claude Opus 4.7' },
64 {
65 value: 'claude-opus-4-7:thinking-max',
66 label: 'Claude Opus 4.7 (Max Thinking)',
67 },
68 { value: 'claude-haiku-4-5', label: 'Claude Haiku 4.5' },
69 ],
70 // Gemini 3.x stream the schema-constrained JSON natively via the #605
71 // combined-mode path (`responseSchema` + `tools` in one
72 // `generateContentStream`). Gemini 2.x is omitted because the docs
73 // mark the tools-with-schema combination as brittle and the demo would
74 // hit the engine's legacy finalization path instead.
75 //
76 // Naming gotcha: Google uses a dash separator for the major version
77 // (`gemini-3-flash-preview`) but a dot separator for the minor version
78 // (`gemini-3.1-pro-preview`). The dropdown values mirror the canonical
79 // ids from `ai-gemini/model-meta` — `GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS`
80 // keys on the exact string, so any drift here silently breaks
81 // combined-mode routing.
82 gemini: [
83 { value: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash' },
84 { value: 'gemini-3.7-flash', label: 'Gemini 3.7 Flash' },
85 { value: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' },
86 { value: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash' },
87 { value: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' },
88 { value: 'gemini-3-flash-preview', label: 'Gemini 3 Flash (Preview)' },
89 { value: 'gemini-3.1-pro-preview', label: 'Gemini 3.1 Pro (Preview)' },
90 { value: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
91 {
92 value: 'gemini-3.1-flash-lite-preview',
93 label: 'Gemini 3.1 Flash Lite (Preview)',
94 },
95 ],
96 // The Grok adapter uses xAI's Responses API and intentionally exposes only
97 // these chat models.
98 grok: [
99 { value: 'grok-build-0.1', label: 'Grok Build 0.1' },
100 { value: 'grok-4.3', label: 'Grok 4.3' },
101 ],
102 groq: [
103 {
104 value: 'meta-llama/llama-4-maverick-17b-128e-instruct',
105 label: 'Llama 4 Maverick 17B',
106 },
107 {
108 value: 'meta-llama/llama-4-scout-17b-16e-instruct',
109 label: 'Llama 4 Scout 17B',
110 },
111 {
112 value: 'moonshotai/kimi-k2-instruct-0905',
113 label: 'Kimi K2 Instruct',
114 },
115 { value: 'llama-3.3-70b-versatile', label: 'Llama 3.3 70B Versatile' },
116 { value: 'openai/gpt-oss-120b', label: 'GPT-OSS 120B' },
117 ],
118 openrouter: [
119 { value: 'anthropic/claude-opus-4.6', label: 'Claude Opus 4.6' },
120 { value: 'anthropic/claude-sonnet-4.6', label: 'Claude Sonnet 4.6' },
121 { value: 'openai/gpt-5.2', label: 'GPT-5.2 (via OpenRouter)' },
122 { value: 'x-ai/grok-4.1-fast', label: 'Grok 4.1 Fast (via OpenRouter)' },
123 ],
124 // OpenRouter Responses (beta) endpoint — same upstream models, but the
125 // request/response uses the Responses API wire format. Useful to compare
126 // streaming behaviour against the chat-completions adapter above.
127 'openrouter-responses': [
128 { value: 'anthropic/claude-opus-4.6', label: 'Claude Opus 4.6' },
129 { value: 'anthropic/claude-sonnet-4.6', label: 'Claude Sonnet 4.6' },
130 { value: 'openai/gpt-5.2', label: 'GPT-5.2 (via OpenRouter)' },
131 { value: 'x-ai/grok-4.1-fast', label: 'Grok 4.1 Fast (via OpenRouter)' },
132 ],
134​
135interface PartialRecommendation {
136 name?: string
137 brand?: string
138 type?: 'acoustic' | 'electric' | 'bass' | 'classical' | string
139 priceRangeUsd?: { min?: number; max?: number }
140 reason?: string
142​
143interface PartialResult {
144 title?: string
145 summary?: string
146 recommendations?: Array<PartialRecommendation>
147 nextSteps?: Array<string>
149​
150interface StreamChunkPayload {
151 type: string
152 delta?: string
153 content?: string
154 name?: string
155 value?: { object?: unknown; raw?: string; reasoning?: string }
156 message?: string
158​
159// Pick the last meaningful sentence/line out of an accumulating reasoning
160// stream so the UI can render a single rolling line of "what it's thinking
161// right now" rather than a growing wall of text.
162function latestThought(reasoning: string): string {
163 const trimmed = reasoning.trimEnd()
164 if (!trimmed) return ''
165 // Prefer the last sentence; fall back to the last newline-delimited line.
166 const sentenceMatch = trimmed.match(/[^.!?\n]+[.!?]?\s*$/)
167 const candidate = sentenceMatch ? sentenceMatch[0] : trimmed
168 const last = candidate.split('\n').filter(Boolean).pop() ?? candidate
169 return last.trim()
171​
172function StructuredOutputPage() {
173 const providerId = 'structured-output-provider'
174 const modelId = 'structured-output-model'
175 const promptId = 'structured-output-prompt'
176 const [prompt, setPrompt] = useState(SAMPLE_PROMPT)
177 const [provider, setProvider] = useState<Provider>('openai')
178 const [model, setModel] = useState<string>(PROVIDER_MODELS.openai[0].value)
179 const [stream, setStream] = useState(true)
180 const [result, setResult] = useState<PartialResult | null>(null)
181 const [rawJson, setRawJson] = useState<string>('')
182 const [deltaCount, setDeltaCount] = useState(0)
183 const [isStreaming, setIsStreaming] = useState(false)
184 const [hasFinalResult, setHasFinalResult] = useState(false)
185 const [reasoningLine, setReasoningLine] = useState<string>('')
186 const [reasoningFull, setReasoningFull] = useState<string>('')
187 const [error, setError] = useState<string | null>(null)
188 const [phaseCounts, setPhaseCounts] = useState<Record<string, number> | null>(
189 null,
190 )
191 const sawCompleteRef = useRef(false)
192​
193 const onProviderChange = (next: Provider) => {
194 setProvider(next)
195 setModel(PROVIDER_MODELS[next][0].value)
196 }
197​
198 const resetLocal = () => {
199 setResult(null)
200 setRawJson('')
201 setDeltaCount(0)
202 setHasFinalResult(false)
203 setReasoningLine('')
204 setReasoningFull('')
205 setError(null)
206 setPhaseCounts(null)
207 }
208​
209 const handleChunk = (chunk: StreamChunk) => {
210 const payload = chunk as StreamChunkPayload
211​
212 if (payload.type === 'TEXT_MESSAGE_CONTENT' && payload.delta) {
213 setRawJson((current) => {
214 const next = current + payload.delta
215 const partial = parsePartialJSON(next) as PartialResult | undefined
216 if (partial && typeof partial === 'object') {
217 setResult(partial)
218 }
219 return next
220 })
221 setDeltaCount((current) => current + 1)
222 } else if (payload.type === 'REASONING_MESSAGE_CONTENT' && payload.delta) {
223 setReasoningFull((current) => {
224 const next = current + payload.delta
225 setReasoningLine(latestThought(next))
226 return next
227 })
228 } else if (
229 payload.type === 'CUSTOM' &&
230 payload.name === 'phase-counts' &&
231 payload.value
232 ) {
233 setPhaseCounts(payload.value as unknown as Record<string, number>)
234 } else if (
235 payload.type === 'CUSTOM' &&
236 payload.name === 'structured-output.complete' &&
237 payload.value?.object
238 ) {
239 sawCompleteRef.current = true
240 setResult(payload.value.object as PartialResult)
241 setHasFinalResult(true)
242 if (
243 typeof (payload.value as { reasoning?: string }).reasoning === 'string'
244 ) {
245 const finalReasoning = (payload.value as { reasoning: string })
246 .reasoning
247 setReasoningFull(finalReasoning)
248 setReasoningLine(latestThought(finalReasoning))
249 }
250 }
251 }
252​
253 const chat = useChat({
254 threadId: 'structured-output:useChat',
255 outputSchema: GuitarRecommendationSchema,
256 connection: fetchServerSentEvents('/api/structured-output'),
257 forwardedProps: { provider, model, stream },
258 onChunk: handleChunk,
259 onError: (err) => {
260 setError(err.message)
261 },
262 })
263​
264 const isLoading = chat.isLoading
265​
266 const reset = () => {
267 resetLocal()
268 chat.clear()
269 }
270​
271 const handleGenerate = async () => {
272 if (!prompt.trim()) return
273 sawCompleteRef.current = false
274 resetLocal()
275 chat.clear()
276 setIsStreaming(stream)
277 await chat.sendMessage(prompt.trim())
278 setIsStreaming(false)
279 if (stream && !sawCompleteRef.current && chat.status === 'ready') {
280 setError('Stream ended before structured-output.complete')
281 }
282 }
283​
284 const handleAbort = () => {
285 sawCompleteRef.current = true
286 chat.stop()
287 setIsStreaming(false)
288 setError('Aborted')
289 }
290​
291 const renderingPartial = isStreaming && !hasFinalResult
292 const recommendations = result?.recommendations ?? []
293 const nextSteps = result?.nextSteps ?? []
294​
295 return (
296 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
297 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
298 <h2 className="text-xl font-semibold">Structured Output</h2>
299 <p className="text-sm text-gray-400 mt-1">
300 Calls <code className="text-orange-400">chat()</code> with an{' '}
301 <code className="text-orange-400">outputSchema</code>. Toggle{' '}
302 <code className="text-orange-400">stream</code> to exercise{' '}
303 <code className="text-orange-400">structuredOutputStream</code> on the
304 selected provider; the UI fills in progressively via{' '}
305 <code className="text-orange-400">parsePartialJSON</code>, then snaps
306 to the validated payload from the terminal{' '}
307 <code className="text-orange-400">structured-output.complete</code>{' '}
308 event. Reasoning models surface a live thinking strip from{' '}
309 <code className="text-orange-400">REASONING_MESSAGE_CONTENT</code>{' '}
310 deltas — openai (Responses API), openrouter, xAI (
311 <code className="text-orange-400">delta.reasoning_content</code>), and
312 Groq (<code className="text-orange-400">delta.reasoning</code>) all
313 stream chain-of-thought.
314 </p>
315 </div>
316​
317 <div className="flex-1 overflow-y-auto p-6">
318 <div className="max-w-2xl mx-auto space-y-6">
319 <div className="grid grid-cols-2 gap-3">
320 <div className="space-y-2">
321 <label htmlFor={providerId} className="text-sm text-gray-400">
322 Provider
323 </label>
324 <select
325 id={providerId}
326 value={provider}
327 onChange={(e) => onProviderChange(e.target.value as Provider)}
328 disabled={isLoading}
329 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
330 >
331 <option value="openai">OpenAI (Responses)</option>
332 <option value="openai-chat">OpenAI (Chat Completions)</option>
333 <option value="anthropic">Anthropic (Claude 4.5+)</option>
334 <option value="gemini">Gemini (3.x)</option>
335 <option value="grok">Grok (xAI)</option>
336 <option value="groq">Groq</option>
337 <option value="openrouter">
338 OpenRouter (Chat Completions)
339 </option>
340 <option value="openrouter-responses">
341 OpenRouter (Responses beta)
342 </option>
343 </select>
344 </div>
345 <div className="space-y-2">
346 <label htmlFor={modelId} className="text-sm text-gray-400">
347 Model
348 </label>
349 <select
350 id={modelId}
351 value={model}
352 onChange={(e) => setModel(e.target.value)}
353 disabled={isLoading}
354 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
355 >
356 {PROVIDER_MODELS[provider].map((opt) => (
357 <option key={opt.value} value={opt.value}>
358 {opt.label}
359 </option>
360 ))}
361 </select>
362 </div>
363 </div>
364​
365 <label className="flex items-center gap-2 text-sm text-gray-300">
366 <input
367 type="checkbox"
368 checked={stream}
369 onChange={(e) => setStream(e.target.checked)}
370 disabled={isLoading}
371 className="accent-orange-500"
372 />
373 Stream (single-request{' '}
374 <code className="text-orange-400">stream: true</code> +{' '}
375 <code className="text-orange-400">
376 response_format: json_schema
377 </code>
378 )
379 </label>
380​
381 <div className="space-y-3">
382 <label htmlFor={promptId} className="text-sm text-gray-400">
383 Prompt
384 </label>
385 <textarea
386 id={promptId}
387 value={prompt}
388 onChange={(e) => setPrompt(e.target.value)}
389 placeholder="Describe what you want recommendations for..."
390 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500/50 resize-none"
391 rows={6}
392 disabled={isLoading}
393 />
394 </div>
395​
396 <div className="flex gap-3">
397 <button
398 onClick={handleGenerate}
399 disabled={!prompt.trim() || isLoading}
400 className="px-6 py-2 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-lg text-sm font-medium transition-colors"
401 >
402 {isLoading
403 ? stream
404 ? 'Streaming...'
405 : 'Generating...'
406 : 'Generate'}
407 </button>
408 {isLoading && stream && (
409 <button
410 onClick={handleAbort}
411 className="px-6 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
412 >
413 Abort
414 </button>
415 )}
416 {(result || rawJson) && !isLoading && (
417 <button
418 onClick={reset}
419 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
420 >
421 Clear
422 </button>
423 )}
424 </div>
425​
426 {error && (
427 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
428 <p className="text-red-400 text-sm">{error}</p>
429 </div>
430 )}
431​
432 {(reasoningLine || reasoningFull) && (
433 <div className="p-3 bg-purple-500/5 border border-purple-500/20 rounded-lg">
434 <div className="flex items-center gap-2 text-xs text-purple-300/80">
435 <span className="uppercase tracking-wider">Thinking</span>
436 {isStreaming && !hasFinalResult && (
437 <span className="inline-block w-1.5 h-1.5 rounded-full bg-purple-400 animate-pulse" />
438 )}
439 </div>
440 <p
441 className="text-sm text-purple-100/90 mt-1 truncate"
442 title={reasoningFull}
443 >
444 {reasoningLine ||
445 reasoningFull.split('\n').filter(Boolean).slice(-1)[0] ||
446 '…'}
447 </p>
448 {reasoningFull && reasoningFull !== reasoningLine && (
449 <details className="mt-2">
450 <summary className="text-xs text-purple-300/60 cursor-pointer">
451 Full reasoning ({reasoningFull.length} chars)
452 </summary>
453 <pre className="text-xs text-purple-100/70 mt-2 whitespace-pre-wrap wrap-break-word">
454 {reasoningFull}
455 </pre>
456 </details>
457 )}
458 </div>
459 )}
460​
461 {result && (
462 <div className="space-y-4">
463 {stream && deltaCount > 0 && (
464 <p className="text-xs text-gray-500">
465 {hasFinalResult ? 'Final result' : 'Streaming'} — {deltaCount}{' '}
466 deltas received
467 {renderingPartial && (
468 <span className="ml-1 inline-block w-2 h-2 rounded-full bg-orange-500 animate-pulse" />
469 )}
470 </p>
471 )}
472​
473 {(result.title || renderingPartial) && (
474 <div
475 className={`p-4 bg-gray-800/50 border border-gray-700 rounded-lg transition-colors ${
476 renderingPartial && !result.summary
477 ? 'border-orange-500/30'
478 : ''
479 }`}
480 >
481 <h3 className="text-lg font-semibold text-white">
482 {result.title || (
483 <span className="text-gray-500 italic">
484 Generating title…
485 </span>
486 )}
487 {renderingPartial && result.title && !result.summary && (
488 <span className="ml-1 inline-block w-1.5 h-4 align-middle bg-orange-400 animate-pulse" />
489 )}
490 </h3>
491 {(result.summary || renderingPartial) && (
492 <p className="text-gray-300 mt-2 text-sm">
493 {result.summary || (
494 <span className="text-gray-500 italic">
495 Generating summary…
496 </span>
497 )}
498 </p>
499 )}
500 </div>
501 )}
502​
503 {recommendations.length > 0 && (
504 <div className="space-y-3">
505 {recommendations.map((rec, i) => {
506 const isLastWhileStreaming =
507 renderingPartial && i === recommendations.length - 1
508 return (
509 <div
510 key={i}
511 className={`p-4 bg-gray-800/50 border rounded-lg transition-colors ${
512 isLastWhileStreaming
513 ? 'border-orange-500/30'
514 : 'border-gray-700'
515 }`}
516 >
517 <div className="flex items-start justify-between gap-3">
518 <div>
519 <p className="text-white font-medium">
520 {[rec.brand, rec.name]
521 .filter(Boolean)
522 .join(' ') || (
523 <span className="text-gray-500 italic">
524 Loading…
525 </span>
526 )}
527 </p>
528 {rec.type && (
529 <p className="text-xs text-orange-400 uppercase tracking-wider mt-0.5">
530 {rec.type}
531 </p>
532 )}
533 </div>
534 {rec.priceRangeUsd?.min != null &&
535 rec.priceRangeUsd.max != null && (
536 <p className="text-sm text-gray-400 whitespace-nowrap">
537 ${rec.priceRangeUsd.min} – $
538 {rec.priceRangeUsd.max}
539 </p>
540 )}
541 </div>
542 {rec.reason && (
543 <p className="text-sm text-gray-300 mt-2">
544 {rec.reason}
545 {isLastWhileStreaming && (
546 <span className="ml-1 inline-block w-1.5 h-4 align-middle bg-orange-400 animate-pulse" />
547 )}
548 </p>
549 )}
550 </div>
551 )
552 })}
553 </div>
554 )}
555​
556 {nextSteps.length > 0 && (
557 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg">
558 <p className="text-sm text-gray-400 mb-2">Next Steps</p>
559 <ul className="list-disc list-inside text-sm text-gray-200 space-y-1">
560 {nextSteps.map((step, i) => (
561 <li key={i}>{step}</li>
562 ))}
563 </ul>
564 </div>
565 )}
566​
567 {rawJson && (
568 <details className="p-4 bg-gray-800/30 border border-gray-700/50 rounded-lg">
569 <summary className="text-sm text-gray-400 cursor-pointer">
570 Raw JSON ({rawJson.length} chars)
571 </summary>
572 <pre className="text-xs text-gray-300 mt-3 overflow-x-auto wrap-break-word whitespace-pre-wrap">
573 {rawJson}
574 </pre>
575 </details>
576 )}
577​
578 {phaseCounts && (
579 <div
580 className={`p-4 border rounded-lg ${
581 phaseCounts.structuredOutput
582 ? 'bg-emerald-900/20 border-emerald-700/50'
583 : 'bg-amber-900/20 border-amber-700/50'
584 }`}
585 >
586 <p className="text-sm font-semibold mb-2">
587 Middleware phase counts{' '}
588 <span className="font-normal text-gray-400">
589 (PR #600 verification)
590 </span>
591 </p>
592 <ul className="text-xs font-mono space-y-1">
593 {Object.entries(phaseCounts).map(([phase, count]) => (
594 <li key={phase}>
595 <span className="text-cyan-300">{phase}</span>
596 {': '}
597 <span className="text-gray-300">
598 {count} chunk{count === 1 ? '' : 's'}
599 </span>
600 </li>
601 ))}
602 </ul>
603 <p className="text-xs text-gray-400 mt-2">
604 {phaseCounts.structuredOutput
605 ? 'PR #600 verified: middleware observed chunks during the structured-output adapter call.'
606 : 'No `structuredOutput` phase observed. Either the provider response was empty, or the bug is still present.'}
607 </p>
608 </div>
609 )}
610 </div>
611 )}
612 </div>
613 </div>
614 </div>
615 )
617​
618export const Route = createFileRoute('/generations/structured-output')({
619 component: StructuredOutputPage,
620})