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 { openaiChatCompletions, openaiText } from '@tanstack/ai-openai'
8import {
9 ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,
10 anthropicText,
11} from '@tanstack/ai-anthropic'
12import {
13 GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS,
14 geminiText,
15} from '@tanstack/ai-gemini'
16import { grokText } from '@tanstack/ai-grok'
17import { groqText } from '@tanstack/ai-groq'
18import {
19 openRouterResponsesText,
20 openRouterText,
21} from '@tanstack/ai-openrouter'
22import { z } from 'zod'
23import type {
24 AnyTextAdapter,
25 ChatMiddleware,
26 AdapterYieldChunk,
27 ReasoningRequest,
28} from '@tanstack/ai'
29import { EventType } from '@tanstack/ai'
30
31/**
32 * Diagnostic middleware that records which middleware phases observed chunks.
33 * Used here to verify PR #600 — middleware should now see chunks attributed
34 * to `phase === 'structuredOutput'` during the final structured-output call.
35 *
36 * Counts are exposed via:
37 * - the JSON response (`_diagnostics` field) for non-streaming
38 * - a trailing CUSTOM `phase-counts` event for streaming
39 */
40function phaseCounterMiddleware(): {
41 middleware: ChatMiddleware
42 snapshot: () => Record<string, number>
43} {
44 const counts: Record<string, number> = {}
45 return {
46 middleware: {
47 name: 'phase-counter',
48 onChunk(ctx) {
49 counts[ctx.phase] = (counts[ctx.phase] ?? 0) + 1
50 },
51 },
52 snapshot: () => ({ ...counts }),
53 }
54}
55
56/**
57 * Wrap a chat stream so it emits a trailing CUSTOM `phase-counts` event
58 * right before terminating, carrying the counter middleware's snapshot.
59 */
60async function* withTrailingPhaseCounts(
61 stream: AsyncIterable<AdapterYieldChunk>,
62 snapshot: () => Record<string, number>,
63 model: string,
64): AsyncIterable<AdapterYieldChunk> {
65 let yieldedCounts = false
66 for await (const chunk of stream) {
67 if (
68 chunk.type === EventType.RUN_FINISHED ||
69 chunk.type === EventType.RUN_ERROR
70 ) {
71 yieldedCounts = true
72 yield {
73 type: EventType.CUSTOM,
74 name: 'phase-counts',
75 value: snapshot(),
76 model,
77 timestamp: Date.now(),
78 }
79 }
80 yield chunk
81 }
82 if (!yieldedCounts) {
83 yield {
84 type: EventType.CUSTOM,
85 name: 'phase-counts',
86 value: snapshot(),
87 model,
88 timestamp: Date.now(),
89 }
90 }
91}
92
93export const GuitarRecommendationSchema = z.object({
94 title: z.string().describe('Short headline for the recommendation'),
95 summary: z.string().describe('One paragraph summary'),
96 recommendations: z
97 .array(
98 z.object({
99 name: z.string(),
100 brand: z.string(),
101 type: z.enum(['acoustic', 'electric', 'bass', 'classical']),
102 priceRangeUsd: z.object({ min: z.number(), max: z.number() }),
103 reason: z.string(),
104 }),
105 )
106 .min(1)
107 .describe('Guitar recommendations with reasons'),
108 nextSteps: z.array(z.string()).describe('Practical follow-up actions'),
109})
110
111export type GuitarRecommendation = z.infer<typeof GuitarRecommendationSchema>
112
113const PROVIDERS = [
114 'openai',
115 'openai-chat',
116 'anthropic',
117 'gemini',
118 'grok',
119 'groq',
120 'openrouter',
121 'openrouter-responses',
122] as const
123
124type Provider = (typeof PROVIDERS)[number]
125
126function isProvider(value: unknown): value is Provider {
127 return typeof value === 'string' && PROVIDERS.includes(value as Provider)
128}
129
130/**
131 * Synthetic suffixes the dropdown uses to opt the route into reasoning
132 * modes that aren't first-class on the wire (e.g. "Opus 4.7 with max
133 * adaptive thinking"). The suffix is stripped before reaching the
134 * adapter. Currently `:thinking-max` is the only one defined.
135 */
136function stripModelSuffix(model: string | undefined): string | undefined {
137 if (!model) return model
138 const colonIdx = model.indexOf(':')
139 return colonIdx === -1 ? model : model.slice(0, colonIdx)
140}
141
142function adapterFor(provider: Provider, model?: string): AnyTextAdapter {
143 const baseModel = stripModelSuffix(model)
144 switch (provider) {
145 case 'openai':
146 return openaiText((baseModel || 'gpt-5.2') as 'gpt-5.2')
147 case 'openai-chat':
148 // Same model surface as the Responses adapter, but talks to
149 // `/v1/chat/completions`. Useful for side-by-side comparison of
150 // streaming structured output across the two OpenAI wire formats.
151 return openaiChatCompletions((baseModel || 'gpt-4o') as 'gpt-4o')
152 case 'anthropic':
153 // Claude 4.5+ supports native combined tools + schema-constrained
154 // streaming (#605) via `output_config.format` on the beta Messages
155 // endpoint. Earlier models fall back to the forced-tool-use
156 // workaround in `structuredOutput` (no real streaming).
157 return anthropicText(
158 (baseModel || 'claude-sonnet-4-5') as 'claude-sonnet-4-5',
159 )
160 case 'gemini':
161 // Gemini 3.x supports native combined tools + schema-constrained
162 // streaming (#605) via `config.responseSchema` +
163 // `responseMimeType: 'application/json'` on a single
164 // `generateContentStream` call. Gemini 2.x is documented as brittle
165 // for the combination and falls back to the engine's legacy
166 // finalization path.
167 //
168 // Keep the default aligned with the dropdown's first entry.
169 return geminiText((baseModel || 'gemini-3.8-flash') as 'gemini-3.8-flash')
170 case 'grok':
171 return grokText((model || 'grok-build-0.1') as 'grok-build-0.1')
172 case 'groq':
173 return groqText(
174 (model ||
175 'meta-llama/llama-4-maverick-17b-128e-instruct') as 'meta-llama/llama-4-maverick-17b-128e-instruct',
176 )
177 case 'openrouter':
178 return openRouterText(
179 (model || 'anthropic/claude-opus-4.6') as 'anthropic/claude-opus-4.6',
180 )
181 case 'openrouter-responses':
182 // OpenRouter Responses (beta) endpoint — same model surface as the
183 // chat-completions adapter, but routes through `/v1/responses`. This
184 // is what exercises `OpenRouterResponsesTextAdapter.structuredOutputStream`.
185 return openRouterResponsesText(
186 (model || 'anthropic/claude-opus-4.6') as 'anthropic/claude-opus-4.6',
187 )
188 }
189}
190
191// Per-provider reasoning, so reasoning models stream their thinking. Without
192// it, they reason silently and the UI never sees REASONING_* events.
193function reasoningFor(
194 provider: Provider,
195 model: string | undefined,
196): ReasoningRequest | undefined {
197 switch (provider) {
198 case 'openai':
199 // Only the reasoning models (gpt-5.x, o-series) take reasoning.
200 if (
201 model?.startsWith('gpt-5') ||
202 model?.startsWith('o3') ||
203 model?.startsWith('o4')
204 ) {
205 return { level: 'medium', summary: true }
206 }
207 return undefined
208 case 'anthropic': {
209 // Default: thinking off. Demo flows that just want streaming
210 // structured output shouldn't pay for reasoning tokens, and adaptive
211 // thinking can easily use the default `max_tokens` before the JSON
212 // finishes. The dropdown opts in via the synthetic `:thinking-max`
213 // suffix.
214 const baseModel = stripModelSuffix(model)
215 if (
216 !baseModel ||
217 !ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(baseModel) ||
218 model?.endsWith(':thinking-max') !== true
219 ) {
220 return undefined
221 }
222 // Adaptive thinking decides from the prompt. For the short demo
223 // prompt, only `max` reliably makes the model think. Budget models
224 // get a small fixed budget.
225 return baseModel.startsWith('claude-opus-4-7')
226 ? { level: 'max', summary: true }
227 : { level: 'low', summary: true, budgetTokens: 1024 }
228 }
229 case 'gemini': {
230 // Only the Gemini 3.x combined-mode models, which take thinking
231 // levels.
232 const baseModel = stripModelSuffix(model)
233 if (
234 !baseModel ||
235 !GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(baseModel)
236 ) {
237 return undefined
238 }
239 return { level: 'high', summary: true }
240 }
241 case 'openrouter':
242 case 'openrouter-responses':
243 return { level: 'medium', summary: true }
244 default:
245 return undefined
246 }
247}
248
249// Groq's Chat Completions only streams `delta.reasoning` when
250// `reasoning_format: 'parsed'`. Required for gpt-oss / qwen3 / kimi-k2 to
251// emit reasoning during structured output (json_schema mode).
252function groqReasoningFormat(
253 provider: Provider,
254 model: string | undefined,
255): Record<string, unknown> | undefined {
256 if (
257 provider === 'groq' &&
258 (model?.startsWith('openai/gpt-oss') ||
259 model?.startsWith('qwen') ||
260 model?.startsWith('moonshotai/kimi'))
261 ) {
262 return { reasoning_format: 'parsed' }
263 }
264 return undefined
265}
266
267async function* structuredOutputResultStream(args: {
268 result: GuitarRecommendation
269 phaseCounts: Record<string, number>
270 threadId: string
271 runId: string
272 model: string
273}): AsyncIterable<AdapterYieldChunk> {
274 const messageId = `structured-output-${args.runId}`
275 const raw = JSON.stringify(args.result)
276 const timestamp = Date.now()
277
278 yield {
279 type: EventType.RUN_STARTED,
280 threadId: args.threadId,
281 runId: args.runId,
282 model: args.model,
283 timestamp,
284 }
285 yield {
286 type: EventType.CUSTOM,
287 name: 'structured-output.start',
288 value: { messageId },
289 model: args.model,
290 timestamp: Date.now(),
291 }
292 yield {
293 type: EventType.CUSTOM,
294 name: 'structured-output.complete',
295 value: { object: args.result, raw },
296 model: args.model,
297 timestamp: Date.now(),
298 }
299 yield {
300 type: EventType.CUSTOM,
301 name: 'phase-counts',
302 value: args.phaseCounts,
303 model: args.model,
304 timestamp: Date.now(),
305 }
306 yield {
307 type: EventType.RUN_FINISHED,
308 threadId: args.threadId,
309 runId: args.runId,
310 model: args.model,
311 timestamp: Date.now(),
312 finishReason: 'stop',
313 }
314}
315
316export const Route = createFileRoute('/api/structured-output')({
317 server: {
318 handlers: {
319 POST: async ({ request }) => {
320 if (request.signal.aborted) {
321 return new Response(null, { status: 499 })
322 }
323
324 const abortController = new AbortController()
325 const onAbort = () => abortController.abort()
326 request.signal.addEventListener('abort', onAbort, { once: true })
327 if (request.signal.aborted) {
328 onAbort()
329 }
330
331 let params: Awaited<ReturnType<typeof chatParamsFromRequestBody>>
332 try {
333 params = await chatParamsFromRequestBody(await request.json())
334 } catch (error) {
335 return new Response(
336 error instanceof Error ? error.message : 'Bad request',
337 { status: 400 },
338 )
339 }
340
341 try {
342 const providerValue = params.forwardedProps.provider
343 const resolvedProvider: Provider = isProvider(providerValue)
344 ? providerValue
345 : 'openrouter'
346 const model =
347 typeof params.forwardedProps.model === 'string'
348 ? params.forwardedProps.model
349 : undefined
350 const stream = params.forwardedProps.stream !== false
351 const adapter = adapterFor(resolvedProvider, model)
352 // Adaptive thinking on Claude 4.7 can chew through a few thousand
353 // tokens before the schema-constrained JSON even starts. The
354 // adapter's default `max_tokens` (1024) was producing truncated
355 // outputs ("response was cut off"). Bump for the
356 // `:thinking-max` variant so the reasoning + JSON both fit. We
357 // keep the budget modest (16k) for everyone else to avoid
358 // surprising bills on the demo. The cap now lives in provider-native
359 // `modelOptions` (Anthropic: `max_tokens`) — the generic root
360 // `maxTokens` was removed.
361 const wantsAnthropicMaxThinking =
362 resolvedProvider === 'anthropic' &&
363 model?.endsWith(':thinking-max') === true
364 const modelOptions = {
365 ...groqReasoningFormat(resolvedProvider, model),
366 ...(wantsAnthropicMaxThinking && { max_tokens: 16_000 }),
367 }
368 const reasoning = reasoningFor(resolvedProvider, model)
369 const counter = phaseCounterMiddleware()
370
371 if (stream) {
372 const streamIterable = chat({
373 adapter,
374 modelOptions: modelOptions as never,
375 reasoning,
376 messages: params.messages,
377 outputSchema: GuitarRecommendationSchema,
378 stream: true,
379 middleware: [counter.middleware],
380 threadId: params.threadId,
381 runId: params.runId,
382 abortController,
383 }) as AsyncIterable<AdapterYieldChunk>
384 const withCounts = withTrailingPhaseCounts(
385 streamIterable,
386 counter.snapshot,
387 adapter.model,
388 )
389 return toServerSentEventsResponse(withCounts, {
390 abortController,
391 })
392 }
393
394 const result = await chat({
395 adapter,
396 modelOptions: modelOptions as never,
397 reasoning,
398 messages: params.messages,
399 outputSchema: GuitarRecommendationSchema,
400 middleware: [counter.middleware],
401 threadId: params.threadId,
402 runId: params.runId,
403 abortController,
404 })
405
406 const responseStream = structuredOutputResultStream({
407 result,
408 phaseCounts: counter.snapshot(),
409 threadId: params.threadId,
410 runId: params.runId,
411 model: adapter.model,
412 })
413
414 return toServerSentEventsResponse(responseStream, { abortController })
415 } catch (error: unknown) {
416 const message =
417 error instanceof Error ? error.message : 'An error occurred'
418 console.error('[api/structured-output] Error:', error)
419 return new Response(JSON.stringify({ error: message }), {
420 status: 500,
421 headers: { 'Content-Type': 'application/json' },
422 })
423 } finally {
424 request.signal.removeEventListener('abort', onAbort)
425 }
426 },
427 },
428 },
429})