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

api.tool-call-lifecycle-wire.ts

164 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 model,
96 timestamp: Date.now(),
97 }
98 yield {
99 type: EventType.TOOL_CALL_ARGS,
100 toolCallId,
101 delta: '{"city":"NYC"}',
102 model,
103 timestamp: Date.now(),
104 }
105 yield {
106 type: EventType.TOOL_CALL_END,
107 toolCallId,
108 toolCallName: 'getWeather',
109 input: { city: 'NYC' },
110 model,
111 timestamp: Date.now(),
112 }
113 yield {
114 type: EventType.RUN_FINISHED,
115 runId,
116 threadId,
117 model,
118 finishReason: 'tool_calls',
119 timestamp: Date.now(),
120 }
121 },
122 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
123 }
125​
126export const Route = createFileRoute('/api/tool-call-lifecycle-wire')({
127 server: {
128 handlers: {
129 POST: async () => {
130 const getWeather = toolDefinition({
131 name: 'getWeather',
132 description: 'Get the weather for a city',
133 inputSchema: z.object({ city: z.string() }),
134 }).server(async ({ city }) => ({ city, tempC: 22 }))
135​
136 const chunks: Array<unknown> = []
137 try {
138 for await (const chunk of chat({
139 threadId: 'tool-call-lifecycle-wire',
140 ...createChatOptions({ adapter: createServerToolAdapter() }),
141 tools: [getWeather],
142 messages: [{ role: 'user', content: "What's the weather in NYC?" }],
143 agentLoopStrategy: maxIterations(3),
144 })) {
145 chunks.push(chunk)
146 }
147 } catch (error) {
148 return new Response(
149 JSON.stringify({
150 chunks,
151 error: error instanceof Error ? error.message : String(error),
152 }),
153 { status: 200, headers: { 'Content-Type': 'application/json' } },
154 )
155 }
156​
157 return new Response(JSON.stringify({ chunks, error: null }), {
158 status: 200,
159 headers: { 'Content-Type': 'application/json' },
160 })
161 },
162 },
163 },
164})