
'Respond in JSON' Isn't a Contract: Getting Structured Output You Can Trust
- كاتب موثّق
محتويات المقال
json.loads with "Expecting value: line 1 column 1": one reply began with a Markdown fence. The next week finance finds totals stored as text, "1,240.50", which the VAT report silently skipped. Nobody changed the prompt. It was never a contract.
The common misconception
It works most of the time. Modern models write JSON well, and a dozen manual tests all parse. Anthropic's own prompting guide says newer models can reliably match complex schemas when told to, especially with retries. Old tricks felt like guarantees: prefilling the reply with {, or forcing a tool call to get arguments as JSON.Valid JSON looks like data, so it's easy to assume the values are as trustworthy as the syntax.
What actually happens
An instruction changes probabilities, not possibilities
"2" instead of 2 or a missing field remain possible. Anthropic's docs list exactly these failures for prompting without structured outputs: invalid JSON syntax, missing required fields, inconsistent data types and schema violations. And when a reply hits max_tokens, it ends mid-object whatever the prompt said.
Constrained decoding changes what can be generated
output_config.format, the API compiles it into a grammar, and at each step it limits sampling to tokens that keep the output valid. That's . Anthropic's docs promise no more parse errors, guaranteed field types and required fields, and no retries for schema violations. Strict tool use (strict: true) applies the same grammar to tool inputs.
minimum or maxLength aren't enforced by the grammar. The SDK helpers move them into field descriptions and check them when they validate the response.
tool_choice does too. In both cases Anthropic points to structured outputs instead.
What the guarantee doesn't cover
stop_reason: "refusal" and may not match the schema. If it hits the token limit, stop_reason is "max_tokens" and the JSON may be incomplete. String enum values can come back with different capitalization, with no error at all. And required properties are emitted before optional ones, so field order can differ from your schema.
Valid JSON can still be wrong data
number is a required string and the invoice has no number, the grammar still demands a string. Give the model a legal way to say "not there" by making such fields nullable, then check the meaning in code: do line items add up to the total, is the currency one you support?
answer key before the reason key in every response on one task, so it answered before reasoning. With Claude, the grammar applies only to the final output, not to thinking, so Claude can reason freely first. Anthropic also warns that a field asking for step-by-step reasoning can trigger a refusal; ask for a short explanation instead.
import jsonimport anthropicclient = anthropic.Anthropic()SYSTEM = ("Extract the invoice. Respond ONLY with valid JSON with the keys " "vendor, number, currency, total and due_date. No other text.")reply = client.messages.create( model="claude-opus-5-5", max_tokens=16000, system=SYSTEM, messages=[{"role": "user", "content": invoice_text}],)text = next(b.text for b in reply.content if b.type == "text")invoice = json.loads(text) # JSONDecodeError the day text starts with ```print(invoice["total"]) # "1,240.50": a string, so the VAT math breaksimport anthropicfrom pydantic import BaseModelclass Invoice(BaseModel): vendor: str number: str | None # null is a legal answer, so it needn't invent one currency: str total: float due_date: str | Noneclient = anthropic.Anthropic()reply = client.messages.parse( model="claude-opus-5-5", max_tokens=16000, output_format=Invoice, system="Extract the invoice. Use null for fields it doesn't show.", messages=[{"role": "user", "content": invoice_text}],)if reply.stop_reason in ("refusal", "max_tokens"): raise RuntimeError(f"No schema guarantee: {reply.stop_reason}")invoice = reply.parsed_outputprint(invoice.total) # 1240.5: a float, as the schema saysclient.messages.parse() turns the Pydantic model into a schema, sends it as output_config.format, validates the response and returns an Invoice in parsed_output. The prompt still matters, for what to extract and when to use null, but it no longer carries the format.
output_config.format, strict: true) does | |
max_tokens can break the schema; enum casing can differ | |
{ or force a tool to get JSON |
How to apply it in your project
Move the format out of the prompt Send a schema with output_config.format, orstrict: trueon tools, instead of describing JSON in words. Keep the prompt for what to extract and how to handle edge cases.Model missing and uncertain data Allow nullwherever the source might not have a value, and use an enum for categories, compared case-insensitively.Check `stop_reason` first Trust the schema only when the reply ended normally. Log refusals and max_tokenscut-offs and handle them on their own path.Validate meaning in code Write the business checks a schema can't express: totals that add up, dates in range, IDs that exist in your database. Measure on real documents Run the extractor on a set of real inputs with known answers and track field-level accuracy, not just parse success.
Key takeaways
A format instruction makes JSON likely; only constrained decoding makes the shape guaranteed. Structured outputs remove parse errors and type mismatches, but not refusals, truncation or enum casing quirks. A schema validates shape, never truth, and a required field forces the model to put something there. Make missing data legal with nullable fields, and check the values with business rules in code. On Claude Opus 5.5, prefill and forced tool calls no longer work for getting JSON; use structured outputs.
📚 المصادر
Structured outputs — Claude API Docs Strict tool use — Claude API Docs Define tools: forcing tool use — Claude API Docs Prompting best practices: migrating away from prefilled responses — Claude API Docs Tam et al., Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models, arXiv:2408.02442
التعليقات (0)