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

api.structured-output.ts

426 lines13.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 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 }
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 }
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)
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)
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((model || 'qwen/qwen3.8-27b') as 'qwen/qwen3.8-27b')
174 case 'openrouter':
175 return openRouterText(
176 (model || 'anthropic/claude-opus-4.6') as 'anthropic/claude-opus-4.6',
177 )
178 case 'openrouter-responses':
179 // OpenRouter Responses (beta) endpoint — same model surface as the
180 // chat-completions adapter, but routes through `/v1/responses`. This
181 // is what exercises `OpenRouterResponsesTextAdapter.structuredOutputStream`.
182 return openRouterResponsesText(
183 (model || 'anthropic/claude-opus-4.6') as 'anthropic/claude-opus-4.6',
184 )
185 }
187​
188// Per-provider reasoning, so reasoning models stream their thinking. Without
189// it, they reason silently and the UI never sees REASONING_* events.
190function reasoningFor(
191 provider: Provider,
192 model: string | undefined,
193): ReasoningRequest | undefined {
194 switch (provider) {
195 case 'openai':
196 // Only the reasoning models (gpt-5.x, o-series) take reasoning.
197 if (
198 model?.startsWith('gpt-5') ||
199 model?.startsWith('o3') ||
200 model?.startsWith('o4')
201 ) {
202 return { level: 'medium', summary: true }
203 }
204 return undefined
205 case 'anthropic': {
206 // Default: thinking off. Demo flows that just want streaming
207 // structured output shouldn't pay for reasoning tokens, and adaptive
208 // thinking can easily use the default `max_tokens` before the JSON
209 // finishes. The dropdown opts in via the synthetic `:thinking-max`
210 // suffix.
211 const baseModel = stripModelSuffix(model)
212 if (
213 !baseModel ||
214 !ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(baseModel) ||
215 model?.endsWith(':thinking-max') !== true
216 ) {
217 return undefined
218 }
219 // Adaptive thinking decides from the prompt. For the short demo
220 // prompt, only `max` reliably makes the model think. Budget models
221 // get a small fixed budget.
222 return baseModel.startsWith('claude-opus-4-7')
223 ? { level: 'max', summary: true }
224 : { level: 'low', summary: true, budgetTokens: 1024 }
225 }
226 case 'gemini': {
227 // Only the Gemini 3.x combined-mode models, which take thinking
228 // levels.
229 const baseModel = stripModelSuffix(model)
230 if (
231 !baseModel ||
232 !GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(baseModel)
233 ) {
234 return undefined
235 }
236 return { level: 'high', summary: true }
237 }
238 case 'openrouter':
239 case 'openrouter-responses':
240 return { level: 'medium', summary: true }
241 default:
242 return undefined
243 }
245​
246// Groq's Chat Completions only streams `delta.reasoning` when
247// `reasoning_format: 'parsed'`. Required for gpt-oss / qwen3 / kimi-k2 to
248// emit reasoning during structured output (json_schema mode).
249function groqReasoningFormat(
250 provider: Provider,
251 model: string | undefined,
252): Record<string, unknown> | undefined {
253 if (
254 provider === 'groq' &&
255 (model?.startsWith('openai/gpt-oss') ||
256 model?.startsWith('qwen') ||
257 model?.startsWith('moonshotai/kimi'))
258 ) {
259 return { reasoning_format: 'parsed' }
260 }
261 return undefined
263​
264async function* structuredOutputResultStream(args: {
265 result: GuitarRecommendation
266 phaseCounts: Record<string, number>
267 threadId: string
268 runId: string
269 model: string
270}): AsyncIterable<AdapterYieldChunk> {
271 const messageId = `structured-output-${args.runId}`
272 const raw = JSON.stringify(args.result)
273 const timestamp = Date.now()
274​
275 yield {
276 type: EventType.RUN_STARTED,
277 threadId: args.threadId,
278 runId: args.runId,
279 model: args.model,
280 timestamp,
281 }
282 yield {
283 type: EventType.CUSTOM,
284 name: 'structured-output.start',
285 value: { messageId },
286 model: args.model,
287 timestamp: Date.now(),
288 }
289 yield {
290 type: EventType.CUSTOM,
291 name: 'structured-output.complete',
292 value: { object: args.result, raw },
293 model: args.model,
294 timestamp: Date.now(),
295 }
296 yield {
297 type: EventType.CUSTOM,
298 name: 'phase-counts',
299 value: args.phaseCounts,
300 model: args.model,
301 timestamp: Date.now(),
302 }
303 yield {
304 type: EventType.RUN_FINISHED,
305 threadId: args.threadId,
306 runId: args.runId,
307 model: args.model,
308 timestamp: Date.now(),
309 finishReason: 'stop',
310 }
312​
313export const Route = createFileRoute('/api/structured-output')({
314 server: {
315 handlers: {
316 POST: async ({ request }) => {
317 if (request.signal.aborted) {
318 return new Response(null, { status: 499 })
319 }
320​
321 const abortController = new AbortController()
322 const onAbort = () => abortController.abort()
323 request.signal.addEventListener('abort', onAbort, { once: true })
324 if (request.signal.aborted) {
325 onAbort()
326 }
327​
328 let params: Awaited<ReturnType<typeof chatParamsFromRequestBody>>
329 try {
330 params = await chatParamsFromRequestBody(await request.json())
331 } catch (error) {
332 return new Response(
333 error instanceof Error ? error.message : 'Bad request',
334 { status: 400 },
335 )
336 }
337​
338 try {
339 const providerValue = params.forwardedProps.provider
340 const resolvedProvider: Provider = isProvider(providerValue)
341 ? providerValue
342 : 'openrouter'
343 const model =
344 typeof params.forwardedProps.model === 'string'
345 ? params.forwardedProps.model
346 : undefined
347 const stream = params.forwardedProps.stream !== false
348 const adapter = adapterFor(resolvedProvider, model)
349 // Adaptive thinking on Claude 4.7 can chew through a few thousand
350 // tokens before the schema-constrained JSON even starts. The
351 // adapter's default `max_tokens` (1024) was producing truncated
352 // outputs ("response was cut off"). Bump for the
353 // `:thinking-max` variant so the reasoning + JSON both fit. We
354 // keep the budget modest (16k) for everyone else to avoid
355 // surprising bills on the demo. The cap now lives in provider-native
356 // `modelOptions` (Anthropic: `max_tokens`) — the generic root
357 // `maxTokens` was removed.
358 const wantsAnthropicMaxThinking =
359 resolvedProvider === 'anthropic' &&
360 model?.endsWith(':thinking-max') === true
361 const modelOptions = {
362 ...groqReasoningFormat(resolvedProvider, model),
363 ...(wantsAnthropicMaxThinking && { max_tokens: 16_000 }),
364 }
365 const reasoning = reasoningFor(resolvedProvider, model)
366 const counter = phaseCounterMiddleware()
367​
368 if (stream) {
369 const streamIterable = chat({
370 adapter,
371 modelOptions: modelOptions as never,
372 reasoning,
373 messages: params.messages,
374 outputSchema: GuitarRecommendationSchema,
375 stream: true,
376 middleware: [counter.middleware],
377 threadId: params.threadId,
378 runId: params.runId,
379 abortController,
380 }) as AsyncIterable<AdapterYieldChunk>
381 const withCounts = withTrailingPhaseCounts(
382 streamIterable,
383 counter.snapshot,
384 adapter.model,
385 )
386 return toServerSentEventsResponse(withCounts, {
387 abortController,
388 })
389 }
390​
391 const result = await chat({
392 adapter,
393 modelOptions: modelOptions as never,
394 reasoning,
395 messages: params.messages,
396 outputSchema: GuitarRecommendationSchema,
397 middleware: [counter.middleware],
398 threadId: params.threadId,
399 runId: params.runId,
400 abortController,
401 })
402​
403 const responseStream = structuredOutputResultStream({
404 result,
405 phaseCounts: counter.snapshot(),
406 threadId: params.threadId,
407 runId: params.runId,
408 model: adapter.model,
409 })
410​
411 return toServerSentEventsResponse(responseStream, { abortController })
412 } catch (error: unknown) {
413 const message =
414 error instanceof Error ? error.message : 'An error occurred'
415 console.error('[api/structured-output] Error:', error)
416 return new Response(JSON.stringify({ error: message }), {
417 status: 500,
418 headers: { 'Content-Type': 'application/json' },
419 })
420 } finally {
421 request.signal.removeEventListener('abort', onAbort)
422 }
423 },
424 },
425 },
426})