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 toolName: 'ping',
132 index: i,
133 model,
134 timestamp: Date.now(),
135 }
136 yield {
137 type: EventType.TOOL_CALL_ARGS,
138 toolCallId,
139 delta: `{"n":${i}}`,
140 model,
141 timestamp: Date.now(),
142 }
143 yield {
144 type: EventType.TOOL_CALL_END,
145 toolCallId,
146 toolCallName: 'ping',
147 toolName: 'ping',
148 input: { n: i },
149 model,
150 timestamp: Date.now(),
151 }
152 }
153
154 yield {
155 type: EventType.RUN_FINISHED,
156 runId,
157 threadId,
158 model,
159 finishReason: 'tool_calls',
160 timestamp: Date.now(),
161 }
162 },
163 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
164 }
165}
166
167export const Route = createFileRoute('/api/max-tool-calls-wire')({
168 server: {
169 handlers: {
170 POST: async () => {
171 let executeCount = 0
172 const ping = toolDefinition({
173 name: 'ping',
174 description: 'Ping tool for fan-out budget tests',
175 inputSchema: z.object({ n: z.number() }),
176 }).server(async ({ n }) => {
177 executeCount++
178 return { n, ok: true }
179 })
180
181 const chunks: Array<unknown> = []
182 let error: string | null = null
183 try {
184 for await (const chunk of chat({
185 ...createChatOptions({
186 adapter: createFatParallelAdapter(8),
187 }),
188 tools: [ping],
189 messages: [{ role: 'user', content: 'Call ping many times' }],
190 // maxIterations high enough that only middleware can stop the loop
191 agentLoopStrategy: maxIterations(10),
192 middleware: [
193 toolCallBudget({
194 maxPerTurn: 3,
195 max: 5,
196 }),
197 ],
198 })) {
199 chunks.push(chunk)
200 }
201 } catch (err) {
202 error = err instanceof Error ? err.message : String(err)
203 }
204
205 return new Response(
206 JSON.stringify({
207 chunks,
208 error,
209 executeCount,
210 }),
211 { status: 200, headers: { 'Content-Type': 'application/json' } },
212 )
213 },
214 },
215 },
216})