Sub topic 6
The agent loop: plan, act, observe, stop
This chapter assumes you have read the earlier chapters on tool use and structured outputs. You should be able to read Python and JSON, and know that a model can request a tool call that your code then runs. Here you will see how those pieces form a loop, how the loop ends, and what goes wrong when it doesn't.
The loop in one sentence
An agent is a for loop around a model call. Each pass, the model looks at everything so far and chooses one of two things: ask for a tool, or give a final answer. If it asks for a tool, your code runs it and appends the result to the conversation. Then the loop repeats.
The four words in the title map to that cycle:
- Plan: the model decides what to do next, given the task and the history.
- Act: the model emits a tool request, and your code executes it.
- Observe: the tool result goes back into the conversation as a new message.
- Stop: the model returns a final answer, or the loop hits a limit you set.
The model does not run anything itself. It only produces text that your code parses. This matters for safety: every action passes through your code, so that is where you enforce limits.
Why the history is the memory
The model keeps no state between calls. Whatever it "knows" about earlier steps comes from the message list you send each time. In a reporting task, a run might look like this:
- The task: "Summarize last month's paid search performance."
- The model requests
fetch_campaign_rowsfor last month. - The result (a list of rows) is appended.
- The model requests
campaign_metricswith those rows. - The computed CTR, CPC and CPA are appended.
- The model writes the summary, citing only those numbers.
Each step depends on the previous observation. The model could not request step 4 without seeing step 3's output. That dependency is the reason to use a loop instead of a single prompt.
A minimal loop
This is the loop from the topic plan. It is provider-neutral: call_model is any function that returns either {"tool": name, "args": {...}} or {"final": text}.
import json
def run_agent(task, call_model, tools, max_steps=5):
"""Minimal agent loop. call_model(messages) must return either
{"tool": name, "args": {...}} or {"final": text}."""
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = call_model(messages)
if "final" in reply:
return reply["final"]
name = reply["tool"]
if name in tools:
result = tools[name](**reply["args"])
else:
result = {"error": "unknown tool: " + name}
messages.append({"role": "assistant", "content": json.dumps(reply)})
messages.append({"role": "user", "content": json.dumps({"tool_result": result})})
raise RuntimeError("step limit reached without a final answer")Note three design choices. The for loop has a fixed upper bound, so the loop cannot run forever. An unknown tool name becomes an observation rather than a crash, which lets the model correct itself. And exceeding the limit raises an error instead of returning something that looks like an answer.
Stop conditions
A loop needs more than one way to end. Use these together.
| Condition | What triggers it | What to return |
|---|---|---|
| Final answer | The model replies with `final` | The answer, plus the step count |
| Step limit | The counter reaches `max_steps` | A failure status, not a partial answer |
| Repeated call | Same tool and same arguments seen before | An error observation, then the limit if it persists |
| Budget | Tokens, cost or wall-clock time exceeded | A failure status with usage so far |
| Fatal error | Credentials fail, data source down | Stop at once and report |
Choose max_steps from the task. A report that needs two data pulls and one calculation should finish in about four steps, so a limit of 8 to 10 leaves room for one retry without allowing a runaway. If an agent regularly needs the limit, the task is probably too broad and should be split.
Making the loop safer
The minimal version has gaps. A tool that raises an exception ends the whole run. A model that repeats the same failing call burns every remaining step. Callers cannot tell a successful run from a failed one without catching exceptions. The next version fixes these and returns a status dictionary.
import json
def run_agent(task, call_model, tools, max_steps=5):
"""Agent loop that returns a status dict instead of raising."""
messages = [{"role": "user", "content": task}]
seen = set()
for step in range(1, max_steps + 1):
reply = call_model(messages)
if "final" in reply:
return {"status": "done", "answer": reply["final"], "steps": step}
name = reply.get("tool")
args = reply.get("args", {})
key = (name, json.dumps(args, sort_keys=True))
if key in seen:
result = {"error": "repeated call; use a different tool or answer"}
elif name not in tools:
result = {"error": "unknown tool: " + str(name)}
else:
seen.add(key)
try:
result = tools[name](**args)
except Exception as exc:
result = {"error": str(exc)}
messages.append({"role": "assistant", "content": json.dumps(reply)})
messages.append({"role": "user", "content": json.dumps({"tool_result": result})})
return {"status": "step_limit", "answer": None, "steps": max_steps}
def cpa(spend, conversions):
return {"cpa": round(spend / conversions, 2) if conversions else None}
def scripted_model(replies):
it = iter(replies)
return lambda messages: next(it)
tools = {"cpa": cpa}
good = scripted_model([
{"tool": "cpa", "args": {"spend": 150.0, "conversions": 10}},
{"final": "CPA was 15.0."},
])
print(run_agent("Report CPA", good, tools))
stuck = lambda messages: {"tool": "cpa", "args": {"spend": 1, "conversions": 1}}
print(run_agent("Report CPA", stuck, tools, max_steps=3))The script prints {'status': 'done', 'answer': 'CPA was 15.0.', 'steps': 2} and then {'status': 'step_limit', 'answer': None, 'steps': 3}. The scripted model stands in for a real one so you can test loop behavior without any API call. Testing the loop this way is worth doing: the stop logic is ordinary code and should have ordinary tests.
Common failure modes
- Runaway loops. The model keeps calling tools because no result satisfies it. The step limit and repeated-call check catch this.
- Premature answers. The model answers from memory without calling a tool. In a reporting agent, this is how invented numbers appear. Require that a final answer cites tool results, and check it in the verification step covered in a later chapter.
- Context growth. Every step appends messages, so a long run sends more tokens each time and costs more per step. A tool that returns 5,000 rows can crowd out the task. Make tools return summaries or aggregates, not raw dumps.
- Malformed replies. The model returns text that is not valid JSON, or omits
args. Parse defensively, and treat a parse failure as an observation ("reply was not valid JSON") rather than a crash. Allow only a small number of such retries. - Side effects on retry. A tool that sends an email or writes to a spreadsheet may run twice if the model repeats itself. Keep action tools separate from read tools, and gate them behind human approval.
Deciding whether a task needs a loop
A loop adds cost, latency and ways to fail. Use one when the next action depends on the last result. If the steps are always the same, such as pull yesterday's data, compute metrics, fill a template, write plain code to run them in order and call the model once, for the narrative. Reach for an agent loop when the path varies, for example when a CPA spike should lead the agent to break results down by campaign, and the right breakdown is unknown in advance.
Logging each pass
Record every step: the model reply, the tool name and arguments, the result size, and the elapsed time. Without that log you cannot explain why a report contains a given number, and you cannot debug a run that stopped early. Later chapters build on these logs for cost control and quality evaluation.
Exercise
In the safer loop, the model requests cpa with the same arguments three times in a row and max_steps is 5. Describe what the model sees after each request and how the run ends if it never changes behavior.
Show answer
The first request runs the tool and the model sees the real result. The second and third requests match a key already in seen, so the tool is not run and the model sees the error "repeated call; use a different tool or answer". If the model keeps repeating the call, the loop uses up the remaining steps and returns {"status": "step_limit", "answer": None, "steps": 5}. The caller sees a failure status, not an answer.
Exercise
A tool returns 8,000 rows of raw ad data, and the agent's later steps slow down and become less accurate. What is the likely cause, and what change would you make to the tool?
Show answer
The rows are appended to the history, so every later model call carries them. This raises cost and can push the task out of the model's useful context. Change the tool to return an aggregate, such as the output of campaign_metrics, or a limited set of top rows, so the history stays small.