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

1 / 7

0 of 10 steps done

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 .env and config.py.
  • Pydantic basics: Type hints and Pydantic. You only need BaseModel and Field; 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:

Run
uv --version
You should see
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.

Run
ollama --version
You should see
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).

Run
ollama list
You should seeyour text will differ: the model writes it
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.

Run
brew install openjdk@21 maven
1

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.

.env
# 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
  1. Ollama's OpenAI-compatible API. The same code talks to any provider with this request shape.line 2
config.py
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"),
    )
  1. Copies .env into os.environ. Real environment variables win, which is what you want on a server.line 6
  2. One place for the three settings. Unchanged from lab 1.line 16
.gitignore
.venv/
__pycache__/
.env
  1. Never commit .env: one day it holds a real key.line 3
llm.py
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)
  1. A function, not a global: tests never call it, they pass in a fake client instead (step 10).line 6
  2. 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
  3. max_retries=2 retries network errors, 429 and 5xx. That is different from the retry loop in step 7, which retries **bad answers**.line 8
Run
uv init invoice-extractor
cd invoice-extractor
uv add openai pydantic python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
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
 ...
Why this way? Keeping client creation in 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.
2

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 €) and 1.000 means 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.

invoices/acme.txt
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!
  1. Shipping is not an item, but the total includes it. So the Invoice model gets its own shipping field (step 4), and the total rule in step 8 adds it in.line 12
invoices/berlin.txt
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
  1. Day first: 14 February. The model must turn this into 2025-02-14.line 3
  2. 1.000 Stück is "1,000 pieces" (the product), and 89,50 € is 89.50.line 6
invoices/mismatch.txt
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
  1. 30.00 + 96.00 is 126.00, not 136.00. A real vendor mistake.line 7
invoices/future.txt
NORTHWIND CONSULTING
Invoice date: 15 Jan 2062
Description: Architecture review, 8 hours at 150.00 per hour = 1200.00
Amount due: 1200.00 GBP
  1. 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
Why this way? Collect real examples before writing prompts. A handful of messy, varied inputs (including wrong ones) is the start of an evaluation set: every change you make later is checked against them.
3

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.

naive.py
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)
  1. sys.argv is the command-line arguments (args in Java); sys.argv[0] is the script name. No argument: use the Acme invoice. Path is like java.nio.file.Path.line 8
  2. Strings in parentheses next to each other are joined into one string. + path.read_text() adds the invoice text.line 9
  3. Temperature 0: the most likely token every time. For extraction you want facts, not creativity.line 18
  4. json.loads turns a JSON string into dicts and lists, like JSON.parse. It raises json.JSONDecodeError if the text is not pure JSON.line 25
  5. repr() shows the value with its type visible: '1,025.00' (a string, in quotes) versus 1025.0 (a number).line 26
Run
uv run naive.py invoices/acme.txt
You should seeyour text will differ: the model writes it
--- 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)
Why this way? Even when 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.
4

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.

models.py
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
  1. date is a calendar date with no time, like Java's LocalDate.line 1
  2. Subclassing BaseModel makes this a validated data class. Like a Java record, with checking built in.line 6
  3. Read it as "quantity is a float, and must be greater than 0". Field(...) in the default-value position adds rules, like @Positive in Bean Validation.line 8
  4. description text goes into the JSON Schema, so the model reads it too. Short hints here help extraction.line 10
  5. In JSON a date is a string. Pydantic accepts "2025-03-03" and gives you a real date object.line 15
  6. A regex: exactly three capital letters (USD, EUR). r"..." is a raw string: backslashes are not escapes, handy for regexes.line 16
  7. list[LineItem] is List<LineItem>. Each item is validated as a LineItem. min_length=1: at least one line.line 17
  8. Shipping gets its own field. default=0: an invoice without shipping can leave it out. ge=0: never negative. The description tells the model to put shipping here and **not** as an extra line item.line 18
  9. 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
  10. 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
breakages.py
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']}")
  1. A dict from a label to a reply text, like a Map<String, String>.line 8
  2. Prose plus a Markdown code fence: the most common failure. \n is a newline inside the string.line 9
  3. json.dumps turns a dict into a JSON string (JSON.stringify). This reply is valid JSON with the wrong types inside.line 10
  4. .items() gives (key, value) pairs; the loop unpacks each pair into two variables.line 20
  5. Skip to the next reply: there is nothing to validate.line 26
  6. !r inside an f-string prints repr() of the value: strings show their quotes.line 27
  7. Validate a dict. (Step 6 uses model_validate_json, which parses and validates a JSON string in one go.)line 29
  8. e.errors() is a list of dicts. loc is the path to the bad field, like ('line_items', 0, 'quantity'); msg says what is wrong.line 32
  9. Joins the path into line_items.0.quantity. str(part) because the 0 is an int.line 33
