Skip to content

Module 07 · Lesson 7.4

Output Validation and Policy Enforcement

40 minUpdated 18 Nov 2026Part of Safety, Security and Reliability · AI Agent Development
On this page
  1. What you will learn
  2. Why you must validate what a model writes
  3. Four layers of checks for an agent reply
  4. What to do when a reply fails a check
  5. Validate more than the final reply
  6. A reply validator in Python
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

A restaurant kitchen has a pass: a shelf where the head chef looks at every plate before a waiter takes it out. The cooks are skilled, yet the chef still checks. A plate with the wrong order, a missing garnish or something dropped on it never reaches the table.

An AI agent needs the same shelf. The model writes the reply, but code should decide whether the reply may leave. This lesson shows what to check, where to put the checks, and what to do when a reply fails. Most of it needs no coding. One short Python script at the end checks three sample replies from Quillfeather Cycles.

What you will learn

  • Explain why a model's reply must be checked in code before it is shown or used.
  • List four layers of checks: shape, allowed values, limits and policy rules.
  • Plan what happens when a check fails: one retry with the reason, then a handover.
  • Run a Python function that returns a list of policy problems for a reply.

Before you start

Why you must validate what a model writes

A model produces text that looks right most of the time. "Most of the time" is not good enough when the text is about to be shown to a customer or handed to a tool. A reply can be well written and still break a rule.

Output validation means checking a model's reply with ordinary code before it is used. Policy enforcement is the part of that checking which applies your own rules, such as "never promise a refund". Both run after the model and before anything else.

Why not just write the rules in the instructions? Instructions are a request, and the model can miss them or be tricked into ignoring them. Code is a gate. It answers the same way every time and you can test it. OWASP, a well-known security group, names the risk of trusting model output without checks: LLM05:2025 Improper Output Handling (opens in a new tab).

Validation
A check that the output has the right form: valid JSON, the expected fields, allowed values.
Policy
A rule your organisation sets, for example "the agent never promises a refund".
Enforcement
Making sure the rule really holds, by blocking or replacing a reply that breaks it.
Downstream
Whatever comes after the model: the customer's screen, a database, another tool or another agent.
Where the check sits
  1. Model reply

    Text from the model

  2. Validator

    Code checks shape and rules

  3. Pass

    Reply goes to the customer

  4. Fail

    Retry once, then hand over

The model never talks to the customer directly. Code stands in between.

Four layers of checks for an agent reply

Run the checks from cheap and simple to specific. If a reply is not even valid JSON, there is no point looking for refund promises in it.

LayerQuestion it answersQuillfeather example
1. ShapeIs it valid and does it have exactly the agreed fields?JSON with status, order_id, sources and reply, and nothing else.
2. Allowed valuesIs each field inside its allowed set or pattern?status is one of five words. order_id is null or looks like QF-1042.
3. LimitsIs anything too long or too big?The reply is at most 300 characters.
4. Policy rulesDoes the content break a company rule?No refund promise, no staff page ids, no email address.
The first three layers are about form. Layer 4 is about meaning, and it is the hardest.

Layers 1 and 2: the reply contract

You wrote this contract in Module 2 and used it in the labs. The reply is one JSON object. Treat the contract as a strict list. A missing field and an extra field are both failures, because an extra field can carry something you never planned to allow.

JSON
{"status": "answered | needs_order_number | return_requested | needs_person | not_found",
 "order_id": "QF-1234 or null",
 "sources": ["KB-03"],
 "reply": "..."}

Layer 3: limits

A length limit is a small check with a large benefit. It stops a runaway reply, keeps screens tidy and limits how much text an attacker can smuggle through. Pick a number that fits your product. Here it is 300 characters.

Layer 4: policy rules

Policy rules come from the agent's specification. Look at your out-of-scope list from Define the Agent's Objective, Scope and Success Criteria and turn each item you can test into a rule. For the Quillfeather support agent, three are easy to write:

  • No refund promises. Only staff approve returns, so the agent must not say "your refund is approved".
  • No staff pages in sources. KB-14, KB-15 and KB-16 are staff-only. If one appears in sources, something went wrong earlier, for example a broken metadata filter. See Vector Search, Metadata Filters and Source Grounding.
  • No email addresses in replies. The shop never asks for or shares details by email, and a stray address in a reply may be personal data.

What to do when a reply fails a check

