Skip to content

Courses / GenAI & LLM / Module 4

Module 4: Structured output and document extraction: schemas, validation, retries

10 h · theory 3 · hands-on 4 · project 2 · revision 1

You will be able to

  • Design Pydantic schemas that models can fill reliably
  • Use JSON modes, tool calling and Instructor to get validated output
  • Retry and repair invalid output, and score field-level confidence
  • Extract fields from invoices, contracts or résumés with a human-review path

Capstone increment: /extract endpoint: document in, validated JSON out, with confidence per field and a review queue for low-confidence fields.

Job-description skills: Structured output, Pydantic, Document extraction · Lab tools: pydantic, instructor, pymupdf, pytest

1. Never parse free text again

Downstream code needs fields, not prose. Asking a model to “return JSON” works most of the time, and most of the time is not good enough for invoices or contracts. Use the strongest mechanism your provider offers: a schema-constrained mode (OpenAI Structured Outputs, JSON-schema mode in vLLM and Ollama), or tool calling with a schema, which every major provider supports.

Even with constrained decoding, the JSON can be valid but wrong: a date in the wrong field, a total that doesn't match the line items, a GSTIN with a bad checksum. Syntax is the provider's job; semantics are yours.

DocumentPDF, scan, emailParsetext + layoutModel + schematool call / JSONValidatePydantic rulesConfidenceper fieldAuto-acceptall fields ≥ thresholdReview queuea human checksStorewith audit trailDocument in, validated JSON outRoute each recordinvalid: send the error back, retry (max 2)highlow
Never trust free text: validate, repair, and route uncertain fields to a person.

2. Design schemas models can fill

Write the schema in Pydantic and generate the JSON Schema from it. Use clear field names and descriptions (the model reads them), enums for closed sets, Optional for fields that may be absent, and ISO dates.

Make absence explicit. If a field can be missing, let it be null and tell the model to return null rather than guess. A required field forces the model to invent something when the document doesn't contain it.

Keep schemas shallow and split huge ones. One call extracting 60 fields is less accurate than three calls of 20 grouped by section, and it's much harder to debug.

Common misconception: “Constrained JSON mode means the output is correct.” It only guarantees the shape. Validators and cross-field checks are what catch wrong values.

3. Validate, repair, retry

Put business rules in validators: the GSTIN matches the format and its checksum, the due date isn't before the invoice date, line items sum to the subtotal. When validation fails, send the error messages back to the model and ask it to correct only those fields. Cap repairs at two attempts, then route to a person.

Instructor wraps this loop: you pass a Pydantic model as the response type and a retry count, and it re-asks with the validation errors for you. Write the loop by hand once (the starter code does) so you understand what the library does on your behalf.

In production: Log every repair. A field that needs repair 20% of the time is a prompt or schema problem worth fixing, not a retry budget to keep paying.

4. Confidence you can actually use

Asking the model “how confident are you?” gives numbers that barely relate to accuracy: models are often 95% sure of wrong answers. Build confidence from signals instead: did validators pass, did two independent runs (different temperature or model) agree, is the value present verbatim in the source text, how good was the OCR on that region.

Then pick an auto-accept threshold from data, not intuition: label a sample by hand, and choose the threshold that keeps shipped errors under your target with the least review work. Try both kinds of confidence in the tool below.

Auto-accept or review?24 fields from 6 invoices; 6 are wrong. Choose where confidence comes from, then set the auto-accept threshold.

Auto-accepted 21 · sent to review 3 (13% of the work) · errors that slip through 6 of 6

