← Blog
Corporate financeAutomation

A language model can propose invoice matches. Only a person should post them.

A receivables matcher in Python where rules clear most bank lines and a model proposes the rest, with evidence, for a person to approve.

Hakob Nahapetyan · 2026-10-28 · 11 min

Matching bank lines to invoices has right answers. A payment either settles INV-10049 or it does not, which is a job for rules. The model belongs on the tail where rules run out. There it only proposes.

This guide builds a receivables matcher in Python: four rule stages, a model that proposes with evidence, a review queue and an audit log that doubles as an eval set.

The data is synthetic

All numbers here come from synthetic data I generated with a seeded script: 190 invoices for 16 customers (3 invoiced in EUR) and 172 GBP bank lines, plus the right answer for each line so the matcher can be scored. No real company's data is in it.

Mess Example
Swapped digits INV-10047 paid as INV-10407
No reference JUNIPER HEAL PYMT 84569145
Odd formats INV10161, RECHNUNG 10022
Bank fee deducted 10, 15 or 25 short
FX rounding EUR invoice paid up to 0.7% off the booking rate
Split payments 30% or 50%, then the rest
One payment, several invoices REMITTANCE JUL for 2 or 3 invoices
Payer name differs NORTHWIND GRP HOLDINGS paying Northwind Trading Ltd
Not a receipt interest, VAT repayment, supplier refund

The order of the stages

Stage Auto-matches when Cleared in my run Left
1 Reference an open invoice number is in the reference and the amount fits 95 77
2 Amount and date one open invoice has exactly that amount inside the date window 27 50
3 Fuzzy name payer scores 0.90 or more against one customer, one invoice fits 12 38
4 Partial and group reference and payer agree on a part payment, or one subset of up to 4 invoices fits 27 11
5 Model never: it proposes into the review queue 0 posted 11 queued

Each stage sees only what earlier stages left and refuses to match when more than one answer fits. Ambiguity moves down the line and never reaches the ledger.

Bars for each stage: reference clears 95 of 172, amount and date 27 of 77, fuzzy name 12 of 50, partial and group 27 of 38, and the model posts none and queues 11

Counts from the run on the synthetic data. Each bar is the lines a stage saw, split into what it cleared and what it left.

The rules, in full

import csv, re, unicodedata
from datetime import date, timedelta
from decimal import Decimal
from difflib import SequenceMatcher
from itertools import combinations

FEE_MAX = Decimal("30.00")    # bank charges we write off without a person
FX_TOL = Decimal("0.01")      # 1% band, only for invoices raised in another currency
NAME_MIN = 0.90               # fuzzy name threshold: tight on purpose
LATE_DAYS = 45                # a payment may land this long after the due date
MAX_CANDIDATES, MAX_GROUP = 12, 4   # limits for the subset search

def load():
    inv = {}
    for r in csv.DictReader(open("invoices.csv")):
        r["open"] = Decimal(r["amount_gbp"])
        r["issue_date"], r["due_date"] = date.fromisoformat(r["issue_date"]), date.fromisoformat(r["due_date"])
        inv[r["invoice_id"]] = r
    bank = []
    for r in csv.DictReader(open("bank.csv")):
        r["amount"], r["date"] = Decimal(r["amount"]), date.fromisoformat(r["date"])
        bank.append(r)
    return inv, sorted(bank, key=lambda b: b["date"])

def norm_name(s):
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().upper()
    s = s.replace(".", "").replace("&", " AND ")
    s = re.sub(r"[^A-Z ]", " ", s)
    s = re.sub(r"\b(LTD|LIMITED|PLC|LLP|GMBH|BV|SA|STE|SOCIETE|INC|PAYMENTS?)\b", " ", s)
    return " ".join(s.split())

def name_score(a, b):
    return SequenceMatcher(None, norm_name(a), norm_name(b)).ratio()

def amount_fit(paid, due, foreign):
    diff = due - paid
    if abs(diff) <= Decimal("0.01"):
        return "exact"
    if Decimal(0) < diff <= FEE_MAX:
        return "fee"
    if foreign and abs(diff) <= due * FX_TOL:
        return "fx"
    return None

