Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 8. Multimodal and voice
  4. 8.8

Lesson 8.8 · 8 of 9 · 7 min read · Reviewed 24 Nov 2026

Lab: extract fields from a receipt image

By the end, you can

  • Design a request that extracts receipt fields into a fixed schema.
  • Validate extracted fields in code, including the arithmetic.
  • Route unreadable or inconsistent receipts to a person.

This is a hands-on lesson. The lab below runs in the Playground. The Playground can’t see real images, so the “model reply” is a fixed, realistic extraction from three receipts. The point of the lab is the part you own in any real system: the schema, the checks and the routingRouting: A workflow pattern that classifies an input and sends it to a specialised prompt, model or handler..

The pipeline

receipt photo
  -> resize (8.6) and send with a schema       (one image block, one text block)
  -> model returns JSON                         (fields, or null when unreadable)
  -> your code validates                        (types, dates, arithmetic)
  -> pass: save      fail: send to a reviewer with the reason

Any vision-capable model works for the extraction step. Lesson 8.5 shows the request shape for Claude.

Step 1. Design the schema

Keep it small and explicit. Every field that might be unreadable is nullable.

{
  "merchant": "string or null",
  "date": "YYYY-MM-DD or null",
  "currency": "three-letter code or null",
  "items": [{"name": "string", "amount": "number"}],
  "tax": "number or null",
  "total": "number or null",
  "evidence": {"total": "the exact text read for the total"}
}

Two choices matter. Nullable fields give the model an honest way to say “I can’t read this” (7.3). The evidence field records what it actually saw, so a reviewer can tell a misread “7” from a missing line.

Step 2. Write the prompt

Tell the model what to do when the image is unclear:

Extract the fields below from the receipt image.
Copy numbers exactly as printed. Do not calculate missing values.
If a field is unreadable or absent, use null.
Return only JSON that matches the schema.

“Do not calculate missing values” is the key line. If the model fills in a smudged total by adding up the items, your arithmetic check can no longer catch anything.

Step 3. Validate in code

Run the starter. It saves every receipt. Add these checks, one at a time:

Check Catches
Required fields are present and not null Unreadable receipts
date parses and isn’t in the future Misread digits, US versus UK date order
currency is in an allowed list Symbols read as the wrong code
sum(items) + tax == total, within 0.01 One misread number anywhere
Every amount is positive A minus sign read from a discount line

Use a small tolerance for the sum, not exact equality, because money stored as floats picks up rounding error.

Step 4. Route the result

Each receipt ends in one of two piles. In the lab, receipt R-1 passes, R-2 fails the sum check, and R-3 has a null total and goes to review with the reason “total unreadable”. Print a one-line summary per receipt with the reasons, so the reviewer starts with the problem rather than the photo.

Step 5. Measure

Once it works, the useful number is how often the checks catch real errors. On a real project, take 50 receipts, extract them, have a person check every field, and count: how many wrong fields got past your checks? That count, not the model’s confidence, tells you whether the pipeline is safe to automate.

Common mistakes

  • Trusting valid JSON. Structured outputsStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. guarantee the shape (chapter 14), not that the numbers are right.
  • Auto-correcting the total. You don’t know which number was misread. Flag it.
  • Sending full-resolution photos. Resize first; the text stays legible and you send far fewer tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id..
  • Keeping card numbers. If a receipt shows card digits, drop them before storage. Use obviously fake test data in examples.

Key points

  • Ask for a fixed schema with nullable fields, so 'I can't read this' is a valid answer instead of a guess.
  • Never trust extracted numbers on their own: check that line items, tax and total add up, and that dates and currencies parse.
  • Ask for the raw text the model read beside each value, so a reviewer can see where a mistake came from.
  • Anything that fails a check goes to review, not straight into the ledger.
Hands-on labRuns in the Playground

Validate fields extracted from a receipt

Check a vision model's receipt extraction in code and route anything doubtful to a person.

You will have: A validator that saves or flags three extracted receipts, each with a one-line reason.

