By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A payables team automates invoice entry. The extractor returns a clean object for most invoices. Then it meets one that says net 30 from approval and nothing else. The schema marks due_date as required, so the job discards the whole document, including the supplier and the amount it read correctly. A clerk rekeys it by hand.
The second failure is worse. On a scanned purchase order the same extractor returns a due_date that belongs to a shipping notice two pages later. The object is valid. The ledger takes it.
Both failures come from one mistake: the team used required as a stand-in for correct. Scenario 6 asks what the pipeline does when a field is missing. It also asks what happens when the document is not the kind you planned for.
Two things. The queue fills with documents that were readable, and wrong-but-valid values still pass, because a required key says nothing about where the value came from. Rejection is not validation.
Scenario 6 describes one pipeline. A document either becomes a record with provenance, a pointer to the page and text a value came from. Otherwise it goes to a person with a reason. Everything else hangs off that split.
The type gate is the cheapest control in that diagram, and the one teams skip. Deciding invoice, credit note or other before extraction stops a purchase order from arriving as an invoice with a missing field.
Give every field a type, and decide three states in the schema: present and trusted, present but unverified, and absent. null is a value a validator can inspect. A missing key is usually a parsing accident, not a fact about the document.
{
"type": "object",
"additionalProperties": false,
"required": ["invoice_id", "total_cents", "currency", "doc_type", "needs_review"],
"properties": {
"invoice_id": {"type": "string", "minLength": 3},
"total_cents": {"type": "integer", "minimum": 0},
"currency": {"type": "string", "enum": ["EUR", "GBP", "USD"]},
"due_date": {"type": ["string", "null"], "format": "date"},
"doc_type": {"type": "string", "enum": ["invoice", "credit_note", "other"]},
"doc_type_detail": {"type": ["string", "null"]},
"needs_review": {"type": "boolean"},
"review_reason": {"type": ["string", "null"]},
"source_page": {"type": "integer", "minimum": 1}
}
}needs_review and review_reason carry the decision. Require a reason whenever a trusted value is null, so the absence is explained rather than assumed. Then the downstream rule is simple: a record with needs_review true never writes to the ledger.
Keep a closed enum open with an other member plus a detail field. doc_type accepts invoice, credit_note and other, and doc_type_detail is required whenever the value is other. The escape hatch stops the model from forcing a wrong label into a slot that does not fit.
A retry that sends the same prompt again buys a new random answer. A retry that sends the validator's message and the offending snippet buys a repair. Cap the attempts at two. If the same field fails twice, the document is the problem, not the model.
REQUIRED = ("invoice_id", "total_cents", "currency", "doc_type", "needs_review")
def validate(obj: dict) -> list[str]:
"""Return every rule the object breaks, one message per rule."""
errors = [f"missing field: {name}" for name in REQUIRED if name not in obj]
if obj.get("doc_type") not in {"invoice", "credit_note", "other"}:
errors.append("doc_type outside the enum")
if obj.get("doc_type") == "other" and not obj.get("doc_type_detail"):
errors.append("doc_type is other but doc_type_detail is empty")
total = obj.get("total_cents")
if not isinstance(total, int) or total < 0:
errors.append("total_cents must be a non-negative integer")
return errors
def extract(document: str, pending: list[dict], feedback: str | None) -> dict:
"""Stand-in for the model call: the queue holds the replies in order."""
print(f" feedback sent: {feedback}")
return dict(pending.pop(0))
def run(document: str, pending: list[dict], max_attempts: int = 2):
feedback = None
for attempt in range(1, max_attempts + 1):
obj = extract(document, pending, feedback)
errors = validate(obj)
print(f" attempt {attempt}: {len(errors)} error(s)")
if not errors:
return obj, attempt
feedback = "; ".join(errors)
return None, max_attempts
REPLIES = [
{
"invoice_id": "INV-2231",
"total_cents": 41200,
"currency": "EUR",
"doc_type": "other",
"needs_review": True,
},
{
"invoice_id": "INV-2231",
"total_cents": 41200,
"currency": "EUR",
"doc_type": "other",
"doc_type_detail": "pro forma invoice",
"needs_review": True,
},
]
record, attempts = run("page 1 text", REPLIES)
print(f"accepted={record is not None} attempts={attempts}")
if record:
print(f"doc_type={record['doc_type']} detail={record['doc_type_detail']}")The second attempt receives the exact rule that failed. That one change separates a loop that converges from a loop that spends money. Store the attempt count with the record, so a reviewer can see that the value needed a repair.
A document is out of distribution when its layout, language or type is unlike anything you tuned on. A purchase order in the invoice queue, a photographed receipt, a new supplier template. The schema will still be satisfied often enough to look healthy, because many documents contain a total and a date.
| Signal | What it suggests | Control |
|---|---|---|
other rate jumps for one supplier | The template changed | Alert weekly, pause that supplier |
needs_review rate doubles | Extraction is guessing | Sample twenty documents by hand |
| One field is null across a batch | The value moved on the page | Re-read the page, then re-tune |
| Totals disagree with line items | The wrong table was read | Add an arithmetic check before the write |
Every field that matters should point at its source: the page number, and the snippet or box it came from. Provenance lets a clerk verify a value in one click, and lets you audit a sample after the prompt changes.
| Downstream need | What the pipeline emits |
|---|---|
| A stable row identity | An idempotency key of supplier and invoice id |
| Honest nulls | null plus review_reason, never a placeholder date |
| No silent writes | needs_review true blocks the ledger entry |
| An audit trail | Page number and snippet for each trusted field |
The handoff is where most pipelines lose the work they did. The record is correct and the integration drops the reason. Pass the reason through, and give the receiving system one rule it can enforce: refuse a record that is flagged for review.
Take a clean invoice. Write the record you expect, including the page number for the total.
Take an invoice that says net 30 from approval. Decide what due_date and review_reason hold.
Take a purchase order. Decide which gate stops it, and what the clerk sees.
Add one field the document never contains, then read the validator's message.
Definition of done: each document has a stated outcome before you run it, and the ledger never receives a value the validator did not see. A document you cannot place in one of the three outcomes is the one that reaches production unhandled.
Key takeaways
A required key proves presence, not correctness, so a missing field is a value the schema must express.
Use null plus needs_review and review_reason, and keep other with a detail field.
Retry with the validator's message, cap at two attempts, then send the document to a person.
A type gate before extraction is the cheapest defence against out-of-distribution documents.
Provenance and the downstream contract decide whether a clerk can trust a record without rereading the page.
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.