def refs_in(text, inv):
    ids = {f"INV-{d}" for d in re.findall(r"(?<!\d)(\d{5})(?!\d)", text)}
    return [i for i in sorted(ids) if i in inv and inv[i]["open"] > 0]

def fit_group(b, group):
    total = sum(g["open"] for g in group)
    return amount_fit(b["amount"], total, all(g["currency"] != "GBP" for g in group))

def open_for(inv, b, customer=None):
    return [i for i in inv.values() if i["open"] > 0 and i["issue_date"] <= b["date"]
            <= i["due_date"] + timedelta(days=LATE_DAYS) and (customer is None or i["customer"] == customer)]

def best_customer(b, inv):
    names = {i["customer"] for i in inv.values()}
    score, name = max((name_score(b["counterparty"], n), n) for n in names)
    return name if score >= NAME_MIN else None

# ---- the stages: each returns (invoice_ids, fit) or None ----
def s1_reference(b, inv):
    ids = refs_in(b["reference"], inv)
    fit = ids and fit_group(b, [inv[i] for i in ids])
    return (ids, fit) if fit else None

def s2_amount_date(b, inv):
    # exact amount only: with no name or reference, a fee band lets the wrong invoice in
    hits = [i for i in open_for(inv, b) if amount_fit(b["amount"], i["open"], False) == "exact"]
    return ([hits[0]["invoice_id"]], "exact") if len(hits) == 1 else None

def s3_name(b, inv):
    cust = best_customer(b, inv)
    if not cust:
        return None
    hits = [i for i in open_for(inv, b, cust) if fit_group(b, [i])]
    return ([hits[0]["invoice_id"]], fit_group(b, hits)) if len(hits) == 1 else None

def s4_partial_or_group(b, inv):
    cust = best_customer(b, inv)
    if not cust:
        return None
    ids = refs_in(b["reference"], inv)
    if len(ids) == 1 and inv[ids[0]]["customer"] == cust:
        i = inv[ids[0]]
        if fit_group(b, [i]):
            return ids, fit_group(b, [i])          # the last part of a split payment
        if b["amount"] < i["open"]:
            return ids, "partial"
    pool = sorted(open_for(inv, b, cust), key=lambda i: i["issue_date"])[:MAX_CANDIDATES]
    found = [c for k in range(1, MAX_GROUP + 1) for c in combinations(pool, k) if fit_group(b, c)]
    if len(found) == 1:                            # two subsets fit (a single counts): a person decides
        return [g["invoice_id"] for g in found[0]], fit_group(b, found[0])
    return None

def apply(b, ids, fit, inv):
    if fit == "partial":
        inv[ids[0]]["open"] -= b["amount"]
    else:
        for i in ids:
            inv[i]["open"] = Decimal(0)

def run_rules(inv, bank):
    matched, left = [], bank
    for name, stage in [("1 reference", s1_reference), ("2 amount+date", s2_amount_date),
                        ("3 fuzzy name", s3_name), ("4 partial/group", s4_partial_or_group)]:
        still = []
        for b in left:
            m = stage(b, inv)
            if m:
                apply(b, *m, inv)
                matched.append({"bank_id": b["bank_id"], "invoice_ids": m[0], "fit": m[1], "stage": name})
            else:
                still.append(b)
        print(f"stage {name:16} cleared {len(left) - len(still):3}   left {len(still)}")
        left = still
    return matched, left

amount_fit is accounting policy. A shortfall up to 30.00 counts as a bank charge and an overpayment never does. The 1% FX band applies only to foreign currency invoices. Whoever owns the ledger signs these numbers off.

A reference alone is never enough: a swapped digit can land on another customer's real invoice, so stage 1 also requires the amount to fit.

A mistake the scoring caught

