Technical

AI Agents for Accounts Payable: Bill Reading, 3-Way Match, Approval

How to build an accounts payable AI agent that reads vendor bills, matches them to purchase orders and receipts, flags mismatches, and leaves posting to a person, with examples for Odoo and ERPNext.

Kalvyai Engineering · · 7 min read

AI Agents for Accounts Payable: Bill Reading, 3-Way Match, Approval (cover)
On this page

Accounts payable is a good fit for an AI agent. The work is repetitive, the inputs are messy (PDFs, scans, email attachments, phone photos), and the rules for checking a bill are mostly clear. It is also a risky place to automate badly. A wrong posting means wrong payables, wrong tax and possibly a payment to the wrong party.

This post describes how we design AP agents that do the reading and checking, and stop before anything reaches the ledger. The examples use Odoo and ERPNext, but the pattern applies to any ERP.

What the agent does, and what it does not do

The agent's job is narrow:

  1. Read an incoming vendor bill and turn it into structured data.
  2. Find the vendor, the purchase order and the receipt it belongs to.
  3. Compare bill, PO and receipt line by line (the three-way match).
  4. Create a draft bill in the ERP with any problems clearly flagged.
  5. Hand it to a person, who approves and posts it, or sends it back.

The agent does not post bills, does not register payments and does not edit purchase orders or receipts. Those limits are enforced through ERP permissions, not just instructions in a prompt.

Stage 1: Reading the bill

Vendor bills arrive in many forms: text PDFs, scanned PDFs, images, and sometimes structured e-invoices. The agent's first step is extraction into a fixed schema. Fixing the schema matters more than which model you use, because every later step depends on it.

A typical extraction result looks like this:

JSON
{
  "vendor_name": "Acme Packaging Pvt Ltd",
  "vendor_tax_id": "[as printed on bill]",
  "bill_number": "INV-20931",
  "bill_date": "2024-05-14",
  "po_reference": "P00412",
  "currency": "INR",
  "lines": [
    {"description": "Corrugated box 12x12", "vendor_sku": "CB-1212", "qty": 500, "unit_price": 18.5, "tax_rate": 18},
    {"description": "Packing tape 48mm", "vendor_sku": "PT-48", "qty": 120, "unit_price": 42.0, "tax_rate": 18}
  ],
  "subtotal": 14290.0,
  "tax_total": 2572.2,
  "total": 16862.2,
  "field_confidence": {"po_reference": 0.62, "bill_number": 0.97, "total": 0.99}
}

A few rules we apply at this stage:

  • Keep the source file attached to whatever the agent creates. The reviewer must be able to see the original next to the extracted values.
  • Check the arithmetic. Line totals should add up to the subtotal, and subtotal plus tax should equal the total. If they don't, either the extraction is wrong or the bill is. Both need a human.
  • Record confidence per field. A low-confidence PO reference is a reason to search more carefully, not a reason to guess.
  • Never fill a missing field with a plausible value. If the bill has no PO number, the field stays empty.

If you run Odoo, our Kalvyai Document Scanner covers this stage: it scans vendor bills, customer orders and invoices into verified Odoo drafts.

Stage 2: Finding the vendor, PO and receipt

Matching starts with the vendor. Match on tax ID first, then on a known vendor bill email address or an exact name, and only then on fuzzy name matching, which should always be flagged for review. Two vendors with similar names is a common source of misposted bills.

Next, find the purchase order:

  1. If the bill carries a PO reference, look it up for that vendor only.
  2. If not, search open POs for that vendor where products and quantities overlap with the bill lines.
  3. If more than one PO could fit, do not pick one. Flag it as ambiguous and list the candidates.

In Odoo, the PO lines already carry what the match needs. Here is a read using the external API:

Python
import xmlrpc.client

models = xmlrpc.client.ServerProxy(f"{URL}/xmlrpc/2/object")

po_lines = models.execute_kw(
    DB, UID, API_KEY,
    "purchase.order.line", "search_read",
    [[("order_id.name", "=", "P00412"),
      ("order_id.partner_id", "=", vendor_id)]],
    {"fields": ["id", "product_id", "product_qty", "qty_received",
                "qty_invoiced", "price_unit", "taxes_id"]},
)

In ERPNext the equivalent data sits on Purchase Order Item (qty, received_qty, rate, billed_amt), with receipt detail on Purchase Receipt Item. The agent can read these through the REST API with a user that has read access only to the purchasing doctypes it needs.

