Inferensys

Prompt

Invoice Field Extraction from Unstructured Text Prompt Template

A practical prompt playbook for accounts payable automation teams extracting line items, totals, dates, and vendor details from OCR text or model narratives. Produces structured invoice records with currency normalization and tax breakdowns.
Finance team reviewing invoice processing automation on laptop, spreadsheets and workflow diagrams visible, casual office moment.
PROMPT PLAYBOOK

When to Use This Prompt

Identify the right conditions for deploying the invoice extraction prompt and understand its operational boundaries before integrating it into your AP automation pipeline.

This prompt is designed for accounts payable automation teams and data pipeline engineers who receive unstructured invoice text from OCR engines, email bodies, or model narratives and need to convert it into a validated, structured JSON record. Use this prompt when the source text contains invoice-level information including vendor details, line items, totals, tax amounts, and dates but arrives as free text rather than a typed schema. The ideal user is an integration engineer or AP operations lead who already has a working extraction pipeline but encounters a recurring failure mode: the upstream model or OCR system produces a narrative description of the invoice instead of a machine-readable payload, and that narrative must be repaired into a clean, application-ready record without manual re-keying.

This prompt is part of the Output Repair and Validation Prompts pillar because it handles the post-generation repair loop. It is not a general-purpose extraction prompt for raw document images or PDFs. It assumes the text has already been extracted and that the failure is structural—the information exists in prose form but lacks the schema required by your general ledger, ERP, or approval system. The prompt includes built-in arithmetic validation checks that reconcile line-item sums against stated subtotals, tax amounts, and invoice totals. These checks serve as a first-pass quality gate, flagging records where the extracted figures do not add up so your pipeline can route them for human review rather than silently posting incorrect data.

Do not use this prompt when the source is a clean, typed invoice object already conforming to your schema—that is a straight mapping problem, not a repair problem. Do not use it for multi-page legal contracts, purchase orders, or receipts, which have different field semantics and validation rules. Do not use it as a substitute for a proper OCR confidence threshold or as the sole validation layer in a high-volume, fully automated posting pipeline. In regulated environments where incorrect invoice posting has material financial or compliance impact, always pair this prompt with a human-in-the-loop review step for any record that fails arithmetic validation or has missing required fields. The next section provides the copy-ready prompt template you can adapt for your specific invoice schema and validation rules.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Invoice Field Extraction from Unstructured Text Prompt Template is the right tool for your current task.

01

Good Fit: OCR-Derived Invoice Text

Use when: you have raw, unstructured text from OCR engines or model narratives that contain invoice data. Guardrail: The prompt is optimized for accounts payable automation and expects common invoice fields like line items, totals, and vendor details. Ensure the source text includes these semantic elements.

02

Bad Fit: Native PDF or Image Files

Avoid when: your input is a raw PDF, scanned image, or other binary format. Guardrail: This prompt operates on extracted text, not visual documents. You must run a dedicated OCR or document intelligence step first. For layout-aware extraction, use a Document Intelligence prompt from the Document Intelligence and PDF Prompts pillar.

03

Required Inputs: Text and Schema

Use when: you can provide the unstructured invoice text and a target output schema. Guardrail: The prompt requires a clear [OUTPUT_SCHEMA] defining the desired JSON structure. Without a schema, the model may produce inconsistent or incomplete records. Always include field definitions for line items, totals, taxes, and vendor details.

04

Operational Risk: Arithmetic Inconsistency

Risk: The model may extract line items and a total that do not reconcile mathematically. Guardrail: Always implement a post-extraction validation step that sums line items and compares against the extracted total. Flag any discrepancies for human review before the record enters your financial system.

05

Operational Risk: Currency Ambiguity

Risk: The source text may omit currency symbols or use ambiguous notation, leading to incorrect normalization. Guardrail: Include a [CURRENCY] placeholder in the prompt template and default to a standard currency if not specified. Validate all extracted amounts against expected currency formats and flag multi-currency invoices for manual review.

06

Bad Fit: Handwritten or Highly Irregular Layouts

Avoid when: the source document is handwritten, heavily damaged, or uses a non-standard layout that OCR cannot reliably linearize. Guardrail: This prompt assumes the input text has a coherent narrative flow. For highly irregular documents, escalate to a human reviewer or use a specialized document intelligence model before attempting extraction.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for extracting structured invoice fields from unstructured OCR text or model narratives.

