Sub topic 7
The agent loop: act, observe, repeat
This chapter assumes you can read Python, have called a JSON web API, and know that a language model takes a list of messages and returns text. It also assumes you have seen tool calling, where the model returns a structured request such as "call get_weather with city=Oslo" instead of prose. Here you assemble those pieces into a loop.
What the loop does
A single model call produces one reply. An agent repeats that call until the goal is met. Each pass through the loop has three parts:
- Act. The model looks at the message history and either requests a tool call or gives a final answer.
- Observe. Your code runs the requested tool and appends the result to the history.
- Repeat. The model is called again, now with the result in view.
The model never runs anything. It only produces text that your program interprets. The loop is ordinary code that you own, and that makes it the place to enforce limits.
The tool side
The loop needs a way to turn a tool name into a function call. A dictionary works as a registry. run_tool wraps every call so that a failure becomes text instead of an exception.
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)})Returning errors as text is deliberate. The model can read {"error": "unknown tool: get_wether"} on its next turn and correct itself. If the exception escaped, the whole run would crash and the model would get no chance to recover.
The loop itself
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."The code has these properties:
call_modelis passed in as a parameter. The loop does not care whether it wraps a hosted API or a test double.- The assistant's reply is appended to the history before the tool runs. The next model call must see its own earlier request, or it cannot connect the result to it.
- The only normal exit is a reply with no tool call. Everything else is a limit.
- The
forloop bounds the run. Awhile Truehere would be a bug, because a model that keeps requesting tools would run forever and keep spending money.
Testing without a real model
A scripted model makes the loop deterministic. You can test control flow without network calls or cost.
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 output is It is 18 C in Oslo. The run has two model calls and one tool call. The first call sees a last message with role user, so the fake requests a tool. The second call sees the tool message and answers.
You can test failure paths the same way. A fake that always requests a tool should end with Stopped: step limit reached. after max_steps calls. A fake that requests get_wether should leave a tool message containing an error in the history.
How the history grows
Every iteration adds at least two messages: the assistant's request and the tool's result. A run with 8 steps therefore carries about 16 messages plus the goal. Each model call re-sends the entire list, so input tokens per call grow with each step and total tokens grow faster than linearly. Large tool outputs, such as a whole web page or a 5,000-row query, can fill the context window in a few steps. Trim or summarize tool results before appending them, and handle the history more carefully as runs get longer. The memory chapter covers this in detail.
Stop conditions
A loop needs more than one way to end. The version above has two: the model answers, or the step limit is reached. Production loops usually add others:
| Condition | Why it exists | Typical handling |
|---|---|---|
| Final answer | The goal is met | Return the content |
| Step limit | Guards against endless tool use | Return a clear failure message or raise |
| Token or cost budget | One run should not cost unbounded money | Track usage per call and stop above a threshold |
| Wall-clock timeout | A slow tool can stall the run | Set timeouts on tools and on the whole run |
| Repeated identical call | The model is stuck | Detect the same name and arguments several times in a row |
| Human stop | A person cancels or declines approval | Check a flag each iteration |
Common errors and edge cases
- Several tool calls in one reply. Many model APIs can return multiple tool calls at once. The loop above handles one call per reply. For several, iterate over the list and append one tool message per call.
- Missing call identifiers. Real APIs attach an ID to each tool call, and each tool result must refer to that ID. The simplified messages here use the tool name instead. Follow your provider's message format when you adapt the loop.
- Non-string tool results. The tool message content must be text. If a tool returns a dict, serialize it with
json.dumpsfirst. - Malformed arguments. The model may omit a required argument or add an unknown one.
TOOLS[name](**arguments)then raisesTypeError, andrun_toolreturns that message to the model. This is usually enough for the model to retry correctly. - Retrying forever on the same error. An error message gives the model information, but it may repeat the same mistake. Stuck-call detection and the step limit catch this.
- Side effects on retry. If a tool sends an email and the loop later retries after a timeout, the email may go out twice. Make mutating tools idempotent, or require approval before they run.
Exercise
Modify run_agent so it stops early when the model requests the same tool with the same arguments three times in a row. What should it return, and why is a plain string a weak choice for that return value?
Show answer
Keep a list of recent (name, arguments) pairs, for example (call["name"], json.dumps(call["arguments"], sort_keys=True)). Compare the last three entries after each tool request. If all three are equal, return early with a distinct status such as {"status": "stuck", "answer": None}. A plain string can be mistaken for a real answer by the caller, so a structured result or a specific exception lets callers tell failures from successes.
Exercise
Why does run_agent append the assistant message to messages before running the tool, and what would go wrong if it did not?
Show answer
The next model call must see its own earlier tool request alongside the tool result. Without the assistant message, the history would show a tool result with no request that produced it. The model could not tell what the result answers, and most provider APIs would reject such a history.