DocumentFieldValueScoreRoute
INV-101invoice_noINV-101 0.99accepted
INV-101total₹48,260.00 0.97accepted
INV-101gstin29ABCDE1234F1Z5 0.95accepted
INV-101due_date2026-12-15 0.96accepted
INV-102invoice_noA/2026/0193 0.98accepted
INV-102total₹1,18,000.00 0.95accepted
INV-102gstin27AAACR5055K1ZV ✗ wrong0.94accepted: error shipped
INV-102due_date2026-01-12 ✗ wrong0.93accepted: error shipped
INV-103invoice_no7781 0.97accepted
INV-103total₹9,440.00 ✗ wrong0.96accepted: error shipped
INV-103gstin(none found) 0.60review
INV-103due_dateon receipt 0.70review
INV-104 (scan)invoice_noSB-55O2 ✗ wrong0.92accepted: error shipped
INV-104 (scan)total₹23,600.00 0.90accepted
INV-104 (scan)gstin33AABCT1332L1ZZ 0.91accepted
INV-104 (scan)due_date2026-11-30 0.93accepted
INV-105invoice_noINV-105 0.99accepted
INV-105total$1,240.00 0.98accepted
INV-105gstin(foreign vendor) 0.85review
INV-105due_date2027-01-05 0.97accepted
INV-106invoice_no2026-PO-18 ✗ wrong0.95accepted: error shipped
INV-106total₹5,90,000.00 0.96accepted
INV-106gstin07AAGCM1234Q1Z2 0.94accepted
INV-106due_date2026-12-01 ✗ wrong0.91accepted: error shipped
Guided experiments
  1. With “Model says how sure it is”, find a threshold that catches every error. How much of the work goes to review? Why are self-reported scores close to useless here?
  2. Switch to the calibrated score (built from validation checks, agreement between two extraction runs and the field type). Find the threshold that catches all errors now. How much review work does it need?
  3. The GSTIN on INV-102 and the date on INV-102 are wrong but look plausible. Which cheap code checks (a checksum, “due date after invoice date”) could have caught them before any model scoring?
  4. If a shipped error costs ₹2,000 to fix and a review costs ₹40, which threshold minimises total cost on this sample?

5. Getting text out of documents

Most extraction errors start before the model: a PDF parser that scrambles columns, a table read row by row in the wrong order, or OCR that turns 0 into O. For digital PDFs use PyMuPDF to get text with positions; for scans you need OCR, or a vision-capable model that reads the page image directly.

Keep page numbers and positions with the text. They let you show reviewers where each value came from, which speeds up review and builds trust. The RAG Systems course goes deeper into layout-aware parsing.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

Lab 4.1: Instructor extraction

Extract the Invoice schema from 20 sample invoices with Instructor and a local model, with max_retries=2. Record how many succeed first time, after one repair, after two, and never.

Expected: A table of attempts per document and the three most common validation errors.

Lab 4.2: /extract endpoint with review queue (capstone increment)

Add POST /extract: upload a PDF, parse with PyMuPDF, extract with schema validation and repair, score each field’s confidence, auto-accept above a threshold and put the rest into a review table with the source page.

Expected: The endpoint returns validated JSON with a confidence per field; low-confidence fields appear in GET /review; tests cover a valid, a repaired and a rejected document.

Lab 4.3: Choose the threshold from data

Hand-check 100 extracted fields. Compute, for thresholds from 0.5 to 0.95, the share of shipped errors and the share of review work. Pick a threshold for “under 1% shipped errors”.

Expected: A threshold table and a chosen value, saved as configuration with a note on how it was picked.

Go deeper

Videos

Further reading

GitHub repositories

  • 567-labs/instructor: The retrying and validation docs, and the examples folder for document extraction patterns.
  • pydantic/pydantic: Field and model validators, and model_json_schema(): how your schema becomes the JSON Schema the model sees.
  • pymupdf/PyMuPDF: Text extraction with positions (page.get_text with 'dict' or 'blocks') to keep page and location for each value.

Checkpoint quiz

1. A field may be missing from some documents. How should the schema handle it?
2. Constrained JSON decoding guarantees…
3. Validation fails on two fields. The best next step is…
4. Why are self-reported model confidence scores a weak routing signal?
5. Most extraction errors on scanned invoices start…

Interview questions

  1. Design an invoice-extraction service that must ship fewer than 1% wrong fields. Where do errors come from and how do you catch each kind?
  2. How do you compute a useful confidence score for an extracted field?
  3. When would you use tool calling instead of a JSON mode to get structured output?
  4. How do you decide the auto-accept threshold, and how do you keep it right over time?
  5. What changes when the documents are phone photos instead of digital PDFs?

Ask the professor

Sign in to ask questions about this module.

Discussion

Community discussion appears here once giscus is configured (see README).