# Why I Built ExpenseFlow: An Autonomous AI-Powered Expense Management and Reimbursement System

Every company has the same quiet bottleneck: **expense reimbursements**.

An employee travels for work, pays for a hotel or a client dinner, snaps a photo of the receipt (or uploads a 4-page PDF), and submits a claim. Then the waiting begins. A finance admin has to open the PDF, squint at the total, cross-check it against a corporate Travel & Expense (T&E) policy document, verify the employee's bank details, check if the same receipt was already reimbursed last month, and finally trigger a payout.

I wanted to see what happens when you replace that manual back-and-forth with an **autonomous multi-agent AI pipeline**—one that doesn't just run OCR on a receipt, but actually *understands policy*, *detects duplicate fraud*, *scores risk*, and *settles eligible claims automatically*.

That is why I built **ExpenseFlow**.

---

## The Problem With "Simple OCR" Expense Tools

Most "AI expense trackers" stop at step one: they send an image to an LLM, extract `{ vendor, amount, date }`, and dump it into a form.

In real enterprise workflows, extraction is only **20% of the job**. The real work happens *after* extraction:

1. **Multi-bill documents:** Employees frequently upload a single PDF containing multiple separate invoices on different pages.
2. **Policy compliance:** A ₹2,200 meal claim should be auto-approved if the policy cap is ₹2,500—while a ₹3,400 meal claim should automatically route to a Finance Admin for approval.
3. **Duplicate & fraud detection:** What if someone re-uploads the same receipt, crops it slightly, or re-compresses the image to change its file hash?
4. **Auditability:** Finance teams need a clear reason *why* a claim was approved, escalated, or rejected.

ExpenseFlow was designed to solve all four end-to-end.

---

## Tech Stack Overview

ExpenseFlow uses a split frontend/microservice architecture deployed together as a unified project:

- **Frontend & API Gateway:** Next.js 16 (App Router)
- **AI Microservice:** Python FastAPI
- **Agent Orchestration:** LangGraph (`StateGraph`)
- **Vision & OCR Engine:** Google Gemini Flash Vision (`gemini-3.5-flash-lite` / `gemini-3.5-flash`)
- **Database:** Neon Cloud PostgreSQL
- **Object Storage:** Vercel Blob (with local disk fallback for offline dev)
- **Deployment:** Vercel Multi-Services (`vercel.json` with internal service bindings)

---

## How does ExpenseFlow's multi-agent architecture work?

ExpenseFlow models every expense claim as a stateful **LangGraph** workflow (`StateGraph`) split across four specialized agents—Document, Verification, Policy & RAG, and Risk—before reaching an automated Decision Gate. Each agent enriches a shared `ExpenseClaimState` and passes structured findings downstream so eligible claims settle automatically while edge cases escalate cleanly.