Steps

  1. Run the starter: all three receipts are saved.
  2. Check required fields are present and not null.
  3. Check the date parses as YYYY-MM-DD and isn't after today (2026-11-24), and the currency is allowed.
  4. Check that items plus tax equal the total within 0.01.
  5. Print SAVE or REVIEW per receipt with the reasons, then a count of each.

Done when

  • R-1 prints SAVE.
  • R-2 prints REVIEW with 'sum 45.65 does not match total 47.65'.
  • R-3 prints REVIEW with 'total unreadable', and the summary reads 'saved 1, review 2'.

Open in the Playground No API key needed.

Starter code (Python)
import json
from datetime import date
TODAY = date(2026, 11, 24)
ALLOWED = {"GBP", "EUR", "USD"}
# What a vision model returned for three receipt photos (test data, no real merchants or cards).
REPLIES = [
    '{"id": "R-1", "merchant": "Corner Cafe", "date": "2026-11-20", "currency": "GBP", "items": [{"name": "Tea", "amount": 2.50}, {"name": "Scone", "amount": 3.20}], "tax": 1.14, "total": 6.84}',
    '{"id": "R-2", "merchant": "Hardware Hub", "date": "2026-11-18", "currency": "GBP", "items": [{"name": "Drill bits", "amount": 29.00}, {"name": "Screws", "amount": 12.50}], "tax": 4.15, "total": 47.65}',
    '{"id": "R-3", "merchant": "Book Nook", "date": "2026-11-21", "currency": "EUR", "items": [{"name": "Novel", "amount": 14.00}], "tax": 0.0, "total": null}',
]

def problems(r):
    found = []
    # TODO: required fields not null; date valid and not in the future; currency allowed
    # TODO: sum(items) + tax equals total within 0.01
    return found

for raw in REPLIES:
    r = json.loads(raw)
    found = problems(r)
    print(r["id"], "SAVE" if not found else "REVIEW: " + "; ".join(found))
Show a solution
import json
from datetime import date
TODAY = date(2026, 11, 24)
ALLOWED = {"GBP", "EUR", "USD"}
REPLIES = [
    '{"id": "R-1", "merchant": "Corner Cafe", "date": "2026-11-20", "currency": "GBP", "items": [{"name": "Tea", "amount": 2.50}, {"name": "Scone", "amount": 3.20}], "tax": 1.14, "total": 6.84}',
    '{"id": "R-2", "merchant": "Hardware Hub", "date": "2026-11-18", "currency": "GBP", "items": [{"name": "Drill bits", "amount": 29.00}, {"name": "Screws", "amount": 12.50}], "tax": 4.15, "total": 47.65}',
    '{"id": "R-3", "merchant": "Book Nook", "date": "2026-11-21", "currency": "EUR", "items": [{"name": "Novel", "amount": 14.00}], "tax": 0.0, "total": null}',
]

def problems(r):
    found = []
    for field in ["merchant", "date", "currency", "total"]:
        if r.get(field) is None:
            found.append(f"{field} unreadable")
    try:
        if r.get("date") and date.fromisoformat(r["date"]) > TODAY:
            found.append("date in the future")
    except ValueError:
        found.append("date does not parse")
    if r.get("currency") and r["currency"] not in ALLOWED:
        found.append("currency not allowed")
    if any(i["amount"] <= 0 for i in r["items"]):
        found.append("non-positive amount")
    if r.get("total") is not None:
        expected = round(sum(i["amount"] for i in r["items"]) + (r.get("tax") or 0), 2)
        if abs(expected - r["total"]) > 0.01:
            found.append(f"sum {expected:.2f} does not match total {r['total']:.2f}")
    return found

saved = review = 0
for raw in REPLIES:
    r = json.loads(raw)
    found = problems(r)
    saved += not found
    review += bool(found)
    print(r["id"], "SAVE" if not found else "REVIEW: " + "; ".join(found))
print(f"saved {saved}, review {review}")
Quick checkIn the lab, a receipt's line items add up to 41.50 and tax is 4.15, but the extracted total is 47.65. What should your code do?
How sure are you?
Pick an answer and how sure you are