cognitive-ai-tutor / backend /vector_store.py
codedawakening's picture
Update backend/vector_store.py
837bf6a verified
Raw History Blame Contribute Delete
6.83 kB
import os
from typing import List, Dict, Any
import hashlib
from datetime import datetime
class VectorStoreManager:
def __init__(self, persist_directory="./data/chroma_db", model_name="all-MiniLM-L6-v2"):
self.persist_directory = persist_directory
os.makedirs(persist_directory, exist_ok=True)
# Initialize embedding model
try:
from sentence_transformers import SentenceTransformer
self.embedding_model = SentenceTransformer(model_name)
self.embedding_available = True
print(f"βœ… Loaded embedding model: {model_name}")
except Exception as e:
print(f"⚠️ Could not load embedding model: {e}")
self.embedding_model = None
self.embedding_available = False
# Initialize ChromaDB with NEW API (correct way)
try:
import chromadb
print("πŸ”„ Initializing ChromaDB with new API...")
# NEW: Simple persistent client
self.client = chromadb.PersistentClient(path=persist_directory)
# Get or create collection
self.collection = self.client.get_or_create_collection(
name="knowledge_base",
metadata={"hnsw:space": "cosine"}
)
self.chroma_available = True
print(f"βœ… ChromaDB initialized successfully!")
print(f"βœ… Collection: {self.collection.name}")
print(f"βœ… Collection count: {self.collection.count()}")
except Exception as e:
print(f"❌ Error initializing vector store: {e}")
import traceback
traceback.print_exc()
self.client = None
self.collection = None
self.chroma_available = False
def is_ready(self) -> bool:
return self.embedding_available and self.chroma_available
def generate_embedding(self, text: str) -> List[float]:
if not self.embedding_available:
# Return dummy embedding
return [0.1] * 384
try:
return self.embedding_model.encode(text).tolist()
except:
return [0.1] * 384
def add_documents(self, documents: List[Dict]) -> bool:
print(f"πŸ“₯ Attempting to add {len(documents)} documents to vector store")
if not self.is_ready():
print("❌ Vector store not ready")
return False
try:
ids = []
embeddings = []
metadatas = []
documents_text = []
for i, doc in enumerate(documents):
text = doc.get("text", doc.get("content", ""))
if not text or not text.strip():
print(f"⚠️ Document {i}: Empty text, skipping")
continue
# Truncate very long text
if len(text) > 10000:
text = text[:10000]
print(f"πŸ“ Document {i}: Truncated to 10,000 chars")
# Generate unique ID
doc_id = f"doc_{i}_{hashlib.md5(text.encode()).hexdigest()[:8]}"
ids.append(doc_id)
# Generate embedding
embedding = self.generate_embedding(text)
embeddings.append(embedding)
# Store metadata
metadata = doc.get("metadata", {})
metadata.update({
"text_length": len(text),
"processed_at": datetime.now().isoformat(),
"source": metadata.get("source", "unknown")
})
metadatas.append(metadata)
# Store text (truncated for display)
display_text = text[:200] + "..." if len(text) > 200 else text
documents_text.append(display_text)
print(f"βœ… Prepared document {i}: {len(text)} chars")
if not ids:
print("❌ No valid documents to add")
return False
print(f"πŸ“Š Adding {len(ids)} documents to collection...")
# Add to collection using new API
self.collection.add(
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents_text
)
print(f"πŸŽ‰ Successfully added {len(ids)} documents to vector store!")
print(f"πŸ“ˆ Total documents in collection: {self.collection.count()}")
return True
except Exception as e:
print(f"❌ Error adding documents: {str(e)}")
import traceback
traceback.print_exc()
return False
def similarity_search(self, query: str, k: int = 3) -> List[Dict]:
if not self.is_ready():
print("⚠️ Vector store not ready, returning simulated results")
# Return simulated results
return [
{
"document": "This is a simulated response. Upload documents to get real answers.",
"score": 0.95,
"metadata": {"source": "demo", "type": "simulated"}
}
]
try:
print(f"πŸ” Searching for: '{query}'")
# Generate query embedding
query_embedding = self.generate_embedding(query)
# Query the collection
results = self.collection.query(
query_embeddings=[query_embedding],
n_results=min(k, 5),
include=["documents", "metadatas", "distances"]
)
if not results["documents"] or not results["documents"][0]:
print("⚠️ No results found in vector store")
return []
formatted_results = []
for doc, meta, distance in zip(
results["documents"][0],
results["metadatas"][0],
results["distances"][0]
):
formatted_results.append({
"document": doc,
"metadata": meta,
"score": 1 - distance if distance else 0.9
})
print(f"βœ… Found {len(formatted_results)} relevant documents")
return formatted_results
except Exception as e:
print(f"❌ Search error: {str(e)}")
import traceback
traceback.print_exc()
return []