Failing a check is normal. Some replies will fail, so plan the next move in advance. A simple rule works well: retry once with the reason, then hand over.

  1. Step 1: Check the reply

    Run the validator. If the list of problems is empty, the reply passes.

  2. Step 2: Retry once, with the reason

    Send the model a short note such as "Your reply cited a staff page. Answer again using only customer pages." Do not repeat the bad reply back at length.

  3. Step 3: Check again

    Run the same validator on the new reply. A reply is never trusted just because it is the second one.

  4. Step 4: Hand over

    If it fails twice, send the safe handover reply from the Module 4 lab and pass the case to a person. Write the problems in your log.

Why only one retry? Each retry costs time and money, and a model that failed once with the same input will often fail again. A limit also stops a loop from running on. Budget Limits, Rate Limits and Runaway Execution Controls goes deeper into this.

Problem foundBest response
Not valid JSON, or wrong fieldsRetry once with the reason, then hand over.
Unknown status or bad order idRetry once. These are often small slips.
Refund promise or staff page citedDo not show the reply. Retry once, then hand over, and log it for review.
Email address in the replyBlock the reply. Never "fix" it silently, because you would hide the problem.
Never show a failed reply to the customer, even partly.

Validate more than the final reply

The final reply is not the only model output. Every tool call the model asks for is output too. If the model asks for lookup_order with an order id of ../secrets, your code must refuse it before the tool runs. You learned this in Designing Tool Schemas and Validating Arguments.

  • Tool arguments: check type, pattern and allowed values before the tool runs.
  • Final reply: check the contract and the policy rules before the customer sees it.
  • Messages to other agents: check them like any other input, as the multi-agent lessons showed.
  • Text going to a web page or a database: never paste model text straight into a page or a query. Escape it or pass it as a parameter, as you would with any untrusted input.

The common idea: model output is untrusted input to the next part of your system. It comes from a very capable program, yet it can still be wrong, and an attacker may have influenced it. Prompt Injection and Untrusted Tool Outputs shows how that can happen.

A reply validator in Python

The script below checks three sample replies: a good one, a risky one and a broken one. It returns a list of problems, so an empty list means the reply passes. No AI model is needed, and the output is the same every time.

Pythoncheck_reply.py
import json
import re

KEYS = {"status", "order_id", "sources", "reply"}
STATUSES = {"answered", "needs_order_number", "return_requested", "needs_person", "not_found"}
STAFF_PAGES = {"KB-14", "KB-15", "KB-16"}
PROMISE = re.compile(r"refund (is|has been) approved|we will refund|guarantee", re.I)
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")


def check_reply(text):
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return ["not valid JSON"]
    if not isinstance(data, dict) or set(data) != KEYS:
        return ["fields are not exactly status, order_id, sources, reply"]
    problems = []
    if data["status"] not in STATUSES:
        problems.append(f"unknown status: {data['status']}")
    if data["order_id"] is not None and not re.fullmatch(r"QF-[0-9]{4}", str(data["order_id"])):
        problems.append("order_id is not null or QF-1234 shaped")
    staff = STAFF_PAGES & set(data["sources"])
    if staff:
        problems.append(f"cites staff pages: {sorted(staff)}")
    if len(data["reply"]) > 300:
        problems.append("reply is longer than 300 characters")
    if PROMISE.search(data["reply"]):
        problems.append("reply promises a refund or guarantee")
    if EMAIL.search(data["reply"]):
        problems.append("reply contains an email address")
    return problems


SAMPLES = {
    "good": '{"status": "answered", "order_id": "QF-1042", "sources": ["KB-02"], "reply": "Your order QF-1042 is dispatched (KB-02)."}',
    "risky": '{"status": "answered", "order_id": "QF-1042", "sources": ["KB-15"], "reply": "Your refund is approved! Write to anna@example.com."}',
    "broken": '{"status": "done", "order_id": "1042", "sources": [], "reply": "Sure."}',
}
for name, text in SAMPLES.items():
    problems = check_reply(text)
    print(name, "->", "OK" if not problems else problems)

Runs offline with any Python 3.10 or later. Save it and run python check_reply.py.

What each part does

  • KEYS, STATUSES and STAFF_PAGES are sets, collections without order that are quick to compare. They hold the contract and the staff-only page ids.
  • PROMISE and EMAIL are regular expressions, patterns that describe text. re.I means "ignore capital letters". The email pattern is simple on purpose and will miss unusual addresses.
  • json.loads(text) turns the reply text into a dictionary. If the text is not valid JSON, the function returns at once with one problem. Later checks would only crash.
  • set(data) != KEYS compares the fields in the reply with the allowed fields. A missing or extra field fails.
  • problems = [] collects every problem found. The function does not stop at the first one, so you see the full picture.
  • STAFF_PAGES & set(data["sources"]) is the overlap of two sets. If it is not empty, the reply cites a staff page.
  • PROMISE.search(...) and EMAIL.search(...) look for the patterns anywhere inside the reply text.
  • The last loop runs the function on each sample and prints OK or the list of problems.
