AI Agent Output Validation 2026
Format errors are the easy kind; valid JSON full of invented content is the real risk. This gives a four-layer validation structure, JSON Schema and Pydantic constraints at the source, a two-attempt repair loop, citation and numeric provenance checks, and when to fail closed versus degrade.
📜 Table of Contents
📖 Keep reading
AI Agent Output Validation: Do You Believe Everything Your Agent Says?
Real failures are small: the agent returns JSON with one missing comma and the front end goes blank. Format errors are the easy kind. The dangerous kind is perfectly valid JSON full of invented content.
Output validation does three jobs: block format errors, catch content errors, make failures traceable.
Four layers, cheapest first
| Layer | Checks | Cost | Catches |
|---|---|---|---|
| Syntax | Valid JSON/XML/Markdown | Microseconds | Truncation, stray prose, escaping |
| Structure | Fields, types, enums | Milliseconds | Missing fields, type drift |
| Semantics | Consistency with context, fabrication | One extra model call | Hallucination, wrong attribution |
| Business | Amounts, permissions, state machine | Milliseconds | Overreach, out-of-range values |
Run cheap layers first; there is no point paying for a semantic check on invalid JSON.
Prevent errors at the source
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Extract key contract terms"}],
response_format={"type": "json_schema", "json_schema": {
"name": "contract_terms", "strict": True,
"schema": {"type": "object",
"properties": {"party_a": {"type": "string"},
"amount": {"type": "number"}},
"required": ["party_a", "amount"],
"additionalProperties": False}}}
)
Strict schema guarantees shape, not truth. Local stacks have equivalents: GBNF grammars in llama.cpp, guided decoding in vLLM, a format parameter in Ollama. Constraints cut format errors but reduce freedom and can slow generation on complex schemas.
Hard validation with Pydantic
class ContractTerms(BaseModel):
party_a: str = Field(min_length=1)
amount: float = Field(gt=0, le=10_000_000)
risk_level: Literal["low", "medium", "high"]
ContractTerms.model_validate_json(raw)
The ValidationError names the field and the reason — useful for repair and for metrics. A field that fails constantly is a field your prompt describes badly.
Repair loop: twice, then stop
for attempt in range(max_repair + 1):
raw = call_model(messages)
try:
return ContractTerms.model_validate_json(raw)
except ValidationError as e:
messages += [{"role": "assistant", "content": raw},
{"role": "user", "content": f"Invalid per schema:\n{e}\nReturn only corrected JSON."}]
Feed the actual error text back, demand JSON only, cap the attempts. Never return an empty string on failure — upstream will treat it as "succeeded with no result" and the bug resurfaces somewhere stranger.
Semantic checks: the three easiest lies
- Citations that do not exist. Require a
sourcesarray and verify each ID against the retrieval set. - Numbers with no provenance. Match amounts, ratios and dates against source text; mark unmatched values as unverified instead of displaying them.
- Missing refusals. Build a set of unanswerable questions; the correct behavior is "the material does not say".
Prefer deterministic checks (ID membership, numeric matching). When using a model, ask a narrow question — "list every factual claim that cannot be supported by the provided material" — not "is this correct".
Business rules stay in code
Money limits, permissions, state transitions and ID existence must be deterministic. The model can explain a rule; it cannot enforce one.
Failure strategies
| Strategy | When | What users see |
|---|---|---|
| Fail closed | Money, permissions, compliance | Explicit error and retry entry |
| Degrade | Display-only, tolerant | Short answer or "cannot generate now" |
| Human fallback | High value, low volume | "Escalated, we will follow up" |
The worst option is silently truncating or returning a placeholder.
Turn validation into metrics
Track block rate, repair success rate, false-positive rate and per-field error distribution. Without these numbers, the validation layer is a blind safety net rather than a feedback loop.
FAQ
Do I still need validation with schema constraints? Yes. Constraints cover structure, not truth, and streaming, truncation or fallback models can bypass them.
What does validation cost? Syntax and structure are nearly free. Semantic checks cost one extra model call — use a cheap model and enable it only for high-risk output.
Local models keep breaking format — what now? Constrained decoding first, then a schema plus a full example in the prompt, then more repair attempts. Examples beat descriptions.
Can the model check itself? Weakly — within the same context it tends to agree with itself. Use a different model, or a fresh session that sees only the output and the source material.
Note: structured output, constrained decoding and JSON schema parameters differ across SDKs and inference frameworks and change between versions. Check official docs.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.