This template is designed to be the core instruction you send to a model when a previous extraction attempt has failed, or when you are working with raw, unstructured text that needs to be converted into a clean, typed invoice record. It is not a general-purpose extraction prompt; it is specifically hardened for the repair and normalization of invoice data, including line items, totals, and tax breakdowns. The template uses square-bracket placeholders like [INPUT_TEXT] and [OUTPUT_SCHEMA] that you must replace with your actual data and constraints before execution. This prompt assumes you have already attempted a structured output generation and are now in a repair loop, or that you are dealing with narrative text from an OCR engine.

Below is the copy-ready template. Replace every placeholder with your concrete values. The [OUTPUT_SCHEMA] should be a strict JSON schema. The [CONSTRAINTS] section is where you enforce business rules like currency normalization to USD or arithmetic consistency checks. The [EXAMPLES] section is critical for few-shot repair; provide at least one example of a malformed input and its perfectly corrected output. The [RISK_LEVEL] placeholder should be set to high for any financial data, which will trigger the instruction to flag low-confidence fields for human review.

text
You are an expert data repair agent specializing in financial documents. Your task is to extract structured invoice data from the unstructured text provided below. The previous extraction attempt failed validation or produced a narrative instead of a typed record. You must repair this by outputting a single, valid JSON object that strictly conforms to the provided schema.

### UNSTRUCTURED INPUT TEXT
[INPUT_TEXT]

### REQUIRED OUTPUT JSON SCHEMA
You must output a JSON object that validates against this schema. Do not include any fields not defined here.
[OUTPUT_SCHEMA]

### CONSTRAINTS AND NORMALIZATION RULES
- Currency: Normalize all monetary values to [TARGET_CURRENCY] using a precision of two decimal places. Do not include currency symbols in numeric fields.
- Dates: Convert all dates to ISO 8601 format (YYYY-MM-DD).
- Line Items: Extract every line item into the `line_items` array. Recalculate the `line_total` for each item as `quantity` * `unit_price`.
- Arithmetic Verification: Calculate the sum of all `line_items.line_total` and the `tax_amount` to verify it matches the provided `total_amount`. If it does not, set the `totals_match` field to `false`.
- Missing Information: For any required field where the value is not present in the text, use `null` and add the field path to the `missing_fields` array.
- Confidence: For each top-level field and each line item, provide a `confidence` score between 0.0 and 1.0.
[CONSTRAINTS]

### FEW-SHOT EXAMPLES OF REPAIR
[EXAMPLES]

### RISK LEVEL
[RISK_LEVEL]

### FINAL INSTRUCTION
Output only the JSON object. Do not include any explanatory text, markdown fences, or code blocks before or after the JSON. If the risk level is `high`, you must include a top-level field `requires_human_review` set to `true` if any required field has a confidence score below [CONFIDENCE_THRESHOLD].

To adapt this template, start by pasting your raw, unstructured invoice text into [INPUT_TEXT]. Then, define your [OUTPUT_SCHEMA] as a strict JSON schema, including required fields like invoice_number, vendor_name, invoice_date, total_amount, and line_items. In the [CONSTRAINTS] section, specify your target currency and any other business logic. Crucially, populate [EXAMPLES] with one or two pairs of a malformed input and its correct, schema-compliant JSON output. This teaches the model the exact repair pattern you expect. Finally, set [RISK_LEVEL] to high and [CONFIDENCE_THRESHOLD] to 0.9 for financial workflows. After receiving the output, you must programmatically validate it against your JSON schema and the arithmetic consistency rule before considering the repair successful. If validation fails, the output should be fed back into this same template as a new [INPUT_TEXT] for a retry loop, up to a defined limit.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate each input before calling the model to prevent extraction failures and arithmetic errors.

PlaceholderPurposeExampleValidation Notes

[UNSTRUCTURED_INVOICE_TEXT]

Raw OCR or narrative text containing invoice data to be extracted

INVOICE #1042\nDate: 14 Feb 2025\nVendor: Acme Corp\nLine Item: Widget A, 2 units, $50.00 each\nSubtotal: $100.00\nTax (8%): $8.00\nTotal: $108.00

