Sub topic 8
The Agent Loop, Step by Step
This chapter assumes you can read basic Python and JSON. It also assumes you know that a model call is stateless, that a request is a list of role-tagged messages, and that a tool is a name, a description, and an input schema. Here those pieces are combined into the loop that makes a model behave like an agent.
The loop in one sentence
The harness is the program around the model. It calls the model, executes any tool the model requests, appends the result to the message list, and calls the model again. It repeats this until the model replies without requesting a tool or a limit is reached.
The model never runs anything itself. It produces text, and sometimes structured tool requests. Everything else, including the repetition, belongs to the harness.
One iteration
The diagram shows two model calls with one tool execution between them.
The same steps as a numbered list:
- Build the request. The harness sends the full message list on every call, plus the tool definitions. The model keeps no state between calls.
- Receive the reply. The reply has optional text and zero or more tool calls. Each tool call has an id, a tool name, and an arguments object.
- Record the reply. The harness appends the assistant message to the list, tool calls included. The next request must contain what the model said, or the tool results would have nothing to refer to.
- Check for an exit. If there are no tool calls, the model considers its work finished. The harness returns the text.
- Execute each tool call. The harness looks up the name in a registry and calls the function with the arguments.
- Record each result. The harness appends a tool message that carries the call id, so the model can match results to requests.
- Go back to step 1. The list is now longer, and the model sees everything that has happened.
The context grows with every iteration. Each step adds an assistant message and one tool message per call, and none are removed unless the harness does it deliberately (see the context management chapter).
A minimal implementation
This is the loop from the plan, with the tools it depends on. Provider APIs differ in field names, so call_model is a placeholder for your provider's client. It must return {"text": str, "tool_calls": [{"id": str, "name": str, "arguments": dict}]}.
import subprocess
from pathlib import Path
def read_file(path):
return Path(path).read_text()[:20000]
def run_command(command):
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
return (r.stdout + r.stderr)[-5000:]
TOOLS = {"read_file": read_file, "run_command": run_command}
def run_agent(task, call_model, max_steps=20):
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply["text"],
"tool_calls": reply["tool_calls"]})
if not reply["tool_calls"]:
return reply["text"]
for call in reply["tool_calls"]:
try:
result = TOOLS[call["name"]](**call["arguments"])
except Exception as e:
result = f"error: {e}"
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": str(result)})
return "stopped: step limit reached"Four details in this code matter:
for _ in range(max_steps)is the step limit. Awhile Trueloop would run forever whenever the model keeps requesting tools.- The assistant message is appended before any tool runs. This keeps the order the provider expects: assistant message with tool calls, then the matching tool messages.
except Exceptionturns a failure into a result. The exception text goes back to the model as a normal tool message, so the model can see what went wrong and try something else.str(result)guarantees the content is text, whatever the tool returned.
Running it without a real model
You can watch the loop work by replacing the model with a scripted one. Add this below the code above. The second scripted call asks for a file that does not exist, so you see the error path as well.
Path("notes.txt").write_text("hello from notes")
script = [
{"text": "", "tool_calls": [
{"id": "c1", "name": "read_file", "arguments": {"path": "missing.txt"}}]},
{"text": "", "tool_calls": [
{"id": "c2", "name": "read_file", "arguments": {"path": "notes.txt"}}]},
{"text": "notes.txt says: hello from notes", "tool_calls": []},
]
replies = iter(script)
calls = 0
def fake_model(messages):
global calls
calls += 1
print(f"call {calls}: {len(messages)} messages, last role={messages[-1]['role']}")
if messages[-1]["role"] == "tool":
print(" last tool result:", messages[-1]["content"])
return next(replies)
print(run_agent("What is in notes.txt?", fake_model))The output is:
call 1: 1 messages, last role=user
call 2: 3 messages, last role=tool
last tool result: error: [Errno 2] No such file or directory: 'missing.txt'
call 3: 5 messages, last role=tool
last tool result: hello from notes
notes.txt says: hello from notesEvery call receives the whole history, which is why the count goes 1, 3, 5. A real model would read the error at call 2 and choose its next action from it. Here the script makes that choice for it.
Details that cause bugs
Every tool call needs a result
If a reply contains two tool calls, the next request must contain two tool messages with matching ids. Most provider APIs reject a request with a missing result. This holds even when you refuse to run a tool. In that case, append a result such as "error: this command was denied by the user".
Unknown tools and bad arguments
TOOLS[call["name"]] raises KeyError if the model invents a tool name. Passing the wrong argument names raises TypeError. Both are caught by the same except and reported back. The model usually corrects itself on the next iteration. Validating arguments against the tool's schema before the call gives clearer messages than a raw Python exception.
Multiple calls in one reply
A model can request several independent reads in a single reply. The loop above runs them one after another, which is correct and simple. Running them in parallel is an optimization. Do it only for calls that cannot affect each other, such as reads. Two edits to the same file must stay in order.
Results are text, and they take space
Tool output is stored as text in the message list and is resent on every later call. A 20,000-character file read costs its tokens again on each subsequent iteration. That is why the tools above cut their output to a fixed length.
Text alongside tool calls
A reply can contain both text and tool calls, for example "I'll check the tests first" plus a run_command call. The loop treats the tool calls as the deciding signal. Text with no tool calls is the final answer. Text with tool calls is progress commentary that stays in the history.
Common mistakes
| Mistake | What you see | Fix |
|---|---|---|
| Not appending the assistant message | API error about tool results with no matching call | Append the reply before running tools |
| Letting exceptions escape the loop | The whole run crashes on one bad tool call | Catch exceptions and return them as tool results |
| No step limit | The agent repeats the same failing call indefinitely | Use `for` with `max_steps` |
| Dropping the call id | The provider rejects the tool message, or results get mismatched | Copy `call["id"]` into `tool_call_id` |
| Returning raw large output | The context fills within a few steps | Truncate in the tool or search instead of reading whole files |
What the loop does not decide
The loop is deliberately simple. It has no plan, no memory beyond the message list, and no judgement about whether a tool call is safe. Those come from other parts of the system. The model chooses the next action. The system prompt shapes its habits. Permission checks decide whether a call runs. Stop conditions beyond the step limit, such as detecting repeated identical calls, are added around the same structure.
Exercise
The scripted run printed "call 3: 5 messages". Using the loop's rules, explain exactly which five messages are in the list, and what the count would be at call 4 if the model had made one more tool call at call 3.
Show answer
The five messages are: (1) the user task, (2) the assistant message with the readfile call for missing.txt, (3) the tool message with the error, (4) the assistant message with the readfile call for notes.txt, (5) the tool message with the file contents. If call 3 had returned one tool call, the loop would append an assistant message and a tool message, so call 4 would receive 7 messages.
Exercise
A model reply contains two tool calls, ids "a" and "b". The harness runs "a" successfully, but "b" is a shell command the user refused to approve. What should the harness append, and why not just skip "b"?
Show answer
It should append a tool message for "a" with its output and a tool message for "b" with an error or denial text, such as "error: command denied by user". Every tool call id must have a matching result or the provider will reject the next request. The denial text also tells the model why nothing happened, so it can choose a different approach instead of repeating the call.