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

api.anthropic-structured-usage.ts

97 lines3.8 KB

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 threadId: 'anthropic-structured-usage',
50 ...options,
51 messages: [{ role: 'user', content: 'recommend a guitar as json' }],
52 })) {
53 if (
54 chunk.type === 'RUN_STARTED' &&
55 typeof chunk.timestamp === 'number'
56 ) {
57 timestamps.runStarted = chunk.timestamp
58 }
59 if (
60 chunk.type === 'CUSTOM' &&
61 chunk.name === 'structured-output.start' &&
62 typeof chunk.timestamp === 'number'
63 ) {
64 timestamps.structuredOutputStart = chunk.timestamp
65 }
66 if (
67 chunk.type === 'CUSTOM' &&
68 chunk.name === 'structured-output.complete' &&
69 typeof chunk.timestamp === 'number'
70 ) {
71 timestamps.structuredOutputComplete = chunk.timestamp
72 }
73 if (chunk.type === 'RUN_FINISHED') {
74 usage = chunk.usage as Record<string, unknown> | undefined
75 if (typeof chunk.timestamp === 'number') {
76 timestamps.runFinished = chunk.timestamp
77 }
78 }
79 }
80 } catch (error) {
81 return new Response(
82 JSON.stringify({
83 ok: false,
84 error: error instanceof Error ? error.message : String(error),
85 }),
86 { status: 200, headers: { 'Content-Type': 'application/json' } },
87 )
88 }
89​
90 return new Response(JSON.stringify({ ok: true, usage, timestamps }), {
91 status: 200,
92 headers: { 'Content-Type': 'application/json' },
93 })
94 },
95 },
96 },
97})