SDK Guide · As of 2026-11-25

Claude Structured Outputs: Getting Valid JSON Every Time with output_config.format and Strict Tool Use

As of 2026-11-25, the most reliable way to get JSON from Claude that you can parse without a try/except is Anthropic's Structured outputs feature: set output_config.format on the request (JSON outputs) or add strict: true to a tool definition (strict tool use). Both compile your JSON Schema into a grammar and constrain sampling, so the output matches the schema. The official docs list the feature as generally available, with no beta header needed, on every current model including Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2. Through QCode's Anthropic endpoint, https://api.qcode.cc/api, the request shape matches the official examples; if you rely on output_config.format, per-tool strict or eager_input_streaming, test with a small request first.

QCode is an independent third-party API service and is not affiliated with Anthropic. Parameters and limits below are taken from the Structured outputs, Strict tool use and Fine-grained tool streaming pages on platform.claude.com, read on 2026-11-25.

Updated 2026-11-26

Key facts

  • Two modes. JSON outputs use output_config={"format": {"type": "json_schema", "schema": {...}}} and constrain the model's final reply. Strict tool use sets "strict": true on a tool and constrains the tool name and input. You can use both in one request.
  • The old parameter is deprecated. output_format without the structured-outputs-2025-11-13 beta header returns 400. In the Python SDK v1.0+, passing a raw dict to output_format raises TypeError.
  • SDK helpers. In Python, call client.messages.parse(..., output_format=PydanticModel) and read parsed_output. In TypeScript, pass zodOutputFormat() or jsonSchemaOutputFormat() to client.messages.parse().
  • Schema limits. At most 20 strict tools per request, 24 optional parameters and 16 union-typed parameters in total. No recursion, no oneOf, no numeric or string-length constraints, and every object needs additionalProperties: false.
  • When output can still miss the schema. stop_reason: "refusal", stop_reason: "max_tokens", and enum casing, which is not guaranteed.
  • What changed with the 5.5 models. Opus 5.5 and Sonnet 5.5 reject tool_choice of any and tool, and assistant prefill is rejected on Opus 5.5 and Sonnet 5.5. The two old tricks, forcing a tool call and prefilling {, no longer work.

Ways to get JSON, compared

Method Guaranteed valid? On 5.5 models Best for
"Reply only with JSON" in the prompt No Works Prototypes, loose internal scripts
Prefill the assistant turn with { No Rejected (400) on Opus 5.5 / Sonnet 5.5 No longer recommended
Force a tool with tool_choice Inputs mostly reliable 400 on Opus 5.5 / Sonnet 5.5 Older models only
Strict tool use, strict: true Tool name and input match schema Supported, with tool_choice: auto Agent actions, several structured actions
JSON outputs, output_config.format Final reply matches schema Supported Extraction, classification, structured results

The short rule: if the answer itself should be JSON, use output_config.format. If you want the model to take an action with structured arguments, use a strict tool.

Method 1: JSON outputs with Pydantic (Python)

The documented path is to hand a Pydantic model to client.messages.parse(). The SDK converts the schema, sends it as output_config.format, validates the reply and puts the result in parsed_output. Parsing happens in your process; if you rely on messages.parse() through QCode, try a small request first.

import os
from typing import Literal
import anthropic
from pydantic import BaseModel

client = anthropic.Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key=os.environ["QCODE_API_KEY"],   # key starts with cr_
)

class Ticket(BaseModel):
    title: str
    severity: Literal["low", "medium", "high"]
    components: list[str]
    needs_repro: bool

resp = client.messages.parse(
    model="claude-sonnet-5-5",
    max_tokens=2048,
    messages=[{"role": "user", "content": "Turn this bug report into a ticket:\n" + report_text}],
    output_format=Ticket,
)
ticket = resp.parsed_output
print(ticket.severity, ticket.components)

During conversion the SDK removes constraints the grammar can't enforce, such as minimum or maxLength, writes them into the field description and adds additionalProperties: false. The model sees the simplified schema, but the validating helper still checks every original constraint in your process. That means client-side validation can still fail, which is why the retry loop further down exists.

Method 2: JSON outputs with Zod (TypeScript)

import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";

const client = new Anthropic({
  baseURL: "https://api.qcode.cc/api",
  apiKey: process.env.QCODE_API_KEY,
});

const Ticket = z.object({
  title: z.string(),
  severity: z.enum(["low", "medium", "high"]),
  components: z.array(z.string()),
  needs_repro: z.boolean(),
});

const res = await client.messages.parse({
  model: "claude-haiku-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: `Turn this bug report into a ticket:\n${report}` }],
  output_config: { format: zodOutputFormat(Ticket) },
});
console.log(res.parsed_output);

If you'd rather not add Zod, jsonSchemaOutputFormat() from @anthropic-ai/sdk/helpers/json-schema takes a plain JSON Schema (declare it as const to get type inference). The docs note that this helper doesn't validate the response, so validate it yourself.

Raw HTTP

The same request without an SDK. The path is /api/v1/messages on QCode:

curl https://api.qcode.cc/api/v1/messages \
  -H "x-api-key: $QCODE_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-haiku-5-5",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Extract name and email: Jane Doe, jane@example.com"}],
    "output_config": {
      "format": {
        "type": "json_schema",
        "schema": {
          "type": "object",
          "properties": {"name": {"type": "string"}, "email": {"type": "string", "format": "email"}},
          "required": ["name", "email"],
          "additionalProperties": false
        }
      }
    }
  }'