Run
uv run breakages.py
You should see
== 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
Why this way? Look at "wrong types": 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.
5

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.

show_schema.py
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")
  1. Returns the schema as a plain dict. A class method: you call it on the class, not on an object.line 6
  2. Saves the full, pretty-printed schema so you can open it in your editor.line 7
  3. One line per field: the type and the rules from Field(...).line 10
  4. LineItem is defined once under $defs and referenced with $ref, like a shared type.line 12
Run
uv run show_schema.py
You should see
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
Why this way? Look at how your Python turned into schema: 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.
6

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.

extract.py
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)
  1. 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
  2. Built once when the module is imported. A Python module-level constant is like a static final field.line 11
  3. The OpenAI-compatible way to say "reply with JSON matching this schema".line 12
  4. name is a label for the schema; schema is the dict from step 5.line 13
  5. Turns a ValidationError into 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
  6. An error about the whole reply (for example "Invalid JSON") has an empty path. x or y gives y when x is empty.line 21
  7. The client is a **parameter**: the real program passes an OpenAI client, tests pass a fake.line 26
  8. The only change to the request compared with lab 1.line 32
  9. The SDK types content as "string or None". or "" turns None into an empty string, which then fails validation with a clear message.line 34
  10. Parse **and** validate the JSON string. Returns an Invoice or raises ValidationError.line 35
main.py
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))
  1. If the reply does not fit, print what is wrong instead of a stack trace.line 13
  2. sys.exit("text") prints the text to stderr and ends the program with exit code 1.line 14
  3. The validated object back to JSON, pretty-printed.line 16
  4. Proof that the types are real now: total is a float, and the date is a datetime.date object, not a string.line 17
Run
uv run main.py invoices/berlin.txt
You should seeyour text will differ: the model writes it
{
  "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)
Why this way? Two layers, two jobs. The schema in the request makes good replies likely (most of the time, guaranteed in shape). Validation in your code makes bad replies impossible to miss. You want both. In Java, 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 --version and 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 check jackson-datatype-jsr310 is in pom.xml.
7

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.

extract.py 25 new or changed lines
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)
  1. @dataclass writes the constructor, __eq__ and __repr__ for you, like a Java record.line 19
  2. A custom exception that carries data, like extending RuntimeException with extra fields.line 25
  3. super().__init__(message) is super(message) in Java: it sets the text shown by str(e).line 27
  4. range(1, 4) is 1, 2, 3: the first attempt plus 2 retries. The end of range is exclusive, like for (i = 1; i < 4; i++).line 46
  5. Valid: return at once with the attempt number.line 52
  6. Invalid: keep the error lines. (e only exists inside the except block, so we keep the text in problems.)line 54
  7. The model's own bad reply goes back into the conversation, so it can see what it wrote.line 55
  8. 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
  9. All attempts used. The caller gets the count and the last errors.line 57
main.py 7 new or changed lines
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)")
  1. Only one thing can go wrong now from the caller's view: no valid invoice after all attempts.line 11
  2. Show what was still wrong on the last attempt.line 12
  3. Seeing 2 attempt(s) tells you the retry saved this invoice.line 15
