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

agentic-cycle.md

320 lines11.3 KB

1---
2title: Agentic Cycle
3id: agentic-cycle
4order: 1
5description: "The agentic cycle in TanStack AI — how the LLM loops through tool calls, results, and reasoning until it produces a final answer."
6keywords:
7 - tanstack ai
8 - agentic cycle
9 - agent loop
10 - tool calling
11 - multi-step reasoning
12 - ai agents
13---
14​
15The agentic cycle is the pattern where the LLM repeatedly calls tools, receives results, and continues reasoning until it can provide a final answer. This enables complex multi-step operations.
16​
17To send a turn to a named child agent, see [Subagents](./subagents).
18​
19> **Tip:** Code Mode can reduce agent loop iterations by letting the LLM write a program that calls multiple tools in a single execution. See [Code Mode](../code-mode/code-mode).
20​
21```mermaid
22graph TD
23 A[User sends message] --> B[LLM analyzes request]
24 B --> C{Does task need tools?}
25 C -->|No| D[Generate text response]
26 C -->|Yes| E[Call appropriate tool]
27 E --> F{Where does<br/>tool execute?}
28 F -->|Server| G[Execute on server]
29 F -->|Client| H[Execute on client]
30 G --> I[Tool returns result]
31 H --> I
32 I --> J[Add result to conversation]
33 J --> K[LLM analyzes result]
34 K --> L{Task complete?}
35 L -->|No| E
36 L -->|Yes| D
37 D --> M[Stream response to user]
38 M --> N[Done]
40 style E fill:#e1f5ff
41 style G fill:#ffe1e1
42 style H fill:#ffe1e1
43 style L fill:#fff4e1
44```
45​
46### Detailed Agentic Flow
47​
48```mermaid
49sequenceDiagram
50 participant User
51 participant Client
52 participant Server
53 participant LLM
54 participant Tools
56 User->>Client: "What's the weather in SF and LA?"
57 Client->>Server: Send message
58 Server->>LLM: Message + tool definitions
60 Note over LLM: Cycle 1: Call first tool
62 LLM->>Server: tool_call: get_weather(SF)
63 Server->>Tools: Execute get_weather
64 Tools-->>Server: {temp: 65, conditions: "sunny"}
65 Server->>LLM: tool_result
67 Note over LLM: Cycle 2: Call second tool
69 LLM->>Server: tool_call: get_weather(LA)
70 Server->>Tools: Execute get_weather
71 Tools-->>Server: {temp: 75, conditions: "clear"}
72 Server->>LLM: tool_result
74 Note over LLM: Cycle 3: Generate answer
76 LLM-->>Server: content: "SF is 65°F..."
77 Server-->>Client: Stream response
78 Client->>User: Display answer
79```
80​
81### Multi-Step Example
82​
83Here's a real-world example of the agentic cycle:
84​
85**User**: "Find me flights to Paris under $500 and book the cheapest one"
86​
87**Cycle 1**: LLM calls `searchFlights({destination: "Paris", maxPrice: 500})`
88- Tool returns: `[{id: "F1", price: 450}, {id: "F2", price: 480}]`
89​
90**Cycle 2**: LLM analyzes results and calls `bookFlight({flightId: "F1"})`
91- Tool requires approval (sensitive operation) — see [Tool Approval](../tools/tool-approval)
92- User approves
93- Tool returns: `{bookingId: "B123", confirmed: true}`
94​
95**Cycle 3**: LLM generates final response
96- "I found 2 flights under $500. I've booked the cheapest one (Flight F1) for $450. Your booking ID is B123."
97​
98### Code Example: Agentic Weather Assistant
99​
100```typescript
101import { chat, toolDefinition, toServerSentEventsResponse } from "@tanstack/ai";
102import { openaiText } from "@tanstack/ai-openai";
103import { z } from "zod";
104​
105// Tool definitions
106const getWeatherDef = toolDefinition({
107 name: "get_weather",
108 description: "Get current weather for a city",
109 inputSchema: z.object({
110 city: z.string(),
111 }),
112});
113​
114const getClothingAdviceDef = toolDefinition({
115 name: "get_clothing_advice",
116 description: "Get clothing recommendations based on weather",
117 inputSchema: z.object({
118 temperature: z.number(),
119 conditions: z.string(),
120 }),
121});
122​
123// Server implementations
124const getWeather = getWeatherDef.server(async ({ city }) => {
125 const response = await fetch(`https://api.weather.com/v1/${city}`);
126 return await response.json();
127});
128​
129const getClothingAdvice = getClothingAdviceDef.server(async ({ temperature, conditions }) => {
130 // Business logic for clothing recommendations
131 if (temperature < 50) {
132 return { recommendation: "Wear a warm jacket" };
133 }
134 return { recommendation: "Light clothing is fine" };
135});
136​
137// Server route
138export async function POST(request: Request) {
139 const { messages } = await request.json();
140​
141 const stream = chat({
142 adapter: openaiText("gpt-5.5"),
143 messages,
144 tools: [getWeather, getClothingAdvice],
145 });
146​
147 return toServerSentEventsResponse(stream);
149```
150​
151**User**: "What should I wear in San Francisco today?"
152​
153**Agentic Cycle**:
1541. LLM calls `get_weather({city: "San Francisco"})` → Returns `{temp: 62, conditions: "cloudy"}`
1552. LLM calls `get_clothing_advice({temperature: 62, conditions: "cloudy"})` → Returns `{recommendation: "Light jacket recommended"}`
1563. LLM generates: "The weather in San Francisco is 62°F and cloudy. I recommend wearing a light jacket."
157​
158The loop continues only while the model's finish reason is `tool_calls` (with pending tool calls) **and** the agent loop strategy permits another iteration. It ends as soon as the model returns a normal `stop` finish reason. An answer that [hits the output limit](#when-the-output-limit-cuts-a-tool-call) is a special case.
159​
160### Controlling the loop
161​
162By 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) (`untilFinishReason(["length"])`). Override this with the `agentLoopStrategy` option.
163​
164Other built-in strategies:
165​
166- **`untilFinishReason([...])`** — continue until the model returns one of the given finish reasons (e.g. `untilFinishReason(["stop", "length"])`).
167- **`combineStrategies([...])`** — combine multiple strategies with AND logic; the loop continues only while every strategy agrees.
168​
169A strategy is just a function that receives `{ iterationCount, finishReason, messages, toolCallCount, lastTurnToolCallCount }` and returns `true` to allow another iteration or `false` to stop, so you can also write your own:
170​
171```typescript
172import { chat, combineStrategies, maxIterations, toServerSentEventsResponse } from "@tanstack/ai";
173import { openaiText } from "@tanstack/ai-openai";
174import type { AgentLoopState } from "@tanstack/ai";
175import { getWeather, getClothingAdvice } from "./tools";
176​
177export async function POST(request: Request) {
178 const { messages } = await request.json();
179 const stream = chat({
180 adapter: openaiText("gpt-5.5"),
181 messages,
182 tools: [getWeather, getClothingAdvice],
183 agentLoopStrategy: combineStrategies([
184 maxIterations(10),
185 ({ messages }: AgentLoopState) => messages.length < 100,
186 ]),
187 });
188 return toServerSentEventsResponse(stream);
190```
191​
192### When the output limit cuts a tool call
193​
194A 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. `chat()` never runs such a call. It asks for no approval and starts no client tool. Each cut call gets an error tool result instead.
195​
196By 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`:
197​
198```typescript
199import { chat, maxIterations, toServerSentEventsResponse } from "@tanstack/ai";
200import { openaiText } from "@tanstack/ai-openai";
201import { writeFile } from "./tools";
202​
203export async function POST(request: Request) {
204 const { messages } = await request.json();
205 const stream = chat({
206 adapter: openaiText("gpt-6.1-sol"),
207 messages,
208 tools: [writeFile],
209 agentLoopStrategy: maxIterations(5),
210 });
211 return toServerSentEventsResponse(stream);
213```
214​
215Then this happens after a cut answer:
216​
2171. The loop calls the model again. The model reads the error result and sends the call again.
2182. `maxIterations` counts the cut answer as one model turn. A model that hits the limit every time stops at the iteration limit.
219​
220The client needs no change. When the loop goes on, 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.
221​
222The 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`:
223​
224```typescript
225import { defineChatMiddleware } from "@tanstack/ai";
226​
227export const cutToolCallText = defineChatMiddleware({
228 onAfterToolCall(_ctx, info) {
229 const cut =
230 info.error instanceof Error &&
231 "code" in info.error &&
232 info.error.code === "max_tokens";
233 if (!cut) return;
234 return {
235 type: "replaceResult",
236 result: `Your call to ${info.toolName} was cut off. Write the file in parts of 200 lines or less.`,
237 };
238 },
239});
240```
241​
242Add it with `middleware: [cutToolCallText]` next to `agentLoopStrategy`.
243​
244On 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.
245​
246### Tool-call budgets (middleware recipe)
247​
248> **Iterations ≠ tool calls.** One model turn can emit many parallel tool calls. `maxIterations` only bounds **model turns**. Strategies run *between* turns, so without a per-turn cap a single runaway turn can still fan out unbounded.
249​
250There is no built-in `maxToolCalls` strategy. Cap tools with middleware:
251​
252- **`onBeforeToolCall`** — skip excess calls inside one turn (`maxPerTurn`)
253- **`onShouldContinue`** — stop further turns once cumulative **emitted** tools hit a budget (`max`); skipped calls still count toward `toolCallCount`
254​
255```typescript
256import {
257 chat,
258 maxIterations,
259 toServerSentEventsResponse,
260 type ChatMiddleware,
261} from "@tanstack/ai";
262import { openaiText } from "@tanstack/ai-openai";
263import { getWeather, getClothingAdvice } from "./tools";
264​
265/** App-owned policy — not a library export. */
266function toolCallBudget(options: {
267 max?: number;
268 maxPerTurn?: number;
269}): ChatMiddleware {
270 const { max, maxPerTurn } = options;
271 let perTurn = 0;
272​
273 return {
274 name: "tool-call-budget",
275 onIteration() {
276 perTurn = 0;
277 },
278 // Fresh per-turn budget for pending/resume batches (no onIteration).
279 onToolPhaseComplete() {
280 perTurn = 0;
281 },
282 onBeforeToolCall() {
283 if (maxPerTurn == null) return undefined;
284 perTurn += 1;
285 if (perTurn > maxPerTurn) {
286 return {
287 type: "skip",
288 result: {
289 error: `Skipped: exceeded maxToolCallsPerTurn (${maxPerTurn})`,
290 },
291 };
292 }
293 return undefined;
294 },
295 onShouldContinue(_ctx, state) {
296 if (max != null && state.toolCallCount >= max) return false;
297 return undefined;
298 },
299 };
301​
302export async function POST(request: Request) {
303 const { messages } = await request.json();
304 const stream = chat({
305 adapter: openaiText("gpt-5.5"),
306 messages,
307 tools: [getWeather, getClothingAdvice],
308 agentLoopStrategy: maxIterations(20), // model turns
309 middleware: [
310 toolCallBudget({
311 maxPerTurn: 10, // cap parallel fan-out inside one turn
312 max: 20, // stop further turns once cumulative emitted tools hit 20
313 }),
314 ],
315 });
316 return toServerSentEventsResponse(stream);
318```
319​
320Place this **before** `toolCacheMiddleware` so over-budget skips win over cache hits. See [`onShouldContinue`](../advanced/middleware#onshouldcontinue) for the hook contract.