Retry-with-Feedback Prompts
Send the document, the bad output and the exact error.
Retry-with-Feedback Prompts is a free Claude Architect lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Claude Architect learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
When Retry Actually Works
Structured extraction will sometimes return output that fails validation: a missing required field, a malformed date, a total that doesn't add up. The architect's question is: retry, or escalate?
Retry-with-feedback is the right tool for format, structural, and arithmetic errors. The information exists in the source — the model just rendered it wrong. A second attempt with precise correction usually fixes it.
It does NOT help when the information is simply absent from the source. No amount of retrying invents a phone number that was never on the invoice.
The Three Things You Must Send Back
A naive retry just says "that was wrong, try again." The model has no idea what was wrong, so it guesses — often producing a different wrong answer.
An effective retry-with-feedback prompt sends all three of these together:
- The original document — the model needs the source of truth again; it keeps NO state between calls.
- The bad output — the exact JSON it produced last time.
- The exact validation error — the precise, machine-generated message saying what failed and why.
Remove any one of these and the correction loop degrades into guessing.
Why The Document Must Go Back Too
It is tempting to send only the bad output plus the error to save tokens. Resist that.
The API is stateless: the model keeps no memory between requests — you pass the full message history every turn. On a fresh validation call, the model cannot "remember" the invoice it just read.
To re-derive the correct value, it needs to look at the source document again, compare it against its bad output, and apply the error as a targeted instruction. Drop the document and the model can only reshape its previous guess — it can't ground the fix in reality.
The Error Message Must Be Exact
Vague feedback produces vague fixes. "Be more precise" or "fix the errors" gives the model nothing to act on — explicit criteria always beat vague ones.
Pass the exact validation error straight from your validator: which field, what constraint, what value failed. Pydantic-style validators give you this for free.
Compare:
- Weak: "The output had a problem."
- Strong: "Field 'invoice_date' failed: expected ISO-8601 YYYY-MM-DD, got '14/03/2026'."
The strong version tells the model precisely which token to change and the format to change it to.
from pydantic import BaseModel, ValidationError
from datetime import date
class Invoice(BaseModel):
invoice_number: str
invoice_date: date
total: float
try:
Invoice.model_validate_json(raw_output)
except ValidationError as e:
# e contains the EXACT field, constraint, and bad value
validation_error = e.json()Anatomy of the Retry Prompt
Here is the shape of a correction turn. Notice each of the three inputs has its own clearly labeled block so the model can tell source from output from instruction.
The structure is deliberate: source document, the rejected attempt, and the precise validator error — then a single instruction to return only corrected JSON.
retry_prompt = f"""You extracted data from the document below, but the output failed validation.
<document>
{original_document}
</document>
<your_previous_output>
{bad_output}
</your_previous_output>
<validation_error>
{validation_error}
</validation_error>
Re-read the document, correct ONLY what the validation error reports, and return the full corrected JSON."""Closing The Loop In Code
Wrap the extraction, validation, and retry in a loop. Each iteration appends the bad output and the error, then re-requests. Combine this with tool_choice set to "any" or a forced extraction tool so every attempt is guaranteed to be structured JSON, not prose.
The retry budget is a safety net, not the primary control — the loop should exit the instant validation passes.
def extract_with_retry(document, max_attempts=3):
messages = [{"role": "user", "content": build_prompt(document)}]
for attempt in range(max_attempts):
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[EXTRACT_TOOL],
tool_choice={"type": "any"}, # force structured output
messages=messages,
)
output = get_tool_input(resp)
try:
return Invoice.model_validate(output) # success: exit immediately
except ValidationError as e:
messages = build_retry_messages(document, output, e.json())
raise MaxRetriesExceeded(partial=output)Self-Correction For Arithmetic
Some errors aren't schema violations — they're silent arithmetic mistakes. The JSON is valid, but the total is wrong.
Catch these with a self-correction design: have the model extract both the calculated_total (summing the line items itself) and the stated_total (the figure printed on the document). Your validator compares them.
If they diverge, you have a concrete, exact discrepancy to feed into a retry — far stronger than hoping the model noticed.
EXTRACT_TOOL = {
"name": "extract_invoice",
"description": "Extract invoice fields. Compute calculated_total by summing line items; copy stated_total verbatim from the printed grand total.",
"input_schema": {
"type": "object",
"properties": {
"line_items": {"type": "array", "items": {"type": "object"}},
"calculated_total": {"type": "number"},
"stated_total": {"type": "number"},
},
"required": ["line_items", "calculated_total", "stated_total"],
},
}Knowing When To Stop Retrying
Before each retry, ask: is this fixable by retrying?
If the same field fails for the same reason across attempts, the data is probably absent from the source — retrying won't conjure it. Distinguish a genuine access/format failure (worth retrying) from a valid empty result (the field truly isn't there).
When retries are exhausted, do not silently drop the record. Surface a structured failure with partial results so a human can fill the gap. Silent suppression hides real data-quality problems.
Don't Require Fields That May Be Absent
A subtle trap that causes the very errors you're retrying: marking an optional field as required in your schema.
If a field is sometimes missing from the source but your schema demands it, the model will fabricate a value to satisfy the contract — and a retry just produces a different hallucination.
Mark a field required only when it is always present. For genuinely optional data, leave it out of required. For open-ended categories, use an enum with an "other" value plus a free-text detail field.
Provenance Survives The Retry
When you correct an extraction, don't lose track of where each value came from. Keep claim→source mappings: the document name, the quoted span, and the location.
This matters during retry because the correction instruction can point at the exact source span ("the date appears as '14 March 2026' in the header"), giving the model an anchor. It also lets a human auditor verify the corrected value rather than trusting it blindly.
Provenance turns a fixed value from "the model said so" into "here is the line it came from."
Retry Loops Are Blocking, Not Batch
Where does the retry loop run? If extraction gates a workflow — a document must be validated before it proceeds — that is a blocking, time-sensitive check. Run it as standard synchronous Messages requests.
Do not route blocking validation through the Message Batches API. Batches are 50% cheaper but have no latency SLA (up to a 24h window) and don't support multi-turn tool calling — useless for an interactive correction loop.
Reserve Batch for non-blocking overnight jobs like bulk audits, where each failure can be re-submitted later by custom_id.
Quick Check: Designing The Retry
An extraction pipeline returns JSON whose tax_amount fails Pydantic validation: a string was supplied where a number was required. You want a retry-with-feedback turn most likely to fix it on the next attempt.
Recap: Retry-With-Feedback
Key takeaways for the exam and for production:
- Use it for format, structural, and arithmetic errors — not for information that is absent from the source.
- Send all three: the original document, the bad output, and the exact validation error. The API is stateless, so the document must go back every turn.
- Be exact: pass the precise Pydantic-style error, not "be more precise."
- Self-correct arithmetic by extracting both
calculated_totalandstated_totaland comparing. - Don't require possibly-absent fields — that forces fabrication.
- Exit on success; caps are a safety net. On exhaustion, surface structured partial results — never suppress silently.
- Run it synchronously for blocking checks; reserve Batch for non-blocking jobs.
Frequently asked questions
Is the “Retry-with-Feedback Prompts” lesson free?
Yes — the full text of “Retry-with-Feedback Prompts” is free to read here on the web, and the Claude Architect course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Claude Architect course, upgrade to CoddyKit PRO.
What will I learn in “Retry-with-Feedback Prompts”?
Send the document, the bad output and the exact error. You practise Claude Architect with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Claude Architect?
No prior experience is required. Claude Architect on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Retry-with-Feedback Prompts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Claude Architect lesson?
Yes. Every Claude Architect lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- When Retry Helps (and When It Can't)
- Retry-with-Feedback Prompts
- Self-Correction
- Multi-Pass & Independent Review