Sub topic 7
Using function and tool calling to return data
This chapter assumes you can write a Pydantic model, you know what a JSON Schema looks like, and you have called a chat API before. Function calling (also called tool calling) is a third way to get structured data, next to JSON mode and schema-constrained output.
What tool calling is
Tool calling was designed so a model can ask your program to run a function. You describe each function with a name, a description, and a JSON Schema for its arguments. The model can reply with a tool call: the function name plus arguments as a JSON string.
You can use this for extraction without running anything. Define a "function" whose arguments are the data you want. The model fills in the arguments, and you read them as your result. The function never has to exist.
Reusing the schema
You already have a schema from the Pydantic chapter. Pass model_json_schema() as the tool's parameters. The example below uses the OpenAI Python SDK. Other providers use different field names for the same idea.
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
MODEL = "gpt-4o-mini" # replace with a model your account can use
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
tools = [
{
"type": "function",
"function": {
"name": "record_triage",
"description": "Record the triage result for a support ticket.",
"parameters": TicketTriage.model_json_schema(),
},
}
]
def triage_with_tool(ticket_text: str) -> TicketTriage:
client = OpenAI()
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Triage this ticket:\n\n" + ticket_text}],
tools=tools,
tool_choice={"type": "function", "function": {"name": "record_triage"}},
)
message = response.choices[0].message
if not message.tool_calls:
raise ValueError("The model did not return a tool call")
arguments = message.tool_calls[0].function.arguments # a JSON string
try:
return TicketTriage.model_validate_json(arguments)
except ValidationError as err:
raise ValueError(f"Tool arguments failed validation: {err}") from errThree details matter here:
- The description is part of the prompt. The model reads the tool's
descriptionand every fielddescription. Write them as instructions. tool_choiceforces the call. With the default setting (usually "auto"), the model may answer in plain text instead. Forcing one named tool makes a tool call the expected result.argumentsis a string. Parse it yourself. Heremodel_validate_jsonparses and validates in one step.
Choosing between tool calling and the alternatives
| Technique | Guarantee | Best when |
|---|---|---|
| JSON mode | Valid JSON, not your schema | You only need parseable output |
| Schema-constrained output | Output matches the schema | The provider supports it and you only need data back |
| Tool calling | Depends on the provider and settings | You also want the model to call real functions, or the provider has no constrained mode |
Tool calling is usually the right choice when a single request mixes extraction with real tools. For example, an agent might search a database and then report its findings in a fixed shape. For pure extraction, schema-constrained output is simpler when it is available.
Limits to know
Strict modes, where they exist, usually restrict the schema. Common requirements are additionalProperties: false and listing every field in required. Some providers also ignore or reject limits such as ge, le, and max_length. Check your provider's documentation, and keep the Pydantic validation as your own check.
Common errors:
- No tool call returned. This happens when
tool_choiceis left on auto. Force the tool, or handle plain-text replies. - Several tool calls. Some models return more than one call in a single reply. Read
tool_calls[0]only if you have forced a single tool, and check the count otherwise. - Arguments cut off. If the reply hits the token limit, the JSON string is incomplete. Check the finish reason before you parse. The failure modes chapter covers this.
- Tool and field names that mislead. A tool named
submitwith a field calleddatagives the model little to go on. Use specific names.
Exercise
You call a model with one tool defined and tool_choice left on its default. Sometimes your code crashes with an error when reading the tool call. What is the likely cause, and what are two fixes?
Show answer
With the default setting the model may reply in plain text and return no tool call, so reading the first tool call fails. Fix it by forcing the tool with tool_choice naming that tool, or by checking whether any tool call exists and handling the plain-text case (for example by retrying). Validating the arguments with the Pydantic model remains necessary in both cases.