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

api.tool-call-lifecycle-wire.ts

165 lines4.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 createChatOptions,
6 maxIterations,
7 toolDefinition,
8} from '@tanstack/ai'
9import { z } from 'zod'
10import type { AnyTextAdapter, AdapterYieldChunk } from '@tanstack/ai'
11​
12/**
13 * Wire-format regression for issue #519.
14 *
15 * Real adapters stream `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END`
16 * for every tool call. Pre-fix, `chat()`'s post-execution phase pushed a
17 * *second* `TOOL_CALL_END` (with no matching `START`) after running a
18 * server tool, so the stream carried an orphan `END` that AG-UI-strict
19 * consumers (`@ag-ui/client`'s `verifyEvents`) reject.
20 *
21 * The self-contained adapter below mirrors a real one: it streams its own
22 * START/ARGS/END for the tool call, then a text answer once the tool result
23 * comes back. The companion spec drains the emitted chunks and asserts the
24 * lifecycle is balanced — exactly one END per tool call, each preceded by a
25 * matching START.
26 */
27function createServerToolAdapter(): AnyTextAdapter {
28 return {
29 kind: 'text',
30 name: 'tool-lifecycle-test',
31 model: 'tool-lifecycle-test',
32 '~types': {
33 providerOptions: {},
34 inputModalities: ['text'],
35 messageMetadataByModality: {},
36 toolCapabilities: [],
37 toolCallMetadata: undefined,
38 systemPromptMetadata: undefined,
39 },
40 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
41 const model = 'tool-lifecycle-test'
42 const runId = options.runId ?? 'tool-lifecycle-run'
43 const threadId = options.threadId ?? 'tool-lifecycle-thread'
44 const messageId = `${runId}-message`
45 const toolCallId = 'call_weather'
46 const hasToolResult = options.messages.some((m) => m.role === 'tool')
47​
48 yield {
49 type: EventType.RUN_STARTED,
50 runId,
51 threadId,
52 model,
53 timestamp: Date.now(),
54 }
55​
56 // Second iteration: the tool ran, answer with text and finish.
57 if (hasToolResult) {
58 yield {
59 type: EventType.TEXT_MESSAGE_START,
60 messageId,
61 role: 'assistant',
62 model,
63 timestamp: Date.now(),
64 }
65 yield {
66 type: EventType.TEXT_MESSAGE_CONTENT,
67 messageId,
68 delta: 'It is 72F in NYC.',
69 model,
70 timestamp: Date.now(),
71 }
72 yield {
73 type: EventType.TEXT_MESSAGE_END,
74 messageId,
75 model,
76 timestamp: Date.now(),
77 }
78 yield {
79 type: EventType.RUN_FINISHED,
80 runId,
81 threadId,
82 model,
83 finishReason: 'stop',
84 timestamp: Date.now(),
85 }
86 return
87 }
88​
89 // First iteration: stream the full tool-call lifecycle, as a real
90 // adapter does, then finish with `tool_calls`.
91 yield {
92 type: EventType.TOOL_CALL_START,
93 toolCallId,
94 toolCallName: 'getWeather',
95 toolName: 'getWeather',
96 model,
97 timestamp: Date.now(),
98 }
99 yield {
100 type: EventType.TOOL_CALL_ARGS,
101 toolCallId,
102 delta: '{"city":"NYC"}',
103 model,
104 timestamp: Date.now(),
105 }
106 yield {
107 type: EventType.TOOL_CALL_END,
108 toolCallId,
109 toolCallName: 'getWeather',
110 toolName: 'getWeather',
111 input: { city: 'NYC' },
112 model,
113 timestamp: Date.now(),
114 }
115 yield {
116 type: EventType.RUN_FINISHED,
117 runId,
118 threadId,
119 model,
120 finishReason: 'tool_calls',
121 timestamp: Date.now(),
122 }
123 },
124 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
125 }
127​
128export const Route = createFileRoute('/api/tool-call-lifecycle-wire')({
129 server: {
130 handlers: {
131 POST: async () => {
132 const getWeather = toolDefinition({
133 name: 'getWeather',
134 description: 'Get the weather for a city',
135 inputSchema: z.object({ city: z.string() }),
136 }).server(async ({ city }) => ({ city, tempC: 22 }))
137​
138 const chunks: Array<unknown> = []
139 try {
140 for await (const chunk of chat({
141 ...createChatOptions({ adapter: createServerToolAdapter() }),
142 tools: [getWeather],
143 messages: [{ role: 'user', content: "What's the weather in NYC?" }],
144 agentLoopStrategy: maxIterations(3),
145 })) {
146 chunks.push(chunk)
147 }
148 } catch (error) {
149 return new Response(
150 JSON.stringify({
151 chunks,
152 error: error instanceof Error ? error.message : String(error),
153 }),
154 { status: 200, headers: { 'Content-Type': 'application/json' } },
155 )
156 }
157​
158 return new Response(JSON.stringify({ chunks, error: null }), {
159 status: 200,
160 headers: { 'Content-Type': 'application/json' },
161 })
162 },
163 },
164 },
165})