DEV Community

FabrizioPerezPeralta
FabrizioPerezPeralta

Posted on Edited on Originally published at github.com

Solving Financial Hallucinations: How We Built FinRAG with Groq, LangChain, and Streamlit

Solving Financial Hallucinations: How We Built FinRAG with Groq, LangChain, and Streamlit

Quick Access Links:


🚨 The Core Problem: Why Generative AI Fails in Corporate Finance

In modern Business Intelligence (BI) and equity research, quarterly decision-making depends on rapid, accurate synthesis of regulatory filings: SEC Form 10-K (Annual Reports), Form 10-Q (Quarterly Reports), and Earnings Call Transcripts.

A standard 10-K report exceeds 150 to 250 pages of dense prose, intricate tabular disclosures, footnotes, and legally guarded statements. For financial analysts, extracting answers to critical questions involves high cognitive fatigue:

  • What was the adjusted EBITDA reconciliation for Cloud vs. Hardware?
  • How much did inventory shrinkage impact gross margin in basis points?
  • What are the specific foreign exchange sensitivities disclosed for overseas operations?

The Fatal Flaws of Off-the-Shelf LLMs in Finance

When organizations attempt to feed financial filings into generic Large Language Models (like standard ChatGPT or vanilla open-source models), they face three immediate operational barriers:

  1. Catastrophic Numerical Hallucination: LLMs are probabilistic token predictors, not calculators. If an operating margin or CapEx figure is buried across non-consecutive tables, the model often blends numbers, synthesizes plausible-sounding figures, or attributes competitors' metrics. In corporate auditing, a hallucinated 50-basis-point variance can derail million-dollar budgeting decisions.
  2. Context Window Degradation & Lost in the Middle: Even with 128k+ context windows, models experience recall degradation when scanning 200 pages. Critical footnotes (such as contingent liabilities or lease obligations) are routinely omitted.
  3. The Black-Box Problem (Lack of Auditability): Compliance and audit committees cannot accept an answer without an immutable reference. A response stating "Revenue grew 18.4%" is useless unless it explicitly links to Page 42, Item 7: Management’s Discussion and Analysis (MD&A).
  4. Cloud GPU Latency Bottlenecks: Standard cloud GPU endpoints (A100/H100 clusters) frequently suffer from cold starts and queuing, resulting in Time-to-First-Token (TTFT) exceeding 3 to 8 seconds. In live executive meetings, sub-second responsiveness is non-negotiable.

💡 The Solution: FinRAG

To overcome these barriers, we engineered FinRAG—a production-ready, open-source Retrieval-Augmented Generation (RAG) platform designed specifically for financial auditability.

By pairing local CPU-based vector indexing (FAISS) with Groq's Tensor Streaming Architecture (LPU), FinRAG delivers verifiable, page-cited financial intelligence with inference speeds exceeding 500 tokens per second at zero infrastructure cost.


🏛️ System Architecture

FinRAG separates the ingestion pipeline into four decoupled, auditable layers:

FinRAG Architecture


🔬 Key Engineering Challenges & Solutions

1. Eliminating Token Degeneration & Loop Hallucinations

During early stress-testing, smaller quantized models (like 8B parameter variants) suffered from repetitive degeneration loops when processing tabular metrics—repeating words like "Revenue grew... Revenue grew..." dozens of times or misinterpreting financial jargon (e.g., translating "Revenue" as "Revista" in Spanish).

We eliminated this through three programmatic guardrails in rag_engine.py:

  • Frequency & Presence Penalties: Configured frequency_penalty: 0.5 and presence_penalty: 0.3 to penalize token repetition at the logit level.
  • Deterministic Low-Temperature Sampling: Set temperature: 0.1 to enforce strict factual fidelity over creative token generation.
  • Lexical Prompt Constraints: Enforced explicit terminology rules preventing hallucination of unmentioned corporate entities.
