Sub topic 7
The agent loop: act, observe, repeat
This chapter assumes you can write Python, read JSON, and know that a model can request a tool call instead of replying with text. Tool calling and tool design come from earlier chapters. Here you will put them into a loop.
The loop in one picture
An agent is a loop around a model. Each pass, the model reads the history and picks a next step. If it asks for a tool, your code runs the tool and adds the result to the history. Then the model goes again. If it answers in plain text, the loop ends.
Step 1: run tools safely
The loop needs a function that turns a tool request into a result. This one uses a registry, which is a dictionary from tool names to Python functions. Errors come back as text, so the model can read them and recover instead of the program crashing.
import json
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})Step 2: write the loop
The loop keeps a messages list. Every model reply and every tool result is appended, so the next call sees everything that happened.
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."Two exits matter here. The model ends the loop by answering without a tool call. Your code ends it with max_steps, which protects you from a model that keeps calling tools forever.
Step 3: test with a scripted model
A real model is slow, costs money, and varies between runs. A scripted model lets you test the loop deterministically. Add this to the code above.
def fake_model(messages):
# Scripted stand-in for a real model, useful for testing the loop.
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
print(run_agent(fake_model, "What is the weather in Oslo?"))The run has two passes. The first sees a user message and requests get_weather. The second sees the tool result and answers. The output is It is 18 C in Oslo.
Common errors
- No step limit. A confused model can loop until your budget is gone. Always set
max_steps. - Dropping the tool result. If you skip the append, the model never sees what happened and repeats the same call.
- Raising exceptions from tools. A crash ends the run. Returning the error as text gives the model a chance to fix its arguments.
- Treating the step limit as success. Return a clear stop message, as above, so callers can tell a finished run from a cut-off one.
Exercise
In run_agent, what two conditions end the loop, and what does each one return?
Show answer
The loop ends when the model replies without a tool call, which returns the model's content as the final answer. It also ends when max_steps passes are used up, which returns "Stopped: step limit reached."
Exercise
Why does run_tool return a JSON error string for an unknown tool instead of raising an exception?
Show answer
The error text is appended to the history, so the model can read it and try a different tool or fix its arguments. An exception would crash the program and end the run.