CoolFace
Apppublic

calvinothayoth/pm-proj-rag

sourceHugging Facemitupdated 3mo agoView on Hugging Face
0likes
App README

Mutual Fund FAQ Assistant - RAG Prototype

A facts-only mutual fund FAQ assistant demonstrating production-grade RAG architecture using a fixed Groww corpus for five HDFC mutual fund schemes.


๐ŸŽฏ Project Goal

Build a RAG (Retrieval-Augmented Generation) system that:

  • โ€”Answers objective, verifiable questions using only retrieved evidence
  • โ€”Refuses advisory, comparative, speculative, or out-of-corpus requests
  • โ€”Enforces strict response contracts (3 sentences, 1 citation, source date)
  • โ€”Demonstrates proper RAG components (embeddings, vector search, reranking, LLM generation)

๐Ÿ—๏ธ RAG Architecture

mermaid
flowchart LR
  user[User Query] --> ui[Web UI]
  ui --> api[FastAPI Server]

  api --> classify[Intent Classification<br/>BGE Embeddings + Keywords]

  classify -->|Advisory/Unsafe| refusal[Refusal Response]
  classify -->|Factual| retrieve[Hybrid Retrieval]

  subgraph Retrieval Pipeline
    retrieve --> faiss[FAISS Vector Search<br/>BGE Embeddings]
    retrieve --> bm25[BM25 Keyword Search<br/>Corpus-aware IDF]
    faiss --> combine[Fusion: 60% dense + 40% sparse]
    bm25 --> combine
    combine --> rerank[Cross-Encoder Reranking<br/>ms-marco-MiniLM]
  end

  rerank --> generate[LLM Generation<br/>Groq Llama 3.1]
  generate --> validate[Response Validation<br/>3 sentences, 1 link, footer]
  validate --> answer[Final Answer]
  refusal --> answer

  subgraph Data Pipeline
    corpus[5 Groww URLs] --> fetch[HTML Fetch]
    fetch --> parse[HTML Parser]
    parse --> chunk[Overlap Chunking<br/>700 chars, 100 overlap]
    chunk --> embed[BGE Embeddings]
    embed --> index[FAISS Index]
  end

  index --> faiss

๐Ÿ”ง Core RAG Components

1. Embedding Model: BGE Small (BAAI/bge-small-en-v1.5)

  • โ€”Type: Dense bi-encoder
  • โ€”Dimensions: 384
  • โ€”Framework: FastEmbed (optimized ONNX runtime)
  • โ€”Usage:
  • โ€”Query understanding (intent classification)
  • โ€”Document embeddings for vector search
  • โ€”Semantic similarity scoring

2. Vector Index: FAISS (Facebook AI Similarity Search)

  • โ€”Index Type: IndexFlatIP (Inner Product on L2-normalized vectors = cosine similarity)
  • โ€”Storage: Binary format (faiss_index.bin) + metadata JSON
  • โ€”Search: Approximate nearest neighbor (ANN) for O(log n) retrieval
  • โ€”Why FAISS: Industry standard for production vector search, supports billions of vectors

3. Hybrid Retrieval

Final Score = 0.6 * FAISS_Cosine_Similarity + 0.4 * BM25_Score
  • โ€”Dense (FAISS): Captures semantic meaning ("minimum investment" โ†’ "SIP amount")
  • โ€”Sparse (BM25): Captures exact keyword matches ("expense ratio", "exit load")
  • โ€”Fusion: Weighted combination for best recall

4. Cross-Encoder Reranking

  • โ€”Model: cross-encoder/ms-marco-MiniLM-L-6-v2
  • โ€”Purpose: Precise query-document relevance scoring
  • โ€”How it works:
  • โ€”Takes (query, document) pair as input
  • โ€”Outputs relevance score (typically [-10, 10])
  • โ€”More accurate than bi-encoder but slower
  • โ€”Standard RAG pattern:
  • โ€”Bi-encoder retrieves top 50-100 candidates (fast)
  • โ€”Cross-encoder reranks to top 5-10 (accurate)

5. BM25 Keyword Search

  • โ€”Implementation: Corpus-aware with proper IDF calculation
  • โ€”Formula:
  IDF(t) = log((N - n(t) + 0.5) / (n(t) + 0.5) + 1.0)
  Score = IDF * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * |D|/avgdl))
  • โ€”Parameters: k1=1.5, b=0.75 (standard values)

6. LLM Generation: Groq (Llama 3.1 8B)

  • โ€”Provider: Groq API (ultra-fast inference)
  • โ€”Model: llama-3.1-8b-instant
  • โ€”Temperature: 0.0 (deterministic, factual)
  • โ€”Max tokens: 150 (concise answers)
  • โ€”Prompt: Facts-only instructions with retrieved context

