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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified RAG System - Production Ready Implementation"""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
import chromadb
|
| 9 |
+
from chromadb.utils import embedding_functions
|
| 10 |
+
|
| 11 |
+
from utils.config import Config
|
| 12 |
+
from utils.data_models import RAGResponse, QueryType
|
| 13 |
+
from utils.evaluator import Evaluator
|
| 14 |
+
from utils.audit_logger import AuditLogger
|
| 15 |
+
from retrieval.hybrid_retriever import HybridRetriever
|
| 16 |
+
from retrieval.query_rewriter import QueryRewriter
|
| 17 |
+
from retrieval.generator import Generator
|
| 18 |
+
from reranking.reranker import Reranker
|
| 19 |
+
from reranking.dynamic_cutoff import DynamicCutoff
|
| 20 |
+
from reranking.mmr_diversifier import MMRDiversifier
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class UnifiedRAGSystem:
|
| 24 |
+
"""
|
| 25 |
+
Production-ready RAG system with all best practices:
|
| 26 |
+
- Query rewriting with step-back prompting
|
| 27 |
+
- Hybrid search (Dense + BM25)
|
| 28 |
+
- Cohere reranking
|
| 29 |
+
- Dynamic chunk selection
|
| 30 |
+
- MMR diversification
|
| 31 |
+
- Quality evaluation
|
| 32 |
+
- Comprehensive audit logging
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self):
|
| 36 |
+
"""Initialize the unified RAG system"""
|
| 37 |
+
print("Initializing RAG System...")
|
| 38 |
+
|
| 39 |
+
self.openai_client = OpenAI(api_key=Config.OPENAI_API_KEY)
|
| 40 |
+
|
| 41 |
+
with open(Config.CHUNKS_JSON, 'r', encoding='utf-8') as f:
|
| 42 |
+
self.chunks_data = json.load(f)
|
| 43 |
+
|
| 44 |
+
chroma_client = chromadb.PersistentClient(path=Config.CHROMA_PATH)
|
| 45 |
+
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
|
| 46 |
+
api_key=Config.OPENAI_API_KEY,
|
| 47 |
+
model_name="text-embedding-3-large"
|
| 48 |
+
)
|
| 49 |
+
self.chroma_collection = chroma_client.get_collection(
|
| 50 |
+
name=Config.COLLECTION_NAME,
|
| 51 |
+
embedding_function=openai_ef
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
self.query_rewriter = QueryRewriter(self.openai_client) if Config.ENABLE_QUERY_REWRITING else None
|
| 55 |
+
self.hybrid_retriever = HybridRetriever(self.chroma_collection, self.chunks_data)
|
| 56 |
+
self.reranker = Reranker(api_key=Config.COHERE_API_KEY)
|
| 57 |
+
self.generator = Generator(self.openai_client)
|
| 58 |
+
self.evaluator = Evaluator(self.openai_client) if Config.ENABLE_EVALUATION else None
|
| 59 |
+
self.audit_logger = AuditLogger() if Config.ENABLE_AUDIT else None
|
| 60 |
+
|
| 61 |
+
print("RAG System initialized successfully")
|
| 62 |
+
print(f" - Query Rewriting: {'Enabled' if Config.ENABLE_QUERY_REWRITING else 'Disabled'}")
|
| 63 |
+
print(f" - Cohere Reranking: {'Enabled' if Config.COHERE_API_KEY else 'Disabled'}")
|
| 64 |
+
print(f" - MMR Diversification: {'Enabled' if Config.ENABLE_MMR else 'Disabled'}")
|
| 65 |
+
print(f" - Evaluation: {'Enabled' if Config.ENABLE_EVALUATION else 'Disabled'}")
|
| 66 |
+
print(f" - Audit Logging: {'Enabled' if Config.ENABLE_AUDIT else 'Disabled'}")
|
| 67 |
+
|
| 68 |
+
def query(self, user_query: str, verbose: bool = True) -> RAGResponse:
|
| 69 |
+
"""
|
| 70 |
+
Execute complete RAG pipeline
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
user_query: User's question
|
| 74 |
+
verbose: Print progress information
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
RAGResponse with answer and metadata
|
| 78 |
+
"""
|
| 79 |
+
start_time = time.time()
|
| 80 |
+
session_id = str(uuid.uuid4())
|
| 81 |
+
|
| 82 |
+
if verbose:
|
| 83 |
+
print(f"\n{'='*80}")
|
| 84 |
+
print(f"Unified RAG Query")
|
| 85 |
+
print(f"{'='*80}")
|
| 86 |
+
print(f"Query: {user_query}")
|
| 87 |
+
|
| 88 |
+
analysis = self.query_rewriter.analyze_query(user_query) if self.query_rewriter else {
|
| 89 |
+
"type": QueryType.FACTUAL,
|
| 90 |
+
"expected_chunks": Config.FACTUAL_DEFAULT,
|
| 91 |
+
"needs_rewriting": False
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if verbose:
|
| 95 |
+
print(f"\nAnalysis: {analysis['type'].value if isinstance(analysis['type'], QueryType) else analysis['type']}")
|
| 96 |
+
|
| 97 |
+
retrieval_query = user_query
|
| 98 |
+
query_rewritten = False
|
| 99 |
+
|
| 100 |
+
if self.query_rewriter and Config.ENABLE_QUERY_REWRITING:
|
| 101 |
+
rewrite_result = self.query_rewriter.rewrite(user_query, analysis)
|
| 102 |
+
|
| 103 |
+
if rewrite_result["status"] == "rejected":
|
| 104 |
+
return RAGResponse(
|
| 105 |
+
query=user_query,
|
| 106 |
+
answer=f"I cannot answer this query. {rewrite_result['reason']}\n\nSuggestion: {rewrite_result['suggestion']}",
|
| 107 |
+
query_type="rejected",
|
| 108 |
+
num_chunks_used=0,
|
| 109 |
+
chunks=[],
|
| 110 |
+
cutoff_reason="rejected",
|
| 111 |
+
latency_ms=(time.time() - start_time) * 1000,
|
| 112 |
+
session_id=session_id,
|
| 113 |
+
timestamp=datetime.now().isoformat()
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if rewrite_result["use_stepback"]:
|
| 117 |
+
retrieval_query = rewrite_result["stepback_query"]
|
| 118 |
+
query_rewritten = True
|
| 119 |
+
if verbose:
|
| 120 |
+
print(f"Rewritten: {retrieval_query}")
|
| 121 |
+
|
| 122 |
+
candidates = self.hybrid_retriever.retrieve(retrieval_query, top_k=Config.INITIAL_CANDIDATES)
|
| 123 |
+
if verbose:
|
| 124 |
+
print(f"Retrieved: {len(candidates)} candidates")
|
| 125 |
+
|
| 126 |
+
reranked = self.reranker.rerank(retrieval_query, candidates, top_k=Config.RERANK_TOP_K)
|
| 127 |
+
if verbose:
|
| 128 |
+
print(f"Reranked: Top {len(reranked)} (scores: {[f'{r.score:.3f}' for r in reranked[:5]]})")
|
| 129 |
+
|
| 130 |
+
if Config.ENABLE_MMR and len(reranked) > 10:
|
| 131 |
+
reranked = MMRDiversifier.diversify(reranked, k=min(20, len(reranked)))
|
| 132 |
+
if verbose:
|
| 133 |
+
print(f"MMR: Diversified to {len(reranked)} chunks")
|
| 134 |
+
|
| 135 |
+
final_chunks, cutoff_reason = DynamicCutoff.determine_cutoff(
|
| 136 |
+
reranked,
|
| 137 |
+
analysis["expected_chunks"]
|
| 138 |
+
)
|
| 139 |
+
if verbose:
|
| 140 |
+
print(f"Cutoff: {len(final_chunks)} chunks ({cutoff_reason})")
|
| 141 |
+
|
| 142 |
+
context = self.generator.build_context(final_chunks)
|
| 143 |
+
answer = self.generator.generate_answer(user_query, context)
|
| 144 |
+
|
| 145 |
+
faithfulness_score = None
|
| 146 |
+
if self.evaluator and Config.ENABLE_EVALUATION:
|
| 147 |
+
faithfulness_score = self.evaluator.evaluate_faithfulness(answer, context)
|
| 148 |
+
if verbose:
|
| 149 |
+
print(f"Faithfulness: {faithfulness_score:.3f}")
|
| 150 |
+
|
| 151 |
+
latency_ms = (time.time() - start_time) * 1000
|
| 152 |
+
|
| 153 |
+
if self.audit_logger and Config.ENABLE_AUDIT:
|
| 154 |
+
self.audit_logger.log({
|
| 155 |
+
"timestamp": datetime.now().isoformat(),
|
| 156 |
+
"session_id": session_id,
|
| 157 |
+
"query": user_query,
|
| 158 |
+
"query_hash": self.audit_logger.hash_text(user_query),
|
| 159 |
+
"query_rewritten": query_rewritten,
|
| 160 |
+
"retrieval_query": retrieval_query,
|
| 161 |
+
"query_type": analysis["type"].value if isinstance(analysis["type"], QueryType) else str(analysis["type"]),
|
| 162 |
+
"num_chunks_used": len(final_chunks),
|
| 163 |
+
"cutoff_reason": cutoff_reason,
|
| 164 |
+
"faithfulness_score": faithfulness_score,
|
| 165 |
+
"latency_ms": latency_ms,
|
| 166 |
+
"answer_hash": self.audit_logger.hash_text(answer)
|
| 167 |
+
})
|
| 168 |
+
|
| 169 |
+
return RAGResponse(
|
| 170 |
+
query=user_query,
|
| 171 |
+
answer=answer,
|
| 172 |
+
query_type=analysis["type"].value if isinstance(analysis['type'], QueryType) else str(analysis['type']),
|
| 173 |
+
num_chunks_used=len(final_chunks),
|
| 174 |
+
chunks=[{
|
| 175 |
+
"id": c.chunk_id,
|
| 176 |
+
"score": c.score,
|
| 177 |
+
"page": c.page,
|
| 178 |
+
"rank": c.rank
|
| 179 |
+
} for c in final_chunks],
|
| 180 |
+
cutoff_reason=cutoff_reason,
|
| 181 |
+
latency_ms=latency_ms,
|
| 182 |
+
query_rewritten=query_rewritten,
|
| 183 |
+
retrieval_query=retrieval_query,
|
| 184 |
+
faithfulness_score=faithfulness_score,
|
| 185 |
+
session_id=session_id,
|
| 186 |
+
timestamp=datetime.now().isoformat()
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
"""Main function for testing"""
|
| 192 |
+
print("=" * 80)
|
| 193 |
+
print("Unified RAG System - Production Ready")
|
| 194 |
+
print("=" * 80)
|
| 195 |
+
|
| 196 |
+
rag = UnifiedRAGSystem()
|
| 197 |
+
|
| 198 |
+
test_queries = [
|
| 199 |
+
"What is the torque specification for the front shock absorber?",
|
| 200 |
+
"Summarize all suspension inspection procedures",
|
| 201 |
+
"How to replace the front coil spring?"
|
| 202 |
+
]
|
| 203 |
+
|
| 204 |
+
print("\n" + "=" * 80)
|
| 205 |
+
print("Running Test Queries")
|
| 206 |
+
print("=" * 80)
|
| 207 |
+
|
| 208 |
+
for query in test_queries:
|
| 209 |
+
print(f"\n{'='*80}")
|
| 210 |
+
print(f"Query: {query}")
|
| 211 |
+
print("=" * 80)
|
| 212 |
+
|
| 213 |
+
result = rag.query(query, verbose=True)
|
| 214 |
+
|
| 215 |
+
print(f"\nAnswer:")
|
| 216 |
+
print(result.answer)
|
| 217 |
+
|
| 218 |
+
print(f"\nMetadata:")
|
| 219 |
+
print(f" Query Type: {result.query_type}")
|
| 220 |
+
print(f" Chunks Used: {result.num_chunks_used}")
|
| 221 |
+
print(f" Cutoff Reason: {result.cutoff_reason}")
|
| 222 |
+
print(f" Latency: {result.latency_ms:.0f}ms")
|
| 223 |
+
if result.faithfulness_score:
|
| 224 |
+
print(f" Faithfulness: {result.faithfulness_score:.3f}")
|
| 225 |
+
print(f" Source Pages: {[c['page'] for c in result.chunks]}")
|
| 226 |
+
|
| 227 |
+
print("\n" + "=" * 80)
|
| 228 |
+
print("Interactive Mode (type 'exit' to quit)")
|
| 229 |
+
print("=" * 80)
|
| 230 |
+
|
| 231 |
+
while True:
|
| 232 |
+
user_input = input("\nYour question: ").strip()
|
| 233 |
+
if user_input.lower() in ['exit', 'quit', 'q']:
|
| 234 |
+
break
|
| 235 |
+
|
| 236 |
+
if not user_input:
|
| 237 |
+
continue
|
| 238 |
+
|
| 239 |
+
result = rag.query(user_input, verbose=True)
|
| 240 |
+
print(f"\nAnswer:\n{result.answer}")
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
main()
|