Enforcing JSON Schemas on LLM Output
Constrain model output to a schema, validate every response before trusting it, and repair or retry invalid payloads without looping forever or hiding failures.
On this page
Introduction
As soon as a language model feeds another program, free text becomes a liability. Downstream code needs a predictable shape: a field that is always present, a number that is actually a number, an enum that never invents a new category. Models are excellent at producing plausible JSON and equally capable of wrapping it in prose, omitting a required field or emitting a trailing comma. Treating that output as trusted input is how a parser crash turns into a production incident, so the discipline is to specify the schema, validate against it and handle the failures explicitly.
Why Models Drift from Structure
A model optimizes for likely text, and likely text about a topic often includes explanation before the JSON and a friendly sentence after it. Left unconstrained it will helpfully add a note, rename a field to something it considers clearer, or return an array where you expected an object. Temperature above zero adds variability, and long outputs risk truncation mid value. None of these are model bugs; they are the expected behaviour of a system that predicts text rather than obeying a type.
import json
from jsonschema import Draft202012Validator, ValidationError
SCHEMA = {
"type": "object",
"properties": {
"title": {"type": "string", "minLength": 1},
"priority": {"enum": ["low", "medium", "high"]},
"tags": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
},
"required": ["title", "priority"],
"additionalProperties": False,
}
_validator = Draft202012Validator(SCHEMA)
def validate_payload(raw: str) -> dict:
try:
obj = json.loads(raw)
except json.JSONDecodeError as e:
raise ValueError(f"not valid JSON: {e}") from e
errors = sorted(_validator.iter_errors(obj), key=lambda e: e.path)
if errors:
# Surface the first error so the repair prompt can target it.
first = errors[0]
raise ValueError(f"schema violation at {list(first.path)}: {first.message}")
return obj
Specifying the Schema in the Prompt
Give the model the contract explicitly and, where the provider supports it, use structured output modes that constrain decoding to the schema rather than merely describing it. Include the schema, a short description of each field and one worked example, because examples anchor format better than prose rules. State the failure mode you want, such as returning null for unknown values instead of guessing. Ask for no surrounding text, and still validate, because a prompt instruction is a strong hint, not a guarantee.
MAX_ATTEMPTS = 2
def extract(call_model, prompt: str) -> dict:
last_error = None
correction = ""
for attempt in range(MAX_ATTEMPTS + 1):
raw = call_model(prompt + correction)
try:
return validate_payload(raw)
except ValueError as e:
last_error = e
# Feed the exact error back only for the next attempt.
correction = (
f"\n\nYour previous output was rejected: {e}. "
"Return only a corrected JSON object with no extra text."
)
raise RuntimeError(f"model failed schema after {MAX_ATTEMPTS + 1} attempts: {last_error}")
Validating Before Trusting
Parse the response and validate it against the same schema with a real validator, treating any exception as a normal control flow path rather than an unexpected crash. Report which field failed and why, so the retry can include that detail in the correction request. Reject unknown properties if strictness matters, and remember that JSON numbers lose precision for large integers, so use strings for identifiers. Validation is cheap compared to the cost of a corrupted record downstream.
Repairing Invalid Output Safely
When validation fails, the cheapest repair is often a second call that includes the original output and the specific validation error, asking only for a corrected JSON object. Bound the number of attempts, typically two, and escalate to a fallback rather than looping and burning budget. Never silently coerce invalid data into a valid shape, because that hides a systematic prompt problem and corrupts records quietly. Log every failure with the input, the raw output and the error so patterns become visible.
Handling Partial and Truncated Output
Long generations can stop at the token limit with an incomplete object, which validation rejects as malformed JSON rather than a missing field. Detect truncation from the finish reason and treat it distinctly from a schema violation, because the fix is a larger limit or a shorter requested output, not a correction prompt. For streaming consumers, buffer until a complete object is parsed instead of acting on each fragment, since a half parsed object is always invalid.
Versioning Output Schemas
A schema is an interface, so changing it breaks every consumer that relied on the old shape. Version the schema, keep the version in the prompt and in the stored record, and only roll consumers forward after they handle both shapes. When you add a required field, decide how historical records will supply it, because validation of old rows against the new schema will fail. Announce breaking changes and provide a deprecation window just as you would for a public API.
Testing and Monitoring Structural Failures
Add tests that feed deliberately malformed, truncated and adversarial outputs through the validation and repair path and assert that each is handled as designed. In production, track the validation failure rate by prompt version, because a jump usually means a prompt or model change broke the contract. Alert on it like any other error budget, and keep a sample of failed outputs for offline analysis. A contract you never measure is a contract you will not notice breaking.
Keeping Schema and Prompt in Step
The schema should live in code, not inside a prompt string. Define it once, generate the prompt description from it, and reuse the same object for validation, so the instruction and the check can never drift apart. Add a test that every field in the schema is mentioned in the prompt description, which catches the case where someone adds a field and forgets to tell the model about it. When the provider gains a native schema mode, switching to it should be a configuration change rather than a rewrite, because the contract was always owned by your code and only borrowed by the prompt.
Sources
Sources: JSON Schema, OpenAI structured outputs, jsonschema for Python.
FAQ
- Is structured output mode enough without validation?
- It constrains decoding but does not remove the need to validate, because truncation, provider bugs and schema version drift can still produce a payload that violates the contract your code assumes.
- How many repair attempts are reasonable?
- Two at most. More attempts rarely converge and multiply cost; if two corrections fail, the prompt or schema likely needs a human fix, so fall back and log the case.
Report a problem with this articleOpens a pre-filled issue on GitHub.