ACxxxy/FinRAG
FinRAG
A production-grade, citation-enforced financial RAG system integrating state-of-the-art AI orchestration with robust enterprise software engineering.
  
π Live Platform: fin-rag-five.vercel.app
What This Does
FinRAG is an enterprise-grade financial research engine designed to query SEC filings (10-K, 10-Q, 8-K) and earnings call transcripts. It leverages advanced LLM reasoning to generate answers that are 100% grounded in source text, enforcing exact citations (company, filing period, section, and page). To eliminate hallucination, the system executes an automated refusal protocol if the evidence is insufficient.
Key Capabilities
- LangGraph Orchestration β Multi-agent state machine routing requests based on query intent and complexity.
- Hybrid Retrieval (RRF) β Fusing BM25 sparse search and dense sentence embeddings via Reciprocal Rank Fusion.
- Cross-Encoder Reranking β Second-stage transformer validation for precision retrieval.
- Multi-turn Session Memory β Thread-safe session tracking, coreference resolution, and entity memory.
- Automated LLM-as-a-Judge β Real-time generation evaluation scoring citation accuracy and faithfulness.
- Containerized Stack (Docker) β Multi-container local orchestration (Next.js frontend, FastAPI backend, Redis, PostgreSQL).
- Sub-Millisecond Caching (Redis) β Ultra-fast caching for frequent prompt/response pairs.
- Query Analytics Engine (PostgreSQL) β Persistent SQL logging tracking token costs, latency distribution, and evaluation metrics.
- Asynchronous Jobs (Async Tasks) β FastAPI background task workers for parallel filing downloads, section-aware chunking, and vector indexing.
- API Rate Limiting β Bulletproof client rate-limiting protection.
- Structured Logging β Standardized, production-grade JSON logging for observability and error tracing.
- Streaming API β Server-Sent Events for progressive UI rendering.
- Guardrails β Prompt injection detection, PII filtering, and output verification.
- CI Quality Gates β Automated testing builds failing if faithfulness < 0.85 or citation coverage < 0.90.
Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FastAPI Layer β
β POST /query β POST /query/stream β GET /metrics β
ββββββββ¬βββββββββ΄βββββββββββ¬ββββββββββββ΄βββββββββββ¬βββββββββββββββ
β β β
βΌ βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LangGraph Orchestration β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β Input ββββΆβ Retrieve ββββΆβ Rerank ββββΆβ Route β β
β β Guard β β (Hybrid)β β (Cross- β β (Keyword β β
β β β β β β Encoder) β β Router) β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββ¬ββββββ β
β β β
β βββββββββββββββββββ¬ββββββββββββββββ β
β βΌ βΌ β
β ββββββββββββ ββββββββββββ β
β β Generate β β Calculate β β
β β (Gemini) β β (Gemini) β β
β ββββββ¬ββββββ ββββββ¬ββββββ β
β β β β
β βΌ βΌ β
β ββββββββββββ ββββββββββββ β
β β Validate ββββΆβ Output β β
β β Citationsβ β Guard β β
β ββββββββββββ ββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
βΌ βΌ
ββββββββββββββββ ββββββββββββββββββββ
β ChromaDB β β Langfuse β
β + BM25 β β Tracing β
β Vector Storeβ β + Metrics β
ββββββββββββββββ ββββββββββββββββββββTech Stack
Setup
Prerequisites
- Python 3.11+
- Google API key (for Gemini LLM)
- Docker & Docker Compose (optional, but highly recommended for complete multi-container setup)
Option 1: Docker Compose (Quickest & Recommended)
Run the entire stack (Next.js UI, FastAPI Backend, Redis prompt cache, and PostgreSQL analytics) with a single command:
# Clone the repo
git clone https://github.com/ac265640/FinRAG.git
cd FinRAG
# Spin up all containers
docker-compose up --buildMake sure to edit the .env file generated in the project root with your credentials.
Option 2: Local Virtual Environment Installation
# Clone the repo
git clone https://github.com/ac265640/FinRAG.git
cd FinRAG
# Create virtual environment
python -m venv .venv
# Activate (Windows)
.venv\Scripts\activate
# Activate (macOS/Linux)
source .venv/bin/activate
# Install with dev dependencies
pip install -e ".[dev]"Environment Configuration
# Copy example env file
cp .env.example .envEdit .env with your credentials:
# Required: Google Gemini API key
GOOGLE_API_KEY=your_key_here
# Optional: Langfuse observability
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
# Optional: API authentication
FINRAG_API_KEY=your_api_secretQuick Start
1. Ingest a Filing
# Download and process Apple's latest 10-K
python scripts/ingest.py --ticker AAPL --filing-type 10-K --count 1This downloads the filing from SEC EDGAR, parses sections, chunks with metadata, and indexes into ChromaDB + BM25.
2. Start the API Server
uvicorn finrag.api.app:app --reload --port 80003. Query the Pipeline
# Synchronous query
curl -X POST http://localhost:8000/api/v1/query \
-H "Content-Type: application/json" \
-d '{"query": "What was Apple total net revenue for fiscal year 2024?"}'
# Streaming query (SSE)
curl -X POST http://localhost:8000/api/v1/query/stream \
-H "Content-Type: application/json" \
-d '{"query": "What was Apple total net revenue for fiscal year 2024?"}'4. Check Metrics
curl http://localhost:8000/api/v1/metricsAPI Reference
Query Request
{
"query": "What was Apple's free cash flow in FY2024?",
"session_id": "optional-session-id",
"metadata_filter": {"ticker": "AAPL"}
}Query Response
{
"answer": "Apple's free cash flow in FY2024 was...",
"citations": [
{
"chunk_id": "abc123",
"filing_reference": "AAPL 10-K FY2024, Item 7 - MD&A",
"section": "Item 7",
"relevance_score": 0.92
}
],
"session_id": "auto-generated-uuid",
"confidence": 0.87,
"route": "retrieve",
"prompt_version": "v2",
"metadata": {
"request_id": "uuid",
"trace_id": "langfuse-trace-id",
"total_latency_ms": 1250
}
}Evaluation
Golden Dataset
50 manually verified Q/A pairs across 4 categories:
Run Evaluations
# RAGAS metrics (faithfulness, relevancy, precision, coverage)
python -m finrag.evaluation.run_eval --mode ragas --threshold 0.85
# LLM-as-Judge citation scoring
python -m finrag.evaluation.run_eval --mode judge --threshold 0.90
# Full evaluation (both)
python -m finrag.evaluation.run_eval --mode full --output report.json
# Filter by category
python -m finrag.evaluation.run_eval --mode ragas --category numericalCI Quality Gates
Every PR triggers the quality gate workflow:
lint β unit tests (60% coverage) β RAGAS eval (β₯0.85) β Judge eval (β₯0.90)Builds fail if quality thresholds are not met.
Project Structure
FinRAG/
βββ .github/workflows/ # CI quality gate
β βββ quality-gate.yml
βββ alembic/ # PostgreSQL migration scripts & schema env
βββ configs/ # Versioned prompt configs (YAML)
βββ data/ # SEC filing database storage
β βββ chroma/ # ChromaDB SQLite3 persistence database
β βββ raw/ # SEC raw filing HTML files grouped by ticker
βββ finrag-ui/ # Next.js 14 frontend interactive application
β βββ app/ # App Router pages and analytics charts
β βββ components/ # Chat component, citations highlight, sidebar
β βββ lib/ # API clients, types, and analytics helpers
β βββ Dockerfile.frontend # Frontend Docker image configuration
βββ scripts/
β βββ ingest.py # EDGAR ingestion CLI
βββ src/finrag/
β βββ ingestion/ # EDGAR client, section chunker
β βββ vectorstore/ # ChromaDB store
β βββ retrieval/ # BM25, hybrid retriever
β βββ orchestration/ # LangGraph, nodes, routing, memory
β βββ guardrails/ # Input/output guards
β βββ api/ # FastAPI app, routes, middleware, MCP
β βββ observability/ # Langfuse tracer, metrics
β βββ evaluation/ # Golden dataset, RAGAS, LLM-as-Judge
βββ tests/ # 16 test modules, 300+ tests
βββ docker-compose.yml # Local microservice container orchestration
βββ Dockerfile # Backend FastAPI space configuration
βββ DEBT_LEDGER.md # Technical debt tracking
βββ pyproject.toml # Dependencies and tooling configDevelopment
Run Tests
# All tests
python -m pytest tests/ -v --tb=short
# Specific day/module
python -m pytest tests/test_integration.py -v
# With coverage
python -m pytest tests/ --cov=finrag --cov-report=term-missingLint
ruff check src/ tests/
ruff format src/ tests/Environment Variables
License
MIT
