Open History to see the last commit
1import { useCallback, useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 ChevronDown,
5 ChevronRight,
6 Code,
7 Loader2,
8 Play,
9 RefreshCw,
10 Sparkles,
11 Trash2,
12 X,
13} from 'lucide-react'
14import { Header } from '@/components'
15
16export const Route = createFileRoute('/_structured-output/structured-output')({
17 component: StructuredOutputPage,
18})
19
20const FIXED_PROMPT =
21 'Use city tools to compare Tokyo and Barcelona. Then produce a concise travel recommendation report with key findings and practical next steps.'
22
23interface SnippetWithCode {
24 id: string
25 name: string
26 description: string
27 code: string
28 trustLevel: 'untrusted' | 'provisional' | 'trusted'
29 usageHints?: Array<string>
30 stats?: { executions: number; successRate: number }
31}
32
33function SnippetsDialog({
34 open,
35 onClose,
36 snippets,
37 onDelete,
38 onDeleteAll,
39 onRefresh,
40 isLoading,
41}: {
42 open: boolean
43 onClose: () => void
44 snippets: Array<SnippetWithCode>
45 onDelete: (name: string) => void
46 onDeleteAll: () => void
47 onRefresh: () => void
48 isLoading: boolean
49}) {
50 const [expandedId, setExpandedId] = useState<string | null>(null)
51
52 if (!open) return null
53
54 const trustColors: Record<string, string> = {
55 untrusted: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
56 provisional: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
57 trusted: 'bg-green-500/20 text-green-400 border-green-500/30',
58 }
59
60 return (
61 <div className="fixed inset-0 z-50 flex items-center justify-center">
62 <div className="absolute inset-0 bg-black/60" onClick={onClose} />
63
64 <div className="relative z-10 w-full max-w-2xl max-h-[80vh] flex flex-col bg-gray-900 border border-gray-700 rounded-xl shadow-2xl mx-4">
65 <div className="flex items-center justify-between px-5 py-4 border-b border-gray-700">
66 <div className="flex items-center gap-2">
67 <Sparkles className="w-4 h-4 text-purple-400" />
68 <h2 className="font-semibold text-white">
69 Registered Snippets
70 <span className="ml-2 text-sm text-gray-400 font-normal">
71 ({snippets.length})
72 </span>
73 </h2>
74 </div>
75 <div className="flex items-center gap-2">
76 <button
77 onClick={onRefresh}
78 disabled={isLoading}
79 className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-gray-700/50 transition-colors disabled:opacity-50"
80 title="Refresh snippets"
81 >
82 <RefreshCw
83 className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`}
84 />
85 </button>
86 {snippets.length > 0 && (
87 <button
88 onClick={() => {
89 if (confirm(`Delete all ${snippets.length} snippets?`)) {
90 onDeleteAll()
91 }
92 }}
93 className="px-3 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/40 text-red-400 border border-red-500/30 rounded-lg transition-colors flex items-center gap-1.5"
94 >
95 <Trash2 className="w-3.5 h-3.5" />
96 Delete All
97 </button>
98 )}
99 <button
100 onClick={onClose}
101 className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-gray-700/50 transition-colors"
102 >
103 <X className="w-4 h-4" />
104 </button>
105 </div>
106 </div>
107
108 <div className="flex-1 overflow-y-auto p-3 space-y-1">
109 {snippets.length === 0 ? (
110 <div className="py-12 text-center text-gray-500">
111 <Sparkles className="w-8 h-8 mx-auto mb-3 text-gray-600" />
112 <p className="text-sm font-medium">No snippets registered yet</p>
113 <p className="text-xs mt-1 text-gray-600">
114 Enable "With Snippets" and run the demo — the AI will create
115 reusable snippets as it works.
116 </p>
117 </div>
118 ) : (
119 snippets.map((snippet) => {
120 const isExpanded = expandedId === snippet.id
121 return (
122 <div
123 key={snippet.id}
124 className="rounded-lg border border-gray-700 overflow-hidden"
125 >
126 <button
127 className="w-full flex items-center gap-3 px-4 py-3 bg-gray-800/50 hover:bg-gray-800 transition-colors text-left"
128 onClick={() =>
129 setExpandedId(isExpanded ? null : snippet.id)
130 }
131 >
132 {isExpanded ? (
133 <ChevronDown className="w-4 h-4 text-gray-400 shrink-0" />
134 ) : (
135 <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
136 )}
137 <div className="flex-1 min-w-0">
138 <div className="flex items-center gap-2">
139 <code className="text-sm font-mono text-purple-300">
140 snippet_{snippet.name}
141 </code>
142 <span
143 className={`text-xs px-1.5 py-0.5 rounded border ${trustColors[snippet.trustLevel] ?? ''}`}
144 >
145 {snippet.trustLevel}
146 </span>
147 </div>
148 {snippet.description && (
149 <p className="text-xs text-gray-400 mt-0.5 truncate">
150 {snippet.description}
151 </p>
152 )}
153 </div>
154 <button
155 onClick={(e) => {
156 e.stopPropagation()
157 if (confirm(`Delete snippet "${snippet.name}"?`)) {
158 onDelete(snippet.name)
159 }
160 }}
161 className="p-1.5 rounded text-gray-500 hover:text-red-400 hover:bg-red-400/10 transition-colors shrink-0"
162 title="Delete snippet"
163 >
164 <Trash2 className="w-3.5 h-3.5" />
165 </button>
166 </button>
167
168 {isExpanded && (
169 <div className="border-t border-gray-700 bg-gray-950">
170 <pre className="p-4 text-xs text-gray-300 overflow-x-auto max-h-64 overflow-y-auto font-mono leading-relaxed">
171 {snippet.code || '// No code available'}
172 </pre>
173 </div>
174 )}
175 </div>
176 )
177 })
178 )}
179 </div>
180 </div>
181 </div>
182 )
183}
184
185function StructuredOutputPage() {
186 const [result, setResult] = useState<unknown>(null)
187 const [error, setError] = useState<string | null>(null)
188 const [isLoading, setIsLoading] = useState(false)
189
190 const [withSnippets, setWithSnippets] = useState(false)
191 const [snippets, setSnippets] = useState<Array<SnippetWithCode>>([])
192 const [isLoadingSnippets, setIsLoadingSnippets] = useState(false)
193 const [snippetsDialogOpen, setSnippetsDialogOpen] = useState(false)
194
195 const loadSnippets = useCallback(async () => {
196 setIsLoadingSnippets(true)
197 try {
198 const response = await fetch('/api/structured-output-snippets')
199 if (response.ok) {
200 const data = await response.json()
201 setSnippets(data)
202 }
203 } catch (err) {
204 console.error('Failed to load snippets:', err)
205 } finally {
206 setIsLoadingSnippets(false)
207 }
208 }, [])
209
210 const deleteSnippet = useCallback(async (name: string) => {
211 try {
212 const response = await fetch(
213 `/api/structured-output-snippets?name=${encodeURIComponent(name)}`,
214 { method: 'DELETE' },
215 )
216 if (response.ok) {
217 setSnippets((prev) => prev.filter((s) => s.name !== name))
218 }
219 } catch (err) {
220 console.error('Failed to delete snippet:', err)
221 }
222 }, [])
223
224 const deleteAllSnippets = useCallback(async () => {
225 try {
226 const response = await fetch('/api/structured-output-snippets?all=true', {
227 method: 'DELETE',
228 })
229 if (response.ok) {
230 setSnippets([])
231 }
232 } catch (err) {
233 console.error('Failed to delete all snippets:', err)
234 }
235 }, [])
236
237 useEffect(() => {
238 if (withSnippets) {
239 loadSnippets()
240 }
241 }, [withSnippets, loadSnippets])
242
243 const runDemo = useCallback(async () => {
244 setResult(null)
245 setError(null)
246 setIsLoading(true)
247
248 try {
249 const response = await fetch('/api/structured-output', {
250 method: 'POST',
251 headers: { 'Content-Type': 'application/json' },
252 body: JSON.stringify({
253 prompt: FIXED_PROMPT,
254 provider: 'anthropic',
255 model: 'claude-haiku-4-5',
256 withSnippets,
257 }),
258 })
259
260 const data = await response.json()
261
262 if (!response.ok) {
263 setError(data.error || 'Request failed')
264 return
265 }
266
267 setResult(data)
268
269 if (withSnippets) {
270 loadSnippets()
271 }
272 } catch (err) {
273 setError(err instanceof Error ? err.message : 'Request failed')
274 } finally {
275 setIsLoading(false)
276 }
277 }, [withSnippets, loadSnippets])
278
279 return (
280 <div className="flex flex-col h-screen bg-gray-900">
281 <Header />
282
283 <div className="flex-1 flex flex-col max-w-5xl mx-auto w-full">
284 <div className="border-b border-pink-500/20 bg-gray-800 p-4 space-y-3">
285 <p className="text-sm text-gray-400">Fixed prompt:</p>
286 <p className="text-sm text-gray-100 bg-gray-900 border border-gray-700 rounded-lg p-3">
287 {FIXED_PROMPT}
288 </p>
289
290 <div className="flex items-center gap-4">
291 <button
292 onClick={runDemo}
293 disabled={isLoading}
294 className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-pink-600 hover:bg-pink-500 text-white font-medium disabled:opacity-50"
295 >
296 {isLoading ? (
297 <Loader2 className="w-4 h-4 animate-spin" />
298 ) : (
299 <Play className="w-4 h-4" />
300 )}
301 {isLoading ? 'Running...' : 'Run Demo'}
302 </button>
303
304 <label className="flex items-center gap-2 cursor-pointer select-none">
305 <input
306 type="checkbox"
307 checked={withSnippets}
308 onChange={(e) => setWithSnippets(e.target.checked)}
309 className="w-4 h-4 accent-purple-500"
310 />
311 <span className="text-sm text-gray-300">With Snippets</span>
312 </label>
313
314 {withSnippets && (
315 <button
316 onClick={() => setSnippetsDialogOpen(true)}
317 className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-purple-600/20 hover:bg-purple-600/40 text-purple-300 border border-purple-500/30 rounded-lg transition-colors"
318 >
319 <Sparkles className="w-3.5 h-3.5" />
320 {snippets.length} Snippets
321 </button>
322 )}
323 </div>
324 </div>
325
326 <div className="flex-1 overflow-y-auto p-4 space-y-3">
327 {!result && !error && !isLoading && (
328 <div className="flex-1 flex items-center justify-center text-gray-400 px-8 pt-16">
329 <div className="max-w-2xl text-center space-y-3">
330 <Sparkles className="w-10 h-10 mx-auto text-pink-400/80" />
331 <p className="text-lg font-medium">Structured Output Demo</p>
332 <p className="text-sm text-gray-500">
333 Click Run Demo. The model will use Code Mode tools to research
334 cities, then return structured JSON.
335 </p>
336 </div>
337 </div>
338 )}
339
340 {isLoading && (
341 <div className="text-sm text-pink-300 animate-pulse">
342 Running Code Mode and generating structured output...
343 </div>
344 )}
345
346 {error && (
347 <div className="text-sm text-red-300 border border-red-500/30 bg-red-900/20 rounded-lg p-3">
348 {error}
349 </div>
350 )}
351
352 {result !== null && (
353 <div className="space-y-3">
354 <div className="flex items-center gap-2 text-sm text-pink-300">
355 <Code className="w-4 h-4" />
356 Structured JSON Output
357 </div>
358 <pre className="text-xs text-gray-100 bg-gray-900 border border-gray-700 rounded-lg p-4 overflow-x-auto">
359 {JSON.stringify(result, null, 2)}
360 </pre>
361 </div>
362 )}
363 </div>
364 </div>
365
366 <SnippetsDialog
367 open={snippetsDialogOpen}
368 onClose={() => setSnippetsDialogOpen(false)}
369 snippets={snippets}
370 onDelete={deleteSnippet}
371 onDeleteAll={deleteAllSnippets}
372 onRefresh={loadSnippets}
373 isLoading={isLoadingSnippets}
374 />
375 </div>
376 )
377}