AI Engineering · Build lab 3 of 14
LLM structured output in Python: JSON Schema, Pydantic validation and retries
Turn messy invoice text into a typed Pydantic object you can trust. See why "please reply in JSON" breaks, send a JSON Schema with response_format, validate with Pydantic, feed errors back to the model in a retry loop, check business rules, and run a whole folder with a report. Plus Spring AI entity().
⏱ 60 minBeginner to intermediate💸 Free (local model)10 stepsPython + Java
Python 3.12uvOllama 0.5+llama3.2:3bopenai SDKPydantic 2pytestSpring AI 1.0 (optional)
Overview video
What you will build
An invoice extractor: a command-line program that reads invoice text (an email, a printed PDF turned into text, a German invoice with commas for decimals) and returns a validated Invoice object with the vendor, date, currency, line items, shipping, tax and total.
You build it the way real teams end up building it. First the naive way, so you see exactly how it breaks. Then you let a JSON Schema generated from your Pydantic model drive the model, validate every reply, send validation errors back for a second try, check rules the schema cannot express (do the line items, shipping and tax add up to the total?), and process a whole folder into a report.json with ok, review and failed rows.
Everything is tested with a fake client, so the tests run in milliseconds with no model at all.
Before you start
- Lab 1 done: Your first LLM call. This lab reuses its
.envandconfig.py. - Pydantic basics: Type hints and Pydantic. You only need
BaseModelandField; each new piece is explained here. - The idea behind it (8 minutes): Structured output explains JSON mode and constrained decoding.
- Ollama 0.5 or newer (that is when it learned JSON Schema output).
Setup
S1Same setup as lab 1
You need uv, Ollama and the llama3.2:3b model from lab 1's setup. If you did lab 1, they are already installed. Check uv:
uv --version uv 0.x.y
S2Check your Ollama version (0.5 or newer)
JSON Schema output (the key feature of this lab) arrived in Ollama 0.5. On an older version the request still works, but the schema is ignored. Update from ollama.com/download if the number is lower.
ollama --version ollama version is 0.x.y
S3Make sure the model is there
ollama list shows the models you have pulled. If llama3.2:3b is missing, run ollama pull llama3.2:3b (about 2 GB).
ollama list NAME ID SIZE MODIFIED llama3.2:3b a80c4f17acd5 2.0 GB 2 days ago
S4Java only (optional): JDK 21 and Maven
Only for the Spring AI version of step 6 (switch to Java at the top of the steps). Same tools as lab 1.
brew install openjdk@21 mavensudo apt install openjdk-21-jdk mavenwinget install Microsoft.OpenJDK.21 Apache.Maven Create the project
A fresh project with the SDK, Pydantic and pytest, plus the settings from lab 1.
uv init creates the project folder and pyproject.toml (like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them there.
New this time: pydantic, the validation library. You describe the data with a class, and Pydantic checks real data against it, converts types, and can export the description as a JSON Schema. Think Jackson plus Bean Validation, or Zod in TypeScript, in one library.
Copy config.py, .env and .gitignore from lab 1 (they are shown again below), and add llm.py: one function that builds the client, so every script and test gets it the same way.
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
# A hosted API instead: change these three lines, nothing else.
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# LLM_MODEL=the-model-name - Ollama's OpenAI-compatible API. The same code talks to any provider with this request shape.line 2
import os
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv() # read .env into environment variables (real env vars win)
@dataclass(frozen=True)
class Settings:
base_url: str
api_key: str
model: str
def settings() -> Settings:
return Settings(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "ollama"),
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
) - Copies
.envintoos.environ. Real environment variables win, which is what you want on a server.line 6 - One place for the three settings. Unchanged from lab 1.line 16
.venv/
__pycache__/
.env - Never commit
.env: one day it holds a real key.line 3
from openai import OpenAI
from config import settings
def make_client() -> OpenAI:
s = settings()
return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2) - A function, not a global: tests never call it, they pass in a fake client instead (step 10).line 6
- Extraction replies are long (a whole JSON object), and a local model on a laptop CPU is slow. 120 seconds is generous on purpose.line 8
max_retries=2retries network errors, 429 and 5xx. That is different from the retry loop in step 7, which retries **bad answers**.line 8
uv init invoice-extractor
cd invoice-extractor
uv add openai pydantic python-dotenv
uv add --dev pytest Initialized project `invoice-extractor` at `.../invoice-extractor` Resolved 17 packages in 420ms Installed 15 packages in 30ms + openai==3.60.0 + pydantic==2.14.4 + pydantic-core==2.50.5 + python-dotenv==1.2.4 ...
make_client() is what makes the whole lab testable: the extraction code receives a client as a parameter (dependency injection), so a test can hand it a fake.Stuck on this step?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux) or open a new terminal. - uv also created
main.py - Newer uv versions write a hello-world
main.py. You replace it in step 6, so leave it or delete it.
Four messy invoices to test with
Realistic input: different layouts, formats and two invoices with real problems.
Make a folder called invoices and put these four text files in it. Each one tests something different:
- acme.txt: a printed table with
$signs, a thousands separator ($1,025.00) and a shipping charge below the item table. The items add up to 966.00; only items plus shipping make the 1,025.00 total. - berlin.txt: a German invoice. The date is
14.02.2025, decimals use a comma (89,50 €) and1.000means one thousand. - mismatch.txt: an email whose items add up to 126.00 but the total says 136.00. The extraction can be perfect and the invoice still wrong.
- future.txt: a typo in the year (2062). Valid JSON, valid date, still clearly wrong. (Watch what a small model does with it in step 9.)
The last two are on purpose: step 8 catches them with business rules.
ACME TOOLS LTD INVOICE #A-1043
42 Mill Road, Leeds
Date: 3 March 2025 Payment due: 30 days
Qty Item Price Amount
2 Claw hammer $12.50 $25.00
10 Box of wood screws (200) $4.20 $42.00
1 Cordless drill, 18V $899.00 $899.00
Subtotal $966.00
Shipping $59.00
TOTAL $1,025.00 USD
Thanks for your business! - Shipping is not an item, but the total includes it. So the
Invoicemodel gets its ownshippingfield (step 4), and the total rule in step 8 adds it in.line 12
Rechnung / Invoice Nr. 2025-117
Druckerei Weber GmbH, Berlin
Datum: 14.02.2025
Pos. Beschreibung Menge Einzelpreis Betrag
1 Flyer A5, 1.000 Stück 2 89,50 € 179,00 €
2 Visitenkarten 1 45,00 € 45,00 €
Gesamtbetrag: 224,00 EUR - Day first: 14 February. The model must turn this into
2025-02-14.line 3 1.000 Stückis "1,000 pieces" (the product), and89,50 €is 89.50.line 6
From: Bright Office Supplies <billing@brightoffice.example>
Subject: Invoice BO-889
Hi! Here's your invoice dated 2025-01-20.
- 5 x printer paper (500 sheets) @ 6.00 = 30.00
- 2 x toner cartridge @ 48.00 = 96.00
Total due: 136.00 USD - 30.00 + 96.00 is 126.00, not 136.00. A real vendor mistake.line 7
NORTHWIND CONSULTING
Invoice date: 15 Jan 2062
Description: Architecture review, 8 hours at 150.00 per hour = 1200.00
Amount due: 1200.00 GBP - Probably meant 2026. A schema cannot catch this, and a small model may quietly "fix" it for you. Step 9 shows why that matters.line 2
The naive way: ask for JSON and hope
See what a model really returns when you only ask for JSON in the prompt.
The first thing everyone tries: describe the keys in the prompt and parse the reply with json.loads (Python's JSON.parse). Run it on the Acme invoice.
Small models usually add a friendly sentence, wrap the JSON in a Markdown code fence, or both. json.loads needs the reply to be only JSON, so it fails. Bigger models fail less often, but "less often" across thousands of invoices is still every day.
import json
import sys
from pathlib import Path
from config import settings
from llm import make_client
path = Path(sys.argv[1] if len(sys.argv) > 1 else "invoices/acme.txt")
prompt = (
"Extract this invoice as JSON with the keys vendor, invoice_date, currency, "
"line_items (each with description, quantity, unit_price, amount) and total.\n\n"
+ path.read_text()
)
resp = make_client().chat.completions.create(
model=settings().model,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
reply = resp.choices[0].message.content
print("--- the model's reply ---")
print(reply)
print("--- json.loads(reply) ---")
try:
data = json.loads(reply)
print("parsed! total =", repr(data.get("total")))
except json.JSONDecodeError as e:
print("JSONDecodeError:", e) sys.argvis the command-line arguments (argsin Java);sys.argv[0]is the script name. No argument: use the Acme invoice.Pathis likejava.nio.file.Path.line 8- Strings in parentheses next to each other are joined into one string.
+ path.read_text()adds the invoice text.line 9 - Temperature 0: the most likely token every time. For extraction you want facts, not creativity.line 18
json.loadsturns a JSON string into dicts and lists, likeJSON.parse. It raisesjson.JSONDecodeErrorif the text is not pure JSON.line 25repr()shows the value with its type visible:'1,025.00'(a string, in quotes) versus1025.0(a number).line 26
uv run naive.py invoices/acme.txt --- the model's reply ---
Here is the extracted invoice in JSON format:
```json
{
"vendor": "ACME TOOLS LTD",
"invoice_date": "3 March 2025",
...
"total": "$1,025.00"
}
```
--- json.loads(reply) ---
JSONDecodeError: Expecting value: line 1 column 1 (char 0) json.loads works, look at the values: "3 March 2025" and "$1,025.00" are strings. Nothing has checked the shape or the types yet. The next step makes that visible without needing a model.Stuck on this step?
- Mine parsed fine!
- Run it on the other invoices (
uv run naive.py invoices/berlin.txt), or run it a few times. The point is that nothing guarantees it. Step 4 shows the failures in a repeatable way. httpx.ConnectError/APIConnectionError- Ollama is not running. Open the Ollama app or run
ollama serve.
Describe the invoice with Pydantic
One class says what a valid invoice is, and catches every problem the naive way lets through.
A Pydantic model is a class whose type hints are enforced. Invoice.model_validate(data) checks a dict against the class and gives you a typed object, or raises ValidationError listing every problem at once (not just the first).
Pydantic is lenient by default ("lax mode"): the string "12.50" becomes the number 12.5, and "2025-03-03" becomes a date. That is what you want with model output. Things it cannot convert, like "two" or "$", are errors.
breakages.py replays three replies that small models really produce, so you can see each failure the same way every time. No model needed.
from datetime import date
from pydantic import BaseModel, Field
class LineItem(BaseModel):
description: str
quantity: float = Field(gt=0)
unit_price: float
amount: float = Field(description="quantity times unit_price")
class Invoice(BaseModel):
vendor: str = Field(min_length=1)
invoice_date: date
currency: str = Field(pattern=r"^[A-Z]{3}$", description="ISO 4217 code, like USD")
line_items: list[LineItem] = Field(min_length=1)
shipping: float = Field(default=0, ge=0, description="shipping or delivery charge; put it here, not in line_items")
tax: float = Field(default=0, ge=0, description="tax or VAT amount; put it here, not in line_items")
total: float dateis a calendar date with no time, like Java'sLocalDate.line 1- Subclassing
BaseModelmakes this a validated data class. Like a Java record, with checking built in.line 6 - Read it as "quantity is a float, and must be greater than 0".
Field(...)in the default-value position adds rules, like@Positivein Bean Validation.line 8 descriptiontext goes into the JSON Schema, so the model reads it too. Short hints here help extraction.line 10- In JSON a date is a string. Pydantic accepts
"2025-03-03"and gives you a realdateobject.line 15 - A regex: exactly three capital letters (USD, EUR).
r"..."is a raw string: backslashes are not escapes, handy for regexes.line 16 list[LineItem]isList<LineItem>. Each item is validated as aLineItem.min_length=1: at least one line.line 17- Shipping gets its own field.
default=0: an invoice without shipping can leave it out.ge=0: never negative. Thedescriptiontells the model to put shipping here and **not** as an extra line item.line 18 - The same for tax or VAT. Without these two fields a small model either drops them (and the total no longer adds up) or invents line items like "Taxes 0.00".line 19
- Floats for money keep this lab simple; step 8 compares amounts in whole cents to avoid float surprises. Production code often uses
Decimal.line 20
import json
from pydantic import ValidationError
from models import Invoice
# Three replies small models really give when you only *ask* for JSON.
REPLIES = {
"prose around the JSON": 'Sure! Here is the invoice:\n```json\n{"vendor": "Acme Tools"}\n```',
"wrong types": json.dumps({
"vendor": "Acme Tools",
"invoice_date": "March 3, 2025",
"currency": "$",
"line_items": [{"description": "Hammer", "quantity": "two", "unit_price": 12.5, "amount": 25}],
"total": "1,025.00",
}),
"missing fields": '{"vendor": "Acme Tools", "total": 25}',
}
for name, reply in REPLIES.items():
print(f"== {name}")
try:
data = json.loads(reply)
except json.JSONDecodeError as e:
print(f" json.loads failed: {e}")
continue
print(f" json.loads worked, total is {data['total']!r} ({type(data['total']).__name__})")
try:
Invoice.model_validate(data)
except ValidationError as e:
print(f" Pydantic found {e.error_count()} problems:")
for err in e.errors():
where = ".".join(str(part) for part in err["loc"])
print(f" {where}: {err['msg']}") - A dict from a label to a reply text, like a
Map<String, String>.line 8 - Prose plus a Markdown code fence: the most common failure.
\nis a newline inside the string.line 9 json.dumpsturns a dict into a JSON string (JSON.stringify). This reply is valid JSON with the wrong types inside.line 10.items()gives (key, value) pairs; the loop unpacks each pair into two variables.line 20- Skip to the next reply: there is nothing to validate.line 26
!rinside an f-string printsrepr()of the value: strings show their quotes.line 27- Validate a dict. (Step 6 uses
model_validate_json, which parses and validates a JSON string in one go.)line 29 e.errors()is a list of dicts.locis the path to the bad field, like('line_items', 0, 'quantity');msgsays what is wrong.line 32- Joins the path into
line_items.0.quantity.str(part)because the 0 is an int.line 33
uv run breakages.py == prose around the JSON
json.loads failed: Expecting value: line 1 column 1 (char 0)
== wrong types
json.loads worked, total is '1,025.00' (str)
Pydantic found 4 problems:
invoice_date: Input should be a valid date or datetime, invalid character in year
currency: String should match pattern '^[A-Z]{3}$'
line_items.0.quantity: Input should be a valid number, unable to parse string as a number
total: Input should be a valid number, unable to parse string as a number
== missing fields
json.loads worked, total is 25 (int)
Pydantic found 3 problems:
invoice_date: Field required
currency: Field required
line_items: Field required json.loads happily accepted it. Without validation, total would be the string "1,025.00", and your code would crash later, somewhere else, with a confusing TypeError. Validate at the boundary, right where the data enters your program, and you get one clear error at the point where things went wrong.Stuck on this step?
- My error messages are worded slightly differently
- Pydantic's messages can change a little between 2.x versions. The fields (
invoice_date,currency,line_items.0.quantity,total) are what matter.
Turn the class into a JSON Schema
Generate the exact description of a valid invoice that the model API understands.
JSON Schema is the standard way to describe the shape of JSON: types, required fields, patterns, nested objects. Model APIs accept one and use it to steer the reply.
You never write it by hand: Invoice.model_json_schema() builds it from the class. Change the class, and the schema follows. One source of truth for your code, your validation and the model.
import json
from pathlib import Path
from models import Invoice
schema = Invoice.model_json_schema()
Path("invoice.schema.json").write_text(json.dumps(schema, indent=2))
print("required:", schema["required"])
for name, prop in schema["properties"].items():
print(f" {name}: {json.dumps(prop)}")
print("LineItem required:", schema["$defs"]["LineItem"]["required"])
print("full schema written to invoice.schema.json") - Returns the schema as a plain dict. A class method: you call it on the class, not on an object.line 6
- Saves the full, pretty-printed schema so you can open it in your editor.line 7
- One line per field: the type and the rules from
Field(...).line 10 LineItemis defined once under$defsand referenced with$ref, like a shared type.line 12
uv run show_schema.py required: ['vendor', 'invoice_date', 'currency', 'line_items', 'total']
vendor: {"minLength": 1, "title": "Vendor", "type": "string"}
invoice_date: {"format": "date", "title": "Invoice Date", "type": "string"}
currency: {"description": "ISO 4217 code, like USD", "pattern": "^[A-Z]{3}$", "title": "Currency", "type": "string"}
line_items: {"items": {"$ref": "#/$defs/LineItem"}, "minItems": 1, "title": "Line Items", "type": "array"}
shipping: {"default": 0, "description": "shipping or delivery charge; put it here, not in line_items", "minimum": 0, "title": "Shipping", "type": "number"}
tax: {"default": 0, "description": "tax or VAT amount; put it here, not in line_items", "minimum": 0, "title": "Tax", "type": "number"}
total: {"title": "Total", "type": "number"}
LineItem required: ['description', 'quantity', 'unit_price', 'amount']
full schema written to invoice.schema.json date became "format": "date", gt=0 became exclusiveMinimum, ge=0 became minimum, pattern stayed a regex, and the descriptions are there for the model to read. Every field without a default is in required; shipping and tax have a default of 0, so they are not. Open invoice.schema.json to see the whole thing.JSON mode: send the schema with the request
The model is forced to reply with JSON in your shape, and Pydantic checks it.
Instead of describing the JSON in the prompt, pass the schema in the request's response_format field. Servers that support it use constrained decoding: while the model writes, any token that would break the schema is blocked. No prose, no code fences, no missing fields.
Ollama supports this through its OpenAI-compatible API: response_format with type: "json_schema" is passed to the model as its output format (the native Ollama API calls the same thing format). Hosted APIs accept the same field.
There is also a weaker mode, {"type": "json_object"}: the reply is guaranteed to be valid JSON, but in any shape. Use the schema whenever the server supports it.
Then Invoice.model_validate_json(reply) parses and validates in one step. You still validate, because not every server enforces every schema rule (number limits like exclusiveMinimum are a common gap) and a reply cut off by the token limit is broken JSON.
from pydantic import ValidationError
from models import Invoice
SYSTEM = (
"You extract invoices into JSON. Use only facts from the text. "
"Write dates as YYYY-MM-DD and numbers without currency symbols or thousands separators. "
"Put shipping and tax in their own fields, never as line items. "
"Copy every value as written, even if it looks wrong."
)
RESPONSE_FORMAT = {
"type": "json_schema",
"json_schema": {"name": "invoice", "schema": Invoice.model_json_schema()},
}
def describe(err: ValidationError) -> str:
"""One short line per problem: readable for people and for the model."""
lines = []
for e in err.errors():
where = ".".join(str(part) for part in e["loc"]) or "reply"
lines.append(f"- {where}: {e['msg']}")
return "\n".join(lines)
def extract_invoice(text: str, client, model: str) -> Invoice:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
]
resp = client.chat.completions.create(
model=model, messages=messages, response_format=RESPONSE_FORMAT, temperature=0
)
reply = resp.choices[0].message.content or ""
return Invoice.model_validate_json(reply) - The instructions. The schema says the **shape**; the prompt still explains **meaning**: date format, no
$signs, shipping and tax in their own fields, and copy values as written (do not "correct" them).line 5 - Built once when the module is imported. A Python module-level constant is like a
static finalfield.line 11 - The OpenAI-compatible way to say "reply with JSON matching this schema".line 12
nameis a label for the schema;schemais the dict from step 5.line 13- Turns a
ValidationErrorinto short lines like- total: Input should be a valid number. You will print it now and send it to the model in step 7.line 17 - An error about the whole reply (for example "Invalid JSON") has an empty path.
x or ygivesywhenxis empty.line 21 - The client is a **parameter**: the real program passes an
OpenAIclient, tests pass a fake.line 26 - The only change to the request compared with lab 1.line 32
- The SDK types
contentas "string or None".or ""turns None into an empty string, which then fails validation with a clear message.line 34 - Parse **and** validate the JSON string. Returns an
Invoiceor raisesValidationError.line 35
import sys
from pathlib import Path
from pydantic import ValidationError
from config import settings
from extract import describe, extract_invoice
from llm import make_client
path = Path(sys.argv[1] if len(sys.argv) > 1 else "invoices/acme.txt")
try:
invoice = extract_invoice(path.read_text(), make_client(), settings().model)
except ValidationError as e:
sys.exit(f"The reply does not match the schema:\n{describe(e)}")
print(invoice.model_dump_json(indent=2))
print("total as a number:", invoice.total, "| date as a date:", repr(invoice.invoice_date)) - If the reply does not fit, print what is wrong instead of a stack trace.line 13
sys.exit("text")prints the text to stderr and ends the program with exit code 1.line 14- The validated object back to JSON, pretty-printed.line 16
- Proof that the types are real now:
totalis a float, and the date is adatetime.dateobject, not a string.line 17
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
</parent>
<groupId>dev.algorung</groupId>
<artifactId>invoice-extractor</artifactId>
<version>0.1.0</version>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - Spring Boot 3.4 with Java 21, the same as lab 1.line 8
- The Ollama starter from lab 1.line 30
- Lets Jackson read
"2025-02-14"into aLocalDate. Spring AI's converter loads it automatically when it is on the classpath. The version comes from Spring Boot.line 34
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=llama3.2:3b
spring.ai.ollama.chat.options.temperature=0
spring.main.web-application-type=none - Temperature 0 for extraction, like the Python version.line 3
package dev.algorung;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
public record Invoice(
String vendor,
LocalDate invoiceDate,
String currency,
List<LineItem> lineItems,
@JsonPropertyDescription("shipping or delivery charge; put it here, not in lineItems") BigDecimal shipping,
@JsonPropertyDescription("tax or VAT amount; put it here, not in lineItems") BigDecimal tax,
BigDecimal total) {
public Invoice {
shipping = shipping == null ? BigDecimal.ZERO : shipping;
tax = tax == null ? BigDecimal.ZERO : tax;
}
public record LineItem(String description, BigDecimal quantity, BigDecimal unitPrice, BigDecimal amount) {}
} - The Java twin of the Pydantic model: a record. Spring AI builds the JSON Schema from it, as
model_json_schema()did.line 9 - JSON field names follow the Java names here:
invoiceDate,lineItems,unitPrice.line 11 - Shipping and tax get their own fields, like in Python.
@JsonPropertyDescriptionputs the hint into the generated schema, asField(description=...)does.line 14 BigDecimalfor money: exact decimals, the usual choice in Java.line 16- A compact constructor: it runs on every new
Invoice. A missing shipping or tax arrives asnull, so it becomes 0, likedefault=0in Pydantic.line 18 - A nested record, like the
LineItemclass in Python.line 23
package dev.algorung;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.converter.BeanOutputConverter;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ExtractInvoice {
static final String SYSTEM = """
You extract invoices into JSON. Use only facts from the text. \
Write dates as YYYY-MM-DD and numbers without currency symbols or thousands separators. \
Put shipping and tax in their own fields, never as line items. \
Copy every value as written, even if it looks wrong.""";
public static void main(String[] args) {
SpringApplication.run(ExtractInvoice.class, args);
}
@Bean
CommandLineRunner run(ChatClient.Builder builder) {
return args -> {
String text = Files.readString(Path.of(args.length > 0 ? args[0] : "invoices/acme.txt"));
var converter = new BeanOutputConverter<>(Invoice.class);
Invoice invoice = builder.build().prompt()
.system(SYSTEM)
.user(text)
.options(OllamaOptions.builder().format(converter.getJsonSchemaMap()).build())
.call()
.entity(converter);
System.out.println(invoice);
BigDecimal sum = invoice.lineItems().stream()
.map(Invoice.LineItem::amount)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.add(invoice.shipping())
.add(invoice.tax());
boolean adds = sum.subtract(invoice.total()).abs().compareTo(new BigDecimal("0.01")) <= 0;
System.out.println(adds ? "items + shipping + tax match the total"
: "NEEDS REVIEW: items + shipping + tax = " + sum + ", but the total is " + invoice.total());
};
}
} - The same instructions as the Python
SYSTEM. The\at a line end inside a text block joins lines without a newline.line 17 - Spring AI's converter: it generates the JSON Schema from the record and maps the reply back to it with Jackson.line 31
formatis Ollama's name for structured output. Passing the schema map here turns on constrained decoding, likeresponse_formatin Python.line 36- The key line.
entity()adds format instructions with the schema to the prompt, calls the model and maps the JSON to anInvoice..entity(Invoice.class)alone also works, but then only the prompt asks for the shape.line 38 - A first business rule in Java: add up the line items, plus shipping and tax, with
BigDecimal.line 41 - Within a cent. With
BigDecimal, compare withcompareTo, neverequals(equalsalso compares the scale:25.0is not equal to25.00).line 46
Java (Spring AI) version of this step:
uv run main.py invoices/berlin.txt {
"vendor": "Druckerei Weber GmbH",
"invoice_date": "2025-02-14",
"currency": "EUR",
"line_items": [
{
"description": "Flyer A5, 1.000 Stück",
"quantity": 2.0,
"unit_price": 89.5,
"amount": 179.0
},
{
"description": "Visitenkarten",
"quantity": 1.0,
"unit_price": 45.0,
"amount": 45.0
}
],
"shipping": 0.0,
"tax": 0.0,
"total": 224.0
}
total as a number: 224.0 | date as a date: datetime.date(2025, 2, 14) mvn -q spring-boot:run -Dspring-boot.run.arguments=invoices/berlin.txt Invoice[vendor=Druckerei Weber GmbH, invoiceDate=2025-02-14, currency=EUR, lineItems=[LineItem[description=Flyer A5, 1.000 Stück, quantity=2, unitPrice=89.50, amount=179.00], LineItem[description=Visitenkarten, quantity=1, unitPrice=45.00, amount=45.00]], shipping=0, tax=0, total=224.00] items + shipping + tax match the total
entity() throws an exception when the JSON cannot be mapped; wrap it in the same retry loop you build next.Stuck on this step?
- The reply still has prose around the JSON
- Your Ollama is older than 0.5 and ignores the schema. Run
ollama --versionand update. - It takes a minute or more
- Normal on a CPU: the reply is a few hundred tokens. Try a shorter invoice first, or
llama3.2:1b(faster, but makes more mistakes; step 7 helps there). - Java: the dates come back as
null - Your JSON field names do not match the record. Print the raw reply with
.call().content()to compare, and checkjackson-datatype-jsr310is inpom.xml.
Retry with the error message
When a reply fails validation, tell the model exactly what was wrong and let it try again (at most 2 retries).
A model that got one field wrong is usually right on a second try if you say what was wrong. So the retry is a conversation: keep the model's bad reply in the message list as an assistant message, then add a user message with the validation errors.
Cap the retries. Each one costs a full call (time and tokens), and a model that failed three times will rarely succeed on the fourth. After the last attempt, raise an exception with the attempt count and the last errors, so the caller can decide what to do.
extract.py changes in three places: the function now returns an Extraction (the invoice and how many attempts it took), there is a new ExtractionFailed exception, and the call sits inside a loop.
from dataclasses import dataclass
from pydantic import ValidationError
from models import Invoice
SYSTEM = (
"You extract invoices into JSON. Use only facts from the text. "
"Write dates as YYYY-MM-DD and numbers without currency symbols or thousands separators. "
"Put shipping and tax in their own fields, never as line items. "
"Copy every value as written, even if it looks wrong."
)
RESPONSE_FORMAT = {
"type": "json_schema",
"json_schema": {"name": "invoice", "schema": Invoice.model_json_schema()},
}
@dataclass
class Extraction:
invoice: Invoice
attempts: int
class ExtractionFailed(Exception):
def __init__(self, attempts: int, last_error: str):
super().__init__(f"no valid invoice after {attempts} attempts")
self.attempts = attempts
self.last_error = last_error
def describe(err: ValidationError) -> str:
"""One short line per problem: readable for people and for the model."""
lines = []
for e in err.errors():
where = ".".join(str(part) for part in e["loc"]) or "reply"
lines.append(f"- {where}: {e['msg']}")
return "\n".join(lines)
def extract_invoice(text: str, client, model: str, max_retries: int = 2) -> Extraction:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
]
for attempt in range(1, max_retries + 2):
resp = client.chat.completions.create(
model=model, messages=messages, response_format=RESPONSE_FORMAT, temperature=0
)
reply = resp.choices[0].message.content or ""
try:
return Extraction(Invoice.model_validate_json(reply), attempt)
except ValidationError as e:
problems = describe(e)
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": f"That JSON is invalid:\n{problems}\nReply with the corrected JSON only."})
raise ExtractionFailed(max_retries + 1, problems) @dataclasswrites the constructor,__eq__and__repr__for you, like a Java record.line 19- A custom exception that carries data, like extending
RuntimeExceptionwith extra fields.line 25 super().__init__(message)issuper(message)in Java: it sets the text shown bystr(e).line 27range(1, 4)is 1, 2, 3: the first attempt plus 2 retries. The end ofrangeis exclusive, likefor (i = 1; i < 4; i++).line 46- Valid: return at once with the attempt number.line 52
- Invalid: keep the error lines. (
eonly exists inside theexceptblock, so we keep the text inproblems.)line 54 - The model's own bad reply goes back into the conversation, so it can see what it wrote.line 55
- Then the exact problems, as a user message. Specific feedback ("total: Input should be a valid number") works far better than "try again".line 56
- All attempts used. The caller gets the count and the last errors.line 57
import sys
from pathlib import Path
from config import settings
from extract import ExtractionFailed, extract_invoice
from llm import make_client
path = Path(sys.argv[1] if len(sys.argv) > 1 else "invoices/acme.txt")
try:
result = extract_invoice(path.read_text(), make_client(), settings().model)
except ExtractionFailed as e:
sys.exit(f"Could not extract {path.name}: {e}\n{e.last_error}")
print(result.invoice.model_dump_json(indent=2))
print(f"\nvalid after {result.attempts} attempt(s)") - Only one thing can go wrong now from the caller's view: no valid invoice after all attempts.line 11
- Show what was still wrong on the last attempt.line 12
- Seeing
2 attempt(s)tells you the retry saved this invoice.line 15
uv run main.py invoices/acme.txt {
"vendor": "Acme Tools Ltd",
"invoice_date": "2025-03-03",
"currency": "USD",
"line_items": [
...
],
"shipping": 59.0,
"tax": 0.0,
"total": 1025.0
}
valid after 1 attempt(s) Stuck on this step?
- It always says
valid after 1 attempt(s). How do I see a retry? - With a working schema, most replies are valid the first time, which is the goal. Step 10 tests the retry path with a fake client that returns a bad reply first.
Business rules the schema cannot check
Catch invoices that are valid JSON but wrong: totals that do not add up, dates in the future.
A schema checks each field on its own. It cannot say "the line items plus shipping plus tax must add up to the total" or "the date must not be in the future". Those rules go in plain code, after validation.
Get the rule right before you trust it. A rule that only adds up the line items would flag acme.txt, a perfectly correct invoice, because its total includes 59.00 shipping. That is why Invoice has shipping and tax fields, and the rule adds them in. The message shows each part, so a reviewer sees at once what is missing.
These problems are not retried. If the invoice itself says 136.00 when the items add up to 126.00, asking the model again cannot fix it. The right result is "needs a person to look at it".
Money and floats: in every language 0.1 + 0.2 is 0.30000000000000004. So the rules convert amounts to whole cents (integers) first and allow one cent of rounding difference.
from datetime import date
from models import Invoice
def cents(x: float) -> int:
return round(x * 100)
def check_rules(inv: Invoice, today: date) -> list[str]:
"""Business checks the schema cannot express. Returns a list of problems (empty = fine)."""
problems = []
for n, item in enumerate(inv.line_items, start=1):
if abs(cents(item.quantity * item.unit_price) - cents(item.amount)) > 1:
problems.append(f"line {n}: {item.quantity:g} x {item.unit_price:.2f} is not {item.amount:.2f}")
items = sum(cents(item.amount) for item in inv.line_items)
expected = items + cents(inv.shipping) + cents(inv.tax)
if abs(expected - cents(inv.total)) > 1:
problems.append(
f"items {items / 100:.2f} + shipping {inv.shipping:.2f} + tax {inv.tax:.2f}"
f" = {expected / 100:.2f}, but the total is {inv.total:.2f}"
)
if inv.invoice_date > today:
problems.append(f"invoice date {inv.invoice_date} is in the future")
return problems round(x * 100)gives an int: 12.5 becomes 1250. Integers compare exactly.line 6todayis a parameter instead of callingdate.today()inside. Tests can then use a fixed date (dependency injection again, for time).line 10- Collect **all** problems instead of stopping at the first one, so a reviewer sees everything.line 12
enumerategives (number, item) pairs.start=1counts from 1, like the line numbers on the invoice.line 13- More than one cent apart: a real problem, not rounding.line 14
:gprints2.0as2;:.2fprints two decimals, like%.2finString.format.line 15sum(...)over a generator: add up every line's cents in one expression. Likestream().mapToInt(...).sum().line 16- What the total should be: the items plus shipping plus tax, all in cents.line 17
- Two f-strings next to each other inside parentheses join into one message. It lists every part, like
items 126.00 + shipping 0.00 + tax 0.00 = 126.00, but the total is 136.00.line 20 dateobjects compare with<and>directly, likeisAfteronLocalDate.line 23
import sys
from datetime import date
from pathlib import Path
from config import settings
from extract import ExtractionFailed, extract_invoice
from llm import make_client
from rules import check_rules
path = Path(sys.argv[1] if len(sys.argv) > 1 else "invoices/acme.txt")
try:
result = extract_invoice(path.read_text(), make_client(), settings().model)
except ExtractionFailed as e:
sys.exit(f"Could not extract {path.name}: {e}\n{e.last_error}")
print(result.invoice.model_dump_json(indent=2))
print(f"\nvalid after {result.attempts} attempt(s)")
problems = check_rules(result.invoice, date.today())
for p in problems:
print("NEEDS REVIEW:", p)
if not problems:
print("all business rules pass") - The real program passes the real date.line 18
- Validated, but flagged for a person.line 20
- An empty list counts as false in Python, so
if not problemsmeans "no problems".line 21
uv run main.py invoices/mismatch.txt {
"vendor": "Bright Office Supplies",
"invoice_date": "2025-01-20",
"currency": "USD",
"line_items": [
...
],
"shipping": 0.0,
"tax": 0.0,
"total": 136.0
}
valid after 1 attempt(s)
NEEDS REVIEW: items 126.00 + shipping 0.00 + tax 0.00 = 126.00, but the total is 136.00 Stuck on this step?
- acme.txt is flagged:
items 966.00 + shipping 0.00 + tax 0.00 = 966.00, but the total is 1025.00 - The model left
shippingat 0. Check thatmodels.pyhas theshippingfield with its description and thatSYSTEMsays "Put shipping and tax in their own fields". Small models still miss it sometimes: that is exactly what the review status is for. - acme.txt is flagged with
shipping 59.00and items of1025.00 - The model put shipping in both places: as a line item and in
shipping. Same fix: the field descriptions and the prompt say "not as line items". The rule did its job by flagging it. - acme.txt says
NEEDS REVIEW: line items add up to 966.00, but the total is 1025.00 - That is the old rule, from before
shippingandtaxexisted: it ignores shipping. Copymodels.pyandrules.pyfrom this page again.
Run a whole folder and write a report
Extract every invoice in a folder, keep going when one fails, and save the results to report.json.
Real work comes in batches. The batch script runs each file through the same steps and records one row per file: the status, the number of attempts, the problems and the extracted invoice.
One bad file must never stop the batch, so each file has its own try. At the end it prints a summary and writes everything to report.json for the next system (or a person) to use.
Look at future.txt in your result. The invoice says 15 Jan 2062, and the rule should send it to review. It usually does now. But when we ran this lab with llama3.2:3b and an earlier prompt that did not say "copy every value as written", the row came back ok: report.json showed "invoice_date": "2026-01-15". The model found 2062 implausible and quietly "fixed" it. The JSON was valid, the date was in the past, so no rule fired. That one line in the prompt changed the result, and small models can still slip on a different file or a different run.
That is the honest limit of validation: it checks what the model returned, not whether it matches the document. This is why you keep the source text next to every extracted row, spot-check some rows by hand, and run an evaluation set (like these four files, with the answers you expect) whenever you change the model or the prompt.
import json
import sys
from collections import Counter
from datetime import date
from pathlib import Path
from config import settings
from extract import ExtractionFailed, extract_invoice
from llm import make_client
from rules import check_rules
folder = Path(sys.argv[1] if len(sys.argv) > 1 else "invoices")
client, model = make_client(), settings().model
rows = []
for path in sorted(folder.glob("*.txt")):
row = {"file": path.name}
try:
result = extract_invoice(path.read_text(), client, model)
except ExtractionFailed as e:
row.update(status="failed", attempts=e.attempts, problems=e.last_error.splitlines())
else:
problems = check_rules(result.invoice, date.today())
row.update(
status="review" if problems else "ok",
attempts=result.attempts,
problems=problems,
invoice=result.invoice.model_dump(mode="json"),
)
rows.append(row)
first = row["problems"][0] if row["problems"] else ""
print(f"{row['status']:<7} {row['file']:<14} attempts={row['attempts']} {first}")
Path("report.json").write_text(json.dumps(rows, indent=2))
counts = Counter(row["status"] for row in rows)
print(f"\n{counts['ok']} ok, {counts['review']} need review, {counts['failed']} failed. Details: report.json") Countercounts things:Counter(["ok", "ok", "review"])gives{"ok": 2, "review": 1}, and a missing key counts as 0.line 3- One client for the whole batch: it reuses connections. Two assignments on one line.line 13
- Every
.txtfile in the folder, in name order, so the report is the same order every run.line 15 - Each row is a dict.
path.nameis the file name without the folder.line 16 dict.update(key=value, ...)adds or replaces several keys at once.line 20try / except / else: theelseblock runs only when no exception happened. It keeps the success code out of thetry, so a bug in it is not mistaken for an extraction failure.line 21- Python's conditional expression:
a if condition else biscondition ? a : b.line 24 - The invoice as a plain dict with JSON-friendly values (the date becomes a string), ready for
json.dumps.line 27 :<7pads to 7 characters, left-aligned, so the columns line up.line 31- Writes the whole report in one call.
indent=2makes it readable.line 33
uv run batch.py invoices ok acme.txt attempts=1 ok berlin.txt attempts=1 review future.txt attempts=1 invoice date 2062-01-15 is in the future review mismatch.txt attempts=1 items 126.00 + shipping 0.00 + tax 0.00 = 126.00, but the total is 136.00 2 ok, 2 need review, 0 failed. Details: report.json
report.json and compare each row with its invoice file. That habit catches what no rule can.Stuck on this step?
- It takes several minutes
- Four invoices, each a full model call (more if retried), on a laptop CPU. Try the batch on two files first: make a folder with just those.
- A file shows
failedwithInvalid JSON: EOF while parsing - The reply was cut off (too long). Pass
max_tokens=2000tocreate()inextract.py. - future.txt is ok, but I expected review
- Check
report.json: ifinvoice_dateis2026-01-15, the model "corrected" the year. Your code is fine. Check that your prompt still says to copy every value as written, then tryLLM_MODEL=llama3.1:8b uv run batch.py invoices(afterollama pull llama3.1:8b, about 5 GB) to see the date reported as written.
Test it with a fake client
Test the retry loop and the rules in milliseconds, with no model and no network.
The extraction code only uses one thing from the client: client.chat.completions.create(...), which returns an object with .choices[0].message.content. A fake only has to look like that. Python checks attributes when the code runs, not types at compile time ("duck typing"), so no interface or mocking library is needed.
The fake returns the replies you give it, in order, and records every request. So a test can say "first reply is bad, second is good", then check that the second request contained the error message.
import json
from types import SimpleNamespace
import pytest
from extract import ExtractionFailed, extract_invoice
GOOD = json.dumps({
"vendor": "Acme Tools",
"invoice_date": "2025-03-03",
"currency": "USD",
"line_items": [{"description": "Claw hammer", "quantity": 2, "unit_price": 12.5, "amount": 25.0}],
"total": 25.0,
})
WRONG_TYPE = GOOD.replace('"quantity": 2', '"quantity": "two"')
NOT_JSON = "Sure! Here is the invoice you asked for."
class FakeClient:
"""Stands in for OpenAI(): hands out the given replies in order and records every request."""
def __init__(self, *replies: str):
self.replies = list(replies)
self.requests = []
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
def create(self, **kwargs):
self.requests.append(kwargs)
message = SimpleNamespace(content=self.replies.pop(0))
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
def test_good_json_first_time():
client = FakeClient(GOOD)
result = extract_invoice("an invoice", client, "fake-model")
assert result.attempts == 1
assert result.invoice.vendor == "Acme Tools"
assert str(result.invoice.invoice_date) == "2025-03-03"
assert client.requests[0]["response_format"]["type"] == "json_schema"
def test_validation_error_is_sent_back_then_fixed():
client = FakeClient(WRONG_TYPE, GOOD)
result = extract_invoice("an invoice", client, "fake-model")
assert result.attempts == 2
feedback = client.requests[1]["messages"][-1]["content"]
assert "line_items.0.quantity" in feedback
assert client.requests[1]["messages"][-2] == {"role": "assistant", "content": WRONG_TYPE}
def test_not_json_at_all_then_fixed():
result = extract_invoice("an invoice", FakeClient(NOT_JSON, GOOD), "fake-model")
assert result.attempts == 2
def test_gives_up_after_two_retries():
client = FakeClient(NOT_JSON, WRONG_TYPE, WRONG_TYPE, GOOD)
with pytest.raises(ExtractionFailed) as info:
extract_invoice("an invoice", client, "fake-model", max_retries=2)
assert info.value.attempts == 3
assert len(client.requests) == 3 SimpleNamespace(a=1)is a quick object with attributea, like a JavaScript object literal{a: 1}.line 2- A valid reply, built from a dict so the JSON is always correct.line 8
- The same reply with
quantityas the word "two": valid JSON, invalid invoice.line 15 - Builds the chain
client.chat.completions.createout of simple objects, ending at our method.line 25 **kwargscollects every keyword argument into a dict, so the test can look atmodel,messagesandresponse_format.line 27- Takes the first queued reply, like
queue.poll().line 29 - Checks the request really asked for schema output.line 39
[-1]is the last element. The last message of the second request must be our error feedback.line 46- The test passes only if the block raises
ExtractionFailed;info.valueis the exception.line 58 - Exactly three calls: the first attempt plus two retries. The fourth (good) reply is never used.line 61
from datetime import date
from models import Invoice, LineItem
from rules import check_rules
TODAY = date(2025, 6, 1)
def invoice(total: float, *amounts: float, shipping: float = 0, tax: float = 0, day: date = date(2025, 3, 3)) -> Invoice:
items = [LineItem(description=f"item {i}", quantity=1, unit_price=a, amount=a) for i, a in enumerate(amounts)]
return Invoice(vendor="Acme", invoice_date=day, currency="USD", line_items=items, shipping=shipping, tax=tax, total=total)
def test_a_correct_invoice_has_no_problems():
assert check_rules(invoice(30.30, 10.10, 20.20), TODAY) == []
def test_one_cent_of_rounding_is_allowed():
assert check_rules(invoice(30.31, 10.10, 20.20), TODAY) == []
def test_shipping_counts_towards_the_total():
assert check_rules(invoice(1025.00, 25.00, 42.00, 899.00, shipping=59.00), TODAY) == []
def test_tax_counts_towards_the_total():
assert check_rules(invoice(119.00, 100.00, tax=19.00), TODAY) == []
def test_total_that_does_not_add_up():
assert check_rules(invoice(136.00, 30.00, 96.00), TODAY) == [
"items 126.00 + shipping 0.00 + tax 0.00 = 126.00, but the total is 136.00"
]
def test_wrong_line_amount():
item = LineItem(description="toner", quantity=2, unit_price=48.0, amount=86.0)
inv = Invoice(vendor="Acme", invoice_date=date(2025, 1, 20), currency="USD", line_items=[item], total=86.0)
assert check_rules(inv, TODAY) == ["line 1: 2 x 48.00 is not 86.00"]
def test_date_in_the_future():
assert check_rules(invoice(10.0, 10.0, day=date(2062, 1, 15)), TODAY) == [
"invoice date 2062-01-15 is in the future"
] - A fixed "today", so these tests give the same result next year.line 6
*amountstakes any number of extra arguments as a tuple, like Java varargsdouble... amounts.shipping,taxanddaycome after it, so they must be passed by name.line 9- A list comprehension: builds one
LineItemper amount in a single expression.line 10 - Exactly one cent off is accepted as rounding.line 18
- The Acme numbers: 25 + 42 + 899 = 966 in items, plus 59 shipping, is the 1,025 total. This test fails with a rule that forgets shipping.line 23
- The same for tax: 100 net plus 19 VAT is 119.line 27
- The typo from
future.txt.line 43
uv run pytest -q 11 passed in 0.04s
Stuck on this step?
ModuleNotFoundError: No module named 'extract'- Run pytest from the project folder (where
extract.pyis) withuv run pytest -q.
Check it works
Three checks: the tests pass with no model, one invoice comes out valid, and the batch report has a row for every file.
With the four sample invoices you should see acme.txt and berlin.txt ok, and future.txt and mismatch.txt in review: both invoices really are wrong. If future.txt comes back ok, the model changed the year (step 9). Some files may need a second attempt.
uv run pytest -q && uv run batch.py invoices 11 passed in 0.04s ok acme.txt attempts=1 ok berlin.txt attempts=1 review future.txt attempts=1 invoice date 2062-01-15 is in the future review mismatch.txt attempts=1 items 126.00 + shipping 0.00 + tax 0.00 = 126.00, but the total is 136.00 2 ok, 2 need review, 0 failed. Details: report.json
Troubleshooting
Every file failed with - reply: Invalid JSON: expected value at line 1 column 1
The server did not return JSON at all. Most likely your Ollama is older than 0.5 (it ignores response_format schemas): update it. Also check LLM_BASE_URL ends in /v1.
openai.BadRequestError mentioning response_format or json_schema
That provider or model does not support JSON Schema output. Try {"type": "json_object"} for RESPONSE_FORMAT (valid JSON, any shape) and keep the validation and retries: they now matter even more.
A hosted OpenAI model rejects the schema when you add "strict": True
Strict mode needs "additionalProperties": false on every object and every field listed in required. Pydantic does not add the first by default: set model_config = ConfigDict(extra="forbid") on both classes, which adds it to the schema.
Numbers come back 100 times too big for the German invoice (8950 instead of 89.50)
The model read 89,50 the American way. Add a hint to SYSTEM, such as "In European invoices a comma is the decimal separator", and keep the line check in rules.py (quantity times unit price must equal the amount): it flags the invoice for review when only some numbers were misread.
An extracted value differs from the invoice, but the row is ok (a year, a quantity, a name)
Small models sometimes "fix" values they find implausible, like turning 2062 into 2026, and sometimes invent rows like "Taxes 0.00". Validation cannot see this: it only checks the reply. Keep the source text with every row, spot-check rows by hand, and measure with an eval set. A larger model (llama3.1:8b or a hosted one) does this far less often.
Extraction is very slow
Constrained decoding adds a little work per token, but most of the time is the model itself on a CPU. Keep invoices short (send only the text, not the whole email thread), and use llama3.2:1b for experiments.
What changes in production
- Validate every reply, even with schema mode. The schema makes bad output rare; your validator makes it impossible to miss. Log every validation failure with the input, so you can see which documents and fields go wrong.
- Budget the retries. Two retries at most, and count them: a rising retry rate is the first sign a model update or a new document type broke something. Retries cost tokens and latency.
- Send "needs review" to a person, never straight to payment. Business rules decide what is safe to automate. Keep the original text next to the extracted fields so the reviewer can compare.
- Version the schema with the code, and measure. The schema comes from the Pydantic class, so a change to the class changes what the model is asked for. Run your sample invoices with their expected answers (an eval set) on every model, prompt or schema change, and spot-check "ok" rows: a model that silently corrects a value passes every rule.
- Do not put secrets or unrelated personal data in the prompt. Send only the invoice text the extraction needs, especially to a hosted API.
Interview angle
“How do you get reliable structured data out of an LLM?”
I define the target as a typed model (Pydantic in Python, a record in Java) and generate a JSON Schema from it, so there is one source of truth. I send the schema with the request (response_format json_schema, or format on Ollama), which uses constrained decoding so the reply is JSON in the right shape. I still validate every reply, because not every rule is enforced and replies can be cut off. On a validation error I retry at most twice, sending the exact errors back as feedback. After that, business rules check what a schema cannot, like totals adding up, and failures go to a human review queue rather than being retried. The parsing and retry logic is unit tested with a fake client; extraction quality is measured separately with an eval set.
Clean up
Keep the project: the tool-calling lab uses the same pattern (a schema in, validated JSON out). The generated invoice.schema.json and report.json can be deleted any time; the scripts recreate them.
rm -f report.json invoice.schema.jsonrm -f report.json invoice.schema.jsonRemove-Item report.json, invoice.schema.json -ErrorAction SilentlyContinue Practice
No model needed: these run in your browser and check your answer.
Rescue the JSON from a chatty reply
For servers without schema mode, a common rescue is to cut the JSON object out of the reply. Write pull_json(reply): take the text from the first { to the last }, parse it with json.loads and return the dict. If there is no {...} in the reply, return None.
import json
def pull_json(reply):
# your code here
return json.loads(reply)
print(pull_json('Sure! Here it is:\n```json\n{"total": 25}\n```'))
Hint
`reply.find("{")` gives the first index (or -1), `reply.rfind("}")` the last. Slice with `reply[start:end + 1]`.
Do the line items add up?
Write adds_up(amounts, total): return True when the amounts add up to the total within one cent. Avoid comparing floats directly: 0.1 + 0.2 == 0.3 is False. Convert to whole cents with round(x * 100) first.
def adds_up(amounts, total):
return sum(amounts) == total
print(adds_up([0.1, 0.2], 0.3))
Hint
Sum `round(a * 100)` for each amount, then compare with `round(total * 100)` using `abs(...) <= 1`.
The full project
Every file from this lab, as it is after the last step.