Lesson 1 of 6 · 5 min read
The Agent Loop
In this lesson
TL;DR: An agent is a model in a loop that the harness runs: assemble the context, call the model, execute the tool calls it proposes, append the results, repeat. The model never executes anything and never stops the run by itself. The transcript grows every turn and the model rereads all of it, so a twenty-turn run pays for its early turns twenty times over.
After this lesson, you should be able to write a working agent loop without a framework, say who decides what at each step, list the ways a run ends, and estimate what a run costs as it grows.
Before you read
Commit to an answer now. The lesson that follows explains it, and having guessed first, even wrongly, makes the explanation easier to remember.
1A model returns a tool call: refund(order="4471", amount=84). What has happened in the world at this point?
Ten lines of loop
Here is a whole agent. A scripted fake model stands in for the real one so the example runs anywhere, but the loop is the same loop every framework runs.
import json
def fake_model(messages, tools):
"""Scripted stand-in for a model API: returns tool calls, then an answer."""
turn = sum(1 for m in messages if m["role"] == "assistant")
script = [
{"tool_calls": [{"id": "c1", "name": "get_order", "args": {"id": "4471"}}]},
{"tool_calls": [{"id": "c2", "name": "get_shipping", "args": {"id": "4471"}}]},
{"content": "Order 4471 shipped on 3 November and arrives on the 6th."},
]
return script[min(turn, len(script) - 1)]
TOOLS = {
"get_order": lambda id: {"id": id, "status": "shipped", "total": 84.0},
"get_shipping": lambda id: {"carrier": "DHL", "eta": "2026-11-06"},
}
def run(task, max_steps=8):
messages = [{"role": "user", "content": task}]
for step in range(1, max_steps + 1):
reply = fake_model(messages, list(TOOLS))
messages.append({"role": "assistant", **reply})
if not reply.get("tool_calls"):
return reply["content"], "final_answer", step
for call in reply["tool_calls"]:
try:
result = TOOLS[call["name"]](**call["args"])
except Exception as exc: # errors go back to the model as data
result = {"error": f"{type(exc).__name__}: {exc}"}
messages.append(
{"role": "tool", "id": call["id"], "content": json.dumps(result)}
)
return None, "step_budget", max_steps
answer, stop, steps = run("Where is my order 4471?")
print(stop, steps) # => final_answer 3
print(answer)
Read it as four moves that repeat. Assemble: the message list is the context; the model sees exactly what the harness put there and nothing else. Call: the model returns either text or tool calls. Dispatch: the harness looks up each tool, runs it, and turns an exception into a result the model can read instead of a crash. Append: results join the history under their call id, and the loop goes round.
Two lines carry most of the design. if not reply.get("tool_calls") is the model's way of saying it is finished, and it is only an opinion. for step in range(1, max_steps + 1) is the harness's way of saying the run is finished whatever the model thinks. Production harnesses add many more exits, but they all live on the harness side of the loop.
- final answer, no tool calls
- step or token budget spent
- wall-clock or cost limit
- a guard refuses the next action
- human takes over
Assemble the context
The harness builds the request: instructions, the tool definitions, and every earlier turn with its tool results. The model sees nothing the harness did not put here.
Who decides what
The authority line runs straight through the loop. The model decides which tool to ask for, with which arguments, and when it believes it has an answer. The harness decides whether that tool exists, whether the arguments are valid, whether this caller may do this to this object, whether the call runs now or waits for a person, what a failure looks like to the model, and when the run ends.
This is why "the agent refunded the wrong order" is never a model problem in the end. The model proposed it. Some piece of code accepted a customer id from model output and executed the refund. A strong engineer reads every incident by asking which side of the line let it through.
What each turn costs
The model is stateless between calls, so every turn resends the whole transcript. Suppose the system prompt and tool definitions take 3,000 tokens and each turn adds about 700 (the model's tool call plus a trimmed result):
input tokens on turn t = 3,000 + 700 × (t − 1)
turn 1 = 3,000
turn 20 = 3,000 + 700 × 19 = 16,300
total over 20 turns = 20 × 3,000 + 700 × (0 + 1 + … + 19)
= 60,000 + 700 × 190 = 193,000 tokens
sanity: the run reads ~12x its final context, because early turns are reread every turn
At an illustrative $3 per million input tokens that run costs about $0.58 in input alone, and the cost grows with the square of the number of turns. This is why agents leak money through long runs, why prompt caching matters more for agents than for chat (most of each request is a prefix the provider has already seen), and why tool results should be trimmed before they enter the history. The numbers are illustrative; the shape is not.
The exits
| Exit | Who triggers it | What the caller should get |
|---|---|---|
| Final answer, no tool calls | The model | The answer, plus the trace if the caller audits |
| Step budget spent | The harness | A partial result and "stopped at the step limit", never a fabricated answer |
| Token, cost or wall-clock budget spent | The harness | The same, with the budget named |
| A guard refuses the next action | Policy code | What was refused and why, and whether a person can approve it |
| A tool fails in a way retries cannot fix | The harness | The failure, the last good state, and an escalation |
| A person takes over | The human-in-the-loop path | The handoff record |
A run that ends at the step limit and returns the model's last half-formed message as if it were an answer is the commonest bug in first harnesses. The exit reason is part of the result.
Where a run goes wrong
When a run misbehaves, the failure entered at one of five places, and naming which one is most of the diagnosis:
- The tool contract. A vague description, an argument the model misreads, an error that gives it nothing to act on. (See Tool Calling & Tool Contracts.)
- The context. The result it needed was truncated, compacted away, or buried under forty earlier results. (Context Engineering.)
- The plan. It committed to an approach and kept going after the world changed. (Planning & Control.)
- The runtime. A timeout, a crash between a side effect and its record, a retry that repeated a write. (Long-Running & Durable Agents.)
- The input. Something it read, a web page or an email, steered it. (Guardrails, Identity & Policy.)
Reading the trace, step by step, is how you find which. A fix with no failure location attached is a guess.
Text formats and native tool calling
Early agents parsed tool calls out of free text, the ReAct format of Thought:, Action: and Observation: lines (Yao et al., 2022). Current model APIs return tool calls as structured objects with ids, and many can return several in one turn. The loop did not change: propose, execute, observe, decide. What changed is that the harness no longer has to recover a call from prose, so malformed calls are rarer and parallel calls are possible. Anything you learn about the loop transfers to every API and framework, because they all implement it.
Say it in 30 seconds
"An agent is a loop the harness runs. Each turn it sends the model the transcript and the tool definitions; the model returns an answer or tool calls; the harness validates and executes the calls, appends the results and goes again. The model proposes and the harness disposes, including the decision to stop, which can come from a budget, a guard or a person as well as from the model. Because the transcript is resent every turn, cost grows roughly with the square of the turn count."
Check yourself
Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.
1Your loop's only exit is 'the model returned no tool calls'. Name two ways that run can go wrong.
2A tool raises an exception. Should the harness crash the run, retry silently, or return the error to the model?
3Turn 1 of a run sends 4,000 tokens and every turn adds 500. Roughly how many input tokens does a 10-turn run read?