The JSON arrives as a string in the text block of content. Newer SDKs send a later anthropic-version (the official curl example uses 2026-10-21); if you rely on a particular header version through QCode, test with a small request first.

Method 3: Strict tool use (structured arguments for actions)

tools = [{
    "name": "create_ticket",
    "description": "Create a ticket in the bug tracker. Call once per distinct bug.",
    "strict": True,
    "input_schema": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "severity": {"type": "string", "enum": ["low", "medium", "high"]},
            "component": {"type": "string"},
        },
        "required": ["title", "severity", "component"],
        "additionalProperties": False,
    },
}]

resp = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    tools=tools,
    tool_choice={"type": "auto"},   # 5.5 models accept only auto / none
    messages=[{"role": "user", "content": "Read these logs and call create_ticket for each bug:\n" + logs}],
)

for block in resp.content:
    if block.type == "tool_use" and block.name == "create_ticket":
        create_ticket(**block.input)   # input is already a dict matching input_schema

On Opus 5.5 and Sonnet 5.5, tool_choice: {"type": "any"} or {"type": "tool", ...} returns tool_choice: type "tool" and "any" are not supported for this model. Use auto plus strict, and say clearly in the prompt when the tool should be called. The Opus 5.5 / Sonnet 5.5 migration checklist has the full list of changes. Also note that toolset entries for computer use and browser use (computer_toolset_20260801, browser_toolset_20260801) don't accept strict, and neither do MCP toolset entries.

Combining both modes

A single request can carry strict tools and output_config.format. A typical agent pattern: strict tools for the actions it takes along the way, and a JSON output schema for the final report it hands back to your code. The grammar only applies to the final output and to tool inputs. It doesn't touch thinking blocks.

Validation and retries: from "almost always right" to "always usable"

Structured outputs guarantee the schema, not your business rules, and the docs list three exceptions. This pattern deals with all of them:

import json
from typing import Literal
from pydantic import BaseModel, ValidationError, field_validator

INVOICE_SCHEMA = {
    "type": "object",
    "properties": {
        "vendor": {"type": "string"},
        "invoice_number": {"type": "string"},
        "currency": {"type": "string", "enum": ["USD", "EUR", "CNY"]},
        "total": {"type": "number", "description": "Total including tax"},
        "due_date": {"type": ["string", "null"], "description": "YYYY-MM-DD or null"},
    },
    "required": ["vendor", "invoice_number", "currency", "total", "due_date"],
    "additionalProperties": False,
}

class Invoice(BaseModel):
    vendor: str
    invoice_number: str
    currency: Literal["USD", "EUR", "CNY"]
    total: float
    due_date: str | None

    @field_validator("currency", mode="before")
    @classmethod
    def normalize_case(cls, v):
        return v.upper() if isinstance(v, str) else v   # enum casing isn't guaranteed

