Ajaykanth Maddi commited on
Commit ·
023441b
1
Parent(s): 996f416
Added RAGSystem Class and imports.
Browse files- app.py +4 -0
- ragbench.py +201 -1
- requirements.txt +6 -1
app.py
CHANGED
|
@@ -145,6 +145,8 @@ def plot_subset_metrics(subset_name):
|
|
| 145 |
|
| 146 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 147 |
bars = ax.bar(keys, values, color='skyblue')
|
|
|
|
|
|
|
| 148 |
|
| 149 |
# ✅ Add count on top of bars
|
| 150 |
ax.bar_label(bars, fmt='%.0f', padding=3)
|
|
@@ -172,6 +174,8 @@ def plot_chunking_strategies(subset_name):
|
|
| 172 |
plt.text(bar.get_x() + bar.get_width()/2, yval + 20, int(yval), ha='center', va='bottom', fontsize=10)
|
| 173 |
|
| 174 |
# plt.xlabel("Chunking Strategies")
|
|
|
|
|
|
|
| 175 |
plt.ylabel("Number of Chunks")
|
| 176 |
plt.title(f"Chunking Strategy Distribution - {subset_name}")
|
| 177 |
plt.xticks(rotation=30)
|
|
|
|
| 145 |
|
| 146 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 147 |
bars = ax.bar(keys, values, color='skyblue')
|
| 148 |
+
plt.tight_layout() # Apply tight layout after plotting
|
| 149 |
+
|
| 150 |
|
| 151 |
# ✅ Add count on top of bars
|
| 152 |
ax.bar_label(bars, fmt='%.0f', padding=3)
|
|
|
|
| 174 |
plt.text(bar.get_x() + bar.get_width()/2, yval + 20, int(yval), ha='center', va='bottom', fontsize=10)
|
| 175 |
|
| 176 |
# plt.xlabel("Chunking Strategies")
|
| 177 |
+
plt.tight_layout() # Apply tight layout after plotting
|
| 178 |
+
|
| 179 |
plt.ylabel("Number of Chunks")
|
| 180 |
plt.title(f"Chunking Strategy Distribution - {subset_name}")
|
| 181 |
plt.xticks(rotation=30)
|
ragbench.py
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
import re
|
| 5 |
from dataclasses import dataclass
|
| 6 |
+
from nltk.tokenize import sent_tokenize
|
| 7 |
+
from langchain.document_loaders import Document as LangchainDocument
|
| 8 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 9 |
+
from langchain.vectorstores import FAISS
|
| 10 |
+
from langchain.retrievers import BM25Retriever, EnsembleRetriever
|
| 11 |
+
from langchain.chat_models import InferenceClient
|
| 12 |
+
|
| 13 |
|
| 14 |
# Define document structure
|
| 15 |
|
|
|
|
| 28 |
source: str
|
| 29 |
chunk_num: int
|
| 30 |
total_chunks: int
|
| 31 |
+
metadata: dict
|
| 32 |
+
|
| 33 |
+
class RAGSystem:
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
subset: str,
|
| 37 |
+
dataset_type: str,
|
| 38 |
+
strategy: str,
|
| 39 |
+
chunks: List[Chunk],
|
| 40 |
+
chunk_size: int = 512,
|
| 41 |
+
chunk_overlap: int = 50,
|
| 42 |
+
generator_model_name: str = "mistralai/Mistral-7B-Instruct-v0.2",
|
| 43 |
+
retriever_model_name: str = "BAAI/bge-large-en-v1.5",
|
| 44 |
+
hf_api_token: str = None
|
| 45 |
+
):
|
| 46 |
+
self.subset = subset
|
| 47 |
+
self.dataset_type = dataset_type
|
| 48 |
+
self.strategy = strategy
|
| 49 |
+
self.chunk_size = chunk_size
|
| 50 |
+
self.chunk_overlap = chunk_overlap
|
| 51 |
+
self.generator_model_name = generator_model_name
|
| 52 |
+
self.retriever_model_name = retriever_model_name
|
| 53 |
+
self.chunks = chunks
|
| 54 |
+
self.hf_api_token = hf_api_token or os.getenv("HF_API_TOKEN")
|
| 55 |
+
|
| 56 |
+
# Initialize components
|
| 57 |
+
self.vector_store = None
|
| 58 |
+
self.embedder = None
|
| 59 |
+
self.hybrid_retriever = None
|
| 60 |
+
self.generator_client = None
|
| 61 |
+
|
| 62 |
+
# Set up API-based generator
|
| 63 |
+
self._init_generator_api()
|
| 64 |
+
|
| 65 |
+
def _init_generator_api(self):
|
| 66 |
+
self.generator_client = InferenceClient(
|
| 67 |
+
model=self.generator_model_name,
|
| 68 |
+
token=self.hf_api_token,
|
| 69 |
+
timeout=120,
|
| 70 |
+
headers={"x-use-cache": "0"}
|
| 71 |
+
)
|
| 72 |
+
self.generation_params = {
|
| 73 |
+
"max_new_tokens": 512,
|
| 74 |
+
"temperature": 0.7,
|
| 75 |
+
"top_p": 0.95,
|
| 76 |
+
"repetition_penalty": 1.1
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
def load_embeddings_database(self):
|
| 80 |
+
"""Load pre-built FAISS index and retrievers"""
|
| 81 |
+
basepath = "/kaggle/input/rag26-emanual"
|
| 82 |
+
fName = basepath + f"/faiss_index_{self.subset}_{self.dataset_type}_{self.strategy}"
|
| 83 |
+
|
| 84 |
+
if not self.embedder:
|
| 85 |
+
self.embedder = HuggingFaceEmbeddings(model_name=self.retriever_model_name)
|
| 86 |
+
|
| 87 |
+
if os.path.exists(fName):
|
| 88 |
+
self.vector_store = FAISS.load_local(fName, self.embedder, allow_dangerous_deserialization=True)
|
| 89 |
+
else:
|
| 90 |
+
print(f"FAISS index not found at: {fName}")
|
| 91 |
+
self.store_embeddings_database()
|
| 92 |
+
|
| 93 |
+
# Load langchain_docs for BM25
|
| 94 |
+
docs_path = os.path.join(fName, "langchain_docs.pkl")
|
| 95 |
+
if os.path.exists(docs_path):
|
| 96 |
+
with open(docs_path, "rb") as f:
|
| 97 |
+
langchain_docs = pickle.load(f)
|
| 98 |
+
bm25 = BM25Retriever.from_documents(langchain_docs)
|
| 99 |
+
bm25.k = 20
|
| 100 |
+
|
| 101 |
+
self.hybrid_retriever = EnsembleRetriever(
|
| 102 |
+
retrievers=[
|
| 103 |
+
self.vector_store.as_retriever(search_kwargs={"k": 20}),
|
| 104 |
+
bm25
|
| 105 |
+
],
|
| 106 |
+
weights=[0.7, 0.3]
|
| 107 |
+
)
|
| 108 |
+
else:
|
| 109 |
+
print(f"[⚠️] docs.pkl not found at {docs_path}, using only FAISS retriever.")
|
| 110 |
+
self.hybrid_retriever = self.vector_store.as_retriever(search_kwargs={"k": 20})
|
| 111 |
+
|
| 112 |
+
def store_embeddings_database(self, save_faiss: bool = True):
|
| 113 |
+
"""Build and store FAISS index from chunks"""
|
| 114 |
+
if not self.embedder:
|
| 115 |
+
self.embedder = HuggingFaceEmbeddings(model_name=self.retriever_model_name)
|
| 116 |
+
|
| 117 |
+
index_path = f"./faiss_index_{self.subset}_{self.dataset_type}_{self.strategy}"
|
| 118 |
+
|
| 119 |
+
if os.path.exists(f"{index_path}/index.faiss"):
|
| 120 |
+
print(f"📂 Reusing existing FAISS index")
|
| 121 |
+
self.vector_store = FAISS.load_local(index_path, self.embedder)
|
| 122 |
+
else:
|
| 123 |
+
print(f"⚙️ Building new FAISS index")
|
| 124 |
+
|
| 125 |
+
langchain_docs = [
|
| 126 |
+
LangchainDocument(
|
| 127 |
+
page_content=chunk.text,
|
| 128 |
+
metadata={
|
| 129 |
+
**chunk.metadata,
|
| 130 |
+
"chunk_id": chunk.chunk_id,
|
| 131 |
+
"doc_id": chunk.doc_id,
|
| 132 |
+
"source": chunk.source,
|
| 133 |
+
"chunk_num": chunk.chunk_num,
|
| 134 |
+
"total_chunks": chunk.total_chunks
|
| 135 |
+
}
|
| 136 |
+
) for chunk in self.chunks
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
self.vector_store = FAISS.from_documents(langchain_docs, self.embedder)
|
| 140 |
+
|
| 141 |
+
if save_faiss:
|
| 142 |
+
os.makedirs(index_path, exist_ok=True)
|
| 143 |
+
self.vector_store.save_local(index_path)
|
| 144 |
+
with open(f"{index_path}/langchain_docs.pkl", "wb") as f:
|
| 145 |
+
pickle.dump(langchain_docs, f)
|
| 146 |
+
|
| 147 |
+
# Initialize hybrid retriever
|
| 148 |
+
bm25 = BM25Retriever.from_documents([
|
| 149 |
+
LangchainDocument(page_content=chunk.text, metadata=chunk.metadata)
|
| 150 |
+
for chunk in self.chunks
|
| 151 |
+
])
|
| 152 |
+
bm25.k = 20
|
| 153 |
+
|
| 154 |
+
self.hybrid_retriever = EnsembleRetriever(
|
| 155 |
+
retrievers=[self.vector_store.as_retriever(search_kwargs={"k": 20}), bm25],
|
| 156 |
+
weights=[0.7, 0.3]
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
def generate_hypothetical_answer(self, question: str) -> str:
|
| 160 |
+
"""Generate HYDE hypothetical answer using API"""
|
| 161 |
+
prompt = f"Generate a detailed hypothetical answer for: {question}"
|
| 162 |
+
return self._generate_with_api(prompt, max_new_tokens=100)
|
| 163 |
+
|
| 164 |
+
def _generate_with_api(self, prompt: str, **kwargs) -> str:
|
| 165 |
+
"""Generate text using HF Inference API with correct parameters"""
|
| 166 |
+
# Default parameters compatible with the API
|
| 167 |
+
params = {
|
| 168 |
+
"max_tokens": kwargs.get("max_tokens", 512), # Note: 'max_tokens' not 'max_new_tokens'
|
| 169 |
+
"temperature": kwargs.get("temperature", 0.7),
|
| 170 |
+
"top_p": kwargs.get("top_p", 0.95),
|
| 171 |
+
# Note: 'repetition_penalty' is not available in chat_completion()
|
| 172 |
+
# Use 'top_k' instead if needed
|
| 173 |
+
# "top_k": kwargs.get("top_k", 50)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
try:
|
| 177 |
+
response = self.generator_client.chat_completion(
|
| 178 |
+
messages=[{"role": "user", "content": prompt}],
|
| 179 |
+
**params
|
| 180 |
+
)
|
| 181 |
+
return response.choices[0].message.content
|
| 182 |
+
except Exception as e:
|
| 183 |
+
print(f"Generation failed: {str(e)}")
|
| 184 |
+
return "I couldn't generate an answer."
|
| 185 |
+
|
| 186 |
+
def retrieve(self, query: str, top_k: int = 10) -> List[Chunk]:
|
| 187 |
+
"""Retrieve relevant chunks using HYDE"""
|
| 188 |
+
pseudo_answer = self.generate_hypothetical_answer(query)
|
| 189 |
+
docs = self.hybrid_retriever.invoke(pseudo_answer)
|
| 190 |
+
return [
|
| 191 |
+
Chunk(
|
| 192 |
+
chunk_id=doc.metadata.get("chunk_id", ""),
|
| 193 |
+
text=doc.page_content,
|
| 194 |
+
doc_id=doc.metadata.get("doc_id", ""),
|
| 195 |
+
source=doc.metadata.get("source", ""),
|
| 196 |
+
chunk_num=doc.metadata.get("chunk_num", -1),
|
| 197 |
+
total_chunks=doc.metadata.get("total_chunks", -1),
|
| 198 |
+
metadata=doc.metadata
|
| 199 |
+
) for doc in docs[:top_k]
|
| 200 |
+
]
|
| 201 |
+
|
| 202 |
+
def generate(self, question: str, context: List[str] = None) -> str:
|
| 203 |
+
"""Generate final answer with RAG context"""
|
| 204 |
+
if context is None:
|
| 205 |
+
retrieved_chunks = self.retrieve(question)
|
| 206 |
+
context = [chunk.text for chunk in retrieved_chunks]
|
| 207 |
+
|
| 208 |
+
formatted_context = "\n\n".join(context)
|
| 209 |
+
|
| 210 |
+
prompt = f"""[INST] You are a helpful assistant. Use *only* the context to answer.
|
| 211 |
+
If unsure, say "I don't know."
|
| 212 |
+
|
| 213 |
+
Context:
|
| 214 |
+
{formatted_context}
|
| 215 |
+
|
| 216 |
+
Question: {question}
|
| 217 |
+
|
| 218 |
+
Answer: [/INST]"""
|
| 219 |
+
|
| 220 |
+
return self._generate_with_api(prompt)
|
requirements.txt
CHANGED
|
@@ -17,4 +17,9 @@ scipy
|
|
| 17 |
pydantic
|
| 18 |
openai
|
| 19 |
nltk>=3.8.1
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
pydantic
|
| 18 |
openai
|
| 19 |
nltk>=3.8.1
|
| 20 |
+
langchain>=0.0.340
|
| 21 |
+
sentence-transformers>=2.2.2
|
| 22 |
+
faiss-cpu>=1.7.4 # or faiss-gpu if you have CUDA
|
| 23 |
+
rank_bm25>=0.2.1
|
| 24 |
+
huggingface-hub>=0.16.4
|
| 25 |
+
transformers>=4.33.3
|