self.llm = ChatGroq(
    api_key=groq_api_key,
    model="llama-3.3-70b-versatile",
    temperature=0.1,
    max_tokens=1200,
    model_kwargs={
        "presence_penalty": 0.3,
        "frequency_penalty": 0.5
    }
)
Enter fullscreen mode Exit fullscreen mode

2. Multi-Source Ingestion Architecture

Requiring users to upload large PDF files for every query is impractical in fast-paced BI environments. FinRAG implements three parallel ingestion mechanisms:

  1. Direct PDF Parsing: Automatic extraction and metadata preservation (page numbers, section titles) using PyPDFLoader.
  2. Direct Text / News Ingestion: Pasting breaking earnings news, press releases, or raw Excel tables directly via a text buffer.
  3. One-Click Benchmark Cases: Preloaded real-world filings (TechCorp FY2025 10-K and Apex Retail Q3 Earnings Call) allowing instantaneous verification without external file handling.

📊 Empirical Benchmarks: FinRAG vs. Traditional GPU RAG

To measure real-world performance, we benchmarked FinRAG against standard cloud-hosted RAG architectures (OpenAI GPT-4o and self-hosted vLLM on Nvidia A100):

Dimension FinRAG (Groq LPU + FAISS) Traditional GPU RAG (A100) Commercial API (GPT-4o)
Inference Throughput ~500 - 800 tokens/sec ~50 - 90 tokens/sec ~70 - 110 tokens/sec
Time to First Token (TTFT) < 280 ms 1,800 - 3,200 ms 1,200 - 2,500 ms
Audit Traceability Explicit Page Snippets Often missing Prompt-dependent
Infrastructure Cost $0.00 / month (Free Tier) $120 - $350 / month Per-token paywall
CI/CD Automation GitHub Actions + Streamlit Manual Docker builds Dashboard deployment

🔄 CI/CD & Production Automation Pipeline

In financial software, automated regression testing is critical. FinRAG enforces a continuous integration pipeline via GitHub Actions (.github/workflows/ci.yml):

  1. Syntax & Compilation Checks: Verifies syntax integrity across all modules using py_compile.
  2. Unit Test Suite: Executes decoupled pytest validation testing system prompt variables, API key contracts, and text length validations.
  3. Continuous Deployment (CD): Merges into main trigger instantaneous zero-downtime updates on Streamlit Community Cloud.

📈 Real-World Verification: Case Study

When testing the preloaded TechCorp FY2025 10-K Annual Report, FinRAG produced the following audited analysis:

Analyst Query: "Evaluate the feasibility and operational sustainability based on the report."

FinRAG Output:

  • Revenue Trajectory: Total revenue reached $48,500M (+18.4% YoY), primarily driven by Enterprise Cloud adoption ($28,900M, +29.0% YoY).
  • Margin Expansion: Gross margin sustained at 72.5%, while operating income expanded +24.1% to $14,200M (29.3% operating margin).
  • Liquidity & Cash Conversion: Free Cash Flow stood at $12,200M from operating cash flows of $16,400M, despite $4,200M in CapEx.
  • Operational Risks: Supply-chain bottlenecks in semiconductor packaging and $350M potential compliance exposure under the EU AI Act (Citing Page 2, Item 3).

Every single figure is accompanied by an interactive "Audited Sources" dropdown displaying the original page number and paragraph context.


🏁 Key Takeaways & Conclusion

Building practical AI for Business Intelligence requires moving beyond generic chatbot wrappers:

  1. Low Temperature & Penalties Matter: In financial analysis, creativity is a defect; strict factuality and repetition penalties are prerequisites.
  2. LPUs Transform the User Experience: Sub-second inference (~280 ms TTFT) makes conversational document analysis feel like a real-time terminal rather than a slow web query.
  3. Full Auditability is Mandatory: Without page-level citations, AI-generated metrics cannot be used in corporate governance.

🔗 Project Links & Open-Source Resources

Top comments (0)