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