File size: 7,991 Bytes
14c2543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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: "<id>: <text>"
        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()