LLM output validation with Claude: semantic checks, retry with feedback, and when a retry can't help
Structured outputs guarantee that Claude's JSON matches your schema, not that the values are right. LLM output validation is the next layer: checks in your code for meaning (dates in order, totals that add up, your business rules), a retry that sends back the exact errors, and a clear stop when the information simply isn't in the source. There, the right output is null and a person, not a better-looking guess.
Video · Claude Structured Output Validation: Pydantic, Zod and Retry With the Error (CCAR-F) · 4:11
Video · When a Retry Can't Help: Missing Data, Stated vs Calculated Totals, detected_pattern (CCAR-F) · 4:05
Valid JSON is not a correct answer
Two different kinds of error reach your pipeline:
| Syntax error | Semantic error | |
|---|---|---|
| Example | Invalid JSON, a missing required field, a string where a number belongs | A return date before the pickup date; line items that don't add up to the total; the right value in the wrong field |
| Fixed by | Structured outputs or strict tool use | Checks in your code, then a retry with the errors |
The docs promise the first half: structured outputs are "Always valid: No more JSON.parse() errors", "Type safe: Guaranteed field types and required fields", and need "No retries needed for schema violations". The exam guide for the Claude Certified Architect certification draws the line where it matters: strict schemas eliminate syntax errors but not semantic ones.
Layer 1: get schema-valid output
With the Python SDK, pass a Pydantic model as the output format. The SDK "transforms the model's schema, sends it as output_config.format, validates the response, and returns the parsed model in parsed_output":
import datetime as dt
from typing import Literal
from anthropic import Anthropic
from pydantic import BaseModel
class DamageReport(BaseModel):
booking_id: str | None # nullable: the email may not say
part: str
severity: Literal["minor", "needs_repair", "unsafe"]
pickup: dt.date
returned: dt.date
client = Anthropic()
Layer 2: check the meaning in code
Schema validation can't know your business. Write the rules as code that returns readable errors:
SAFETY_PARTS = {"brakes", "frame", "battery"}
def check(r: DamageReport, email: str) -> list[str]:
errors = []
if r.returned < r.pickup:
errors.append(f"returned ({r.returned}) is before pickup ({r.pickup})")
if r.part in SAFETY_PARTS and r.severity == "minor":
errors.append(f"{r.part} is a safety part, so severity can't be minor")
if r.booking_id and r.booking_id not in email:
errors.append(f"booking_id {r.booking_id} does not appear in the email")
return errors
Pydantic's own validators (for example a model validator in "after" mode) or Zod refinements in TypeScript do the same job; what matters is that every rule produces a message precise enough to act on.
Layer 3: retry with the specific errors
A blind retry repeats the same mistake. Send back the original document, the failed output and the exact errors:
def extract(email: str, retries: int = 2) -> DamageReport | None:
messages = [{"role": "user", "content": f"Extract the damage report.\n<email>{email}</email>"}]
for _ in range(retries + 1):
report = client.messages.parse(model="claude-opus-5-5", max_tokens=1024,
messages=messages, output_format=DamageReport).parsed_output
errors = check(report, email)
if not errors:
return report
messages += [
{"role": "assistant", "content": report.model_dump_json()},
{"role": "user", "content": "These fields fail our checks:\n- " + "\n- ".join(errors)
+ "\nFix them using only the email. If the email doesn't say, use null."},
]
return None # still failing: send it to a person
The docs give no retry count. One or two retries, then a person, is a sensible rule: if two targeted corrections don't fix it, a third rarely will. When you validate many documents at once, the same loop works over the Message Batches API at half price.
When a retry can't help
The exam guide is explicit: retries are ineffective when the required information is "simply absent from the source document", or exists only in a document you didn't provide. Retrying there only pushes the model toward inventing a value. Three defenses:
- Nullable fields. Mark fields the source may not contain as nullable, so Claude can return null "rather than fabricating values to satisfy required fields". A required field always gets some value.
- Extract what was stated, check it yourself. Extract the stated total and the line items, compute the sum in code, and flag a mismatch, instead of asking the model to reconcile it.
- Flag conflicts instead of picking. When the email gives two booking IDs, return a
conflict_detectedflag and both values, and let a person decide.
See LLM hallucination for the wider set of techniques, and human in the loop for routing the cases that remain.
Measure what your retries fix
Log every validation error with its kind. After a few hundred documents, you know which errors a retry fixes (format, misplaced values) and which it never does (missing information). Fix the second group upstream: a better prompt, a nullable field, an extra source document. The exam guide adds a related pattern for review pipelines: record which pattern triggered each finding, so dismissal rates show which checks are noise.
Validation on the Claude Certified Architect exam
The CCAR-F exam covers this in Domain 4: task 4.3 (schemas eliminate syntax errors, nullable fields against fabrication) and task 4.4 (semantic versus syntax errors, retry with the document, the failed extraction and the specific errors, and the limits of retry when information is absent). The classic wrong answer is "retry until it passes" for a value the source never contained.
More in all articles.
Sources: Structured outputs, read on 22 October 2026; Strict tool use; Pydantic validators; Zod refinements; Reduce hallucinations; Claude Certified Architect Foundations exam guide v1.0, task statements 4.3 and 4.4.
FAQ
Do structured outputs make validation unnecessary?
No. They guarantee valid JSON, field types and required fields, so syntax errors and schema retries disappear. They don't check meaning: a return date before the pickup date, or line items that don't add up to the total, still pass the schema.
How do you validate LLM output in Python?
Get the structured result, for example with client.messages.parse and a Pydantic model, then run your own checks on the values and collect specific error messages. Pydantic validators or plain functions both work.
What should a retry prompt contain?
The original document, the failed extraction and the specific validation errors, so the model can fix exactly those fields. Cap the retries at one or two, then route the case to a person.
When does retrying an LLM not help?
When the information is absent from the source, or lives in a document you didn't provide. Make those fields nullable so the model can return null instead of inventing a value, and send the case for review.
Read next
- Few-Shot Prompting: How Many Examples, Which Ones
- LLM Hallucination: 7 Ways to Reduce It with Claude
- Claude Structured Output: JSON Schemas That Hold
- Claude Batch API: Half Price, Within 24 Hours
- Authentication vs Authorization: Sessions, JWT, OAuth, SSO
- Software Engineering Unpacked: home
- The CCAR-F video playlist on YouTube