Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 20 min · revision 3

Validation, Repair and Retry Budgets

Route each outcome of a structured-output call to the right action: no retry for refusals, more room for truncation, a small repair budget for validation failures and separate transport retries, then measure what each budget buys.

Contentsand lesson path

What you will learn

  • Validate model output in code and handle refusals, truncation and validation failures with a bounded repair or retry.

Prerequisites: LLM API Integration

01. The problem

The lab in lesson 4 left you with a report: 23 good extractions (two only after a retry with more room), 2 honest "cannot answer" results, 1 refusal and 4 replies that failed validation. The tempting fix is one loop: "if anything goes wrong, try again, up to three times". That loop sends a refused document back to be refused again, asks a model to "fix the JSON" of a reply that simply ran out of tokens, sleeps before a repair as if a validation error were a rate limit, and stores nothing useful when it gives up.

In this lesson you replace it with a router. Each outcome gets its own response and its own budget, and every document ends in a known place: stored, stored with a status, or in a review queue with enough context for a person to act. The code builds on extract.py and the fake provider from the lab, so run it in the same so-lab folder with the fake running.

02. Step 1: Decide what each outcome deserves

Start with a table in words, before any code:

  • ok: store it.
  • cannot_answer (not_an_invoice, unreadable): store the status and reason. This is a correct answer, not a failure, and it must never be retried until it "succeeds".
  • refused: no retry. The same input will usually be refused again. Record it and send it to review. Detect it before parsing: OpenAI's Responses API returns a refusal content part (Chat Completions: message.refusal), Claude returns stop_reason: "refusal".
  • truncated: not a quality problem, a size problem. Retry once with a higher limit; if that is still not enough, split the document (for example, line items in pages) or send it to review. Never send the fragment back for "repair". With OpenAI's Chat Completions helper this arrives as a LengthFinishReasonError exception, so catch it explicitly.
  • invalid: the reply finished and matched the schema, but your validators rejected it. This is the only outcome where a repair turn, showing the model its error, can help.
  • transport errors (429 rate limits, 5xx, Claude's 529 overloaded): these are not outcomes of the model at all. Both official Python SDKs retry them with exponential backoff, twice by default, configurable with max_retries; when that budget runs out, the SDK raises an exception, which belongs in your error handling and alerts, not in the repair loop. The lab's urllib client has no transport retries, so with it a 429 surfaces at once as an HTTPError. Keep the transport budget separate from the repair budget, and never sleep before a repair: waiting does not fix a wrong total.

03. Step 2: A bounded repair loop

A repair turn works because it gives the model information it did not have: which field broke which rule. The prompt below includes the field path and the validator's message, sends the model's previous reply back as the assistant turn, and asks for a corrected reply. It does not include stack traces, the raw request or anything secret, and it tells the model not to invent numbers to make a check pass, because some documents really are inconsistent.

The repair is the last message in the conversation and comes from the user. Claude's structured outputs cannot be combined with prefilling the assistant's reply, so the corrected answer always starts fresh. The schema stays the same on every turn, so each repaired reply is still constrained, and still validated.

Python · repair.py
"""Route every outcome; spend a small repair budget only on validation failures."""
import sys
from collections import Counter
from pathlib import Path

from extract import Outcome, extract

MAX_REPAIRS = 2  # semantic repairs per document, set from measured first-repair success
ROUTE = {
    "ok": "store",
    "cannot_answer": "store the status and reason, no invoice",
    "refused": "review queue, no retry",
    "truncated": "split the document, then review",
    "invalid": "review queue, with the validation errors",
    "stopped": "review queue",
}


def repair_prompt(outcome: Outcome) -> str:
    return (
        f"Your JSON failed validation: {outcome.detail}. Re-read the document and "
        "return the corrected JSON. If the document itself is inconsistent, copy "
        "the values exactly as printed; do not invent numbers to make them agree."
    )


def extract_with_repair(provider: str, document: str) -> tuple[Outcome, int]:
    turns = [{"role": "user", "content": document}]
    outcome = extract(provider, turns, max_tokens=800)
    if outcome.kind == "truncated":  # not a repair: give it room, once
        outcome = extract(provider, turns, max_tokens=3200)
    repairs = 0
    while outcome.kind == "invalid" and repairs < MAX_REPAIRS:
        repairs += 1
        turns += [{"role": "assistant", "content": outcome.raw},
                  {"role": "user", "content": repair_prompt(outcome)}]
        outcome = extract(provider, turns, max_tokens=3200)
    return outcome, repairs


provider, chosen = sys.argv[1], sys.argv[2:]
docs = chosen or sorted(p.name for p in Path("docs").iterdir())
final, spent = Counter(), Counter()
for doc in docs:
    outcome, repairs = extract_with_repair(provider, Path("docs", doc).read_text())
    final[outcome.kind] += 1
    spent[repairs] += 1
    if chosen:
        print(f"{doc}: {outcome.kind}, {repairs} repair(s) -> {ROUTE[outcome.kind]}")
print("final outcomes:", " ".join(f"{k}={v}" for k, v in sorted(final.items())))
print("documents by repairs used:",
      " ".join(f"{k}:{v}" for k, v in sorted(spent.items())))

04. Step 3: Run it and read the routes

Run five documents that each show one route, using the Claude-shaped endpoint, then the whole set through the OpenAI-shaped one.

Terminal · in so-lab, with fake_provider.py running
python repair.py anthropic inv-03.txt inv-20.txt inv-26.txt inv-05.txt \
  inv-09.txt
python repair.py openai
Expected output (first command; counts come from the fake)
inv-03.txt: ok, 1 repair(s) -> store
inv-20.txt: invalid, 2 repair(s) -> review queue, with the validation errors
inv-26.txt: refused, 0 repair(s) -> review queue, no retry
inv-05.txt: ok, 0 repair(s) -> store
inv-09.txt: cannot_answer, 0 repair(s) -> store the status and reason, no invoice
final outcomes: cannot_answer=1 invalid=1 ok=2 refused=1
documents by repairs used: 0:3 1:1 2:1
Expected output (second command)
final outcomes: cannot_answer=2 invalid=1 ok=26 refused=1
documents by repairs used: 0:26 1:3 2:1

Follow each document:

  • inv-03 skipped its discount line, failed the totals check, and was fixed by the first repair: the error message told the model exactly where to look.
  • inv-20 failed twice more and went to review. Its printed total really is wrong, and the model correctly refused to invent a number. Repair cannot fix the source document; a person has to.
  • inv-26 was refused and went straight to review, with zero repairs spent.
  • inv-05 was truncated at 800 tokens and succeeded with 3,200. That retry is not counted as a repair.
  • inv-09 is a delivery note: stored with its status, no retries.

Across all 30 documents, three of the four validation failures were fixed with one repair, and one used the full budget and still failed. With a real model these numbers are what you measure, not what you assume.

05. Step 4: Set budgets from measurements

A budget is a number you choose from data. Log, for every document: the outcome, the number of repairs, whether a truncation retry happened, and the tokens used. Then look at the distribution. If nearly every fixable error is fixed by the first repair and the second rarely helps, a budget of one is enough, and the second call is mostly cost. If second repairs often succeed, keep two. Re-measure when you change model, prompt or schema.

Cost grows faster than the number of attempts suggests. Every repair resends the whole conversation (the document, the earlier reply and the error), so each turn costs more input tokens than the last. A per-document token ceiling, checked before each repair, stops one awkward document from costing as much as a hundred normal ones.

Finally, make the review queue useful. Store the document ID, the outcome, the last reply, the validation errors and the number of attempts, but not the document text in your logs if it contains personal data; link to it instead. Watch the rates over time: a jump in refusals, truncations or repairs after a supplier changes their invoice layout is an early warning that the schema, the prompt or the limits need attention.

06. Check your understanding

Practice check · 3 questions

Routing outcomes and spending budgets

Think about which budget each situation should use.

Q1. In the five-document run, `inv-03` and `inv-05` each made two model calls, yet `repair.py` prints 1 repair for `inv-03` and 0 for `inv-05`. Why?
Q2. What should the repair turn in `repair.py` contain?
Q3. Over all 30 documents the second command prints `invalid=1` and `documents by repairs used: 0:26 1:3 2:1`. What does that say about `MAX_REPAIRS = 2`?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish the skill project with this routing:

  • run your 30 documents through repair.py (or your own version) on one real provider, and report outcomes, repairs used per document and truncation retries. Raise the 800 and 3,200 token limits first, as lesson 4 explains: thinking tokens count towards them;
  • choose MAX_REPAIRS from your own first-repair success rate and write one sentence explaining the choice;
  • list what your review queue stores for each document, and check that it contains no secrets or unnecessary personal data.

08. Review prompt

From memory: name the six outcomes and the action for each. Explain why a truncated reply gets more room rather than a repair, why a refusal gets no retry, and why backoff belongs in the SDK's transport retries. Describe how you would pick the repair budget.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check