피드백과 함께 재시도하는 프롬프트
문서, 잘못된 출력, 정확한 오류를 함께 전송합니다
피드백과 함께 재시도하는 프롬프트은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“피드백과 함께 재시도하는 프롬프트” 강의는 무료인가요?
네 — “피드백과 함께 재시도하는 프롬프트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
“피드백과 함께 재시도하는 프롬프트”에서 뭘 배우나요?
문서, 잘못된 출력, 정확한 오류를 함께 전송합니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Claude Architect을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“피드백과 함께 재시도하는 프롬프트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 재시도가 도움이 될 때와 그렇지 않을 때
- 피드백과 함께 재시도하는 프롬프트
- 자기 수정
- 다중 패스 및 독립 검토