Sub topic 13
Letting the model request tool calls
This chapter assumes you can send a chat request, read the response, and keep message history as shown in earlier chapters. It also assumes you can parse JSON in Python.
What tool calling is
A model cannot run code, query a database, or read a clock. With tool calling, you describe functions to the model. The model may reply with a request to call one of them, and your program does the work.
The model never runs anything. It returns the function name and a JSON string of arguments. Your code runs the function and sends the result back as a new message.
The loop
Describing a tool
Each tool has a name, a description, and a JSON Schema for its parameters. The description matters. The model uses it to decide when to call the tool.
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature in Celsius for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"],
},
},
}
]A complete round trip
This example uses the chat-completions shape. Field names differ between providers, so check your provider's documentation.
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 in Celsius for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
def get_weather(city):
return {"city": city, "temp_c": 18} # stand-in for a real lookup
REGISTRY = {"get_weather": get_weather}
def post(messages):
resp = requests.post(
URL,
headers=HEADERS,
json={"model": MODEL, "messages": messages, "tools": tools},
timeout=30,
)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]
messages = [{"role": "user", "content": "How warm is it in Oslo?"}]
reply = post(messages)
if reply.get("tool_calls"):
messages.append(reply)
for call in reply["tool_calls"]:
name = call["function"]["name"]
func = REGISTRY.get(name)
try:
args = json.loads(call["function"]["arguments"])
result = func(**args) if func else {"error": f"unknown tool {name}"}
except (json.JSONDecodeError, TypeError) as exc:
result = {"error": str(exc)}
messages.append(
{
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
}
)
reply = post(messages)
print(reply["content"])Three details matter here:
- The assistant message that contains
tool_callsmust go into the history before the tool results. - Each result message carries the
tool_call_idof the call it answers. - The
argumentsfield is a string, so you must parse it yourself.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| API rejects the second request | Assistant message with `tool_calls` was left out of history | Append it before the results |
| `JSONDecodeError` | The model produced malformed arguments | Catch it and return an error result |
| Unknown tool name | The model invented a name | Look up names in a registry, never call by `eval` |
| Endless loop | The model keeps requesting tools | Cap the number of rounds |
| Wrong or missing arguments | The model guessed values | Validate arguments before running |
Handling many rounds
A model may call tools several times before answering. Wrap the steps above in a loop that runs until the reply has no tool_calls, with a fixed maximum such as five rounds. Each round adds to the history, so it also adds to token cost.
Exercise
A tool-calling request fails on the second call. Your code appended the tool result with the right tool_call_id but did not append the model's earlier reply. Why does it fail, and how do you fix it?
Show answer
The API expects every tool message to answer a tool_calls entry in a preceding assistant message. Without that assistant message, the result has nothing to refer to. Append the assistant message that holds tool_calls to the history first, then the tool result messages.
Exercise
Why should you cap the number of tool-calling rounds?
Show answer
The model can keep requesting tools without reaching a final answer. A cap bounds the cost, latency, and side effects of a loop that never ends.