Skip to content
CCAR-F Prep

Task Statement 4.4·Domain 4 — 20% of exam

Validation, Retry, and Feedback Loops

Implement validation, retry, and feedback loops for extraction quality

Jump to practice →

Official Exam Guide Objectives

The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.

Task 4.4: Implement validation, retry, and feedback loops for extraction quality

Knowledge of

  • Retry-with-error-feedback: appending specific validation errors to the prompt on retry to guide the model toward correction
  • The limits of retry: retries are ineffective when the required information is simply absent from the source document (vs format or structural errors)
  • Feedback loop design: tracking which code constructs trigger findings (detected_pattern field) to enable systematic analysis of dismissal patterns
  • The difference between semantic validation errors (values don't sum, wrong field placement) and schema syntax errors (eliminated by tool use)

Skills in

  • Implementing follow-up requests that include the original document, the failed extraction, and specific validation errors for model self-correction
  • Identifying when retries will be ineffective (e.g., information exists only in an external document not provided) versus when they will succeed (format mismatches, structural output errors)
  • Adding detected_pattern fields to structured findings to enable analysis of false positive patterns when developers dismiss findings
  • Designing self-correction validation flows: extracting "calculated_total" alongside "stated_total" to flag discrepancies, adding "conflict_detected" booleans for inconsistent source data

What You Need to Know

Extraction systems fail in production, and reliably: documents arrive shaped unexpectedly, figures fail to reconcile, values land in the wrong field. What distinguishes a robust pipeline is not the absence of those failures but what happens next. The validation-retry pattern converts them into a workflow that repairs itself.

The one idea to hold: a retry is a correction channel, not a magic wand. It works only if the information the model needs is reachable from what you send it. When validation fails, ask first whether the answer is present in what the model can see. If it is, retry with the document, the failed output and the specific errors. If it is not, do not retry: mark the field null or unresolved, route the record to human review, or fetch the missing source first.

Retry-with-Error-Feedback

A retry worth making carries three things back to the model:

  1. The original document — there is nothing to re-read without it, and a retry is a re-reading
  2. The failed extraction — its own previous answer, so the correction is targeted rather than a fresh attempt
  3. The specific validation error — the one element that distinguishes this from simply asking again

Each does distinct work, so dropping any one of them weakens the retry. Leave out the document and the model cannot re-check the evidence; leave out the failed extraction and it cannot see what to correct, so it starts again from scratch; leave out the error and it has no new information at all.

The simplest shape is a fresh request whose single user message carries all three:

// Retry with error feedback
const retryMessages = [
  {
    role: "user",
    content: `Original document:\n${originalDocument}\n\n` +
      `Your extraction:\n${JSON.stringify(failedExtraction)}\n\n` +
      `Validation error: Line items sum to £450 but stated_total is £500. ` +
      `Please re-extract, ensuring all line items are captured.`
  }
];

If the extraction came back through a tool call and you continue that same conversation instead, the turn structure changes: the next user message must answer the tool_use block with a tool_result (marked is_error) that carries the errors. The Deep Dive shows that shape.

The gap between this and a bare retry is large. Re-running the same request against the same document invites the same reading of it, so the same mistake comes back. Naming the discrepancy gives the model somewhere to direct its attention — hunting for the line item it missed, checking which field a value landed in, redoing the arithmetic.

A bare retry repeats the mistake — the error must be named Re-sending a document with only "try again" invites the same reading of it, so the same discrepancy comes back: line items summing to 450 pounds against a stated total of 500 pounds. A retry that instead carries three things — the original document, the failed extraction, and the specific validation error naming the 450 versus 500 mismatch — gives the model somewhere to direct its attention, and the totals reconcile on the next pass. Bare retry Original document + "try again" 450 vs stated_total 500 ✕ same discrepancy again nothing new to work from — the same reading comes back Retry with error feedback Original document Your extraction: 450 vs 500 Line items sum to 450 but stated_total is 500 calculated_total: 500 stated_total: 500 ✓ totals reconcile naming the discrepancy gives the model somewhere to direct its attention
1 / 6Swipe diagram ↔

A bare retry repeats the mistake — the error must be named, step 1: Bare retry — same document, try again

Writing the error: what is wrong, the evidence, what to do

A useful error message states what is wrong, points at the evidence in the document, and says what to do about it. "Validation failed. Please try again." does none of these. Compare three messages that each do all three:

ProblemFeedback that gives the model something to act on
A missed line item"calculated_total is 1,289.00 but the line items you extracted sum to 1,314.00. The difference of 25.00 matches the line 'Expedited shipping 25.00', which you omitted. Re-read the line-item table, including any rows below the subtotal."
An ambiguous date"invoice_date reads 03/04/2026 and the vendor address is in the UK, where dates are day-first. Re-check; if it stays ambiguous, set invoice_date to null and record the ambiguity."
Values in the wrong field"vendor_name 'Northwind Logistics' comes from the Bill To block; the From block reads 'Acme Freight Ltd'. The vendor is the issuer (From) and the customer is Bill To. Swap them."

Open the message with a scope instruction such as "Correct only these problems and return the full corrected object", so the model fixes what failed without disturbing fields that were right. This is the same structured-error idea that tool error responses use (task 2.2): say what went wrong and what to try next.

Retry hygiene

  • Cap the attempts. Two or three is a typical ceiling. Nothing outside your code stops a loop that is not converging; the API leaves the retry limit to you (see the Deep Dive).
  • Never resend identical inputs. A retry without new information is the bare retry above.
  • Stop when the same error comes back. If the second attempt fails for the same reason as the first, the loop is not converging: route the record to human review rather than spending the rest of the budget.

Classify before you retry

Decide whether an error is fixable before the first retry, not after the budget is spent. An error that names data absent from the source should never consume an attempt; it goes straight to review or to a null. The reliable way to make that decision is a typed flag set by the check that raised the error, not a guess made afterwards by matching words in the error text:

from dataclasses import dataclass

@dataclass
class ValidationError:
    field: str
    retryable: bool   # False: the information is not in the document, so a retry cannot help
    message: str      # what is wrong, the evidence, what to do

def next_step(errors: list[ValidationError], attempt: int, max_attempts: int = 3) -> str:
    if not errors:
        return "accept"
    if not any(e.retryable for e in errors):
        return "human_review"   # absent information: stop at once
    if attempt >= max_attempts:
        return "human_review"   # not converging
    return "retry"              # send the document, the failed extraction and the errors

The invariant: a record whose only errors are non-retryable leaves the loop after one attempt, and every record leaves it after at most max_attempts.

Keep business rules in a separate check from extraction checks. "The downstream system requires a PO number" is a rule the document may be unable to satisfy: if the invoice carries no PO because POs live in the procurement system, that check raises a non-retryable error, and the record is routed rather than retried.

The Retry Effectiveness Boundary

This is the concept the exam tests most aggressively in this task statement. Retries have a clear effectiveness boundary:

Retries ARE effective for:

  • Dates rendered in the wrong convention, or currency written inconsistently between fields
  • Output whose shape is wrong — values nested at the wrong level, or assigned to the wrong property
  • A value that is in the document and ended up under the wrong key
  • Arithmetic that fails because a line item was skipped on the first pass

Retries are NOT effective for:

  • Anything the source simply does not state
  • Values that live in a second document nobody supplied
  • Fields that would require knowledge from outside the material provided

The line between the two lists is whether the answer is present in what the model was given. Everything above it is a reading failure and re-reading can correct it; everything below it is an absence, and no number of attempts conjures a department name out of a document that never mentioned one. Items will offer a retry for both situations. For the second, the correct response is to route the extraction to human review, or to return null where the schema permits it.

Retries fix a misread — not an absence A document that contains a line item the model missed on its first pass is a reading failure, and a retry that re-reads it finds it. A document that never states a department name anywhere is not a reading failure — no number of retries conjures a name from a document that never mentioned one. The correct response there is to route the extraction to human review, or return null where the schema allows it, not to keep retrying. Fixable — misread Line item "Widget C £80" present in the document, missed once retry re-reads — finds it ✓ present in what it received Unfixable — absent "department" never appears anywhere in the source retry again? ✕ no attempt conjures a name route to human review, or return null ✓ the test is whether the answer was present in what the model was given
1 / 6Swipe diagram ↔

Retries fix a misread — not an absence, step 1: Fixable — a line item present but missed

Failure by failure

FailureRetry?Right action
po_number is null and POs live in the procurement systemNoMake the field nullable; fetch the PO from that system or leave it null
Line items do not sum to the stated totalYesFeedback naming the discrepancy and the likely missed line
A numeric date is ambiguousYes, onceFeedback with the locale rule; if still ambiguous, null plus a note
Vendor and customer swappedYesFeedback naming which block is which
The extraction cites page 4 of a three-page documentNoThe page does not exist; flag for review
A scanned page is illegibleNoHuman review; a retry re-reads the same pixels
A required field does not exist for this document typeNoA schema mismatch: make the field nullable or use a different schema

The tell in a stem is whether the missing information is anywhere in the input. If it is not, every retry costs money and returns the same answer, often a more confident fabrication, because each nudge adds pressure to fill the field.

Making absence a valid answer

Returning null needs two things. The schema must make absence representable (the field is nullable and not in required), and the prompt must make it acceptable: a line such as "Use null for any field the document does not contain. A null is a correct extraction; do not infer, compute or carry a value over from another document." A schema that requires every field forces the model to put something in a field the document never filled, which is the fabrication the boundary warns about.

Self-Correction Flow Design

Some validation can live inside the schema rather than in the logic that inspects its output:

calculated_total vs stated_total: Ask for both — the sum the model derives from the line items, and the total the document asserts. A disagreement between two fields is then visible in the extraction itself, with no external arithmetic required to notice it.

{
  "line_items": [
    { "description": "Widget A", "amount": 150.00 },
    { "description": "Widget B", "amount": 300.00 }
  ],
  "calculated_total": 450.00,
  "stated_total": 500.00,
  "total_discrepancy": true
}

Two rules keep the pair honest:

  • stated_total is nullable. It is the total as printed, and not every document prints one. Making it required contradicts the nullable-field rule above.
  • calculated_total is computed, never copied. Say so in the field description ("the sum of the line items that you compute; never copy stated_total"). If the model copies the printed total across, the two fields always agree and the cross-check does nothing.

Both totals beat the alternatives. A single total plus a flag the model sets when it believes the arithmetic is wrong asks you to trust a judgement it never had to show. A free-text notes field describes a discrepancy in a form nothing downstream can branch on. Recomputing in your own code works, but the extraction itself then never carries the signal.

conflict_detected booleans: Where a source may contradict itself, give the model a field to say so. A document stating "payment due: 30 days" in one place and "payment terms: net 60" in another should surface both readings with conflict_detected: true, rather than the model quietly selecting whichever it encountered first. Pair it with a conflict_note that says what conflicts, and require the note whenever the flag is true.

Self-correction fields make a discrepancy visible Extracting calculated_total alongside stated_total puts both numbers in the extraction itself, so a disagreement between 450 and 500 is visible with no external arithmetic. Where a source contradicts itself — payment due in 30 days in one place, payment terms net 60 in another — a model with no conflict_detected field silently picks one reading. A conflict_detected boolean gives it a field to surface both readings instead of quietly choosing. calculated_total vs stated_total Widget A: £150.00 Widget B: £300.00 line_items calculated_total: 450.00 stated_total: 500.00 total_discrepancy: true visible in the extraction itself — no external arithmetic required conflict_detected "payment due: 30 days" "payment terms: net 60" two places, one document silently picks "30 days" ✕ arbitrary conflict_ detected: true ✓ both surface a field to say so, rather than quietly choosing
1 / 6Swipe diagram ↔

Self-correction fields make a discrepancy visible, step 1: Line items plus two totals, side by side

conflict_detected is the stop condition

A totals mismatch has two possible causes: the model missed a line, or the document disagrees with itself. Without conflict_detected the two look identical, so a validator that errors on every mismatch retries a self-contradictory invoice forever: it will never reconcile. The flag separates "the model extracted wrongly" from "the document is wrong". The first is retried; the second is accepted as extracted, with the conflict recorded, and routed to a person.

A validator that runs three checks makes this work. In the fragment below, amounts are integers in minor units (pence), so the comparisons are exact; with decimal amounts, compare within a small tolerance such as 0.01. ValidationError is the dataclass above.

def check_totals(x: dict) -> list[ValidationError]:
    errors = []
    line_sum = sum(item["amount_minor"] for item in x["line_items"])
    if x["calculated_total"] != line_sum:   # the model's own arithmetic
        errors.append(ValidationError("calculated_total", True,
            f"{x['calculated_total']} is not the line-item sum {line_sum}; recompute, do not copy stated_total"))
    stated = x.get("stated_total")          # nullable
    if stated is not None and stated != line_sum and not x["conflict_detected"]:
        errors.append(ValidationError("stated_total", True,
            f"stated_total {stated} differs from the line-item sum {line_sum} by {stated - line_sum}. "
            "Re-read the table, including rows below the subtotal; if the document contradicts itself, "
            "set conflict_detected to true with a conflict_note"))
    if x["conflict_detected"] and not x.get("conflict_note"):
        errors.append(ValidationError("conflict_note", True, "required when conflict_detected is true"))
    return errors

Trace one invoice through it. Line items of 12,750 and 2,500 with a printed total of 15,999: without the flag the second check fires, the error invites a re-read, and the model either finds a missed line or sets conflict_detected with a note such as "printed total 159.99 does not match its own line items (152.50)". With the flag and the note set, the function returns no errors, the loop stops, and the record goes to review as a document problem rather than an extraction problem. This is the same rule as conflict annotation in task 5.6: record the conflict; do not silently pick a value.

The same approach covers other conditional rules: a total_discrepancy flag must match whether the totals actually differ, and a free-text detail field can be required whenever an enum is set to other or unclear.

detected_pattern Fields

Review and analysis pipelines benefit from recording what triggered each finding, not only the finding itself:

{
  "finding": "Potential SQL injection vulnerability",
  "severity": "critical",
  "detected_pattern": "string concatenation in SQL query",
  "file": "user_service.py",
  "line": 42
}

That field turns dismissals into data. Group the findings developers reject by detected_pattern and the weak rules identify themselves — if everything triggered by "variable shadowing in nested scope" is being waved through, that pattern's prompt needs work rather than the reviewers needing persuasion. Extract, validate, gather what was dismissed, refine, repeat.

detected_pattern turns dismissals into a priority list Recording a detected_pattern field on each finding lets rejected findings be grouped by what triggered them. Extract, validate, gather what developers dismissed, and grouping dismissals by detected_pattern shows that a pattern like variable shadowing in nested scope is being waved through disproportionately — the weak rule identifies itself. That pattern's prompt criteria are refined and the loop repeats. Extract detected_pattern set Validate some dismissed Gather dismissals grouped by pattern dismissal rate by pattern variable shadowing in nested scope 62% string concat in SQL query 4% the weak rules identify themselves Refine "variable shadowing in nested scope" ✓ criteria reworked, not the reviewer persuaded extract, validate, gather, refine, repeat
1 / 6Swipe diagram ↔

detected_pattern turns dismissals into a priority list, step 1: Extract — every finding carries a detected_pattern

From dismissals to a diagnosis

Severity and category cannot do this job. Without detected_pattern you know only that "performance findings get dismissed a lot", which is not actionable; with it, each dismissal is attributed to the construct that produced it:

detected_patternRaisedDismissedPrecision (kept ÷ raised)
db_call_in_for_loop84710.15
unawaited_promise3120.94
broad_except_swallow22180.18
missing_null_check_before_index4750.89

Now the fix is precise. Inspection of the dismissed db_call_in_for_loop findings shows they fire on small fixed collections, so its criterion is rewritten to require an unbounded collection; broad_except_swallow is flagging catches that re-raise, so those are excluded. Few-shot contrast pairs for both patterns (task 4.2) then show the model the boundary. The loop runs across the whole domain: explicit criteria (4.1), examples that demonstrate the boundary (4.2), measurement of which constructs misfire (4.4), and back to the criteria.

Which pattern first

Rank patterns by the number of dismissals, which is frequency multiplied by dismissal rate, not by either figure alone. A pattern raised 400 times with a 12% dismissal rate wastes about 48 reviews; one raised 20 times at 90% wastes 18. The rarer pattern shouts louder, but fixing the common one returns more reviewer attention.

Not every dismissal is a false positive

Some dismissed findings are true but unwanted: the code does what the finding says, and the team does not care. That is not a model error to retry or tune away; it is a criteria change (task 4.1), such as removing the category from what the reviewer reports.

Schema Syntax Errors vs Semantic Validation Errors

The exam distinguishes between these two error categories:

Schema syntax errors — Malformed JSON, missing required fields, wrong data types. Eliminated entirely by tool_use with JSON schemas (covered in Task Statement 4.3).

Semantic validation errors — Structurally valid output carrying wrong values: totals that do not reconcile, dates in an impossible order, data in the wrong field. Nothing about the schema can detect these, because each one satisfies it. They need validation logic written separately, and they are what retry loops exist for.

These two task statements deliberately overlap, and the point being tested is the boundary between them: tool_use closes the first category completely and the second not at all.

Adding the boundary of the previous section gives three classes, and the exam's discriminating question for each is whether a retry will help:

ClassExamplesRemoved byRetry works?
Syntax or shapeInvalid JSON, wrong type, missing required field, value outside the enumtool_use with a schema (4.3)Not needed: these no longer occur
SemanticLine items that do not match the stated total; the vendor in the customer field; the due date in the invoice-date field; an invoice dated after its own due dateNothing automatic; your validatorUsually: the evidence is in the document
Absent informationA PO number that exists only in a separate procurement systemNothingNo: the data is not there to find

A validator therefore spends its effort on the semantic checks: sums, date ordering (an invoice date before its due date, a start before an end), field placement, and the conditional rules above. Required fields, types and enum membership are the schema's job.

Deep Dive

An invalid tool call is your loop's to handle

The API does not quietly repair a malformed tool call for you. The docs' instruction is: "When a client tool fails or a call is invalid, send a tool_result block with is_error set to true. Claude might then call the tool again with a new tool_use block, so limit how many retries your loop allows." For a call that is missing parameters, the docs add that it "usually means that there wasn't enough information for Claude to use the tool correctly", that "The best approach during development is to try the request again with more-detailed description values in your tool definitions", and that after an error result "Claude can then call the tool again with the missing information filled in."

The same page names the way to remove the syntax class altogether: "To eliminate invalid tool calls entirely, use strict tool use with strict: true on your tool definitions. This guarantees that tool inputs always match your schema exactly, preventing missing parameters and type mismatches." That is the product behind the exam's "schema syntax errors (eliminated by tool use)"; your application-level loop is for the semantic errors strict mode cannot see.

Sourceplatform.claude.com › handle-tool-callsfetched 2026-11-19

Semantic errors on a tool call go back in a tool_result

When the extraction arrived as a tool_use block and you continue that conversation, the turn rules decide the shape of the retry. The docs' steps: add the response's content unchanged as an assistant message, then "Add a user message with one tool_result block for each tool_use block in that content, even if the tool failed", and "Send the request with the same tools as the first request." Two formatting rules apply: "Tool result blocks must immediately follow their corresponding tool use blocks in the message history", and "the tool_result blocks must come FIRST in the content array. Any text must come AFTER all tool results."

is_error is defined as "Set to true if the tool failed or the call was invalid", and an extraction your validator rejects is an invalid call. So the specific validation errors travel in that tool_result, not in a separate plain-text turn. Here response is the reply whose tool_use block (block) carried the extraction, and errors holds your validator's messages:

messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": [
    {
        "type": "tool_result",
        "tool_use_id": block.id,
        "is_error": True,
        "content": "\n".join(e.message for e in errors),
    },
    # Optional text must come after every tool_result block.
    {"type": "text", "text": "Correct only these problems and call the tool again."},
]})

