Validation-Retry Loops for Claude Extraction: Send Back the Exact Errors, and Stop When a Retry Cannot Help
Three supplier invoices, three endings: a dropped line item fixed on the second try, a format slip fixed while a missing PO number stops the loop, and a typo in the document itself that goes to a person. Plain Python checks decide which errors are worth a retry.
What you will learn
- Tell a syntax error (broken shape) from a semantic error (values that do not agree)
- Build a retry message from the document, the failed extraction and the specific errors
- Give every problem a kind so the loop knows when to retry and when to stop
- Use calculated_total, conflict_detected and detected_pattern to decide the next step
Before you start
- Defensive parsing of Claude replies
- Content boundaries and schema design for Claude
- Basic Python
A supplier invoice says total due 220.00. The model reads it and returns a tidy record. The JSON is valid, every field is there, every type is right. But the line items add up to 180.00. We are off by 40.
A schema checks the shape of an answer. It can't check that the values agree with each other. That part is your code's job, and when your code finds a problem, the next question is: is it worth asking the model again? This article builds a small loop that answers that question for every problem it finds.
Two kinds of error
- Syntax errors: a broken shape, a missing field, a string where a number should be. Tool use with a JSON schema handles most of these (see defensive parsing of Claude replies).
- Semantic errors: values that are well formed but wrong. Line items that don't add up to the stated total. A value in the wrong field. Only your own validation catches these.
Think of two ways a teacher can hand back homework. One sheet says just wrong. Which line? You can only guess. The other says line 3: 7 × 8 is 56, not 54, and your own sheet comes back with it. Now you fix line 3 and keep the rest. A retry should work like the second sheet.
The loop
Five steps: the model extracts, plain code validates (sums, required fields, formats), every problem becomes a specific error, the retry carries the original document, the failed extraction and those errors, and the result is validated again. The tries are capped, so a stuck loop always ends.
validate.py: every problem has a kind
The checks are plain Python. No model, no key.
"""Plain-Python checks on an extracted invoice. No model, no key.
kind says what a retry can do: format and sum can be fixed by the
model, missing and conflict cannot."""
def problem(field, kind, message):
return {"field": field, "kind": kind, "message": message}
def check(inv):
"""Return a list of problems. An empty list means clean."""
errors = []
for n, item in enumerate(inv["items"]):
if not isinstance(item["qty"], (int, float)):
errors.append(problem(
f"items[{n}].qty", "format",
f'items[{n}].qty "{item["qty"]}" must be a number'))
readable = not errors
if inv["po_number"] is None:
errors.append(problem(
"po_number", "missing",
"po_number is null: not in this document"))
if readable:
total = sum(i["qty"] * i["price"] for i in inv["items"])
stated = inv["stated_total"]
if inv["conflict_detected"]:
errors.append(problem(
"stated_total", "conflict",
f"calculated_total {inv['calculated_total']:.2f} vs "
f"stated_total {stated:.2f}"))
elif round(total, 2) != stated:
errors.append(problem(
"stated_total", "sum",
f"line items add up to {total:.2f}, "
f"stated_total is {stated:.2f}"))
return errors
Four kinds of problem:
- format: a quantity that should be a number and isn't, like
"2 doz". - missing: the PO number is
null, which means the document doesn't have it. - conflict: the model itself reports that the document disagrees with itself.
- sum: the lines don't add up to the stated total.
Each message names the field and the numbers. "Line items add up to 180.00, stated_total is 220.00" tells the model exactly what to look at. A bare "invalid" doesn't.
retry_loop.py: document, last output, errors
The follow-up message carries three things: the original document, the failed extraction exactly as the model gave it, and the specific errors, one line each.
RETRYABLE = ("format", "sum")
def retry_prompt(doc, previous, errors):
"""The follow-up: document + failed output + specific errors."""
lines = "\n".join(f"- {e['message']}" for e in errors)
return (f"DOCUMENT:\n{doc}\n\n"
f"YOUR LAST EXTRACTION:\n{json.dumps(previous)}\n\n"
f"PROBLEMS FOUND:\n{lines}\n"
"Fix only these problems.")
def run(name, max_tries=3):
doc = DOCS[name]
prompt = f"Extract this invoice as JSON:\n{doc}"
for attempt in range(1, max_tries + 1):
result = stand_in_model(name, prompt)
errors = check(result)
word = f"{len(errors)} problem" if errors else "clean"
print(f"{name} try {attempt}: {word}"
+ ("s" if len(errors) > 1 else ""))
for e in errors:
print(f" [{e['kind']}] {e['message']}")
if not errors:
return "saved"
fixable = [e for e in errors if e["kind"] in RETRYABLE]
if not fixable:
kinds = ", ".join(sorted({e["kind"] for e in errors}))
print(f"{name} STOP: a retry cannot fix {kinds}")
return "stopped"
prompt = retry_prompt(doc, result, fixable)
return "gave up"
The decision is in two lines. Only format and sum problems are worth a retry, because those are mistakes in reading. If nothing in the list is fixable, the loop stops and says why. Notice the retry sends only the fixable errors; there's no point asking the model to fix a PO number the document doesn't have.
In the project, stand_in_model imitates the model with scripted answers (one per attempt), so no API key is needed. The checks and the loop are real code.
Three invoices, three endings
The three documents, as the project writes them:
DOCS = {
"invoice_C": "Cable 3 x 20.00 | Adapter 2 x 15.00 | Hub 1 x 90.00"
" | Case 1 x 40.00 | Total 220.00 | PO 7731",
"invoice_B": "Cable 2 doz @ 6.00 | Hub 1 @ 130.00 | Total 274.00"
" | PO: see purchase order document",
"invoice_D": "Cable 3 x 20.00 | Adapter 2 x 15.00 | Hub 1 x 90.00"
" | Total 220.00 (typo: the lines add up to 180.00)",
}
Running python retry_loop.py:
invoice_C try 1: 1 problem
[sum] line items add up to 180.00, stated_total is 220.00
invoice_C try 2: clean
invoice_B try 1: 2 problems
[format] items[0].qty "2 doz" must be a number
[missing] po_number is null: not in this document
invoice_B try 2: 1 problem
[missing] po_number is null: not in this document
invoice_B STOP: a retry cannot fix missing
invoice_D try 1: 1 problem
[conflict] calculated_total 180.00 vs stated_total 220.00
invoice_D STOP: a retry cannot fix conflict
magic_number 3 of 4 dismissed
bare_except 0 of 3 dismissed
unused_import 1 of 2 dismissed
- Invoice C: the first extraction dropped the Case row (40.00). With the sum error in front of it, try two finds the missing row and comes back clean.
- Invoice B: "2 doz" is fixed to 24 on try two. The missing PO number stays missing, so the loop stops.
- Invoice D: the document itself has the typo. The loop stops at once and flags it.
When a retry is useless
Look at invoice B again. "2 doz" was written in the document, so the model can read it again and turn it into 24. But the PO line says only see purchase order document. The value lives in another document. Ask a hundred times and it stays null, because there's nothing new to read.
So: for format and structure errors, retry. For absent information, stop and mark it missing. A retry can fix what was misread. It can't create what was never written. This is also why the schema should allow null in the first place, as covered in content boundaries and schema design.
Let the extraction check itself
Invoices C and D have the same gap of 40. The causes are opposite.
That's why the extraction asks for three extra fields: the stated_total as written, a calculated_total from the lines, and a boolean conflict_detected. In invoice C the model misread, so conflict_detected is false and a retry helps. In invoice D the model saw that the document disagrees with itself, so it says true, and a person checks it. A retry can't fix a typo in the source.
The same idea for review findings
The last three lines of the run come from a second loop, this time over code-review findings. Each finding carries a detected_pattern field, and the team records whether a developer dismissed it.
def dismissal_report(findings):
"""Per detected_pattern: (how many found, how many dismissed)."""
stats = {}
for f in findings:
seen, gone = stats.get(f["detected_pattern"], (0, 0))
stats[f["detected_pattern"]] = (seen + 1,
gone + f["dismissed"])
return stats
magic_number was dismissed 3 of 4 times, bare_except 0 of 3, unused_import 1 of 2. The pattern developers dismiss most is the one whose criteria need tightening. A pattern that is dismissed again and again is a prompt to fix, not a person to blame. For how to tighten it, see explicit criteria vs vague prompts.
Common mistakes
- Trusting a valid schema. Valid JSON with the right types can still hold values that don't add up.
- A bare "try again". Without the document, the last output and the exact error, try two is a guess.
- Retrying absent information. If the value lives in another document, the loop burns tries and the answer never changes.
- Treating every gap the same. A misread and a typo in the source look identical until the extraction reports
conflict_detected. - No cap. Always end after a fixed number of tries and hand over.
Recap
| Problem kind | Example | Next step |
|---|---|---|
| format | "2 doz" as a quantity | Retry with the error |
| sum | Lines 180.00, total 220.00, misread | Retry with the error |
| missing | PO number in another document | Stop, mark it null |
| conflict | Typo in the document itself | Stop, flag for a person |
On the exam, when an extraction fails validation, the right answer retries with the document, the failed output and the exact errors. If the information isn't in the source, retrying won't help.
Try it yourself
Add a date_format check to check() with kind format, give one scripted answer a date like "3rd March", and watch the loop fix it on the second try. Then change its kind to missing and see the loop stop instead.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