![](https://cdn.hashnode.com/uploads/covers/6b122d41f7d75f635aafc65d/3a003d1f-52f5-47c2-b3a5-a057f3ab2fa8.jpg align="center")

### 1\. Document Agent (Intake, Splitting & Fingerprinting)

- Accepts images (`PNG`, `JPG`, `WEBP`) and multi-page `PDF` files.
- Uses **Gemini Flash Vision** to extract structured JSON: vendor name, total amount, currency, invoice number, bill date, category, and line items.
- Computes two distinct fingerprints for every claim:
  - `SHA-256` **file hash** for exact byte-level matching.
  - `64-bit dHash` **(perceptual image hash)** for visual similarity matching.

### 2\. Verification Agent (Identity & Spend Velocity)

- Cross-references the claimant against the PostgreSQL employee directory.
- Confirms their active direct-deposit bank account number.
- Pulls historical claim counts and total claimed spend to establish a personal baseline.

### 3\. Policy & RAG Agent (Dynamic Policy Auditing)

- Queries corporate T&E policy rules and spending caps dynamically for each expense category (e.g., **Utilities:** ₹1,500, **Meals:** ₹2,500, **Lodging:** ₹8,000, **Office Supplies:** ₹10,000, **Travel:** ₹15,000).
- Evaluates whether the claimed amount falls within the allowed threshold or requires Finance Admin sign-off.

### 4\. Decision & Approval Gate

- Synthesizes findings from all four agents to render a final verdict:
  - **Auto-Approved (**`Refund Processed`**):** Clean claim at or below the category policy cap $\rightarrow$ triggers the reimbursement tool and generates a transaction ID (`TXN-REFUND-...`).
  - **Escalated (**`Pending Review`**):** Amount exceeds the policy cap or carries elevated risk $\rightarrow$ sent to the Finance Admin queue with an exact audit explanation.
  - **Rejected (**`Rejected`**):** Duplicate receipt or invalid amount.

---

## How does it prevent duplicate or fraudulent receipts?

ExpenseFlow stops duplicate and suspicious claims using a **3-tier fingerprinting pipeline** paired with an **anomaly-based Risk Agent** (`0.00` to `1.00`). Even if someone crops, resizes, or re-compresses a previously reimbursed receipt, perceptual hashing catches the visual match before a payout is ever triggered.

### 3-Tier Duplicate Detection

1. **Tier 1 (Exact Match):** Compares the cryptographic `SHA-256` `file_hash` against all stored claims.
2. **Tier 2 (Visual Similarity):** Compares the `64-bit dHash` perceptual `image_hash` using Hamming distance ($\le 5$), catching cropped, rotated, or re-saved screenshots of an already-submitted bill.
3. **Tier 3 (Metadata Match):** Checks for the same vendor and exact total amount against already-settled claims.

### Anomaly & Risk Scoring

- The **Risk Agent** flags behavioral anomalies—weekend transaction dates (`+0.15`), suspicious round-number totals (`+0.10`), generic vendor names (`+0.15`), or claims exceeding $3.5\times$ the employee's historical average (`+0.20`).
- Any claim with a `MEDIUM` or `HIGH` risk score is automatically escalated to `Pending Review` for Finance Admin inspection.

---

## What were the main engineering challenges and results?

Deploying a **Next.js + Python FastAPI** multi-agent system to production serverless infrastructure exposed four real bottlenecks around bundle size, ephemeral storage, Edge runtimes, and model latency. Solving each one cut OCR extraction down to ~1–2 seconds and kept the Python serverless bundle well under Vercel's 500 MB limit.

### 1\. Hitting the 500 MB Python Serverless Bundle Limit

When I first deployed the FastAPI service to Vercel, the build failed with `LAMBDA_SIZE_EXCEEDED` at **557.47 MB**. The culprit was `chromadb`, which pulled in heavy native binaries like `onnxruntime` and `grpcio`. Since serverless functions have ephemeral filesystems anyway, I made `chromadb` an optional dependency and backed all policy lookups directly with **Neon Cloud PostgreSQL**, slashing the Python bundle size well below 500 MB.

### 2\. Why Saving Files to Disk Breaks in Serverless

Locally, saving uploaded PDFs to `./uploads` works fine. On serverless, Container A writes to `/tmp/uploads`, and five minutes later Container B tries to serve the file and throws `Stored file not found on disk`. Integrating **Vercel Blob** (`@vercel/blob`) gave every receipt a permanent CDN URL while keeping a clean local fallback for offline development.

### 3\. Edge Runtime vs. Multi-Services

In Vercel Multi-Services mode, Next.js middleware compiles to an Edge Function (`_middleware`), which isn't supported alongside service bindings. Moving auth validation cleanly into Node.js API routes and client guards resolved the deployment block immediately.

### 4\. Eliminating Hidden Latency in Model Cascades

During live testing, OCR extraction felt sluggish because the fallback list tried deprecated or rate-limited model IDs before landing on an active one, triggering the rate-limiter's backoff sleep. Benchmarking the active models directly and updating the cascade to start with `gemini-3.5-flash-lite` brought extraction down to ~1–2 seconds.

---

## What's Next for ExpenseFlow?

ExpenseFlow started as an exploration into how **multi-agent workflows** can replace rigid, rule-heavy enterprise software. Next up, I'm looking at:

- Multi-currency FX conversion at historical invoice dates
- Automated ERP/accounting webhook exports (CSV/JSON ledger sync)
- Deeper role-based approval chains for department managers

If you're building with **Next.js + FastAPI + LangGraph**, I'd love to hear how you're structuring your agent states and deployments—drop a comment below!

---

## Try It Out

- **Live App:** [expenseflow.aryanh.online](https://expenseflow.aryanh.online/)
- **Project Case Study:** [ExpenseFlow on aryanh.online](https://www.aryanh.online/projects/expenseflow-autonomous-ai-powered-expense-management-reimbursement-system)
