FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Strict schemas still let refusals and truncated JSON through

A Claude refusal comes back with status 200 and a token bill, so your code has to read the stop signal before it parses.

ShareLinkedInFacebookX

In brief

  • With Claude, a refusal still returns status 200, still bills tokens, and its JSON may not match the schema
  • JSON cut off by max_tokens carries its own signal; Anthropic's guidance is to resend with a higher max_tokens
  • JSON that matches the schema may still hold wrong values: always validate them in your application
Decision tree: check stop_reason before parsing JSON. If it is refusal, send the response to a queue for human review, with no blind retry. If it is max_tokens, retry with 1024, then 2048, then 4096 tokens, and stop after 3 attempts. In all other cases, call json.loads and then validate, because the values can still be wrong.
With Claude, a refusal still returns status 200 and is still billed for tokens. Each stop_reason value needs its own handling before the JSON can be trusted. Source: Anthropic's structured outputs documentation, as cited in the article.

The response returns status 200 and the tokens are billed in full, yet the JSON inside does not match the schema you sent. With Claude, this can be a refusal rather than a system error. Anthropic’s documentation says so plainly: when the model refuses, the refusal message takes precedence over the schema constraints.

It is easy to assume that turning on strict is enough. In practice, strict only guarantees the structure of the JSON when the model answers in full. Two other outcomes remain: the model refuses, or the output is cut off at the token limit. A Claude refusal looks just like a successful response. Truncated output has its own stop signal, but only code that reads the signal will see it.

For an FDE putting a data extraction pipeline into a client’s systems, these three branches are where a demo and a production system part ways. The guide below builds them one at a time, in the order they need to be checked.

What will you build, and what do you need?

The running example is hypothetical. A function called extract_invoice(text) reads a client’s invoice emails and returns a dict with the vendor, invoice number, total and currency. When there is no usable result, it raises a clearly named error instead of letting arbitrary exceptions escape.

You need Python, an API key for Claude or OpenAI, and a few sample emails. The code blocks below have been shortened to make the logic easy to follow. Check the exact field names and SDK calls against your provider’s current documentation.

Step 1: Which schemas will the API accept?

Start with the schema, because many 400 errors begin here. Anthropic allows additionalProperties to be set only to false, and does not support recursive schemas, external $refs, or numeric and string constraints.

Simon Willison, writing about OpenAI’s strict mode, adds that every key of an object must be in required there. The schema below follows both rules so that it works with either provider.

INVOICE_SCHEMA = {
    "type": "object",
    "properties": {
        "vendor": {"type": "string"},
        "invoice_number": {"type": "string"},
        "total": {"type": "number"},
        "currency": {"type": "string"},
    },
    "required": ["vendor", "invoice_number", "total", "currency"],
    "additionalProperties": False,
}

Note what has been left out on purpose: total has no minimum, and currency has no length limit. With Anthropic, using an unsupported feature returns a 400 error with details. For Gemini, Google also warns that a schema that is too large or too deeply nested may be rejected with 400 INVALID_ARGUMENT.

Check: send a test request. If you get a 400, read the error details and fix the schema before writing another line of code.

Step 2: Send the request with the schema

With Claude, the schema goes in output_config.format with type: "json_schema", and the valid JSON arrives in a text content block of the response. In shortened form:

request = {
    "model": MODEL,
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": prompt}],
    "output_config": {
        "format": {"type": "json_schema", "schema": INVOICE_SCHEMA}
    },
}

If you use OpenAI, do not confuse JSON mode with Structured Outputs. OpenAI states that both produce valid JSON but only Structured Outputs guarantees a schema match, and it recommends always using Structured Outputs. Willison reckons that 99% of the time you will want to set "strict": true.

Check: measure latency from the second request onward. Willison notes that the first request with each schema is slow because the schema has to be preprocessed. Benchmark on that first request and you will only alarm yourself.

Step 3: Read the stop signal before parsing

This is the step most easily skipped. Do not call json.loads right away. With Claude, a refusal has a stop_reason of refusal, while truncated output has a stop_reason of max_tokens, in which case the JSON may be incomplete.

