D4 · Prompt Engineering › Cluster 7 · Structured Outputs & JSON

7.4 · The Structured Outputs Feature

Guaranteed schema conformance

CONCEPT Constrain the response to a JSON Schema

Structured Outputs is the purpose-built feature for "always valid JSON." You supply a JSON Schema on output_config.format and the model's text output is guaranteed to conform — enforced by constrained decoding, not by prompting. The valid JSON lands in response.content[0].text.

resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=1024,
    messages=[{"role": "user",
               "content": "John Smith, john@example.com, enterprise plan."}],
    output_config={
        "format": {
            "type": "json_schema",          # the only format type
            "schema": {
                "type": "object",
                "properties": {
                    "name":  {"type": "string"},
                    "email": {"type": "string"},
                    "plan":  {"type": "string"},
                },
                "required": ["name", "email", "plan"],
                "additionalProperties": False,
            },
        }
    },
)
data = json.loads(resp.content[0].text)   # first text block IS valid JSON
⚠️ Field names verified. The parameter is output_config with a nested format of {"type": "json_schema", "schema": …}. The older top-level output_format parameter (and the structured-outputs-2025-11-13 beta header) is deprecated — output_config.format is GA and needs no beta header.

CONCEPT messages.parse(), models, and schema limits

The recommended path is client.messages.parse(), which validates the response against your schema automatically and hands back a typed object.

from pydantic import BaseModel

class Contact(BaseModel):
    name: str
    email: str
    plan: str

resp = client.messages.parse(
    model="claude-opus-4-8", max_tokens=1024,
    messages=[{"role": "user", "content": "John Smith, john@example.com, enterprise."}],
    output_format=Contact,          # Python convenience; derives + validates the schema
)
contact = resp.parsed_output        # → a validated Contact instance
🔑 Supported models (Claude API, GA): Fable 5, Opus 4.8 / 4.7 / 4.6, Sonnet 5 / 4.6 / 4.5, Opus 4.5, Haiku 4.5. TypeScript uses output_config.format: zodOutputFormat(schema) on messages.parse().
⚠️ JSON Schema is a subset. Supported: object/array/string/number/integer/ boolean/null, enum, const, anyOf, allOf, $ref/$def, string formats (date-time, date, email, uri, uuid, …). Not supported: recursive schemas, numeric bounds (minimum/maximum), string length (minLength/maxLength), and additionalProperties other than false. The Python/TS/Ruby/PHP SDKs strip unsupported constraints and re-validate client-side.

DIAGRAM What the feature guarantees — and what it doesn't

flowchart TD REQ["Request + output_config.format (json_schema)"] --> COMP["Compile grammar
(1st call slower · 24h cache)"] COMP --> GEN["Constrained decoding"] GEN --> SR{"stop_reason?"} SR -->|"end_turn"| OK["🟢 content[0].text is valid JSON
matching the schema"] SR -->|"refusal"| REF["🔴 Safety wins over schema —
output may not conform"] SR -->|"max_tokens"| CUT["🔴 Truncated — invalid JSON;
raise max_tokens & retry"] classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef bad fill:#f8d7da,stroke:#dc3545,color:#721c24; class OK ok; class REF bad; class CUT bad;

CODE Structured output + strict tool use together

The two features compose: constrain the final answer with output_config.format while a strict tool guarantees any tool arguments.

resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=1024,
    messages=[{"role": "user", "content": "Plan a trip to Paris next month."}],
    output_config={"format": {"type": "json_schema", "schema": {
        "type": "object",
        "properties": {
            "summary":    {"type": "string"},
            "next_steps": {"type": "array", "items": {"type": "string"}},
        },
        "required": ["summary", "next_steps"], "additionalProperties": False,
    }}},
    tools=[{
        "name": "search_flights", "strict": True,
        "input_schema": {"type": "object",
            "properties": {"destination": {"type": "string"},
                           "date": {"type": "string", "format": "date"}},
            "required": ["destination", "date"], "additionalProperties": False},
    }],
)
First call with a new schema pays a one-time grammar-compilation cost; compiled grammars are cached for 24 h. Changing the schema (or the tool set) invalidates that cache; changing only a tool's name/description does not.

TRADE-OFFS Feature vs. the prompt/tool routes

ApproachGuaranteeCost / caveat
Prompt techniques (7.1)Best-effortZero setup; you validate & retry
Prefill + stop (7.2)Best-effortPrefill dead on current models
Strict tool use (7.3)Guaranteed (args)Payload nested in a tool_use block
Structured Outputs (7.4)Guaranteed (answer)1st-call compile latency; JSON-Schema subset; ZDR-compatible

EXAM TRAPS

Trap: Using the deprecated top-level output_format parameter (or the structured-outputs-2025-11-13 beta header). → The current, GA field is output_config.format with {"type":"json_schema","schema":…}, no beta header.
Trap: "Structured outputs guarantees valid JSON no matter what." → A refusal or a max_tokens cutoff can still produce non-conforming output — check stop_reason before trusting the text.
Trap: Putting minLength, maximum, or a recursive schema in the format. → Those constraints are not supported; SDKs strip them and validate client-side. Don't rely on the model to enforce them.
Trap: Expecting the enum's exact casing back. → Enum capitalization is not guaranteed — compare case-insensitively when matching returned enum values.

PRACTICE

Q1 · What is the exact parameter shape for structured outputs, and is a beta header needed?

output_config={"format": {"type": "json_schema", "schema": {…}}} on messages.create(). It is GA and needs no beta header — the old top-level output_format + structured-outputs-2025-11-13 header is deprecated.

Q2 · How does the feature guarantee conformance, and when can it still fail?

Via constrained decoding — the model can only emit tokens that keep the JSON valid against the schema. It can still fail to conform on stop_reason: "refusal" (safety overrides schema) or stop_reason: "max_tokens" (truncated); guard on stop_reason.

Q3 · Name two JSON-Schema constructs the feature does NOT enforce.

Any two of: recursive schemas, numeric bounds (minimum/maximum/ multipleOf), string length (minLength/maxLength), array constraints beyond limited minItems, and additionalProperties set to anything but false.