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

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:
- Read an incoming vendor bill and turn it into structured data.
- Find the vendor, the purchase order and the receipt it belongs to.
- Compare bill, PO and receipt line by line (the three-way match).
- Create a draft bill in the ERP with any problems clearly flagged.
- 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:
{
"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:
- If the bill carries a PO reference, look it up for that vendor only.
- If not, search open POs for that vendor where products and quantities overlap with the bill lines.
- 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:
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:
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 flagsThis 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 change not updated on PO | Purchasing |
| Bill sent before goods arrived, or short delivery | Warehouse / Purchasing |
| Receipt not validated in the ERP | Warehouse |
| Service bill, or PO number missing | AP |
| Several open POs fit | AP |
| Same vendor and bill number already exists | AP |
| Tax rate on bill differs from PO line taxes | Accounts |
| 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:
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
- Pick one vendor group. Start with vendors who send clean PDFs and always quote a PO number.
- 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.
- Agree tolerances with finance. Write down price and quantity tolerances before switching on draft creation.
- Switch on draft creation for that vendor group, with posting still fully manual.
- Measure. Track how many drafts were posted unchanged, how many needed edits, and which flags were false alarms.
- 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.
- 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