OutputCaptured from a real run
good -> OK
risky -> ["cites staff pages: ['KB-15']", 'reply promises a refund or guarantee', 'reply contains an email address']
broken -> ['unknown status: done', 'order_id is not null or QF-1234 shaped']

The risky reply broke three policy rules at once, and the broken reply failed the allowed-values checks. In a real agent, a non-empty list triggers the retry-once-then-hand-over plan from the previous section.

Conclusion and your next step

Treat every model output as untrusted input. Check the shape, the allowed values, the limits and your own policy rules in code. When a reply fails, retry once with the reason, check again, and then hand over to a person. Never show a failed reply, and log which checks failed.

Your next step: write your own three policy rules for an agent you are designing, and turn them into checks like the ones above. Then continue to Budget Limits, Rate Limits and Runaway Execution Controls, where you cap how much one run, and one user, can cost.

Want more background first? Read How to Prevent AI Hallucinations in Code Generation for ideas on checking model claims, or the Agent Launch Safety Checklist before you connect an agent to real systems.

Common errors and how to fix them

A reply with a stray extra field gets through.

Why it happens: The validator only checks that required fields exist, not that no other fields appear.

Fix: Compare the full set of fields with the allowed set, as set(data) != KEYS does.

The validator crashes on a reply that is not JSON.

Why it happens: The code reads fields before it has checked that the text parses.

Fix: Parse inside try, and return a problem straight away when parsing fails.

The agent retries again and again after a failure.

Why it happens: There is no limit on retries, or the failed reply is trusted on the second try.

Fix: Allow one retry, run the same validator again, then hand over.

A policy rule works in tests, then misses a rephrased promise in real use.

Why it happens: The rule is a short word list, and models can say the same thing in many ways.

Fix: Keep word rules as a first net, and add design controls: no refund tool, person approval, and a sample of real replies reviewed regularly.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add two rules to the reply validator

Extend check_reply with two new checks. First, block any reply that tells the customer to sue or to hire a lawyer. Second, block a reply whose status is return_requested but whose order_id is null. Then write one test reply for each rule.

You will need

  • The check_reply function from this lesson.
  • A new pattern for the words lawyer and sue.
  • The rule that a return request always belongs to one order.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Add one more compiled pattern, for example a regular expression that matches lawyer or sue as whole words.
  • Compare with None when you test for a missing order id, not with the text "null".
  • Run the good sample last, to prove the new rules did not break it.
Show a model answer

Add LEGAL = re.compile(r"\b(lawyer|sue)\b", re.I) and append "reply gives legal advice" when LEGAL.search(data["reply"]) finds a match. Add a second check: if data["status"] == "return_requested" and data["order_id"] is None, append "return requested without an order id". The word boundary \b matters, because without it the word "issue" would match "sue" and block good replies. Testing the lesson's good sample afterwards shows that a new rule has not become too strict.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Where should the rule "never promise a refund" be enforced?
    Show the answer and explanation

    Answer: B. Code gives the same answer every time and can be tested. Instructions help, which makes the first option tempting, but a model can miss or be talked out of an instruction.

  2. 2.A reply fails the validator. What is the safest plan?
    Show the answer and explanation

    Answer: B. One retry gives the model a fair second chance and keeps cost down. Retrying until it passes sounds persistent, but it can loop forever and spend money on a model that keeps failing.

  3. 3.A reply is valid JSON with all the right fields. Is it safe to use?
    Show the answer and explanation

    Answer: B. A well-formed reply can still cite a staff page or promise a refund. Shape tells you the text can be read, not that its content is allowed.

Frequently asked questions

What is output validation for an AI agent?

It is checking the model's output with normal code before anything uses it. The code checks the format, the allowed values and your own rules. If the output fails, it is not shown or acted on.

Why not just tell the model the rules in the prompt?

A prompt is a request, and models can miss it or be tricked by text in a document. Code is a gate that does not get tired or talked around. Use both: the prompt makes good replies more likely, and the code catches the rest.

How do I make an AI return valid JSON every time?

You cannot guarantee it from the prompt alone. Ask for the format clearly, use any structured-output feature your model provider offers, and always parse the result in code. If parsing or checking fails, retry once and then hand over.

Should I retry when the model's output fails a check?

Yes, once, with a short note about what was wrong. Check the new reply with the same validator. If it fails again, stop and hand over to a person. Unlimited retries cost money and rarely help.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.