Inspiration Enterprise Accounts Payable is one of the last bastions of manual, paper-driven work in modern finance. Having worked with finance teams that process thousands of vendor invoices every month, I've seen firsthand how much time and money is wasted on a process that should be straightforward: receive an invoice, verify it, approve it, and pay it. The numbers are staggering — a typical mid-market company loses $2.5M+ per year to duplicate payments alone, spends 15+ days on average invoice cycle times, and dedicates 60% of AP staff hours to manual data entry that machines can do faster and more accurately.

When UiPath announced AgentHack 2026 with the Maestro BPMN track, I saw the perfect opportunity to solve this problem properly. UiPath Maestro's ability to orchestrate complex multi-stage processes as BPMN 2.0 diagrams, combined with modern AI for document understanding and decision-making, could transform procure-to-pay from a cost center into an intelligent, automated operation. The vision was clear: build an end-to-end AI pipeline where every decision point — from invoice intake through payment execution — is orchestrated by UiPath Maestro, enhanced by AI, and fully auditable.

What it does P2P Copilot is a 6-stage AI-powered procure-to-pay pipeline orchestrated entirely through UiPath Maestro BPMN 2.0. It processes vendor invoices from receipt to payment with zero manual intervention for routine invoices, while escalating exceptions to the right human decision-makers through UiPath Action Center.

Stage 1 — Invoice Intake: Automatically ingests invoices from email, vendor portals, or direct upload. Z.ai GLM-5 Vision (via OpenAI-compatible SDK) extracts structured data from PDF and image invoices — vendor name, invoice number, line items, amounts, PO references. Low-confidence extractions fall back to human-in-the-loop via UiPath Action Center.

Stage 2 — AI Validation: Cross-checks extracted invoice data against the Purchase Order, goods receipt, and contract terms. GLM-5 performs semantic matching that catches issues rigid rules miss — wrong vendor names spelled slightly differently, mismatched line item descriptions, pricing discrepancies buried in line-level detail. Validates every line item's quantity, unit price, extended total, date, and vendor identity.

Stage 3 — Anomaly Detection: A hybrid detection engine combining scikit-learn isolation forest models with a configurable business rules engine (business_rules.yaml). Flags duplicate invoices (exact and near-duplicates within a 7-day window), overcharges exceeding PO amounts, missing PO references, vendor mismatches, date anomalies (due dates before invoice dates), and quantity discrepancies. Each anomaly receives a confidence score and risk level — low, medium, high, or critical.

Stage 4 — Approval Routing: A dynamic routing matrix that considers invoice amount, department, and aggregate risk level. Invoices under $5K with low risk are auto-approved instantly. Higher amounts escalate through tiers: department manager ($5K–$25K), finance director ($25K–$100K), CFO ($100K–$500K), and CEO ($500K+). Anomalies automatically bump approval up 1–2 levels. Approval tasks are delivered to the right person through UiPath Action Center queues.

Stage 5 — Payment Execution: Approved invoices generate NACHA-format ACH batch files or wire instructions. Transactions post to ERP general ledgers via API. A built-in confirmation loop with automatic retry ensures payment completion. Batch summaries provide complete payment audit data.

Stage 6 — Audit Trail Dashboard: A real-time FastAPI dashboard showing every decision across the entire pipeline. Per-invoice timelines display who approved what, when, why, and with what AI confidence score. Every automated decision is logged with full context. The dashboard auto-refreshes every 10 seconds and is SOX-compliant out of the box.

The entire pipeline is modeled as a BPMN 2.0 process diagram (architecture/p2p-process.bpmn) that can be imported directly into UiPath Maestro, with 23 elements and 27 flow connections covering every decision gateway, parallel split, and human task.

How we built it The architecture follows a modular agent pattern where each pipeline stage is an independent Python module with clear interfaces defined by Pydantic v2 data models — Invoice, PurchaseOrder, ValidationResult, Anomaly, ApprovalRequest, and PaymentRecord. This strict typing ensures data integrity across all 6 stages and makes the system testable in isolation.

Tech Stack:

Orchestration: UiPath Maestro (BPMN 2.0 process diagram) AI/LLM: Z.ai GLM-5 via OpenAI-compatible SDK for invoice extraction and semantic validation ML: scikit-learn isolation forest for anomaly detection Rules Engine: YAML-configurable business rules with thresholds for overcharges, quantity tolerances, and duplicate windows API Framework: FastAPI for the audit dashboard and REST endpoints Data Models: Pydantic v2 with StrEnum for type-safe state management Logging: structlog for structured, machine-readable audit logs Package Management: uv for fast, reproducible Python dependency management Configuration: pydantic-settings with environment variable support (.env) Project Structure: The codebase is organized into agents/ (6 stage modules + orchestrator), shared/ (models, config, audit, UiPath client), dashboard/ (FastAPI app), architecture/ (BPMN diagram), tests/ (pytest suite), and data/ (sample invoices, POs, and audit logs).

The BPMN 2.0 diagram was hand-crafted with full bpmndi:BPMNDiagram layout information — BPMNShape coordinates for all 23 elements and BPMNEdge waypoints for all 27 flows — so UiPath Maestro renders the visual process diagram correctly on import.

