Lab 2: Invoices and charts you can trust¶
Build an invoice reader that returns clean, typed data, checks its own maths, and sends anything suspicious to a human.
| When | Day 1 (25 minutes, hands-on) |
| Lab file | labs/02-invoices-and-charts.ts, run with npm run lab2 -- <step> |
| Files used | data/invoice_01.png, data/invoice_02.png, data/invoice_03_rotated.jpg, data/chart_revenue.png |
Warning
Rule of the day: never trust an extracted number until code has checked it. The model reads; your code checks.
What you'll build¶
Step 0: Open the lab file¶
Do: open labs/02-invoices-and-charts.ts in your editor. Each step below is one block in that file; run it with npm run lab2 -- <step number>. You should see Provider: ... | model: ... at the top of every run.
Step 1: Define the shape of the answer¶
Do: read the LineItem and Invoice schemas near the top of the file. They use Zod, a TypeScript library that describes and checks the shape of data. Then run npm run lab2 -- 1.
You should see the list of fields in the schema. Fields marked .nullish() may be missing on a real invoice.
Why it matters: the schema is a contract. It's like handing someone a form to fill in instead of asking for an essay. Your later code relies on these field names and types.
Step 2: Extract the first invoice¶

Do: npm run lab2 -- 2.
You should see an invoice object with these values:
| Field | Expected value |
|---|---|
| vendor_name | Sahyadri Cloud Services Pvt Ltd |
| invoice_number | SCS/2026/1147 |
| invoice_date | 14-11-2026 |
| line items | 4 lines: 25,200 + 26,100 + 32,000 + 15,000 |
| subtotal | 98,300 |
| tax_amount (GST 18%) | 17,694 |
| total | 115,994 |
Why it matters: no template and no coordinates. The model found every field from the picture alone.
Step 3: Check the maths with code¶
Do: npm run lab2 -- 3. It uses validate() (read it in the file), which checks that:
- each line's quantity × rate equals its amount
- the lines add up to the subtotal
- the tax equals the tax rate × subtotal
- subtotal + tax equals the total
- the GSTIN is 15 characters long
You should see:
Step 4: Catch the broken invoice¶

Do: npm run lab2 -- 4.
You should see at least one warning, for example:
The lines add up to 55,500 (22,500 + 24,000 + 9,000), but the invoice prints 54,500. The GST (9,810) and total (64,310) were then calculated on the wrong subtotal.
Why it matters: this is a real-world error: the document is wrong, and your pipeline caught it.
Info
Try this: remove the words "exactly as printed" from PROMPT near the top of the file and run Step 4 again. Does the model quietly "fix" the subtotal? If it does, it hides the very error you needed to catch.
Success
Checkpoint: invoice_01 passes and invoice_02 shows a subtotal warning.
Step 5: Try a bad scan¶

Do: npm run lab2 -- 5. The prompt now adds: "If a value is unreadable, use null and do not guess."
You should see total read: ... | truth: 115994.0, then either ✅ passes or one or more warnings.
Why it matters: results on poor scans vary from run to run and from person to person. Compare with your neighbour. Allowing null gives the model an honest way out instead of a guess.
Step 6: Route each invoice¶
Do: npm run lab2 -- 6.
You should see one line per invoice:
{'doc': 'invoice_01', 'decision': 'AUTO_ACCEPT', 'reasons': []}
{'doc': 'invoice_02', 'decision': 'HUMAN_REVIEW', 'reasons': ['Subtotal 54,500.00 != sum of lines 55,500.00']}
{'doc': 'invoice_03', 'decision': ..., 'reasons': [...]}
Why it matters: the rule is simple and explainable. If every check passes, the invoice is accepted automatically; otherwise a person reviews it and sees exactly why.
Step 7: Ask questions about a chart¶

Do: npm run lab2 -- 7. It asks four questions about the chart.
Check the answers against the truth:
| Question | Correct answer |
|---|---|
| Highest revenue quarter | Q2 FY27, 563 crore |
| Growth from Q1 FY26 to Q2 FY27 | (563 − 412) ÷ 412 = 36.7% |
| Does the AI-led share ever fall? | No: 31 → 35 → 39 → 44 → 48 → 52% |
| The chart as a JSON table | Revenue 412, 438, 455, 497, 521, 563; AI share 31, 35, 39, 44, 48, 52 |
Why it matters: language models are better readers than calculators. The safest pattern is to ask for the table first, then do the maths in code.
Your turn (if you finish early)¶
Add each exercise as a new step (8, 9, 10) where the comment Your turn sits at the bottom of the lab file, then run it with npm run lab2 -- 8. See Running the labs.
1. Add a due-date check. Add a due_date field and check that it comes after invoice_date.
Hint
8: {
title: "Due-date check", run: async () => {
const InvoiceWithDue = Invoice.extend({ due_date: z.string().nullish() }); // DD-MM-YYYY if printed
const inv = await askJson("Extract this invoice exactly as printed. Numbers without commas. " +
"Use null for any field that is not printed.",
{ images: ["data/invoice_01.png"], schema: InvoiceWithDue });
const toDate = (s: string) => { const [d, m, y] = s.split("-").map(Number); return new Date(y, m - 1, d); };
if (inv.due_date) console.log(toDate(inv.due_date) > toDate(inv.invoice_date) ? "✅ due date OK" : "⚠️ due date is before invoice date");
else console.log("No due date printed");
},
},
The sample invoices say "Payment due within 30 days" but print no date, so a correct answer here is null. Did your model invent a date?
2. Read a receipt. Make a receipt schema and run it on data/images/receipt_cafe.png.

Hint
9: {
title: "Read a receipt", run: async () => {
const Receipt = z.object({
merchant: z.string(),
date: z.string().nullish(),
items: z.array(z.object({ name: z.string(), amount: z.number() })),
total: z.number(),
});
const r = await askJson("Extract this receipt exactly as printed.",
{ images: ["data/images/receipt_cafe.png"], schema: Receipt });
console.log(r);
const sum = r.items.reduce((s, i) => s + i.amount, 0);
console.log(Math.abs(sum - r.total) < 1 ? "✅ adds up" : "⚠️ doesn't add up");
},
},
Expected: Chai Point, three items (120 + 160 + 60), total 340.
3. Stretch: compare two invoices in one call. Send both invoices together and ask which vendor charges more GST.
Hint
10: {
title: "Compare two invoices", run: async () => {
console.log(await ask("Image 1 and Image 2 are two invoices. Which vendor charges more GST in rupees? " +
"Quote both GST amounts exactly as printed.",
{ images: ["data/invoice_01.png", "data/invoice_02.png"] }));
},
},
Expected: Sahyadri Cloud Services (17,694) charges more than Konkan Data Labs (9,810).
Key takeaways¶
- Define a schema first; ask the model to fill it exactly as printed.
- Let the model read and let code check: arithmetic, formats, totals.
- Route on checks you can explain, not on the model's own confidence.
- For charts, extract the table first and calculate in code.
Stuck?¶
ZodErrorfromaskJson: the model's JSON didn't match the schema, even after one automatic repair. Run the step again; if it keeps failing, ask your trainer about a stronger model.validate()shows warnings on invoice_01: look at the warning. A misread digit (for example 26,100 read as 28,100) is exactly what the checks are for. Run the step again and compare.ReferenceError: z is not definedin your own step: the import is at the top of the file (import { z } from "zod"); check you didn't delete it.- Red squiggles in VS Code but the step runs: fine.
tsxruns the file even when the editor shows a type warning.