Sub topic 13
Letting models call tools and APIs
A language model only produces text. It cannot check the weather, query your database, or send an email. Tool use (also called function calling) closes that gap. The model writes a structured request, and your program carries it out. This chapter covers the working model, a runnable dispatcher, validation, and the errors that show up most often.
This chapter assumes you know basic Python, can read JSON, and have seen how structured output is validated (the previous chapters on extraction and structured output). It also assumes you know what an HTTP API is.
The working model
The model never runs anything. Your code does. A tool-calling exchange has these parts:
- You describe each tool to the model: a name, a plain-language description, and a schema for its arguments.
- The user sends a message.
- The model replies with either normal text or a tool call. A tool call is structured data naming a tool and giving arguments.
- Your program checks the call, runs the matching function, and captures the result.
- You send the result back to the model as text.
- The model uses the result to write the final answer, or asks for another tool call.
The key point is that the tool call is a proposal. The model chose the tool and the arguments from its training and the descriptions you gave it. Your program decides whether to run it.
Describing a tool
Most model APIs accept tool descriptions as JSON Schema. The exact envelope differs between providers, but the content is the same.
WEATHER_TOOL = {
"name": "get_weather",
"description": "Get current temperature in Celsius for a city. Use only when the user asks about current weather.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Oslo"}
},
"required": ["city"],
},
}
print(WEATHER_TOOL["name"])The description is a prompt. The model picks tools by reading it, so vague names and descriptions cause wrong or missed calls. State what the tool does, when to use it, and what each argument means. Give units and formats.
Running the call yourself
The dispatcher looks the tool up in an allow-list, runs it, and returns the result as text.
import json
def get_weather(city):
return {"city": city, "temp_c": 18}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS[call["name"]]
return json.dumps(fn(**call["arguments"]))
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Oslo"}}))Two design choices matter here. The TOOLS dictionary is an allow-list: only functions you put in it can run, whatever name the model produces. And the result is serialized to a string, because the model reads text.
Validating before executing
The version above trusts the model completely. A real dispatcher treats a tool call like any other untrusted input, in the same way you validated extracted JSON earlier. The model can invent a tool name, omit an argument, or pass the wrong type.
import json
def get_weather(city):
return {"city": city, "temp_c": 18}
TOOLS = {"get_weather": get_weather}
def safe_tool_call(call):
name = call.get("name")
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
args = call.get("arguments")
if not isinstance(args, dict):
return json.dumps({"error": "arguments must be an object"})
if name == "get_weather" and not isinstance(args.get("city"), str):
return json.dumps({"error": "city must be a string"})
try:
return json.dumps(TOOLS[name](**args))
except TypeError as exc:
return json.dumps({"error": f"bad arguments: {exc}"})
except Exception as exc:
return json.dumps({"error": f"tool failed: {exc}"})
print(safe_tool_call({"name": "get_weather", "arguments": {"city": "Oslo"}}))
print(safe_tool_call({"name": "delete_all", "arguments": {}}))
print(safe_tool_call({"name": "get_weather", "arguments": {"town": "Oslo"}}))Returning errors as text instead of raising is deliberate. The model can read "unknown tool" or "bad arguments" and correct its next call. Keep error messages short and free of secrets such as stack traces, file paths, or credentials.
Choosing what to expose
Each tool is a capability you grant to a system that can be wrong or manipulated. Sort tools by what they can do:
| Kind | Example | Risk | Typical safeguard |
|---|---|---|---|
| Read-only | Look up an order status | Leaks data if scoped too widely | Restrict to the current user's data |
| Reversible write | Add an item to a draft | Clutter, wrong edits | Log changes, allow undo |
| Irreversible or external | Send email, charge a card, delete a record | Real damage | Require human confirmation |
Apply least privilege. Run tools with the current user's permissions, not an administrator's. Do not give the model a generic tool such as "run any SQL" or "run any shell command" when a narrow one such as "get order by ID" will do.
Common errors
- Wrong tool chosen. Overlapping descriptions confuse the model. Make tools distinct, and keep the number of tools small. Accuracy tends to fall as the list grows.
- Invented or malformed arguments. The model may guess a missing value, such as a made-up order ID, instead of asking. Mark fields required, validate formats, and say in the description to ask the user when a value is unknown.
- Calling a tool when none is needed. Say when to use the tool and when not to.
- Large results. A tool that returns 50,000 rows fills the context window and raises cost. Return only the fields needed, paginate, and truncate with a note such as "showing 10 of 240".
- Slow or failing tools. Set timeouts, handle exceptions, and return a clear error so the model can explain the failure.
- Repeated side effects. If a call is retried after a timeout, a payment may run twice. Use idempotency keys on actions that change state.
- Treating the result as truth. The model can still misread or misreport a correct result. For high-stakes answers, show the source data next to the model's summary.
Several calls and the road to agents
A model may request more than one call in a single reply, such as weather for two cities. Run each one and return every result, matched to the call it answers by an ID. A model may also need the result of one call before choosing the next. Repeating the cycle of call, result, and next call until the model gives a final answer is the loop that agents build on. Whenever you loop, set a maximum number of steps so a confused model cannot call tools forever.
def run_loop(ask_model, run_tool, user_message, max_steps=5):
messages = [{"role": "user", "content": user_message}]
for _ in range(max_steps):
reply = ask_model(messages)
if "tool_call" not in reply:
return reply["text"]
result = run_tool(reply["tool_call"])
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "tool", "content": result})
return "Stopped: too many steps."
# A scripted stand-in for a model, to show the control flow
script = iter([
{"tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}},
{"text": "It is 18 C in Oslo."},
])
print(run_loop(lambda m: next(script), lambda c: '{"temp_c": 18}', "Weather in Oslo?"))The fake model here only demonstrates the control flow. With a real API, ask_model would send messages and your tool descriptions, then convert the provider's response into this shape.
Testing tool use
Test the pieces separately. Unit-test the dispatcher with valid calls, unknown tools, missing arguments, and wrong types. Then build a small set of user requests with the expected tool and arguments, run them against the model, and count how often it picks correctly. This gives you a number to compare when you change a description or switch models.
Exercise
A model returns the tool call {"name": "refundorder", "arguments": {"orderid": "A-1042"}}. Your dispatcher looks up refund_order in its allow-list and runs it. Name two safeguards that should apply before the refund executes.
Show answer
First, check that the order belongs to the current user and that the user is allowed to refund it, because the model's argument is untrusted input. Second, require explicit human confirmation, since a refund is irreversible and external. An idempotency key on the refund request is also good, so a retry cannot refund twice.
Exercise
Why does the dispatcher return error messages as text to the model instead of raising an exception?
Show answer
The model reads the tool result as its next input. A short error such as "unknown tool" or "city must be a string" lets it correct the call or tell the user what went wrong. Raising an exception would stop the program without giving the model a chance to recover.