Sub topic 13
Letting the model request tool calls
A language model only produces text. It cannot check the weather, query a database, or send an email. Tool calling (also called function calling) is the pattern that lets a model ask your program to do those things. This chapter covers the request shape, the response shape, the loop your code must run, and the errors that come up most often.
This chapter assumes you can send a chat request, read the response object, and keep the message list yourself, as covered in earlier chapters. It also assumes you can parse JSON and validate it, as in the structured output chapter.
The core idea: the model asks, your code acts
The model never runs anything. When you declare tools in a request, the model may reply with a request to call one of them, with arguments it chose. Your program then does the following:
- Checks that the request is valid and allowed.
- Runs the real function.
- Sends the result back as a new message.
- Calls the API again so the model can write the final answer.
The API is stateless, so every step sends the full message history again. A tool call therefore costs at least two API calls.
Declaring a tool
In the chat-completions shape, you add a tools list to the request. Each tool has a name, a description, and a JSON Schema that describes its arguments.
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}The model sees the name, description, and schema as part of its input. This has two consequences:
- A clear description and clear parameter descriptions are the main way you steer when and how the tool is used.
- Tool definitions use tokens on every request, so a long list of verbose tools raises cost and latency.
Field names and some details differ between providers. Check your provider's documentation for the exact shape.
Reading a tool call in the response
When the model decides to use a tool, the assistant message has a tool_calls list. The content field is often null, and the finish_reason is usually "tool_calls".
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Paris\", \"unit\": \"celsius\"}"
}
}
]
}Note that arguments is a string that contains JSON, not an object. You must parse it yourself, and the string can be malformed or contain values that break your schema. Treat it as untrusted input.
The id links the request to your answer. You must return it unchanged in the tool result message.
A complete tool loop
The program below defines one tool, runs the loop, and caps the number of rounds. It uses the same environment variables as the earlier chapters. The weather function returns fixed data so you can run the example without another service.
import json
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
MODEL = os.environ["LLM_MODEL"]
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}
]
def get_weather(city, unit="celsius"):
fake_data = {"paris": 18, "tokyo": 24}
temp = fake_data.get(city.lower())
if temp is None:
return {"error": f"No data for {city}"}
if unit == "fahrenheit":
temp = round(temp * 9 / 5 + 32)
return {"city": city, "temperature": temp, "unit": unit}
REGISTRY = {"get_weather": get_weather}
def run_tool(call):
name = call["function"]["name"]
func = REGISTRY.get(name)
if func is None:
return {"error": f"Unknown tool: {name}"}
try:
args = json.loads(call["function"]["arguments"])
if not isinstance(args, dict):
return {"error": "Arguments must be a JSON object"}
return func(**args)
except json.JSONDecodeError:
return {"error": "Arguments were not valid JSON"}
except TypeError as exc:
return {"error": f"Bad arguments: {exc}"}
def chat(question, max_rounds=5):
messages = [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": question},
]
for _ in range(max_rounds):
payload = {"model": MODEL, "messages": messages, "tools": TOOLS}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=60)
resp.raise_for_status()
message = resp.json()["choices"][0]["message"]
messages.append(message)
calls = message.get("tool_calls")
if not calls:
return message["content"]
for call in calls:
result = run_tool(call)
messages.append(
{
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
}
)
raise RuntimeError("Tool loop did not finish within max_rounds")
print(chat("Is it warmer in Paris or Tokyo right now?"))Points to notice in this code:
- The assistant message that contains
tool_callsis appended to the history before the results. The API rejects atoolmessage that has no matching assistant request before it. - Each result uses
role: "tool"and the sametool_call_idas the request. - The
contentof a tool message is a string, so the result goes throughjson.dumps. - Errors go back to the model as data. The model can then correct its arguments, try another approach, or explain the problem to the user.
max_roundsstops a model that keeps requesting tools from looping forever and running up cost.
For the question above, the model will probably request two get_weather calls in one message. That is parallel tool calling, and the for call in calls loop handles it. Each call needs its own result message.
Controlling when tools are used
The tool_choice field sets the policy.
| Value | Behavior |
|---|---|
| `"auto"` | The model decides whether to call a tool. This is the default when tools are present. |
| `"none"` | The model answers in text only, even though tools are declared. |
| `"required"` | The model must call at least one tool. |
| A named function | The model must call that specific tool. |
Some providers also offer a switch that disables parallel calls. Use it when your tools depend on each other or must run in a fixed order.
Forcing a tool is a common way to get structured output: define a tool whose schema is the shape you want, force it, and read the arguments. You still validate the result.
Validating arguments and limiting what tools can do
The model chooses the arguments, and its input can include text from users or from web pages. A crafted input can push the model to request a harmful call. Apply the same rules you would use for any untrusted API client:
- Validate arguments against the schema before running anything. A library such as
jsonschemaorpydanticdoes this better than hand-written checks. - Allow only the tools in your registry. Never run a name from the model with
eval,getattr, or a shell. - Give each tool the least privilege it needs. A read-only database account is safer than a general one.
- Require user confirmation before actions that cannot be undone, such as sending money or deleting data.
- Check authorization in your code, using the identity of the real user. Do not rely on the model to refuse.
- Treat tool output as data. A web page returned by a tool may contain text that tries to give the model new instructions.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 400 error about a missing tool response | A `tool_call_id` has no matching `tool` message | Return one result for every call, including failed ones |
| 400 error about message order | The assistant message with `tool_calls` was not appended | Append it before the tool results |
| `JSONDecodeError` on arguments | The model produced malformed JSON, often after hitting a length limit | Return an error as a result, and check `finish_reason` for `"length"` |
| The model never calls the tool | Vague description, or `tool_choice` is `"none"` | Rewrite the description, or force the tool |
| The loop never ends | The model keeps requesting tools | Keep `max_rounds`, and return clear errors |
| Cost is higher than expected | Large tool definitions and large tool results, resent every round | Shorten descriptions, and trim results before returning them |
A related cost point: tool results go into the context window and count as input tokens on every later call. Return only the fields the model needs, not a whole database row or an entire web page.
Design tips for good tools
- Use few tools with distinct purposes. A model picks better from five tools than from fifty.
- Name tools with a verb and a noun, such as
search_orders. - Use enums for fixed choices, as the
unitfield shows. - Describe units and formats in the parameter descriptions, such as "date in YYYY-MM-DD".
- Make tools idempotent when you can, so a retry after a timeout does not run an action twice.
- Return short, clear error messages that tell the model what to change.
Exercise
In the tool loop, a model returns two tool calls in one assistant message. You run both and send back only one tool message, then call the API. What happens, and how do you fix the code?
Show answer
The API will usually reject the request with a 400 error, because one tool_call_id has no matching result. Fix it by looping over every entry in tool_calls and appending one tool message per call, each with its own tool_call_id. This holds even when a call fails: send the error as that call's result.
Exercise
A tool named delete_file takes a path argument chosen by the model. List two checks your code should make before running it.
Show answer
Any two of these: validate that path is a string that matches the schema. Resolve the path and confirm it is inside an allowed directory, which blocks values like ../../etc/passwd. Check that the current user is authorized to delete that file. Ask the user to confirm before deleting. Run the tool with the least privilege it needs.