Sub topic 7
Using function and tool calling to return data
This chapter assumes you can write basic Python with classes and exceptions, read JSON, and have called an LLM API at least once. It also assumes you have seen JSON Schema and Pydantic models from earlier chapters. Here you will use tool calling, a feature built for running functions, as a way to get structured data back.
What tool calling is
Tool calling (also called function calling) is an API feature where you describe one or more functions to the model. Each description has a name, a plain-language purpose, and a JSON Schema for its arguments. The model can then reply with a request to call one of those functions, including a JSON object of arguments that follows your schema.
The original purpose is to let a model act: look up the weather, query a database, send an email. Your program runs the function and sends the result back. But the arguments the model produces are structured data in the shape you defined. If you only want the data, you can define a tool, read its arguments, and never run anything.
That is the trick of this chapter. You declare a "tool" whose parameters are the fields you want extracted. The model "calls" it, and the call's arguments are your result.
The request and response flow
A tool-calling exchange has these steps.
- You send the user's text, plus a list of tool definitions.
- The model decides whether to call a tool. It returns a message containing a tool call: a tool name and an arguments value.
- Your code reads the arguments and parses them.
- For a real action, you run the function and send the result back in a follow-up message. For data extraction, you stop at step 3.
Provider APIs differ in field names, but the shape is the same everywhere. A tool has a name, a description, and a parameters schema. A response contains a list of tool calls, each with a name and arguments.
A tool definition for the ticket example
Earlier chapters used a ticket triage schema. Here is the same shape as a tool definition. The wrapper format below follows the common "function" style. Your provider may name the keys differently, such as input_schema instead of parameters, so check its documentation.
{
"type": "function",
"function": {
"name": "record_ticket_triage",
"description": "Record the triage result for a support ticket.",
"parameters": {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "bug", "feature_request", "other"]
},
"priority": {
"type": "integer",
"description": "1 is most urgent, 3 is least urgent"
},
"summary": {
"type": "string",
"description": "One-sentence summary of the ticket"
}
},
"required": ["category", "priority", "summary"],
"additionalProperties": false
}
}
}The name and description matter more than they look. The model reads them to decide when and how to use the tool. A name like record_ticket_triage tells it what the arguments represent. A name like tool1 does not.
Generating the definition from a Pydantic model
You should not maintain the JSON by hand when you already have a Pydantic model. Build the tool definition from the model, so there is one source of truth.
from typing import Literal
from pydantic import BaseModel, Field
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")
def tool_from_model(model, name, description):
"""Build a function-style tool definition from a Pydantic model."""
return {
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": model.model_json_schema(),
},
}
tool = tool_from_model(
TicketTriage,
"record_ticket_triage",
"Record the triage result for a support ticket.",
)
print(tool["function"]["parameters"]["required"])Running this prints ['category', 'priority', 'summary']. Note that ge, le, and max_length become minimum, maximum, and maxLength in the schema. Whether the provider enforces those keywords varies, which is why validation still matters later in this chapter.
Forcing the model to call the tool
By default the model chooses whether to call a tool. For extraction you want it to always call yours. Most APIs have a setting, often called tool_choice, with options like these:
| Setting | Meaning |
|---|---|
| auto | The model may answer in text or call any tool. |
| required (or "any") | The model must call some tool. |
| a specific tool name | The model must call that exact tool. |
| none | The model may not call tools. |
For extraction, name the specific tool. If you offer a single tool and leave the choice on auto, the model can still reply with plain text such as a clarifying question, and your code then finds no tool call.
The exact spelling of these settings differs between providers, so treat the table as the concept and check your provider's reference for the syntax.
Reading the tool call
The arguments often arrive as a JSON string, not as a parsed object. Some SDKs parse it for you, and some do not. Handle both, and treat the contents as untrusted until validated.
The function below works on a response already converted to a plain dictionary. It uses the TicketTriage model from the previous section, and the request-level wiring is left to your SDK.
import json
from pydantic import ValidationError
def parse_tool_call(message: dict, expected_name: str) -> TicketTriage:
"""Extract and validate the arguments of a single expected tool call."""
calls = message.get("tool_calls") or []
if not calls:
raise ValueError("Model returned no tool call")
call = next((c for c in calls if c["function"]["name"] == expected_name), None)
if call is None:
raise ValueError(f"Model did not call {expected_name}")
arguments = call["function"]["arguments"]
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError as err:
raise ValueError(f"Arguments were not valid JSON: {err}") from err
return TicketTriage.model_validate(arguments)
message = {
"tool_calls": [
{
"function": {
"name": "record_ticket_triage",
"arguments": '{"category": "billing", "priority": 2, "summary": "Customer was charged twice."}',
}
}
]
}
print(parse_tool_call(message, "record_ticket_triage"))This prints the validated TicketTriage object. Three separate failures are handled: no call at all, a call to the wrong tool, and arguments that are not parseable JSON. A fourth, arguments that parse but break the schema, is raised by Pydantic as a ValidationError.
Does tool calling guarantee your schema?
Not by default. This is the most common misunderstanding.
Tool calling started as a trained behavior. Models are fine-tuned to produce arguments that follow the schema, and they usually do. But "usually" is not "always." Without enforcement, you can see:
- Missing required fields.
- Invalid enum values, such as
"Billing"instead of"billing". - Numbers returned as strings, such as
"2"instead of2. - Invented extra fields.
- Arguments that are not valid JSON, especially when output is cut off.
Some providers offer a strict mode for tools. In strict mode, the schema is enforced with constrained decoding, the technique from the previous chapter, so arguments always match. Strict mode typically restricts which JSON Schema keywords you can use. For example, it may require additionalProperties: false and every property listed as required, and it may ignore limits like maxLength. If you turn strict mode on, read the list of supported keywords.
Treat strict mode as a reliability improvement for the shape, not for the meaning. A strictly valid object can still contain a wrong category.
Tool calling versus the other approaches
You now have four ways to get structured data. Choosing among them depends on what your provider supports and what you are building.
| Approach | Guarantees valid JSON | Guarantees your schema | Best for |
|---|---|---|---|
| Prompt only | No | No | Quick experiments, models with no other option |
| JSON mode | Yes | No | Valid JSON when you validate it yourself |
| Schema-constrained outputs | Yes | Yes, for supported keywords | Pure extraction and data return |
| Tool calling (non-strict) | Usually | No | Choosing between actions, or providers lacking schema outputs |
| Tool calling (strict) | Yes | Yes, for supported keywords | Same as constrained outputs, inside an agent loop |
Use schema-constrained outputs for a plain "read this text and give me data" task if your provider offers them. The intent is clearer, because you are not pretending to call a function.
Use tool calling when:
- The model must choose among several actions, each with its own argument shape.
- Your provider has no direct schema-constrained response format, but does support tools.
- You are building an agent that mixes data return with real function execution.
Choosing between several shapes
Tool calling has a natural advantage when the output can take more than one form. Suppose a message might be a ticket, a cancellation request, or something you cannot handle. Define one tool per shape, and let the model pick.
from typing import Literal
from pydantic import BaseModel, Field
class CreateTicket(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
summary: str = Field(max_length=200)
class CancelSubscription(BaseModel):
reason: str = Field(max_length=200)
class NeedsHuman(BaseModel):
why: str = Field(description="Why this message cannot be handled automatically")
TOOLS = {
"create_ticket": CreateTicket,
"cancel_subscription": CancelSubscription,
"needs_human": NeedsHuman,
}
def route(message: dict):
"""Validate the first tool call against the model registered for its name."""
calls = message.get("tool_calls") or []
if not calls:
raise ValueError("Model returned no tool call")
call = calls[0]["function"]
model = TOOLS.get(call["name"])
if model is None:
raise ValueError(f"Unknown tool: {call['name']}")
return model.model_validate_json(call["arguments"])Including a needs_human escape tool is a useful pattern. When the model has no good option, it can say so, instead of forcing a bad answer into the wrong shape. Without an escape route, models tend to pick the closest tool even when none fits.
Some providers allow several tool calls in one response (parallel tool calling). route reads only the first. If your task expects exactly one, either disable parallel calls where the API allows it, or raise an error when more than one arrives.
Edge cases and gotchas
Several problems recur in practice.
- Truncation. If the response hits the output token limit, the arguments can end mid-string. The JSON then fails to parse. Check the stop or finish reason in the response. A reason meaning "length" tells you the output was cut off, so do not retry with the same limit.
- Text beside the call. Some models write a sentence of text before the tool call. Read the tool call and ignore the text, rather than expecting the message to contain only a call.
- Refusals. The model may decline the request and return text with no tool call. Your parser should treat a missing call as a distinct failure, which
parse_tool_calldoes. - Nested and optional fields. Deep nesting, unions, and optional fields raise the error rate even with trained tool calling. Keep tool schemas flat where you can.
- Descriptions as instructions. Field descriptions affect what the model writes. A vague description such as "the value" yields vague values.
- Wrong values, right shape. A call can be fully valid and still wrong. A ticket about a crash can be labeled
billingand pass every check. - Side effects. If you do run the functions, validate arguments before you act on them. A model's tool call is a proposal, not a command. This matters most for deleting data, sending messages, or spending money.
A complete extraction function
This function combines the pieces: a forced tool, parsing, validation, and a bounded retry that feeds errors back. It reuses tool_from_model and parse_tool_call from above. It takes call_llm, a function you supply, that sends the messages and tool list to your provider and returns the assistant message as a dictionary.
def extract_with_tool(ticket_text, call_llm, max_attempts=3):
"""call_llm(messages, tools, tool_name) -> dict returns the assistant message."""
tools = [
tool_from_model(
TicketTriage,
"record_ticket_triage",
"Record the triage result for a support ticket.",
)
]
messages = [
{"role": "user", "content": "Triage this support ticket.\n\n" + ticket_text}
]
last_error = None
for _ in range(max_attempts):
reply = call_llm(messages, tools, "record_ticket_triage")
try:
return parse_tool_call(reply, "record_ticket_triage")
except (ValueError, ValidationError) as err:
last_error = err
messages.append({"role": "user", "content": (
f"Your previous tool call was invalid: {err}\n"
"Call record_ticket_triage again with corrected arguments."
)})
raise ValueError(f"No valid tool call after {max_attempts} attempts: {last_error}")ValidationError is a subclass of ValueError in Pydantic v2, so the tuple is redundant but harmless, and it makes the intent explicit. The loop always ends: after max_attempts it raises an error instead of calling the model forever. Your caller decides what to do next, such as queueing the ticket for a person.
One caution applies. In a real chat API, a follow-up that includes the previous assistant message and a tool result message keeps the conversation valid. Some providers reject a history where a tool call has no matching tool result. If yours does, append the assistant message and a tool-result message that holds the error text, instead of a plain user message.
Summary of when to use it
Tool calling is a good fit when the model must choose between actions or you are building an agent. For plain extraction, prefer schema-constrained outputs where available. In every case, validate the arguments in your own code, bound your retries, and handle the cases where no call comes back.
Exercise
Your extraction task uses tool calling with a single tool, and tool_choice is left on auto. Occasionally your parser finds no tool call in the response. Give two possible causes and one change that reduces how often this happens.
Show answer
The model may have replied in plain text, such as a clarifying question or a refusal, because auto lets it skip the tool. Alternatively, the output may have been truncated by the token limit before a complete call was produced, which you can confirm by checking the finish reason. Setting tool_choice to force the specific tool (or "required") reduces plain-text replies. For truncation, raise the output token limit.
Exercise
Strict mode is on for your tool, and the model returns {"category": "bug", "priority": 2, "summary": "..."} for a ticket where the customer says they were double charged. The object passes schema validation. What kind of error is this, and how would you detect it?
Show answer
It is a semantic error: the shape is valid but the value is wrong, since this ticket should be billing. Schema validation cannot catch it. You would detect it by testing the pipeline against a fixed set of labeled example tickets and tracking how often the predicted category differs from the expected one.