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.
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.
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.
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-accepted 21 · sent to review 3 (13% of the work) · errors that slip through 6 of 6
| Document | Field | Value | Score | Route |
|---|---|---|---|---|
| INV-101 | invoice_no | INV-101 | 0.99 | accepted |
| INV-101 | total | ₹48,260.00 | 0.97 | accepted |
| INV-101 | gstin | 29ABCDE1234F1Z5 | 0.95 | accepted |
| INV-101 | due_date | 2026-12-15 | 0.96 | accepted |
| INV-102 | invoice_no | A/2026/0193 | 0.98 | accepted |
| INV-102 | total | ₹1,18,000.00 | 0.95 | accepted |
| INV-102 | gstin | 27AAACR5055K1ZV ✗ wrong | 0.94 | accepted: error shipped |
| INV-102 | due_date | 2026-01-12 ✗ wrong | 0.93 | accepted: error shipped |
| INV-103 | invoice_no | 7781 | 0.97 | accepted |
| INV-103 | total | ₹9,440.00 ✗ wrong | 0.96 | accepted: error shipped |
| INV-103 | gstin | (none found) | 0.60 | review |
| INV-103 | due_date | on receipt | 0.70 | review |
| INV-104 (scan) | invoice_no | SB-55O2 ✗ wrong | 0.92 | accepted: error shipped |
| INV-104 (scan) | total | ₹23,600.00 | 0.90 | accepted |
| INV-104 (scan) | gstin | 33AABCT1332L1ZZ | 0.91 | accepted |
| INV-104 (scan) | due_date | 2026-11-30 | 0.93 | accepted |
| INV-105 | invoice_no | INV-105 | 0.99 | accepted |
| INV-105 | total | $1,240.00 | 0.98 | accepted |
| INV-105 | gstin | (foreign vendor) | 0.85 | review |
| INV-105 | due_date | 2027-01-05 | 0.97 | accepted |
| INV-106 | invoice_no | 2026-PO-18 ✗ wrong | 0.95 | accepted: error shipped |
| INV-106 | total | ₹5,90,000.00 | 0.96 | accepted |
| INV-106 | gstin | 07AAGCM1234Q1Z2 | 0.94 | accepted |
| INV-106 | due_date | 2026-12-01 ✗ wrong | 0.91 | accepted: error shipped |
Guided experiments
- 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?
- 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?
- 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?
- 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 codeLabs
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
- Pydantic is all you need: Jason Liu · AI Engineer · ~17 min. The case for schema-first LLM output from the author of Instructor.
- FastAPI Course for Beginners · freeCodeCamp.org · ~64 min. Request validation and file uploads for the /extract endpoint.
Further reading
- Docs Pydantic documentation · Pydantic. Models, validators and JSON Schema generation: the validation layer used throughout this course.
- Docs Understanding JSON Schema · JSON Schema. What tool and output schemas are written in; read the sections on types, enums and required fields.
- Docs Instructor · Jason Liu and contributors. Structured output with Pydantic models, validation and automatic retries across providers.
- Paper Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of LLMs · Tam et al., 2024. Evidence that forcing strict formats can hurt reasoning, and how to structure output without losing quality.
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
Interview questions
- 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?
- How do you compute a useful confidence score for an extracted field?
- When would you use tool calling instead of a JSON mode to get structured output?
- How do you decide the auto-accept threshold, and how do you keep it right over time?
- 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).