Open History to see the last commit
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 {
11 AnyTextAdapter,
12 ChatMiddleware,
13 AdapterYieldChunk,
14} from '@tanstack/ai'
15
16/**
17 * Wire-format regression for issue #964.
18 *
19 * `maxIterations` counts model turns, not tool calls. A single turn can emit
20 * unbounded parallel tool calls. This route emits a fat parallel turn (8
21 * calls) and asserts an app-owned tool-budget middleware can:
22 * 1. Cap how many execute per turn (`onBeforeToolCall` skip)
23 * 2. Stop further model turns once cumulative emitted tools hit a budget
24 * (`onShouldContinue`)
25 * 3. Still emit error tool results for skipped calls (history stays consistent)
26 *
27 * The budget middleware is the docs recipe — not a library export.
28 */
29function toolCallBudget(options: {
30 max?: number
31 maxPerTurn?: number
32}): ChatMiddleware {
33 const { max, maxPerTurn } = options
34 let perTurn = 0
35 return {
36 name: 'tool-call-budget',
37 onIteration() {
38 perTurn = 0
39 },
40 onToolPhaseComplete() {
41 perTurn = 0
42 },
43 onBeforeToolCall() {
44 if (maxPerTurn == null) return undefined
45 perTurn += 1
46 if (perTurn > maxPerTurn) {
47 return {
48 type: 'skip' as const,
49 result: {
50 error: `Skipped: exceeded maxToolCallsPerTurn (${maxPerTurn})`,
51 },
52 }
53 }
54 return undefined
55 },
56 onShouldContinue(_ctx, state) {
57 if (max != null && state.toolCallCount >= max) return false
58 return undefined
59 },
60 }
61}
62
63function createFatParallelAdapter(callCount: number): AnyTextAdapter {
64 return {
65 kind: 'text',
66 name: 'max-tool-calls-test',
67 model: 'max-tool-calls-test',
68 '~types': {
69 providerOptions: {},
70 inputModalities: ['text'],
71 messageMetadataByModality: {},
72 toolCapabilities: [],
73 toolCallMetadata: undefined,
74 systemPromptMetadata: undefined,
75 },
76 async *chatStream(options): AsyncGenerator<AdapterYieldChunk> {
77 const model = 'max-tool-calls-test'
78 const runId = options.runId ?? 'max-tool-calls-run'
79 const threadId = options.threadId ?? 'max-tool-calls-thread'
80 const messageId = `${runId}-message`
81 const hasToolResult = options.messages.some((m) => m.role === 'tool')
82
83 yield {
84 type: EventType.RUN_STARTED,
85 runId,
86 threadId,
87 model,
88 timestamp: Date.now(),
89 }
90
91 // Later iterations: answer with text once any tool results are present.
92 if (hasToolResult) {
93 yield {
94 type: EventType.TEXT_MESSAGE_START,
95 messageId,
96 role: 'assistant',
97 model,
98 timestamp: Date.now(),
99 }
100 yield {
101 type: EventType.TEXT_MESSAGE_CONTENT,
102 messageId,
103 delta: 'done',
104 model,
105 timestamp: Date.now(),
106 }
107 yield {
108 type: EventType.TEXT_MESSAGE_END,
109 messageId,
110 model,
111 timestamp: Date.now(),
112 }
113 yield {
114 type: EventType.RUN_FINISHED,
115 runId,
116 threadId,
117 model,
118 finishReason: 'stop',
119 timestamp: Date.now(),
120 }
121 return
122 }
123
124 // First iteration: emit many parallel tool calls in one turn.
125 for (let i = 0; i < callCount; i++) {
126 const toolCallId = `call_${i}`
127 yield {
128 type: EventType.TOOL_CALL_START,
129 toolCallId,
130 toolCallName: 'ping',
131 index: i,
132 model,
133 timestamp: Date.now(),
134 }
135 yield {
136 type: EventType.TOOL_CALL_ARGS,
137 toolCallId,
138 delta: `{"n":${i}}`,
139 model,
140 timestamp: Date.now(),
141 }
142 yield {
143 type: EventType.TOOL_CALL_END,
144 toolCallId,
145 toolCallName: 'ping',
146 input: { n: i },
147 model,
148 timestamp: Date.now(),
149 }
150 }
151
152 yield {
153 type: EventType.RUN_FINISHED,
154 runId,
155 threadId,
156 model,
157 finishReason: 'tool_calls',
158 timestamp: Date.now(),
159 }
160 },
161 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
162 }
163}
164
165export const Route = createFileRoute('/api/max-tool-calls-wire')({
166 server: {
167 handlers: {
168 POST: async () => {
169 let executeCount = 0
170 const ping = toolDefinition({
171 name: 'ping',
172 description: 'Ping tool for fan-out budget tests',
173 inputSchema: z.object({ n: z.number() }),
174 }).server(async ({ n }) => {
175 executeCount++
176 return { n, ok: true }
177 })
178
179 const chunks: Array<unknown> = []
180 let error: string | null = null
181 try {
182 for await (const chunk of chat({
183 threadId: 'max-tool-calls-wire',
184 ...createChatOptions({
185 adapter: createFatParallelAdapter(8),
186 }),
187 tools: [ping],
188 messages: [{ role: 'user', content: 'Call ping many times' }],
189 // maxIterations high enough that only middleware can stop the loop
190 agentLoopStrategy: maxIterations(10),
191 middleware: [
192 toolCallBudget({
193 maxPerTurn: 3,
194 max: 5,
195 }),
196 ],
197 })) {
198 chunks.push(chunk)
199 }
200 } catch (err) {
201 error = err instanceof Error ? err.message : String(err)
202 }
203
204 return new Response(
205 JSON.stringify({
206 chunks,
207 error,
208 executeCount,
209 }),
210 { status: 200, headers: { 'Content-Type': 'application/json' } },
211 )
212 },
213 },
214 },
215})