Sub topic 5
Tool calling: letting the model request actions
This chapter assumes you can write Python, call web APIs, and read JSON. It also assumes you know what a prompt is and that a language model produces text. By the end you will know how a model "calls" a tool, what your code must do in response, and where this goes wrong.
What tool calling is
A language model only produces text. It cannot read a file, query a database, or check the weather. Tool calling is the protocol that closes this gap. You describe a set of functions to the model. When the model decides one is needed, it replies with a structured request naming the function and its arguments. Your program runs the function and sends the result back. The model then continues with that result in view.
The key point is that the model never executes anything. It emits a request. Your code decides whether to run it, how to run it, and what to report back. This is why tool calling is the natural place to enforce permissions, validation, and logging.
Tool calling builds on structured outputs. The arguments the model produces must follow a JSON schema, so your code can parse them reliably.
The round trip
One tool call involves two model requests and one function execution.
Each step in detail:
- Your program sends the conversation plus a list of tool descriptions.
- The model either answers in plain text or returns a tool call.
- If it returns a tool call, your program looks up the function by name and runs it.
- Your program appends the result to the conversation as a tool message.
- You call the model again. It reads the result and answers, or requests another tool.
Steps 2 to 5 can repeat. That repetition is the agent loop, covered in a later chapter. This chapter focuses on a single pass.
What a tool description contains
A tool description has three parts:
- Name. A short identifier such as
get_weather. - Description. Plain language telling the model what the tool does and when to use it.
- Parameters. A JSON schema listing argument names, types, and which are required.
The exact wrapper differs between providers, but the content is the same. A typical description looks like this:
get_weather_spec = {
"name": "get_weather",
"description": "Get the current temperature in Celsius for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Oslo"}
},
"required": ["city"],
},
}The model never sees your Python code. It sees only this description. If the description is vague, the model will call the tool at the wrong time or with the wrong arguments. The next chapter covers how to write good descriptions.
Running the requested tool
The model's request arrives as a name plus an arguments object. Your code needs a registry that maps names to functions, and a runner that handles the failure cases. Here is a minimal version.
import json
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})Three design choices matter here.
- A dictionary lookup, not
evalorgetattron arbitrary names. Only functions you registered can run. The model cannot reach anything else. - Errors become text. If the tool fails,
run_toolreturns the error as a JSON string instead of raising. The model reads it and can fix its arguments or try another approach. A raised exception would crash your program. - Results are strings. The model consumes text, so serialize everything. JSON works well because the model reads it easily.
Seeing the whole pass in code
To try this without a paid model, use a scripted stand-in. It returns a tool call the first time and a final answer once it sees the tool result. The loop below includes a step limit, so it also stops if a model keeps requesting tools.
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."
def fake_model(messages):
# Scripted stand-in for a real model, useful for testing the loop.
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
print(run_agent(fake_model, "What is the weather in Oslo?"))Put this after the run_tool code in the same file. It prints It is 18 C in Oslo. The history after the run holds four messages: the user goal, the assistant's tool call, the tool result, and the final answer.
A real provider's message format differs in field names. Most attach an ID to each tool call and require the tool result to carry the same ID. Check your provider's documentation and keep that ID pairing intact.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Model never calls the tool | Description does not say when to use it | Rewrite the description around the situation that needs it |
| Wrong or missing arguments | Schema is loose or lacks examples | Add types, `required`, and a description with an example per field |
| Unknown tool name | Model invented a name, or the registry is out of date | Return an error naming the valid tools |
| `TypeError` on call | Arguments do not match the function signature | Validate against the schema before calling |
| Program crashes on a tool failure | Exception propagated out of the runner | Catch exceptions and return the error as text |
| Model repeats the same failing call | Error message gives no guidance | Make errors say what was wrong and how to fix it |
Edge cases
- Several tool calls in one reply. Some models request multiple tools at once. Run each one and return every result, matched by ID. Independent calls can run in parallel.
- Malformed arguments. The model can return JSON that is invalid or does not match the schema. Catch the parse error and send it back as a tool error rather than failing.
- Text and a tool call together. A reply may contain explanatory text plus a call. Keep both in the history.
- Large results. A tool that returns a 50,000-character page fills the context window. Truncate or summarize results inside the tool.
- Side effects. A tool that sends email or deletes data changes the world. Retrying after an error can repeat the action. Separate read tools from write tools, and require approval for writes, as covered in the guardrails chapter.
- Forcing or forbidding calls. Most providers let you require a particular tool, require any tool, or disable tools for a turn. Use these when the next step is known.
Exercise
In the run_tool function, why does it return {"error": ...} as a string when a tool raises an exception, instead of letting the exception propagate? Name one extra risk that this design does not remove.
Show answer
Returning the error as text puts it into the conversation, so the model can read what went wrong and correct its arguments or choose another tool. Letting the exception propagate would crash the program and end the run. The design does not stop the model from retrying a side-effecting tool, such as one that sends an email, after a failure that happened partway through. Retries of write actions need separate protection such as approval or idempotency checks.
Exercise
Extend the TOOLS registry with a second function add(a: int, b: int) -> str that returns the sum as JSON. Then call run_tool("add", {"a": 2}) and describe what comes back.
Show answer
Add def add(a: int, b: int) -> str: return json.dumps({"sum": a + b}) and register it as "add": add. The call run_tool("add", {"a": 2}) omits b, so Python raises a TypeError about a missing argument. The except branch catches it and returns a JSON string such as {"error": "add() missing 1 required positional argument: 'b'"}. The model can read this and retry with both arguments.