Ledge AI
Ledging the AI process!!
The problem Ledge AI solves
THE PROBLEM
Priya runs a 6-person interior design studio in Bengaluru.
She has ₹67,000 in the bank, ₹2,33,000 owed to her, and
salaries due in 14 days. She has no idea she is about to
miss payroll. This is not exceptional — 84% of India's
63 million MSMEs borrow from informal lenders at predatory
rates because banks require collateral and audited books
they do not have. The ₹20–30 lakh crore MSME credit gap
exists because there is no verified, real-time picture
of their financial health.
WHAT WE BUILT
LedgeAI is a fully offline, on-device AI financial copilot
that runs entirely on a laptop with no internet connection
after setup. Four deterministic financial engines analyse
the business. Gemma 4 (E4B QAT, via Ollama) explains the
findings in plain English and drafts collection emails.
A bankability report maps the business to Mudra and CGTMSE
loan schemes. Nothing ever leaves the device.
HOW IT WORKS — END TO END
Data enters via a seed script (demo), CSV import, or our
fully offline local PDF parser for bank statements and
invoices (built using pypdf — no cloud OCR, no Vision APIs,
no external transmission of sensitive financial data).
Bank statements and invoices are parsed locally on the
device, structured into ledger entries, and written
directly into SQLite. One database read then builds a
frozen CompanySnapshot. Six pure functions run in strict
order:
-
Anomaly Detection — Student t-score per client
(t = (days_since − μ) / (σ/√n), dynamic threshold
from t.ppf(0.95, df=n−1)) flags invoices with
statistically abnormal payment delays. -
Liquidity Scoring — Weighted composite of runway,
quick ratio, DSO, and receivables quality. All
arithmetic in Python Decimal (28-precision) — no
IEEE 754 rounding errors on rupee amounts. -
Cash Flow Projection — 90-day daily ledger simulation
with a statistically correct t-based prediction
interval: PI(h) = ŷ(h) ± t(0.95,n−2)·s·√(1+1/n+
(h−h̄)²/Sxx). The band widens honestly with horizon.
No fudge factors. -
Payment Optimizer — True Mixed-Integer Linear Program
via scipy.optimize.milp (HiGHS solver). Objective:
maximize Σ(discount_i·amount_i·x_i), x_i∈{0,1},
subject to liquidity floor and hard deadline constraints.
Not a sort. A formal mathematical optimum. -
GST Calendar — CBIC GSTR-3B deadlines with urgency
classification (OVERDUE / URGENT / UPCOMING / FUTURE). -
Bankability Report — DSO, DPO, Cash Conversion Cycle
(CCC = DSO − DPO) mapped to Mudra Shishu / Kishore /
Tarun / Tarun Plus and CGTMSE eligibility thresholds.
GEMMA AS AN AGENT (MCP ARCHITECTURE)
Gemma 4 is not a chatbot wrapper. It is an autonomous
agent that calls our verified financial engines as tools
via Model Context Protocol. When a user asks "Which
clients put my payroll at risk?", Gemma decides to call
get_anomalous_invoices() and get_cashflow_projection()
sequentially, receives structured engine results, and
synthesizes a grounded final response.
The grounding firewall — our core differentiator — validates
every number in Gemma's output against the engine allowlist
before it reaches the screen. Monetary values: ±₹1 absolute
tolerance. Ratios and scores: 1% relative tolerance. If
Gemma invents a number, the entire response is rejected and
a verified fallback is shown. This is enforced by mechanism,
not by prompt wording.
THE DIFFERENTIATORS
• Offline PDF parsing: Bank statements and invoices are
parsed locally using pypdf — no cloud OCR, no Vision
APIs, no external transmission of sensitive financial
data. Privacy guaranteed at the ingestion layer.
• Offline-first: Gemma 4 E4B QAT (~5GB) runs on
127.0.0.1:11434. Airplane mode from second 15 of the
demo. No financial data ever leaves the device.
• Deterministic engines: Same input always produces the
same output. DEMO_DATE anchor, no datetime.now(), no
randomness. Structurally impossible to hallucinate a
financial metric.
• True MILP optimizer: scipy.optimize.milp with HiGHS —
not a heuristic sort. Formally optimal payment schedule.
• Statistically honest forecasting: t-distribution
prediction intervals, not fabricated confidence bands.
Six months of data does not buy a clean line at Day 90.
We show the honest range.
• Grounding firewall: A 40-line mechanism that makes
hallucination structurally impossible for numeric
outputs. Bifurcated tolerance — ±₹1 absolute for money,
1% relative for ratios. Enforced by code, not promises.
• MCP agentic orchestration: Gemma autonomously selects
and calls financial engine tools. It reasons across
multiple tool results before synthesizing a response.
Tool call trace is visible in the UI.
• India-native: ₹ Indian number grouping (1,85,000),
GST calendar, Mudra / CGTMSE bankability tiers,
Peenya-style MSME persona baked into every prompt.
THE BUSINESS MODEL
LedgeAI acts as a Loan Service Provider (LSP) under the
Open Credit Enablement Network (OCEN) framework. The
ambient operational data captured
Challenges we ran into
Building an offline-first, mathematically deterministic financial AI turned out to be significantly harder than plugging into a cloud API. Below are the four hardest problems we solved.
1. The IEEE 754 Floating-Point Trap
Our first working prototype used Python float for all monetary calculations. This silently broke our grounding firewall: engine outputs and LLM-narrated values would diverge by fractions of a rupee due to binary representation errors (0.1 + 0.2 = 0.30000000000000004). Aggregated across GST calculations, partial payments, and running cash balances, the drift became large enough to either falsely reject correct LLM outputs or pass incorrect ones.
Fix: We migrated all monetary arithmetic to Python's Decimal module with 28-digit precision (mirroring IBM's decNumber standard used in mainframe banking). Engines now cast inputs to Decimal on entry, compute exactly, and cast back to float only at the schema boundary for JSON serialization.
2. Ollama Tool-Calling Format Detection
We built the MCP agentic layer expecting Ollama's native tool_calls format to work universally. It doesn't — support varies by model version and Ollama build. On one team member's machine Gemma returned tool calls perfectly; on another it returned free-text explanations of what tool it would call.
Fix: We built a runtime detection mechanism (_detect_tool_support()) that sends a minimal test tool call at startup. If native tool-calling fails, we automatically fall back to a JSON-in-prompt pattern where Gemma returns {"tool": "...", "params": {...}} as raw text, which our executor parses manually. Both paths produce identical results from the user's perspective.
3. Statistically Honest Prediction Bands on 6 Data Points
Our first cash-flow projection multiplied the standard error by a hand-tuned (day_idx / 30.0 + 1) scaling factor to make the uncertainty band "look right." This was intellectually dishonest — any statistician judge would catch it in seconds. But the real formula requires converting monthly regression variance to daily balance-scale uncertainty, and the units kept fighting us.
Fix: We rederived the interval from first principles using the standard t-based prediction formula PI(h) = ŷ(h) ± t·s·√(1 + 1/n + (h−h̄)²/Sxx), then explicitly documented the monthly→daily unit conversion. The band now widens mathematically with horizon — no fudge factors — and we can defend every term from first principles.
4. The Grounding Firewall Tolerance Bug
Initial firewall used a single 2% relative tolerance for everything. This meant a ₹1,85,000 invoice had a tolerance window of ±₹3,700 — enough for Gemma to invent thousands of rupees while still passing validation. On the other extreme, a 1% tolerance on a t-score of 2.87 was too tight and rejected valid outputs due to display rounding.
Fix: We bifurcated the tolerance logic. Monetary values above ₹100 use an absolute tolerance of ±₹1.00 (invented rupees are structurally impossible). Ratios, scores, and days use a 1% relative tolerance (accommodates display rounding). Two lines of code, but this is the mechanism that makes our "no hallucination" claim provable rather than promissory.
Honorable Mentions
- SQLAlchemy 2.0 requires
sa.text()wrappers for raw SQL — we hitObjectNotExecutableErroron our first pipeline run and had to refactor every query. - Streamlit session state with more than 3 keys caused race conditions on rapid clicks — we consolidated to
result,narratives,runningand embedded the snapshot intoAnalysisResult. - Ollama cold-start latency on first call could exceed 45 seconds. We solved this by pre-warming an LLM cache keyed on
sha256(snapshot_json)so demo runs are instant even in airplane mode.
Technologies used