def extract_invoice(text: str, retries: int = 2) -> Invoice:
    max_tokens = 2048
    for _ in range(retries + 1):
        resp = client.messages.create(
            model="claude-sonnet-5-5",
            max_tokens=max_tokens,
            output_config={
                "effort": "low",
                "format": {"type": "json_schema", "schema": INVOICE_SCHEMA},
            },
            messages=[{"role": "user", "content": "Extract the invoice fields:\n\n" + text}],
        )
        if resp.stop_reason == "refusal":
            raise RuntimeError("Model refused; inspect the input instead of retrying as-is")
        if resp.stop_reason == "max_tokens":
            max_tokens *= 2        # output was cut off; retry with more room
            continue
        raw = next(b.text for b in resp.content if b.type == "text")
        try:
            inv = Invoice.model_validate_json(raw)
        except ValidationError:
            continue
        if inv.total < 0:          # a business rule the grammar can't express
            continue
        return inv
    raise RuntimeError("No valid invoice after retries")

What each branch handles:

  • Refusal. HTTP 200 with stop_reason: "refusal". The generated tokens are billed and the output may not match the schema. Don't retry the same input. A field that asks the model to write out its step-by-step reasoning can trigger a reasoning_extraction refusal, so ask for a short justification instead.
  • max_tokens. The output was truncated and the JSON is incomplete. Thinking is on by default on the 5.5 models and max_tokens covers thinking and text together, so don't set it too low.
  • Enum casing. The docs say a value can come back differing only in case (often the first letter after a space), without an error. Compare case-insensitively and don't define enum values that differ only by case.
  • Read blocks by type. The reply can start with a thinking block, so select the text with b.type == "text" rather than content[0].
  • Property order. Required properties come first in the output, then optional ones. If order matters, make every property required, as above, and use ["string", "null"] for nullable fields.

Streaming and partial JSON

JSON outputs stream like any reply, but until the stream ends you hold incomplete JSON. Accumulate and parse at the end:

chunks = []
with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=4096,
    output_config={"format": {"type": "json_schema", "schema": INVOICE_SCHEMA}},
    messages=[{"role": "user", "content": "Extract the invoice fields:\n\n" + text}],
) as stream:
    for piece in stream.text_stream:
        chunks.append(piece)      # a tolerant partial-JSON parser can update your UI here
data = json.loads("".join(chunks))

Tool input streaming works differently. Set "eager_input_streaming": true on the tool and the input arrives as partial_json fragments in input_json_delta events. Concatenate them and parse on content_block_stop. The docs warn that this fine-grained streaming is not buffered or validated server-side, so the assembled string may not be valid JSON. When that happens, return a tool_result with is_error: true that wraps the raw string as {"INVALID_JSON": "..."} and let the model recover.

Writing schemas that compile

Limit Value Notes
Strict tools per request 20 Non-strict tools don't count
Optional parameters in total 24 Across all strict tools and the JSON output schema
Union-typed parameters in total 16 Parameters using anyOf or a type array such as ["string", "null"]
Grammar compile timeout 180 s Longer compiles fail

Past the internal limit you get a 400: Schema is too complex for compilation. Reduce complexity in this order: mark only critical tools strict, make parameters required where you can, flatten nesting, and split large strict tool sets across requests or subagents.

Supported: basic types, enum and const, anyOf and allOf (with exceptions), $ref and $defs, common string formats (date-time, date, email, uri, uuid and others), and array minItems of 0 or 1. Not supported: recursive schemas, oneOf (use anyOf), not, external $ref, minimum / maximum / multipleOf, minLength / maxLength, and complex regex (backreferences, lookaround). Unsupported features return a 400 with details.

Objects with unknown keys. Because additionalProperties must be false, the model can only return keys you listed. When keys aren't known in advance, use an array of {"key": ..., "value": ...} objects instead.

Compatibility. The docs say it works with batch processing, token counting and streaming, but not with Citations (enabling both returns 400) or with message prefill.

