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

api.tools-test.ts

583 lines18.0 KB

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