import os import json import numpy as np import pickle import time from typing import List, Dict, Any, Tuple from pathlib import Path from dotenv import load_dotenv import faiss from rank_bm25 import BM25Okapi from sentence_transformers import CrossEncoder import torch from openai import OpenAI # Load environment variables for API keys load_dotenv() # Initialize OpenAI client client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY')) # Define paths BASE_DIR = Path(os.path.dirname(os.path.abspath(__file__))) INDEX_DIR = BASE_DIR / 'index' os.makedirs(INDEX_DIR, exist_ok=True) # Define file paths VECTORS_FILE = INDEX_DIR / 'vectors.faiss' BM25_FILE = INDEX_DIR / 'bm25_index.pkl' CHUNKS_FILE = INDEX_DIR / 'chunks.json' #This cames from the first step RAG_CHUNKS_FILE = BASE_DIR / 'rag_ingested_chunks.json' #at the end is my chunks.json # Initialize cross-encoder for reranking cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2') #IM not using this fucntion because I've replaced for IndexFlatIP # Create FAISS index #def cosine_similarity(a, b): #Calculate cosine similarity between two vectors # return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) def reciprocal_rank_fusion(rank_lists, k=60): """ Implement Reciprocal Rank Fusion to combine multiple ranked lists Args: rank_lists: List of lists, each inner list contains dicts with 'id', 'text', and other metadata k: Constant in RRF formula, typically set to 60 Returns: List of dicts with combined RRF scores """ from collections import defaultdict # Track all unique chunks across all lists all_chunks = {} chunk_to_ranks = defaultdict(list) # Process each ranked list for rank_list in rank_lists: for rank, chunk in enumerate(rank_list): chunk_id = chunk['id'] # Store the chunk data if we haven't seen it yet if chunk_id not in all_chunks: all_chunks[chunk_id] = chunk # Store the rank from this list chunk_to_ranks[chunk_id].append(rank + 1) # +1 because RRF uses 1-based ranks # Calculate RRF scores for each chunk rrf_scores = {} for chunk_id, ranks in chunk_to_ranks.items(): # For each chunk, calculate the RRF score across all lists rrf_score = sum(1.0 / (k + r) for r in ranks) rrf_scores[chunk_id] = rrf_score # Create the final combined list combined_results = [] for chunk_id, score in sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True): result = all_chunks[chunk_id].copy() result['rrf_score'] = score combined_results.append(result) return combined_results def rerank_with_cross_encoder(query, results, top_k=10): """ Rerank results using a cross-encoder model Args: query: The user query results: List of result dicts with 'id' and 'text' fields top_k: Number of top results to return after reranking Returns: Reranked list of results """ if not results: return [] # Prepare pairs for the cross-encoder pairs = [(query, result['text']) for result in results] # Get scores from the cross-encoder scores = cross_encoder.predict(pairs) # Add scores to results for i, result in enumerate(results): result['cross_encoder_score'] = float(scores[i]) # Sort by cross-encoder score reranked_results = sorted(results, key=lambda x: x['cross_encoder_score'], reverse=True) # Return top-k results return reranked_results[:top_k] def format_context(results, max_tokens=3000): """ Format the retrieved chunks into a context string for the LLM Args: results: List of result dicts with 'id' and 'text' fields max_tokens: Maximum number of tokens to include in the context Returns: Formatted context string """ context_parts = [] current_tokens = 0 for result in results: # Format: ": " chunk_text = f"{result['id']}: {result['text']}" # Approximate token count (4 chars ~= 1 token) chunk_tokens = len(chunk_text) // 4 if current_tokens + chunk_tokens > max_tokens: break context_parts.append(chunk_text) current_tokens += chunk_tokens return "\n\n---\n\n".join(context_parts) def tokenize_text(text): """Simple tokenization for BM25""" return text.lower().split() def create_vector_index(chunks): """Create a FAISS index from chunk embeddings""" # Extract embeddings from chunks embeddings = [chunk['embedding'] for chunk in chunks] # Convert to numpy array embeddings_array = np.array(embeddings).astype('float32') # Get dimensionality of embeddings dimension = embeddings_array.shape[1] # Create FAISS index index = faiss.IndexFlatIP(dimension) # Inner product (cosine similarity for normalized vectors) index.add(embeddings_array) return index def create_bm25_index(chunks): """Create a BM25 index from chunk texts""" # Extract texts from chunks texts = [chunk['text'] for chunk in chunks] # Tokenize texts tokenized_texts = [tokenize_text(text) for text in texts] # Create BM25 index bm25_index = BM25Okapi(tokenized_texts) return bm25_index def main(): """ Main function to load chunks, create indices, and demonstrate retrieval """ print("Loading chunks from rag_ingested_chunks.json...") # Load chunks from file try: with open(RAG_CHUNKS_FILE, 'r', encoding='utf-8') as f: chunks = json.load(f) print(f"Loaded {len(chunks)} chunks") except Exception as e: print(f"Error loading chunks: {e}") return # Create vector index print("Creating vector index...") vector_index = create_vector_index(chunks) # Create BM25 index print("Creating BM25 index...") bm25_index = create_bm25_index(chunks) # Save indices print("Saving indices...") faiss.write_index(vector_index, str(VECTORS_FILE)) with open(BM25_FILE, 'wb') as f: pickle.dump(bm25_index, f) # Save chunks to index directory for the chat application with open(CHUNKS_FILE, 'w', encoding='utf-8') as f: json.dump(chunks, f, indent=2) print(f"Indices and chunks saved to {INDEX_DIR}") print("Processing complete. You can now run the chat application (3new_chat.py).") class HybridRetriever: def __init__(self): self.vector_index = None self.bm25_index = None self.chunks = [] def fit(self, chunks): """Fit the retriever with text chunks""" # Simple chunking - you might want to add embeddings here self.chunks = [{"id": i, "text": chunk} for i, chunk in enumerate(chunks)] # Create BM25 index texts = [chunk["text"] for chunk in self.chunks] tokenized_texts = [tokenize_text(text) for text in texts] self.bm25_index = BM25Okapi(tokenized_texts) def retrieve(self, query, top_k=5): """Retrieve relevant chunks using BM25""" if not self.bm25_index: return [] # Tokenize query query_tokens = tokenize_text(query) # Get BM25 scores scores = self.bm25_index.get_scores(query_tokens) # Get top-k results top_indices = np.argsort(scores)[-top_k:][::-1] return [self.chunks[i]["text"] for i in top_indices] if __name__ == "__main__": main()