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?
Constrained decoding guarantees valid syntax, correct field types and required fields, so the first three cannot happen. A well-formed date placed under the wrong object passes the schema, because each field is valid when checked alone. Only your own semantic validation can catch it.
“Type safe: Guaranteed field types and required fields”Source: platform.claude.com
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?
Correct answer: A — Semantic error the schema cannot detect; add a post-extraction check that recomputes the line-item sum and compares it to order_total
- A. Correct. Strict schemas enforce types and required keys, but a mismatch between two individually valid values is a semantic error. Application code has to recompute the sum from the line items and compare it with the stated total.
- B. Incorrect. A range or pattern on one field checks only that field's own value. JSON Schema cannot express that one number must equal the sum of other fields, so a total of $980 still passes. The inconsistency needs a cross-field check outside the schema.
- C. Incorrect. Examples can make mismatches less frequent, but they give no guarantee and no detection. Both values already satisfy the schema, so an inconsistent total can still be returned unnoticed. Only an explicit comparison against the line items catches it.
- D. Incorrect. Retrying with a lower temperature accepts any response that passes schema validation, and a response with mismatched totals passes that test. Arithmetic disagreement between fields is a recurring extraction risk, so a deterministic consistency check is needed.
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.
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:
- The original document, so the model checks the correction against the source and does not just rearrange the JSON it produced before.
- 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.
- 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.
Moving the field produces correct structure, but nothing checks the value. The model could move a date that was misread in the first place. With the document in the request, the corrected output is a complete extraction that can be checked against the source form, not just a reshuffle of the earlier output.
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,
}
)The failure is sent back as a tool_result with is_error: true and the exception text as content. Claude reads that specific error and can retry with corrected input. The program does not crash, and the error is not thrown away. 'strict' is the tool-definition flag for schema enforcement, and 'retry' and 'error_feedback' are not tool_result fields.
Source: platform.claude.com3.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 | Is the answer in the provided source? | Does a retry with feedback help? | What to do |
|---|---|---|---|
| Correct value placed in the wrong object | Yes | Yes: the error message names the right location | Retry with the document, the failed output and the error |
| Line items do not add up to the extracted total, though the document itself is consistent | Yes | Usually: the model re-reads the source and fixes the misread value | Retry with the calculated and stated totals in the error message |
| Document prints two different totals that contradict each other | Yes, but the two values contradict each other | No: the contradiction is in the source | Send to human review with the conflict flagged |
| Field left blank on the scanned form | No | No | Stop retrying, escalate, and let the field be empty |
| Value exists only in an external document that was never provided | No | No | Supply 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?
The date is not in anything the model received, so no retry, larger model or tighter schema can recover it. Making the field required only pushes the model to invent a value. Make the field optional, stop retrying, and escalate the record or provide the missing document.
“Match schema to task. If the task might not have all the information your schema requires, make those fields optional.”Source: code.claude.com
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?
Correct answer: A — Stop the retry loop and send the record to a human reviewer, so the project code can be obtained from the submitter
- A. Correct. Retries only help with format or structural failures. The employee left the project code blank, so the value is not in the source and no extraction attempt can produce it. The record needs a person who can get the code from the submitter.
- B. Incorrect. A stricter schema and a format example address malformed output, but the field is empty because the form never contained a value. Three retries with error feedback have already shown that formatting guidance is not the problem.
- C. Incorrect. Higher resolution helps when a value is present but hard to read. Here the code was left blank on the physical form, so a sharper image shows the same empty space and the field stays unfilled.
- D. Incorrect. A larger model reads documents more accurately, but it cannot find a value that is not on the page. Sending the error history does not change the scan, so the field stays empty or the model may invent a code.
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_reasonsuch 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?
Only a field that names the triggering code construct lets you group dismissals by something you can change in the review criteria, for example a rule that values passed through the sanitization helper count as sanitized. A dismissal reason says why a finding was rejected, not what triggered it. Confidence describes the model's certainty, not the code. Severity tiers spread one construct's findings across every tier.
“Make Claude's response auditable by having it cite quotes and sources for each of its claims.”Source: platform.claude.com
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?
Correct answer: A — Add a detected_pattern field that names the code construct behind each finding, so dismissal rates can be compared per construct
- A. Correct. Dismissals cluster around findings tied to one helper function, so each finding must record which code construct triggered it. A detected_pattern field gives a stable grouping key, so dismissal rates can be aggregated per construct over time and the noisy detection can be isolated.
- B. Incorrect. Preset dismissal categories are structured, but they describe why a reviewer rejected a finding, not what produced it. Many constructs would share the same category, so the helper-function pattern cannot be separated out and tracked.
- C. Incorrect. A confidence score reflects how certain the model is, and it is not tied to a particular construct. Bucketing dismissals by score band shows nothing about which helper function's findings are being rejected, so the trend stays unattributed.
- D. Incorrect. Severity describes impact, so dismissals grouped by tier mix findings from many different constructs. The tier does not identify the sanitization helper that keeps triggering rejected findings, so the pattern-specific trend cannot be isolated.
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/reduce-hallucinationsOfficial docs
“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.
“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.https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5Official docs
“Check that the result has the fields you expect, and retry once if it doesn't.”
↩︎ What goes into a retry request - 5.
“LLM responses can be demonstrably improved when feedback is provided”
↩︎ What goes into a retry request“Clear evaluation criteria”
↩︎ Feedback loops that improve the reviewer - 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