{"slug": "test-your-local-ais-invoice-json-before-handing-it-to-an-import-job", "title": "Test your local AI’s invoice JSON before handing it to an import job", "summary": "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.", "body_md": "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.\n\nBuild 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.\n\nFor 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.\n\nSave 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.\n\nThe 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.\n\n``` python\nimport json\nimport re\nfrom decimal import Decimal\n\nlabels = {\"subtotal\": \"Subtotal\", \"tax\": \"Tax\", \"total\": \"Total\"}\nsource = [\"Subtotal: USD 80.00\", \"Tax: USD 8.00\", \"Total: USD 88.00\"]\nraw = \"\"\"{\"subtotal\":{\"line\":1,\"usd\":\"80.00\"},\n          \"tax\":{\"line\":2,\"usd\":\"8.00\"},\n          \"total\":{\"line\":3,\"usd\":\"88.00\"}}\"\"\"\ndraft = json.loads(raw)\n\ndef review(lines, candidate):\n    if not isinstance(candidate, dict) or set(candidate) != set(labels):\n        return \"shape\"\n    amounts = {}\n    for key, label in labels.items():\n        cell = candidate[key]\n        if cell is None:\n            return \"unknown:\" + key\n        if not isinstance(cell, dict) or set(cell) != {\"line\", \"usd\"}:\n            return \"shape:\" + key\n        line, usd = cell[\"line\"], cell[\"usd\"]\n        if type(line) is not int or not 1 <= line <= len(lines):\n            return \"line:\" + key\n        matches = [i for i, text in enumerate(lines, 1)\n                   if text.startswith(label + \":\")]\n        if (matches != [line] or not isinstance(usd, str)\n            or not re.fullmatch(r\"(0|[1-9][0-9]{0,8})[.][0-9]{2}\", usd)\n            or lines[line - 1] != f\"{label}: USD {usd}\"):\n            return \"source:\" + key\n        amounts[key] = Decimal(usd)\n    if amounts[\"subtotal\"] + amounts[\"tax\"] != amounts[\"total\"]:\n        return \"arithmetic\"\n    return \"checks_passed\"\n\nassert review(source, draft) == \"checks_passed\"\n\nwrong = dict(draft, total={\"line\": 3, \"usd\": \"89.00\"})\nassert review(source, wrong) == \"source:total\"\nprinted_wrong = source[:2] + [\"Total: USD 89.00\"]\nassert review(printed_wrong, wrong) == \"arithmetic\"\n\nfor totals in ([\"Total: USD 88.00\", \"Total: USD 89.00\"],\n               [\"Total: USD 89.00\", \"Total: USD 88.00\"]):\n    match = dict(draft, total={\"line\": 3, \"usd\": totals[0].split()[-1]})\n    assert review(source[:2] + totals, match) == \"source:total\"\n```\n\nThe local chat API accepts a schema in format. [Ollama structured outputs](https://docs.ollama.com/capabilities/structured-outputs)\n\nThe checker constructs Decimal values directly from strings. [Python decimal reference](https://docs.python.org/3/library/decimal.html)\n\nAI was used to help draft this article.", "url": "https://wpnews.pro/news/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job", "canonical_source": "https://dev.to/cloudgpu_app/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job-3mc2", "published_at": "2026-11-26 08:30:37+00:00", "updated_at": "2026-11-26 08:43:13.846581+00:00", "lang": "en", "topics": ["ai-tools", "large-language-models", "ai-agents"], "entities": ["Ollama", "Python"], "also_reported_by": [], "takeaway": "Validate model-extracted invoice JSON against the source text with separate line, exact-value, duplicate-label and Decimal arithmetic assertions, and surface each failure as a distinct review reason rather than silently correcting the draft.", "recommendation": {"advice": "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.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job", "markdown": "https://wpnews.pro/news/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job.md", "text": "https://wpnews.pro/news/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job.txt", "jsonld": "https://wpnews.pro/news/test-your-local-ais-invoice-json-before-handing-it-to-an-import-job.jsonld"}}