Sub topic 2
Tool Calling in Brief
This chapter assumes you can read Python and JSON, and that you know what a chat message list is. You don't need to have used a tool-calling API before. Tool calling is the mechanism that both handoffs and agents-as-tools build on, so the later chapters rely on the model described here.
What tool calling is
A large language model (LLM) produces text. It cannot run code, query a database, or send an email. Tool calling is a protocol that lets the model ask your program to do those things on its behalf.
You describe a set of functions to the model. During a turn, the model can reply with a request to call one of them, with arguments. Your program runs the function and appends the result to the conversation. The model then reads that result and continues.
Two points matter for everything that follows:
- The model never executes anything. It only emits a structured request. Your code decides whether and how to run it.
- The result goes back into the message history. The model "knows" what a tool returned only because that text is in the messages it reads on the next call.
The anatomy of a tool
A tool has three parts that the model sees and one part it does not.
| Part | Seen by model | Purpose |
|---|---|---|
| Name | Yes | A short identifier the model uses to request the call |
| Description | Yes | Plain-language guidance on when to use the tool |
| Parameter schema | Yes | A JSON Schema describing the arguments |
| Implementation | No | The function your program runs |
The schema is how the model learns the argument names and types. Here is a tool definition in the JSON Schema style that most providers use. Field names differ slightly between providers, but the shape is the same.
get_order_status_tool = {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "integer", "description": "The order number"},
},
"required": ["order_id"],
},
}The description is part of your prompt. A vague description such as "gets order info" leads to wrong or missing calls. A good one says what the tool does and when to use it.
The tool-calling loop
One tool call takes at least two model calls: one to request the tool, and one to use its result.
In code, this is a loop. The loop keeps going while the model asks for tools, and stops when the model produces a final answer.
import json
def get_order_status(order_id: int) -> str:
# Stand-in for a real database lookup.
return json.dumps({"order_id": order_id, "status": "shipped"})
TOOLS = {"get_order_status": get_order_status}
def fake_model(messages):
"""A scripted stand-in for a real model, so this example runs offline."""
last = messages[-1]
if last["role"] == "user":
return {"type": "tool", "name": "get_order_status", "args": {"order_id": 1042}}
return {"type": "final", "text": f"Here is what I found: {last['content']}"}
def run_loop(messages, call_model, max_turns=5):
for _ in range(max_turns):
reply = call_model(messages)
if reply["type"] == "final":
return reply["text"]
result = TOOLS[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": result})
raise RuntimeError("max_turns exceeded")
messages = [{"role": "user", "content": "Where is order 1042?"}]
print(run_loop(messages, fake_model))Running it prints the final text built from the tool result:
Here is what I found: {"order_id": 1042, "status": "shipped"}The simplified reply format (final or tool) is the same one used in the Topic Spine's agent loop. Real provider APIs wrap the same information differently. They usually attach a call ID to each request, and you must return the result with that ID so the model can match them up. The loop shape does not change.
Why this matters for multi-agent systems
An agent, in the sense used in this tutorial, is a model plus instructions plus tools, run in this loop. Once you have that, two multi-agent ideas follow almost for free:
- Agent as tool. A tool's implementation can itself run another agent's loop and return its final text. To the calling model, it looks like any other function.
- Handoff. A tool call can be interpreted by your program as "switch the active agent" instead of "run a function". The model still emits an ordinary tool call, such as
transfer_to_billing. Your loop sees the name and swaps the agent.
Both reuse the machinery in this chapter. Later chapters build them in detail.
Common errors
Most tool-calling bugs fall into a few groups.
Bad arguments
The model produces arguments, and arguments are model output. It may omit a required field, use the wrong type, or invent a value. Treat them as untrusted input:
- Validate arguments against the schema before running the function.
- Return a clear error string when validation fails. The model can read it and retry.
- Never pass arguments straight into a shell command or SQL string.
def safe_call(tools, name, args):
if name not in tools:
return f"Error: unknown tool '{name}'. Available: {sorted(tools)}"
try:
return str(tools[name](**args))
except TypeError as exc:
return f"Error: bad arguments for '{name}': {exc}"
except Exception as exc:
return f"Error: tool '{name}' failed: {exc}"Returning errors as tool results, instead of raising, keeps the loop alive and gives the model a chance to correct itself. Unknown tool names and wrong argument names are the most common causes of TypeError here.
Missing or malformed results
Tool results must be text (or a structured block your provider accepts). If you return a Python object, convert it first. If the result is huge, such as a whole file, it fills the context window and crowds out the rest of the conversation. Truncate or summarize large results, and say that you did so in the text.
Weak descriptions and too many tools
Models choose tools by reading descriptions. Two tools with overlapping descriptions cause inconsistent choices. A long list of tools raises the chance of a wrong pick. This is one of the practical reasons to split work across agents, which the next chapter covers.
Forgetting the loop guard
A model can keep requesting tools forever, for instance by retrying a failing call with the same arguments. Without max_turns, the loop never ends and you keep paying for model calls. Always cap the number of turns.
Dropping the result
If you run the tool but forget to append the result to messages, the model sees the same history on the next call and will likely request the same tool again. This is a frequent cause of repeated calls.
Parallel tool calls
Many providers let the model request several tool calls in one reply, for example looking up three orders at once. Your loop must then run each request and append one result per call before calling the model again. If the calls are independent, you can run them concurrently. The chapter on parallel fan-out covers this. For now, remember that a reply may contain more than one tool request, and the simple loop above handles only one per turn.
Summary of the model
- A tool is a name, a description, a parameter schema, and an implementation.
- The model requests calls. Your program runs them and appends results.
- Each tool use costs at least one extra model call.
- Arguments are untrusted. Errors should go back to the model as text.
- Always cap the loop.
Exercise
In the loop above, a developer changes the code so that the tool runs but its result is never appended to messages. The model's request was get_order_status(order_id=1042). What will most likely happen on the next iteration, and which safeguard in the loop stops it from running forever?
Show answer
The model receives the same messages as before, with no sign that the tool ran, so it will most likely request the same tool call again. This repeats each turn. The max_turns cap stops it by raising RuntimeError("max_turns exceeded") after the allowed number of iterations.
Exercise
A tool is called with {"order_id": "abc"} although the schema says order_id is an integer. Should the program raise an exception that ends the run, or return something else? Give your choice and a reason.
Show answer
Return an error message as the tool result, for example "Error: orderid must be an integer". The model reads it on the next turn and can correct the argument. Raising an exception would end the whole run for a mistake the model can usually fix. The `maxturns` cap still bounds the number of retries.