Sub topic 7
Putting it together: the tool-calling loop
This chapter assembles the pieces from earlier chapters into one working loop. It assumes you can read Python and JSON, know that chat APIs take a list of role-tagged messages, and have seen a tool definition, a model-issued tool call, a dispatcher, and a tool result message. The code uses a fake model, so you can run it without an API key.
Why a loop is needed
A single request to a model is not enough for tool use. The model cannot run your function. It can only reply with a proposed call. Your code has to run the call, append the result to the conversation, and ask the model again. The model may then answer, or it may propose another call. Because you can't know in advance how many rounds it will take, you write a loop.
The loop has three rules:
- Send the full message list to the model on every round.
- If the reply has no tool calls, it is the final answer. Stop.
- If the reply has tool calls, run each one, append one result per call, and go around again.
The code, piece by piece
The dispatcher runs one call and never raises. It turns unknown tools, bad arguments, and exceptions into error text, so the loop doesn't crash on a bad model proposal.
import json
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS.get(call["name"])
if fn is None:
return {"is_error": True, "content": "Unknown tool: " + str(call["name"])}
try:
result = fn(**call["arguments"])
except TypeError as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}The loop itself is short:
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")Four details in this function matter.
- The assistant reply is appended before the results. The model needs to see its own tool call in the history. Most providers reject a tool result that has no matching call before it.
- Each result carries the call's id. The
tool_call_idlinks a result to the call that produced it. This matters most when one reply holds several calls. - The stop test is the absence of tool calls. Providers also expose a stop signal, such as
finish_reasonorstop_reason. Checking for the calls themselves is the more reliable test, because it matches what your code needs to act on. - The loop is bounded.
max_stepsguarantees it ends, even if the model keeps asking for tools.
Running it end to end
Here is a fake model that behaves like a real one for this question. It proposes a call when the last message is from the user, and it answers once it sees a tool result.
def fake_model(messages):
last = messages[-1]
if last["role"] == "user":
return {
"role": "assistant",
"tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}}
],
}
data = json.loads(last["content"])
text = "It is %d degrees Celsius in %s." % (data["temperature"], data["city"])
return {"role": "assistant", "content": text}
messages = [{"role": "user", "content": "What is the weather in Oslo?"}]
print(run_agent(fake_model, messages))
print(len(messages))Run this together with the two code blocks above. It prints It is 7 degrees Celsius in Oslo. and then 4. The four messages are the user question, the assistant's tool call, the tool result, and the final answer. This matches the exchange shape from the earlier chapter on sending results back.
What the message list looks like after each round
The list only grows. Nothing is edited or removed.
| After round | Messages in the list |
|---|---|
| Start | user |
| 1 (model proposes a call) | user, assistant (tool_calls) |
| 1 (your code runs it) | user, assistant (tool_calls), tool |
| 2 (model answers) | user, assistant (tool_calls), tool, assistant (text) |
Each round resends the whole list, so input tokens grow with every round. A long loop costs more than the sum of its rounds suggests. The chapter on step limits and cost covers this.
Edge cases to handle
Several calls in one reply
The for call in calls loop already handles this. Append exactly one result per call, each with its own id. If you skip one, many providers return an error on the next request. Calls in one reply are usually independent, so you can run them concurrently. Keep the results in a stable order and tie each to its id.
Text alongside tool calls
Some models return explanatory text and tool calls in the same reply. The loop above ignores the text when calls are present, but it still appends the whole reply, so the text stays in the history. Don't show that text to the user as the final answer. Only the reply with no calls ends the loop.
A model that never stops
A model can keep proposing the same call, for example when a tool keeps returning an error it doesn't understand. This fake model shows what the step limit does:
def stubborn_model(messages):
return {
"role": "assistant",
"tool_calls": [
{"id": "call_%d" % len(messages), "name": "get_weather", "arguments": {"city": "Oslo"}}
],
}
try:
run_agent(stubborn_model, [{"role": "user", "content": "Weather?"}], max_steps=3)
except RuntimeError as exc:
print(exc)After three rounds it prints Tool loop did not finish within max_steps. In production, decide what the caller sees at this point. Options are an error, a partial answer, or one last request with tools disabled so the model must reply in text. Log the message list so you can see what the model was stuck on.
Provider differences
The loop shape is the same everywhere, but the message format is not. Some APIs put the result in a message with role tool. Others, such as Anthropic's Messages API, put a tool_result block inside a user message, and the assistant's call appears as a tool_use block in its content. Keep provider-specific parsing in a small adapter so the loop logic stays the same.
Mutating the caller's list
run_agent appends to the list it receives. That is convenient when you want the full transcript afterward, as in the len(messages) check above. It is surprising if the caller reuses the list. Pass a copy if you need the original left alone.
Common mistakes
- Returning the first reply as the answer. The first reply is often a tool call with no useful text. Check for calls before treating a reply as final.
- Reusing one id for every result. Results must match the id of their own call.
- Letting exceptions escape the dispatcher. An uncaught error ends the loop. A returned error message lets the model try again.
- No step limit. A
while Trueloop can run up cost and latency without bound. - Hiding errors from the model. Return error text as the tool result instead of dropping the call. The next chapters cover how to phrase it.
Exercise
A model reply contains two tool calls, with ids "a" and "b". Your loop runs both and appends one tool message for "a" only, because the call for "b" raised an exception that your dispatcher did not catch and your code skipped it. What is likely to happen on the next request, and how do you fix it?
Show answer
Many providers reject the next request, because the assistant message has a tool call with no matching result. Fix it by making the dispatcher catch all exceptions and return an error result, so every call gets a tool message with its own id. The model can then read the error and decide what to do.
Exercise
Modify runagent so that when maxsteps is reached, it makes one more call to the model with tools disabled and returns that text instead of raising. What do you need from your provider to do this?
Show answer
You need a way to turn tools off for a request, such as a tool-choice setting of "none", or simply calling the model without sending tool definitions. Make this extra call after the for loop ends, passing the same messages, and return its content. Note that the history still contains tool calls, so some providers require the tool definitions to be present even when tool use is disabled. Check your provider's rules.