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

api.anthropic-redacted-thinking-wire.ts

244 lines7.0 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'
9​
10const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
11​
12type SseEvent = Record<string, unknown> & { type: string }
13​
14const messageStart: SseEvent = {
15 type: 'message_start',
16 message: {
17 id: 'msg_redacted',
18 type: 'message',
19 role: 'assistant',
20 content: [],
21 model: 'claude-sonnet-4-5',
22 stop_reason: null,
23 stop_sequence: null,
24 usage: { input_tokens: 5, output_tokens: 0 },
25 },
27​
28/** Claude sends a redacted block whole, on its start event. */
29function redacted(index: number, data: string) {
30 return [
31 {
32 type: 'content_block_start',
33 index,
34 content_block: { type: 'redacted_thinking', data },
35 },
36 { type: 'content_block_stop', index },
37 ]
39​
40function text(index: number, value: string) {
41 return [
42 {
43 type: 'content_block_start',
44 index,
45 content_block: { type: 'text', text: '' },
46 },
47 {
48 type: 'content_block_delta',
49 index,
50 delta: { type: 'text_delta', text: value },
51 },
52 { type: 'content_block_stop', index },
53 ]
55​
56function toolUse(index: number, name: string) {
57 return [
58 {
59 type: 'content_block_start',
60 index,
61 content_block: { type: 'tool_use', id: 'toolu_1', name, input: {} },
62 },
63 {
64 type: 'content_block_delta',
65 index,
66 delta: { type: 'input_json_delta', partial_json: '{}' },
67 },
68 { type: 'content_block_stop', index },
69 ]
71​
72function end(stopReason: string) {
73 return [
74 {
75 type: 'message_delta',
76 delta: { stop_reason: stopReason, stop_sequence: null },
77 usage: { output_tokens: 20 },
78 },
79 { type: 'message_stop' },
80 ]
82​
83function sse(events: Array<SseEvent>): Response {
84 return new Response(
85 events
86 .map(
87 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
88 )
89 .join(''),
90 { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
91 )
93​
94type Body = {
95 messages: Array<{ role: string; content: unknown }>
97​
98/** Answers each call with the next scripted stream and records its body. */
99function scriptedFetch(streams: Array<Array<SseEvent>>) {
100 const bodies: Array<Body> = []
101 const fetchImpl: typeof fetch = async (input, init) => {
102 const req = input instanceof Request ? input : new Request(input, init)
103 bodies.push(JSON.parse(await req.text()))
104 return sse(
105 streams[bodies.length - 1] ?? [
106 messageStart,
107 ...text(0, 'Done.'),
108 ...end('end_turn'),
109 ],
110 )
111 }
112 return { bodies, fetchImpl }
114​
115function blocks(body: Body | undefined, role: string) {
116 const message = body?.messages.filter((m) => m.role === role).at(-1)
117 return Array.isArray(message?.content)
118 ? (message.content as Array<Record<string, unknown>>)
119 : []
121​
122/**
123 * Three scripted runs, answered by a capturing `fetch`:
124 *
125 * - `nextTurn`: a redacted block and text, then a second turn through
126 * `StreamProcessor`, `uiMessagesToWire`, and `chatParamsFromRequestBody`,
127 * as a browser client and `/api/chat` do.
128 * - `sameRun`: a redacted block and a tool call. The run's second request
129 * continues after the tool.
130 * - `toolError`: the tool throws. The run's second request carries the result.
131 */
132export const Route = createFileRoute('/api/anthropic-redacted-thinking-wire')({
133 server: {
134 handlers: {
135 POST: async () => {
136 try {
137 const nextTurn = scriptedFetch([
138 [
139 messageStart,
140 ...redacted(0, 'opaque-1'),
141 ...text(1, 'Hello.'),
142 ...end('end_turn'),
143 ],
144 ])
145 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
146 fetch: nextTurn.fetchImpl,
147 })
148 const client = new StreamProcessor({})
149 for (const [index, prompt] of ['Hi', 'Say it again'].entries()) {
150 client.addUserMessage(prompt)
151 const params = await chatParamsFromRequestBody({
152 threadId: 'redacted-thinking',
153 runId: `redacted-thinking-${index + 1}`,
154 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
155 messages: JSON.parse(
156 JSON.stringify(uiMessagesToWire(client.getMessages())),
157 ),
158 tools: [],
159 context: [],
160 })
161 for await (const chunk of chat({
162 threadId: 'anthropic-redacted-thinking-wire',
163 ...createChatOptions({ adapter }),
164 messages: params.messages,
165 stream: true,
166 })) {
167 client.processChunk(chunk)
168 }
169 client.finalizeStream()
170 }
171​
172 const sameRun = scriptedFetch([
173 [
174 messageStart,
175 ...redacted(0, 'opaque-2'),
176 ...toolUse(1, 'check'),
177 ...end('tool_use'),
178 ],
179 ])
180 for await (const _ of chat({
181 threadId: 'anthropic-redacted-thinking-wire',
182 ...createChatOptions({
183 adapter: createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
184 fetch: sameRun.fetchImpl,
185 }),
186 }),
187 messages: [{ role: 'user', content: 'Check it' }],
188 tools: [
189 {
190 name: 'check',
191 description: 'Check something.',
192 execute: () => 'ok',
193 },
194 ],
195 stream: true,
196 })) {
197 // consume
198 }
199​
200 const toolError = scriptedFetch([
201 [messageStart, ...toolUse(0, 'fail'), ...end('tool_use')],
202 ])
203 for await (const _ of chat({
204 threadId: 'anthropic-redacted-thinking-wire',
205 ...createChatOptions({
206 adapter: createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
207 fetch: toolError.fetchImpl,
208 }),
209 }),
210 messages: [{ role: 'user', content: 'Try it' }],
211 tools: [
212 {
213 name: 'fail',
214 description: 'Always fails.',
215 execute: () => {
216 throw new Error('Tool broke')
217 },
218 },
219 ],
220 stream: true,
221 })) {
222 // consume
223 }
224​
225 return Response.json({
226 ok: true,
227 nextTurnBlocks: blocks(nextTurn.bodies[1], 'assistant'),
228 sameRunBlocks: blocks(sameRun.bodies[1], 'assistant').map(
229 (block) => block.type,
230 ),
231 toolResult: blocks(toolError.bodies[1], 'user').find(
232 (block) => block.type === 'tool_result',
233 ),
234 })
235 } catch (error) {
236 return Response.json({
237 ok: false,
238 error: error instanceof Error ? error.message : String(error),
239 })
240 }
241 },
242 },
243 },
244})