Must be non-empty string. Reject if fewer than 20 characters or contains no numeric values. Flag for human review if text appears to be a packing slip or quote rather than an invoice.

[TARGET_CURRENCY]

ISO 4217 currency code for normalizing all monetary values

USD

Must match ^[A-Z]{3}$ pattern. Reject unsupported currencies. Default to USD if null but log warning. Validate against allowed currency list in application config.

[REQUIRED_FIELDS]

Array of field names that must be present in the output for the extraction to be considered complete

["invoice_number", "invoice_date", "vendor_name", "line_items", "subtotal", "tax_amount", "total_amount"]

Must be a valid JSON array of strings. Each field name must correspond to a key in [OUTPUT_SCHEMA]. Empty array allowed but will skip completeness checks. Validate against schema definition before prompt assembly.

[OUTPUT_SCHEMA]

JSON Schema definition describing the expected output structure with field types and constraints

{"type": "object", "properties": {"invoice_number": {"type": "string"}, "line_items": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string"}, "quantity": {"type": "number"}, "unit_price": {"type": "number"}, "line_total": {"type": "number"}}}}}}

Must be valid JSON Schema draft-07 or later. Parse and validate schema before prompt assembly. Reject schemas with circular references. Ensure numeric fields specify minimum: 0 where appropriate.

[TAX_RATE_HINT]

Optional known tax rate as a decimal to help validate extracted tax amounts

0.08

If provided, must be a number between 0.0 and 1.0. Used for arithmetic consistency check between subtotal, tax, and total. Null allowed when tax rate is unknown or variable. Do not force extraction to match this hint if invoice shows different rate.

[CONFIDENCE_THRESHOLD]

Minimum confidence score (0.0 to 1.0) required for extracted fields to be accepted without human review

0.85

Must be a float between 0.0 and 1.0. Fields below threshold should be flagged with low_confidence: true and routed for human approval. Default to 0.80 if null. Lower values increase automation but risk incorrect extraction.

[VENDOR_ALIAS_MAP]

Optional mapping of known vendor name variations to canonical names for normalization

{"Acme Corp.": "Acme Corporation", "ACME INC": "Acme Corporation"}

Must be a valid JSON object with string keys and string values. Null allowed. Apply normalization after extraction but preserve original extracted name in raw_vendor_name field. Log normalization events for audit trail.

[LINE_ITEM_REQUIRED_FIELDS]

Array of field names that must be present in each line item object for the extraction to be considered valid

["description", "quantity", "unit_price", "line_total"]

Must be a valid JSON array of strings. Each line item in the output must contain all specified fields. Missing fields trigger retry or human review depending on retry configuration. Validate against line item schema definition.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the invoice extraction prompt into a reliable application pipeline with validation, retries, and human review.

This prompt is designed to be a post-generation repair step, not the primary structured output generator. The typical integration pattern is: (1) attempt structured generation via function calling or JSON mode, (2) if that fails or returns narrative text, route the output to this prompt for repair, (3) validate the repaired output against the invoice schema, and (4) escalate to human review if validation still fails. Do not use this prompt as your first-choice extraction method—it is a safety net for when the model ignores your output format instructions.

Validation checks must run after every extraction. At minimum, verify: (a) invoice_total equals the sum of line_items[].line_total plus tax_breakdown[].tax_amount, within a small floating-point tolerance; (b) all required fields (invoice_number, invoice_date, vendor_name, invoice_total, currency) are present and non-null; (c) invoice_date and due_date parse to valid ISO 8601 dates; (d) currency matches an expected ISO 4217 code; and (e) line_items is a non-empty array with each item containing description, quantity, unit_price, and line_total. If any check fails, log the specific failure and the raw model output for debugging. For high-value invoices (above a configurable threshold), route failures to a human review queue with the original OCR text, the extracted fields, and the specific validation errors highlighted.

Retry logic should be bounded. If the first repair attempt produces invalid output, retry once with the same prompt but prepend the validation errors as additional context: [PREVIOUS_OUTPUT] and [VALIDATION_ERRORS]. If the second attempt also fails, stop retrying and escalate. Avoid infinite repair loops—each retry costs tokens and latency. For production systems processing hundreds of invoices per hour, consider a model routing strategy: use a faster, cheaper model for the initial structured extraction attempt, and reserve a more capable model (e.g., GPT-4 or Claude 3.5 Sonnet) for the repair step only when the primary extraction fails.

Logging and observability are critical. Capture the raw OCR input, the primary extraction output, whether the repair prompt was invoked, the repaired output, validation results, and the final disposition (accepted, repaired, escalated). This trace data lets you measure repair prompt effectiveness over time and identify patterns—for example, if certain vendors or invoice formats consistently trigger the repair path, you may need to improve your primary extraction prompt or add few-shot examples for those cases. Store these traces in your existing observability platform (Datadog, Grafana, etc.) alongside other model inference metrics.

Human review integration should present reviewers with a side-by-side view: original document text on the left, extracted fields on the right, with validation failures highlighted in red. Allow reviewers to correct fields directly and submit the corrected record. Use these corrections as feedback data to improve both the primary extraction prompt and the repair prompt over time—each human correction is a labeled example you can add to your few-shot examples or use for fine-tuning evaluation.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact fields, types, and validation rules for the structured invoice record produced by the prompt. Use this contract to build your downstream parser or validator before processing model output.

Field or ElementType or FormatRequiredValidation Rule

invoice_number

string

Must match pattern [A-Z0-9-]+. Reject if null or empty.

invoice_date

string (ISO 8601)

Must parse as YYYY-MM-DD. Reject if date is in the future or unparseable.

due_date

string (ISO 8601)

Must parse as YYYY-MM-DD. Must be on or after invoice_date. Reject if null.

vendor.name

string

Must be non-empty string. Reject if only whitespace or missing.

vendor.address

string

Allow null. If present, must be non-empty string.

vendor.tax_id

string

Allow null. If present, must match pattern [A-Z0-9-]{5,20}.

currency

string (ISO 4217)

Must be exactly 3 uppercase letters. Reject if not in allowed currency list.

total_amount

number

Must be positive. Must equal sum of line_items.amount + tax_breakdown.total_tax. Tolerance: 0.01.

subtotal

number

Must be positive. Must equal sum of line_items.amount. Reject if negative.

tax_breakdown.total_tax

number

Must be non-negative. Must equal sum of tax_breakdown.details[].amount. Reject if negative.

tax_breakdown.details

array of objects

Allow empty array. Each object must have rate (number, 0-100) and amount (number, non-negative).

line_items

array of objects

Must contain at least 1 item. Each item requires description (string, non-empty), quantity (number, positive), unit_price (number, non-negative), amount (number, must equal quantity * unit_price within 0.01 tolerance).

notes

string

Allow null or empty string. If present, must not exceed 500 characters.

confidence_flags.invoice_number

string (enum)

Must be one of: high, medium, low. Set to low if extracted from ambiguous text region.

confidence_flags.total_amount

string (enum)

Must be one of: high, medium, low. Set to low if arithmetic check fails within tolerance.

source_text_hash

string

Must be non-empty. Use SHA-256 of input text for traceability. Reject if missing.

PRACTICAL GUARDRAILS

Common Failure Modes

Invoice extraction from unstructured text is brittle. Models hallucinate totals, misparse line items, and normalize currencies incorrectly. These are the most common production failures and how to prevent them before they reach your AP system.

01

Line-Item Total Mismatch

What to watch: The sum of extracted line items does not equal the extracted invoice total. The model may hallucinate a line item to make the math work or drop a real line item that was poorly OCR'd. Guardrail: Add a post-extraction arithmetic validator that sums line items and compares against the invoice total. Flag any discrepancy greater than $0.01 for human review. Reject outputs where the mismatch exceeds 1% of the total.

02

Currency Symbol Hallucination

What to watch: The model inserts a currency symbol or code that does not appear in the source text, especially when the invoice lacks explicit currency markers. Common with USD/€/£ confusion in international invoices. Guardrail: Constrain the prompt to only extract currency if explicitly present in the source. Add a post-processing rule that strips any currency value not matched to a source substring. Default to a null currency field rather than guessing.

03

Vendor Name vs. Legal Entity Confusion

What to watch: The model extracts a trade name or DBA instead of the legal entity name required for payment processing. This breaks downstream vendor matching and compliance checks. Guardrail: Instruct the prompt to distinguish between 'remit-to name', 'legal entity name', and 'trade name' when present. Add a validation step that cross-references extracted vendor names against your vendor master. Flag unmatched names for manual review.

04

Date Format Ambiguity

What to watch: The model misinterprets date formats (MM/DD vs DD/MM), especially for invoices with dates like 03/04/2025. This corrupts due dates, payment terms, and aging reports. Guardrail: Require ISO 8601 output format in the prompt schema. Add a validator that rejects dates where day > 12 when format is ambiguous, or flag for human clarification. Never let the model silently guess the format.

05

Multi-Page Invoice Truncation

What to watch: When OCR text from a multi-page invoice exceeds the context window, the model extracts only page-one fields and silently omits line items or totals from later pages. The output looks valid but is incomplete. Guardrail: Add a completeness check that verifies the presence of a final total and compares page count metadata against extracted content. If the invoice text was chunked, require a summary reconciliation step before final extraction.

06

Tax Breakdown Fabrication

What to watch: The model invents tax rates, tax amounts, or tax categories that are not present in the source invoice. This is especially common when the invoice shows a total with tax included but no explicit tax line. Guardrail: Instruct the prompt to only extract tax fields when explicitly stated in the source. Add a validator that flags any tax amount that, when subtracted from the total, does not match the pre-tax subtotal. Require source citation for every tax field.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of structured invoice records extracted from unstructured text before integrating the output into downstream accounts payable systems.

CriterionPass StandardFailure SignalTest Method

Required Field Presence

All fields in [OUTPUT_SCHEMA] marked as required are present and non-null in every record

Missing invoice_number, total_amount, or invoice_date in any output record

Schema validation check: iterate all output records and assert required fields exist and are not null

Currency Normalization

All monetary values use the ISO 4217 currency code specified in [CURRENCY] and amounts are parsed to decimal numbers

Currency symbol mismatch, string amounts like '$1,234.56' instead of numeric 1234.56, or mixed currencies in a single invoice

Regex check for non-numeric characters in amount fields; assert all currency fields match [CURRENCY] code

Date Standardization

All date fields conform to [DATE_FORMAT] and are parseable as valid calendar dates

Unparseable date strings, dates in wrong format, or future dates for invoice_date

Parse each date field with the expected format string; assert no parse errors and invoice_date is not in the future

Line Item Arithmetic Consistency

Sum of line item totals equals the invoice subtotal within a tolerance of 0.01

Subtotal does not match sum of line items; tax amount calculated from wrong base; total does not equal subtotal plus tax

Compute sum(line_item_total) for each invoice; assert abs(sum - subtotal) <= 0.01 and abs(subtotal + tax - total) <= 0.01

Vendor Name Extraction

Vendor name matches a known entity in [VENDOR_LIST] or is extracted verbatim from the source text without hallucination

Hallucinated vendor name not present in source text; truncated vendor name; vendor name conflated with billing address entity

String containment check: extracted vendor name must appear in [INPUT_TEXT] or match an entry in [VENDOR_LIST]

Tax Breakdown Accuracy

Tax amount and tax rate are both present when [TAX_REQUIRED] is true; tax rate is a positive decimal

Missing tax_rate when tax_amount is present; negative tax values; tax_rate stored as string with percent sign

Assert tax_amount is numeric and >= 0; assert tax_rate is numeric and > 0 when tax_amount > 0; strip percent signs before validation

No Hallucinated Fields

Output contains only fields defined in [OUTPUT_SCHEMA]; no invented fields like 'payment_terms' or 'po_number' unless specified

Extra fields appear in output that were not requested in the schema

Diff output keys against [OUTPUT_SCHEMA] field list; assert no unexpected keys present in any record

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt\nUse the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet). Relax output validation to accept minor field name variations. Focus on getting the extraction logic right before hardening the schema.\n\n### Prompt snippet\n```\nExtract invoice fields from the text below. Return JSON with vendor_name, invoice_date, due_date, line_items (array of {description, quantity, unit_price, amount}), subtotal, tax_total, and total. If a field is missing, use null.\n\n[UNSTRUCTURED_INVOICE_TEXT]\n```\n\n### Watch for\n- Line item totals that don't sum to the invoice total\n- Date formats varying across invoices (MM/DD/YYYY vs DD-MM-YYYY)\n- Currency symbols embedded in amount strings

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.