Part I — What actually is an agent?Lesson 02 of 36Agent loop3 min readdone

The agent loop

What you should understand afterwards

observe → decide → act → observe → … → stop. This is the central concept for everything else.

The agent loop is what turns a single call to a model into a system that can get work done. This lesson covers what happens on each pass through it, and what makes it stop.

The four steps of the loop

A tool call is a structured request that appears in the model's reply, asking for something to be run on its behalf: read this file, run this command. The model cannot reach outside the conversation itself, so the loop exists to service those requests, and it has four steps. Send the conversation so far to the model; read the reply; if the reply contains a tool call, run that tool and append its result to the conversation; then send the conversation again. A reply with no tool call in it ends the loop, and that reply is the answer. Written out in Python this comes to nine or ten lines. What ends there is the inner loop: control goes back to whoever asked the question, and their next message starts it again, so an interactive agent is two loops nested one inside the other.

Read

  1. Anthropic docs § The agentic loop (client tools)
  2. Philip Zeyliger, Sketch — the whole loop in nine lines of Python
  3. mini-swe-agent · agents/default.py, run(), lines 88–124
  4. mini_agent · README, the inner and outer loops, lines 102–110

Why the whole conversation is sent every time

Each request to the model is independent. The model keeps no record of earlier steps in the run, so the code around it sends the entire conversation every time: the original instruction, every reply the model has made, and the result of every tool call so far. The loop grows that list by appending to it, which is why the conversation is the only memory an agent has. The number of tokens sent therefore grows with the square of the number of steps, because each step resends everything that came before it. Prompt caching brings the cost back to roughly linear, because the provider stores the computation for a prefix it has already processed and charges less to reuse it, but that only holds while the earliest part of the conversation stays byte-for-byte identical. A long run still fills the context window, which is the maximum amount of text the model can be sent at once.

Read

  1. Sergei Rastrigin § The Conversation History
  2. mini-swe-agent · README, Has a completely linear history
  3. mini-swe-agent · agents/default.py, add_messages(), lines 69–86
  4. OpenAI, "Unrolling the Codex agent loop" § Performance considerations

Stop conditions: how the loop knows it is finished

stop_reason is a field on the model's response that says why the model stopped generating, and the loop keys on it: carry on while the value is tool_use, which means the model has asked for a tool to be run and is waiting for the result. Every other value ends the loop. end_turn means the model finished its reply, max_tokens means the response hit a length limit, and refusal means the model declined. pause_turn looks like an ending but is not one: it means the model paused a long-running operation and expects the conversation to be sent back so it can continue, so a loop that exits on it cuts the work short. Not every agent reads this field at all: some check only whether any tool calls came back, which is shorter to write and behaves identically until one of the rarer values turns up.

Read

  1. Anthropic docs § Stop reason values
  2. Anthropic docs § pause_turn
  3. Thorsten Ball, "How to Build an Agent" § The read_file tool, the inference loop
  4. OpenAI guide p. 14, Single-agent systems

Turn limits and other endings the model does not choose

A stop_reason is the model's own signal that it has finished. A turn limit is a different kind of ending: the code around the loop stops it after a fixed number of passes whatever the model wanted, usually to bound cost or to cut off a run that is making no progress. Keeping the two apart matters in logs and in error handling, because "the model finished" and "we stopped it" call for different responses, and a record that does not distinguish them is hard to debug afterwards. Deciding on purpose which endings belong to the model and which belong to the code around it is what keeps an agent from running until the budget is gone.

Read

  1. 12-Factor Agents · Factor 8, Own your control flow
  2. Anthropic, "Building effective agents" § Agents, the stopping-conditions paragraph
  3. Steve Kinney § The loop every framework converges on

Where the idea came from: the ReAct paper

The loop predates the APIs that make it convenient to write. The ReAct paper, published in 2022, prompted a model to produce a thought, then an action, then to read an observation from the environment, and to repeat that sequence. It also defined an explicit finish[answer] action for ending the episode, which is a stop condition expressed as one of the available actions rather than as a field on a response. ReAct is an ancestor of the modern loop rather than the same technique: it recovers that structure by parsing generated text, where an API now returns the structure directly.