The conversation already holds the original document and the failed extraction (the tool_use input), so this message supplies the third ingredient. The docs' advice on wording matches the rest of this lesson: "Instead of generic errors such as "failed", include what went wrong and what Claude should try next." After an execution error, "Claude can then call the tool again or tell the user what happened."

Sourceplatform.claude.com › handle-tool-callsfetched 2026-11-19

Forcing the extraction tool on the newest models

Extraction loops are often written with tool_choice forcing the extraction tool on every attempt, which task 4.3 teaches as the way to guarantee a structured result. The docs now limit that.

The retry pattern itself is unaffected: whichever way the call is made, the specific errors go back in the tool_result, and your loop caps the attempts.

Sourceplatform.claude.com › define-toolsfetched 2026-11-19

Rules-based feedback outranks vague or judge-based feedback

Anthropic's Agent SDK guidance ranks feedback quality explicitly: "The best form of feedback is providing clearly defined rules for an output, then explaining which rules failed and why. Code linting is an excellent form of rules-based feedback. The more in-depth in feedback the better." This is precisely the shape of "Line items sum to £450 but stated_total is £500" — a specific rule, a specific violation, not a generic "validation failed." The same guidance places another common alternative near the bottom of the hierarchy: judging output with a second LLM call is "generally not a very robust method, and can have heavy latency tradeoffs" — reinforcing why this task statement favours deterministic, rule-based validation logic over an LLM re-grading its own extraction.

Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30