7. Intent Classification

  • โ€”Primary: Semantic similarity using BGE embeddings
  • โ€”Fallback: Keyword matching for robustness
  • โ€”Categories:
  • โ€”Allowed: expenseratio, exitload, minimumsip, lockinperiod, riskometer, benchmark, documentdownload
  • โ€”Refused: investmentadvice, comparison, ranking, returnprojection, performance_calculation

๐Ÿ“ฆ Tech Stack

ComponentTechnologyPurpose
EmbeddingsFastEmbed + BGE SmallDense vector representations
Vector SearchFAISSEfficient similarity search
Keyword SearchCustom BM25Lexical retrieval
RerankingSentence Transformers (Cross-Encoder)Precision reranking
LLMGroq (Llama 3.1)Answer generation
APIFastAPIREST API server
UIVanilla JS + CSSMinimal web interface
HTML ParserBeautifulSoup4Web scraping

๐Ÿš€ Setup & Usage

Prerequisites

  • โ€”Python 3.9+
  • โ€”Groq API key (for LLM generation)

Installation

bash
# Clone repository
git clone <repo-url>
cd pm-proj-rag

# Install dependencies
pip install -e .

# Set environment variables
echo "GROQ_API_KEY=your_key_here" > .env

Data Pipeline

bash
# 1. Ingest Groww pages (fetch, parse, chunk)
python scripts/ingest.py

# 2. Build FAISS index (embed chunks, create vector index)
python scripts/build_index.py

Run the Application

bash
# Start API server + UI
uvicorn src.pm_rag.api.server:app --reload --port 8000

# Open browser
http://localhost:8000

Run Tests

bash
python -m unittest discover -s tests

๐Ÿ“Š Data Flow

Ingestion Pipeline (Offline)

5 Groww URLs
  โ†’ HTML Fetch (requests)
  โ†’ HTML Parse (BeautifulSoup4)
  โ†’ Text Chunking (700 chars, 100 overlap)
  โ†’ BGE Embeddings (FastEmbed)
  โ†’ FAISS Index (IndexFlatIP)
  โ†’ Save: faiss_index.bin + metadata.json

Query Pipeline (Online)

User Query
  โ†’ Intent Classification (BGE embeddings + keywords)
  โ†’ If allowed:
    โ†’ FAISS Search (top 10 candidates)
    โ†’ BM25 Search (lexical matching)
    โ†’ Fusion (60% dense + 40% sparse)
    โ†’ Cross-Encoder Reranking (top 5)
    โ†’ LLM Generation (Groq Llama 3.1)
    โ†’ Response Validation (3 sentences, 1 link, footer)
  โ†’ If refused:
    โ†’ Polite refusal message

๐ŸŽฏ Response Contract

Every answer must:

  1. 1.โœ… Stay within 3 sentences
  2. 2.โœ… Include exactly one source link from the fixed 5-URL corpus
  3. 3.โœ… End with Last updated from sources: <YYYY-MM-DD>
  4. 4.โœ… Avoid investment advice, opinions, recommendations, return calculations

Example Response:

The HDFC Mid Cap Fund has an expense ratio of 0.73%. This is a direct plan growth option with no distributor commissions.
Source: https://groww.in/mutual-funds/hdfc-mid-cap-fund-direct-growth
Last updated from sources: 2026-05-29

๐Ÿ“ Project Structure

pm-proj-rag/
โ”œโ”€โ”€ src/pm_rag/
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ server.py              # FastAPI server
โ”‚   โ”œโ”€โ”€ ui/
โ”‚   โ”‚   โ”œโ”€โ”€ index.html             # Web UI
โ”‚   โ”‚   โ”œโ”€โ”€ styles.css             # Styling
โ”‚   โ”‚   โ””โ”€โ”€ app.js                 # Frontend logic
โ”‚   โ””โ”€โ”€ core/
โ”‚       โ”œโ”€โ”€ ingestion/
โ”‚       โ”‚   โ”œโ”€โ”€ fetcher.py         # HTML fetcher
โ”‚       โ”‚   โ”œโ”€โ”€ parser.py          # HTML parser
โ”‚       โ”‚   โ”œโ”€โ”€ chunker.py         # Text chunking
โ”‚       โ”‚   โ””โ”€โ”€ pipeline.py        # Ingestion orchestration
โ”‚       โ”œโ”€โ”€ retrieval/
โ”‚       โ”‚   โ”œโ”€โ”€ faiss_index.py     # FAISS vector index โญ
โ”‚       โ”‚   โ”œโ”€โ”€ embedder.py        # BGE embeddings โญ
โ”‚       โ”‚   โ”œโ”€โ”€ keyword_search.py  # BM25 search โญ
โ”‚       โ”‚   โ”œโ”€โ”€ reranker.py        # Rule-based reranking
โ”‚       โ”‚   โ”œโ”€โ”€ cross_encoder_reranker.py  # Cross-encoder โญ
โ”‚       โ”‚   โ””โ”€โ”€ retriever.py       # Hybrid retrieval โญ
โ”‚       โ”œโ”€โ”€ compliance/
โ”‚       โ”‚   โ”œโ”€โ”€ classifier.py      # Intent classification โญ
โ”‚       โ”‚   โ”œโ”€โ”€ policies.py        # Allowed/refused policies
โ”‚       โ”‚   โ””โ”€โ”€ validators.py      # Response validation
โ”‚       โ”œโ”€โ”€ answering/
โ”‚       โ”‚   โ”œโ”€โ”€ prompts.py         # LLM prompts
โ”‚       โ”‚   โ”œโ”€โ”€ generator.py       # LLM generation โญ
โ”‚       โ”‚   โ””โ”€โ”€ formatter.py       # Response formatting
โ”‚       โ””โ”€โ”€ sources/
โ”‚           โ””โ”€โ”€ catalog.py         # Corpus validation
โ”œโ”€โ”€ configs/
โ”‚   โ””โ”€โ”€ corpus.yaml                # Fixed 5-URL corpus
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ raw/                       # HTML snapshots
โ”‚   โ”œโ”€โ”€ processed/                 # Chunks with metadata
โ”‚   โ””โ”€โ”€ indexes/                   # FAISS index + metadata
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ ingest.py                  # Run ingestion
โ”‚   โ””โ”€โ”€ build_index.py             # Build FAISS index
โ””โ”€โ”€ tests/                         # Phase-wise tests

