Sub topic 15
Tool Calling Versus Structured Output
This chapter assumes you can read JSON and JSON Schema, you know how role-tagged chat messages work, and you have seen the tool-calling loop from earlier chapters. Tool calling and structured output both make a model produce JSON that matches a schema. They answer different questions, and choosing the wrong one adds complexity or loses guarantees.
Two Features, Two Purposes
Tool calling asks the model to decide whether your program should do something. The model proposes a call, your code runs it, and the result goes back into the conversation. The model's JSON is an instruction to your program, and the exchange usually continues for another turn.
Structured output asks the model to shape its own answer. You supply a schema, and the final reply is JSON that conforms to it. Nothing is executed and no result returns to the model. The JSON is the product.
| Question | Tool calling | Structured output |
|---|---|---|
| Who acts on the JSON? | Your code runs a function | Your code reads data |
| Does the model get a result back? | Yes, in a tool message | No |
| Number of model turns | One or more | Usually one |
| Who decides if it happens? | The model chooses among tools | You always want the shape |
| Typical use | Fetch data, change state | Extract, classify, format |
Where the Two Overlap
Both features rely on JSON Schema, and the schema in a tool definition looks like the schema for a structured reply. This is why the two are easy to confuse. A tool call whose arguments are the data you want is a form of structured output. Many developers use this on purpose: they define a tool such as record_invoice and never execute it. They read the arguments and discard the rest.
{
"name": "record_invoice",
"description": "Record the fields extracted from an invoice. Call once per invoice.",
"parameters": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"total": {"type": "number", "description": "Amount in the invoice currency"},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]}
},
"required": ["vendor", "total", "currency"],
"additionalProperties": false
}
}This "tool as schema" trick was common before providers added native structured output. It still works, but it has costs. The model may decline to call the tool and answer in prose. You must force the choice with the tool-choice setting from the earlier chapter, and you still must handle the case where nothing comes back. Native structured output avoids both problems.
Native Structured Output
Most major providers now offer a mode where you attach a schema to the request, and the reply is constrained to match it. The exact parameter names differ between providers, such as response_format or a JSON-schema option on the generation settings, so check your provider's documentation. The following sketch is provider-neutral. call_model stands in for your SDK call.
import json
INVOICE_SCHEMA = {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"total": {"type": "number"},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]},
},
"required": ["vendor", "total", "currency"],
"additionalProperties": False,
}
def extract_invoice(call_model, text):
messages = [
{"role": "user", "content": "Extract the invoice fields:\n" + text},
]
reply = call_model(messages, response_schema=INVOICE_SCHEMA)
return json.loads(reply["content"])There is no loop and no dispatcher. One request produces one parsed object. This simplicity is the main reason to prefer structured output when no action is needed.
What "Guaranteed" Means
Providers differ in how strictly they enforce a schema. Some use constrained decoding, which restricts the tokens the model may emit so the output always parses and matches the supported schema features. Others only instruct the model and hope. Even with constrained decoding, three gaps remain:
- Unsupported keywords. Providers support a subset of JSON Schema. Features such as complex
patternexpressions, numeric bounds, or someoneOfforms may be ignored or rejected. - Semantic errors. A reply can match the schema and still be wrong. A
totalof1200is a valid number even if the invoice says120.0. - Refusals and truncation. A model can refuse a request, or hit the output token limit mid-object. The result is no JSON or invalid JSON, even in a strict mode.
For these reasons, parse and validate the result in your own code, as you do with tool arguments. Check business rules the schema cannot express, such as "total must be positive" or "currency must match the customer's account".
Choosing Between Them
Use this decision path.
Some guidelines follow from the diagram.
- Extraction, classification, and reformatting need structured output. The input is already in the prompt, so no outside call is needed.
- Lookups and side effects need tool calling. The model cannot know current weather, or send an email, without your code.
- Choosing among several actions needs tool calling. Each action is a tool, and the model picks one. Structured output can also do this with an
enumfield, but you then write the routing code yourself. - A pipeline that gathers data and reports in a fixed format needs both. The model calls tools during the loop, then the final turn returns JSON that matches a schema.
Combining Both
When an agent loop must end with machine-readable output, there are two common patterns.
The first uses native structured output on the final request only. During the loop you pass tools. When the model stops calling tools, you make one more request with the schema and no tools, or you use a provider that allows both at once.
The second adds a terminal tool, such as submit_report, whose parameters are the final schema. The loop ends when the model calls it. This keeps everything in one mechanism, but it brings back the weakness of the tool-as-schema trick. The model can still end with plain text, so the loop needs a fallback for that case.
def run_until_submit(call_model, messages, max_steps=6):
for _ in range(max_steps):
reply = call_model(messages)
messages.append(reply)
calls = reply.get("tool_calls", [])
if not calls:
raise ValueError("Model answered in text instead of calling submit_report")
for call in calls:
if call["name"] == "submit_report":
return call["arguments"]
outcome = run_tool_call(call)
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"],
})
raise RuntimeError("No report submitted within max_steps")This reuses run_tool_call from the dispatching chapter. The terminal tool's arguments still need the validation described in the validation chapter, because they come from the model.
Common Mistakes
- Using tool calling for plain extraction without forcing it. The model sometimes replies in prose, and your parser fails.
- Defining a tool that does nothing. If you never execute it, a native structured output mode is simpler and cleaner.
- Trusting a schema-conformant reply. Valid shape does not mean correct values.
- Forgetting the schema cost. A large schema is sent as input on every request, which adds tokens and latency, the same as tool definitions do.
- Assuming equal support. A provider may offer structured output for some models but not others, or forbid combining it with tools. Test the exact model you plan to use.
Exercises
Exercise
You are building a feature that reads a support email and returns its category (billing, bug, or other) and a priority from 1 to 5. No database or API is involved. Which feature do you choose and why?
Show answer
Structured output. All the information is already in the prompt, no function must run, and you only need a fixed JSON shape. Define a schema with an enum for the category and an integer for the priority, then validate the parsed result. Tool calling would add a dispatcher and a risk that the model replies in prose.
Exercise
An agent searches an order database and must finish with JSON containing orderid, status, and refundeligible. Describe two ways to produce the final JSON, and name one weakness of each.
Show answer
Option 1: loop with the search tool, then make a final request with a native structured-output schema and no tools. Weakness: one extra model call, which adds cost and latency. Option 2: add a terminal tool such as submit_result whose parameters are the schema. Weakness: the model may answer in plain text instead of calling it, so the loop needs a fallback and a step limit.
Exercise
A reply from a strict structured-output mode matches your schema, but total is 1200 when the invoice says 120.0. What does this show, and what should your code do?
Show answer
It shows that schema conformance guarantees shape, not correctness. Your code should apply its own checks, such as comparing the total with the sum of the line items, and flag or retry the result when the checks fail.