Self-verification is valuable — but only inside the fixable boundary

The Agent SDK blog frames self-checking as a reliability multiplier: "Agents that can check and improve their own output are fundamentally more reliable — they catch mistakes before they compound." Read alongside this task's retry-effectiveness boundary, the claim only holds for errors the model can actually correct by re-examining information it already has access to (the source document). It is not a claim that self-checking can conjure data the source document never contained — that failure mode still routes to human review, not another retry.

Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30

Repeated failures on the same pattern call for a formal rule, not another retry

For findings that fail repeatedly in the same recognisable way — the exact scenario detected_pattern tracking is built to surface — the documented fix is architectural, not another retry attempt: "If your agent fails at a task repeatedly, can you add a formal rule in your tool calls to identify and fix the failure?" This is the systematic-improvement half of the loop: detected_pattern data tells you which pattern keeps failing or getting dismissed; the fix is a prompt or schema change for that pattern, not persistence with the retry loop.

Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30

Quick Reference

ItemValue / rule
Retry message must includeOriginal document + failed extraction + specific validation error
A useful error statesWhat is wrong, the evidence in the document, what to do
Retry capA small fixed ceiling (two or three attempts); stop early if the same error repeats
Fixability checkBefore the first retry, from a typed retryable flag on each error
Invalid tool callSend a tool_result with "is_error": true; Claude might call the tool again, so your loop limits retries
Retry on a tool call, same conversationOne tool_result per tool_use, carrying the specific errors; tool_result blocks first, any text after; same tools
Removing invalid tool calls entirelystrict: true on the tool definition
Best feedback form (documented ranking)Clearly defined rules + which rule failed and why (e.g. code linting)
Weakest feedback form (documented ranking)LLM-as-judge — "not a very robust method," heavy latency tradeoffs
Retries ARE effective forFormat mismatches, structural errors, misplaced values, missed line items
Retries are NOT effective forInformation genuinely absent from the source document
Unfixable extractionFlag for human review or return null — do not keep retrying
Null as an answerNullable field in the schema and a prompt line saying null is correct
Self-correction schema fieldscalculated_total vs stated_total, total_discrepancy, conflict_detected + conflict_note
stated_total / calculated_totalPrinted total, nullable / computed from line items, never copied
Stop condition for a totals mismatchconflict_detected: true with a note: route to review, do not retry
Systematic improvement signaldetected_pattern field + dismissal-rate analysis
Which pattern to fix firstMost dismissals (frequency × dismissal rate)
True-but-unwanted dismissalsA criteria change (4.1), not a model fix
Repeated pattern failuresAdd a formal rule / refine the prompt for that pattern — not another retry
Forced tool_choice on Opus 5.5, Sonnet 5.5, Fable 5.2/5.1, Mythos 5.2/5.1400 error today; exam answer is still forced selection for guaranteed structure
Schema syntax errorsEliminated by tool_use (Task 4.3)
Semantic validation errorsRequire validation logic and retry loops (this task)

