Sub topic 8
Validating output before you use it
This chapter assumes you can write a Pydantic model, handle Python exceptions, and have called an LLM API before. Earlier chapters showed how to ask for JSON. Here you check that what came back is safe to use.
Why valid JSON is not enough
A reply can parse as JSON and still break your program. The model may omit a field, return "high" where you expected an integer, or invent a category you never listed. Even schema-constrained decoding does not check limits such as ge=1 in every provider. Treat every model reply as untrusted input, the same way you treat a web form submission.
Validation has two layers:
- Syntax: does the text parse as JSON at all?
- Shape and values: do the fields, types, and limits match your schema?
Pydantic does both in one call, model_validate_json.
Validating with Pydantic
This example reuses the TicketTriage model from the schema chapter. It runs as shown.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
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")
good = '{"category": "bug", "priority": 2, "summary": "App crashes on login."}'
bad = '{"category": "complaint", "priority": 7, "summary": "Too slow."}'
print(TicketTriage.model_validate_json(good))
try:
TicketTriage.model_validate_json(bad)
except ValidationError as err:
print(err)The first call returns a TicketTriage object. The second raises ValidationError, which lists every problem at once: category is not an allowed value, and priority is greater than 3. The message names the field and the rule, which is useful later when you send it back to the model.
Two kinds of failure
model_validate_json raises the same exception class for two different problems. Knowing which one occurred helps you log and react correctly.
| Failure | Example | Typical cause |
|---|---|---|
| Not JSON | `Here is the result: {...}` | Prose or a code fence around the object |
| Wrong shape or value | `"priority": 7` | Missing field, wrong type, value outside limits |
You can tell them apart through the error details:
from pydantic import ValidationError
try:
TicketTriage.model_validate_json("Sure! Here you go: {}")
except ValidationError as err:
for item in err.errors():
print(item["type"], item["loc"], item["msg"])A syntax failure has the type json_invalid. Shape failures have types such as missing, literal_error, or less_than_equal. Record the type in your logs so you can see which kind of error is common.
Reject unknown fields
By default Pydantic ignores extra keys. A model that invents "confidence": 0.9 passes without complaint, and the field is dropped. If a stray key tells you the model misunderstood the task, you want to know. Forbid extras like this:
from pydantic import ConfigDict
class StrictTicket(TicketTriage):
model_config = ConfigDict(extra="forbid")This mirrors additionalProperties: false in the JSON Schema.
Checks that the schema cannot express
A type and a range do not prove a value is right. A summary can be 40 characters of nonsense, and the category can be valid but wrong. Add business rules with a validator, and keep them cheap and deterministic.
from pydantic import field_validator
class CheckedTicket(TicketTriage):
@field_validator("summary")
@classmethod
def summary_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("summary must not be blank")
return value.strip()Validators run inside model_validate_json, so their errors appear in the same ValidationError. Checks against the source text, such as confirming an extracted order number appears in the ticket, belong here too. Those catch a common failure, a plausible value the model made up.
Where validation sits in the pipeline
The validation step decides whether the data moves forward or goes to error handling.
The next chapter covers the retry loop. For now, make sure invalid data never reaches the code after the gate.
Common errors
- Parsing with
json.loadsand then using the dictionary directly. This skips type and range checks. - Catching a bare
Exception, which also hides bugs in your own code. - Validating only the happy-path examples. Test with replies that are broken on purpose.
- Trusting provider-side schema enforcement as a replacement for your own check. Limits such as
maxLengthmay not be enforced by every provider, and your code is the final guard.
Exercise
A model returns {"category": "bug", "priority": "2", "summary": "Crash", "confidence": 0.9}. With the default TicketTriage model, does validation pass, and what does the resulting object contain? What single change makes the reply fail on the extra field?
Show answer
It passes. Lax mode converts the string "2" to the integer 2, and the extra confidence key is ignored, so the object has only category, priority, and summary. Adding model_config = ConfigDict(extra="forbid") makes validation fail on confidence.
Exercise
Write the code that catches a ValidationError and prints only the error types, such as json_invalid or missing. Why record the types instead of only counting failures?
Show answer
Use except ValidationError as err: then print([e["type"] for e in err.errors()]). Types show whether failures come from broken syntax or from wrong values, and these have different fixes. Syntax errors point to prompting or code fences. Value errors point to the schema or its descriptions.