الانتقال إلى المحتوى
أساسيات الـ AIPrompt Engineering· 7 دقائق للقراءة

'Respond in JSON' Isn't a Contract: Getting Structured Output You Can Trust

A format instruction makes JSON likely, not certain. Constrained decoding guarantees the shape; your code still checks the meaning.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

An invoice-extraction job passes every test in the notebook. The prompt ends with "Respond ONLY with valid JSON. No other text." In production, the nightly run stops on 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

"If the prompt says 'respond only with valid JSON', I'll get parseable, correct data." It's easy to believe:

  • 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.

The half-truth: instructions do raise the odds a lot. But "reliably" isn't "always", and an instruction can't change which tokens are possible. It also says nothing about whether the values are right.

What actually happens

An instruction changes probabilities, not possibilities

The model writes its reply one token at a time, sampling from a probability distribution. Your instruction makes JSON tokens far more likely. It doesn't remove the others, so a polite preamble, a code fence, a trailing comment, "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.

How often depends on the model and the task. In Tam and colleagues' 2024 study, models asked for JSON through prompt instructions ranged from near-zero parsing failures for GPT-3.5 Turbo and Gemini 1.5 Flash to 60% of Claude 3 Haiku's answers on the GSM8K math benchmark. Those are older models, and the point isn't the rate. It's that the rate is a property of one model on one task, and it changes when either does.

Constrained decoding changes what can be generated

Structured outputs move the guarantee from the model's habits to the decoder. You send a in 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.

Some costs come with it. The first request with a new schema waits while the grammar compiles; compiled grammars are cached for 24 hours after their last use. The API adds a system prompt describing the format, which you pay for in input tokens. And only a subset of JSON Schema is supported: constraints such as 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.

The old tricks are closing. Starting with the Claude 4.6 models, prefilling the last assistant turn returns a 400 error, and on Claude Opus 5.5 forcing a tool with tool_choice does too. In both cases Anthropic points to structured outputs instead.

What the guarantee doesn't cover

The docs list the exceptions. If Claude refuses, the response has 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

A schema checks shape, never truth. Worse, it can push the model to invent: if 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?

Field order matters too. In the same study, GPT-3.5 Turbo in JSON mode put the 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.

Python extract_invoice.py
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 breaks

client.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.

BeliefReality
"Respond only in JSON" guarantees parseable outputIt raises the odds; fences, preambles and truncation still happen
A schema in the prompt enforces typesOnly constrained decoding (output_config.format, strict: true) does
Structured outputs never failRefusals and max_tokens can break the schema; enum casing can differ
Schema-valid means correctA required field gets filled even when the source has no value
Prefill { or force a tool to get JSONOn Claude Opus 5.5, both return a 400 error

How to apply it in your project

  1. Move the format out of the promptSend a schema with output_config.format, or strict: true on tools, instead of describing JSON in words. Keep the prompt for what to extract and how to handle edge cases.
  2. Model missing and uncertain dataAllow null wherever the source might not have a value, and use an enum for categories, compared case-insensitively.
  3. Check `stop_reason` firstTrust the schema only when the reply ended normally. Log refusals and max_tokens cut-offs and handle them on their own path.
  4. Validate meaning in codeWrite the business checks a schema can't express: totals that add up, dates in range, IDs that exist in your database.
  5. Measure on real documentsRun 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.

📚 المصادر

  1. Structured outputs — Claude API Docs
  2. Strict tool use — Claude API Docs
  3. Define tools: forcing tool use — Claude API Docs
  4. Prompting best practices: migrating away from prefilled responses — Claude API Docs
  5. 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)