Sub topic 2
Tool calling in brief
This chapter assumes you can read Python and JSON, and that you know how a chat model takes a list of messages and returns a reply. It reviews tool calling, because both handoffs and orchestrators are built on it.
The working model
A language model only produces text. Tool calling lets that text describe an action. You give the model a list of tools, each with a name, a description, and a schema for its arguments. When the model wants to use one, it returns a structured request instead of a final answer, for example {"name": "get_order_status", "args": {"order_id": "1042"}}.
The model never runs anything. Your code does. The cycle is:
- Send the messages and the tool list to the model.
- If the reply is a tool request, look up the function, validate the arguments, and run it.
- Append the result to the messages as a tool message.
- Call the model again. Repeat until it returns a final answer.
This cycle is the agent loop from the previous chapter.
A runnable example
This version replaces the model with a stub, so it runs without an API key. The loop and the dispatch table are the same as in a real system.
def get_order_status(order_id: str) -> str:
orders = {"1042": "delivered", "1043": "shipped"}
return orders.get(order_id, "not found")
TOOLS = {"get_order_status": get_order_status}
def fake_model(messages):
if messages[-1]["role"] == "tool":
return {"type": "final", "text": f"Order 1042 is {messages[-1]['content']}."}
return {"type": "tool", "name": "get_order_status", "args": {"order_id": "1042"}}
def run_once(messages, max_turns=5):
for _ in range(max_turns):
reply = fake_model(messages)
if reply["type"] == "final":
return reply["text"]
try:
result = TOOLS[reply["name"]](**reply["args"])
except (KeyError, TypeError) as exc:
result = f"error: {exc!r}"
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")
print(run_once([{"role": "user", "content": "Where is order 1042?"}]))The output is Order 1042 is delivered.
Common errors
- Unknown tool name. Models sometimes invent a tool. A dictionary lookup fails with
KeyError. Catch it and send the error back as the tool result so the model can correct itself. - Bad arguments. A missing or misspelled argument raises
TypeError. Treat it the same way. Validate types before running anything with side effects. - Vague descriptions. The model chooses tools from their descriptions. Two tools with overlapping descriptions get confused, and a precise description usually fixes it.
- Raising instead of returning. An uncaught exception ends the run. A returned error message keeps the loop alive.
- No turn limit. Without
max_turns, a model that keeps calling tools never stops.
Why this matters for multi-agent systems
A tool result is just text added to the history. A handoff is a tool call whose "result" is that the loop switches to another agent. An agent used as a tool is a tool function that runs a whole inner loop. The next chapters build on this one mechanism.
Exercise
In the loop above, why is a failed tool call returned as a tool message instead of raised as an exception, and what stops the loop if the model keeps failing?
Show answer
Returning the error as a tool message lets the model read it and retry with corrected arguments, so one bad call does not end the run. If the model keeps failing, max_turns stops the loop and raises RuntimeError.