Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { getGuitars } from '@/lib/tools'
5
6const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
7
8/** Models the spec drives through this route. */
9const WIRE_MODELS = ['claude-sonnet-4-5', 'claude-opus-5-5'] as const
10type WireModel = (typeof WIRE_MODELS)[number]
11
12/** Reads `model` from the request body. Defaults to `claude-sonnet-4-5`. */
13async function readModel(request: Request): Promise<WireModel> {
14 const body: unknown = await request.json().catch(() => null)
15 const model =
16 body && typeof body === 'object' && 'model' in body ? body.model : null
17 return WIRE_MODELS.find((known) => known === model) ?? 'claude-sonnet-4-5'
18}
19
20/**
21 * Wire-format verification for `chat({ toolChoice })` on Anthropic. POST
22 * `{ model }` to pick the model.
23 *
24 * aimock stores Anthropic requests in its journal in OpenAI shape and drops
25 * `tool_choice`, so the journal cannot show it. A custom `fetch` captures the
26 * outgoing request and answers with a synthetic Claude SSE stream, the same
27 * approach as `api.anthropic-opus-5-combined-wire.ts`. The stream has no
28 * tool call, so the run makes one request.
29 */
30
31/** Minimal Anthropic Messages stream with one text block. */
32function makeSyntheticAnthropicStream(
33 model: WireModel,
34): ReadableStream<Uint8Array> {
35 const encoder = new TextEncoder()
36 const events = [
37 {
38 type: 'message_start',
39 message: {
40 id: 'msg_tool_choice_wire',
41 type: 'message',
42 role: 'assistant',
43 content: [],
44 model,
45 stop_reason: null,
46 stop_sequence: null,
47 usage: { input_tokens: 5, output_tokens: 0 },
48 },
49 },
50 {
51 type: 'content_block_start',
52 index: 0,
53 content_block: { type: 'text', text: '' },
54 },
55 {
56 type: 'content_block_delta',
57 index: 0,
58 delta: { type: 'text_delta', text: 'Done.' },
59 },
60 { type: 'content_block_stop', index: 0 },
61 {
62 type: 'message_delta',
63 delta: { stop_reason: 'end_turn', stop_sequence: null },
64 usage: { output_tokens: 2 },
65 },
66 { type: 'message_stop' },
67 ]
68
69 return new ReadableStream<Uint8Array>({
70 start(controller) {
71 for (const event of events) {
72 controller.enqueue(
73 encoder.encode(
74 `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
75 ),
76 )
77 }
78 controller.close()
79 },
80 })
81}
82
83export const Route = createFileRoute('/api/tool-choice-wire')({
84 server: {
85 handlers: {
86 POST: async ({ request }) => {
87 const model = await readModel(request)
88 const capturedBodies: Array<unknown> = []
89
90 /** Records the outgoing request and answers with the synthetic stream. */
91 const capturingFetch: typeof fetch = async (input, init) => {
92 const req =
93 input instanceof Request ? input : new Request(input, init)
94 capturedBodies.push(await req.json())
95 return new Response(makeSyntheticAnthropicStream(model), {
96 status: 200,
97 headers: {
98 'Content-Type': 'text/event-stream',
99 'Cache-Control': 'no-cache',
100 },
101 })
102 }
103
104 try {
105 for await (const _ of chat({
106 threadId: 'tool-choice-wire',
107 adapter: createAnthropicChat(model, DUMMY_KEY, {
108 fetch: capturingFetch,
109 }),
110 messages: [
111 {
112 role: 'user',
113 content: '[toolchoice] what guitars do you have in stock',
114 },
115 ],
116 tools: [getGuitars],
117 toolChoice: { type: 'tool', name: 'getGuitars' },
118 })) {
119 // Drain the stream.
120 }
121 } catch (error) {
122 return Response.json({
123 ok: false,
124 error: error instanceof Error ? error.message : String(error),
125 capturedBodies,
126 })
127 }
128
129 return Response.json({ ok: true, capturedBodies })
130 },
131 },
132 },
133})