Output Validation
Schema checks, policy scanners, and verifiers on model outputs before they reach users/tools.
In plain words
Before using what the AI wrote, the app checks that it has the right shape, follows the rules and is safe, and if not it asks the AI to try again or stops.
Think of it like…
A food-safety inspection between the kitchen and the table: no matter how skilled the chef, every plate passes through checks for allergens, temperature and presentation, and anything that fails goes back to the kitchen instead of to the customer.
Where you’ve seen it
A support agent returns {"order_id": "A1", "amount": 125.0, "reason": "damaged"} for a refund. Structural validation uses a schema with required fields, an enum for reason and amount as a positive number with two decimals: a plain prompt produces invalid JSON 3% of the time; one repair retry that includes the validation error fixes 2.4 points, leaving 0.6% for a fallback (constrained decoding or a schema-enforced API reduces this toward zero). Semantic validation then checks that the order belongs to the authenticated user, that the order's remaining refundable amount is at least $125 and that the amount is within the auto-approval limit; failure routes to a human. Content scanning removes email addresses and API-key patterns from the customer-facing text and rejects URLs outside the allowlist. When the answer is rendered in a web page, it's treated as plain text or sanitised markdown, so a payload like <img src=x onerror=...> is neutralised. Costs: schema check under 1 ms, regex scanners 2 ms, a verifier model (about 600 ms) only on high-risk answers.
Words you’ll hear
- Structured / schema validation
- Checking that output parses and matches the expected fields and types.
- Business-rule validation
- Checking domain constraints such as ownership, limits and valid references.
- Fail closed
- On validation failure, refuse or escalate instead of passing output through.
- Output encoding
- Escaping model text for its destination (HTML, SQL, shell) so it can't execute.
Visual diagram
Theory & deep dive
Layers of validation
Structural: define the contract with a JSON Schema or a typed model (Pydantic, Zod) and validate every response; prefer provider features for structured outputs or constrained decoding, which guarantee syntax, and still validate semantics because a syntactically valid object can be wrong. Business rules: check ownership (the order belongs to the caller), ranges and limits (amount ≤ remaining refundable), referential integrity (the product id exists), state (the order isn't already refunded) and idempotency. Do these in code using the same services as your normal API validation, never by asking the model whether the output is fine.
Content and safety: scan for PII, secrets (key formats, high-entropy strings), disallowed categories and active content (HTML tags, scripts, markdown links, image URLs to unapproved domains). Grounding: for RAG answers, check that cited ids exist and that each claim is supported by the retrieved text, using entailment or a verifier model (see the faithfulness lesson) on high-stakes answers. Consistency: compare numbers in the text with those in the tool results and refuse if they differ. Order checks from cheapest to most expensive and short-circuit on the first failure; log the reason so you can monitor failure categories.
assert order.user_id == ctx.user_id and args.amount <= order.refundable_remaining and args.amount <= policy.auto_limit in the tool layer. The model may propose any amount; the code decides whether the action is allowed.
Safe handling at the destination and repair loops
Most damage comes from where the output goes. Browser: render model text as plain text or sanitised markdown (an allowlist sanitiser such as DOMPurify), set a strict Content-Security-Policy and block model-generated links and images to unapproved domains. Database: never let the model write raw SQL for execution against production data; use parameterised queries, read-only roles and an allowlist of tables, or have the model fill a validated query spec. Shell and code: don't execute model-written commands outside a sandbox; use allowlisted commands and arguments. HTTP clients and tools: validate URLs against an allowlist to prevent server-side request forgery. Always encode for the sink, since escaping for HTML doesn't protect a SQL query.
For repair loops, return the validator's error to the model ("field amount must be a number with two decimals") and retry once or twice; more retries add cost and latency with diminishing returns (3% invalid → 0.6% after one retry). Cap total attempts, then use a fallback: a simpler prompt, a template-based answer, a different model, a human handoff or a polite refusal. Monitor validation failure rates by type (schema, rule, content), since a spike indicates a prompt, model or attack change, and add failing examples to your eval suite. Test validators with adversarial outputs (payloads in every field, extremely long strings, Unicode tricks) and treat any path that bypasses them as a bug.
100,000 calls a day. Without repair 3% fail = 3,000. One retry that returns the error fixes 80% → 600 residual (0.6%) go to fallback. Retry adds about 3,000 × the call's latency and cost, a small price for 2,400 saved interactions.
How it works, step by step
Step 1 of 41. Define the contract
Write a schema for every structured output and list business rules and content policies per consumer.
- Use
- constrained decoding if available
When to use it & trade-offs
What it is
Output validation treats everything a model produces as untrusted input to the rest of your system and checks it before it reaches a user, a browser, a database or a tool. Checks fall into layers: structural (does it parse and match the JSON Schema or Pydantic model?), semantic and business rules (is the refund amount within the order total? does the cited document exist?), safety and content (PII, secrets, policy violations, disallowed links) and grounding or verification (is each claim supported by the sources?). When a check fails the system repairs (retry with the error message), degrades (a safe fallback) or fails closed (refuses or escalates), rather than passing the output along.
Why it matters: Models produce plausible text, not guaranteed-correct data: JSON with a missing field, a refund for the wrong amount, an HTML snippet that runs a script, a SQL query that touches the wrong table. Treating output as trusted is the root of OWASP's "Improper Output Handling" risk and turns prompt injection into real damage. Validation is deterministic, cheap and testable, so it's one of the highest-return controls in an AI system.
When to reach for it
- Any model output used by code, tools or UIs
- Agents that take actions
- RAG answers with citations
When to avoid or be careful
- Inserting raw model output into HTML or SQL
- Asking the model to approve its own output instead of checking in code
- Unlimited retry loops
Validation approaches
Strengths: Deterministic, fast and testable.
Watch out: Needs explicit rules per output type.
Strengths: Catch PII, secrets and active content.
Watch out: Pattern-based; some misses and false positives.
Strengths: Flexible, catches unsupported claims.
Watch out: Slower, costlier and imperfect.
Interview signals & numbers to know
When this topic comes up
- “The JSON was invalid again”
- Improper output handling
- XSS from model output
- Fail closed
- Constrained decoding
Benchmarks & rules of thumb
- 3% → 0.6%
- invalid outputs after one repair retry
- < 1 ms / 2 ms / ~600 ms
- schema, regex scan and verifier-model latencies
- 2,400 of 3,000
- failures fixed by a retry at 100,000 calls a day
Common mistakes & follow-ups
Common interview mistakes
- Validating syntax but not business rules.
- Escaping for HTML and then using the same string in a SQL query.
- Not logging failures, so attacks and prompt regressions go unnoticed.
Likely interviewer follow-ups
- How would you validate an agent's tool arguments?
- What is improper output handling and how do you prevent it?
- When would you use a verifier model?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Output Validation with generative AI interview Q&A and hands-on practice.