
Technical Architecture
Gemini 3 Flash with
agentic function calling
3-tier reconciliation with dynamic thinking levels, 8 investigation tools, streaming reasoning via Firestore, and pattern memory with Levenshtein fuzzy matching.
Full stack
System Architecture
Next.js 14 frontend, Firebase Cloud Functions backend, Gemini 3 Flash AI, and Firestore for real-time streaming.
- PDF scan (inlineData)
- CSV detection & parsing
- Template fingerprinting
- responseMimeType: JSON
- Tier 1: Rule-based scan
- Tier 2: thinking_level LOW
- Tier 3: thinking_level HIGH
- Pattern memory + learning
- queryFirestore tool
- getOverview / getCashFlow
- 90-day cash flow forecast
- Natural language queries
Gemini 3 API
How We Use Gemini 3
Four distinct Gemini 3 API features — Vision, Structured Output, Function Calling, and Thinking Levels — each serving a specific role.
Vision Processing
PDF pages sent as base64 to Gemini 3 Flash's multimodal input. Detects tables, headers, and transaction rows from any bank format.
inlineData: {
mimeType: "application/pdf",
data: base64EncodedPDF
}Structured Output
Guaranteed JSON responses — no regex parsing of AI text. Every extraction and reconciliation returns typed, validated data.
config: {
responseMimeType: "application/json",
// Gemini returns valid JSON directly
}Function Calling
8 tool declarations registered with Gemini. Manual calling loop processes tool calls until the AI is satisfied — up to 10 iterations.
tools: [{
functionDeclarations: [
searchTransactions,
findInvoiceCombination,
getFXRate, // ... 8 tools total
]
}]Thinking Levels
Dynamic thinking budget per tier. LOW for batch matching (speed). HIGH for complex investigations (depth). No thinking for rule-based.
thinkingConfig: {
thinkingLevel: ThinkingLevel.HIGH
// LOW for Tier 2, HIGH for Tier 3
}Deep dive
Reconciliation Engine
Five scoring signals, fee detection, FX conversion, combined payments, and pattern memory — all in one engine.
5-Signal Scoring Formula
Fee Pattern Detection
When a transaction amount doesn't match exactly, the engine checks if it matches after subtracting known processor fees.
Multi-Currency FX
- 40+ currency pairs with 3-tier fallback: Live API → Firestore cache → hardcoded rates
- Pegged currency detection — ANG, AWG, XCG treated as equivalent
- Cross-currency via USD pivot when direct rate unavailable
- FX tolerance: 2% for rounding, 5% for rate variance, 10% for fluctuation
Combined Payment Detection
When one transaction pays multiple invoices, the engine runs subset-sum with early termination to find document combinations that match the payment amount.
- Max 5 documents per combination (configurable)
- Groups by counterparty first (most likely), then cross-vendor
- Early termination after 3 matches found
- 2% tolerance for rounding differences
// Subset-sum with early termination
function findCombination(
docs, targetAmount, tolerance,
onFound, maxDocs = 5
) {
const recurse = (startIdx, current, sum) => {
if (found >= 3) return; // early termination
if (sum > target + tol) return; // prune
if (current.length >= 2 && diff <= tol)
onFound(current, sum);
};
}
Specifications
Technical Specifications
| AI Model | Gemini 3 Flash |
| Thinking Levels | LOW (batch) / HIGH (investigation) |
| Agent Tools | 8 function-calling tools |
| Max Iterations | 10 per investigation |
| Batch Size | 10 txns, 4 concurrent batches |
| FX Currencies | 40+ pairs, 3-tier fallback |
| Fee Patterns | Stripe, PayPal, Square, Wise, Card |
| Fuzzy Matching | Levenshtein distance, 0.7 threshold |
| Auto-Confirm | 93%+ confidence |
| Streaming | Real-time Firestore ProgressStream |
| Time Budget | 4 min/batch with graceful degradation |
| Combined Payments | Subset-sum, max 5 docs, early termination |
| Cash Flow Forecast | 90-day, 3 periods, 4096-token thinking budget |
| Anomaly Detection | 2σ outliers, slow payers, FX exposure, match rate |
| Chat Agent | Dynamic queryFirestore + 11 collections + 10 rounds |
| Chat Thinking | 2048-token budget, 90s timeout, 20-msg history |
Intelligence layer
Anomaly Detection & Cash Flow Forecast
Beyond reconciliation — statistical analysis, risk scoring, and predictive forecasting powered by Gemini 3 extended thinking.
Anomaly Detection
Statistical Outliers (2σ)
Debit amounts exceeding mean + 2 standard deviations flagged automatically. Runs on every transaction set.
Slow Payer Identification
Vendors with 30+ day delays detected from AI-learned vendor_patterns. Surfaces cash flow risks.
Low Match Rate Alerts
>20% unreconciled transactions triggers high-priority alert. Uses latest reconciliation_run data.
FX Exposure Detection
Cross-currency matches flagged for rate variance review. Detects when txn.currency ≠ doc.currency.
Spending Trend Analysis
Monthly debit comparison: >10% increase = trending up, >10% decrease = trending down.
// insights/page.tsx — computed on real data
const anomalies: { type, severity, description }[] = [];
// Statistical outlier detection
if (amount > mean + 2 * stdDev) anomalies.push(...);
// Slow payer from vendor_patterns
if (p.typicalDelay.max > 30) anomalies.push(...);
90-Day Cash Flow Forecast
Data Collection (6 parallel queries)
Gemini 3 Flash Configuration
Output Structure
Thinking Animation (7 steps)
✓ Analyzing historical transaction patterns...
✓ Scanning upcoming receivables and payables...
✓ Detecting seasonal spending trends...
✓ Computing projected inflows from unpaid invoices...
✓ Estimating recurring expense patterns...
✓ Assessing cash flow risk factors...
● Generating 90-day forecast with Gemini 3...
Agentic assistant
Financial Chat — “Ask Your Books”
An autonomous AI agent with direct Firestore access. Gemini 3 constructs its own queries from a full database schema — no hardcoded search functions.
Dynamic Query Architecture
queryFirestore — The Primary Tool
AI constructs arbitrary queries with filters, ordering, text search, and field selection. userId filter auto-applied for security.
Security Whitelist — 11 Collections
Agent Loop
Real-Time Progress Streaming
> ANALYZING QUERY
Processing: "Which vendors have unpaid invoices?"
> QUERYING DATABASE
Querying invoices: paymentStatus == unpaid
Found 12 results in invoices collection
Querying vendor_patterns: orderBy matchCount desc
Loaded financial overview across all collections
AI analyzing results (round 2)...
> GENERATING RESPONSE
Complete — 3 queries, 2 rounds, 2.1s
// Manual function-calling loop
while (response.functionCalls?.length > 0
&& iterations < 10) {
for (const fc of response.functionCalls) {
await writeProgressEvent(...);
result = await executeTool(fc.name, fc.args);
}
response = await ai.models.generateContent(...);
}
Export to any accounting system
Once your data is extracted, export it in the exact format your software needs.
Standard Formats
Ready-to-use templates for common accounting software.
Accounting Software
Pre-configured formats that import directly.
Custom Templates
Create your own export format with custom columns.
Enterprise Security
SOC 2 Type II
Certified compliant
256-bit Encryption
At rest and in transit
99.9% Uptime
SLA guaranteed
GDPR Compliant
Full data control
Ready to see it work?
Start your free 14-day trial today. No credit card required.