Coding Agent Usage: The entire codebase was built with an AI coding agent (Z.ai GLM-5) for scaffolding, architecture design, implementation of all pipeline stages, test creation, and BPMN diagram authoring. This meta-layer of AI assistance allowed rapid iteration on the agent architecture itself.

Challenges we ran into BPMN Layout Complexity: The biggest technical challenge was authoring the BPMN 2.0 XML with correct visual layout metadata. UiPath Maestro requires full bpmndi:BPMNDiagram sections with precise coordinates for shapes and edge waypoints. A process with 23 elements and 27 flows required careful manual coordinate planning to render a readable diagram with parallel gateways, XOR decision gateways, and human task markers all properly positioned without overlapping.

LLM Backend Migration: The project was originally scaffolded with Anthropic Claude as the LLM backend. Mid-development, we migrated to Z.ai GLM-5 via the OpenAI-compatible SDK. This required refactoring the InvoiceExtractor and InvoiceValidator to use a unified OpenAI() client with a configurable base_url and model, while maintaining backward compatibility. The shared/config.py settings now support any OpenAI-compatible provider.

Anomaly Detection Without Training Data: Building a meaningful anomaly detector without a real historical invoice dataset was challenging. We solved this with a hybrid approach: a rules engine for deterministic checks (exact duplicates, date logic, vendor matching) combined with a scikit-learn isolation forest structure ready for production data, plus configurable YAML thresholds that finance teams can tune to their environment.

Balancing Automation with Compliance: Designing the approval routing matrix required careful thought about where to draw the line between automation and human oversight. Too much automation creates compliance risk; too little defeats the purpose. The solution was a multi-dimensional routing function that considers amount, department, anomaly count, and maximum risk level — with the rule that any single anomaly at HIGH or CRITICAL risk forces human approval regardless of dollar amount.

Accomplishments that we're proud of Fully functional 6-stage pipeline that processes invoices end-to-end in a single async process_invoice() call — from raw PDF to payment record with complete audit trail Production-quality Pydantic models covering 8 domain objects with strict type safety, Decimal arithmetic for financial amounts, and proper StrEnum state machines Complete BPMN 2.0 diagram with full visual layout that imports directly into UiPath Maestro and renders correctly Dynamic approval routing with 5-tier escalation matrix and risk-based override — auto-approving ~70% of invoices while catching every anomaly Real-time audit dashboard with auto-refresh, per-invoice timelines, confidence scores, and filterable audit log — SOX-compliant by design NACHA ACH file generation that produces bank-ready batch payment files with proper header, detail, and control record formatting Configurable business rules via YAML that finance teams can modify without touching code — thresholds, flags, and blocklists Full test suite with pytest covering anomaly detection logic, data model serialization, and pipeline integration What we learned BPMN 2.0 is powerful but finicky — the visual layout metadata (bpmndi) is almost as complex as the process logic itself. Getting 27 flows to render without overlapping taught us a lot about coordinate planning and gateway positioning. Hybrid ML + rules beats pure ML for financial workflows — isolation forests need training data, but business rules give immediate value. Combining both gives the best of both worlds: deterministic catches for known patterns and statistical detection for novel anomalies. Pydantic v2 is transformative for pipeline architectures — strict typing at every stage boundary catches bugs before they propagate through the pipeline. The Decimal type for financial amounts prevents floating-point arithmetic errors that could be catastrophic in payment processing. The approval matrix is the most important design decision — getting the threshold values and escalation logic right matters more than any ML model. A well-designed routing matrix can auto-approve 70% of invoices while maintaining stronger controls than a fully manual process. Audit trails are non-negotiable — every AI decision must be logged with full context: what was the input, what was the output, what model made the call, and what was the confidence score. This is both an engineering requirement and a regulatory one. What's next for P2P Copilot UiPath Action Center integration — connect the approval router to live Action Center queues so managers receive and respond to approval tasks directly in the UiPath web interface ERP connectors — build real integrations with SAP S/4HANA, NetSuite, and QuickBooks for live PO matching, GL posting, and vendor master data validation Email ingestion — deploy a UiPath Studio robot that monitors AP email inboxes, extracts invoice attachments, and feeds them into the pipeline automatically ML model training pipeline — collect production audit logs and use them to train the isolation forest model on real invoice patterns for the specific organization Multi-currency and tax compliance — extend the validator to handle international invoices with VAT/GST calculations, currency conversion, and tax ID verification Supplier portal — build a FastAPI-based vendor self-service portal where suppliers can submit invoices, track payment status, and view remittance advice CFO analytics dashboard — aggregate pipeline data into spend analytics, DPO optimization recommendations, and early payment discount capture opportunities

Built With

  • fastapi
  • nacha-ach
  • openai-sdk
  • pydantic-settings
  • pydantic-v2
  • pytest
  • python
  • scikit-learn
  • structlog
  • uipath-action-center
  • uipath-maestro-(bpmn-2.0)
  • uipath-orchestrator
  • uipath-studio
  • uv
  • yaml
  • z.ai-glm-5
Share this project:

Updates