| Day | Topic | Example | Status | |---|---|---|---| | 1 | Talking to an LLM from code | Classifying emails by category and urgency | ✅ Code | | 2 | Roles, examples and delimiters in prompts | Translating technical language into plain language | ✅ Code | | 3 | Structured output with JSON, validated with Pydantic | Turning a chat order into a table | ✅ Code | | 4 | Images with vision models | Scanning a receipt and returning a JSON with the products and the total | 📍 You're here | | 5 | Embeddings: meaning as numbers | Grouping 20 news articles by topic | ⏳ Coming soon |
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.
Vision 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.
The schema
I created two classes: Article describes each item the customer bought, and Receipts contains all the information about the purchase, including the list of articles.
class Receipts(BaseModel):
name: str | None = Field(
default=None, description="Name of the store where the purchase was made"
)
purchase_date: date | None = Field(default=None, description="Date where the purchase was done")
address: str | None = Field(
default=None, description="null if not mentioned the address of the store"
)
payment_method: str | None = Field(
default=None, description="null if not mentioned the payment method"
)
subtotal: float | None = Field(
default=None, description="The price of the products with no tax included"
)
tax: float | None = Field(
default=None,
description="amount in money, not the percentage",
)
total: float | None = Field(default=None, description='The grand total of the purchase')
receipt: bool | None = Field(
default=None,
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",
)
articles: list[Article]
Two details make this schema work:
description guides the model.19 instead of $3.80 for the tax.receipt: bool acts as a filter.False, and my code discards it. Reading the image
def describe_receipt(path: str) -> Receipts | None:
image_bytes = Path(path).read_bytes()
image_part = types.Part.from_bytes(
data=image_bytes,
mime_type=MIME_TYPE[Path(path).suffix.lower()],
)
response = client.models.generate_content(
model=model,
contents=image_part,
config=types.GenerateContentConfig(
system_instruction="""Extract the products orders. Use only information present in the image""",
temperature=0,
response_mime_type="application/json",
response_schema=Receipts,
),
)
# in case the receipt property is False
return None if not response.parsed.receipt else response.parsed
The 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.
Checking the math
def check_totals(receipt: Receipts) -> None:
"""Verify the model's numbers instead of trusting them blindly."""
items_sum = 0
for article in receipt.articles:
items_sum += article.price * article.amount
# Check 1: items vs subtotal (round to cents to avoid float errors)
if round(items_sum, 2) == round(receipt.subtotal, 2):
print(f"Check 1 OK: items sum {items_sum:.2f} = subtotal {receipt.subtotal:.2f}")
else:
print(f"Check 1 FAILED: items sum {items_sum:.2f} != subtotal {receipt.subtotal:.2f}")
# Check 2: subtotal + tax vs total
expected_total = receipt.subtotal + receipt.tax
if round(expected_total, 2) == round(receipt.total, 2):
print(f"Check 2 OK: subtotal + tax {expected_total:.2f} = total {receipt.total:.2f}")
else:
print(f"Check 2 FAILED: subtotal + tax {expected_total:.2f} != total {receipt.total:.2f}")
A 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.
This is the receipt I used:
And this is the output:
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. 👉 Full code: day4_receipt_reader.py
原文来源:dev.to