Sub topic 6
The agent loop: plan, act, observe, stop
This chapter assumes you can read basic Python, know what a large language model (LLM) is, and are comfortable with JSON. You should also know the metrics from the earlier chapters, such as clicks, spend and conversions.
The working model
An agent is a loop around a model. The model does not run tools itself. Your code asks the model what to do next, runs the tool it picks, and shows the model the result. This repeats until the model gives a final answer or your code stops it.
Each pass has four parts:
- Plan: the model reads the task and the history so far, then decides the next step.
- Act: your code runs the chosen tool, such as a function that computes campaign metrics.
- Observe: the tool result is added to the conversation so the model can see it.
- Stop: the loop ends on a final answer or when a safety limit is reached.
A minimal loop
The function below is independent of any provider. call_model is any function that takes the message list and 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")Three details matter here.
- The
toolsdictionary is an allowlist. The model can only run functions you registered. - An unknown tool name returns an error result instead of crashing. The model sees the error and can correct itself on the next pass.
- Both the model's request and the tool result are appended to
messages. Without that, the model has no memory of what it already tried.
Stop conditions
A loop without a stop condition can run forever and spend money on every pass. Use more than one condition.
| Condition | What it catches |
|---|---|
| Final answer | The normal, successful exit |
| Step limit (`max_steps`) | A model that keeps calling tools without finishing |
| Budget limit | Token or cost totals above a set amount |
| Repeated call check | The same tool with the same arguments called twice in a row |
The code above implements the first two. Raising an error at the limit is deliberate. Returning a partial answer as if it were complete would put an unfinished report in front of readers.
Common errors
- Letting the model do arithmetic. Give it a deterministic tool for metrics and have it call that tool. A tool can return
Nonefor a zero denominator, and the model can then say "no conversions yet" instead of inventing a cost per acquisition. - Swallowing tool failures. Return the error in the tool result so the model can react, and log it for you.
- Setting
max_stepstoo high. Most reporting tasks need three to six steps. A high limit hides loops that are stuck. - Returning huge tool results. Large raw tables fill the context window. Return summaries or totals.
Exercise
In run_agent, the model asks for a tool named get_budget, but only campaign_metrics is registered. What happens, and why is this better than raising a KeyError?
Show answer
The loop puts {"error": "unknown tool: get_budget"} into the history as the tool result and continues. The model sees the error on the next step and can choose a valid tool or give a final answer. A KeyError would end the whole run on a single mistaken request.
Exercise
Name two stop conditions besides the final answer, and say what each protects against.
Show answer
A step limit protects against a model that keeps calling tools without finishing. A budget limit protects against runaway token or cost use. A repeated-call check also works, since it catches a model stuck repeating the same request.