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

api.anthropic-bug-test.ts

178 lines6.2 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 createChatOptions,
5 maxIterations,
6 toolDefinition,
7} from '@tanstack/ai'
8import { createAnthropicChat } from '@tanstack/ai-anthropic'
9import { webFetchTool } from '@tanstack/ai-anthropic/tools'
10import { z } from 'zod'
11import type { UIMessage } from '@tanstack/ai'
12​
13const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
14const DUMMY_KEY = 'sk-e2e-test-dummy-key'
15​
16/**
17 * Reproduces issue #604 against the real `webFetchTool()` surface: a user
18 * client tool mixed with `webFetchTool()` previously broke when Claude
19 * returned a `tool_use` followed by a `server_tool_use` (web_fetch) in the
20 * same streaming response — the server tool's `input_json_delta`s appended
21 * onto the client tool's input buffer, and the agent loop's `JSON.parse`
22 * threw on the concatenated JSON.
23 *
24 * The route runs the Anthropic adapter against a mounted aimock path that
25 * emits the exact SSE shape Claude returns (aimock doesn't natively model
26 * `server_tool_use` blocks). Test-only — no production code path should set
27 * a custom Anthropic baseURL like this.
28 */
29export const Route = createFileRoute('/api/anthropic-bug-test')({
30 server: {
31 handlers: {
32 POST: async ({ request }) => {
33 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
34 baseURL: `${LLMOCK_DEFAULT_BASE}/anthropic-bug-test`,
35 })
36​
37 if (
38 new URL(request.url).searchParams.get('case') === 'thinking-order'
39 ) {
40 const messages: Array<UIMessage> = [
41 {
42 id: 'initial-user-message',
43 role: 'user',
44 parts: [{ type: 'text', content: 'Research top AI companies' }],
45 },
46 {
47 id: 'assistant-message',
48 role: 'assistant',
49 parts: [
50 {
51 type: 'thinking',
52 content: 'First signed thinking block',
53 signature: 'signature-1',
54 },
55 {
56 type: 'tool-call',
57 id: 'srvtoolu_search',
58 name: 'web_search',
59 arguments: '{"query":"top AI companies"}',
60 state: 'input-complete',
61 metadata: {
62 providerExecuted: true,
63 anthropic: {
64 serverToolType: 'web_search',
65 resultBlockType: 'web_search_tool_result',
66 result: [
67 {
68 type: 'web_search_result',
69 title: 'Example result',
70 url: 'https://example.com',
71 encrypted_content: 'opaque-provider-payload',
72 },
73 ],
74 },
75 },
76 },
77 {
78 type: 'thinking',
79 content: 'Second signed thinking block',
80 signature: 'signature-2',
81 },
82 {
83 type: 'tool-call',
84 id: 'toolu_create_block',
85 name: 'createBlock',
86 arguments: '{"block":{"type":"entity-grid"}}',
87 state: 'complete',
88 output: { ok: true },
89 },
90 {
91 type: 'tool-result',
92 toolCallId: 'toolu_create_block',
93 content: '{"ok":true}',
94 state: 'complete',
95 },
96 ],
97 },
98 {
99 id: 'follow-up-user-message',
100 role: 'user',
101 parts: [
102 {
103 type: 'text',
104 content: '[thinking-tool-order] continue',
105 },
106 ],
107 },
108 ]
109​
110 const chunks: Array<unknown> = []
111 try {
112 for await (const chunk of chat({
113 ...createChatOptions({ adapter }),
114 messages,
115 })) {
116 chunks.push(chunk)
117 }
118 } catch (error) {
119 return new Response(
120 JSON.stringify({
121 chunks,
122 error: error instanceof Error ? error.message : String(error),
123 }),
124 { status: 200, headers: { 'Content-Type': 'application/json' } },
125 )
126 }
127​
128 return new Response(JSON.stringify({ chunks, error: null }), {
129 status: 200,
130 headers: { 'Content-Type': 'application/json' },
131 })
132 }
133​
134 // A trivial client tool the user might pair with webFetchTool(). The
135 // server lookup just echoes back so the agent loop can settle into
136 // the follow-up text response.
137 const lookupWeather = toolDefinition({
138 name: 'lookup_weather',
139 description: 'Return the current weather for a city',
140 inputSchema: z.object({ location: z.string() }),
141 }).server(async ({ location }) => ({ location, summary: 'sunny' }))
142​
143 const chunks: Array<unknown> = []
144 try {
145 for await (const chunk of chat({
146 ...createChatOptions({ adapter }),
147 // The real bug surface: a user tool + webFetchTool() in the same
148 // request. Pre-fix this combination caused
149 // "Failed to parse tool arguments as JSON" in the agent loop.
150 tools: [lookupWeather, webFetchTool()],
151 messages: [
152 {
153 role: 'user',
154 content: 'Weather in Berlin and fetch example.com',
155 },
156 ],
157 agentLoopStrategy: maxIterations(3),
158 })) {
159 chunks.push(chunk)
160 }
161 } catch (error) {
162 return new Response(
163 JSON.stringify({
164 chunks,
165 error: error instanceof Error ? error.message : String(error),
166 }),
167 { status: 200, headers: { 'Content-Type': 'application/json' } },
168 )
169 }
170​
171 return new Response(JSON.stringify({ chunks, error: null }), {
172 status: 200,
173 headers: { 'Content-Type': 'application/json' },
174 })
175 },
176 },
177 },
178})