My first version let stage 2 use the fee band. It cleared 34 lines and 5 went to the wrong invoice: with no reference and no name, a 30.00 band lets another invoice fit. With exact amounts only it cleared 27 with none wrong. Stage 3 then matched the fee-deducted lines by name. Score every rule change against a labelled set before it touches real books.

Stage 5: the model proposes, with evidence

Code builds the candidates and computes the evidence. The model picks a candidate key or NONE. Code checks the key exists. A made-up key becomes "no proposal".

import json, re
from datetime import datetime, timezone
from itertools import combinations
from match import name_score, refs_in, fit_group, amount_fit

MODEL, PROMPT_VERSION = "claude-haiku-5-5", "propose-v1"

def mask(text):
    return re.sub(r"\d{6,}", lambda m: "****" + m[0][-4:], text)   # account numbers keep last 4

def candidates(b, inv, k=5):
    """Evidence is computed here, in code. The model reads it; it does not invent it."""
    live = [i for i in inv.values() if i["open"] > 0 and i["issue_date"] <= b["date"]]
    refs = set(refs_in(b["reference"], inv))
    def score(i):
        return name_score(b["counterparty"], i["customer"]) + (1 if i["invoice_id"] in refs else 0)
    singles = [[i] for i in sorted(live, key=score, reverse=True)[:k]]
    top = singles[0][0]["customer"] if singles else None
    pool = sorted((i for i in live if i["customer"] == top), key=lambda i: i["issue_date"])[:12]
    groups = [list(c) for n in (2, 3, 4) for c in combinations(pool, n) if fit_group(b, c)][:3]
    out = []
    for n, group in enumerate(singles + groups, 1):
        total = sum(g["open"] for g in group)
        out.append({"key": f"C{n}", "invoice_ids": [g["invoice_id"] for g in group],
                    "customer": group[0]["customer"], "open_total": str(total),
                    "difference": str(total - b["amount"]),
                    "amount_fit": fit_group(b, group) or ("short" if b["amount"] < total else "over"),
                    "name_score": round(name_score(b["counterparty"], group[0]["customer"]), 2),
                    "reference_names_it": any(g["invoice_id"] in refs for g in group),
                    "days_since_issue": (b["date"] - max(g["issue_date"] for g in group)).days})
    return out

TOOL = {"name": "propose_match", "description": "Propose one candidate for this bank line, or none.",
        "input_schema": {"type": "object", "properties": {
            "candidate": {"type": "string", "description": "a candidate key such as C2, or NONE"},
            "confidence": {"type": "number", "minimum": 0, "maximum": 1},
            "reason": {"type": "string", "description": "one or two sentences citing the evidence"}},
            "required": ["candidate", "confidence", "reason"]}}

PROMPT = ("You help an accounts receivable clerk. You PROPOSE a match; a person decides and posts. "
          "Pick the candidate the evidence supports, or NONE if no candidate is a payment of that invoice "
          "(interest, tax refunds, loans and supplier refunds are NONE). "
          "Partial payments are allowed when the reference names the invoice.\n\n")

def propose(client, b, inv):
    cands = candidates(b, inv)
    line = {"date": b["date"].isoformat(), "amount": str(b["amount"]),
            "counterparty": b["counterparty"], "reference": mask(b["reference"])}
    resp = client.messages.create(
        model=MODEL, max_tokens=500, tools=[TOOL], tool_choice={"type": "tool", "name": "propose_match"},
        messages=[{"role": "user", "content": PROMPT + json.dumps({"bank_line": line, "candidates": cands})}])
    out = next(c for c in resp.content if c.type == "tool_use").input
    keys = {c["key"]: c for c in cands}
    pick = keys.get(out["candidate"])              # unknown key -> treated as no proposal
    return {"bank_line": {"bank_id": b["bank_id"], **line}, "candidates": cands,
            "proposal": pick["invoice_ids"] if pick else [], "confidence": out["confidence"],
            "reason": out["reason"], "model": MODEL, "prompt_version": PROMPT_VERSION}

