Skip to content
AgenticAIWiki
  1. Learn
  2. Part 2
  3. 14. Structured output
  4. 14.4

Lesson 14.4 · 4 of 8 · 5 min read · Reviewed 24 Nov 2026

Validation-retry loops

By the end, you can

  • Build a validate-and-retry loop for structured output.
  • Feed specific validation errors back to the model.

Even good prompts sometimes produce output that fails a check: a wrong date format, a total that doesn’t add up, a missing field.

The loop

  1. Ask for the structured outputStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types..
  2. Validate in code: schema check, plus business rules (totals add up, dates are real).
  3. If valid, done.
  4. If not, send the specific errors back with the previous output:
Your output failed validation:
- invoice_date "03/04/2025" must match YYYY-MM-DD
- line totals sum to 410.00 but total is 401.00
Return corrected JSON only.
  1. Retry up to a limit, such as 2. After that, send the item to a review queue.

Why specific errors matter

“That was wrong, try again” gives the model nothing to go on. The exact error points at the exact fix.

Semantic checks

A schema can’t tell you that a total is wrong or that a date is in the future. Add those checks yourself. They catch the errors that matter most.

Key points

  • Always validate structured output in code, even with tool_use.
  • On failure, retry with the specific error message so the model can fix that exact problem.
  • Cap retries; after the limit, route the item to a person or a fallback queue.
Hands-on labRuns in the Playground

Build a capped validate and retry loop

Write a retry loop that feeds exact validation errors back, stops at a cap and sends what is left to review.

You will have: A working extract_with_retries function and a run summary over six simulated documents.

Steps

  1. Read fake_model: it fixes an error only when the feedback names that exact error, which mimics why specific feedback works.
  2. Complete validate with two checks: the date must match YYYY-MM-DD, and line totals must add up to the total.
  3. Complete extract_with_retries: validate, and on failure retry with the joined error messages, up to 2 retries.
  4. Send items that still fail to the review list and print the summary.

Done when

  • Documents fixed on retry are counted separately from first-time passes.
  • The document the model can never fix ends in review, not in an endless loop.
  • The script prints 'passed first time: 3, fixed by retry: 2, to review: 1'.

Open in the Playground No API key needed.

Starter code (Python)
import re

DOCS = {
    "inv-1": {"date": "2026-03-04", "lines": [100, 50], "total": 150},
    "inv-2": {"date": "03/04/2026", "lines": [200], "total": 200},
    "inv-3": {"date": "2026-01-09", "lines": [10, 10], "total": 20},
    "inv-4": {"date": "2026-02-11", "lines": [300, 110], "total": 401},
    "inv-5": {"date": "2026-05-30", "lines": [5], "total": 5},
    "inv-6": {"date": "next Tuesday", "lines": [70], "total": 70},
}
UNFIXABLE = {"inv-6"}  # the source has no real date

def fake_model(doc_id, feedback):
    out = dict(DOCS[doc_id])
    if doc_id in UNFIXABLE:
        return out
    if "YYYY-MM-DD" in feedback:
        out["date"] = "2026-03-04"
    if "line totals" in feedback:
        out["total"] = sum(out["lines"])
    return out

def validate(data):
    errors = []
    # TODO: if the date does not match YYYY-MM-DD, add: 'date "<value>" must match YYYY-MM-DD'
    # TODO: if sum(lines) != total, add: 'line totals sum to X but total is Y'
    return errors

def extract_with_retries(doc_id, max_retries=2):
    # TODO: call fake_model(doc_id, feedback), validate, and retry with the specific errors.
    # Return (status, data) where status is "first", "retry" or "review".
    return "first", fake_model(doc_id, "")

summary = {"first": 0, "retry": 0, "review": 0}
for d in DOCS:
    status, _ = extract_with_retries(d)
    summary[status] += 1
print(f"passed first time: {summary['first']}, fixed by retry: {summary['retry']}, to review: {summary['review']}")
Show a solution
import re

DOCS = {
    "inv-1": {"date": "2026-03-04", "lines": [100, 50], "total": 150},
    "inv-2": {"date": "03/04/2026", "lines": [200], "total": 200},
    "inv-3": {"date": "2026-01-09", "lines": [10, 10], "total": 20},
    "inv-4": {"date": "2026-02-11", "lines": [300, 110], "total": 401},
    "inv-5": {"date": "2026-05-30", "lines": [5], "total": 5},
    "inv-6": {"date": "next Tuesday", "lines": [70], "total": 70},
}
UNFIXABLE = {"inv-6"}  # the source has no real date

def fake_model(doc_id, feedback):
    out = dict(DOCS[doc_id])
    if doc_id in UNFIXABLE:
        return out
    if "YYYY-MM-DD" in feedback:
        out["date"] = "2026-03-04"
    if "line totals" in feedback:
        out["total"] = sum(out["lines"])
    return out

def validate(data):
    errors = []
    if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", data["date"]):
        errors.append(f'date "{data["date"]}" must match YYYY-MM-DD')
    if sum(data["lines"]) != data["total"]:
        errors.append(f"line totals sum to {sum(data['lines'])} but total is {data['total']}")
    return errors

def extract_with_retries(doc_id, max_retries=2):
    feedback = ""
    for attempt in range(max_retries + 1):
        data = fake_model(doc_id, feedback)
        errors = validate(data)
        if not errors:
            return ("first" if attempt == 0 else "retry"), data
        feedback = "Your output failed validation:\n- " + "\n- ".join(errors) + "\nReturn corrected JSON only."
    print(f"{doc_id} to review: {errors}")
    return "review", data

summary = {"first": 0, "retry": 0, "review": 0}
for d in DOCS:
    status, _ = extract_with_retries(d)
    summary[status] += 1
print(f"passed first time: {summary['first']}, fixed by retry: {summary['retry']}, to review: {summary['review']}")

Do it Build a validated extractor in the Playground in the Playground. No API key needed.

Quick checkExtracted JSON fails validation: 'date must match YYYY-MM-DD'. What's the best retry?
How sure are you?
Pick an answer and how sure you are