What this is
What is the agent loop?
The agent loop is the code that lets an AI language model carry out a task one step at a time. A language model can only write text. So the loop calls it, runs whatever it asks for (a search, a lookup), sends the result back, and repeats until the language model says it is done. Picture a new assistant who reports back after every errand and asks for the next one, while you run the errands. The plain loop is about ten lines of code. A loop fit for production adds limits on steps, tokens and dollars, a check for repeated requests and a way to hand the task to a person, so every run ends for a reason you can name.
Why it matters: The plain loop stops only when the language model says it is done, so a confused one can search forever, each call costing more than the last. Once an agent spends real money or changes real records, you need the controls that end every run on purpose.
At a glance
Key takeaways
- The agent loop calls the model, runs the tools it asks for, appends the results and repeats until the model ends its turn (
end_turn). - The model never runs anything. Your code checks and runs every tool call.
- A production loop adds step limits, token and dollar budgets, loop detection, errors returned as results, and a hand-off to a person.
- Tools requested in the same turn run at once, and all their results go back in one user message.
- Input cost grows roughly with the square of the number of steps, because every call re-sends the history.
How it works, from scratch
Each reply from the model is either an answer or a request to use a tool. The loop's work is to tell the two apart, carry out each request, and call the model again with the result. Follow one question through it.
Chapter 1
The loop, on one question
Take the question "How many PTO days does alice have left, and what rolls over?" (PTO is paid time off) and an agent with two tools: one searches the company's policy documents, the other looks up an employee's leave balance. Here is the transcript of a run in which a scripted stand-in plays the model:
[user] How many PTO days does alice have left, and what rolls over?
[assistant] I'll check the PTO policy and alice's balance at the same time.
tool_use toolu_1 search_kb {"query": "PTO rollover"}
tool_use toolu_2 get_pto_balance {"employee": "alice", "as_of": "2026-09-25"}
[user] tool_result toolu_1 "[hr-001] Paid time off: ... Unused PTO up to 5 days rolls over. ..."
tool_result toolu_2 {"employee": "alice", "as_of": "2026-09-25", "days_left": 12}
[assistant] Alice has 12 PTO days left. Up to 5 unused days roll over to next year [hr-001].
(stop_reason: end_turn)
The model's first reply is a sentence and two requests, one for each tool.
It asks for both in one turn because neither answer depends on the other.
The loop runs both tools and sends the two results back as the next user
message. With the policy and the balance in front of it, the model writes
its answer and ends its turn, which the API reports as end_turn.
This alternation of a short piece of reasoning ("I'll check both at once") with actions, each followed by reading what came back, is called ReAct ("reason + act"), after the paper that named it.
Figure 1 · Diagram
flowchart LR
G[Goal] --> T[Think<br/>choose next step]
T --> C[Call a tool]
C --> O[Observe result]
O --> D{Done, or budget<br/>or step limit hit?}
D -->|No| T
D -->|Yes| F[Final answer<br/>or hand to human]
In code: run_agent is this loop, and search_kb and get_pto_balance
are the two tools. It returns an AgentResult with the final text, the stop
cause, every step, the usage and the cost. View source
Chapter 2
One round trip, message by message
The same question, drawn as the messages that pass between the user, your loop, the model and the tools:
Figure 2 · Diagram
sequenceDiagram participant U as User participant L as Your loop participant M as Model participant T as Tools U->>L: task L->>M: system + messages + tool definitions M-->>L: tool_use blocks (stop_reason = tool_use) L->>L: validate, check budget, check for loops L->>T: run the calls (concurrently) T-->>L: results or errors L->>M: ONE user message with every tool_result M-->>L: final text (stop_reason = end_turn) L-->>U: answer + stop cause
tool_use), never an action. Everything between that request and the next
call to the model happens in your loop: checking the request, the budget and
any repeats, then running the tools. Look at the two arrows into the model.
The second carries the whole conversation again, the first exchange
included.In code: each pass through run_agent appends the model's full reply,
runs the requested tools and appends every result in one user message. A
Step records one model call and the ToolExecutions it triggered. View source
Chapter 3
Why cost grows quadratically
Because every call sends the entire conversation so far, a run costs more than its length suggests. If every step adds about tokens, call sends roughly input tokens, so a run of steps sends
The formula and its symbols
Symbols
| Symbol | Meaning |
|---|---|
| new tokens each step adds to the conversation (tool call + result) | |
| the step number, 1, 2, 3, ... | |
| total steps in the run |
In words: call carries all steps so far, so the total is times , which is about half of squared times .
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: with and , the total is input tokens, not the you'd guess. Double to and it's , almost 4x.
In Python:
t = 500
def total_input(n):
# Σ_k k·t: step k re-sends k steps' worth
return sum(k * t for k in range(1, n + 1))
total_input(10) # → 27500
total_input(20) # → 105000
# almost 4x
round(total_input(20) / total_input(10), 1) # → 3.8
Figure 3 · Chart
At 10 steps re-sending the history costs 27,500 input tokens against the 5,000 a flat per-step cost suggests, and the gap keeps widening
A model that keeps working without ever finishing climbs that curve until something stops it. In the next run a scripted model searches again and again with a new query each time, so it never repeats itself, and the loop has a budget of 12,000 tokens.
Figure 4 · Chart
Each call of a runaway agent sends more tokens than the last, and the run stops at the first call where the running total passes the 12,000-token budget
In code: cumulative_input_tokens evaluates the formula, times
, for any run length. View source
Chapter 4
The controls, in the order the loop checks them
A runaway bill is one way the ten-line loop fails. Each way gets a control, much as an assistant sent out on errands gets a spending limit (the budget), a time to be back by (the step limit), an instruction to come home if they pass the same shop a third time (loop detection), and a number to call if something feels wrong (the hand-off to a person). The loop checks its controls after every reply from the model, in a fixed order.
Figure 5 · Diagram
flowchart TD
R[Model response] --> S1{stop_reason?}
S1 -->|refusal| X1[stop: refusal]
S1 -->|max_tokens| X2[stop: max_tokens<br/>don't run half-written calls]
S1 -->|end_turn| X3[stop: completed]
S1 -->|tool_use| B{Over token or<br/>dollar budget?}
B -->|yes| X4[stop: budget_exceeded]
B -->|no| H{Called handoff_to_human?}
H -->|yes| X5[stop: handoff]
H -->|no| L{Same tool + same args<br/>seen N times?}
L -->|yes| X6[stop: loop_detected]
L -->|no| E[Run tools concurrently]
E --> A[Append all results<br/>in one user message]
A --> N{Step limit hit?}
N -->|yes| X7[stop: max_steps]
N -->|no| M[Call the model again]
stop: is an exit, seven in
all, and each is a cause the run reports when it ends. Read top to bottom:
the model's own stop reason comes first, then the budget, then a request
for a person, then repetition, and only after all of those does the loop
spend time running tools. A truncated reply (max_tokens) is caught before
any tool runs, because a call cut off mid-argument must never execute.| Failure | What happens | Control in run_agent |
|---|---|---|
| Model never says "done" | Runs forever | max_steps |
| Each turn re-sends the whole conversation | Cost grows quadratically with steps | max_total_tokens, max_cost_usd |
| Model repeats the same call | Burns money, no progress | loop detection on (tool, canonical args) |
| Tool raises | Loop crashes, or the model never learns why | errors become is_error tool results with actionable text |
| Unknown tool / hallucinated name | KeyError |
is_error result listing the real tools |
| Several independent calls in one turn | Slow if run one by one | run concurrently, return all results in one user message |
Output cut off (max_tokens) |
Half-written tool call | stop with cause max_tokens |
Safety refusal (refusal) |
Content is not an answer | stop with cause refusal |
| Task is outside the agent's authority | Agent guesses | a handoff_to_human tool that ends the run cleanly |
Three rows never stop the run. A failed tool call and a call to a missing
tool go back to the model as error messages it can act on, such as "date
must be YYYY-MM-DD", and running calls at once only saves time. Every other
row ends the run with a named cause, such as loop_detected at step 3,
which you can count and alert on.
In code: AgentConfig holds every limit and the prices that turn token
usage into dollars. A tool raises ToolError to send the model an error it
can act on, and HANDOFF_TOOL_DEF defines the hand-off tool. View source
Chapter 5
Parallel tool calls
When the model asks for several tools in one turn, as it did for the leave question, the loop can run them all at once.
Figure 6 · Diagram
flowchart LR M[Assistant turn<br/>tool_use A, tool_use B, tool_use C] --> A[run A] M --> B[run B] M --> C[run C] A --> J[One user message:<br/>tool_result A, B, C<br/>matched by tool_use_id] B --> J C --> J
Figure 7 · Chart
Run one after another, tool calls take the sum of their latencies and keep climbing; run concurrently, they take only as long as the slowest call
In code: execute_tools runs one turn's calls on a thread pool and
returns their results in the order they were asked for, with an unknown tool
or a raised exception turned into an error result. View source
Chapter 6
Running it against a real model
Every run so far used a scripted stand-in for the model. The loop needs only
something that takes the messages and returns a reply (the LLM protocol in
Talking to a language model), so the same code runs against Claude:
from primer.agents.llm import ClaudeLLM
from primer.agents.agent_loop import run_agent, AgentConfig
result = run_agent(
ClaudeLLM(), # needs `pip install anthropic` + credentials
task="How many PTO days does alice have left, and what's the rollover rule?",
tools=HR_TOOLS, # name -> python function
tool_defs=HR_TOOL_DEFS, # Anthropic tool definitions (JSON Schema)
system="You are an HR assistant. Use tools; cite doc ids.",
config=AgentConfig(max_steps=8, max_cost_usd=0.50),
)
print(result.stop_cause, result.final_text)
Anthropic's SDK also ships a tool runner (client.beta.messages.tool_runner)
that runs this loop for you. Write the loop yourself when you need your own
budgets, loop detection, approval steps or tracing.
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: An agent in production suddenly costs 5x more per task. What do you check first?Think it through, then reveal
A: Steps per task and tokens per step, from traces. A jump usually means a loop (the same call repeated), a tool that started returning huge payloads, or a prompt change that stopped the model from recognizing "done". Step budgets and loop detection cap the damage; alerts on tokens per task catch it early.
Question 2Q: A tool throws an exception mid-run. What should the loop do?Think it through, then reveal
A: Catch it and return a tool_result with is_error: true and a message the
model can act on ("date must be YYYY-MM-DD, got 'next friday'"). The model
usually fixes its next call. Crashing the loop throws away the work so far;
hiding the error makes the model guess.
Question 3Q: Why return all parallel tool results in one message?Think it through, then reveal
A: The API pairs each tool_use with its tool_result by id in the next user
turn. Splitting results across several messages breaks that pairing and
teaches the model to stop making parallel calls, which slows every run.
Question 4Q: When should an agent hand off to a human?Think it through, then reveal
A: When it lacks authority (refunds over a limit), lacks information after reasonable search, finds conflicting sources, or hits a budget. Make hand-off a tool, so it is an explicit, logged outcome rather than a vague final answer.
Primary sources
The papers behind this lesson
A language model that alternated short reasoning with tool actions, reading each result before its next step, made up fewer facts than one that only reasoned, and beat earlier methods on a text game and a shopping website. The loop in this lesson has that shape.
Read on rumblr →The paperResearcher's shelf
Further reading
- Anthropic, Building effective agents: https://www.anthropic.com/engineering/building-effective-agents
- Claude tool use, implementing the loop: https://docs.claude.com/en/docs/agents-and-tools/tool-use/implement-tool-use
- Yao et al., ReAct: Synergizing Reasoning and Acting in Language Models (2022): https://arxiv.org/abs/2210.03629
- Lilian Weng, LLM Powered Autonomous Agents: https://lilianweng.github.io/posts/2023-06-23-agent/
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.