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

agentic-cycle.md

266 lines8.7 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.
159​
160### Controlling the loop
161​
162By default the loop is bounded by `maxIterations(5)` — after five **model turns** it stops even if the model would keep calling tools. 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### Tool-call budgets (middleware recipe)
193​
194> **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.
195​
196There is no built-in `maxToolCalls` strategy. Cap tools with middleware:
197​
198- **`onBeforeToolCall`** — skip excess calls inside one turn (`maxPerTurn`)
199- **`onShouldContinue`** — stop further turns once cumulative **emitted** tools hit a budget (`max`); skipped calls still count toward `toolCallCount`
200​
201```typescript
202import {
203 chat,
204 maxIterations,
205 toServerSentEventsResponse,
206 type ChatMiddleware,
207} from "@tanstack/ai";
208import { openaiText } from "@tanstack/ai-openai";
209import { getWeather, getClothingAdvice } from "./tools";
210​
211/** App-owned policy — not a library export. */
212function toolCallBudget(options: {
213 max?: number;
214 maxPerTurn?: number;
215}): ChatMiddleware {
216 const { max, maxPerTurn } = options;
217 let perTurn = 0;
218​
219 return {
220 name: "tool-call-budget",
221 onIteration() {
222 perTurn = 0;
223 },
224 // Fresh per-turn budget for pending/resume batches (no onIteration).
225 onToolPhaseComplete() {
226 perTurn = 0;
227 },
228 onBeforeToolCall() {
229 if (maxPerTurn == null) return undefined;
230 perTurn += 1;
231 if (perTurn > maxPerTurn) {
232 return {
233 type: "skip",
234 result: {
235 error: `Skipped: exceeded maxToolCallsPerTurn (${maxPerTurn})`,
236 },
237 };
238 }
239 return undefined;
240 },
241 onShouldContinue(_ctx, state) {
242 if (max != null && state.toolCallCount >= max) return false;
243 return undefined;
244 },
245 };
247​
248export async function POST(request: Request) {
249 const { messages } = await request.json();
250 const stream = chat({
251 adapter: openaiText("gpt-5.5"),
252 messages,
253 tools: [getWeather, getClothingAdvice],
254 agentLoopStrategy: maxIterations(20), // model turns
255 middleware: [
256 toolCallBudget({
257 maxPerTurn: 10, // cap parallel fan-out inside one turn
258 max: 20, // stop further turns once cumulative emitted tools hit 20
259 }),
260 ],
261 });
262 return toServerSentEventsResponse(stream);
264```
265​
266Place this **before** `toolCacheMiddleware` so over-budget skips win over cache hits. See [`onShouldContinue`](../advanced/middleware#onshouldcontinue) for the hook contract.