Latency and cost tips

  • The first request is slower. A schema's grammar is compiled on first use and cached for 24 hours from last use. Changing the schema structure, or the set of tools when tools are present, invalidates it. Changing only a name or description doesn't.
  • Keep the schema stable. Changing output_config.format invalidates the prompt cache for that conversation. Treat the schema as a constant and don't rebuild it with a different field order per request. More on cache economics in the prompt caching cost guide.
  • The injected prompt is billed. Structured outputs add a system prompt, so input tokens rise slightly.
  • Match the model to the job. Field extraction and classification often run fine on Haiku 5.5, at the official $0.10 / $0.50 per million tokens for prompts up to 100K (the whole request bills at $0.50 / $2.50 above 100K). Use Sonnet 5.5 ($2 / $10) for structures that need reasoning, and set effort to low to cut thinking tokens. See the Haiku 5.5 guide.
  • Offline bulk jobs. The official Batch API is 50% off and supports structured outputs. Availability through QCode isn't documented; test with a small request first if you plan to rely on it.
  • QCode bills at the official price × 1.0. Live prices are on /models.

What about GPT models?

The same QCode key also reaches GPT models, but only through the OpenAI-compatible endpoint (https://api.qcode.cc/openai/v1), and structured output there uses OpenAI's own parameters rather than output_config; confirm the exact parameters with a small test request first. Claude models, in turn, only work through the Anthropic endpoint. For tool calling and caching on the Responses API, see GPT-6.2 Sol Responses API tool calling and caching.

FAQ

Do Claude structured outputs need a beta header?

No. The docs list the feature as generally available, using output_config.format. Only the deprecated output_format parameter needs the structured-outputs-2025-11-13 header; without it, you get a 400.

Which models support structured outputs?

All current models, according to the docs, including claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-2, as well as Opus 4.6–4.8, Sonnet 4.5 / 4.6 and Haiku 4.5. Use the same model IDs through QCode.

Should I use JSON outputs or strict tool use?

Use JSON outputs when you want a structured answer. Use strict tools when the model should decide which action to take and supply structured arguments. You can combine them in one request.

Why did a structured output still not match my schema?

The documented exceptions are refusals (stop_reason: "refusal") and truncation at max_tokens. Enum casing isn't guaranteed either. Check stop_reason, validate client-side and retry a bounded number of times.

How do I fix "Schema is too complex for compilation"?

Your strict schemas together exceed the compile limit. Use fewer strict tools, make optional parameters required, cut anyOf and nullable types, flatten nesting, or split tools across requests.

Can structured outputs stream?

Yes, like normal text, but you can only parse the full JSON after the stream ends. Tool inputs can stream with eager_input_streaming, but the assembled string may be invalid JSON and needs error handling.

Do I need to change code to use structured outputs through QCode?

Set the SDK base URL to https://api.qcode.cc/api and use your QCode key; the request body is the same as create, and parsing happens client-side. If you rely on messages.parse() through QCode, test it with a small request first. Claude models can't be called through /openai/v1.

Can I put PHI or other sensitive data in the schema?

No. The docs say the schema is cached separately for up to 24 hours and doesn't get the same protection as prompts and responses. Keep PHI out of property names, enums, const values and patterns, and send sensitive data only in message content.

Which plan fits

Structured outputs mostly power data pipelines, extraction scripts and small tools whose volume goes up and down, which doesn't always justify a monthly plan. QCode pay-as-you-go packs start from $4, need no subscription, last 7 days, and bill at the official price × 1.0. Details are on /pay-as-you-go. If usage settles into a steady daily volume, compare the daily-quota plans on /pricing.

Which plan fits

One key for both the Anthropic Messages API and OpenAI-compatible APIs. Claude and GPT are billed at the official price ×1.0; live rates are on /models.

Not sure where to start?

Try it for a week

Small Pack: $4 for $30 of quota, valid 7 days

Use it every day

Starter: $9.00/month with $5 of quota every day — just $0.060 per $1 of quota, vs about $0.113 for the Medium Pack