Skip to content

Repository files navigation

LedgrAI

AI-powered invoice extraction, reconciliation, and fraud detection.

LedgrAI automates accounts-payable reconciliation: it extracts structured data from supplier invoices, matches them against purchase orders, detects price and quantity discrepancies, flags duplicate/fraudulent invoices, and routes each invoice to auto-approve or human-review — with a full audit trail.

Highlights

  • Multi-agent reconciliation pipeline — document extraction → PO matching → discrepancy detection → decision recommendation, with a reasoning trace.
  • Works with zero configuration — a built-in deterministic regex extractor
    • fallback path means the product runs and is testable with no API keys.
  • Optional LLM enhancement — plug in Groq or OpenAI for higher-accuracy extraction when a key is available.
  • Three-tier decisions: AUTO_APPROVE, REQUEST_CLARIFICATION, ESCALATE_TO_HUMAN.
  • Fraud & duplicate detection — file-hash dedup, duplicate invoice-number detection, amount-anomaly checks against PO totals.
  • Multi-tenant — every record is scoped to an authenticated user.
  • Full audit log — every reconciliation and human review is recorded.
  • 23 automated tests — unit + end-to-end integration, green with no API key.

Architecture

┌─────────────┐     ┌──────────────────────────────────────────┐
│  Next.js    │────▶│              FastAPI Backend              │
│  Frontend   │     │                                          │
│ (10 routes) │     │  ┌──────────┐  ┌─────────┐  ┌────────┐ │
└─────────────┘     │  │ Extract  │─▶│ Match   │─▶│ Detect │ │
                    │  │ (LLM/    │  │ PO      │  │ Discrep│ │
                    │  │  regex)  │  │         │  │        │ │
                    │  └──────────┘  └─────────┘  └───┬────┘ │
                    │                                   ▼      │
                    │  ┌──────────┐  ┌─────────┐  ┌────────┐ │
                    │  │ Fraud    │◀─│ Decide  │◀─│Reason  │ │
                    │  │ Check    │  │         │  │ Engine │ │
                    │  └────┬─────┘  └─────────┘  └────────┘ │
                    │       ▼                               │
                    │  SQLite (via SQLAlchemy async)         │
                    └──────────────────────────────────────────┘

Tech Stack

Layer Technology
Backend FastAPI, SQLAlchemy 2.0 (async), Pydantic v2
Database SQLite (dev) — swap to Postgres for production
Extraction pdfplumber (PDF), regex fallback, optional LLM
Matching RapidFuzz (fuzzy string matching)
Auth JWT (python-jose) + bcrypt
Frontend Next.js 14, React 18, TypeScript, Tailwind CSS
Testing pytest + pytest-asyncio (23 tests)

Quick Start

Prerequisites

  • Python 3.11+
  • Node.js 18+

Backend

cd backend
python -m pip install -r requirements.txt
copy .env.example .env       # (Windows)  — or:  cp .env.example .env
uvicorn app.main:app --reload --port 8000

The API is now live at http://localhost:8000 with interactive docs at http://localhost:8000/docs.

Frontend

cd frontend
npm install
npm run dev

The UI is at http://localhost:3000. Register an account, then upload an invoice (.pdf or .txt) to see reconciliation in action.

Run Tests

cd backend
python -m pytest -v

All 23 tests pass with no API key configured.

Optional: Enable LLM Extraction

Edit backend/.env:

LLM_PROVIDER=groq          # or "openai"
LLM_API_KEY=your_key_here
LLM_MODEL=llama-3.1-8b-instant
LLM_BASE_URL=https://api.groq.com/openai/v1

When a key is present, the extractor uses the LLM first and falls back to the deterministic regex parser on any failure. Without a key, only the regex path runs — the product is fully functional either way.

API Endpoints

Method Path Description
POST /auth/register Create account, get token
POST /auth/login Login, get token
GET /auth/me Current user
POST /invoices/upload Upload + reconcile an invoice
GET /invoices List invoices (filterable)
GET /invoices/{id} Invoice detail
POST /invoices/{id}/review Submit human review decision
GET /invoices/{id}/audit Audit trail for an invoice
DELETE /invoices/{id} Delete an invoice
GET /dashboard/stats Aggregated dashboard metrics
GET /health Health check

Decision Logic

The resolution engine applies rules in priority order:

  1. Missing/invalid PO numberESCALATE_TO_HUMAN (critical)
  2. Match confidence < 60%ESCALATE_TO_HUMAN
  3. Any price mismatch (beyond tolerance) → ESCALATE_TO_HUMAN
  4. No issuesAUTO_APPROVE
  5. Only minor issuesREQUEST_CLARIFICATION

Any HIGH-severity fraud flag overrides an auto-approval to escalation.

Project Structure

100M/
├── backend/
│   ├── app/
│   │   ├── api/            # FastAPI routers (auth, invoices, dashboard, meta)
│   │   ├── core/           # config, database, security
│   │   ├── data/           # purchase order reference dataset
│   │   ├── models/         # SQLAlchemy ORM models
│   │   ├── services/       # extraction, matching, resolution, fraud, pipeline
│   │   ├── schemas.py      # Pydantic request/response schemas
│   │   └── main.py         # App factory + entry point
│   ├── tests/              # 23 pytest tests (unit + integration)
│   ├── requirements.txt
│   └── .env.example
├── frontend/
│   ├── app/                # Next.js App Router pages
│   ├── components/         # Shared UI components
│   ├── lib/                # API client
│   └── package.json
└── README.md

License

MIT — see LICENSE.

About

AI 驱动的发票提取、PO 对账与欺诈检测,多 Agent 应付账款自动化流水线。FastAPI + Next.js,零 API Key 可运行。

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages