AI Response Validation
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The model gave you an answer. Before it goes to a customer, a database or another system, you need to know that it has the right shape, that the facts in it are ones your system knows, and that it doesn't break a rule the model has never heard of. This lesson builds the checks in layers: ask for structure, parse it, apply business rules and decide what happens on failure. The last part matters most, because the checks are only as good as the plan for when they fail.
What you'll learn
- Asking for structured output, and what the documentation says it does and doesn't guarantee.
- Validating shape with a schema.
- Business-rule checks a schema can't express.
- Repairing once, and then handing over to a person.
- Reading
stop_reason before you trust the text.
Before you start
Step 0: check why it stopped
Every response has a stop_reason, and the documentation lists seven values: end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal and model_context_window_exceeded. Two of them mean the text can't be trusted as a complete answer:
max_tokens: the reply was cut off, perhaps mid-sentence or mid-JSON.
refusal: Claude declined. It arrives as a normal HTTP 200, not an error, and the response has a stop_details field naming the category. The documentation suggests retrying on a different model or rephrasing.
Our gateway (lesson 8.8) turns both into exceptions, Truncated and Refused, so the validation code below never sees half an answer. The tests cover both, and the service sends either to a person.
Step 1: ask for a shape
The API can constrain the reply to a JSON schema. You pass a schema in output_config.format with type json_schema, and in Python the messages.parse() helper accepts a Pydantic model and returns it in parsed_output. A few documented details are worth knowing before you rely on it:
- Some JSON Schema features aren't supported (recursive schemas, numeric bounds like
minimum, string lengths like maxLength, among others) and using one returns a 400. The SDK helpers remove the unsupported constraints, move them into descriptions and validate the response against the original constraints afterwards.
- The first request with a new schema is slower, because the grammar is compiled. Compiled grammars are cached for 24 hours after last use.
- Changing
output_config.format invalidates the prompt cache for that conversation.
- If the response is a refusal or stops at
max_tokens, the output may not match the schema, so check stop_reason first.
Our service takes the other route, which works on any model and any SDK version: the system prompt asks for JSON in a stated shape, and our own code parses and validates it. That means you need the validation layer below even when you use structured outputs, because a schema checks shape, not truth.
Step 2: parse and validate shape
class SupportDraft(BaseModel):
reply: str = Field(min_length=10, max_length=1200)
order_ids: list[str] = []
needs_human: bool = False
reason: str = Field(default="", max_length=300)
Our parser tolerates the usual model habits: a ```json fence or a sentence before the object. It still rejects anything that isn't JSON, or that breaks the limits. We tested a fenced reply, a chatty non-JSON reply, a too-short reply and a too-long one.
Step 3: check what the schema can't
A schema knows a reply is a string under 1,200 characters. It doesn't know that your shop never promises refunds, or that order A999 doesn't exist. Those checks are code:
"""Never pass model output straight on. Parse it, check it against rules only your code knows, and decide what happens
when it fails."""
import json
import re
from dataclasses import dataclass, field
from pydantic import BaseModel, Field, ValidationError
from gateway import Gateway, Reply
from llm_util import parse_json
class SupportDraft(BaseModel):
"""The shape we ask the model to produce."""
reply: str = Field(min_length=10, max_length=1200)
order_ids: list[str] = [] # orders the reply talks about
needs_human: bool = False
reason: str = Field(default="", max_length=300)
PROMISES = re.compile(r"\b(we (will|'ll) (refund|reimburse|compensate)|you (will|'ll) (get|receive) (a |your )?(refund|compensation)|guarantee[ds]?|free of charge)\b", re.I)
SECRETS = re.compile(r"(sk-[A-Za-z0-9_-]{16,}|Bearer\s+[A-Za-z0-9._-]{16,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)")
ORDER_REF = re.compile(r"\b[A-Z]\d{3,6}\b")
@dataclass
class Verdict:
ok: bool
draft: SupportDraft | None = None
problems: list[str] = field(default_factory=list)
repaired: bool = False
def check_rules(draft: SupportDraft, known_orders: dict[str, dict]) -> list[str]:
"""Checks that need facts only your system has."""
problems = []
if PROMISES.search(draft.reply):
problems.append("The reply promises a refund or compensation, which only a person may do.")
if SECRETS.search(draft.reply):
problems.append("The reply contains something that looks like a secret.")
mentioned = set(ORDER_REF.findall(draft.reply)) | set(draft.order_ids)
unknown = sorted(m for m in mentioned if m not in known_orders)
if unknown:
problems.append(f"The reply mentions orders that were not looked up: {', '.join(unknown)}.")
for oid in draft.order_ids:
status = known_orders.get(oid, {}).get("status")
if status and status in ("cancelled",) and re.search(r"\b(shipped|on its way|delivered)\b", draft.reply, re.I):
problems.append(f"The reply describes order {oid} as shipped or delivered, but it is {status}.")
return problems
def parse_draft(text: str) -> SupportDraft:
return SupportDraft(**parse_json(text))
def get_validated_draft(gateway: Gateway, prompt: str, known_orders: dict[str, dict], system: str | None = None) -> Verdict:
"""Ask, validate, and give the model ONE chance to repair a failed answer. After that, a person takes over."""
reply: Reply = gateway.ask(prompt, system=system)
problems: list[str] = []
try:
draft = parse_draft(reply.text)
problems = check_rules(draft, known_orders)
if not problems:
return Verdict(True, draft)
except (ValueError, ValidationError) as e:
draft, problems = None, [f"The answer was not valid JSON for the required shape: {type(e).__name__}."]
repair = (prompt + "\n\nYour previous answer had these problems. Fix them and answer again in the same JSON shape:\n- "
+ "\n- ".join(problems))
reply2 = gateway.ask(repair, system=system)
try:
draft2 = parse_draft(reply2.text)
problems2 = check_rules(draft2, known_orders)
except (ValueError, ValidationError):
return Verdict(False, None, problems + ["The repaired answer was still not valid."], True)
if problems2:
return Verdict(False, draft2, problems2, True)
return Verdict(True, draft2, [], True)
The rules, each tested:
- No promises. A pattern catches phrases like "we will refund" or "guaranteed". It will miss some wordings. It's a net, not a wall, which is why a person still reads drafts.
- No secrets. Anything shaped like an API key, bearer token or private key block fails.
- Grounding. Every order ID in the reply, whether in the text or the declared list, must be one the service actually looked up. This is the simplest and most effective defence against a model inventing an order.
- Consistency. A reply that says an order shipped when your system says it was cancelled fails.
Step 4: repair once, then stop
When validation fails, get_validated_draft sends the problems back to the model and asks for a corrected answer, one time. Models are often good at fixing a specific complaint. If the second answer also fails, it returns the problems and the draft so a person can decide. Two attempts is a deliberate limit. Each loop costs money and delay, and an answer that fails twice usually needs judgement, not a third try. Our tests check: a first-time pass uses one call; a promise repaired on the second call; invalid JSON repaired once and then given up; and a repaired draft that's still wrong returns its problems.
What the service does with the verdict
- Valid and the model doesn't ask for help: return the draft (for a person to approve and send).
- The model set
needs_human, or validation failed twice: return "needs a person" with a reason.
- Refusal or truncation: "needs a person".
Every failure path ends somewhere safe. Nothing the model said is sent to a customer by this service.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A customer says their parcel is late and they're angry. The model writes a sympathetic draft that says "we will refund you in full". The schema check passes. The promise rule fails, so the service asks for a rewrite that avoids promises. The second draft says "I've passed this to our team who can look at options". It passes, and a person sees it with the draft. The shop's rule, "only people promise refunds", was enforced by two lines of code and didn't depend on the model remembering a sentence in the prompt.
Mistakes to avoid
- Treating "valid JSON" as "correct".
- Ignoring
stop_reason and parsing a truncated reply.
- Retrying forever. One repair, then a person.
- Rules that only live in the prompt. The prompt asks, the code enforces.
- Checks so strict that most good answers fail. Watch the rejection rate (lesson 8.7).
Security notes
Output validation is also a security layer: it catches secrets in replies, invented identifiers and promises that an injected instruction might have produced. Validate before any side effect, and never let a value from the model choose a file, a query or a command without a check against known-good values.
Cost and speed
A repair costs another model call, roughly doubling that request's cost, so track how often it happens. A high repair rate means the prompt or schema needs work, and it's a good metric for the monitoring in lesson 8.7. Output checks themselves take microseconds.
Key takeaways
- Check
stop_reason first: refusals and truncation aren't answers.
- Structured output and schemas give shape; your code must check truth and policy.
- Ground identifiers against facts you looked up.
- Repair once, then hand over to a person.
Lesson recap: a schema gives shape; your code checks truth, then repairs once and escalates.
Quick quiz
- Name two stop reasons that mean the text isn't a finished answer.
- What can a JSON schema not check?
- Why check order IDs against the looked-up orders?
- Why limit repair to one attempt?
- What happens to a reply that fails validation twice?
Answers and explanations
max_tokens (cut off) and refusal (declined). model_context_window_exceeded also means truncated.
- Facts and policy: whether an order exists, whether a promise is allowed, whether a statement matches your data.
- It stops the model inventing or misremembering an order and presenting it as real.
- Each retry costs money and time, and an answer that fails twice usually needs human judgement.
- It goes to a person with the problems listed, and nothing is sent to the customer.
Official references and further reading
Related tutorials