rumblr Work in progressWIP

● The AI Primer · Lesson 40 · Part 6: building systems people rely on

The agent loop

production-grade

This lesson covers The loop that runs a language model's errands, with the limits that let it stop

Members · open during launch 20 min7 figures and diagrams

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

  1. 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).
  2. The model never runs anything. Your code checks and runs every tool call.
  3. A production loop adds step limits, token and dollar budgets, loop detection, errors returned as results, and a hand-off to a person.
  4. Tools requested in the same turn run at once, and all their results go back in one user message.
  5. 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

Reading it: start at Goal on the left and follow the arrows round the cycle. The model only ever does the Think box: it reads everything so far and picks the next action. Call a tool and Observe result are your code. The diamond is the only exit, with three ways out: the model says it is done, a limit trips, or the task goes to a person.

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

Reading it: time runs top to bottom. The model's reply is a request (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

0 5 10 15 20 25 30 steps in the run 0 50000 100000 150000 200000 total input tokens Cumulative input tokens (500 new tokens per step) if each step cost the same (linear) re-sending history (quadratic)

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

Reading it: the x-axis is the number of steps in a run and the y-axis the total input tokens sent, at 500 new tokens a step. The straight line is what you would expect if every step cost the same. The curve is what re-sending the history costs. At 10 steps the gap is about 5x, and it widens with every step. Trimming tool output and prompt caching (see Cost and latency) flatten the curve.

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

0 2 4 6 8 10 step 0 2000 4000 6000 8000 10000 12000 tokens A runaway agent: each call re-sends the whole history running total budget (12,000) tokens sent this step

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

Reading it: each bar is one call to the model, and the bars grow because the history grows. The line is the running total, which is what you pay for, and it bends upward. The dashed horizontal line is the budget. The run stops at the first step where the total crosses it.

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

Reading it: every box that starts with 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

Reading it: the model asked for A, B and C in the same turn, before it saw any result, so none depends on another and they are safe to run at once. The turn then takes as long as the slowest call instead of the sum of all three. On the way back, all three results go in a single user message, where the API pairs each with its request by id. Splitting them across messages teaches the model to stop asking for parallel calls.

Figure 7 · Chart

1 2 3 4 5 6 7 8 tool calls requested in one turn 1 2 3 4 5 wall-clock seconds Parallel tool calls: time is the slowest call, not the sum sequential (sum of latencies) concurrent (max latency)

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

Reading it: the x-axis is how many tools the model asked for in one turn. Each tool has an illustrative latency, drawn at random between 0.2 s and 1.2 s. Run one after another, the time is the sum and climbs with every tool. Run concurrently, it is the longest single call, and the line levels off.

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

Yao et al., ReAct: Synergizing Reasoning and Acting in Language Models (2022).

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 paper

Researcher'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.