Sub topic 8
The agent loop, step by step
This chapter assumes you know basic Python, JSON, and how tool definitions and tool calls work (the two chapters before this one). Here you will see how those pieces fit into one repeating cycle.
The loop in one sentence
A coding agent is a model called in a loop. The harness, which is the program around the model, sends the conversation, reads the reply, runs any requested tools, appends the results, and calls the model again. Each model call is stateless, so the harness resends the whole message list every time.
A minimal implementation
The code below needs a TOOLS registry, which maps tool names to Python functions. It also needs call_model, a placeholder for your provider's API.
def run_agent(task, call_model, max_steps=20):
# call_model(messages) is a placeholder for your provider's API. It returns
# {"text": str, "tool_calls": [{"id": str, "name": str, "arguments": dict}]}.
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"Walking through one iteration
Suppose the task is "Fix the failing test in utils.py".
- Send. The harness sends
messages, which holds one user message. The tool definitions travel with it. - Reply. The model returns no final answer yet. It returns a tool call:
read_filewith{"path": "utils.py"}. - Record. The harness appends the assistant message, including the tool call, to
messages. Skipping this step breaks the conversation, because the next call would contain a tool result with no matching request. - Execute. The harness looks up
read_fileinTOOLSand runs it with the arguments. - Feed back. The harness appends a
toolmessage. Itstool_call_idmatches the call'sid, so the model can pair each result with its request. - Repeat. The model now sees the file contents and may call
run_commandwithpytest, then an edit tool, thenpytestagain.
The loop ends when a reply has no tool calls. That reply is the final answer.
Details that matter
- The model never runs anything. It only emits text that names a tool and arguments. The harness decides whether to execute it.
- Messages only grow. Every iteration adds at least two messages, so the context window fills up as the work continues.
- Errors are results. The
try/exceptturns an exception into a string the model reads. The model can then correct a wrong path or a bad argument instead of the program crashing. - Several calls can arrive in one reply. The inner
forloop handles each one and appends one result per call.
Common mistakes
| Mistake | Symptom |
|---|---|
| Not appending the assistant message before the tool results | The provider rejects the request, or the model repeats its last call |
| Mismatched `tool_call_id` | The API returns a validation error |
| No step limit | A confused agent loops and spends money without finishing |
| Returning huge tool output | The context window fills after a few steps |
Exercise
In the loop above, what are the two ways the loop can end, and which one signals success?
Show answer
The loop ends when a model reply contains no tool calls, which returns the model's final answer and is the normal, successful exit. It also ends when max_steps iterations pass, which returns "stopped: step limit reached" and means the agent did not finish in time.
Exercise
Why must the harness append the assistant message, with its tool calls, before appending the tool result messages?
Show answer
The model call is stateless, so the next request must contain the full history. A tool result needs the assistant message that requested it, and its tool_call_id refers to a call id in that message. Without it, the history is inconsistent and the provider may reject it.