Exam Traps

More wrong answers, and why each fails

Tempting answerWhy it failsChoose instead
Retry until validation passesA non-convergent failure never terminates, and each pass adds pressure to invent a valueA fixed cap, and stop when the same error repeats
Retry with the failed extraction and the error, dropping the document to save tokensA retry is a re-reading; without the document there is nothing to re-checkAll three ingredients
Retry with the document and the error, without the failed extractionThe closest wrong answer: it yields a fresh attempt, not a targeted correctionAll three ingredients
Decide fixability by matching words in the error textBrittle, and errors that match nothing are misroutedA typed retryable flag set by the check that raised the error
After a tool_use, send the validation error as plain text in a new user turnThe turn must answer the tool_use with a tool_result; text may only follow itA tool_result with is_error carrying the specific errors
Let the model fill calculated_total however it likesIf it copies the printed total, the cross-check is a no-opDescribe it as computed from the line items, never copied
Make stated_total requiredDocuments without a printed total force an invented oneNullable stated_total, required calculated_total
Fix the pattern with the highest dismissal rate firstA rare pattern at 90% wastes fewer reviews than a common one at 12%Rank by number of dismissals
Answer a pattern that keeps failing with another retry roundRepeated identical failure means the criteria are wrong, not the readingA formal rule or a prompt change for that pattern

