Skip to content
AISeeker

Search

Search reports, topics, companies…

CH.05Tutorials
3 min read
Signal strength: 3/5Important
Verified · 4 Sources

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 needClaude (Messages API)OpenAI (Responses API)
Final answer in a fixed shapeoutput_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 argumentsTool with strict: trueFunction tool with strict: true
A tool call on every turnPrompt for it and check; forced tool_choice returns a 400 on Opus 5.5 and Sonnet 5.5tool_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.

python
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 null

Claude:

python
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_output

OpenAI:

python
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 refused

The 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:

json
{
  "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 a tool_use block (Claude) or a function_call item (OpenAI) before assuming one arrived.
  • Return every result. On Claude, send all tool_result blocks for a turn in one user message, and mark failures with is_error: true instead of dropping them. On OpenAI, append a function_call_output item with the matching call_id.
  • Parse, never pattern-match. OpenAI returns arguments as a JSON string; Claude may escape characters differently between models. Use a JSON parser.
  • Gate side effects. A well-formed refund_order call 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 (use anyOf), numeric minimum/maximum, and string minLength/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 additionalProperties must be false, a dict field 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_tokens cut-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_extraction refusal; 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. [1]
    Structured outputs

    Anthropic (Claude Platform Docs)2026.11.28Primary

  2. [2]
    Strict tool use

    Anthropic (Claude Platform Docs)2026.11.28Primary

  3. [3]
    Structured model outputs

    OpenAI API Docs2026.11.28Primary

  4. [4]
    Function calling

    OpenAI API Docs2026.11.28Primary

Back to Tutorials →