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

api.anthropic-thinking-order-wire.ts

368 lines11.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createChatOptions,
6} from '@tanstack/ai'
7import { StreamProcessor, uiMessagesToWire } from '@tanstack/ai/client'
8import { createAnthropicChat } from '@tanstack/ai-anthropic'
9import { webSearchTool } from '@tanstack/ai-anthropic/tools'
10​
11const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
12​
13type SseEvent = Record<string, unknown> & { type: string }
14​
15const messageStart: SseEvent = {
16 type: 'message_start',
17 message: {
18 id: 'msg_thinking_order',
19 type: 'message',
20 role: 'assistant',
21 content: [],
22 model: 'claude-sonnet-4-5',
23 stop_reason: null,
24 stop_sequence: null,
25 usage: { input_tokens: 5, output_tokens: 0 },
26 },
28​
29function thinking(index: number, text: string, signature: string) {
30 return [
31 {
32 type: 'content_block_start',
33 index,
34 content_block: { type: 'thinking', thinking: '', signature: '' },
35 },
36 {
37 type: 'content_block_delta',
38 index,
39 delta: { type: 'thinking_delta', thinking: text },
40 },
41 {
42 type: 'content_block_delta',
43 index,
44 delta: { type: 'signature_delta', signature },
45 },
46 { type: 'content_block_stop', index },
47 ]
49​
50function webSearch(index: number) {
51 return [
52 {
53 type: 'content_block_start',
54 index,
55 content_block: {
56 type: 'server_tool_use',
57 id: 'srvtoolu_arenas',
58 name: 'web_search',
59 input: {},
60 },
61 },
62 {
63 type: 'content_block_delta',
64 index,
65 delta: { type: 'input_json_delta', partial_json: '{"query":"arenas"}' },
66 },
67 { type: 'content_block_stop', index },
68 {
69 type: 'content_block_start',
70 index: index + 1,
71 content_block: {
72 type: 'web_search_tool_result',
73 tool_use_id: 'srvtoolu_arenas',
74 content: [
75 {
76 type: 'web_search_result',
77 url: 'https://example.com/arenas',
78 title: 'Arenas',
79 encrypted_content: 'opaque',
80 page_age: null,
81 },
82 ],
83 },
84 },
85 { type: 'content_block_stop', index: index + 1 },
86 ]
88​
89function text(index: number, value: string) {
90 return [
91 {
92 type: 'content_block_start',
93 index,
94 content_block: { type: 'text', text: '' },
95 },
96 {
97 type: 'content_block_delta',
98 index,
99 delta: { type: 'text_delta', text: value },
100 },
101 { type: 'content_block_stop', index },
102 ]
104​
105function clientToolUse(
106 index: number,
107 id = 'toolu_pick',
108 name = 'pick_arena',
109 args = '{}',
110) {
111 return [
112 {
113 type: 'content_block_start',
114 index,
115 content_block: { type: 'tool_use', id, name, input: {} },
116 },
117 {
118 type: 'content_block_delta',
119 index,
120 delta: { type: 'input_json_delta', partial_json: args },
121 },
122 { type: 'content_block_stop', index },
123 ]
125​
126function end(stopReason: string) {
127 return [
128 {
129 type: 'message_delta',
130 delta: { stop_reason: stopReason, stop_sequence: null },
131 usage: { output_tokens: 20 },
132 },
133 { type: 'message_stop' },
134 ]
136​
137/** thinking → web_search → result → thinking → text, as Claude streams it. */
138const interleaved = [
139 messageStart,
140 ...thinking(0, 'Which arena is largest?', 'sig-a'),
141 ...webSearch(1),
142 ...thinking(3, 'Still unsure about capacity.', 'sig-b'),
143 ...text(4, 'Avicii Arena is the largest.'),
145​
146function sse(events: Array<SseEvent>): Response {
147 return new Response(
148 events
149 .map(
150 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
151 )
152 .join(''),
153 { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
154 )
156​
157/** Answers each call with the next scripted stream and records its body. */
158function scriptedFetch(streams: Array<Array<SseEvent>>) {
159 const bodies: Array<{
160 messages: Array<{ role: string; content: unknown }>
161 }> = []
162 const fetchImpl: typeof fetch = async (input, init) => {
163 const req = input instanceof Request ? input : new Request(input, init)
164 bodies.push(JSON.parse(await req.text()))
165 return sse(
166 streams[bodies.length - 1] ?? [
167 messageStart,
168 ...text(0, 'Done.'),
169 ...end('end_turn'),
170 ],
171 )
172 }
173 return { bodies, fetchImpl }
175​
176function blockTypes(message: { content: unknown } | undefined) {
177 return Array.isArray(message?.content)
178 ? message.content.map((block: { type: string }) => block.type)
179 : []
181​
182/** Each block as `type:signature` or `type:id`, to check the order. */
183function blockKeys(message: { content: unknown } | undefined) {
184 return Array.isArray(message?.content)
185 ? message.content.map(
186 (block: { type: string; signature?: string; id?: string }) =>
187 `${block.type}:${block.signature ?? block.id ?? ''}`,
188 )
189 : []
191​
192/**
193 * Anthropic signs every thinking block against the blocks before it. When
194 * web_search runs inside the response, the next request must replay
195 * `thinking, server_tool_use, web_search_tool_result, thinking, text` in that
196 * order, or Claude rejects it with "thinking blocks ... cannot be modified".
197 *
198 * Three scripted runs, answered by a capturing `fetch` (no aimock fixture):
199 *
200 * - `replay` — two turns through `StreamProcessor` → `uiMessagesToWire` →
201 * `chatParamsFromRequestBody` → `chat()`, as a browser client and
202 * `/api/chat` do. Returns the block order of the second request.
203 * - `interrupt` — the same turn ends with a client tool. Returns the client
204 * tool requests and the client view after the interrupt snapshot.
205 * - `clientTools` — Claude answers thinking, tool_use, thinking, tool_use
206 * with two client tools. The client sends both results back over the wire.
207 * Returns the client view of the answer and the replayed blocks.
208 */
209export const Route = createFileRoute('/api/anthropic-thinking-order-wire')({
210 server: {
211 handlers: {
212 POST: async () => {
213 try {
214 const replay = scriptedFetch([[...interleaved, ...end('end_turn')]])
215 const replayAdapter = createAnthropicChat(
216 'claude-sonnet-4-5',
217 DUMMY_KEY,
218 { fetch: replay.fetchImpl },
219 )
220 const replayClient = new StreamProcessor({})
221 for (const [index, prompt] of [
222 'Find the largest arena',
223 'And the second largest?',
224 ].entries()) {
225 replayClient.addUserMessage(prompt)
226 const params = await chatParamsFromRequestBody({
227 threadId: 'thinking-order',
228 runId: `thinking-order-${index + 1}`,
229 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
230 messages: JSON.parse(
231 JSON.stringify(uiMessagesToWire(replayClient.getMessages())),
232 ),
233 tools: [],
234 context: [],
235 })
236 for await (const chunk of chat({
237 threadId: 'anthropic-thinking-order-wire',
238 ...createChatOptions({ adapter: replayAdapter }),
239 messages: params.messages,
240 stream: true,
241 })) {
242 replayClient.processChunk(chunk)
243 }
244 replayClient.finalizeStream()
245 }
246​
247 const interrupt = scriptedFetch([
248 [...interleaved, ...clientToolUse(5), ...end('tool_use')],
249 ])
250 const interruptClient = new StreamProcessor({})
251 interruptClient.addUserMessage('Find the largest arena, then pick')
252 const events: Array<unknown> = []
253 for await (const chunk of chat({
254 threadId: 'anthropic-thinking-order-wire',
255 ...createChatOptions({
256 adapter: createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
257 fetch: interrupt.fetchImpl,
258 }),
259 }),
260 messages: interruptClient.getMessages(),
261 tools: [
262 webSearchTool({
263 name: 'web_search',
264 type: 'web_search_20250305',
265 }),
266 { name: 'pick_arena', description: 'Let the user pick one.' },
267 ],
268 stream: true,
269 })) {
270 events.push(chunk)
271 interruptClient.processChunk(chunk)
272 }
273 interruptClient.finalizeStream()
274​
275 const clientTools = scriptedFetch([
276 [
277 messageStart,
278 ...thinking(0, 'Check Stockholm first.', 'sig-c'),
279 ...clientToolUse(
280 1,
281 'toolu_stockholm',
282 'arena_size',
283 '{"city":"Stockholm"}',
284 ),
285 ...thinking(2, 'Now check Oslo.', 'sig-d'),
286 ...clientToolUse(
287 3,
288 'toolu_oslo',
289 'arena_size',
290 '{"city":"Oslo"}',
291 ),
292 ...end('tool_use'),
293 ],
294 ])
295 const clientToolsAdapter = createAnthropicChat(
296 'claude-sonnet-4-5',
297 DUMMY_KEY,
298 { fetch: clientTools.fetchImpl },
299 )
300 const sizeTool = {
301 name: 'arena_size',
302 description: 'Read the size of an arena.',
303 }
304 const toolClient = new StreamProcessor({})
305 toolClient.addUserMessage('Compare the two arenas')
306 /** One request, as a browser client and `/api/chat` send it. */
307 const sendClientToolTurn = async (runId: string) => {
308 const params = await chatParamsFromRequestBody({
309 threadId: 'thinking-order-client-tools',
310 runId,
311 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
312 messages: JSON.parse(
313 JSON.stringify(uiMessagesToWire(toolClient.getMessages())),
314 ),
315 tools: [],
316 context: [],
317 })
318 for await (const chunk of chat({
319 threadId: 'anthropic-thinking-order-wire',
320 ...createChatOptions({ adapter: clientToolsAdapter }),
321 messages: params.messages,
322 tools: [sizeTool],
323 stream: true,
324 })) {
325 toolClient.processChunk(chunk)
326 }
327 toolClient.finalizeStream()
328 }
329 await sendClientToolTurn('thinking-order-client-tools-1')
330 const clientToolView = toolClient
331 .getMessages()
332 .filter((message) => message.role === 'assistant')
333 .map((message) => message.parts.map((part) => part.type))
334 // The browser runs both tools and sends the results back.
335 toolClient.addToolResult('toolu_stockholm', { seats: 16000 })
336 toolClient.addToolResult('toolu_oslo', { seats: 9000 })
337 await sendClientToolTurn('thinking-order-client-tools-2')
338​
339 return Response.json({
340 ok: true,
341 clientToolView,
342 clientToolReplay: blockKeys(
343 clientTools.bodies[1]?.messages.find(
344 (m) => m.role === 'assistant',
345 ),
346 ),
347 replayedBlocks: blockTypes(
348 replay.bodies[1]?.messages.find((m) => m.role === 'assistant'),
349 ),
350 // Interrupt ids for client work are `client_tool_<toolCallId>`.
351 clientToolRequests: ['toolu_pick', 'srvtoolu_arenas'].filter((id) =>
352 JSON.stringify(events).includes(`client_tool_${id}`),
353 ),
354 viewAfterInterrupt: interruptClient
355 .getMessages()
356 .filter((message) => message.role === 'assistant')
357 .map((message) => message.parts.map((part) => part.type)),
358 })
359 } catch (error) {
360 return Response.json({
361 ok: false,
362 error: error instanceof Error ? error.message : String(error),
363 })
364 }
365 },
366 },
367 },
368})