Sub topic 6
The agent loop: call, observe, decide
This chapter assumes you know basic Python, what a prompt and a completion are, and how a classic retrieve-then-generate pipeline works. It also assumes you have seen the search_docs tool from the previous chapter. Here you will build the loop that lets a model use that tool.
From one pass to a loop
In classic RAG, your code calls retrieval once and then calls the model once. In agentic RAG, the model sits inside a loop. Each turn it 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 three words in the title map to the loop like this:
- Call: the model emits one or more tool calls, each with an id, a name, and arguments.
- Observe: your code runs the tools and appends the results as
toolmessages. - Decide: on the next model call, the model reads those results and either searches again or answers.
The code
The function below is provider-neutral. You supply call_model, which wraps whichever API you use.
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\"]Details that matter
- Append the assistant message before the tool results. Most APIs require each tool result to match a
tool_call_idfrom the assistant message just before it. If you skip the assistant message, the next call usually fails. - Return errors as results. An unknown tool name becomes
{"error": ...}instead of an exception. The model can then correct itself on the next turn. - The loop ends in two ways. A reply with no tool calls is the normal exit.
MAX_STEPSis the safety exit. Without it, a model that keeps searching will loop and spend money indefinitely. - The final call passes no tools. Offering an empty tool list forces the model to write text. The extra user message tells it to report gaps instead of guessing.
Common errors
| Symptom | Likely cause |
|---|---|
| API rejects the second call | Tool result has no matching assistant message, or `tool_call_id` is wrong |
| Model repeats the same search | Tool results were not appended, or the query description is too vague |
| Loop always hits the limit | The system prompt never tells the model when it may stop |
| Answer ignores the results | Tool output is too long or not valid JSON text |
Exercise
In run_agent, why does the code append the assistant message with its tool_calls before appending the tool messages, and what exits the loop if the model never stops calling tools?
Show answer
The API links each tool message to a tool_call_id in the preceding assistant message, so the assistant message must be in the history first or the next call is invalid. If the model keeps requesting tools, the for loop ends after MAX_STEPS iterations. The code then adds a user message and calls the model with an empty tool list to force a final text answer.