Output Validation / Schema Enforcement

Reject malformed model output before it pollutes the next step.

Model responses are validated against schemas, types, or business rules before use, and a failed check triggers a reject-and-re-prompt loop rather than letting the malformed output flow downstream.

In practiceAn order-processing agent validates that every model-generated JSON payload matches its Pydantic schema before inserting it into the database, rejecting and re-prompting on the first malformed response.

Without itWithout output validation, a hallucinated field or mistyped value from the model propagates silently into downstream systems and may corrupt database records or trigger unintended actions.

Level
04 · Production
Subdomain
Governance & Safety
Also known as
Structured Output Validation, Schema Validation, Guarded Output
Trade-off
Higher reliability is gained against restrictions on expressive freedom.
Native in
OpenAI Structured Outputs, LangGraph, Microsoft Agent Framework, Google ADK, Pydantic AI
The mechanism

How it works.

Nothing the model returns is used as it is. The output is parsed and checked against a schema and against business rules, and a failed check goes back to the model together with the reason.

1 · Define

  1. Write the schemaFields, types, allowed values
  2. Add business rulesWhat a schema cannot express

2 · On every output

  1. ParseIs it valid JSON at all?
  2. ValidateThe schema first, then the rules
  3. Reject with the reasonThe error text goes back to the model
  4. Accept or give upAfter a fixed number of retries
Schema
The expected form of the output: which fields exist and which type each has.
Business rule
A check on meaning, not on form: the quantity is positive, the delivery date is not in the past.
Retry budget
How often the model may try again. When it is used up the run fails loudly instead of passing bad data on.
Walk it through

A real run, step by step.

TaskAn agent turns an email into an order record: “Please send 12 boxes of A4 paper by Friday.”
Illustrative run.
AttemptModel outputCheckResult
1Quantity “twelve”, delivery “Friday”Schema: the quantity must be an integerRejected
2Quantity 12, a delivery date one year backRule: the delivery date lies in the pastRejected
3Quantity 12, the date of the coming FridaySchema and rules passAccepted and stored
What this shows: the first error would have crashed the insert. The second would have gone through without a sound, and that makes it the worse one. A schema catches form, a rule catches meaning, and both are needed. What validation cannot tell is whether 12 is what the customer wrote. It checks that the record is well-formed and plausible, not that it is true.
In code

The pattern in code.

Pydanticpython
from datetime import date
from pydantic import BaseModel, ValidationError, field_validator

class Order(BaseModel):
    product: str
    quantity: int
    delivery: date

    @field_validator("quantity")
    @classmethod
    def positive(cls, value):
        if value <= 0:
            raise ValueError("quantity must be positive")
        return value

def extract_order(email, max_retries=2):
    prompt = f"Extract the order as JSON:\n{email}"
    for _ in range(max_retries + 1):
        raw = model(prompt)
        try:
            order = Order.model_validate_json(raw)  # form
            if order.delivery < date.today():  # meaning
                raise ValueError("delivery date lies in the past")
            return order
        except (ValidationError, ValueError) as error:
            prompt += f"\n\nYour last answer was rejected: {error}\nReturn corrected JSON."
    raise RuntimeError("no valid order after retries")
Fit

Use it, or not.

When to reach for it

  • Downstream systems expect structured data.
  • Errors must be caught early.
  • Automated processing follows.

When it backfires

  • Free-form text is the actual goal.
  • Schemas inadmissibly restrict the answer.
  • Validation is purely syntactic while being blind to business logic.
Pitfalls

Two ways this pattern will hurt you.

Schema passes; business logic fails

The JSON parses and matches the type, but the values violate an unstated rule — a negative quantity, a date in the past, a customer that doesn't exist.

Countermeasure

Layer business validators on top of the schema. Treat syntactic validation as a precondition, not a guarantee.

Re-prompt loops forever on an unsatisfiable schema

The schema demands a field the model cannot produce for this input. Reject-and-re-prompt never converges, burning tokens and latency on a validation that can never pass.

Countermeasure

Cap validation retries. On exhaustion, fall back to a typed error or human review rather than looping; log the schema that never validated so it can be fixed.

Framework support

Where Output Validation / Schema Enforcement is native.

OpenAI Structured OutputsServiceconstrained decodingNative
LangGraphstructured output nodeNative
Microsoft Agent Frameworkschema-typed responsesNative
Google ADKcontrolled generationNative
Pydantic AIoutput_type: validated, typed output with retryNative

Search

Search patterns, frameworks, and pages.