By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
At 02:10 the invoice loader writes a row with total_cents of zero and two line items totalling 12,900. Nothing in the logs is red. The object was valid: every field had the right type. The retry loop never ran, because it had nothing to retry.
This lesson is about the gate between the model and your database. The gate has three jobs: check the object, send a useful error back, and stop. Miss the first and wrong rows land. Miss the second and the repair never succeeds. Miss the third and a bad document becomes an outage.
Validation means you parse the model's reply into a typed object and refuse anything that does not fit. With the Pydantic library you call model_validate_json, which raises ValidationError with a field-level message. An equivalent library, or a hand-written checker, does the same job.
Two layers matter, and teams usually build only the first. The structural layer covers types, required fields and allowed values. The semantic layer covers totals that match their lines, dates in the right order and ids that exist in your database. JSON Schema and Pydantic cover the structural layer well. The semantic layer is yours to write, and it is where silent errors live.
Every validated call takes one of three paths. It passes first time, it passes after a repair, or it exhausts its attempts and goes to a human. Design all three before you write the loop, because the third path is the one that decides whether the system is safe.
A repair request needs three things: the validation error, the original input and an instruction to change only what failed. Include the model's own invalid reply as an assistant turn so the conversation contains the thing being fixed. Without it, the model regenerates from nothing and often repeats the same mistake.
Send the specific message, not a generic complaint. Pydantic gives you exc.errors(), which names the field and the reason. The object you returned does not validate teaches nothing. total_cents does not equal the sum of line items teaches the repair.
Validate the reply and capture the field-level errors.
Append the invalid reply to the conversation as an assistant message.
Append a user message with the errors, the original input and the instruction to change only those fields.
Validate again and increment the attempt counter.
from pydantic import BaseModel, Field, ValidationError, model_validator
class LineItem(BaseModel):
description: str = Field(min_length=1)
amount_cents: int = Field(ge=0)
class Invoice(BaseModel):
invoice_id: str
line_items: list[LineItem] = Field(min_length=1)
total_cents: int = Field(ge=0)
@model_validator(mode="after")
def total_matches_lines(self):
expected = sum(item.amount_cents for item in self.line_items)
if self.total_cents != expected:
raise ValueError(
f"total_cents is {self.total_cents} but the line items sum to {expected}"
)
return self
REPAIR = (
"Your object did not validate:\n{errors}\n\n"
"The original input was:\n{source}\n\n"
"Return one corrected object with the same fields. "
"Change only the fields the error names."
)
def extract_with_repair(source: str, call_model, max_attempts: int = 3) -> dict:
messages = [{"role": "user", "content": source}]
history = []
for attempt in range(1, max_attempts + 1):
reply = call_model(messages)
try:
invoice = Invoice.model_validate_json(reply)
except ValidationError as exc:
history.append({"attempt": attempt, "errors": exc.errors()})
if attempt == max_attempts:
return {
"status": "needs_human",
"attempts": attempt,
"history": history,
"source": source,
}
messages.append({"role": "assistant", "content": reply})
messages.append({
"role": "user",
"content": REPAIR.format(errors=exc.errors(), source=source),
})
continue
return {
"status": "accepted",
"attempts": attempt,
"invoice": invoice.model_dump(),
}
return {"status": "needs_human", "attempts": max_attempts, "history": history}Two or three attempts is the usual budget. Each attempt costs latency and tokens. A model that failed twice on the same field usually has a reason a third attempt will not fix. The document may be unreadable, the field may be absent, or the rule may be impossible to satisfy.
| Attempt | What you send | If it fails again |
|---|---|---|
| 1 | The original input | Build the repair message with the error |
| 2 | The error, the original input and the invalid reply | Repair once more, and say that this is the last attempt |
| 3 | The same evidence plus the attempt count | Stop: route to human review or a safe default |
The fallback is a product decision, so write it down before launch. Routing to a human preserves the record. A safe default, such as quarantining the document, keeps the pipeline moving. Silently writing a partial row is neither, and it is the option most teams drift into.
Count the repairs while you are there. A repair rate that climbs is the earliest signal that a document format changed, and it costs you one log field to find out.
Add a semantic check to a schema you already use, then make the loop prove it can stop.
Key takeaways
Types catch shape; you must write the semantic checks that catch meaning.
Validate before any downstream code reads the object, not after.
Send the field-level error, the original input and the invalid reply together.
Cap the attempts at two or three, then fall back to human review or a safe default.
Log the attempt count; the repair rate is your earliest quality signal.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.