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

agentic-cycle.md

368 lines11.5 KB

1---
2title: Agentic Cycle
3id: agentic-cycle
4order: 1
5description: "How chat() loops through tool calls and tool results until the model gives a final answer, and how to limit that loop."
6keywords:
7 - tanstack ai
8 - agentic cycle
9 - agent loop
10 - tool calling
11 - multi-step reasoning
12 - ai agents
13---
14​
15The agent loop calls the model again after each tool result. One call cannot finish a task that needs a tool first.
16​
17`chat()` runs this loop for you. The model calls a tool, `chat()` runs it and gives the result back, and the model continues until it can answer.
18​
19## Quick setup
20​
21### 1. Define the tools
22​
23```typescript
24// tools.ts
25import { toolDefinition } from "@tanstack/ai";
26import { z } from "zod";
27​
28export const getWeather = toolDefinition({
29 name: "get_weather",
30 description: "Get the current weather for a city",
31 inputSchema: z.object({
32 city: z.string(),
33 }),
34}).server(async ({ city }) => {
35 // Replace with a call to your weather API.
36 return { city, temperature: 62, conditions: "cloudy" };
37});
38​
39export const getClothingAdvice = toolDefinition({
40 name: "get_clothing_advice",
41 description: "Get clothing advice for the weather",
42 inputSchema: z.object({
43 temperature: z.number(),
44 conditions: z.string(),
45 }),
46}).server(async ({ temperature }) => {
47 if (temperature < 65) {
48 return { recommendation: "Wear a light jacket" };
49 }
50 return { recommendation: "Light clothing is fine" };
51});
52```
53​
54### 2. Give the tools to `chat()`
55​
56```typescript
57// api/chat.ts
58import {
59 chat,
60 chatParamsFromRequest,
61 toServerSentEventsResponse,
62} from "@tanstack/ai";
63import { openaiText } from "@tanstack/ai-openai";
64import { getClothingAdvice, getWeather } from "./tools";
65​
66export async function POST(request: Request) {
67 const { messages, threadId, runId } = await chatParamsFromRequest(request);
68​
69 const stream = chat({
70 adapter: openaiText("gpt-6.1-sol"),
71 messages,
72 threadId,
73 runId,
74 tools: [getWeather, getClothingAdvice],
75 });
76​
77 return toServerSentEventsResponse(stream);
79```
80​
81### 3. Show the tool calls on the client
82​
83The tool calls arrive as `tool-call` parts in the same message as the text:
84​
85```tsx
86import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
87​
88export function Chat() {
89 const { messages, sendMessage } = useChat({
90 connection: fetchServerSentEvents("/api/chat"),
91 threadId: "support-chat",
92 });
93​
94 return (
95 <>
96 <button
97 type="button"
98 onClick={() => sendMessage("What should I wear in San Francisco today?")}
99 >
100 Ask
101 </button>
102 {messages.map((message) => (
103 <div key={message.id}>
104 {message.parts.map((part, index) => {
105 if (part.type === "tool-call") {
106 return <p key={index}>Called {part.name}</p>;
107 }
108 return part.type === "text" ? <p key={index}>{part.content}</p> : null;
109 })}
110 </div>
111 ))}
112 </>
113 );
115```
116​
117Click "Ask". You see two tool calls, then an answer that uses both results.
118​
119## How it works
120​
121For the question above, the loop runs three model turns:
122​
1231. The model calls `get_weather({ city: "San Francisco" })`. The tool returns `{ temperature: 62, conditions: "cloudy" }`.
1242. The model calls `get_clothing_advice({ temperature: 62, conditions: "cloudy" })`. The tool returns `{ recommendation: "Wear a light jacket" }`.
1253. The model writes: "It is 62 degrees and cloudy in San Francisco. Wear a light jacket."
126​
127```mermaid
128sequenceDiagram
129 participant Client
130 participant Server
131 participant LLM
132 participant Tools
133​
134 Client->>Server: Send message
135 Server->>LLM: Message + tool definitions
136 LLM->>Server: tool_call get_weather
137 Server->>Tools: Run get_weather
138 Tools-->>Server: Result
139 Server->>LLM: tool_result
140 LLM->>Server: tool_call get_clothing_advice
141 Server->>Tools: Run get_clothing_advice
142 Tools-->>Server: Result
143 Server->>LLM: tool_result
144 LLM-->>Server: Final text
145 Server-->>Client: Stream the answer
146```
147​
148The loop continues only while both of these are true:
149​
150- The model stops with the finish reason `tool_calls`, and tool calls wait to run.
151- The agent loop strategy allows one more model turn.
152​
153The loop ends when the model stops with the finish reason `stop`. The full loop is one run, so the client sees one stream.
154​
155Related pages:
156​
157- A tool can run on the client instead of the server. See [Client Tools](../tools/client-tools).
158- A sensitive tool can wait for the user to say yes. See [Tool Approval](../tools/tool-approval).
159- To send a turn to a named child agent, see [Subagents](./subagents).
160​
161> [!TIP]
162> Code Mode can make the loop shorter. The model writes one program that calls many tools in one run. See [Code Mode](../code-mode/code-mode).
163​
164## Control the loop
165​
166By default, the loop stops after five model turns (`maxIterations(5)`), even if the model calls more tools. It also stops after an answer that [hits the output limit](#when-the-output-limit-cuts-a-tool-call). The full default is `combineStrategies([maxIterations(5), untilFinishReason(["length"])])`.
167​
168Set `agentLoopStrategy` to change it:
169​
170```typescript
171// api/chat.ts
172import {
173 chat,
174 chatParamsFromRequest,
175 combineStrategies,
176 maxIterations,
177 toServerSentEventsResponse,
178} from "@tanstack/ai";
179import type { AgentLoopState } from "@tanstack/ai";
180import { openaiText } from "@tanstack/ai-openai";
181import { getClothingAdvice, getWeather } from "./tools";
182​
183export async function POST(request: Request) {
184 const { messages, threadId, runId } = await chatParamsFromRequest(request);
185​
186 const stream = chat({
187 adapter: openaiText("gpt-6.1-sol"),
188 messages,
189 threadId,
190 runId,
191 tools: [getWeather, getClothingAdvice],
192 agentLoopStrategy: combineStrategies([
193 maxIterations(10),
194 ({ messages }: AgentLoopState) => messages.length < 100,
195 ]),
196 });
197​
198 return toServerSentEventsResponse(stream);
200```
201​
202The built-in strategies:
203​
204- `maxIterations(n)`: stop after `n` model turns.
205- `untilFinishReason([...])`: continue until the model returns one of the given finish reasons, for example `untilFinishReason(["stop", "length"])`.
206- `combineStrategies([...])`: continue only while every strategy in the list agrees.
207​
208A strategy is a function. It gets the loop state and returns `true` to allow one more turn, or `false` to stop. The state has these fields:
209​
210- `iterationCount`: the model turns so far, from 0.
211- `finishReason`: the finish reason of the last response.
212- `messages`: the current messages.
213- `toolCallCount`: the tool calls so far in this run.
214- `lastTurnToolCallCount`: the tool calls in the last batch.
215​
216## Advanced
217​
218### When the output limit cuts a tool call
219​
220A model can run out of output tokens in the middle of a tool call, for example while it writes a long file. The provider stops with the finish reason `length`, and the input of the call is not complete.
221​
222`chat()` never runs such a call:
223​
224- It asks for no approval.
225- It starts no client tool.
226- Each cut call gets an error tool result.
227​
228By default, the run then ends with the finish reason `length`. To let the model send the cut call again, use a strategy that does not stop on `length`:
229​
230```typescript
231// api/chat.ts
232import {
233 chat,
234 chatParamsFromRequest,
235 maxIterations,
236 toServerSentEventsResponse,
237} from "@tanstack/ai";
238import { openaiText } from "@tanstack/ai-openai";
239import { getClothingAdvice, getWeather } from "./tools";
240​
241export async function POST(request: Request) {
242 const { messages, threadId, runId } = await chatParamsFromRequest(request);
243​
244 const stream = chat({
245 adapter: openaiText("gpt-6.1-sol"),
246 messages,
247 threadId,
248 runId,
249 tools: [getWeather, getClothingAdvice],
250 agentLoopStrategy: maxIterations(5),
251 });
252​
253 return toServerSentEventsResponse(stream);
255```
256​
257Then this happens after a cut answer:
258​
2591. The loop calls the model again. The model reads the error result and sends the call again.
2602. `maxIterations` counts the cut answer as one model turn. A model that hits the limit every time stops at the iteration limit.
261​
262The client needs no change. When the loop continues, the `RUN_FINISHED` event of the cut answer has the finish reason `tool_calls`. So `useChat` keeps the stream open for the next model turn.
263​
264The default error text tells the model to send the calls again and to split a large input. To use your own text, return a new result from the `onAfterToolCall` middleware hook. The error of a cut call has the code `max_tokens`:
265​
266```typescript
267import { defineChatMiddleware } from "@tanstack/ai";
268​
269export const cutToolCallText = defineChatMiddleware({
270 onAfterToolCall(_ctx, info) {
271 const cut =
272 info.error instanceof Error &&
273 "code" in info.error &&
274 info.error.code === "max_tokens";
275 if (!cut) return;
276 return {
277 type: "replaceResult",
278 result: `Your call to ${info.toolName} was cut off. Write the file in parts of 200 lines or less.`,
279 };
280 },
281});
282```
283​
284Add it with `middleware: [cutToolCallText]` next to `agentLoopStrategy`.
285​
286On the server, each assistant message that `chat()` stores keeps `metadata.tanstack.finishReason`. A cut answer has `length`. If a transcript has a cut call with no result, `chat()` does not run that call.
287​
288### Tool-call budgets (middleware recipe)
289​
290`maxIterations` limits model turns, not tool calls. One model turn can emit many tool calls in parallel. A strategy runs between turns, so it cannot stop one turn that calls too many tools.
291​
292TanStack AI has no built-in `maxToolCalls` strategy. Use middleware to limit tool calls:
293​
294- `onBeforeToolCall`: skip extra calls inside one turn (`maxPerTurn`).
295- `onShouldContinue`: stop more turns when the total of emitted tool calls reaches a budget (`max`). Skipped calls also count toward `toolCallCount`.
296​
297```typescript
298// api/chat.ts
299import {
300 chat,
301 chatParamsFromRequest,
302 maxIterations,
303 toServerSentEventsResponse,
304 type ChatMiddleware,
305} from "@tanstack/ai";
306import { openaiText } from "@tanstack/ai-openai";
307import { getClothingAdvice, getWeather } from "./tools";
308​
309// Your own policy. This is not a library export.
310function toolCallBudget(options: {
311 max?: number;
312 maxPerTurn?: number;
313}): ChatMiddleware {
314 const { max, maxPerTurn } = options;
315 let perTurn = 0;
316​
317 return {
318 name: "tool-call-budget",
319 onIteration() {
320 perTurn = 0;
321 },
322 // A pending or resume batch has no onIteration, so reset here too.
323 onToolPhaseComplete() {
324 perTurn = 0;
325 },
326 onBeforeToolCall() {
327 if (maxPerTurn == null) return undefined;
328 perTurn += 1;
329 if (perTurn > maxPerTurn) {
330 return {
331 type: "skip",
332 result: {
333 error: `Skipped: exceeded maxToolCallsPerTurn (${maxPerTurn})`,
334 },
335 };
336 }
337 return undefined;
338 },
339 onShouldContinue(_ctx, state) {
340 if (max != null && state.toolCallCount >= max) return false;
341 return undefined;
342 },
343 };
345​
346export async function POST(request: Request) {
347 const { messages, threadId, runId } = await chatParamsFromRequest(request);
348​
349 const stream = chat({
350 adapter: openaiText("gpt-6.1-sol"),
351 messages,
352 threadId,
353 runId,
354 tools: [getWeather, getClothingAdvice],
355 agentLoopStrategy: maxIterations(20), // model turns
356 middleware: [
357 toolCallBudget({
358 maxPerTurn: 10, // limit parallel calls inside one turn
359 max: 20, // stop more turns after 20 emitted tool calls in total
360 }),
361 ],
362 });
363​
364 return toServerSentEventsResponse(stream);
366```
367​
368Put this middleware before `toolCacheMiddleware`. Then a skip for a call over the budget wins over a cache hit. See [`onShouldContinue`](../advanced/middleware-advanced#onshouldcontinue) for the hook contract.