Structured outputs and tool calling done right: schemas, strict mode and failure handling
Schema-constrained decoding is now standard on Claude and OpenAI. What still breaks: schema design, refusals, truncation and tool-loop bookkeeping.
Key figures
- 20
- Max strict tools per Claude request
- 24
- Max optional params across strict schemas
- 24h
- Compiled-grammar cache lifetime
The days of begging a model to "respond only with JSON" are over. Anthropic and OpenAI both offer grammar-constrained decoding: give the API a JSON Schema and the output is guaranteed to match it, with a short list of exceptions. That moves the hard part from parsing to design. This tutorial shows the current request shapes on both APIs, a schema pattern that works on each, and the failure cases you still have to handle. It assumes Python with the anthropic and openai SDKs; request shapes follow both vendors' current documentation.
1. Choose the right mechanism
| You need | Claude (Messages API) | OpenAI (Responses API) |
|---|---|---|
| Final answer in a fixed shape | output_config.format or messages.parse(output_format=Model) | text.format with json_schema or responses.parse(text_format=Model) |
| Model calls your function with valid arguments | Tool with strict: true | Function tool with strict: true |
| A tool call on every turn | Prompt for it and check; forced tool_choice returns a 400 on Opus 5.5 and Sonnet 5.5 | tool_choice: "required" or a named function |
Rule of thumb: extraction, classification and report generation want JSON output; anything with side effects or multi-step work wants tools. You can combine them: Claude accepts JSON output and strict tools in the same request.
2. Extraction on both APIs with one Pydantic model
Define the schema once. Every field is required; values that may be missing are nullable rather than optional. That satisfies OpenAI's strict mode and keeps Claude's optional-parameter budget free.
from typing import Literal
from pydantic import BaseModel
class LineItem(BaseModel):
description: str
quantity: int
unit_price_cents: int
class Invoice(BaseModel):
vendor: str
invoice_date: str # ISO 8601, e.g. "2026-10-02"
currency: Literal["USD", "EUR", "JPY", "TWD"]
items: list[LineItem]
po_number: str | None # required key, may be nullClaude:
import anthropic
claude = anthropic.Anthropic()
resp = claude.messages.parse(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": f"Extract this invoice:\n\n{text}"}],
output_format=Invoice,
)
if resp.stop_reason in ("refusal", "max_tokens"):
raise RuntimeError(f"no usable output: {resp.stop_reason}")
invoice = resp.parsed_outputOpenAI:
from openai import OpenAI
oai = OpenAI()
resp = oai.responses.parse(
model=OPENAI_MODEL,
input=[{"role": "user", "content": f"Extract this invoice:\n\n{text}"}],
text_format=Invoice,
)
if resp.status == "incomplete":
raise RuntimeError(f"truncated: {resp.incomplete_details.reason}")
invoice = resp.output_parsed # None if the model refusedThe Anthropic SDK converts the model into output_config.format and validates the reply; OpenAI's helper sends text.format with type: "json_schema" and strict: true. Without the helpers, send the raw schema yourself and parse the text block with json.loads.
3. Strict tools and a correct tool loop
On Claude, strict: true sits next to name and input_schema, and the schema must set additionalProperties: false:
{
"name": "refund_order",
"description": "Issue a refund for an order. Only call after confirming the order ID with the user.",
"strict": true,
"input_schema": {
"type": "object",
"properties": {
"order_id": { "type": "string" },
"amount_cents": { "type": "integer" },
"reason": { "type": "string", "enum": ["damaged", "late", "other"] }
},
"required": ["order_id", "amount_cents", "reason"],
"additionalProperties": false
}
}Strict mode guarantees the tool name exists and the arguments type-check. The loop around it is still your job:
- A call is not guaranteed. With
auto, check for atool_useblock (Claude) or afunction_callitem (OpenAI) before assuming one arrived. - Return every result. On Claude, send all
tool_resultblocks for a turn in one user message, and mark failures withis_error: trueinstead of dropping them. On OpenAI, append afunction_call_outputitem with the matchingcall_id. - Parse, never pattern-match. OpenAI returns
argumentsas a JSON string; Claude may escape characters differently between models. Use a JSON parser. - Gate side effects. A well-formed
refund_ordercall can still be the wrong call. Require confirmation or limits in your code, not just in the description.
4. Design schemas the decoder can handle
Claude compiles schemas into grammars, which brings limits worth knowing:
- Unsupported features: recursive schemas,
oneOf(useanyOf), numericminimum/maximum, and stringminLength/maxLength. The SDK helpers move such constraints into descriptions and re-check them locally. - Complexity caps per request: 20 strict tools, 24 optional parameters and 16 union-typed parameters, counted across all strict schemas.
- No free-form maps. Because
additionalPropertiesmust be false, adictfield can only come back as{}. Use an array of key/value objects instead. - Ordering: required properties are emitted first, then optional ones.
- First-call latency: a new schema compiles on first use; compiled grammars are cached for 24 hours from last use.
On OpenAI, the Responses API tries to normalise function schemas into strict mode and silently falls back to non-strict if it cannot, so check the strict flag on the tool in the response when debugging.
Pitfalls and next steps
- Refusals and truncation break the guarantee. A refusal or a
max_tokenscut-off can return non-conforming output. Check the stop reason or status first. - Do not ask for a "reasoning" field. On Claude, a property demanding step-by-step thinking can trigger a
reasoning_extractionrefusal; ask for a one-sentence justification instead. - Enum casing is not guaranteed. Claude may change capitalisation of multi-word enum values; compare case-insensitively.
- Citations do not mix with JSON output on Claude; the API rejects the combination.
- Valid is not true. A schema cannot tell whether line items add up to the invoice total. Add business-rule checks and an eval set.
Start by converting one brittle "return JSON" prompt to a Pydantic model, add the stop-reason checks, then log every validation failure for a week. The log will tell you which fields to redesign.
Researched and drafted with AI assistance under editorial review. Report errors to support@aiseeker.dev.
Sources
This report synthesises the sources below. Primary sources are marked.
- [1]Structured outputs
Anthropic (Claude Platform Docs)2026.11.28Primary
- [2]Strict tool use
Anthropic (Claude Platform Docs)2026.11.28Primary
- [3]Structured model outputs
OpenAI API Docs2026.11.28Primary
- [4]Function calling
OpenAI API Docs2026.11.28Primary