The agent cycle
“Every agent that works is a loop that someone had the discipline to limit.”
Objective
Build the minimal agent loop in Python, understand each iteration of the model–action–observation cycle, and prove that the core of an agent does not depend on a specific model — by running the complete loop with a scripted model, with no network and no API key.
2.1 The core on one screen
The agent loop is surprisingly small. Its most honest version fits on one screen and has nothing exotic about it: a for, a function call, an append to a list and a return.
Listing 2.1. Minimal agent loop.
def agent_loop(question: str, max_steps: int = 8) -> str:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
]
for _ in range(max_steps):
response = model(messages, tools=TOOLS_SPEC)
messages.append(response)
if not response.tool_calls:
return response.content # the model decided to finish
for call in response.tool_calls:
result = execute(call.name, call.arguments)
messages.append({"role": "tool",
"tool_call_id": call.id,
"content": result})
return "step limit reached"
Read it again. What makes this an agent is not the complexity of the code, but the fact that the decision to continue or stop belongs to the model, not to the for. The for only prevents the model from deciding to continue forever.
2.2 The cycle, step by step
It is worth taking apart what happens in each iteration, because every detail becomes an engineering problem later in the book.
-
Context assembly. The harness takes the message history and sends it to the model along with the list of available tools. This request is where the cost happens: everything in the history is billed again, at every step.
-
Model decision. The model returns one of two things: final text (it is done) or a list of tool calls (it wants to act). Some models return both together — text and calls — and the loop needs to know what to do with that.
-
Execution. For each call, the harness validates the arguments, applies policies, executes and captures the result. Errors must not bring down the loop: they become result text.
-
Observation. The result enters the history as a message with the
toolrole, tied to theidof the call. This is how the model “sees” what happened. -
Repetition. Back to step 1. The history has grown. The cost has grown. The context has grown.
Step 5 is where agents die in practice. A loop that works in three steps can blow past the context window in thirty. Chapter 5 deals with this in detail.
The
toolrole is not decorative. In the tools API, the result of a call must come back with the sameidas the call that originated it. This link is what lets the model know which result corresponds to which request, especially when it asks for three tools in the same step. A result without anid— or with the wrongid— is accepted by some providers and rejected by others, and the error is hard to diagnose because the loop “works” but the model ignores the data.
2.3 Why the loop needs a ceiling
Without max_steps, an agent can fall into a cycle: it calls the tool, does not like the result, calls it again, does not like it, calls it again. This is not a model bug — it is expected behavior from a system that is trying to solve something and cannot find what it is looking for.
The ceiling is what turns a possible hang into a manageable error. The same goes for time and cost. A well-built loop has at least three ceilings: steps, wall-clock time and tokens (or money). The principle is introduced here and detailed in Chapter 4: every loop needs an external limit that does not depend on the model.
2.4 The minimal loop, running
To prove that the core does not depend on an API, the following example uses a scripted “model” — a function that decides based on the history. It is the same loop, with the network call replaced by a deterministic decision.
Listing 2.2. Scripted model: replaces the API with a decision based on the history.
def fake_model(messages):
n_tool_msgs = sum(1 for m in messages if m.role == "tool")
if n_tool_msgs == 0:
return Message(role="assistant",
content="I will check the Python version.",
tool_calls=[{"id": "c1", "name": "run_shell",
"arguments": {"command": "python --version"}}])
if n_tool_msgs == 1:
return Message(role="assistant",
content="Now the current directory.",
tool_calls=[{"id": "c2", "name": "run_shell",
"arguments": {"command": "pwd"}}])
last = [m for m in messages if m.role == "tool"][-1].content
return Message(role="assistant", content=f"Done. Last data point: {last}")
Running this loop with the run_shell tool registered produces the following output:
Listing 2.3. Output of the loop with a scripted model.
=== AGENT LOOP ===
[step 1] assistant: I will check the Python version.
[tool] run_shell({'command': 'python --version'}) -> 'Python 3.14.9'
[step 2] assistant: Now the current directory.
[tool] run_shell({'command': 'pwd'}) -> '/c/Users/gigi/Documents/.../examples'
[step 3] assistant: Done. Last data point observed: /c/Users/gigi/...
=== FINAL ===
Done. Last data point observed: /c/Users/gigi/Documents/.../examples
Three steps, two tools, one result. The final history has seven messages: system, user, and three interleaved assistant/tool pairs, ending with the assistant that answered. (In the example above, two pairs, because the two calls were made in separate steps.)
Note what the agent did in step 3: it did not “know” the directory — it observed it. This distinction between knowing and observing is what separates a chatbot from an agent. The model has no access to your file system; it has access to the tool, and the tool’s result comes back into its context as text.
2.5 What the model actually sees
A common question from beginners: how does the model know the tool exists? The answer is simple and matters for the rest of the book: it does not know. It is told, in every call, by a list of specifications.
Listing 2.4. Tool specification sent to the model (OpenAI-compatible format).
TOOLS_SPEC = [{
"type": "function",
"function": {
"name": "run_shell",
"description": "Runs a shell command and returns its output.",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string",
"description": "command to execute"}
},
"required": ["command"],
},
},
}]
The model never sees the function’s code. It sees the name, the description and the schema — the industry-standard format for function calling (OpenAI 2024). That is why the description matters as much as the implementation — and it is the subject of Chapter 3.
2.6 When the model answers with text and asks for tools
A practical detail that bites early: some models return, in the same turn, a text message and one or more tool calls. What does the loop do with that?
The correct answer is: execute the tools and do not return the text to the user. The text is a narration of the plan, not the final answer. If you return the text to the user at this point, the user receives “I will check the Python version” and nothing else — the final answer never arrives.
Common pitfall
Treating
msg.contentas the final answer whenever it is not empty. The correct stopping condition isif not msg.tool_calls, notif msg.content. A model that narrates before acting produces non-emptycontentat every step, and the loop ends at the first one — before any tool runs.