krishibondhu-api / api /rag /vector_store.py
hodoly163's picture
Add DuckDB warehouse, Kuzu graph DB, Chroma vector store, sklearn forecast, LangGraph agent
5a121e4 verified
Raw History Blame Contribute Delete
2.34 kB
"""Chroma embedded vector store over the knowledge-base chunks.
Lexical TF-IDF vectors are stored as dense embeddings, so no model download is
needed. Any failure returns None and api.rag.store falls back to numpy cosine.
"""
from __future__ import annotations
import math
import re
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent.parent
_PATH = ROOT / "data" / "chroma"
_TOKEN = re.compile(r"[a-zA-Z\u0980-\u09FF]+")
def _tokens(s: str):
return _TOKEN.findall((s or "").lower())
class VectorStore:
def __init__(self, chunks, idf):
import chromadb
self.chunks = chunks
self.idf = idf
vocab = sorted({t for c in chunks for t in _tokens(c["full"])})
self.vocab = {t: i for i, t in enumerate(vocab)}
client = chromadb.PersistentClient(path=str(_PATH))
try:
client.delete_collection("krishi_kb")
except Exception:
pass
self.col = client.get_or_create_collection(
"krishi_kb", metadata={"hnsw:space": "cosine"}
)
self.col.add(
ids=[str(i) for i in range(len(chunks))],
documents=[c["text"] for c in chunks],
metadatas=[
{"idx": i, "doc": c["doc"], "title": c["title"], "context": c["context"]}
for i, c in enumerate(chunks)
],
embeddings=[self.embed(c["full"]) for c in chunks],
)
def embed(self, text: str):
tf = Counter(_tokens(text))
total = sum(tf.values()) or 1
vec = [0.0] * len(self.vocab)
for token, count in tf.items():
idx = self.vocab.get(token)
if idx is not None:
vec[idx] = (count / total) * self.idf.get(token, math.log(len(self.chunks) + 1) + 1.0)
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]
def query(self, text: str, n: int = 4):
res = self.col.query(
query_embeddings=[self.embed(text)],
n_results=max(1, n),
include=["metadatas", "distances"],
)
out = []
for meta, dist in zip(res["metadatas"][0], res["distances"][0]):
out.append({"idx": int(meta["idx"]), "score": round(1.0 - float(dist), 4)})
return out