Sub topic 7
Putting it together: the tool-calling loop
This chapter assumes you know chat messages and roles, can read a JSON Schema tool definition, and have seen the dispatcher from the previous chapter. Here you connect those pieces into one loop.
Why a loop
A single model call is often not enough. The model may ask for a tool, read the result, and then ask for another tool before it can answer. Your code cannot know in advance how many rounds this takes. So you repeat the same steps until the model replies with no tool calls.
The model never runs anything. It only proposes calls. Your code runs them and sends the results back.
The loop in code
The loop below reuses run_tool_call from the dispatching chapter. call_model stands in for your provider's SDK call. It takes the message list and returns one assistant message.
def run_agent(call_model, messages, max_steps=5):
for _ in range(max_steps):
reply = call_model(messages)
messages.append(reply)
calls = reply.get("tool_calls", [])
if not calls:
return reply["content"]
for call in calls:
outcome = run_tool_call(call)
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"],
})
raise RuntimeError("Tool loop did not finish within max_steps")Follow one turn of the code:
call_modelsends the whole conversation, including earlier tool results.- The reply is appended to
messagesbefore anything else. The next request must contain the assistant's tool calls, or the tool results will have nothing to refer to. - If
tool_callsis empty, the reply is the final answer and the function returns. - Otherwise each call is dispatched, and its result is appended with the matching
tool_call_id.
What the messages look like
For the Oslo weather question, the list grows like this:
[
{"role": "user", "content": "What is the weather in Oslo?"},
{"role": "assistant", "tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}}
]},
{"role": "tool", "tool_call_id": "call_1", "content": "{\"temperature\": 7, \"unit\": \"celsius\"}"},
{"role": "assistant", "content": "It is 7 degrees Celsius in Oslo."}
]The loop made two model calls. The first produced the tool call. The second saw the result and wrote the answer.
Common errors
- Dropping the assistant message. If you append only the tool result, most providers reject the request because the result has no matching call.
- Mismatched ids. Each result must carry the
idof the call it answers. Reusing one id for several results confuses the model. - No step limit. A model that keeps requesting tools will loop forever and run up cost. Always cap the steps.
- Skipping results for failed calls. Every call needs a result message, even an error. The dispatcher already turns failures into text, so append its output regardless.
- Reading
contenton a tool-call reply. Some providers return empty or missing content when tool calls are present. Check for calls first, as the code does.
Exercise
In run_agent, why is messages.append(reply) placed before the loop over calls, and what usually happens if you leave it out?
Show answer
The next request must include the assistant message that contains the tool calls, so each tool result can be matched to a call by tool_call_id. Without it, most providers reject the request with an error about a tool result that has no corresponding call, or the model loses track of what it asked for.