What leaves your machine: one bank line (runs of six or more digits masked to the last four) plus up to eight candidates with customer name, open amount and scores. If customer names cannot go to an outside API, use a local open-weights model. propose only calls messages.create, so nothing else changes.

I ran this without an API key. A stub client returns the real tool_use shape, with picks from a fixed rule. Every proposal below is stub output, shown only as an example of the format.

The review queue

The first item from the run. Candidates and evidence come from code, the proposal line from the stub.

2026-07-19     2412.32  NORTHWIND GRP HOLDINGS  "PART INV-10049"

-> C1  INV-10049                      Northwind Trading Ltd  open   4824.65  diff   2412.33  short   name 0.77  ref yes
   C2  INV-10076                      Northwind Trading Ltd  open   8098.84  diff   5686.52  short   name 0.77  ref no
   C3  INV-10084                      Northwind Trading Ltd  open   7582.73  diff   5170.41  short   name 0.77  ref no
   C4  INV-10132                      Northwind Trading Ltd  open   3255.22  diff    842.90  short   name 0.77  ref no
   C5  INV-10031                      Greyfield Hotels plc   open   2647.22  diff    234.90  short   name 0.37  ref no

proposal: INV-10049  (0.80)  Reference names this invoice; payer name differs.
[a] accept   [r] reject   [1-9] pick another candidate
  • One action per item: a accepts, r rejects, a number picks another candidate.
  • Evidence sits in columns. The model's reason is one line underneath, because it is the least checked thing on screen.
  • Nothing posts from the queue. decide logs the decision and returns the ids to post. Recheck they are still open: two queued Northwind lines here point at one invoice.

A review queue item for bank line B0110: six candidate invoices with evidence columns, a proposed group of three invoices and buttons to accept, reject or pick another

Another queued line from the run, B0110, a payment for three Acme invoices. Candidates and evidence come from code. The proposal and its reason come from the stub client and are an example of the format.

def decide(item, action, reviewer, log_path="audit.jsonl"):
    """The only way a proposal becomes a posting. One action per item, every decision logged."""
    if action == "a":
        final = item["proposal"]
    elif action == "r":
        final = []
    else:
        final = item["candidates"][int(action) - 1]["invoice_ids"]
    record = {**item, "action": action, "final_invoice_ids": final, "reviewer": reviewer,
              "decided_at": datetime.now(timezone.utc).isoformat()}
    with open(log_path, "a") as f:
        f.write(json.dumps(record) + "\n")
    return final

The audit log is also the eval set

Each line in audit.jsonl holds the bank line, candidates with evidence, proposal, confidence, model id, prompt version, reviewer action, final invoice ids, reviewer and timestamp. Why did B0010 go to INV-10049? One line answers that.

The same file is your eval set. Before switching prompt or model, replay the logged items and compare the new picks with the human decisions.

What the run cleared

Rules cleared 161 of 172 lines (93.6%), none wrong against the synthetic answers. Stage 4 handled 13 multi-invoice payments and both halves of 7 split payments. The 11 left: 4 lines that belong to no invoice, 4 Northwind lines with a name score of 0.77, 2 group payments that included invoices past the 45-day late window and 1 where two subsets fit.

A test script played the reviewer from the synthetic answers and accepted all 11 stub proposals. That checks the queue and the log. It tells you nothing about real model accuracy. Measure that on your own logged decisions.

Run it yourself

run.py is 17 lines of glue: load, run_rules, propose on each line left, write review_queue.jsonl. With --fake it uses a stub whose messages.create returns a tool_use block.

python3 -m venv venv && . venv/bin/activate
pip install anthropic
python run.py --fake          # rules plus the stub client, no key needed
export ANTHROPIC_API_KEY=your-key
python run.py                 # the real model proposes

Inputs are invoices.csv (invoice_id, customer, currency, amount_gbp, issue_date, due_date) and bank.csv (bank_id, date, amount, counterparty, reference).

If your finance team wants this built on its own ledger and bank data, write to me.

Have finance work that eats hours?

Tell me how it is done today and who does it. I will say whether automation is the right fix.

Get in touch

More from the blog