vM.

How to Extract Structured Invoice Data with an LLM

Author
Vishal Maurya
Published on
Reading time
2 min read

Overview

Asking a language model to “read this invoice and return JSON” is not enough for an accounting workflow. The output may be syntactically valid but still contain the wrong invoice number, confuse tax and total, or invent a value that was not visible.

Use a typed schema to define the output contract, preserve the source document, and validate extracted values against deterministic rules. Where possible, request evidence such as page references or short source snippets for fields that need review.

Add validation after extraction

  1. Use PDF text extraction for digital documents and OCR for image-only pages.
  2. Pass only the relevant text or page region to the model where possible.
  3. Validate the model response against a schema and reject malformed output.
  4. Check arithmetic, currency, date, vendor identity, and duplicate invoice numbers.
  5. Route missing or conflicting fields to human review rather than guessing.
  6. Record the model version, extraction version, source file, and approved corrections for auditing.

Example: a concrete starting point

from pydantic import BaseModel, Field
from decimal import Decimal

class InvoiceFields(BaseModel):
    invoice_number: str = Field(min_length=1)
    vendor_name: str = Field(min_length=1)
    currency: str = Field(min_length=3, max_length=3)
    subtotal: Decimal | None = None
    tax: Decimal | None = None
    total: Decimal = Field(ge=0)

The example illustrates the boundary and validation pattern; adapt names, persistence, error handling, and provider-specific details to your application. It is not a complete production system by itself.

Failure cases to test

Schema validity does not prove factual validity. Avoid using model output as the sole approval signal for payments. Keep personal and financial data access controlled and verify the model provider’s data-handling requirements before sending documents.

Before release, test the happy path, invalid input, missing permissions, dependency failure, and a retry or duplicate request where relevant. Record expected behavior so the implementation can be reviewed against the real business requirement.

When to bring in a developer

I can add structured AI extraction to a document workflow with validation rules, exception handling, and traceable outputs.

Conclusion

The reliable version of this feature is not just the happy-path demo. It makes ownership, validation, authorization, failure handling, and operational behavior explicit. Start with the smallest useful workflow, measure it against real data, and expand only when the next requirement is clear.

Additional Resources

  • docs.pydantic.dev
  • platform.openai.com