How This Is Tested

Stem signalAnswerWrong-answer pattern beside it
An extraction fails validation; what goes in the retry?The original document, the failed extraction and the specific errors"Try again" or "be more careful"; dropping one of the three
A field (a PO number, a department) is not in the document and lives elsewhereNo retry: nullable field, fetch it from its source, or human reviewMore retries; a stronger instruction to fill the field
Outputs are schema-valid but the line items do not match the totalSemantic validation with calculated_total against stated_totalA stricter schema; trusting tool use alone
The source gives two different dates or terms for the same thingconflict_detected with a note; surface bothPick the first or the most recent value silently
A totals mismatch retries to the budget limit on some invoicesThe document contradicts itself: add conflict_detected and stop on itRaise the retry cap; drop the totals check
A fixed retry budget, and many failures are fields the source never statesClassify errors before retrying; route absent-data errors to reviewLower the cap; check for fabrication after the last attempt
Developers dismiss many findings and you need to know which construct misfiresdetected_pattern on every finding, then group dismissals by itFilter by severity or category; ask reviewers to explain
One pattern's findings keep being dismissed after several retry roundsRewrite that pattern's criteria, then add contrast examplesAnother retry round; better reviewer training
The extraction came from a tool call and validation failedA tool_result with is_error and the specific errors, then the same request againPlain text in a new user turn; an exception that halts the pipeline
Replace deterministic validation with a second model grading the outputKeep rule-based validation; it is the strongest feedback formLLM-as-judge for its flexibility

Practice Scenario

Your extraction pipeline retries every document that fails validation, three attempts each, before flagging it. In last month's log, 60% of failures were fields the source document never stated, which the downstream ledger nonetheless requires, and on those the third attempt usually returns a confident value the document does not support. What's the most effective first step?

Practice Questions

Exam simulator

Question 1 of 14

Scenario · Structured Data Extraction

When an invoice extraction fails the line-items-must-sum check, your retry sends Claude the failed JSON and the error "line items sum to 450, stated total is 500". The retried extractions now pass, but an audit finds that Claude has been changing line-item amounts until they match the total. What change would most effectively fix the retry?

Sources