Run
uv run main.py invoices/acme.txt
You should seeyour text will differ: the model writes it
{
  "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)
Why this way? Retrying with the same prompt and temperature 0 often gives the same wrong answer. Adding the error to the conversation changes the input, and that is what changes the output.
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.
8

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.

rules.py
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
  1. round(x * 100) gives an int: 12.5 becomes 1250. Integers compare exactly.line 6
  2. today is a parameter instead of calling date.today() inside. Tests can then use a fixed date (dependency injection again, for time).line 10
  3. Collect **all** problems instead of stopping at the first one, so a reviewer sees everything.line 12
  4. enumerate gives (number, item) pairs. start=1 counts from 1, like the line numbers on the invoice.line 13
  5. More than one cent apart: a real problem, not rounding.line 14
  6. :g prints 2.0 as 2; :.2f prints two decimals, like %.2f in String.format.line 15
  7. sum(...) over a generator: add up every line's cents in one expression. Like stream().mapToInt(...).sum().line 16
  8. What the total should be: the items plus shipping plus tax, all in cents.line 17
  9. 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
  10. date objects compare with < and > directly, like isAfter on LocalDate.line 23
main.py 7 new or changed lines
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")
  1. The real program passes the real date.line 18
  2. Validated, but flagged for a person.line 20
  3. An empty list counts as false in Python, so if not problems means "no problems".line 21
Run
uv run main.py invoices/mismatch.txt
You should seeyour text will differ: the model writes it
{
  "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
Why this way? Splitting can I read it? (schema and retries) from is it right? (business rules) gives you three clear outcomes: ok, needs review, failed. That is what an accounts team can actually work with.
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 shipping at 0. Check that models.py has the shipping field with its description and that SYSTEM says "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.00 and items of 1025.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 shipping and tax existed: it ignores shipping. Copy models.py and rules.py from this page again.
9

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.

batch.py
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")
  1. Counter counts things: Counter(["ok", "ok", "review"]) gives {"ok": 2, "review": 1}, and a missing key counts as 0.line 3
  2. One client for the whole batch: it reuses connections. Two assignments on one line.line 13
  3. Every .txt file in the folder, in name order, so the report is the same order every run.line 15
  4. Each row is a dict. path.name is the file name without the folder.line 16
  5. dict.update(key=value, ...) adds or replaces several keys at once.line 20
  6. try / except / else: the else block runs only when no exception happened. It keeps the success code out of the try, so a bug in it is not mistaken for an extraction failure.line 21
  7. Python's conditional expression: a if condition else b is condition ? a : b.line 24
  8. The invoice as a plain dict with JSON-friendly values (the date becomes a string), ready for json.dumps.line 27
  9. :<7 pads to 7 characters, left-aligned, so the columns line up.line 31
  10. Writes the whole report in one call. indent=2 makes it readable.line 33
Run
uv run batch.py invoices
You should seeyour text will differ: the model writes it
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
Why this way? The mismatch row is the batch working, not failing: the extraction was right and the invoice itself is wrong. Both review rows are real problems in the invoices. And remember the other direction from the text above: ok only means "no rule found a problem in what the model returned". Open 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 failed with Invalid JSON: EOF while parsing
The reply was cut off (too long). Pass max_tokens=2000 to create() in extract.py.
future.txt is ok, but I expected review
Check report.json: if invoice_date is 2026-01-15, the model "corrected" the year. Your code is fine. Check that your prompt still says to copy every value as written, then try LLM_MODEL=llama3.1:8b uv run batch.py invoices (after ollama pull llama3.1:8b, about 5 GB) to see the date reported as written.
10

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.

test_extract.py
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
  1. SimpleNamespace(a=1) is a quick object with attribute a, like a JavaScript object literal {a: 1}.line 2
  2. A valid reply, built from a dict so the JSON is always correct.line 8
  3. The same reply with quantity as the word "two": valid JSON, invalid invoice.line 15
  4. Builds the chain client.chat.completions.create out of simple objects, ending at our method.line 25
  5. **kwargs collects every keyword argument into a dict, so the test can look at model, messages and response_format.line 27
  6. Takes the first queued reply, like queue.poll().line 29
  7. Checks the request really asked for schema output.line 39
  8. [-1] is the last element. The last message of the second request must be our error feedback.line 46
  9. The test passes only if the block raises ExtractionFailed; info.value is the exception.line 58
  10. Exactly three calls: the first attempt plus two retries. The fourth (good) reply is never used.line 61
test_rules.py
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"
    ]
  1. A fixed "today", so these tests give the same result next year.line 6
  2. *amounts takes any number of extra arguments as a tuple, like Java varargs double... amounts. shipping, tax and day come after it, so they must be passed by name.line 9
  3. A list comprehension: builds one LineItem per amount in a single expression.line 10
  4. Exactly one cent off is accepted as rounding.line 18
  5. 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
  6. The same for tax: 100 net plus 19 VAT is 119.line 27
  7. The typo from future.txt.line 43
Run
uv run pytest -q
You should see
11 passed in 0.04s
Why this way? Your tests check your code: the loop, the feedback message, the give-up rule and the business rules. Whether a particular model extracts a particular invoice well is a different question, answered by an evaluation set (the evals lab), not by unit tests.
Stuck on this step?
ModuleNotFoundError: No module named 'extract'
Run pytest from the project folder (where extract.py is) with uv 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.

Test
uv run pytest -q && uv run batch.py invoices
You should see
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.

Run
rm -f report.json invoice.schema.json

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.

Exercise
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.

Exercise
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.

Download Python project (.zip) Download Java project (.zip)