{"slug": "structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output", "title": "Structured Outputs from LLMs: JSON Schema, Validation and Retry on Bad Output", "summary": "A technical guide recommends combining three layers to get reliable structured data from large language models: a Pydantic schema defining the output shape, provider-side schema enforcement, and validation with retry in application code. The guide documents that Anthropic, OpenAI and Gemini now all support constraining model output to a JSON Schema — Anthropic via `output_config.format` with `type: \"json_schema\"`, OpenAI via `text.format` or `response_format` with `strict: true`, and Gemini via `response_format` with a MIME type and `schema` — and shows a Pydantic `Invoice` model using `extra=\"forbid\"` to emit `additionalProperties: false` plus a `model_validator` that rejects totals off by more than 0.01 from the line items. The guide advises stopping on refused or truncated responses, sending validation errors back to the model while retry attempts remain, and failing loudly when they run out.", "body_md": "Sooner or later your app has to do something with a model's answer. Show it in a UI, save it to a database, pass it to another service. For that, you need data, not prose.\n\nThe old way was to write \"respond only with JSON\" in the prompt and hope. It works until it doesn't: a stray sentence before the opening brace, a missing field, a string where you wanted a number, or a response cut off mid-object.\n\nThe fix is three layers that work together: a **schema** that defines the shape, **enforcement** by the provider, and **validation plus retry** in your code.\n\n**Sources:** the API details come from the official Anthropic, OpenAI, Gemini and Pydantic documentation. These APIs change quickly, so check the current docs before you ship.\n\n``` php\nflowchart TD\n    A[\"Prompt + JSON Schema\"] --> B[\"LLM call\"]\n    B --> C{\"Refused or truncated?\"}\n    C -- Yes --> D[\"Stop and handle it\"]\n    C -- No --> E[\"Parse and validate\"]\n    E --> F{\"Valid?\"}\n    F -- Yes --> G[\"Use the result\"]\n    F -- No --> H{\"Attempts left?\"}\n    H -- Yes --> I[\"Send the errors back to the model\"]\n    I --> B\n    H -- No --> J[\"Fail loudly\"]\n```\n\n## Step 1: Define the shape once\n\nWrite the structure as a Pydantic model. It gives you a JSON Schema for the provider and a validator for your code, from one definition:\n\n``` python\nfrom pydantic import BaseModel, ConfigDict, model_validator\n\nclass Strict(BaseModel):\n    model_config = ConfigDict(extra=\"forbid\")  # adds \"additionalProperties\": false\n\nclass LineItem(Strict):\n    description: str\n    quantity: float\n    unit_price: float\n\nclass Invoice(Strict):\n    invoice_number: str\n    customer_name: str\n    line_items: list[LineItem]\n    total_amount: float\n\n    @model_validator(mode=\"after\")\n    def total_matches_line_items(self):\n        expected = sum(item.quantity * item.unit_price for item in self.line_items)\n        if abs(expected - self.total_amount) > 0.01:\n            raise ValueError(\n                f\"total_amount is {self.total_amount}, \"\n                f\"but the line items add up to {expected:.2f}\"\n            )\n        return self\n\nschema = Invoice.model_json_schema()\n```\n\nTwo details matter here. `extra=\"forbid\"` makes Pydantic emit `additionalProperties: false`, which the strict modes of both Anthropic and OpenAI expect. And because no field has a default, every field is listed as required.\n\nUse clear field names. A descriptive name like `unit_price` guides the model better than `p`, and you can add `Field(description=...)` for anything ambiguous.\n\n## Step 2: Let the provider enforce the schema\n\nAll three major providers can now constrain the model's output to a schema. Anthropic describes its version as constrained decoding: generation is steered so the output can't break the schema, which means syntax errors and missing fields disappear.\n\n| Provider | Where the schema goes | Python helper | \n|---|---|---|\n| Anthropic | `output_config.format` with`type: \"json_schema\"` | `client.messages.parse(output_format=Model)` , result in`parsed_output` | \n| OpenAI (Responses API) | `text.format` with`strict: true` | `client.responses.parse(text_format=Model)` , result in`output_parsed` | \n| OpenAI (Chat Completions) | `response_format` with`strict: true` | `client.chat.completions.parse(response_format=Model)` , result in`message.parsed` | \n| Gemini | `response_format` with a MIME type and`schema` | Pass `Model.model_json_schema()` , then call`Model.model_validate_json(response.text)` | \n\nOlder Gemini examples use `response_mime_type` and `response_json_schema` instead, so check which one your SDK version expects.\n\nWith Claude, the shortest path is the SDK helper:\n\n``` python\nfrom anthropic import Anthropic\n\nclient = Anthropic()\n\nresponse = client.messages.parse(\n    model=\"claude-sonnet-5-5\",\n    max_tokens=2048,\n    messages=[{\"role\": \"user\", \"content\": \"Extract the invoice data: ...\"}],\n    output_format=Invoice,\n)\ninvoice = response.parsed_output\n```\n\nThe helper converts your model into a schema the API accepts, sends it, and validates the response against your original model, including constraints the API can't enforce itself.\n\nDon't confuse this with plain \"JSON mode\". OpenAI's docs are clear that JSON mode guarantees valid JSON but not that it matches your schema. Always prefer the schema version.\n\n### Know the schema limits\n\nProviders support a subset of JSON Schema. For Anthropic, that means:\n\n- No recursive schemas, `oneOf` or`not` . Use`anyOf` instead.\n- No numeric limits ( `minimum` ,`maximum` ) or string length limits (`minLength` ,`maxLength` ).\n- `additionalProperties` must be`false` on every object.\n- A cap on complexity, including 24 optional parameters and 16 union-typed parameters per request.\n\nUsing an unsupported keyword in a raw schema returns a 400 error. The SDK helpers sidestep this by moving those constraints into the field description and checking them after the response arrives.\n\n**Heads up:** don't use `dict` fields in a Pydantic model for Claude. The SDK sends them as an object with no properties, so the model can only return `{}`. Use a nested model, or a list of `{key, value}` items.\n\n## Step 3: Validate anyway\n\nIt's tempting to stop after step 2. Don't. OpenAI's docs say outright that your app still has to handle refusals, incomplete responses and any business rules the schema doesn't express. Anthropic's docs list the same kinds of exceptions. A valid shape is not the same as a correct answer.\n\n| Layer | What it catches | What it misses | \n|---|---|---|\n| Constrained decoding | Invalid JSON, missing fields, wrong types | Refusals, truncation, wrong values | \n| Pydantic validation | Out-of-range values, business rules, bad enum values | Plausible but wrong answers | \n| Retry with feedback | One-off mistakes | A model that systematically misreads the input | \n\nThese are the cases the schema can't save you from:\n\n- **Refusals.** If Claude declines for safety reasons, the response has`stop_reason: \"refusal\"` with a 200 status, and the output may not match your schema. OpenAI exposes a`refusal` field on the message.\n- **Truncation.** When the model hits`max_tokens` (OpenAI calls it`finish_reason: \"length\"` ), you get incomplete JSON even with strict mode on.\n- **Constraints the API can't express.** Number ranges, string lengths, and anything involving more than one field.\n- **Enum case drift.** Anthropic notes that capitalization of enum values isn't guaranteed. Compare case-insensitively.\n- **Business rules.** In the model above, nothing in the schema says the total must equal the sum of the line items. The validator does.\n\nTreat model output like any other untrusted input. If it contains an ID, check that the ID exists before you use it.\n\n## Step 4: Retry with the error, not just \"try again\"\n\nWhen validation fails, the best retry tells the model exactly what was wrong. Show it its own output and the specific errors:\n\n``` python\nfrom pydantic import ValidationError\n\nclass StructuredOutputError(Exception):\n    pass\n\ndef describe(error: ValidationError) -> str:\n    lines = []\n    for item in error.errors(include_url=False, include_input=False):\n        where = \".\".join(str(part) for part in item[\"loc\"]) or \"(whole output)\"\n        lines.append(f\"- {where}: {item['msg']}\")\n    return \"\\n\".join(lines)\n\ndef extract(call_llm, prompt, model_cls, max_attempts=3):\n    messages = [{\"role\": \"user\", \"content\": prompt}]\n\n    for _ in range(max_attempts):\n        text, status = call_llm(messages)\n\n        if status == \"refused\":\n            raise StructuredOutputError(\"The model refused the request.\")\n        if status == \"truncated\":\n            raise StructuredOutputError(\"Output hit the token limit. Raise max_tokens.\")\n\n        try:\n            return model_cls.model_validate_json(text)\n        except ValidationError as error:\n            messages += [\n                {\"role\": \"assistant\", \"content\": text},\n                {\n                    \"role\": \"user\",\n                    \"content\": \"Your JSON was invalid:\\n\"\n                    + describe(error)\n                    + \"\\nReturn the corrected JSON only.\",\n                },\n            ]\n\n    raise StructuredOutputError(f\"Still invalid after {max_attempts} attempts.\")\n```\n\n`model_validate_json` handles both problems in one call: bad JSON and a bad shape both raise `ValidationError`. Broken JSON shows up as an error of type `json_invalid`.\n\nHere is the adapter that plugs Claude into it. It uses the raw schema from step 1 and maps the stop reasons to the statuses the loop understands:\n\n``` python\ndef call_claude(messages):\n    response = client.messages.create(\n        model=\"claude-sonnet-5-5\",\n        max_tokens=2048,\n        messages=messages,\n        output_config={\"format\": {\"type\": \"json_schema\", \"schema\": schema}},\n    )\n    status = {\"refusal\": \"refused\", \"max_tokens\": \"truncated\"}.get(response.stop_reason, \"ok\")\n    text = next((block.text for block in response.content if block.type == \"text\"), \"\")\n    return text, status\n\ninvoice = extract(call_claude, \"Extract the invoice data: ...\", Invoice)\n```\n\n**Heads up:** this raw-schema version sends exactly what `model_json_schema()` produces. If your model has `Field(ge=1, le=5)` style limits, those become `minimum` and `maximum` in the schema, and Claude's API rejects them. Either keep such checks in validators, as in step 1, or use `client.messages.parse`, which handles the conversion.\n\nA few rules make this loop behave well:\n\n- **Retry only validation failures.** A refusal or a truncated response won't be fixed by sending the same request again. Raise the token limit for truncation, and surface refusals to the caller.\n- **Be specific.** A field path and a message gives the model something to act on. \"Try again\" doesn't.\n- **Cap the attempts** at two or three, then fail loudly, fall back to a default, or queue the item for a human.\n- **Keep API errors separate.** Timeouts and rate limits need backoff and a plain retry of the same request, not an error message to the model.\n- **Know when the input is the problem.** If the source document is itself inconsistent, say an invoice whose printed total is wrong, no number of retries will fix it. Let those failures reach a person.\n\n## Production tips\n\n- **Keep schemas small and flat.** Simpler schemas compile faster and leave less room for error. Make fields required where you can, since each optional field adds complexity.\n- **Expect a slower first request.** Anthropic compiles each new schema into a grammar on first use, then caches it for 24 hours.\n- **Give the model an exit.** If a field can legitimately be missing from the source, make it nullable. Otherwise the model has to invent a value.\n- **Don't ask for reasoning inside the JSON.** Anthropic warns that fields requesting step-by-step thinking can trigger refusals. Ask for a short explanation instead.\n- **Accumulate before parsing.** When you stream, collect the full response first. Partial JSON isn't valid JSON.\n- **Track your retry rate.** A rising rate means your prompt, schema or model needs attention. Log the raw failing output so you can see why.\n\n## Checklist\n\n- One Pydantic model defines both the schema and the validation.\n- Native structured outputs are on, with `additionalProperties: false` .\n- Refusals and truncation are handled before parsing.\n- Business rules live in validators, not in the prompt.\n- Retries send back specific errors and stop after a few attempts.\n- Failures are logged with the raw output.\n\nStart with the schema and native enforcement, since that removes most of the pain. Then add validation and one retry for everything it can't promise.", "url": "https://wpnews.pro/news/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output", "canonical_source": "https://zyvop.com/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output-ydyga", "published_at": "2026-11-24 02:30:00+00:00", "updated_at": "2026-11-24 02:44:50.663358+00:00", "lang": "en", "topics": ["large-language-models", "structured-data", "ai-tools", "developer-tools"], "entities": ["Anthropic", "OpenAI", "Gemini", "Pydantic", "Claude"], "also_reported_by": [], "takeaway": "Define the output shape once as a Pydantic model with `extra=\"forbid\"` so it emits `additionalProperties: false` for Anthropic and OpenAI strict modes, then feed validation errors back to the model on retry and fail loudly when attempts run out.", "recommendation": {"advice": "Pair provider-enforced JSON Schema output with Pydantic validation and error-fed retries, and stop rather than parse when a response is refused or truncated.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output", "markdown": "https://wpnews.pro/news/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output.md", "text": "https://wpnews.pro/news/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output.txt", "jsonld": "https://wpnews.pro/news/structured-outputs-from-llms-json-schema-validation-and-retry-on-bad-output.jsonld"}}