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

api.structured-output.ts

458 lines15.8 KB

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