๐Ÿงช What This Prototype Demonstrates

โœ… Proper RAG Patterns

  1. 1.Embedding-based retrieval (not keyword-only)
  2. 2.Vector database (FAISS, not JSON file)
  3. 3.Hybrid search (dense + sparse)
  4. 4.Cross-encoder reranking (production pattern)
  5. 5.Semantic intent classification (not just regex)
  6. 6.Response validation (contract enforcement)

โœ… Engineering Best Practices

  1. 1.Modular architecture (separation of concerns)
  2. 2.Fallback mechanisms (LLM โ†’ regex simulator)
  3. 3.Corpus validation (fixed source guardrails)
  4. 4.Traceability (source URLs, dates, metadata)
  5. 5.Compliance gates (pre/post generation checks)

๐Ÿ”’ Safety & Compliance

  • โ€”Fixed corpus only: 5 Groww URLs, no external sources
  • โ€”No advisory responses: Refuses "should I invest?", "which is better?"
  • โ€”No sensitive data: Rejects PAN, Aadhaar, account number requests
  • โ€”Facts-only generation: No hallucination, no opinions
  • โ€”Source attribution: Every answer cites the exact Groww URL

๐Ÿ“ Known Limitations

  1. 1.Small corpus: Only 5 URLs (73 chunks) - designed for demonstration
  2. 2.Single LLM provider: Groq only (no fallback provider)
  3. 3.No caching: Every query re-runs embedding + LLM
  4. 4.No rate limiting: Not hardened for production traffic
  5. 5.No monitoring: No logging, metrics, or alerting

๐ŸŽ“ RAG Concepts Demonstrated

ConceptImplementationFile
Dense RetrievalBGE embeddings + FAISSfaiss_index.py
Sparse RetrievalBM25 with corpus-aware IDFkeyword_search.py
Hybrid SearchWeighted fusion (60/40)retriever.py
RerankingCross-encoder ms-marcocross_encoder_reranker.py
Embedding ModelBGE Small (384-dim)embedder.py
ChunkingOverlap-based (700/100)chunker.py
Intent ClassificationSemantic + keywordclassifier.py
LLM GenerationGroq Llama 3.1generator.py
Response ContractValidation layervalidators.py
Corpus CurationFixed source catalogcorpus.yaml

๐Ÿ“„ License

This project is for educational/demonstration purposes.


Disclaimer

Facts-only. No investment advice.

Active Source Rule

Only the five exact Groww URLs listed in configs/corpus.yaml may be used. Do not add AMC pages, AMFI pages, SEBI pages, third-party pages, extra Groww pages, or links discovered from these pages.

Selected Schemes

#SchemeCategorySource URL
1HDFC Mid Cap Fund - Direct GrowthMid Caphttps://groww.in/mutual-funds/hdfc-mid-cap-fund-direct-growth
2HDFC Equity Fund - Direct GrowthFlexi Caphttps://groww.in/mutual-funds/hdfc-equity-fund-direct-growth
3HDFC Focused Fund - Direct GrowthFocusedhttps://groww.in/mutual-funds/hdfc-focused-fund-direct-growth
4HDFC ELSS Tax Saver - Direct Plan GrowthELSShttps://groww.in/mutual-funds/hdfc-elss-tax-saver-fund-direct-plan-growth
5HDFC Large Cap Fund - Direct GrowthLarge Caphttps://groww.in/mutual-funds/hdfc-large-cap-fund-direct-growth