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

api.mid-conversation-changes-wire.ts

383 lines10.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, toolDefinition } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { createOpenaiChat } from '@tanstack/ai-openai'
5import { z } from 'zod'
6import type { ChatMiddleware } from '@tanstack/ai'
7​
8const OPENAI_KEY = 'sk-e2e-test-dummy-key'
9const ANTHROPIC_KEY = 'sk-ant-e2e-test-dummy-key'
10​
11type SseEvent = Record<string, unknown> & { type: string }
12​
13/** Both SDKs read `event:` + `data:` frames. */
14function sse(events: Array<SseEvent>): string {
15 return events
16 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
17 .join('')
19​
20const weatherArgs = JSON.stringify({ city: 'Paris' })
21​
22const gptCall = {
23 id: 'call_weather',
24 call_id: 'call_weather',
25 type: 'function_call',
26 name: 'get_weather',
27 arguments: weatherArgs,
28 status: 'completed',
30​
31/** GPT calls get_weather, as OpenAI Responses streams it. */
32const gptToolCall = sse([
33 {
34 type: 'response.created',
35 response: {
36 id: 'resp_tool',
37 object: 'response',
38 model: 'gpt-6-astra',
39 status: 'in_progress',
40 output: [],
41 },
42 },
43 {
44 type: 'response.output_item.added',
45 response_id: 'resp_tool',
46 output_index: 0,
47 item: { ...gptCall, arguments: '', status: 'in_progress' },
48 },
49 {
50 type: 'response.function_call_arguments.delta',
51 response_id: 'resp_tool',
52 item_id: 'call_weather',
53 output_index: 0,
54 delta: weatherArgs,
55 },
56 {
57 type: 'response.function_call_arguments.done',
58 response_id: 'resp_tool',
59 item_id: 'call_weather',
60 output_index: 0,
61 arguments: weatherArgs,
62 },
63 {
64 type: 'response.output_item.done',
65 response_id: 'resp_tool',
66 output_index: 0,
67 item: gptCall,
68 },
69 {
70 type: 'response.completed',
71 response: {
72 id: 'resp_tool',
73 object: 'response',
74 model: 'gpt-6-astra',
75 status: 'completed',
76 output: [gptCall],
77 usage: { input_tokens: 5, output_tokens: 3, total_tokens: 8 },
78 },
79 },
80])
81​
82/** GPT answers with text. */
83const gptText = sse([
84 {
85 type: 'response.created',
86 response: {
87 id: 'resp_text',
88 object: 'response',
89 model: 'gpt-6-astra',
90 status: 'in_progress',
91 output: [],
92 },
93 },
94 {
95 type: 'response.output_text.delta',
96 response_id: 'resp_text',
97 item_id: 'msg_text',
98 output_index: 0,
99 content_index: 0,
100 delta: 'Sunny in Paris.',
101 },
102 {
103 type: 'response.completed',
104 response: {
105 id: 'resp_text',
106 object: 'response',
107 model: 'gpt-6-astra',
108 status: 'completed',
109 output: [
110 {
111 id: 'msg_text',
112 type: 'message',
113 role: 'assistant',
114 status: 'completed',
115 content: [{ type: 'output_text', text: 'Sunny in Paris.' }],
116 },
117 ],
118 usage: { input_tokens: 8, output_tokens: 4, total_tokens: 12 },
119 },
120 },
121])
122​
123function claudeStart(id: string): SseEvent {
124 return {
125 type: 'message_start',
126 message: {
127 id,
128 type: 'message',
129 role: 'assistant',
130 content: [],
131 model: 'claude-opus-5-5',
132 stop_reason: null,
133 stop_sequence: null,
134 usage: { input_tokens: 5, output_tokens: 0 },
135 },
136 }
138​
139function claudeEnd(stopReason: string): Array<SseEvent> {
140 return [
141 {
142 type: 'message_delta',
143 delta: { stop_reason: stopReason, stop_sequence: null },
144 usage: { output_tokens: 10 },
145 },
146 { type: 'message_stop' },
147 ]
149​
150/** Claude calls get_weather, as Anthropic Messages streams it. */
151const claudeToolCall = sse([
152 claudeStart('msg_tool'),
153 {
154 type: 'content_block_start',
155 index: 0,
156 content_block: {
157 type: 'tool_use',
158 id: 'toolu_weather',
159 name: 'get_weather',
160 input: {},
161 },
162 },
163 {
164 type: 'content_block_delta',
165 index: 0,
166 delta: { type: 'input_json_delta', partial_json: weatherArgs },
167 },
168 { type: 'content_block_stop', index: 0 },
169 ...claudeEnd('tool_use'),
170])
171​
172/** Claude answers with text. */
173const claudeText = sse([
174 claudeStart('msg_text'),
175 {
176 type: 'content_block_start',
177 index: 0,
178 content_block: { type: 'text', text: '' },
179 },
180 {
181 type: 'content_block_delta',
182 index: 0,
183 delta: { type: 'text_delta', text: 'Sunny in Paris.' },
184 },
185 { type: 'content_block_stop', index: 0 },
186 ...claudeEnd('end_turn'),
187])
188​
189type Captured = { body: Record<string, unknown>; beta: string | null }
190​
191/** Records each request. Answers the first with `toolCall`, the rest with `text`. */
192function capture(toolCall: string, text: string) {
193 const requests: Array<Captured> = []
194 const fetchImpl: typeof fetch = async (input, init) => {
195 const request = input instanceof Request ? input : new Request(input, init)
196 requests.push({
197 body: JSON.parse(await request.text()),
198 beta: request.headers.get('anthropic-beta'),
199 })
200 return new Response(requests.length === 1 ? toolCall : text, {
201 status: 200,
202 headers: { 'Content-Type': 'text/event-stream' },
203 })
204 }
205 return { requests, fetchImpl }
207​
208const getWeather = toolDefinition({
209 name: 'get_weather',
210 description: 'Get the weather for a city',
211 inputSchema: z.object({ city: z.string() }),
212}).server(({ city }) => ({ city, temperature: 21 }))
213​
214const getForecast = toolDefinition({
215 name: 'get_forecast',
216 description: 'Get the forecast for a city',
217 inputSchema: z.object({ city: z.string() }),
218}).server(({ city }) => ({ city, tomorrow: 'sunny' }))
219​
220/** Adds get_forecast before the second model call, after the first tool batch. */
221const addForecast: ChatMiddleware = {
222 name: 'add-forecast',
223 onConfig: (ctx, config) => {
224 if (ctx.phase !== 'beforeModel' || ctx.iteration === 0) return undefined
225 if (config.tools.some((tool) => tool.name === 'get_forecast')) {
226 return undefined
227 }
228 return { tools: [...config.tools, getForecast] }
229 },
231​
232function isRecord(value: unknown): value is Record<string, unknown> {
233 return typeof value === 'object' && value !== null
235​
236function list(value: unknown): Array<unknown> {
237 return Array.isArray(value) ? value : []
239​
240function names(value: unknown): Array<string> {
241 return list(value).flatMap((tool) =>
242 isRecord(tool) && typeof tool.name === 'string' ? [tool.name] : [],
243 )
245​
246/** The RUN_ERROR chunks of a run, so a broken stream shows in the spec. */
247async function errorsOf(stream: AsyncIterable<{ type: string }>) {
248 const errors: Array<string> = []
249 for await (const chunk of stream) {
250 if (chunk.type === 'RUN_ERROR') errors.push(JSON.stringify(chunk))
251 }
252 return errors
254​
255/** What the spec checks in the two requests of one case. */
256function summarize(
257 name: string,
258 errors: Array<string>,
259 requests: Array<Captured>,
260) {
261 const [first, second] = requests
262 const last = list(second?.body.input ?? second?.body.messages).at(-1)
263 return {
264 name,
265 errors,
266 requestCount: requests.length,
267 firstTools: names(first?.body.tools),
268 secondTools: names(second?.body.tools),
269 // OpenAI: the tools of `additional_tools` input items.
270 additionalTools: list(second?.body.input).flatMap((item) =>
271 isRecord(item) && item.type === 'additional_tools'
272 ? names(item.tools)
273 : [],
274 ),
275 // Anthropic: the tools of `tool_addition` blocks in `system` messages.
276 toolAdditions: list(second?.body.messages)
277 .flatMap((message) =>
278 isRecord(message) && message.role === 'system'
279 ? list(message.content)
280 : [],
281 )
282 .flatMap((block) =>
283 isRecord(block) && block.type === 'tool_addition'
284 ? names([block.tool])
285 : [],
286 ),
287 deferred: list(second?.body.tools).flatMap((tool) =>
288 isRecord(tool) && tool.defer_loading === true ? names([tool]) : [],
289 ),
290 // The tools with a set prompt-cache marker, per request. Custom tools
291 // always send `cache_control: null`, so only an object counts.
292 toolCacheMarks: requests.map((request) =>
293 list(request.body.tools).flatMap((tool) =>
294 isRecord(tool) && isRecord(tool.cache_control) ? names([tool]) : [],
295 ),
296 ),
297 betas: requests.map((request) =>
298 request.beta ? request.beta.split(',').map((beta) => beta.trim()) : [],
299 ),
300 lastItem: isRecord(last) ? String(last.type ?? last.role) : null,
301 }
303​
304/** A custom `fetch` turns the channels off, so the GPT cases turn them on. */
305async function gpt(model: 'gpt-6-astra' | 'gpt-6.1-sol') {
306 const wire = capture(gptToolCall, gptText)
307 const errors = await errorsOf(
308 chat({
309 threadId: 'mid-conversation-changes-wire',
310 adapter: createOpenaiChat(model, OPENAI_KEY, {
311 fetch: wire.fetchImpl,
312 midConversationChannels: true,
313 }),
314 messages: [
315 { role: 'user', content: '[mid-conversation] weather in Paris' },
316 ],
317 tools: [getWeather],
318 middleware: [addForecast],
319 }),
320 )
321 return summarize(model, errors, wire.requests)
323​
324async function claude(
325 name: string,
326 model: 'claude-opus-5-5' | 'claude-sonnet-5-5',
327 options: { midConversationChannels?: boolean },
328) {
329 const wire = capture(claudeToolCall, claudeText)
330 const errors = await errorsOf(
331 chat({
332 threadId: 'mid-conversation-changes-wire',
333 adapter: createAnthropicChat(model, ANTHROPIC_KEY, {
334 fetch: wire.fetchImpl,
335 ...options,
336 }),
337 messages: [
338 { role: 'user', content: '[mid-conversation] weather in Paris' },
339 ],
340 tools: [getWeather],
341 middleware: [addForecast],
342 }),
343 )
344 return summarize(name, errors, wire.requests)
346​
347/**
348 * A middleware adds `get_forecast` after the first tool batch. Runs that with
349 * real adapters and a capturing `fetch` on two models in the map
350 * (`gpt-6-astra`, `claude-opus-5-5`) and two outside it (`gpt-6.1-sol`,
351 * `claude-sonnet-5-5`), all with `midConversationChannels: true`, and on
352 * `claude-opus-5-5` with no option (the gateway case). Returns what the two
353 * requests of each case held.
354 */
355export const Route = createFileRoute('/api/mid-conversation-changes-wire')({
356 server: {
357 handlers: {
358 POST: async () => {
359 try {
360 return Response.json({
361 ok: true,
362 cases: [
363 await gpt('gpt-6-astra'),
364 await gpt('gpt-6.1-sol'),
365 await claude('claude-opus-5-5', 'claude-opus-5-5', {
366 midConversationChannels: true,
367 }),
368 await claude('claude-sonnet-5-5', 'claude-sonnet-5-5', {
369 midConversationChannels: true,
370 }),
371 await claude('claude-opus-5-5 gateway', 'claude-opus-5-5', {}),
372 ],
373 })
374 } catch (error) {
375 return Response.json({
376 ok: false,
377 error: error instanceof Error ? error.message : String(error),
378 })
379 }
380 },
381 },
382 },
383})