Sub topic 14
Agents: loops of reasoning and action
This chapter assumes you have read the chapter on tool use. You should know that the model proposes a tool call as structured data and that your code runs it. You should also be comfortable with Python and JSON.
What an agent is
An agent is a program that calls a model in a loop. On each turn the model either asks for a tool call or gives a final answer. Your code runs the tool, appends the result to the conversation, and calls the model again. The loop ends when the model answers or a limit is reached.
A single tool call is one step. An agent chains many steps, and the model chooses the next step based on earlier results.
A minimal loop
The code below uses a scripted fake_model in place of a real API, so it runs as shown. In a real program you would replace it with your provider's call.
import json
def get_weather(city):
return {"city": city, "temp_c": 18}
TOOLS = {"get_weather": get_weather}
MAX_STEPS = 5
def fake_model(messages):
# Stands in for a real model: asks for a tool once, then answers.
if not any(m["role"] == "tool" for m in messages):
return {"type": "tool_call", "name": "get_weather",
"arguments": {"city": "Oslo"}}
result = json.loads(messages[-1]["content"])
return {"type": "answer",
"text": f"It is {result['temp_c']} C in {result['city']}."}
def run_agent(goal, model):
messages = [{"role": "user", "content": goal}]
for _ in range(MAX_STEPS):
reply = model(messages)
if reply["type"] == "answer":
return reply["text"]
fn = TOOLS.get(reply["name"])
if fn is None:
output = json.dumps({"error": "unknown tool"})
else:
try:
output = json.dumps(fn(**reply["arguments"]))
except Exception as exc:
output = json.dumps({"error": str(exc)})
messages.append({"role": "tool", "content": output})
return "Stopped: step limit reached."
print(run_agent("What is the weather in Oslo?", fake_model))Four details matter here:
- The tool lookup uses an allow-list, so the model cannot run arbitrary code.
- Errors go back to the model as text, which lets it retry or change course.
MAX_STEPSprevents endless loops and runaway cost.- The full message history is resent each turn, so context grows with every step.
Common errors
| Problem | Cause | Mitigation |
|---|---|---|
| Endless loop | The model repeats the same failing call | Step limit, and detect repeated identical calls |
| Wrong tool or arguments | Vague tool descriptions | Clear names, typed parameters, validation |
| Compounding mistakes | An early error feeds later steps | Check intermediate results, keep steps few |
| High cost and latency | Each step is a full model call | Use fewer steps and shorter results |
| Harmful actions | The tool can change real data | Read-only tools first, human approval for writes |
When to use an agent
Use a fixed workflow when you know the steps in advance, such as extract, then validate, then store. It is cheaper, faster, and easier to test. Use an agent when the steps depend on what the model finds along the way, such as researching a question across several sources. Start with the simplest design that works.
Exercise
In the loop above, why are tool errors returned to the model as text instead of crashing the program, and what protects you if the model keeps causing errors?
Show answer
Returning the error lets the model see what went wrong and try a different call or explain the failure. The MAX_STEPS limit protects you, because it ends the loop even if the model keeps repeating failing calls.