DhiGrowth_FAQ_RAG / src /embed_loader.py
mathanmithun's picture
Upload 39 files
f45a28c verified
Raw History Blame Contribute Delete
8.09 kB
"""
STEP 4 — CREATE VECTOR DATABASE
Loads data from JSONL, creates embeddings, and stores in ChromaDB
"""
import os
import sys
import json
from pathlib import Path
# Add parent directory to path for imports
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from sentence_transformers import SentenceTransformer
import chromadb
from logger_config import setup_logger
import config
logger = setup_logger(__name__)
def load_data(file_path):
"""
Load data from JSONL file
Args:
file_path: Path to JSONL file
Returns:
list: List of parsed JSON objects
"""
try:
logger.info(f"Loading data from: {file_path}")
data = []
with open(file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
try:
item = json.loads(line.strip())
data.append(item)
except json.JSONDecodeError as e:
logger.warning(f"Skipping invalid JSON on line {line_num}: {str(e)}")
continue
logger.info(f"Loaded {len(data)} items from JSONL file")
return data
except FileNotFoundError:
logger.error(f"Data file not found: {file_path}")
raise
except Exception as e:
logger.error(f"Error loading data: {str(e)}", exc_info=True)
raise
def extract_chunks(data):
"""
Extract assistant message content from data
Args:
data: List of JSON objects with messages
Returns:
list: List of text chunks (assistant messages)
"""
try:
logger.info("Extracting assistant messages from data")
chunks = []
for item in data:
if "messages" not in item:
logger.warning("Item missing 'messages' key, skipping")
continue
for msg in item["messages"]:
if msg.get("role") == "assistant":
content = msg.get("content", "").strip()
if content: # Only add non-empty content
chunks.append(content)
logger.info(f"Extracted {len(chunks)} chunks from data")
return chunks
except Exception as e:
logger.error(f"Error extracting chunks: {str(e)}", exc_info=True)
raise
def create_embeddings(chunks, embedder):
"""
Create embeddings for text chunks
Args:
chunks: List of text chunks
embedder: SentenceTransformer model
Returns:
list: List of embedding vectors
"""
try:
if not chunks:
logger.warning("No chunks to embed")
return []
logger.info(f"Creating embeddings for {len(chunks)} chunks...")
embeddings = embedder.encode(chunks, show_progress_bar=True, convert_to_numpy=True)
embeddings_list = embeddings.tolist()
logger.info(f"Created {len(embeddings_list)} embeddings")
return embeddings_list
except Exception as e:
logger.error(f"Error creating embeddings: {str(e)}", exc_info=True)
raise
def store_in_chromadb(chunks, embeddings, collection):
"""
Store chunks and embeddings in ChromaDB
Args:
chunks: List of text chunks
embeddings: List of embedding vectors
collection: ChromaDB collection object
"""
try:
if not chunks or not embeddings:
logger.warning("No chunks or embeddings to store")
return
if len(chunks) != len(embeddings):
logger.error(f"Mismatch: {len(chunks)} chunks but {len(embeddings)} embeddings")
raise ValueError("Chunks and embeddings must have the same length")
logger.info(f"Storing {len(chunks)} documents in ChromaDB...")
# Check if collection already has data
existing_count = collection.count()
if existing_count > 0:
logger.warning(f"Collection already contains {existing_count} documents")
logger.info("Adding new documents to existing collection")
# Start IDs from existing count to avoid conflicts
start_id = existing_count
else:
start_id = 0
# Prepare data for batch insertion
ids = [str(i + start_id) for i in range(len(chunks))]
documents = chunks
embeddings_list = embeddings
# Add in batches to handle large datasets
batch_size = 100
total_batches = (len(chunks) + batch_size - 1) // batch_size
for batch_idx in range(0, len(chunks), batch_size):
batch_ids = ids[batch_idx:batch_idx + batch_size]
batch_docs = documents[batch_idx:batch_idx + batch_size]
batch_embeddings = embeddings_list[batch_idx:batch_idx + batch_size]
collection.add(
ids=batch_ids,
documents=batch_docs,
embeddings=batch_embeddings
)
current_batch = (batch_idx // batch_size) + 1
logger.info(f"Stored batch {current_batch}/{total_batches} ({len(batch_ids)} documents)")
final_count = collection.count()
logger.info(f"Successfully stored {final_count} documents in ChromaDB")
except Exception as e:
logger.error(f"Error storing in ChromaDB: {str(e)}", exc_info=True)
raise
def create_vector_database():
"""
Main function to create the vector database
"""
try:
logger.info("=" * 60)
logger.info("Starting vector database creation")
logger.info("=" * 60)
# Initialize embedder
logger.info(f"Loading embedding model: {config.EMBEDDING_MODEL}")
embedder = SentenceTransformer(config.EMBEDDING_MODEL)
logger.info("Embedding model loaded successfully")
# Initialize ChromaDB
logger.info(f"Initializing ChromaDB at: {config.EMBEDDINGS_PATH}")
db = chromadb.PersistentClient(path=config.EMBEDDINGS_PATH)
collection = db.get_or_create_collection(
name="dhigrowth",
metadata={"description": "Dhigrowth RAG knowledge base"}
)
logger.info("ChromaDB collection ready")
# Load data
data_path = Path(config.DATA_PATH)
if not data_path.exists():
logger.error(f"Data file does not exist: {data_path}")
raise FileNotFoundError(f"Data file not found: {data_path}")
data = load_data(data_path)
if not data:
logger.error("No data loaded from file")
raise ValueError("No data to process")
# Extract chunks
chunks = extract_chunks(data)
if not chunks:
logger.error("No chunks extracted from data")
raise ValueError("No chunks to embed")
# Create embeddings
embeddings = create_embeddings(chunks, embedder)
if not embeddings:
logger.error("No embeddings created")
raise ValueError("Failed to create embeddings")
# Store in ChromaDB
store_in_chromadb(chunks, embeddings, collection)
logger.info("=" * 60)
logger.info("Vector database creation complete!")
logger.info("=" * 60)
return True
except Exception as e:
logger.error(f"Failed to create vector database: {str(e)}", exc_info=True)
return False
if __name__ == "__main__":
"""
Run this script to create the vector database
Usage: python src/embed_loader.py
"""
success = create_vector_database()
sys.exit(0 if success else 1)