cd /news/ai-tools/test-your-local-ais-invoice-json-bef… · home › topics › ai-tools › article
[ARTICLE · art-176674] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=↑ positive

Test your local AI’s invoice JSON before handing it to an import job

A developer published a dependency-free Python checker, review.py, that validates a local model's invoice JSON against the source text before any import job runs. The script asserts that each extracted amount cites the correct line, matches the printed label and value exactly, appears only once, and that subtotal plus tax equals total using Decimal arithmetic, returning a specific failure reason such as source:total or arithmetic for human review. The author notes the demo assumes a simple three-line USD bill and that a passing result is not permission to import.

recommendation

Before importing model-extracted invoice data, assert line citations, exact printed values, unique labels and Decimal arithmetic separately, and route each failure to human review instead of auto-fixing.

more in playbook: Verifying model output
by read3 min views6 publishedNov 26, 2026

Start with a text fixture, not a PDF: line 1 Subtotal: USD 80.00, line 2 Tax: USD 8.00, line 3 Total: USD 88.00. Ask your model for three keys: subtotal, tax, total. Each value is an object with a one-based line and a two-decimal string named usd, or null if missing. Ollama can accept a JSON Schema as the format for a chat response, but the schema cannot determine whether 88.00 was printed.

Build three assertions against the parsed draft. Total points to line 3 and its exact labelled value. No label has more than one match. Decimal("80.00") + Decimal("8.00") equals Decimal("88.00"). Treat each failure as a different reason to ask for review, rather than silently fixing the draft.

For a regression, keep the JSON shape valid and replace the total string with "89.00". A shape-only test passes, but the line check must fail. Change the source total as well and the amount now matches the source, but the arithmetic check must fail. Everything here is synthetic. No OCR or model benchmark is implied.

Save the entire block as review.py and run python3 review.py with Python 3. No packages, service or model are needed. No output means every assertion passed. The fixed JSON plays the role of the model response. The duplicate-label checks also reverse the order of the printed totals to make sure positional selection is rejected.

The checker returns the first failing reason. Keep that reason beside the original draft. On source:total, show the cited line and the amount side by side. On arithmetic, pass all three quoted amounts to the reviewer without correcting the printed total. If the original is a scan, keep the image separately because agreement with an OCR transcript is not agreement with the image. This demo assumes a simple three-line USD bill without discounts, credits or fee rules. A passing result is not permission to import.

import json
import re
from decimal import Decimal

labels = {"subtotal": "Subtotal", "tax": "Tax", "total": "Total"}
source = ["Subtotal: USD 80.00", "Tax: USD 8.00", "Total: USD 88.00"]
raw = """{"subtotal":{"line":1,"usd":"80.00"},
          "tax":{"line":2,"usd":"8.00"},
          "total":{"line":3,"usd":"88.00"}}"""
draft = json.loads(raw)

def review(lines, candidate):
    if not isinstance(candidate, dict) or set(candidate) != set(labels):
        return "shape"
    amounts = {}
    for key, label in labels.items():
        cell = candidate[key]
        if cell is None:
            return "unknown:" + key
        if not isinstance(cell, dict) or set(cell) != {"line", "usd"}:
            return "shape:" + key
        line, usd = cell["line"], cell["usd"]
        if type(line) is not int or not 1 <= line <= len(lines):
            return "line:" + key
        matches = [i for i, text in enumerate(lines, 1)
                   if text.startswith(label + ":")]
        if (matches != [line] or not isinstance(usd, str)
            or not re.fullmatch(r"(0|[1-9][0-9]{0,8})[.][0-9]{2}", usd)
            or lines[line - 1] != f"{label}: USD {usd}"):
            return "source:" + key
        amounts[key] = Decimal(usd)
    if amounts["subtotal"] + amounts["tax"] != amounts["total"]:
        return "arithmetic"
    return "checks_passed"

assert review(source, draft) == "checks_passed"

wrong = dict(draft, total={"line": 3, "usd": "89.00"})
assert review(source, wrong) == "source:total"
printed_wrong = source[:2] + ["Total: USD 89.00"]
assert review(printed_wrong, wrong) == "arithmetic"

for totals in (["Total: USD 88.00", "Total: USD 89.00"],
               ["Total: USD 89.00", "Total: USD 88.00"]):
    match = dict(draft, total={"line": 3, "usd": totals[0].split()[-1]})
    assert review(source[:2] + totals, match) == "source:total"

The local chat API accepts a schema in format. Ollama structured outputs

The checker constructs Decimal values directly from strings. Python decimal reference

AI was used to help draft this article.

── more in #ai-tools 4 stories · sorted by recency
── more on @ollama 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/test-your-local-ais-…] indexed:0 read:3min 2026-11-26 · —