Product matching between bill lines and PO lines is often the hardest part. Vendors use their own SKUs and descriptions. Store the vendor's product code against your product where your ERP supports it (in Odoo, the vendor pricelist on the product; in ERPNext, the Supplier Part Number in the item's Supplier Items table). Every confirmed match by a reviewer can be saved so the next bill matches without guessing.

Stage 3: The three-way match

The three-way match compares three numbers per line:

  • Ordered quantity and price on the PO
  • Received quantity on the receipt
  • Billed quantity and price on the vendor bill

You can only pay for what you ordered and received, minus what has already been billed. Here is the core check:

Python
from dataclasses import dataclass

# Tolerances are a finance decision, not an engineering one.
PRICE_TOLERANCE_PCT = 0.0   # set this with your finance team
QTY_TOLERANCE = 0.0

@dataclass
class LineInput:
    po_line_id: int
    ordered_qty: float
    received_qty: float
    already_billed_qty: float
    po_price: float
    bill_qty: float
    bill_price: float

def check_line(c: LineInput) -> list[str]:
    flags = []
    open_to_bill = c.received_qty - c.already_billed_qty

    if c.received_qty == 0:
        flags.append("not_received: nothing received on this PO line yet")
    elif c.bill_qty > open_to_bill + QTY_TOLERANCE:
        flags.append(f"qty_over_received: billed {c.bill_qty}, open to bill {open_to_bill}")

    if c.bill_qty > c.ordered_qty - c.already_billed_qty + QTY_TOLERANCE:
        flags.append("qty_over_ordered")

    if c.po_price:
        diff_pct = abs(c.bill_price - c.po_price) / c.po_price * 100
        if diff_pct > PRICE_TOLERANCE_PCT:
            flags.append(f"price_variance: {diff_pct:.2f}% vs PO price {c.po_price}")

    return flags

This logic is deliberately plain code, not a model call. The model reads documents and suggests matches; deterministic code decides whether numbers agree. That makes the check repeatable and easy to test.

One Odoo detail to respect: products have a control policy that decides whether bills are based on ordered or received quantities (purchase_method on the product). If some of your products bill on ordered quantities, the agent should apply the same rule instead of always requiring a receipt.

Stage 4: Flagging mismatches

Most bills will match. The value of the agent is in how clearly it explains the ones that don't. We group flags into categories so reviewers can sort and filter:

Flag

Typical cause

Who usually resolves it

price_variance

Price change not updated on PO

Purchasing

qty_over_received

Bill sent before goods arrived, or short delivery

Warehouse / Purchasing

not_received

Receipt not validated in the ERP

Warehouse

no_po_found

Service bill, or PO number missing

AP

ambiguous_po

Several open POs fit

AP

possible_duplicate

Same vendor and bill number already exists

AP

tax_mismatch

Tax rate on bill differs from PO line taxes

Accounts

arithmetic_error

Totals don't add up

AP, often back to vendor

The duplicate check deserves special attention. Search existing bills, in draft and posted states, for the same vendor and the same vendor bill number. Also check same vendor, same total and close dates, because vendors sometimes resend a bill with a new number.

Each flag should be written in plain language on the draft bill, with the numbers that triggered it. "Price 19.20 vs PO 18.50 (+3.78%) on line 1" is useful. "Mismatch detected" is not.

Stage 5: Draft only, with a person approving

The agent creates the bill as a draft and stops. In Odoo that means an account.move with move_type set to in_invoice, left in draft, with each line linked to its PO line:

Python
bill_id = models.execute_kw(DB, UID, API_KEY, "account.move", "create", [{
    "move_type": "in_invoice",
    "partner_id": vendor_id,
    "ref": "INV-20931",
    "invoice_date": "2024-05-14",
    "invoice_line_ids": [(0, 0, {
        "purchase_line_id": po_line_id,
        "product_id": product_id,
        "quantity": 500,
        "price_unit": 18.5,
    })],
}])

models.execute_kw(DB, UID, API_KEY, "account.move", "message_post", [[bill_id]], {
    "body": "AI check: 1 flag. price_variance on line 1: 19.20 vs PO 18.50 (+3.78%).",
})

In ERPNext, the agent creates a Purchase Invoice with docstatus 0 (draft), with purchase_order, po_detail, purchase_receipt and pr_detail set on each item so the link to the source documents is kept.

