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

api.anthropic-multi-turn-structured-wire.ts

170 lines5.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'
9import { recipeSchema } from '@/lib/schemas'
10​
11const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
12​
13const FIRST_RECIPE = JSON.stringify({
14 title: 'Classic Spaghetti Pomodoro',
15 cuisine: 'Italian',
16 servings: 2,
17 estimatedCostUsd: 12,
18 ingredients: [{ item: 'spaghetti', amount: '200 g' }],
19 steps: ['Cook the pasta'],
20 tips: ['Salt the water'],
21})
22​
23const SECOND_RECIPE = JSON.stringify({
24 title: 'Vegan Spaghetti Pomodoro',
25 cuisine: 'Italian',
26 servings: 2,
27 estimatedCostUsd: 11,
28 ingredients: [{ item: 'spaghetti', amount: '200 g' }],
29 steps: ['Cook the pasta'],
30 tips: ['Nutritional yeast stands in for the parmesan'],
31})
32​
33const PROMPTS = [
34 '[multiturn-structured-wire-1] pasta dinner for two',
35 '[multiturn-structured-wire-2] now make it vegan',
37​
38/** Claude 4.5+ combined-mode turn: the whole final text is the schema JSON. */
39function makeStructuredAnthropicStream(
40 json: string,
41): ReadableStream<Uint8Array> {
42 const encoder = new TextEncoder()
43 const events = [
44 {
45 type: 'message_start',
46 message: {
47 id: 'msg_multi_turn_structured_wire',
48 type: 'message',
49 role: 'assistant',
50 content: [],
51 model: 'claude-sonnet-4-5',
52 stop_reason: null,
53 stop_sequence: null,
54 usage: { input_tokens: 5, output_tokens: 0 },
55 },
56 },
57 {
58 type: 'content_block_start',
59 index: 0,
60 content_block: { type: 'text', text: '' },
61 },
62 {
63 type: 'content_block_delta',
64 index: 0,
65 delta: { type: 'text_delta', text: json },
66 },
67 { type: 'content_block_stop', index: 0 },
68 {
69 type: 'message_delta',
70 delta: { stop_reason: 'end_turn', stop_sequence: null },
71 usage: { output_tokens: 20 },
72 },
73 { type: 'message_stop' },
74 ]
75​
76 return new ReadableStream<Uint8Array>({
77 start(controller) {
78 for (const event of events) {
79 controller.enqueue(
80 encoder.encode(
81 `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
82 ),
83 )
84 }
85 controller.close()
86 },
87 })
89​
90/**
91 * Two structured turns on Anthropic's #605 native combined path, captured on
92 * the wire. `StreamProcessor` consumes turn 1, then `uiMessagesToWire` +
93 * `chatParamsFromRequestBody` rebuild the history exactly as a browser client
94 * and `/api/chat` do before turn 2 goes back out.
95 *
96 * The capturing `fetch` answers with a synthetic Claude stream, so this needs
97 * no fixture and never touches aimock's shared journal. The companion spec
98 * reads `requestBodies[1]`.
99 */
100export const Route = createFileRoute(
101 '/api/anthropic-multi-turn-structured-wire',
102)({
103 server: {
104 handlers: {
105 POST: async () => {
106 const requestBodies: Array<unknown> = []
107​
108 const capturingFetch: typeof fetch = async (input, init) => {
109 const req =
110 input instanceof Request ? input : new Request(input, init)
111 const rawBody = await req.text()
112 requestBodies.push(rawBody ? JSON.parse(rawBody) : null)
113​
114 return new Response(
115 makeStructuredAnthropicStream(
116 requestBodies.length === 1 ? FIRST_RECIPE : SECOND_RECIPE,
117 ),
118 {
119 status: 200,
120 headers: {
121 'Content-Type': 'text/event-stream',
122 'Cache-Control': 'no-cache',
123 },
124 },
125 )
126 }
127​
128 const adapter = createAnthropicChat('claude-sonnet-4-5', DUMMY_KEY, {
129 fetch: capturingFetch,
130 })
131 const processor = new StreamProcessor({})
132​
133 try {
134 for (const [index, prompt] of PROMPTS.entries()) {
135 processor.addUserMessage(prompt)
136 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
137 const params = await chatParamsFromRequestBody({
138 threadId: 'anthropic-multi-turn-structured-wire',
139 runId: `anthropic-multi-turn-structured-wire-${index + 1}`,
140 messages: JSON.parse(
141 JSON.stringify(uiMessagesToWire(processor.getMessages())),
142 ),
143 tools: [],
144 context: [],
145 })
146​
147 const stream = chat({
148 threadId: 'anthropic-multi-turn-structured-wire',
149 ...createChatOptions({ adapter }),
150 messages: params.messages,
151 outputSchema: recipeSchema,
152 stream: true,
153 })
154 for await (const chunk of stream) {
155 processor.processChunk(chunk)
156 }
157 processor.finalizeStream()
158 }
159 } catch (error) {
160 return Response.json({
161 ok: false,
162 error: error instanceof Error ? error.message : String(error),
163 })
164 }
165​
166 return Response.json({ ok: true, requestBodies })
167 },
168 },
169 },
170})