When to reach for it
- Downstream systems expect structured data.
- Errors must be caught early.
- Automated processing follows.
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.
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
2 · On every output
| Attempt | Model output | Check | Result |
|---|---|---|---|
| 1 | Quantity “twelve”, delivery “Friday” | Schema: the quantity must be an integer | Rejected |
| 2 | Quantity 12, a delivery date one year back | Rule: the delivery date lies in the past | Rejected |
| 3 | Quantity 12, the date of the coming Friday | Schema and rules pass | Accepted and stored |
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")When to reach for it
When it backfires
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.
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.
Keep going
Search patterns, frameworks, and pages.