File size: 7,687 Bytes
91651eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | """
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
|