Sub topic 8
Validating output before you use it
This chapter assumes you can write basic Python classes and handle exceptions, and that you can read JSON. It also assumes you have called an LLM API at least once. It uses Pydantic v2 and the TicketTriage model from earlier in the tutorial.
Why validate when the provider promises a schema
A model's reply is untrusted input. It crosses a boundary into your program, the same as a web form or a third-party API response. Even when you use schema-constrained decoding, you should still validate, for four reasons:
- Not every path is constrained. Prompt-only formatting and JSON mode guarantee little or nothing about your schema.
- Providers support only part of JSON Schema. Keywords such as
minimum,maxLength, andpatternare sometimes ignored or rejected by constrained decoding. Your Pydantic model can still enforce them. - Output can be cut short. A reply that hits the token limit stops mid-structure, and the result is not valid JSON.
- Valid is not correct. A reply can match the schema perfectly and still contain a wrong or invented value.
Validation is the step that turns "a string the model produced" into "an object your code can rely on". Everything downstream should receive only the validated object, never the raw string.
Three layers of checking
Output can be wrong in three different ways, and each needs a different check.
| Layer | Question | Typical tool | Example failure |
|---|---|---|---|
| Syntax | Is it parseable JSON? | `json.loads` | Code fence around the JSON, trailing comma, truncated reply |
| Schema | Does it have the right shape and types? | Pydantic model | Missing key, `priority` of 7, unknown category |
| Semantic | Do the values make sense for this input? | Custom validators and checks against the source | An order ID that is not in the ticket text |
The layers run in order. A later layer is meaningless if an earlier one fails, so the pipeline stops at the first failure.
Recording which stage rejected a reply matters later. In the monitoring chapter you will track failure rates, and a rising parse-stage rate points to a different problem than a rising semantic-stage rate.
Syntax and schema validation with Pydantic
Pydantic can do the parse and the schema check in one call, model_validate_json. For invalid JSON it raises ValidationError with an error type of json_invalid. That is convenient, but it blurs two failure kinds into one exception. When you want the stage recorded, parse with json.loads first and validate the resulting dictionary with model_validate.
The following module does that. It also tightens the model from earlier with two settings that matter for validation.
import json
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
class TicketTriage(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
@field_validator("summary")
@classmethod
def summary_not_blank(cls, value: str) -> str:
cleaned = value.strip()
if not cleaned:
raise ValueError("summary must not be blank")
return cleaned
class OutputRejected(Exception):
"""Raised when a model reply fails validation. Carries the stage and the raw reply."""
def __init__(self, stage: str, detail: str, raw: str):
super().__init__(f"{stage}: {detail}")
self.stage = stage
self.detail = detail
self.raw = raw
def validate_reply(raw: str) -> TicketTriage:
try:
data = json.loads(raw)
except json.JSONDecodeError as err:
raise OutputRejected("parse", str(err), raw) from err
try:
return TicketTriage.model_validate(data)
except ValidationError as err:
raise OutputRejected("schema", str(err), raw) from err
replies = [
'{"category": "bug", "priority": 2, "summary": "App crashes on login."}',
'```json\n{"category": "bug", "priority": 2, "summary": "App crashes."}\n```',
'{"category": "bug", "priority": "2", "summary": "App crashes."}',
'{"category": "outage", "priority": 7, "summary": " "}',
'{"category": "bug", "priority": 1, "summary": "Crash.", "confidence": 0.9}',
'{"category": "bug", "priority": 1, "summary": "Crash. The report is long and',
]
for raw in replies:
try:
result = validate_reply(raw)
print("OK ", result)
except OutputRejected as rejected:
first_line = rejected.detail.splitlines()[0]
print(f"REJECT [{rejected.stage}] {first_line}")Running this prints one line per reply. Only the first reply is accepted. The code-fenced reply fails at the parse stage. The other four fail at the schema stage, except the last, which is truncated and fails at the parse stage.
What the two settings do
extra="forbid" rejects keys the model invented, such as confidence in the fifth reply. The default is to ignore extra keys silently. Ignoring them is usually harmless, but a stray key can be a sign that the model misread the schema, and rejecting it makes that visible.
strict=True turns off Pydantic's default type coercion. In the default lax mode, the string "2" is converted to the integer 2. Strict mode rejects it. Which one you want depends on the pipeline:
- Lax mode accepts more replies, so fewer retries. It can also hide drift, such as a model that has started returning numbers as strings.
- Strict mode gives you a precise signal of what the model actually produced. It costs extra retries when the mismatch is harmless.
If you use lax mode, record that coercion happens. Otherwise a change in model behavior will go unnoticed until something stricter downstream breaks.
Reading validation errors
ValidationError carries a structured list of problems. The errors() method returns one dictionary per problem, with the location, a machine-readable type, and a message.
from pydantic import ValidationError
try:
TicketTriage.model_validate({"category": "outage", "priority": 7, "summary": " "})
except ValidationError as err:
for problem in err.errors():
print(problem["loc"], problem["type"], problem["msg"])Pydantic reports every failing field, not only the first. That is useful for two reasons. You can log a complete picture of one bad reply, and you can pass the whole error text back to the model in a repair step, which the next chapter covers.
Use loc and type for programmatic decisions and logs. Do not parse msg, because its wording can change between Pydantic versions.
Semantic checks
A schema describes shape. It cannot know whether a value is true. Semantic checks apply rules that depend on meaning, on other fields, or on the original input.
Rules inside one object
For a rule involving several fields, use a model_validator. Here a refund request must not combine a currency with an impossible amount:
from typing import Literal
from pydantic import BaseModel, Field, model_validator
class RefundRequest(BaseModel):
order_id: str = Field(min_length=3)
amount: float = Field(gt=0)
currency: Literal["USD", "EUR", "JPY"]
@model_validator(mode="after")
def whole_units_for_jpy(self):
if self.currency == "JPY" and self.amount != int(self.amount):
raise ValueError("JPY amounts must be whole numbers")
return self
print(RefundRequest(order_id="A-1042", amount=19.99, currency="USD"))A validator that raises ValueError is reported as a normal validation error. The failure appears in the same ValidationError as type and range problems, so your error handling stays in one place.
Checks against the source text
The strongest semantic check compares the output with the input you gave the model. If the model extracts an order ID, that ID should appear in the ticket. A value that does not appear was probably invented.
def check_grounded(request: RefundRequest, source_text: str) -> None:
if request.order_id not in source_text:
raise ValueError(f"order_id {request.order_id!r} does not appear in the source text")
ticket = "Hi, I was charged twice for order A-1042 and want 19.99 USD back."
check_grounded(RefundRequest(order_id="A-1042", amount=19.99, currency="USD"), ticket)Grounding checks are cheap, deterministic, and catch a failure that no schema can. Good candidates are identifiers, quoted phrases, dates, and amounts that must come from the text. Choose values that appear verbatim in the input. A grounding check on a paraphrased summary would reject correct output.
Gotchas
- Defaults hide omissions. If a field has a default, a reply that leaves it out validates successfully. For fields the model must decide, leave out the default so that a missing key is an error. This also applies to
Nonedefaults. nullis not "missing". A model may return"priority": null. Withpriority: int, that fails, which is what you want. Withint | None, it passes, so only make a field optional when the program can handle the absence.- Duplicate keys are silent.
json.loadskeeps the last value when a key appears twice, without warning. - Truncation can look like success. A cut-off reply usually fails to parse. But a reply truncated inside a long free-text field in a streamed or repaired response can sometimes be closed by a tolerant parser. Check the provider's finish reason (for example
lengthormax_tokens) and treat a truncated reply as a failure before you parse. - Refusals are not data. A provider may return a refusal in a separate field or as plain text instead of your schema. Check for it first. Do not let a refusal message reach the parser and be logged as a "parse error".
- Validation is not sanitization. A string that passes
max_lengthcan still contain markup or text meant to manipulate a downstream system. Escape or sanitize model-produced strings before they go into HTML, SQL, or shell commands, the same as any untrusted input.
Failing safely
A validation step has three outcomes to design for: success, a retryable failure, and a final failure. Keep them distinct in your function signatures. One approach is to let validate_reply raise OutputRejected and let the caller decide. Another is to return a result type, such as a tuple of an optional object and an optional rejection.
Whichever you choose, the rejection record should include:
- The stage that failed (
parse,schema, orsemantic). - The raw reply, so you can reproduce the failure.
- The Pydantic error list, if there was one.
- The model name, prompt version, and finish reason, so you can find patterns later.
Be careful with the raw reply in logs. It may contain personal data copied from the input, so apply the same retention and redaction rules you use for the input itself.
Summary of the approach
- Treat model output as untrusted, even under schema-constrained decoding.
- Check in three layers: syntax, schema, semantics. Record which layer failed.
- Use
extra="forbid"to catch invented keys. Choose strict or lax typing on purpose. - Add cross-field and source-grounding checks for rules that a schema cannot express.
- Avoid defaults on required fields, and check the finish reason and refusals before parsing.
- Give every failure a defined outcome. Never use unvalidated text as a fallback.
Exercise
Your pipeline validates with TicketTriage.model_validate_json(raw) and logs the ValidationError on failure. A week later, the failure rate is 8%, but the logs do not show whether the model is returning broken JSON or well-formed JSON with wrong values. What change would let you tell, and what does each answer suggest?
Show answer
Parse with json.loads first and validate the dictionary with model_validate, recording the stage (parse or schema) with each rejection. A high parse-stage rate suggests code fences, truncation (check the finish reason and max_tokens), or a prompt-only or JSON-mode setup without a schema constraint. A high schema-stage rate points to the schema or prompt: unclear field descriptions, enum values the model does not follow, or limits such as priority range or max_length that the model exceeds.
Exercise
A reply to RefundRequest extraction validates, but the order_id is "A-2041" while the ticket text says "A-1042". Which layer catches this, and how would you implement the check?
Show answer
Only the semantic layer can catch it, because the value is a valid string and matches the schema. Implement a grounding check that compares the extracted value with the source text, such as if request.order_id not in source_text: raise ValueError(...), and treat the failure as a rejection at the semantic stage.