Validate model output against a schema and escalate
Validate model output with Pydantic and route unknown categories, refusals and malformed values to an escalation path.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 10 minutes to read.
In short
Model output is untrusted text until your code checks it. A Pydantic model describes the exact shape you accept, and validation either returns a typed object or raises a clear error. Anything that fails validation, any unknown category, refusal or ambiguous result goes to an escalation path where a person decides.
Think of it like this: Validation is the customs desk at an airport: everything is checked against the rules, and anything that does not match is set aside for an officer.
Explained simply
A model's reply is just text. It might be perfect JSON, JSON with a missing field, JSON wrapped in extra words, or a polite refusal. Your program must never assume the reply is correct. It must check.
Pydantic is a Python library that does the checking. You write a class that lists each field and its type, such as category must be one of five words. Pydantic then reads the reply and either gives you a typed object or raises an error that says exactly what was wrong.
Some replies pass the format check but still are not safe to use. The category might be 'other', the model may have listed missing details, or it may have refused. These cases need a person, not an automatic action.
So every reply ends up in one of two places: accepted and passed on, or escalated to a review queue with a reason code. Nothing is quietly turned into a default value, because that would hide problems you need to see.
Press Play on a diagram to walk through it one step at a time.
- 1Raw text
Whatever the model returned
- 2Parse JSON
Fails on broken or truncated output
- 3Validate schema
Types, allowed values, lengths
- 4Check business rules
Refusal, missing info, low confidence
- 5Route
Auto-accept or escalate to a person
- Malformed
- Not valid JSON
- Missing required field
- Wrong type
- Unknown value
- Category not in the allowed list
- Refusal
- Model declined to answer
- Ambiguous
- Missing info listed
- Category is other
- Triage service to Model: Prompt triage-v3 with ticket1Prompt triage-v3 with ticket
- Model to Triage service: Reply with category 'network'2Reply with category 'network'
- Triage service to Validator: model_validate_json(reply)3model_validate_json(reply)
- Validator to Triage service: ValidationError: literal_error4ValidationError: literal_error
- Triage service to Review queue: Escalation reason unknown_category5Escalation reason unknown_category
In depth
Modelling the output with Pydantic v2
Define a BaseModel subclass with one attribute per output field. Use Literal for a fixed set of strings, or an Enum if other code needs the values too. Use Field with min_length and max_length to bound text. Set model_config = ConfigDict(extra="forbid") so unexpected keys fail instead of being ignored. Then call Triage.model_validate_json(raw_text) to parse and validate in one step; it raises ValidationError if anything is wrong. For data that is already a dict, use model_validate. To send the object onwards, model_dump gives a plain dict. Keep the schema in one module and import it everywhere, so the prompt contract, the validator and the tests share one definition.
- Literal or Enum for categories
- Field(min_length=..., max_length=...) for text
- ConfigDict(extra="forbid") rejects unknown keys
- model_validate_json parses and validates
- model_dump turns the object back into a dict
Rejecting unknown categories and malformed values
Malformed output comes in a few shapes. The reply may not be JSON at all, or JSON may be cut off because the output token limit was reached. A field may be missing, have the wrong type, or hold a value outside the allowed list, such as 'network' when your list has no such category. Pydantic catches all of these as a ValidationError, and e.errors() lists each problem with its location and type. Record the error types, not just the message, so you can count them later. Avoid tolerant tricks such as mapping 'network' to 'software' silently. If a new category keeps appearing, that is a signal to change the contract deliberately, not to patch around it.
- Not JSON
- Prose reply
- Markdown fences
- Truncated object
- Schema mismatch
- Missing field
- Wrong type
- Extra key
- Bad value
- Unknown category
- Empty summary
- Summary too long
Detecting refusals
Sometimes a model declines a request, for example because the ticket contains something that looks like a policy violation. Some providers mark refusals explicitly: OpenAI's Structured Outputs feature can return a separate refusal field instead of schema-shaped content. Other models simply reply in prose, which then fails JSON parsing. Handle both. Check for an explicit refusal signal first, and treat a non-JSON reply as malformed. Record refusals with their own reason code, because they need a different response from broken formatting: usually a person should read the ticket rather than retrying the model.
Routing ambiguous results to a person
Valid output can still be uncertain. Treat these as ambiguous: category is other, missing_info is not empty, or the summary mentions details that do not appear in the ticket. Write the routing as a small pure function that takes the raw text and returns either an accepted Triage object or an Escalation with a reason code such as malformed, unknown_category, refusal or needs_info. A pure function is easy to test with fixed inputs. The review queue then shows the ticket, the raw model output and the reason, so a person can act quickly. Count escalations by reason every week; a rising count tells you what to fix next.
- Reason codes: malformed, unknown_category, refusal, needs_info
- Routing is a pure function you can unit test
- Reviewers see ticket, raw output and reason
- Track escalation counts by reason
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Model the output with Pydantic~45m
- 2Reject unknown categories~45m
- 3Detect refusals and malformed values~45m
- 4Route ambiguous results to a person~45m
Key points
- Use Literal or an Enum for categories so unknown values fail validation automatically.
- Set extra="forbid" in ConfigDict so unexpected keys are rejected rather than ignored.
- model_validate_json parses and validates in one step and raises ValidationError on failure.
- Structured output features in provider APIs reduce malformed JSON but do not replace your own checks.
- Every failure becomes a typed escalation record with a reason code, never a silent default.
Key terms
Tap a card to flip it. 0/5 known
Examples
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class Triage(BaseModel):
model_config = ConfigDict(extra="forbid")
category: Literal["access", "billing", "hardware", "software", "other"]
summary: str = Field(min_length=5, max_length=200)
next_step: str = Field(min_length=3)
missing_info: list[str] = []
try:
t = Triage.model_validate_json('{"category": "marketing", "summary": "x", "next_step": "y"}')
except ValidationError as e:
print(e.error_count(), "errors") # unknown category, short fieldsAn unknown category and too-short fields fail validation with a clear error count.
Routing every reply to accept or escalate
The route function returns a typed result in all cases. Step 1: parse and validate. Step 2: on ValidationError, decide whether it is an unknown category or general malformed output. Step 3: on a valid object, escalate if more information is needed. Expected evidence: tests with fake replies hit each branch.
from dataclasses import dataclass
from pydantic import ValidationError
@dataclass
class Escalation:
reason: str
raw: str
def route(raw: str) -> Triage | Escalation:
try:
t = Triage.model_validate_json(raw)
except ValidationError as e:
kinds = {err["type"] for err in e.errors()}
return Escalation("unknown_category" if "literal_error" in kinds else "malformed", raw)
if t.missing_info or t.category == "other":
return Escalation("needs_info", raw)
return tTesting the branches with a fake model
Prepare four fake replies: a valid access ticket, a reply with category network, a prose refusal and a valid reply with missing_info filled. Step 1: run each through route. Step 2: assert the results are Triage, unknown_category, malformed and needs_info. Step 3: add a case for truncated JSON such as an object missing its closing brace; it should be malformed. If you use a provider with an explicit refusal field, add a check before parsing that maps it to the reason refusal. Cleanup is not needed because everything runs in memory.
Quick reference
- Model output is untrusted text until it passes validation
- Literal[...] for categories; unknown values raise literal_error
- ConfigDict(extra="forbid") rejects keys you did not define
- Model.model_validate_json(raw) parses and validates in one step
- Never default a failed result to 'other'; escalate with a reason code
- Provider structured outputs reduce bad JSON but do not replace your validator
- Escalate valid but uncertain results too: other, needs_info, refusals
Common mistakes
- Catching the error and defaulting to 'other', which hides model failures in the data.
- Trusting a provider's schema feature and skipping your own validation.
- Escalating with no reason code, so reviewers cannot see why or spot patterns.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a Pydantic model with a category limited to three values and a summary between 5 and 200 characters.
- Exercise 2medium
Write a function that returns the list of Pydantic error types for a raw reply, or an empty list if it is valid.
- Exercise 3hard
Extend route to detect a refusal: if the raw reply does not start with '{' and contains phrases such as "I can't" or 'I cannot', return Escalation('refusal'). Write pytest cases for all four reasons.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- If the provider supports structured outputs, do I still need Pydantic?
- Yes. Structured outputs make valid JSON much more likely, but your own validation still checks business rules, catches refusals and protects you if you switch models.
- Should I retry when validation fails?
- One retry can help with occasional formatting slips. Cap retries, log every failure, and escalate if the retry fails too.
- What is the difference between model_validate and model_validate_json?
- model_validate takes a Python object such as a dict. model_validate_json takes a JSON string and parses it before validating.