Building an AI agent accounts receivable collections workflow is less about fancy models and more about reliable orchestration around messy ERP data. The goal is to automate dunning, payment reminders, and dispute handling without breaking compliance or annoying customers.
1. Map the AR process before writing code
Pull a real aging report and trace what a collector does today. Invoices move through states: draft, open, overdue, disputed, paid, written off. Each state triggers different actions—reminder email, phone call, legal notice. If you skip this mapping, you will encode assumptions that conflict with finance policy.
Define the dunning sequence explicitly:
- d+0: invoice issued
- d+1: courtesy confirmation
- d+7: first overdue reminder
- d+14: second reminder with amount due and link
- d+30: escalate to human or external collections agency
Document the data sources: ERP (NetSuite, SAP, Dynamics), payment gateway (Stripe, Adyen), CRM for contact preferences. Check legal constraints up front. TCPA restricts auto-dialing; GDPR limits personal data in prompts; some jurisdictions forbid certain language in dunning notices. An AI agent accounts receivable collections system that ignores these will create liability, not savings.
2. Choose a model routing strategy
Don’t send every task to a frontier model. Classify intent with a 7B-class model, generate customer-facing text with a larger one. When building an AI agent accounts receivable collections pipeline, use an OpenAI-compatible gateway so you aren’t locked to one provider. n4n.ai exposes one such endpoint with 240+ models and automatic fallback when a provider is degraded, so a single base_url covers routing needs without custom retry logic.
from openai import OpenAI
client = OpenAI(
base_url="https://api.n4n.ai/v1",
api_key="sk-...",
)
def classify_intent(text: str) -> str:
resp = client.chat.completions.create(
model="mistralai/mistral-7b-instruct",
messages=[{"role": "user", "content": text}],
temperature=0,
)
return resp.choices[0].message.content.strip()
For long-form apology or negotiation emails, switch to openai/gpt-4o-mini or similar. The gateway forwards cache-control hints, so repeated invoice contexts can hit provider caches and cut latency. Keep a config map of task → model so you can swap without code changes.
3. Build the agent loop with structured tools
The agent needs callable tools, not free text. Define a JSON schema for each action:
{
"name": "send_reminder",
"description": "Send a dunning email for an overdue invoice",
"parameters": {
"type": "object",
"properties": {
"invoice_id": {"type": "string"},
"tone": {"type": "string", "enum": ["firm", "friendly"]}
},
"required": ["invoice_id", "tone"]
}
}
Then run a bounded loop:
messages = [{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Invoice INV-102 is 9 days overdue"}]
for _ in range(5):
resp = client.chat.completions.create(
model="anthropic/claude-3.5-haiku",
messages=messages,
tools=[SEND_REMINDER_SCHEMA],
)
msg = resp.choices[0].message
if not msg.tool_calls:
break
for call in msg.tool_calls:
result = execute_tool(call.function.name, call.function.arguments)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
Keep the loop bounded—max 5 iterations—to avoid runaway costs. Each tool result must be serializable and small; never return a full ERP customer object, just the fields the model needs.
4. Prompt design for collections scenarios
The prompt for an AI agent accounts receivable collections must constrain tone and forbid invented facts:
You are an AR collections assistant. Use only data from provided tools.
Tone: professional, empathetic, never threatening.
If invoice is disputed, do not request payment; open a dispute task.
Never generate payment links; use the link from get_invoice.
Few-shot examples reduce errors. Show a late-payment reminder vs a dispute acknowledgment. A common pitfall is letting the model improvise a settlement discount—that changes revenue recognition. Keep discounts behind a separate approved tool.
Tradeoff: longer prompts cost tokens per call. Use cached context via the gateway’s cache-control to avoid resending the static policy block on every loop turn.
5. Integrate with ERP and payment systems
Read invoice status through a read-only service account. Write actions (send email, create task) through a queue that an idempotent worker processes.
def get_invoice(invoice_id: str) -> dict:
r = requests.get(f"https://erp.internal/api/invoices/{invoice_id}",
headers={"Authorization": "Bearer ERP_TOKEN"}, timeout=5)
r.raise_for_status()
return r.json()
Wrap external calls with timeouts and circuit breakers. ERP APIs are slow and flaky; a 30-second hang will stall your agent loop. Tradeoff: strong consistency vs availability. If the ERP is down, the agent should pause, not guess invoice status.
Payment gateways often have separate auth and rate limits. Use a dedicated token with minimal scopes. Log the gateway response codes to distinguish “customer paid” from “gateway error”.
6. Handle failures, retries, and human escalation
SMTP outages happen. Use idempotency keys on send_reminder so a retry doesn’t spam the customer.
def execute_tool(name, args):
if name == "send_reminder":
key = f"rem-{args['invoice_id']}-{args['tone']}"
if redis.exists(key):
return "already sent"
# send email via transactional provider
redis.setex(key, 86400, "1")
return "sent"
If the model returns low-confidence or the tool errors twice, push to a human queue:
if tool_error_count > 1:
create_human_task(invoice_id, "agent failed")
Deploying an AI agent accounts receivable collections loop without a human fallback is reckless. Automatic model fallback helps with provider errors, but business failures (wrong amount, angry customer) need a person.
7. Observability and evaluation
Log every completion: model used, tokens, latency, tool calls. Per-token metering from the gateway gives cost attribution per customer segment, so you can see if enterprise accounts burn 10x the inference budget.
Build an eval set from 100 historical collector interactions. Score the agent on:
- Correct state detection (overdue vs disputed)
- Appropriate channel (email vs escalate)
- No fabricated amounts or links
Measure false escalation rate; too high means you trained the model to be timid and humans drown in trivial tasks. Track time-to-first-contact versus the manual baseline.
8. Common pitfalls and tradeoffs
Over-automation burns customer trust. A wrong amount email triggers disputes that cost more than the late payment. Keep a shadow mode for two weeks: agent suggests, human approves, then compare outcomes.
Model drift is real. ERP schema changes break your tool parsing. Add a weekly regression test against recorded inputs. If a field rename hits get_invoice, the agent should fail safe, not hallucinate.
Cost vs latency: a 7B model classifies in ~200ms at pennies; a frontier model takes 2s. Route deliberately. An AI agent accounts receivable collections system is a distributed systems problem wearing an ML mask. Get the orchestration, tools, and guardrails right, and the models become interchangeable.