class Refused(Exception): pass
class Truncated(Exception): pass

def read_claude(response):
    if response.stop_reason == "refusal":
        raise Refused(response)
    if response.stop_reason == "max_tokens":
        raise Truncated(response)
    text = next(b.text for b in response.content if b.type == "text")
    return json.loads(text)

On OpenAI, the signals sit elsewhere. Truncated output has a response.status of incomplete, with incomplete_details.reason set to max_output_tokens. Willison describes a refusal as arriving in a separate refusal message in place of JSON that follows the schema. Because a refusal may not follow the schema, the API adds a refusal field that you must check before reading the parsed content.

# Shortened: the exact location of the refusal field and the content
# depends on the endpoint you use; check the OpenAI documentation
def read_openai(response, output):
    if response.status == "incomplete" and \
       response.incomplete_details.reason == "max_output_tokens":
        raise Truncated(response)
    if getattr(output, "refusal", None):
        raise Refused(output.refusal)
    return json.loads(output.text)
Situation Claude OpenAI
Model refuses stop_reason is refusal, status 200, tokens still billed Separate refusal field, does not follow the schema
Cut off by the token limit stop_reason is max_tokens status is incomplete, reason max_output_tokens
What to do before parsing Read stop_reason Read status, then the refusal field

Step 4: Retry truncated output, with a stopping point

Anthropic’s guidance is to resend with a higher max_tokens to get the full JSON. The rest is yours to design. One sensible approach is to double the limit each time, from 1024 to 2048 to 4096, and stop after three attempts so that one abnormal email does not burn tokens indefinitely.

def extract_invoice(text, budgets=(1024, 2048, 4096)):
    for max_tokens in budgets:
        try:
            return read_claude(call(text, max_tokens))
        except Truncated:
            continue
    raise Truncated("token budget exhausted")

Refusals need very different handling: do not retry them blindly. Each one still bills tokens, and there is no reason to expect a different result from the same input. Send these cases to a queue for human review.

Check: run call(text, 50) on a long email. The Truncated branch must fire, and json.loads must not raise a parse error.

Step 5: A matching schema does not mean correct values

Google says it directly in the Gemini documentation: the values in syntactically correct JSON still have to be validated in the application. The constraints you removed from the schema in step 1 are rewritten here, in code you control.

def validate(inv):
    errors = []
    if inv["total"] < 0:
        errors.append("total is negative")
    if len(inv["currency"]) != 3:
        errors.append("currency is not a 3-character code")
    if not inv["invoice_number"].strip():
        errors.append("invoice number is missing")
    return errors

Take an email that says only “total as per last week’s quote.” Every key is in required, so the schema demands them all, and you may well get back an empty invoice_number. The schema matches perfectly, but the client’s accounting system will not accept the row.

Which mistakes are easy to make?

One is parsing first and checking afterward: a refusal is then easily mistaken for a JSON error and logged in the wrong category. Another is leaving optional keys out of required in OpenAI’s strict mode. Nor should you cram business rules into the schema, unless you are willing to lose an afternoon to debugging 400 errors.

If you use strict tool use in place of an output format, remember that Anthropic limits each request to 20 strict tools. An agent whose tool list keeps growing will hit that limit sooner than you expect.

How does this skill show up at a client?

At the first review on real data, suppose the client asks what percentage of cases the pipeline handles. The three failure branches above give you the answer: count refusals, truncations and records that fail validation separately. Put those three numbers on a dashboard in the first week, before anyone asks.

For your career, a resume line such as “built an extraction pipeline with strict schemas, handling refusals and truncated output separately, with error metrics by type” shows a recruiter that you have shipped something to production. When a job description mentions “LLM in production,” this may well be the skill the employer needs.

Getting output that fits the schema is the easy part of structured outputs. What makes you valuable is knowing what to do when the output is invalid.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
4 sources
Read next on the roadmap · Stage 2: Broad engineeringThe grid data mismatch FDEs should not rush to fixAt electric utilities, GIS records how the network was designed to run and SCADA how it is running now; missing that can cost weeks of needless repairs.