{"slug": "receipt-reader-with-vision", "title": "Receipt Reader with vision", "summary": "A developer built a receipt-scanning pipeline that sends a photo to Gemini's vision model and returns validated structured data—store name, purchase date, payment method, subtotal, tax, total and line items—using a Pydantic schema passed as the response schema. The approach relies on field descriptions to steer extraction, a boolean 'receipt' flag to discard unpaid or future-dated receipts, temperature 0, and a separate check that recomputes item totals rather than trusting the model's arithmetic.", "body_md": "| Day | Topic | Example | Status | \n|---|---|---|---|\n| 1 | Talking to an LLM from code | Classifying emails by category and urgency | ✅ [Code](https://github.com/SantiagoAlvarze22/ai-engineering-lab/blob/main/week1/day1_clasificator.py) | \n| 2 | Roles, examples and delimiters in prompts | Translating technical language into plain language | ✅ [Code](https://github.com/SantiagoAlvarze22/ai-engineering-lab/blob/main/week1/day2_jargon_translator.py) | \n| 3 | Structured output with JSON, validated with Pydantic | Turning a chat order into a table | ✅ [Code](https://github.com/SantiagoAlvarze22/ai-engineering-lab/blob/main/week1/day3_chat_orders.py) | \n| 4 | Images with vision models | Scanning a receipt and returning a JSON with the products and the total | 📍 You're here | \n| 5 | Embeddings: meaning as numbers | Grouping 20 news articles by topic | ⏳ Coming soon | \n\n**The goal:** take a photo of a receipt and turn it into structured data: the store, the date, the payment method, the totals and every item purchased.\n\nVision models can read images, not just text. That means I can send a photo to Gemini and get the data back in the same validated format I used on Day 3.\n\n**The schema**\n\nI created two classes: `Article` describes each item the customer bought, and `Receipts` contains all the information about the purchase, including the list of articles.\n\n```\nclass Receipts(BaseModel):\n    name: str | None = Field(\n        default=None, description=\"Name of the store where the purchase was made\"\n    )\n    purchase_date: date | None = Field(default=None, description=\"Date where the purchase was done\")\n    address: str | None = Field(\n        default=None, description=\"null if not mentioned the address of the store\"\n    )\n    payment_method: str | None = Field(\n        default=None, description=\"null if not mentioned the payment method\"\n    )\n    subtotal: float | None = Field(\n        default=None, description=\"The price of the products with no tax included\"\n    )\n    tax: float | None = Field(\n        default=None,\n        description=\"amount in money, not the percentage\",\n    )\n    total: float | None = Field(default=None, description='The grand total of the purchase')\n    receipt: bool | None = Field(\n        default=None,\n        description=\"The receipt shows that the purchase is already paid. True only if appears any of these, the payment method, card number, amount charged, and False if the date of payment is in the future according to the date the image has\",\n    )\n    articles: list[Article]\n```\n\nTwo details make this schema work:\n\n`description` guides the model.`19` instead of `$3.80` for the tax.`receipt: bool` acts as a filter.`False`, and my code discards it.\n**Reading the image**\n\n``` php\ndef describe_receipt(path: str) -> Receipts | None:\n    image_bytes = Path(path).read_bytes()\n    image_part = types.Part.from_bytes(\n        data=image_bytes,\n        mime_type=MIME_TYPE[Path(path).suffix.lower()],\n    )\n\n    response = client.models.generate_content(\n        model=model,\n        contents=image_part,\n        config=types.GenerateContentConfig(\n            system_instruction=\"\"\"Extract the products orders. Use only information present in the image\"\"\",\n            temperature=0,\n            response_mime_type=\"application/json\",\n            response_schema=Receipts,\n        ),\n    )\n\n    # in case the receipt property is False\n    return None if not response.parsed.receipt else response.parsed\n```\n\nThe function reads the image as bytes and tells the model what kind of file it is (`mime_type`, based on the extension: `.png`, `.jpg`...). Then it sends the image together with the schema. `response.parsed` already returns a validated `Receipts` object, so there's no need to parse the JSON by hand.\n\n**Checking the math**\n\n``` php\ndef check_totals(receipt: Receipts) -> None:\n    \"\"\"Verify the model's numbers instead of trusting them blindly.\"\"\"\n    items_sum = 0\n    for article in receipt.articles:\n        items_sum += article.price * article.amount\n\n    # Check 1: items vs subtotal (round to cents to avoid float errors)\n    if round(items_sum, 2) == round(receipt.subtotal, 2):\n        print(f\"Check 1 OK: items sum {items_sum:.2f} = subtotal {receipt.subtotal:.2f}\")\n    else:\n        print(f\"Check 1 FAILED: items sum {items_sum:.2f} != subtotal {receipt.subtotal:.2f}\")\n\n    # Check 2: subtotal + tax vs total\n    expected_total = receipt.subtotal + receipt.tax\n    if round(expected_total, 2) == round(receipt.total, 2):\n        print(f\"Check 2 OK: subtotal + tax {expected_total:.2f} = total {receipt.total:.2f}\")\n    else:\n        print(f\"Check 2 FAILED: subtotal + tax {expected_total:.2f} != total {receipt.total:.2f}\")\n```\n\nA model can misread a number in the image. This function does the math again in plain Python: the items must add up to the subtotal, and the subtotal plus tax must equal the total.\n\nThis is the receipt I used:\n\nAnd this is the output:\n\n`mime_type`). The rest works just like with text.` None`.` receipt.tax` is `subtotal + tax` crashes. Every field that can be empty needs a plan for when it is.\n👉 Full code: [day4_receipt_reader.py](https://github.com/SantiagoAlvarze22/ai-engineering-lab/blob/main/week1/day4_receipt_reader.py)", "url": "https://wpnews.pro/news/receipt-reader-with-vision", "canonical_source": "https://dev.to/sao2207/receipt-reader-with-vision-3mn3", "published_at": "2026-12-02 18:12:54+00:00", "updated_at": "2026-12-02 18:18:05.170769+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "generative-ai", "computer-vision", "ai-tools"], "entities": ["Gemini", "Pydantic", "SantiagoAlvarze22"], "also_reported_by": [], "takeaway": "Passing a Pydantic schema as Gemini's response_schema with per-field descriptions and temperature 0 returns a validated object via response.parsed, and a boolean field can filter out unpaid receipts before downstream use.", "recommendation": {"advice": "Use response_schema with descriptive fields and temperature 0 for vision extraction, then recompute totals in code instead of trusting the model's arithmetic.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/receipt-reader-with-vision", "markdown": "https://wpnews.pro/news/receipt-reader-with-vision.md", "text": "https://wpnews.pro/news/receipt-reader-with-vision.txt", "jsonld": "https://wpnews.pro/news/receipt-reader-with-vision.jsonld"}}