Sub topic 4
Tool Calling with the SDK
This chapter covers how tool calling works at the provider SDK level. It assumes you can call a chat completions endpoint, read JSON, and write basic Python functions. It also assumes you have seen structured output with Pydantic from the previous chapter.
What tool calling actually is
Tool calling (also called function calling) lets a model ask your program to run a function. The model never runs code itself. It returns a message that names a function and supplies arguments. Your code runs the function, then sends the result back so the model can write a final answer.
This matters for the framework comparison later. Every framework's "tool" feature wraps the same four steps:
- You describe the available functions to the model as JSON Schema.
- The model replies with a tool call instead of text, or in addition to it.
- Your code parses the arguments, runs the function, and captures the result.
- You append the result to the conversation and call the model again.
Once you see these steps in raw SDK code, the framework versions are easier to judge.
Describing a tool
A tool definition has three parts that the model sees: a name, a description, and a parameter schema. The model chooses tools based on these, so the description is a prompt in its own right.
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 stringThe parameters field is standard JSON Schema. Write it by hand for a few tools. For many tools, it is common to generate the schema from a Pydantic model with model_json_schema(), which keeps the schema and your validation code in sync.
What the response looks like
When the model decides to use a tool, message.content is usually None and message.tool_calls holds a list. Each entry has:
| Field | Meaning |
|---|---|
| `id` | A unique identifier you must echo back with the result |
| `function.name` | The tool the model chose |
| `function.arguments` | The arguments as a JSON **string**, not a dict |
Two points trip people up. First, arguments is a string, so you must call json.loads or validate it yourself. Second, the model can return several entries in tool_calls in one turn (parallel tool calls), so do not assume the list has length one.
Completing the round trip
The example above stops after the first step. A complete version runs the function and sends the result back. The tool result goes in a message with role tool, and its tool_call_id must match the id of the call it answers.
import json
from openai import OpenAI
client = OpenAI()
def get_weather(city: str) -> str:
# Stand-in for a real weather API call.
return json.dumps({"city": city, "temperature_c": 18, "conditions": "cloudy"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
registry = {"get_weather": get_weather}
messages = [{"role": "user", "content": "What is the weather in Paris?"}]
first = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
assistant_message = first.choices[0].message
if assistant_message.tool_calls:
messages.append(assistant_message) # the model's tool call must stay in the history
for call in assistant_message.tool_calls:
func = registry[call.function.name]
args = json.loads(call.function.arguments)
result = func(**args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
second = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
print(second.choices[0].message.content)
else:
print(assistant_message.content)Several details in this code are required, not optional:
- The assistant message containing the tool calls must be appended before the tool results. The API rejects a
toolmessage that has no matching call before it. - Every
tool_call_idin the assistant message needs a correspondingtoolmessage. If the model made two calls, you owe two results. - The
contentof a tool message is a string. Serialize dictionaries withjson.dumps. - Pass
toolsagain on the second call if the model might want to call another tool.
The registry dictionary is a small but useful pattern. It maps tool names to Python callables, so you dispatch by name instead of with a growing if chain. Frameworks build the same lookup for you from decorated functions.
Controlling tool use
The tool_choice parameter controls whether the model may, must, or must not call tools.
| Value | Behavior |
|---|---|
| `"auto"` (default) | The model decides whether to call a tool |
| `"none"` | The model answers in text and calls no tools |
| `"required"` | The model must call at least one tool |
| A specific function object | The model must call that named function |
Forcing a specific function is a way to get structured output without JSON mode, because the arguments follow your schema. Some providers also offer a strict option on the function definition that constrains the arguments to the schema exactly. Check your provider's documentation, because strict mode adds restrictions on which schema features you can use.
Failure modes you must handle
The model produces the arguments, so treat them like untrusted input from a user. Real applications run into the following problems.
Malformed or invalid arguments
The argument string can be invalid JSON, especially when output is cut off by a token limit. It can also be valid JSON that does not match your schema: a missing field, a string where you wanted an integer, or a value outside an allowed range. Validate with Pydantic before running the function:
import json
from pydantic import BaseModel, Field, ValidationError
class WeatherArgs(BaseModel):
city: str = Field(min_length=1)
def safe_call(raw_arguments: str) -> str:
try:
args = WeatherArgs.model_validate_json(raw_arguments)
except ValidationError as err:
# Return the error to the model so it can correct itself.
return json.dumps({"error": str(err)})
return json.dumps({"city": args.city, "temperature_c": 18})
print(safe_call('{"city": "Paris"}'))
print(safe_call('{"city": ""}'))Returning the validation error as the tool result lets the model see what went wrong and retry. This is a cheap, effective repair strategy. Put a limit on the number of retries.
Unknown tool names
Models occasionally name a tool that does not exist. Use registry.get(name) and return an error message instead of letting a KeyError crash the request.
Exceptions inside your function
If your function raises, decide what the model should see. Often the best choice is to catch the exception and return a short error string as the tool result. Do not return full stack traces, which can leak internal details and waste tokens.
Side effects and security
A tool that sends email, deletes records, or runs SQL is acting on the model's choice, and the model's choice can be influenced by text in the conversation, including text pulled from web pages or documents. Apply least privilege:
- Give tools the narrowest permissions that work.
- Validate every argument as if a stranger supplied it.
- Require explicit user confirmation before irreversible actions.
- Never pass model-generated strings to a shell or build SQL from them by concatenation.
Parallel calls
Because several calls can arrive in one turn, run them in a loop as shown above. If the calls are independent and slow, such as network requests, you can run them concurrently with concurrent.futures or asyncio. Keep the results in order and keep each result tied to its own tool_call_id.
Costs and limits
Tool definitions count as input tokens on every request. A set of twenty tools with long descriptions adds noticeable cost and latency to each call. Large tool sets can also make selection less reliable, as the model has more near-duplicates to pick from. Keep descriptions specific, keep the set small, and consider sending only the tools relevant to the current task.
Tool results also grow the conversation. A function that returns a 50-kilobyte JSON payload will inflate the next request. Trim results to what the model needs.
Where this leads
What you wrote here is one pass through the loop. If the model might need several rounds of tool calls, such as searching, reading a result, and then searching again, you repeat the call-run-append cycle until the model replies without tool calls. The next chapter builds that loop by hand.
For the framework comparison, note what you did manually: schema writing, argument parsing, validation, dispatch, message bookkeeping, and error handling. Frameworks automate many of these. Typically they generate the schema from a Python function's type hints and docstring, validate arguments, and manage the messages. What they hide is exactly the history and the retry behavior that you saw above, which is why being able to inspect the raw messages matters when something goes wrong.
Exercise
A model returns two entries in tool_calls in one assistant message. You run the first function, append one tool message, and call the API again. What happens, and how do you fix it?
Show answer
The API returns an error because every tool_call_id in the assistant message needs a matching tool message. Fix it by looping over all entries in message.tool_calls and appending one tool message for each, with the correct tool_call_id, before making the next request.
Exercise
The model sends {"city": 42} for a tool that expects a string city name. Describe a way to handle this that lets the conversation continue without crashing or running the function with bad data.
Show answer
Validate the argument string with a Pydantic model (or JSON Schema validator) before calling the function. On a ValidationError, do not run the function. Return the error text as the content of the tool message for that call, so the model can see the problem and issue a corrected call. Cap the number of retries so a stubborn model cannot loop forever.