Skip to content

    AI Architect Case Files

    Case: Invoice Processing Agent and ERP Integration

    A distributor's invoice agent posted duplicates and wrong totals to its ERP. Strict schemas, validation before the call and idempotency fixed it.

    By Published 7 min read

    • ai-architect
    • case-file
    • industry-manufacturing-logistics
    • pattern-tool-integration
    • failure-integration-fragility
    • kind-composite
    Share

    Composite scenario, not a real company. Assembled from common industry patterns; every number is illustrative and its assumptions are listed at the end.

    This case belongs to Agents, Tools and MCP.

    Context

    • A regional parts distributor receives about 8,000 supplier invoices a month, mostly PDFs attached to emails and some scans.
    • Accounts payable clerks key the header, line items and tax into the ERP and match each invoice to a purchase order. A clerk spends about 6 minutes per invoice.
    • The ERP's posting interface returns numeric error codes and has no idempotency support. A posted document can only be undone with a credit note.
    • The team builds an agent that reads an invoice, matches it to a purchase order and posts it.

    Problem statement

    A 400-invoice pilot of the first design went wrong in two ways.

    Pilot result Count Rate Exposure
    Posted twice 9 2.25% 9 x 2,400 = 21,600 units (assumed average invoice)
    Posted with a wrong amount 14 3.5%

    Goals for the redesign: zero duplicate postings, no invoice posted whose lines do not add up to its total, and 75% of invoices posted without a clerk touching them, the rest in a review queue.

    Constraints

    • Fixed: the ERP interface cannot change, and posting is expensive to reverse.
    • Fixed: bank details come from the supplier master, never from an invoice.
    • Fixed: invoice text goes only to providers on the approved list.

    Why the traditional approach fell short

    Approach Where it breaks
    Template extraction Fast and exact for the 20 suppliers that send 60% of the volume; breaks when one changes a layout. The other 400 or so suppliers each have their own layout, and a template per supplier is not affordable
    Rules Match purchase-order numbers but cannot read a line such as "freight surcharge per contract"
    Manual keying 800 clerk hours a month

    Options considered

    Option Verdict
    A. Templates and rules for the top suppliers, manual for the rest (non-AI): covers about 60% of volume at low risk Kept for the top suppliers while the new path proves itself, then reviewed
    B. Model extracts into a strict schema; code validates and posts. The model reads and matches with read-only tools, deterministic code checks the result and makes the single posting call with an idempotency key, and anything doubtful goes to a human queue Accepted
    C. Agent composes ERP calls freely: the model chooses ERP functions and arguments and reads error codes Rejected: this was the pilot design

    B is mostly a workflow with one model step and a short tool loop, by intent: the model decides how to match, code decides whether to post.

    Solution architecture

    Figure 1. Invoice agent components

    Invoice agent componentsEvent bus to Worker; Document store to Worker; Worker to Orchestrator; Orchestrator to Model gateway; Model gateway to LLM provider; Orchestrator to Tool server; Tool server to ERP; Orchestrator to Approval service (doubtful); Orchestrator to Trace storeCOMPANY BOUNDARYLLM provider: approved listLLM providerapproved listModel gatewayModel gatewayTrace storeTrace storeEvent bus: invoice receivedEvent businvoice receivedWorkerWorkerOrchestratorOrchestratorTool server: read, validate, postTool serverread, validate,postERP: existingERPexistingDocument store: invoice filesDocument storeinvoice filesApproval service: clerk queueApprovalserviceclerk queuedoubtful

    How to read this: the model is reached only through the Orchestrator, and the ERP only through the Tool server.

    Figure 2. One invoice, with the validation failure and the ERP timeout

    sequenceDiagram accTitle: Runtime path of one invoice accDescr: The Worker hands an invoice to the Orchestrator. The model matches the purchase order with a read tool and then submits the extracted fields. The Tool server validates them. A failure returns a specific rule to the model for one correction, then the invoice goes to the review queue. A valid invoice is recorded under an idempotency key in the Tool server and posted, and an ERP timeout is resolved by looking the invoice up before any retry. autonumber participant WK as Worker participant OR as Orchestrator participant MG as Model gateway participant TS as Tool server participant ERP as ERP participant AS as Approval service participant TR as Trace store WK->>OR: invoice text and file reference OR->>MG: extract fields, tool definitions with schemas MG-->>OR: call find_po OR->>TS: find_po TS->>ERP: read purchase order ERP-->>TS: order lines TS-->>OR: order lines OR->>MG: tool result MG-->>OR: call submit_invoice with extracted fields OR->>TS: validate fields alt validation fails twice TS-->>OR: failed rule named Note over OR,TS: The first failure returns the rule to the model for one correction OR->>AS: queue for clerk with reasons else valid Note over TS: Record the idempotency key in the Tool server's own store TS->>ERP: post invoice alt ERP times out TS->>ERP: look up supplier and invoice number ERP-->>TS: found or not found Note over TS,ERP: Found means return that document, not found means one more post else ERP replies ERP-->>TS: document number end TS-->>OR: posted document number end OR-)TR: audit event

    How to read this: the first alt block is the validation gate, and the nested block is the timeout rule that prevents a duplicate.

    How AI solved it, step by step

    Step through one invoice, then switch to "Without the fix" to see what the pilot did.

    One invoice (interactive when JavaScript is on)

    As designed

    1. Invoice arrives. An email lands an event on the Event bus. A Worker passes the invoice text to the Orchestrator.
    2. Model gets the tools. The Orchestrator sends the text with three tool definitions: find_supplier, find_po and submit_invoice. The last has the invoice schema: integer minor-unit amounts, ISO dates, a currency code, and each line's quantity and unit price.
    3. Read tools. The model calls find_supplier and find_po. The Tool server answers from the ERP.
    4. Model submits fields. The model calls submit_invoice with the fields it extracted. The Orchestrator does not execute it; it validates first.
    5. Validator checks. The validator checks the schema, that the supplier id is the one find_supplier returned in this run, that line amounts plus tax equal the total exactly, that the lines match the purchase order, and that no invoice from this supplier has this number already.
    6. Failure: one correction. On a failure the model receives the name of the failed rule and gets one correction attempt. A second failure goes to the clerk queue.
    7. Post with a key. On success the Tool server records the idempotency key supplier_id + normalized invoice number in its own store, because the ERP has none, and then posts.
    8. Timeout: look up first. If the ERP times out, the Tool server looks the invoice up before any retry. Found means return that document; not found means one more post.
    9. Audit. The Orchestrator records the outcome and the source link.

    Without the fix

    1. Free ERP calls. The model chooses ERP functions and arguments itself and reads the numeric error codes.
    2. A schema, but no business rules. A total of 1234500 (minor units) is valid against the schema. It is wrong if the invoice says 1,234.50, which is 123450 in minor units: a misread locale shifts the decimal point, which is what happened in the pilot.
    3. Error handling by the model. The model fixed an error by changing data: in the pilot it swapped a supplier id.
    4. Timeout after commit. The ERP committed, then timed out, and the retry posted again.
    5. Pilot result. Of 400 invoices, 9 were posted twice and 14 with a wrong amount.

    Under the hood

    The key step is the function-calling round trip. Anthropic's tool-use documentation (as of 2026-10-21) describes it:

    1. The request carries tool definitions with a name, a description and an input_schema.
    2. The model replies with stop_reason: "tool_use" and one or more tool_use blocks. For client tools, the model does not execute anything.
    3. The application runs the operation and sends a tool_result block back with the matching tool_use_id.

    The documentation also notes that for a missing required parameter some models may infer a value instead of asking, and that strict: true makes calls match the schema exactly. The MCP specification's tools page states that servers MUST validate all tool inputs.

    A schema guarantees shape, never truth, so the tool_use input is treated like a form post from an untrusted client and validated by code that knows the business rules. See the lesson's function-calling section.

    What went wrong / failure modes

    Failure Mitigation
    Timeout after commit: the ERP committed, then timed out, and the retry posted again Look up by supplier and invoice number before any retry; treat the pair as the idempotency key
    The model "fixes" an error by changing data (in the pilot it swapped a supplier id) The supplier id must equal one returned by find_supplier; error messages name the rule, not a value to use
    Ambiguous values: "03/04/2026" can be two dates ISO dates in the schema; ambiguity with no supplier locale goes to the queue
    Injected text such as new bank details Bank details come only from the supplier master
    Opaque ERP codes The Tool server maps known codes to a short set; an unknown code goes to the queue, never to a retry
    Layout drift lowers accuracy silently A monthly run over a golden set of 100 invoices and a 5% audit sample

    Results

    These are illustrative targets, not measurements.

    Measure Calculation Value
    Effort today 8,000 x 6 min 48,000 min = 800 hours
    Posted automatically (75%) 8,000 x 0.75 6,000
    Clerk queue 2,000 x 6 min 12,000 min
    5% audit of posted invoices 300 x 2 min 600 min
    Effort after 12,000 + 600 12,600 min = 210 hours
    Saved 800 - 210 590 hours, about 74%
    Duplicate postings; postings where lines plus tax differ from the total Target 0; 0

    Tradeoffs and when NOT to use this approach

    • A strict validator sends more invoices to clerks at first; tune it with the audit sample.
    • Do not automate posting where errors are costly to reverse and no validation catches them.
    • Route on the validator's checks, not on a model's own confidence score.

    Design rules extracted

    1. Validate every tool input in code against business rules, in addition to the schema.
    2. Give the posting tool an idempotency key based on a business key, and look up before retrying.
    3. Return errors that name the rule, so the model corrects the extraction and not the data.
    4. Take values such as bank details only from systems of record.
    5. Send doubtful items to a human queue and audit a sample of the rest.

    Assumptions

    • All numbers are chosen for illustration. Pilot: 400 invoices, 9 duplicates, 14 wrong amounts; average invoice 2,400 currency units.
    • Volume: 8,000 invoices a month at 6 clerk minutes each. The top 20 suppliers send 60% of volume.
    • Target: 75% auto-posted, the rest queued at 6 minutes each, and a 5% audit of the posted invoices at 2 minutes each. The arithmetic is in Results; 590 / 800 = 73.75%.
    • The golden set of 100, the 5% audit rate and the one-correction limit are illustrative choices.
    • The distributor, its ERP and its suppliers are invented.

    Last verified: 2026-10-22

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments