0Pricing
Claude Architect · Lekcja

Prompty ponawiania z informacją zwrotną

Wyślij dokument, niepoprawne dane wyjściowe i dokładny opis błędu

Prompty ponawiania z informacją zwrotną to bezpłatna lekcja Claude Architect na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Claude Architect, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Claude Architect zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Prompty ponawiania z informacją zwrotną” jest bezpłatna?

Tak — pełny tekst „Prompty ponawiania z informacją zwrotną” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Claude Architect, przejdź na CoddyKit PRO. Kurs Claude Architect zawiera 4 lekcji w sumie.

Co nauczysz się w „Prompty ponawiania z informacją zwrotną”?

Wyślij dokument, niepoprawne dane wyjściowe i dokładny opis błędu Ćwiczysz Claude Architect z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Claude Architect?

Nie wymagamy żadnego doświadczenia. Claude Architect w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Prompty ponawiania z informacją zwrotną”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Claude Architect?

Tak. Każda lekcja Claude Architect zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Kiedy ponowienie pomaga, a kiedy nie
  2. Prompty ponawiania z informacją zwrotną
  3. Samokorekta
  4. Wiele przebiegów i niezależny przegląd
← Powrót do Claude Architect