CAMS-AI / services /vector_store.py
Rahul-rr's picture
Deploy CAMS Assistant
91651eb
Raw History Blame Contribute Delete
7.69 kB
"""
services/vector_store.py
-------------------------
Two-path RAG architecture:
PATH A β€” Account queries (balance, SIP, transactions):
PAN/ID exact lookup from investors.json β†’ instant (~0ms)
PATH B β€” Knowledge queries (KYC rules, SEBI norms, fund info):
TF-IDF keyword search over knowledge_base.json β†’ ~5ms (in-process, no API)
Why TF-IDF instead of embeddings?
- Groq has NO embeddings API (404)
- sentence-transformers = 80MB download, 28s load
- For 10 policy docs, TF-IDF is fast, accurate, and zero-dependency
- scikit-learn is already a common Python package
- Works offline, no API key, no rate limits
"""
from __future__ import annotations
import json
import logging
import re
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
DATA_PATH = Path(__file__).parent.parent / "data" / "investors.json"
KB_PATH = Path(__file__).parent.parent / "data" / "knowledge_base.json"
try:
import chromadb
CHROMA_OK = True
except ImportError:
CHROMA_OK = False
try:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
SKLEARN_OK = True
except ImportError:
SKLEARN_OK = False
logger.warning("scikit-learn not installed. pip install scikit-learn")
# ── Singleton ─────────────────────────────────────────────────────────────────
_store: Optional["VectorStore"] = None
def get_vector_store() -> "VectorStore":
global _store
if _store is None:
_store = VectorStore()
return _store
class VectorStore:
def __init__(self) -> None:
self._investors: list[dict] = []
self._kb_docs: list[dict] = []
self._tfidf_matrix = None
self._tfidf_vectorizer = None
self._load_investors()
self._load_knowledge_base()
if SKLEARN_OK and self._kb_docs:
self._build_tfidf_index()
# ── Loaders ───────────────────────────────────────────────────────────────
def _load_investors(self) -> None:
if not DATA_PATH.exists():
logger.warning("investors.json not found. Run: python setup_data.py")
return
with open(DATA_PATH) as f:
self._investors = json.load(f)
logger.info(f"Loaded {len(self._investors)} investor records (PATH A β€” exact lookup)")
def _load_knowledge_base(self) -> None:
if not KB_PATH.exists():
logger.info("knowledge_base.json not found β€” PATH B disabled")
return
with open(KB_PATH) as f:
self._kb_docs = json.load(f)
logger.info(f"Loaded {len(self._kb_docs)} KB documents (PATH B β€” TF-IDF search)")
# ── TF-IDF index (built in-memory at startup, takes ~10ms) ───────────────
def _build_tfidf_index(self) -> None:
try:
corpus = [doc["content"] for doc in self._kb_docs]
self._tfidf_vectorizer = TfidfVectorizer(
stop_words = "english",
ngram_range = (1, 2), # unigrams + bigrams
max_features = 5000,
)
self._tfidf_matrix = self._tfidf_vectorizer.fit_transform(corpus)
logger.info(f"TF-IDF index built | {len(corpus)} docs | "
f"{self._tfidf_matrix.shape[1]} features | ~0ms query time")
except Exception as e:
logger.warning(f"TF-IDF index failed: {e}")
self._tfidf_matrix = None
# ═════════════════════════════════════════════════════════════════════════
# PATH A β€” Investor exact lookup (instant)
# ═════════════════════════════════════════════════════════════════════════
def get_investor(
self,
pan: Optional[str] = None,
investor_id: Optional[str] = None,
query: str = "",
) -> Optional[dict]:
"""Exact match only β€” never guesses. Returns None if no identifier."""
if not self._investors:
return None
if pan:
for inv in self._investors:
if inv["pan"] == pan.upper().strip():
logger.info(f"PATH A: PAN match β†’ {inv['name']}")
return inv
if investor_id:
for inv in self._investors:
if inv["investor_id"] == investor_id.upper().strip():
logger.info(f"PATH A: ID match β†’ {inv['name']}")
return inv
if query:
q = query.upper()
for inv in self._investors:
if inv["pan"] in q or inv["investor_id"] in q:
logger.info(f"PATH A: keyword match β†’ {inv['name']}")
return inv
return None
# ═════════════════════════════════════════════════════════════════════════
# PATH B β€” Knowledge base TF-IDF search (~5ms, in-process)
# ═════════════════════════════════════════════════════════════════════════
async def search_knowledge(self, query: str, top_k: int = 2) -> str:
"""
TF-IDF cosine similarity search over knowledge base.
No API call, no model loading β€” runs in-process in ~5ms.
"""
if not SKLEARN_OK or self._tfidf_matrix is None or not query:
return self._keyword_fallback(query, top_k)
try:
q_vec = self._tfidf_vectorizer.transform([query])
scores = cosine_similarity(q_vec, self._tfidf_matrix)[0]
top_idx = scores.argsort()[::-1][:top_k]
chunks = []
for idx in top_idx:
if scores[idx] > 0.05: # Minimum relevance threshold
doc = self._kb_docs[idx]
chunks.append(f"[{doc['title']}]\n{doc['content']}")
logger.info(f"PATH B: '{doc['title']}' score={scores[idx]:.3f}")
if chunks:
return "\n\n".join(chunks)
except Exception as e:
logger.warning(f"TF-IDF search failed: {e}")
return self._keyword_fallback(query, top_k)
def _keyword_fallback(self, query: str, top_k: int) -> str:
"""Simple keyword overlap fallback if sklearn unavailable."""
if not self._kb_docs or not query:
return ""
query_words = set(re.findall(r'\w+', query.lower()))
scored = []
for doc in self._kb_docs:
doc_words = set(re.findall(r'\w+', doc["content"].lower()))
score = len(query_words & doc_words)
if score > 0:
scored.append((score, doc))
scored.sort(reverse=True)
chunks = [f"[{d['title']}]\n{d['content']}" for _, d in scored[:top_k]]
return "\n\n".join(chunks)
def get_all_investors(self) -> list[dict]:
return self._investors