SmartInvoice
DemoFeaturesPricingContact
Sign InStart Free Trial
Features

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.

Start Free TrialView Pricing

Full stack

System Architecture

Next.js 14 frontend, Firebase Cloud Functions backend, Gemini 3 Flash AI, and Firestore for real-time streaming.

Client
Next.js 14 + React 19 + Firestore SDK + Tailwind CSS
Real-time onSnapshot listeners for streaming AI progress
Real-time listeners
Firebase Cloud Functions (onCall)
Vision Pipeline
  • PDF scan (inlineData)
  • CSV detection & parsing
  • Template fingerprinting
  • responseMimeType: JSON
Reconciliation Engine
  • Tier 1: Rule-based scan
  • Tier 2: thinking_level LOW
  • Tier 3: thinking_level HIGH
  • Pattern memory + learning
AI Assistant
  • queryFirestore tool
  • getOverview / getCashFlow
  • 90-day cash flow forecast
  • Natural language queries
Firestore
transactions, invoices, bills, vendor_patterns, match_history, fx_cache, reconciliation_runs
ProgressStream
Firestore events → onSnapshot → Terminal UI with color-coded reasoning steps

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

Reference Match/40
Invoice # found in description
Amount Match/35
Exact, FX-converted, or fee-adjusted
Identity Match/25
Vendor name fuzzy match (Levenshtein)
Time Proximity/20
Days between invoice and payment
Context/5
Unique amount, cross-currency bonus
Total: /125 → normalized to 0-100% confidence

Fee Pattern Detection

Stripe2.9% + $0.30
PayPal2.9% + $0.30
Square2.6% + $0.10
Wise1%
Card3%

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 ModelGemini 3 Flash
Thinking LevelsLOW (batch) / HIGH (investigation)
Agent Tools8 function-calling tools
Max Iterations10 per investigation
Batch Size10 txns, 4 concurrent batches
FX Currencies40+ pairs, 3-tier fallback
Fee PatternsStripe, PayPal, Square, Wise, Card
Fuzzy MatchingLevenshtein distance, 0.7 threshold
Auto-Confirm93%+ confidence
StreamingReal-time Firestore ProgressStream
Time Budget4 min/batch with graceful degradation
Combined PaymentsSubset-sum, max 5 docs, early termination
Cash Flow Forecast90-day, 3 periods, 4096-token thinking budget
Anomaly Detection2σ outliers, slow payers, FX exposure, match rate
Chat AgentDynamic queryFirestore + 11 collections + 10 rounds
Chat Thinking2048-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)

accounts
transactions (100)
invoices
bills
vendor_patterns
reconciliation_runs (3)

Gemini 3 Flash Configuration

Modelgemini-3-flash
Temperature0.3 (conservative)
Thinking Budget4,096 tokens
Response Formatapplication/json
Max Output4,096 tokens

Output Structure

3 forecast periods — 30/60/90 days with confidence scores
Risk factors — severity + estimated dollar impact
AI recommendations — actionable next steps
Reasoning — 2-3 paragraph methodology explanation

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.

collectionfilters[]orderByorderDirectionlimitselectFields[]textSearch

Security Whitelist — 11 Collections

invoicesbillstransactionsaccountsstatementsreconciliation_matchesvendor_patternsinvoice_line_itemsreconciliation_runsmatch_historydocuments

Agent Loop

Max iterations10 rounds
Thinking budget2,048 tokens
Conversation historyLast 20 messages
Timeout90 seconds

Real-Time Progress Streaming

chat_progress — live events

> 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

financial-chat.ts — agentic loop
// 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.

Excel (.xlsx)CSVJSONPDF Report

Accounting Software

Pre-configured formats that import directly.

QuickBooksXeroSageFreshBooks

Custom Templates

Create your own export format with custom columns.

Custom CSVAPI/JSONBank Format

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.

Start Free TrialRequest Demo
SmartInvoice

AI-Powered Bank Statement Processing. Automate your financial workflows with AI-powered document processing and real-time insights.

twitter
linkedin

Product

  • Features
  • Pricing
  • Changelog
  • Roadmap

Company

  • About
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service
  • Cookie Policy
  • Security
  • GDPR

© 2026 SmartInvoice Ltd. All rights reserved.

|

Built by AI Makers

All systems operational