CertSafari
    Anthropic Claude Certified Architect – Foundations (CCAR-F)· Lessons

    Domain 4 · Lesson 22/30

    Validation, retry with error feedback, and self-correcting extraction

    Implement validation, retry, and feedback loops for extraction quality

    16 min read
    3.33% of exam
    6 sources
    Published 20 Oct 2026
    Docs as of 14 Oct 2026

    What you will be able to do

    • Tell the semantic errors that pass schema validation apart from the syntax errors that structured outputs remove
    • Add calculated_total, stated_total and conflict_detected fields so that validation code can find discrepancies
    • Build a retry request that contains the original document, the failed extraction and the specific validation errors
    • Tell when a retry can fix a failure and when the record must go to a person instead
    • Add a detected_pattern field to findings so that dismissals can be analysed by code construct

    Key concept

    Retry with error feedback — Your own code validates an extraction. When validation fails, you send the model a follow-up request that contains the source document, the output that failed and the exact errors, so the model can correct the output against the source. This works for errors in how the output is put together. It does not work when the information is missing from the source.

    1.Validation after the schema has passed

    Structured outputs and strict tool use make an extraction parse correctly. They do not make it correct. With constrained decoding, every response is valid JSON with the right types and every required key, so you no longer need retries for malformed syntax. The errors that remain are semantic. A date of birth can sit under the wrong object. A total can disagree with its own line items. A value can be well formed and still wrong. The schema accepts all of these because each field is valid when checked alone (Schema syntax errors vs semantic errors). Retry with feedback exists to fix semantic errors like these.

    Your validation layer has to own every rule the schema cannot express. The SDK helpers already work this way for constraints such as minimum: the constraint is removed from the schema Claude receives, and the helper checks it in your code afterwards. Cross-field rules follow the same pattern. Line items must add up to the total. A patient's date of birth must sit under patient. These checks run after the model responds, and they are the only place such errors get caught. Tightening the schema with a numeric range or a pattern on the total does not help, because $1,250 is a valid amount. It is wrong only in relation to the other fields.

    Self-correction fields put that relationship into the output. Have the model extract stated_total, the figure printed on the document, and next to it calculated_total, the sum of the line items it extracted. Your validator compares the two. When they differ, you have a specific, checkable discrepancy, and you have it without sending a second model to re-read the document. Asking the model to check its own figures against each other is a lightweight form of iterative refinement.

    Sometimes the document itself is inconsistent: the summary page says one total and the remittance slip says another. Add a conflict_detected boolean so the model can report this instead of quietly choosing one value. This is the single-document version of Annotating conflicting statistics. The flag also controls what happens next. If the totals differ and conflict_detected is false, the model probably made an extraction error, and a retry may fix it. If conflict_detected is true, the inconsistency comes from the document, and another extraction attempt will not resolve it.

    Checkpoint 1 of 7· Check yourself

    A medical-records extractor uses strict tool use with a schema that has patient and guardian objects, each with a required date_of_birth string. Which error can still reach your code and needs a check you write yourself?

    Checkpoint 2 of 7· Exam question

    A purchase-order extractor uses a strict JSON schema, so every response has correctly typed fields and no missing keys. On one order, the extracted line-item amounts sum to $940 while the extracted "order_total" field reads $980. Both values are individually valid against the schema. How should this discrepancy be classified and handled?

    Sources12

    2.What goes into a retry request

    A retry works only when the model can see what went wrong. In an agent loop, the tool-use pattern shows how: when a call fails, the error is returned to the model as a tool_result with is_error: true, and the model reads it and adjusts. An extraction retry applies the same idea to semantic validation. The failures your validator found are passed back to the model as feedback, not discarded.

    Returning a failure to Claude with is_error instead of crashing, so it can correct its next attemptpython
    except Exception as exc:
                    # Signal failure so Claude can retry or ask for clarification.
                    tool_results.append(
                        {
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": str(exc),
                            "is_error": True,
                        }
                    )

    A retry is often a separate Messages API request, and nothing from the first attempt carries over to it. So the follow-up has to include everything the correction depends on:

    1. The original document, so the model checks the correction against the source and does not just rearrange the JSON it produced before.
    2. The failed extraction, so the model can see what it produced, keep the parts that were right and change only the parts that were wrong.
    3. The specific validation errors, written as concrete facts. For example: "date_of_birth is under guardian; it belongs under patient" or "line items sum to 940; stated_total is 980". A message that says only "the output was invalid, try again" gives the model nothing to act on.

    This loop works because two conditions hold: the failure can be checked against clear criteria, and the model's output improves when it gets feedback. Both are signs that a generate-and-evaluate loop fits the task. Your validator supplies the criteria, and the error messages supply the feedback. Keep the number of attempts small. A failure that the first targeted retry does not fix usually belongs to a different category, which is the subject of the next section.

    Checkpoint 3 of 7· Fill the gap

    Your validator rejected a tool call. Which key in the returned tool_result tells Claude the call failed, so it reads the error and corrects its next attempt instead of treating the error text as a normal result?

    except Exception as exc:
                    # Signal failure so Claude can retry or ask for clarification.
                    tool_results.append(
                        {
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": str(exc),
                            " ? ": True,
                        }
                    )

    Sources345

    3.When a retry cannot succeed

    A retry helps only if the correct answer is already in the input. Format mismatches, values placed in the wrong object and line items that were mis-summed can all be fixed, because the source contains the right answer and the feedback points the model to it. Information that is missing from the source is different. If a field was left blank on the paper form, or the figure appears only in a letter that was never sent to the pipeline, no rewording of the request will make it appear. A model pushed to fill a required field it cannot find is being pushed toward inventing a value.

    Failure categories and whether retrying with error feedback can fix them
    FailureIs the answer in the provided source?Does a retry with feedback help?What to do
    Correct value placed in the wrong objectYesYes: the error message names the right locationRetry with the document, the failed output and the error
    Line items do not add up to the extracted total, though the document itself is consistentYesUsually: the model re-reads the source and fixes the misread valueRetry with the calculated and stated totals in the error message
    Document prints two different totals that contradict each otherYes, but the two values contradict each otherNo: the contradiction is in the sourceSend to human review with the conflict flagged
    Field left blank on the scanned formNoNoStop retrying, escalate, and let the field be empty
    Value exists only in an external document that was never providedNoNoSupply that document, or escalate

    When the information is absent, the usual fixes do not help. A stricter schema or a sample format only shapes a value that does not exist. Re-rendering the scan at higher resolution only helps if the field was unreadable, and a blank field is not unreadable. A larger model reads the same empty box. The right response is the other branch of the error-handling pattern: stop retrying, explain the limitation, and send the record to a person who can get the value, often from whoever submitted the document. The Agent SDK has a built-in version of this stopping point. When it runs out of attempts it returns the error_max_structured_output_retries result subtype, and your code has to handle that result.

    Schema design determines whether the model can report a missing value honestly. If the task may not contain every value the schema asks for, make those fields optional or nullable, and tell the model explicitly that it may say the information is not there. A required field that cannot be left empty encourages the model to make something up.

    Checkpoint 4 of 7· Check yourself

    A contract extractor's schema has a required renewal_date string. The contract says only that renewal terms are set out in the Master Agreement, and that document was never sent to the pipeline. Three retries have each returned a different date that appears nowhere in the contract. What is the right next step?

    Checkpoint 5 of 7· Exam question

    A reimbursement pipeline extracts a required "project_code" field from scanned expense reports. On one submission, the employee left the project code blank on the physical form, so it does not appear anywhere in the scanned image. After three retries with error feedback, the field is still empty. What should the pipeline do next?

    Sources362

    4.Feedback loops that improve the reviewer

    Retries fix one output. A feedback loop improves the system that produces the outputs. In a code-review or security-scanning pipeline, the most useful signal is which findings developers dismiss. Every dismissal suggests that a finding may have been a false positive, and false positives cost the tool the developers' trust (False positives and developer trust). A pile of dismissals is useful only if you can group it by something you can change.

    For that, add a detected_pattern field to each structured finding that names the code construct that triggered it: string concatenation into a SQL query, a call to the team's own input-sanitization helper, a regex used for validation. When a developer dismisses a finding, log the dismissal along with that pattern. Over weeks, you get dismissal rates per construct. If one pattern is dismissed most of the time, that construct is producing false positives, and you can address it directly. For example, you can add an explicit criterion to the prompt saying that values passed through the sanitization helper count as sanitized. Like asking the model to cite its sources, the pattern field makes each finding auditable.

    Other fields can look like substitutes. None of them identifies the construct:

    • A dismissal_reason such as false_positive or wont_fix says why developers rejected findings. It does not say which code triggered them, so you know false positives are high but not where they come from.
    • A model-reported confidence score describes the model's certainty, not the code. A high-confidence finding about the sanitization helper is still a false positive.
    • Severity tiers group findings by impact. Findings about one construct appear in every tier, so the tiers spread the trend instead of exposing it.

    Checkpoint 6 of 7· Check yourself

    Over two months, developers have dismissed 40% of a security-review bot's findings. The team wants to know which prompt criterion to change. Which field, added to each structured finding and logged with every dismissal, makes that possible?

    Checkpoint 7 of 7· Exam question

    A security review assistant extracts structured findings from source code and developers frequently dismiss a large share of the findings tied to one particular helper function used for input sanitization. The team wants to analyze this dismissal trend systematically over time. What should be added to the structured finding schema to support this analysis?

    Sources25

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Structured outputs guarantee schema-compliant responses through constrained decoding”
      ↩︎ Validation after the schema has passed
      “Claude receives a simplified schema, but a helper that validates responses still enforces every constraint in your code.”
      ↩︎ Validation after the schema has passed
      “Reliable: No retries needed for schema violations”
      ↩︎ Exam trap 1
      “Type safe: Guaranteed field types and required fields”
      ↩︎ Checkpoint
    2. 2.
      “Use Claude's outputs as inputs for follow-up prompts, asking it to verify or expand on previous statements.”
      ↩︎ Validation after the schema has passed
      “This can catch and correct inconsistencies.”
      ↩︎ Validation after the schema has passed
      “Explicitly give Claude permission to admit uncertainty.”
      ↩︎ When a retry cannot succeed
      “Make Claude's response auditable by having it cite quotes and sources for each of its claims.”
      ↩︎ Feedback loops that improve the reviewer
      “Make Claude's response auditable by having it cite quotes and sources for each of its claims.”
      ↩︎ Exam trap 4
    3. 3.
      “When a tool raises an error, send the error message back with is_error: true instead of crashing.”
      ↩︎ What goes into a retry request
      “Claude reads the error and can retry with corrected input, ask the user for clarification, or explain the limitation.”
      ↩︎ When a retry cannot succeed
      “Claude reads the error and can retry with corrected input, ask the user for clarification, or explain the limitation.”
      ↩︎ Key concept
      “When a tool raises an error, send the error message back with is_error: true instead of crashing.”
      ↩︎ Exam trap 2
    4. 4.
      “Check that the result has the fields you expect, and retry once if it doesn't.”
      ↩︎ What goes into a retry request
    5. 5.
      “LLM responses can be demonstrably improved when feedback is provided”
      ↩︎ What goes into a retry request
    6. 6.
      “If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ When a retry cannot succeed
      “Could not produce valid output”
      ↩︎ When a retry cannot succeed
      “If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ Exam trap 3
      “Match schema to task. If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ Checkpoint

    Spotted a mistake, or was something unclear? Tell us.