Sub topic 4
Tool calling with the SDK
This chapter assumes you can call a chat completions endpoint, read JSON, and write basic Python functions. You should also know what a Pydantic model is from the previous chapter.
What tool calling is
Tool calling (also called function calling) lets a model ask your program to run a function. The model never runs anything itself. You describe your functions in the request. If the model decides one is needed, it replies with the function name and a set of arguments, and your code does the work.
The model's reply is data, not an action. Your code must read it, run the function, and send the result back.
Describing a tool
Each tool is a JSON Schema description with a name, a description, and the parameters. The description matters. The model uses it to decide when to call the tool.
from openai import OpenAI
client = OpenAI()
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What is the weather in Paris?"}],
tools=tools,
)
message = response.choices[0].message
if message.tool_calls:
call = message.tool_calls[0]
print(call.function.name, call.function.arguments) # arguments is a JSON stringTwo details cause most early bugs:
call.function.argumentsis a JSON string, not a dictionary. Parse it withjson.loads.message.tool_callsisNonewhen the model answers directly. Always check before you read it.
Sending the result back
To finish the round trip, append the model's message to the conversation. Then add a message with role tool that carries the result. The tool_call_id must match the call it answers.
import json
from openai import OpenAI
client = OpenAI()
def get_weather(city: str) -> str:
return f"Sunny, 22 C in {city}" # a stub in place of a real weather API
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
messages = [{"role": "user", "content": "What is the weather in Paris?"}]
response = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
message = response.choices[0].message
if message.tool_calls:
messages.append(message) # the assistant turn that contains the tool call
for call in message.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
final = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
print(final.choices[0].message.content)
else:
print(message.content)The loop over message.tool_calls matters. A model can request several calls in one reply, and each needs its own tool message.
Common errors
| Symptom | Likely cause |
|---|---|
| `JSONDecodeError` on arguments | The model produced malformed JSON. Catch the error and retry or report it. |
| API error about missing tool messages | You skipped a `tool_call_id` when several calls came back. |
| Wrong function chosen | The tool descriptions are vague or overlap. Rewrite them. |
| Function raises `TypeError` | The model invented or omitted an argument. Validate before you call. |
Validating arguments
You can reuse Pydantic from the previous chapter to check arguments before running the function.
from pydantic import BaseModel, ValidationError
class WeatherArgs(BaseModel):
city: str
def safe_call(raw_arguments: str) -> str:
try:
args = WeatherArgs.model_validate_json(raw_arguments)
except ValidationError as err:
return f"Invalid arguments: {err}" # send this back so the model can retry
return f"Sunny, 22 C in {args.city}"
print(safe_call('{"city": "Paris"}'))
print(safe_call('{"town": "Paris"}'))Returning the error text as the tool result often lets the model correct itself on the next turn. This single round trip is the first step of an agent loop, which the next chapter extends.
Exercise
In the tool-calling round trip, which part runs the function, and what must the tool message contain so the model can match it to its request?
Show answer
Your own code runs the function, not the model. The tool message must carry the result as its content and the tool_call_id of the call it answers.
Exercise
Why should you call json.loads on call.function.arguments, and what should you do if it fails or the arguments are wrong?
Show answer
The arguments arrive as a JSON string, so you must parse it before using the values. If parsing or validation fails, catch the error and either retry the request or send the error text back as the tool result so the model can correct its call.