Claude Architect · 课时

带反馈的重试提示词

发送文档、错误输出和确切的错误信息。

第 2 / 4 课13 个步骤

带反馈的重试提示词 是 CoddyKit 上的免费 Claude Architect 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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_total and stated_total and 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.
免费开始

用 AI 导师学习 Python — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
26
课程
104

常见问题解答

「带反馈的重试提示词」课时是免费的吗?

是的 — 「带反馈的重试提示词」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Claude Architect 课程的其余内容,请升级到 CoddyKit PRO。 Claude Architect 课程共包含 4 节课。

「带反馈的重试提示词」这节课中我会学到什么?

发送文档、错误输出和确切的错误信息。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Claude Architect 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Claude Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「带反馈的重试提示词」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Claude Architect 课中编写并运行代码吗?

能。每节 Claude Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 何时重试有帮助(以及何时无效)
  2. 带反馈的重试提示词
  3. 自我纠正
  4. 多轮处理与独立审查
← 返回 Claude Architect