Sub topic 6
The agent loop: call, observe, decide
This chapter assumes you can read basic Python and know what a prompt and a completion are. It also assumes you have seen the tool schema from the previous chapter, where retrieval is described to the model as a function with a name, a description and parameters. Here you wire that tool into a loop.
What the loop does
In classic RAG, your code decides to retrieve exactly once. In agentic RAG, the model decides, and it can decide again after seeing what came back. The mechanism is a loop with three beats:
- Call. Send the conversation so far, plus the tool definitions, to the model.
- Observe. If the model asked for tool calls, run them and append the results to the conversation.
- Decide. Call the model again. It either asks for more tools or writes a final answer.
The model never runs anything itself. It emits a structured request ("call search_docs with this query"). Your code executes that request and reports the result as a new message. Because the full message list is sent every time, the model "remembers" earlier searches only through that list.
The loop in code
The function below is provider-neutral. You supply call_model, which wraps whatever API you use and returns a dict with content and an optional tool_calls list.
import json
MAX_STEPS = 5
def run_agent(question, call_model, tools_by_name, tool_specs):
# call_model(messages, tool_specs) is supplied by you and returns a dict:
# {"content": str, "tool_calls": [{"id": str, "name": str, "arguments": dict}]}
# An empty or missing "tool_calls" means the model has given its final answer.
messages = [
{"role": "system", "content": "Answer from the documentation. Search when you need facts, and cite passage ids."},
{"role": "user", "content": question},
]
for _ in range(MAX_STEPS):
reply = call_model(messages, tool_specs)
tool_calls = reply.get("tool_calls") or []
if not tool_calls:
return reply["content"]
messages.append({
"role": "assistant",
"content": reply.get("content", ""),
"tool_calls": tool_calls,
})
for call in tool_calls:
tool = tools_by_name.get(call["name"])
if tool is None:
result = {"error": f"unknown tool: {call['name']}"}
else:
result = tool(**call["arguments"])
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
})
# Budget spent: force a final answer with no tools offered.
messages.append({
"role": "user",
"content": "Step limit reached. Answer now with what you have found and say what is still missing.",
})
return call_model(messages, [])[“content”]How the pieces fit
- The stop test is the absence of tool calls. The loop has no "done" flag. A reply without
tool_callsis the answer. - The assistant message must be recorded before its results. Most providers reject a
toolmessage that does not follow an assistant message containing the matching call. tool_call_idlinks result to request. If the model makes two calls in one reply, each needs its own result message with the right id.- Results are strings.
json.dumpsturns the tool's return value into text the model can read. MAX_STEPSbounds the loop. Without it, a model that keeps searching never returns.- The fallback call passes
[]for tools. The model can no longer ask for a search, so it has to write text.
Running it without a real model
You can check the control flow with a scripted stand-in. This call_model asks for one search, then answers once a tool result exists.
import json
MAX_STEPS = 5
def run_agent(question, call_model, tools_by_name, tool_specs):
messages = [
{"role": "system", "content": "Answer from the documentation. Search when you need facts, and cite passage ids."},
{"role": "user", "content": question},
]
for _ in range(MAX_STEPS):
reply = call_model(messages, tool_specs)
tool_calls = reply.get("tool_calls") or []
if not tool_calls:
return reply["content"]
messages.append({"role": "assistant", "content": reply.get("content", ""), "tool_calls": tool_calls})
for call in tool_calls:
tool = tools_by_name.get(call["name"])
result = {"error": f"unknown tool: {call['name']}"} if tool is None else tool(**call["arguments"])
messages.append({"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)})
messages.append({"role": "user", "content": "Step limit reached. Answer now."})
return call_model(messages, [])["content"]
def fake_model(messages, tool_specs):
if not any(m["role"] == "tool" for m in messages):
return {"content": "", "tool_calls": [
{"id": "call_1", "name": "search_docs", "arguments": {"query": "export API rate limit"}}
]}
return {"content": "The export API allows 60 requests per minute [doc-12].", "tool_calls": []}
tools = {"search_docs": lambda query, top_k=4: [{"id": "doc-12", "text": "Export API: 60 requests per minute per key."}]}
print(run_agent("What is the export API rate limit?", fake_model, tools, []))Running it prints the answer after exactly two model calls. If you change fake_model so it always requests a search, the loop makes five calls and then takes the forced-answer path.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Provider rejects the request after a tool step | Assistant message with `tool_calls` not appended, or a result lacks its `tool_call_id` | Append the assistant message first, then one tool message per call |
| `TypeError` inside the loop | Model sent arguments your function does not accept | Catch exceptions and return them as an error result (see below) |
| `arguments` is a string, not a dict | Some providers return JSON text | Run `json.loads` in your `call_model` wrapper, not in the loop |
| Same query repeated every step | Tool result was empty or unhelpful and the model has no new idea | Return a clear "no results" message, and tune the tool description to suggest rewording |
| Loop always hits the budget | Model never feels it has enough evidence | Lower the bar in the system prompt, or add grading (a later chapter) |
| Answer ignores the last search | Result was truncated or malformed | Log the exact tool message the model saw |
A minimal wrapper looks like this:
def safe_call(tool, arguments):
try:
return tool(**arguments)
except Exception as exc:
return {"error": f"{type(exc).__name__}: {exc}"}Replace the direct call in the loop with safe_call(tool, call["arguments"]).
Design points worth knowing
One step is one model call, not one tool call. The model can request several searches in a single reply. They share a step, so the budget measures model round trips. Your latency is roughly the number of steps times the model's response time, plus tool time.
The messages list grows every step. Each result is added in full, and the whole list is sent again on the next call. Cost and context use grow with steps. The tool function in this tutorial truncates passages to 1,200 characters for that reason.
Order and determinism. The loop is sequential. Parallel tool calls within one reply can run in any order if the tools are independent, but the results must still be appended with the right ids.
Fail loudly in logs. Record every message the model saw. Debugging an agent means reading the transcript to see which query it chose and what came back.
Exercise
In the loop, the model replies with two tool calls in one step, and your code appends only one tool message before calling the model again. What goes wrong, and how many steps of MAX_STEPS did that reply use?
Show answer
Most providers reject the next request because one tool call has no matching result (tool_call_id), so the model call fails or behaves unpredictably. The reply used one step, because a step is one model call no matter how many tools it requests. The fix is to loop over all tool calls and append one tool message for each.
Exercise
Why does the fallback call at the end of run_agent pass an empty list of tool specs instead of the normal ones?
Show answer
With no tools offered, the model cannot return another tool call and must write a text answer. If tools were still offered, it could ask for another search and the function would return without a real answer.