The important part is permissions. Do not rely on the agent "choosing" not to post:

  • Odoo: give the agent's user only the access needed to create draft vendor bills and read purchasing data.
  • ERPNext: create a dedicated role with Create and Write on Purchase Invoice but without Submit. Submit is what posts the document to the ledger.

Your existing approval rules then apply as normal. A reviewer opens the draft, sees the original document, the extracted values and the flags, and either posts it, corrects it or rejects it.

Budgets and the audit trail

Two controls make the agent safe to leave running.

A hard spending cap on model usage. Bill volume can spike at month-end, and a retry loop on a bad file can burn through tokens. Set a monthly limit that stops calls when reached, rather than an alert you might miss. Our AI Base apps for Odoo and ERPNext let you plug any AI model into the ERP with a hard monthly cap.

A log of every agent action. For each bill, record:

  • the source file and when it was received
  • the extracted data and confidence scores
  • which PO and receipt were matched, and why
  • every flag raised
  • the model used
  • who approved or rejected the draft, and when

Keeping this on the document itself (chatter in Odoo, comments and version history in ERPNext) means auditors don't need a separate system to follow what happened.

A practical rollout plan

  1. Pick one vendor group. Start with vendors who send clean PDFs and always quote a PO number.
  2. Run in shadow mode. Let the agent extract and match, but store results outside the ERP. Compare them to what your AP team actually posted.
  3. Agree tolerances with finance. Write down price and quantity tolerances before switching on draft creation.
  4. Switch on draft creation for that vendor group, with posting still fully manual.
  5. Measure. Track how many drafts were posted unchanged, how many needed edits, and which flags were false alarms.
  6. Expand to more vendors and document types once the edit rate is acceptable to your team.

Common pitfalls

  • Receipts not validated on time. If the warehouse validates receipts days late, every bill looks like not_received. Fix the process first, or the agent will just produce noise.
  • Letting the model decide numbers. Use the model for reading and suggesting; use code for comparisons.
  • Silent auto-correction. If the agent "fixes" a price to match the PO, you lose the evidence of a vendor overcharge. Flag, don't fix.
  • Shared credentials. The agent needs its own user so its actions are distinguishable in the audit trail.

How Kalvyai can help

We build and connect Odoo, ERPNext and Shopify systems, and we add AI agents that work inside them with human approvals, budgets and an audit trail. Accounts payable agents like the one above are a typical project: document reading, PO and receipt matching, clear flags and a permission setup that keeps posting with your team. You can read more about our agent work at kalvyai.com/ai-agents, and browse our ready-made apps at store.kalvyai.com.

If you want to talk through your AP process, contact us.

Share this article

  • accounts payable
  • AI agents
  • three-way match
  • Odoo
  • ERPNext
  • vendor bills
  • approvals

Kalvyai Engineering · Engineering team

The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.

Comments

No comments yet. Questions and corrections are welcome.

Rate this post or leave a comment

Your rating (optional)
Not rated

Comments appear after an editor approves them. See our privacy notice.

Read next

AI Bank Reconciliation: Suggested Matches a Person Confirms (cover)Technical
Kalvyai EngineeringAI agents

AI Bank Reconciliation: Suggested Matches a Person Confirms

How an AI matcher suggests bank reconciliation matches from descriptions and amounts, explains each one, sorts them by confidence, and leaves the final confirmation to a person.

7 min read

Claude Tool Use for ERP Tasks: Safe Read and Write Actions (cover)Technical
Kalvyai EngineeringAI agents

Claude Tool Use for ERP Tasks: Safe Read and Write Actions

How to give Claude function calling access to your ERP without giving it the keys: narrow tools, argument validation in code, approval gates for writes, and a log entry for every call. Includes a Python example against Odoo.

6 min read

AI Agent Audit Trail: What to Log and How Long to Keep It (cover)Technical
Kalvyai EngineeringAI agents

AI Agent Audit Trail: What to Log and How Long to Keep It

A practical design for audit trails of AI agents in ERP and commerce systems: which events to record, how to store them so they can't be quietly changed, how long to keep them, and how to use them to investigate an incident.

8 min read

Newsletter

Get new guides in your inbox.

Practical notes on Odoo, ERPNext, Shopify and AI agents, written by the engineers who build them. No spam, and you can ask to stop at any time.

Prefer a feed? Subscribe by RSS. We use your email only to send new articles. See our privacy policy.