Read

  1. ReAct paper § 2, ReAct (p. 3)
  2. ReAct paper § 3.1 Setup (p. 4), the action space

My notes

  • Doing prompt caching can save tokens, but the prefix needs to be the same, if not this triggers cache misses.
  • When a user changes the permissions (e.g. auto mode or manual accept), then the LLM needs to be told too, usually with a message saying the permissions have changed.
  • Anthropic has a post about the different tools that can be used, some of them will be used and controlled/maintained by Anthropic’s servers (e.g. web search), or tools that are in the client by also controlled by Anthropic (e.g. file editing). These tools will be trained-in. User-defined tools will not.
  • When building code for a tool, it’s important to not only give the result back to the LLM, but also mention any other important context for the LLM (e.g. errors, any intermediate results).
  • When the history is just a list of all the messages that were passed to the LLM, then it is deemed to be linear, making it easier to debug. However, some operations might make this history non-linear, such as context compaction.
  • Agents are typically stateless, meaning the servers do not hold any history, the entire history is always passed each time a request is sent.

Build — write the agent

Tiny Agent v0 is the first version of the agent you build across this course: a model, a loop, three tools, and a turn limit, in a few dozen lines. In this lesson it fixes a misspelled greeting — it lists the files in a small repository, reads them to find the greeting, and edits the file to correct it. You write the loop and the tools; the recorder, the fixture files, and the runner are provided.

Your task

Provided for you — don’t edit these

  • agent/harness/trace.py — the recorder your loop calls. It writes the trace, so you never build the JSON by hand.
  • agent/harness/repo.py — the four-file greeting repository the agent works on.
  • agent/v0/__main__.py — the runner that wires everything together and saves the trace.

To do

  • agent/v0/loop.py — the loop. Send the conversation to the model, run any tool it asks for, add the result, and repeat until the model stops or the turn limit is reached. The full recipe is in the file's docstring.
  • agent/v0/tools.py — the three tool bodies: list_files, read_file, and edit_file.

Run it

uv run --env-file .env python -m agent.v0
The solution

After you run your code, the trace is saved to src/content/traces/02-agent-loop.json. The interactive demo below reads that file, so you can step through your own run one message at a time.

step 1/22 · messages: 1
You

The greeting printed by this package is misspelled. Find the file it lives in, fix the spelling, and tell me what you changed.

Measure — the cost of the loop

Question. How does the number of input tokens grow as a task needs more sequential tool calls?

Hypothesis
Every step resends the whole conversation, so the cumulative input tokens grow faster than the number of steps — roughly with its square.
Variants
  • Task A — a task that needs 1 tool call
  • Task B — a task that needs 3
  • Task C — a task that needs 5
  • Task D — a task that needs 10
Held constant
  • the same model and tools
  • the same turn limit
  • the same fixture shape — a chain of tiny files, each naming the next
Metric
cumulative input tokens across the whole run
Your task

To do

  • Write the experiment in experiments/token-growth/: run the agent on the four tasks and record the input tokens for each request.
  • Run it with your key, and commit the numbers to experiments/token-growth/results.json, which the chart below reads.
The solution
cumulative input tokens against the number of tool calls, for four tasks05k10k12345678910tool call numberA (1 call)B (3 calls)C (5 calls)D (10 calls)
Show the numbers
TaskTool callsCumulative input tokens
A1574
B31,948
C53,594
D108,899

Extra reading

  1. I think "agent" may finally have a widely enough agreed upon definition to be useful jargon nowSimon Willison · Simon Willison's Weblog · 18 Sep 2025post
  2. You Should Write An AgentThomas Ptacek · The Fly Blog · 6 Nov 2025post
  3. Nanocode: Build Your Own AI Coding AgentGitHubrepo
  4. Tutorial: Build a tool-using agentClaude Platform Docsdocs