Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { z } from 'zod'
5
6const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
7const DUMMY_KEY = 'sk-e2e-test-dummy-key'
8
9/**
10 * Drives the Anthropic text adapter (`AnthropicTextAdapter`) through the
11 * streaming structured-output path. That adapter has no native
12 * `structuredOutputStream`, so `chat({ outputSchema, stream: true })` routes
13 * through the activity layer's `fallbackStructuredOutputStream`, which wraps the
14 * non-streaming `structuredOutput()`. The mounted `/anthropic-structured-usage`
15 * aimock path returns a tool-forced `structured_output` response whose `usage`
16 * carries `input_tokens` / `output_tokens` / `cache_read_input_tokens`.
17 *
18 * Regressions for #758 and #1125: the companion spec asserts that usage reaches
19 * `RUN_FINISHED.usage` and fallback timestamps follow stream order.
20 */
21export const Route = createFileRoute('/api/anthropic-structured-usage')({
22 server: {
23 handlers: {
24 POST: async () => {
25 // `claude-opus-4-1` is intentionally a *pre-4.5* model: it is NOT in
26 // `ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS`, so
27 // `supportsCombinedToolsAndSchema()` is false and the engine routes
28 // `chat({ outputSchema, stream: true })` through the non-streaming
29 // `structuredOutput()` wrapped by `fallbackStructuredOutputStream` —
30 // exactly the path #758 fixes. A 4.5+ model would use the native
31 // combined path and never touch the fallback.
32 const adapter = createAnthropicChat('claude-opus-4-1', DUMMY_KEY, {
33 baseURL: `${LLMOCK_DEFAULT_BASE}/anthropic-structured-usage`,
34 })
35
36 const options = createChatOptions({
37 adapter,
38 outputSchema: z.object({
39 recommendation: z.string(),
40 price: z.number(),
41 }),
42 stream: true,
43 })
44
45 let usage: Record<string, unknown> | undefined
46 const timestamps: Record<string, number> = {}
47 try {
48 for await (const chunk of chat({
49 ...options,
50 messages: [{ role: 'user', content: 'recommend a guitar as json' }],
51 })) {
52 if (
53 chunk.type === 'RUN_STARTED' &&
54 typeof chunk.timestamp === 'number'
55 ) {
56 timestamps.runStarted = chunk.timestamp
57 }
58 if (
59 chunk.type === 'CUSTOM' &&
60 chunk.name === 'structured-output.start' &&
61 typeof chunk.timestamp === 'number'
62 ) {
63 timestamps.structuredOutputStart = chunk.timestamp
64 }
65 if (
66 chunk.type === 'CUSTOM' &&
67 chunk.name === 'structured-output.complete' &&
68 typeof chunk.timestamp === 'number'
69 ) {
70 timestamps.structuredOutputComplete = chunk.timestamp
71 }
72 if (chunk.type === 'RUN_FINISHED') {
73 usage = chunk.usage as Record<string, unknown> | undefined
74 if (typeof chunk.timestamp === 'number') {
75 timestamps.runFinished = chunk.timestamp
76 }
77 }
78 }
79 } catch (error) {
80 return new Response(
81 JSON.stringify({
82 ok: false,
83 error: error instanceof Error ? error.message : String(error),
84 }),
85 { status: 200, headers: { 'Content-Type': 'application/json' } },
86 )
87 }
88
89 return new Response(JSON.stringify({ ok: true, usage, timestamps }), {
90 status: 200,
91 headers: { 'Content-Type': 'application/json' },
92 })
93 },
94 },
95 },
96})