Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 maxIterations,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import type { AnyTextAdapter, AdapterYieldChunk } from '@tanstack/ai'
10import type { TestRuntimeContext } from '@/lib/tools-test-tools'
11import { createTextAdapter } from '@/lib/providers'
12import {
13 getToolsForScenario,
14 STOP_CLIENT_TOOL_MESSAGE,
15} from '@/lib/tools-test-tools'
16
17const providerFreeScenarios = new Set([
18 'server-context',
19 'client-context',
20 'client-tool-error',
21 'client-server-context',
22 'client-tool-stop',
23 'client-tool-input-error',
24 'invalid-client-tool-retry',
25 'malformed-tool-arguments',
26 'provider-rejected-tool-call',
27])
28
29function createProviderFreeAdapter(scenario: string): AnyTextAdapter {
30 const stopsPendingTool = scenario === 'client-tool-stop'
31 const config =
32 scenario === 'provider-rejected-tool-call'
33 ? {
34 arguments: '{"component":"database","unexpected":true}',
35 initialText: 'Checking system status.',
36 input: { component: 'database', unexpected: true },
37 name: 'provider-rejected-tool-call-test',
38 responseText: 'Recovered from provider-rejected tool call.',
39 result: JSON.stringify({ error: 'Provider rejected tool call' }),
40 state: 'output-error' as const,
41 toolName: 'check_status',
42 }
43 : scenario === 'malformed-tool-arguments'
44 ? {
45 arguments: '{',
46 initialText: 'Checking system status.',
47 input: undefined,
48 name: 'malformed-tool-arguments-test',
49 responseText: 'Recovered from malformed tool arguments.',
50 result: undefined,
51 state: undefined,
52 toolName: 'check_status',
53 }
54 : scenario === 'client-tool-error'
55 ? {
56 arguments: '{}',
57 initialText: 'Running the client tool.',
58 input: {},
59 name: 'client-tool-error-test',
60 responseText: 'Recovered from client tool failure.',
61 result: undefined,
62 state: undefined,
63 toolName: 'fail_client_tool',
64 }
65 : scenario === 'client-tool-input-error' ||
66 scenario === 'invalid-client-tool-retry'
67 ? {
68 // An object cannot be repaired into the string `message`.
69 arguments: '{"message":{"text":"hi"},"type":"info"}',
70 initialText: 'Showing a notification.',
71 input: { message: { text: 'hi' }, type: 'info' },
72 name:
73 scenario === 'invalid-client-tool-retry'
74 ? 'invalid-client-tool-retry-test'
75 : 'client-tool-input-error-test',
76 responseText:
77 scenario === 'invalid-client-tool-retry'
78 ? 'Recovered after client tool input retry.'
79 : 'Unexpected client continuation.',
80 result: undefined,
81 state: undefined,
82 toolName: 'show_notification',
83 }
84 : {
85 arguments: stopsPendingTool
86 ? JSON.stringify({
87 message: STOP_CLIENT_TOOL_MESSAGE,
88 type: 'info',
89 })
90 : '{}',
91 initialText: stopsPendingTool
92 ? 'Showing a notification.'
93 : 'Reading runtime context.',
94 input: stopsPendingTool
95 ? { message: STOP_CLIENT_TOOL_MESSAGE, type: 'info' }
96 : {},
97 name: stopsPendingTool
98 ? 'client-tool-stop-test'
99 : 'runtime-context-test',
100 responseText: stopsPendingTool
101 ? 'The notification was shown.'
102 : 'Runtime context was read.',
103 result: undefined,
104 state: undefined,
105 toolName: stopsPendingTool
106 ? 'show_notification'
107 : scenario === 'client-context'
108 ? 'read_client_context'
109 : 'read_server_context',
110 }
111 return {
112 kind: 'text',
113 name: config.name,
114 model: config.name,
115 '~types': {
116 providerOptions: {},
117 inputModalities: ['text'],
118 messageMetadataByModality: {},
119 toolCapabilities: [],
120 toolCallMetadata: undefined,
121 systemPromptMetadata: undefined,
122 },
123 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
124 const model = config.name
125 const runId = options.runId ?? 'runtime-context-run'
126 const threadId = options.threadId ?? 'runtime-context-thread'
127 const messageId = `${runId}-message`
128 const toolResultCount = options.messages.filter(
129 (message) => message.role === 'tool',
130 ).length
131 const hasToolResult = toolResultCount > 0
132 const retryClientTool =
133 scenario === 'invalid-client-tool-retry' && toolResultCount === 1
134
135 yield {
136 type: EventType.RUN_STARTED,
137 runId,
138 threadId,
139 model,
140 timestamp: Date.now(),
141 }
142
143 if (!hasToolResult || retryClientTool) {
144 const toolCallId =
145 scenario === 'invalid-client-tool-retry'
146 ? `${scenario}-tool-call-${toolResultCount + 1}`
147 : `${scenario}-tool-call`
148 const toolArguments = retryClientTool
149 ? '{"message":"done","type":"info"}'
150 : config.arguments
151 const toolInput = retryClientTool
152 ? { message: 'done', type: 'info' }
153 : config.input
154
155 yield {
156 type: EventType.TEXT_MESSAGE_START,
157 messageId,
158 role: 'assistant',
159 model,
160 timestamp: Date.now(),
161 }
162 yield {
163 type: EventType.TEXT_MESSAGE_CONTENT,
164 messageId,
165 delta: config.initialText,
166 model,
167 timestamp: Date.now(),
168 }
169 yield {
170 type: EventType.TEXT_MESSAGE_END,
171 messageId,
172 model,
173 timestamp: Date.now(),
174 }
175 yield {
176 type: EventType.TOOL_CALL_START,
177 toolCallId,
178 toolCallName: config.toolName,
179 toolName: config.toolName,
180 model,
181 timestamp: Date.now(),
182 }
183 yield {
184 type: EventType.TOOL_CALL_ARGS,
185 toolCallId,
186 delta: toolArguments,
187 model,
188 timestamp: Date.now(),
189 }
190 yield {
191 type: EventType.TOOL_CALL_END,
192 toolCallId,
193 toolCallName: config.toolName,
194 toolName: config.toolName,
195 ...(toolInput === undefined ? {} : { input: toolInput }),
196 ...(config.result === undefined
197 ? {}
198 : { result: config.result, state: config.state }),
199 model,
200 timestamp: Date.now(),
201 }
202 yield {
203 type: EventType.RUN_FINISHED,
204 runId,
205 threadId,
206 model,
207 finishReason: 'tool_calls',
208 timestamp: Date.now(),
209 }
210 return
211 }
212
213 yield {
214 type: EventType.TEXT_MESSAGE_START,
215 messageId,
216 role: 'assistant',
217 model,
218 timestamp: Date.now(),
219 }
220 yield {
221 type: EventType.TEXT_MESSAGE_CONTENT,
222 messageId,
223 delta: config.responseText,
224 model,
225 timestamp: Date.now(),
226 }
227 yield {
228 type: EventType.TEXT_MESSAGE_END,
229 messageId,
230 model,
231 timestamp: Date.now(),
232 }
233 yield {
234 type: EventType.RUN_FINISHED,
235 runId,
236 threadId,
237 model,
238 finishReason: 'stop',
239 timestamp: Date.now(),
240 }
241 },
242 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
243 }
244}
245
246/**
247 * Regression adapter for PR #1481.
248 *
249 * Streams wire arguments with an extra `region: null` (the shape OpenAI
250 * strict mode widens an optional field into), then sends the canonical
251 * `input` without it on TOOL_CALL_END. Once history holds a tool result, it
252 * echoes the tool-call arguments of that history as text. On a second user
253 * turn, that history comes from the client's tool-call part.
254 */
255function createCanonicalToolInputAdapter(): AnyTextAdapter {
256 const model = 'canonical-tool-input-test'
257 return {
258 kind: 'text',
259 name: model,
260 model,
261 '~types': {
262 providerOptions: {},
263 inputModalities: ['text'],
264 messageMetadataByModality: {},
265 toolCapabilities: [],
266 toolCallMetadata: undefined,
267 systemPromptMetadata: undefined,
268 },
269 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
270 const runId = options.runId ?? 'canonical-tool-input-run'
271 const threadId = options.threadId ?? 'canonical-tool-input-thread'
272 const messageId = `${runId}-message`
273 const toolCallId = 'canonical-tool-input-tool-call'
274 const timestamp = Date.now()
275
276 yield { type: EventType.RUN_STARTED, runId, threadId, model, timestamp }
277
278 if (options.messages.some((message) => message.role === 'tool')) {
279 const historyArguments = options.messages
280 .flatMap((message) => message.toolCalls ?? [])
281 .map((toolCall) => toolCall.function.arguments)
282 yield {
283 type: EventType.TEXT_MESSAGE_START,
284 messageId,
285 role: 'assistant',
286 model,
287 timestamp,
288 }
289 yield {
290 type: EventType.TEXT_MESSAGE_CONTENT,
291 messageId,
292 delta: `History arguments: ${historyArguments.join(' ')}`,
293 model,
294 timestamp,
295 }
296 yield { type: EventType.TEXT_MESSAGE_END, messageId, model, timestamp }
297 yield {
298 type: EventType.RUN_FINISHED,
299 runId,
300 threadId,
301 model,
302 finishReason: 'stop',
303 timestamp,
304 }
305 return
306 }
307
308 yield {
309 type: EventType.TOOL_CALL_START,
310 toolCallId,
311 toolCallName: 'check_status',
312 toolName: 'check_status',
313 model,
314 timestamp,
315 }
316 yield {
317 type: EventType.TOOL_CALL_ARGS,
318 toolCallId,
319 delta: '{"component":"database","region":null}',
320 model,
321 timestamp,
322 }
323 yield {
324 type: EventType.TOOL_CALL_END,
325 toolCallId,
326 toolCallName: 'check_status',
327 toolName: 'check_status',
328 input: { component: 'database' },
329 model,
330 timestamp,
331 }
332 yield {
333 type: EventType.RUN_FINISHED,
334 runId,
335 threadId,
336 model,
337 finishReason: 'tool_calls',
338 timestamp,
339 }
340 },
341 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
342 }
343}
344
345/**
346 * Regression adapter for issue #1017.
347 *
348 * Emits a TEXT_MESSAGE_CONTENT delta between two TOOL_CALL_ARGS deltas.
349 * Pre-fix, the interleaved text force-completed the tool call with a
350 * lenient partial-JSON parse of the truncated arguments
351 * (`{"city":"New Yo"}`) and the later TOOL_CALL_END was skipped.
352 */
353function createInterleavedArgsAdapter(): AnyTextAdapter {
354 return {
355 kind: 'text',
356 name: 'interleaved-args-test',
357 model: 'interleaved-args-test',
358 '~types': {
359 providerOptions: {},
360 inputModalities: ['text'],
361 messageMetadataByModality: {},
362 toolCapabilities: [],
363 toolCallMetadata: undefined,
364 systemPromptMetadata: undefined,
365 },
366 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
367 const model = 'interleaved-args-test'
368 const runId = options.runId ?? 'interleaved-args-run'
369 const threadId = options.threadId ?? 'interleaved-args-thread'
370 const messageId = `${runId}-message`
371 const toolCallId = 'interleaved-args-tool-call'
372 const hasToolResult = options.messages.some(
373 (message) => message.role === 'tool',
374 )
375
376 yield {
377 type: EventType.RUN_STARTED,
378 runId,
379 threadId,
380 model,
381 timestamp: Date.now(),
382 }
383
384 if (hasToolResult) {
385 yield {
386 type: EventType.TEXT_MESSAGE_START,
387 messageId,
388 role: 'assistant',
389 model,
390 timestamp: Date.now(),
391 }
392 yield {
393 type: EventType.TEXT_MESSAGE_CONTENT,
394 messageId,
395 delta: 'It is 72F in New York City.',
396 model,
397 timestamp: Date.now(),
398 }
399 yield {
400 type: EventType.TEXT_MESSAGE_END,
401 messageId,
402 model,
403 timestamp: Date.now(),
404 }
405 yield {
406 type: EventType.RUN_FINISHED,
407 runId,
408 threadId,
409 model,
410 finishReason: 'stop',
411 timestamp: Date.now(),
412 }
413 return
414 }
415
416 yield {
417 type: EventType.TOOL_CALL_START,
418 toolCallId,
419 toolCallName: 'get_weather',
420 toolName: 'get_weather',
421 model,
422 timestamp: Date.now(),
423 }
424 yield {
425 type: EventType.TOOL_CALL_ARGS,
426 toolCallId,
427 delta: '{"city":"New Yo',
428 model,
429 timestamp: Date.now(),
430 }
431 yield {
432 type: EventType.TEXT_MESSAGE_CONTENT,
433 messageId,
434 delta: 'Let me check the weather. ',
435 model,
436 timestamp: Date.now(),
437 }
438 yield {
439 type: EventType.TOOL_CALL_ARGS,
440 toolCallId,
441 delta: 'rk City"}',
442 model,
443 timestamp: Date.now(),
444 }
445 yield {
446 type: EventType.TOOL_CALL_END,
447 toolCallId,
448 toolCallName: 'get_weather',
449 toolName: 'get_weather',
450 model,
451 timestamp: Date.now(),
452 }
453 yield {
454 type: EventType.RUN_FINISHED,
455 runId,
456 threadId,
457 model,
458 finishReason: 'tool_calls',
459 timestamp: Date.now(),
460 }
461 },
462 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
463 }
464}
465
466export const Route = createFileRoute('/api/tools-test')({
467 server: {
468 handlers: {
469 POST: async ({ request }) => {
470 const requestSignal = request.signal
471
472 if (requestSignal?.aborted) {
473 return new Response(null, { status: 499 })
474 }
475
476 const abortController = new AbortController()
477
478 let params
479 try {
480 params = await chatParamsFromRequestBody(await request.json())
481 } catch (error) {
482 return new Response(
483 error instanceof Error ? error.message : 'Bad request',
484 { status: 400 },
485 )
486 }
487
488 const fp = params.forwardedProps
489 const scenario =
490 typeof fp.scenario === 'string' ? fp.scenario : 'text-only'
491 const testId: string | undefined =
492 typeof fp.testId === 'string' ? fp.testId : undefined
493 const aimockPort: number | undefined =
494 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
495
496 try {
497 // Special error scenario: return a stream that immediately errors
498 if (scenario === 'error') {
499 const errorStream =
500 (async function* (): AsyncGenerator<AdapterYieldChunk> {
501 yield {
502 type: EventType.RUN_STARTED,
503 runId: 'error-test',
504 threadId: 'error-test',
505 timestamp: Date.now(),
506 }
507 yield {
508 type: EventType.RUN_ERROR,
509 message: 'Test error: Something went wrong during generation',
510 timestamp: Date.now(),
511 code: 'provider_error',
512 // Mirrors a provider's structured error body forwarded by the
513 // adapters as `rawEvent`. Asserts it survives SSE transport,
514 // the strip-to-spec middleware, and reaches the consumer.
515 rawEvent: {
516 provider_name: 'test-provider',
517 raw: { reason: 'upstream overloaded' },
518 },
519 }
520 })()
521 return toServerSentEventsResponse(errorStream, { abortController })
522 }
523
524 const adapterOptions =
525 scenario === 'interleaved-args'
526 ? { adapter: createInterleavedArgsAdapter() }
527 : scenario === 'canonical-tool-input'
528 ? { adapter: createCanonicalToolInputAdapter() }
529 : providerFreeScenarios.has(scenario)
530 ? { adapter: createProviderFreeAdapter(scenario) }
531 : createTextAdapter(
532 'openai',
533 scenario === 'client-tool-reasoning'
534 ? 'gpt-5.2'
535 : undefined,
536 aimockPort,
537 testId,
538 )
539
540 const tools = getToolsForScenario(scenario)
541 const runtimeContext: TestRuntimeContext =
542 scenario === 'client-server-context' &&
543 typeof fp.runtimeUserId === 'string'
544 ? {
545 userId: fp.runtimeUserId,
546 tenantId: 'server-tenant-context',
547 source: 'forwarded-props',
548 }
549 : {
550 userId: 'server-user-context',
551 tenantId: 'server-tenant-context',
552 source: 'server-route',
553 }
554
555 const stream = chat({
556 ...adapterOptions,
557 messages: params.messages,
558 tools,
559 context: runtimeContext,
560 threadId: params.threadId,
561 runId: params.runId,
562 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
563 ...(params.resume ? { resume: params.resume } : {}),
564 agentLoopStrategy: maxIterations(
565 scenario === 'client-tool-input-error' ? 1 : 20,
566 ),
567 abortController,
568 })
569
570 return toServerSentEventsResponse(stream, { abortController })
571 } catch (error) {
572 console.error('[Tools Test API] Error:', error)
573 if (
574 (error instanceof Error && error.name === 'AbortError') ||
575 abortController.signal.aborted
576 ) {
577 return new Response(null, { status: 499 })
578 }
579 const message =
580 error instanceof Error ? error.message : 'An error occurred'
581 return new Response(JSON.stringify({ error: message }), {
582 status: 500,
583 headers: { 'Content-Type': 'application/json' },
584 })
585 }
586 },
587 },
588 },
589})