Spaces:
Running
Running
File size: 36,361 Bytes
ed28876 |
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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 |
# RAG_Library.py
#########################################
# RAG Search & Related Functions Library
# This library is used to hold any/all RAG-related operations.
# Currently, all of this code was generated from Sonnet 3.5. 0_0
#
####
import os
from typing import List, Tuple, Callable, Optional
from contextlib import contextmanager
import sqlite3
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import logging
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class RAGException(Exception):
"""Custom exception class for RAG-related errors"""
pass
class BaseRAGSystem:
def __init__(self, db_path: str, model_name: Optional[str] = None):
"""
Initialize the RAG system.
:param db_path: Path to the SQLite database
:param model_name: Name of the SentenceTransformer model to use
"""
self.db_path = db_path
self.model_name = model_name or os.getenv('DEFAULT_MODEL_NAME', 'all-MiniLM-L6-v2')
try:
self.model = SentenceTransformer(self.model_name)
logger.info(f"Initialized SentenceTransformer with model: {self.model_name}")
except Exception as e:
logger.error(f"Failed to initialize SentenceTransformer: {e}")
raise RAGException(f"Model initialization failed: {e}")
self.init_db()
@contextmanager
def get_db_connection(self):
conn = sqlite3.connect(self.db_path)
try:
yield conn
finally:
conn.close()
def init_db(self):
try:
with self.get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY,
title TEXT,
content TEXT,
embedding BLOB
)
''')
conn.commit()
logger.info("Initialized database schema")
except sqlite3.Error as e:
logger.error(f"Failed to initialize database schema: {e}")
raise RAGException(f"Database schema initialization failed: {e}")
def add_documents(self, documents: List[Tuple[str, str]]):
try:
embeddings = self.model.encode([content for _, content in documents])
with self.get_db_connection() as conn:
cursor = conn.cursor()
cursor.executemany(
'INSERT INTO documents (title, content, embedding) VALUES (?, ?, ?)',
[(title, content, embedding.tobytes()) for (title, content), embedding in zip(documents, embeddings)]
)
conn.commit()
logger.info(f"Added {len(documents)} documents in batch")
except Exception as e:
logger.error(f"Failed to add documents in batch: {e}")
raise RAGException(f"Batch document addition failed: {e}")
def get_documents(self) -> List[Tuple[int, str, str, np.ndarray]]:
try:
with self.get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT id, title, content, embedding FROM documents')
documents = [(id, title, content, np.frombuffer(embedding, dtype=np.float32))
for id, title, content, embedding in cursor.fetchall()]
logger.info(f"Retrieved {len(documents)} documents")
return documents
except sqlite3.Error as e:
logger.error(f"Failed to retrieve documents: {e}")
raise RAGException(f"Document retrieval failed: {e}")
def close(self):
try:
self.conn.close()
logger.info("Closed database connection")
except sqlite3.Error as e:
logger.error(f"Error closing database connection: {e}")
class StandardRAGSystem(BaseRAGSystem):
def get_relevant_documents(self, query: str, top_k: int = 3) -> List[Tuple[int, str, str, float]]:
try:
query_embedding = self.model.encode([query])[0]
documents = self.get_documents()
similarities = [
(id, title, content, cosine_similarity([query_embedding], [doc_embedding])[0][0])
for id, title, content, doc_embedding in documents
]
similarities.sort(key=lambda x: x[3], reverse=True)
logger.info(f"Retrieved top {top_k} relevant documents for query")
return similarities[:top_k]
except Exception as e:
logger.error(f"Error in getting relevant documents: {e}")
raise RAGException(f"Retrieval of relevant documents failed: {e}")
def rag_query(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> str:
try:
relevant_docs = self.get_relevant_documents(query, top_k)
context = "\n\n".join([f"Title: {title}\nContent: {content}" for _, title, content, _ in relevant_docs])
llm_prompt = f"Based on the following context, please answer the query:\n\nContext:\n{context}\n\nQuery: {query}"
response = llm_function(llm_prompt)
logger.info("Generated response for query")
return response
except Exception as e:
logger.error(f"Error in RAG query: {e}")
raise RAGException(f"RAG query failed: {e}")
class HyDERAGSystem(BaseRAGSystem):
def generate_hypothetical_document(self, query: str, llm_function: Callable[[str], str]) -> str:
try:
prompt = f"Given the question '{query}', write a short paragraph that would answer this question. Do not include the question itself in your response."
hypothetical_doc = llm_function(prompt)
logger.info("Generated hypothetical document")
return hypothetical_doc
except Exception as e:
logger.error(f"Error generating hypothetical document: {e}")
raise RAGException(f"Hypothetical document generation failed: {e}")
def get_relevant_documents(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> List[
Tuple[int, str, str, float]]:
try:
hypothetical_doc = self.generate_hypothetical_document(query, llm_function)
hyde_embedding = self.model.encode([hypothetical_doc])[0]
documents = self.get_documents()
similarities = [
(id, title, content, cosine_similarity([hyde_embedding], [doc_embedding])[0][0])
for id, title, content, doc_embedding in documents
]
similarities.sort(key=lambda x: x[3], reverse=True)
logger.info(f"Retrieved top {top_k} relevant documents using HyDE")
return similarities[:top_k]
except Exception as e:
logger.error(f"Error in getting relevant documents with HyDE: {e}")
raise RAGException(f"HyDE retrieval of relevant documents failed: {e}")
def rag_query(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> str:
try:
relevant_docs = self.get_relevant_documents(query, llm_function, top_k)
context = "\n\n".join([f"Title: {title}\nContent: {content}" for _, title, content, _ in relevant_docs])
llm_prompt = f"Based on the following context, please answer the query:\n\nContext:\n{context}\n\nQuery: {query}"
response = llm_function(llm_prompt)
logger.info("Generated response for query using HyDE")
return response
except Exception as e:
logger.error(f"Error in HyDE RAG query: {e}")
raise RAGException(f"HyDE RAG query failed: {e}")
# Example usage with error handling
def mock_llm(prompt: str) -> str:
if "write a short paragraph" in prompt:
return "Paris, the capital of France, is renowned for its iconic Eiffel Tower and rich cultural heritage."
else:
return f"This is a mock LLM response for the prompt: {prompt}"
def main():
use_hyde = False # Set this to True when you want to enable HyDE
try:
if use_hyde:
rag_system = HyDERAGSystem('rag_database.db')
logger.info("Using HyDE RAG System")
else:
rag_system = StandardRAGSystem('rag_database.db')
logger.info("Using Standard RAG System")
# Add sample documents in batch
sample_docs = [
("Paris", "Paris is the capital of France and is known for the Eiffel Tower."),
("London", "London is the capital of the United Kingdom and home to Big Ben."),
("Tokyo", "Tokyo is the capital of Japan and is famous for its bustling city life.")
]
for title, content in sample_docs:
rag_system.add_document(title, content)
query = "What is the capital of France?"
result = rag_system.rag_query(query, mock_llm)
print(f"Query: {query}")
print(f"Result: {result}")
except RAGException as e:
logger.error(f"RAG system error: {e}")
print(f"An error occurred: {e}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
print(f"An unexpected error occurred: {e}")
finally:
if 'rag_system' in locals():
rag_system.close()
if __name__ == "__main__":
main()
####################################################################################
# async:
# import os
# import asyncio
# from typing import List, Tuple, Callable, Optional
# import aiosqlite
# import numpy as np
# from sentence_transformers import SentenceTransformer
# from sklearn.metrics.pairwise import cosine_similarity
# import logging
# from dotenv import load_dotenv
#
# load_dotenv()
#
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# logger = logging.getLogger(__name__)
#
#
# class RAGException(Exception):
# """Custom exception class for RAG-related errors"""
# pass
#
#
# class BaseRAGSystem:
# def __init__(self, db_path: str, model_name: Optional[str] = None):
# """
# Initialize the RAG system.
#
# :param db_path: Path to the SQLite database
# :param model_name: Name of the SentenceTransformer model to use
# """
# self.db_path = db_path
# self.model_name = model_name or os.getenv('DEFAULT_MODEL_NAME', 'all-MiniLM-L6-v2')
# try:
# self.model = SentenceTransformer(self.model_name)
# logger.info(f"Initialized SentenceTransformer with model: {self.model_name}")
# except Exception as e:
# logger.error(f"Failed to initialize SentenceTransformer: {e}")
# raise RAGException(f"Model initialization failed: {e}")
#
# async def init_db(self):
# try:
# async with aiosqlite.connect(self.db_path) as db:
# await db.execute('''
# CREATE TABLE IF NOT EXISTS documents (
# id INTEGER PRIMARY KEY,
# title TEXT,
# content TEXT,
# embedding BLOB
# )
# ''')
# await db.commit()
# logger.info("Initialized database schema")
# except aiosqlite.Error as e:
# logger.error(f"Failed to initialize database schema: {e}")
# raise RAGException(f"Database schema initialization failed: {e}")
#
# async def add_documents(self, documents: List[Tuple[str, str]]):
# try:
# embeddings = self.model.encode([content for _, content in documents])
# async with aiosqlite.connect(self.db_path) as db:
# await db.executemany(
# 'INSERT INTO documents (title, content, embedding) VALUES (?, ?, ?)',
# [(title, content, embedding.tobytes()) for (title, content), embedding in
# zip(documents, embeddings)]
# )
# await db.commit()
# logger.info(f"Added {len(documents)} documents in batch")
# except Exception as e:
# logger.error(f"Failed to add documents in batch: {e}")
# raise RAGException(f"Batch document addition failed: {e}")
#
# async def get_documents(self) -> List[Tuple[int, str, str, np.ndarray, str]]:
# try:
# async with aiosqlite.connect(self.db_path) as db:
# async with db.execute('SELECT id, title, content, embedding, source FROM documents') as cursor:
# documents = [
# (id, title, content, np.frombuffer(embedding, dtype=np.float32), source)
# async for id, title, content, embedding, source in cursor
# ]
# logger.info(f"Retrieved {len(documents)} documents")
# return documents
# except aiosqlite.Error as e:
# logger.error(f"Failed to retrieve documents: {e}")
# raise RAGException(f"Document retrieval failed: {e}")
#
#
# class AsyncStandardRAGSystem(BaseRAGSystem):
# async def get_relevant_documents(self, query: str, top_k: int = 3) -> List[Tuple[int, str, str, float]]:
# try:
# query_embedding = self.model.encode([query])[0]
# documents = await self.get_documents()
# similarities = [
# (id, title, content, cosine_similarity([query_embedding], [doc_embedding])[0][0])
# for id, title, content, doc_embedding in documents
# ]
# similarities.sort(key=lambda x: x[3], reverse=True)
# logger.info(f"Retrieved top {top_k} relevant documents for query")
# return similarities[:top_k]
# except Exception as e:
# logger.error(f"Error in getting relevant documents: {e}")
# raise RAGException(f"Retrieval of relevant documents failed: {e}")
#
# async def rag_query(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> str:
# try:
# relevant_docs = await self.get_relevant_documents(query, top_k)
# context = "\n\n".join([f"Title: {title}\nContent: {content}\nSource: {source}" for _, title, content, _, source in relevant_docs])
#
# llm_prompt = f"Based on the following context, please answer the query. Include citations in your response using [Source] format:\n\nContext:\n{context}\n\nQuery: {query}"
#
# response = llm_function(llm_prompt)
# logger.info("Generated response for query")
# return response
# except Exception as e:
# logger.error(f"Error in RAG query: {e}")
# raise RAGException(f"RAG query failed: {e}")
#
#
# class AsyncHyDERAGSystem(BaseRAGSystem):
# async def generate_hypothetical_document(self, query: str, llm_function: Callable[[str], str]) -> str:
# try:
# prompt = f"Given the question '{query}', write a short paragraph that would answer this question. Do not include the question itself in your response."
# hypothetical_doc = llm_function(prompt)
# logger.info("Generated hypothetical document")
# return hypothetical_doc
# except Exception as e:
# logger.error(f"Error generating hypothetical document: {e}")
# raise RAGException(f"Hypothetical document generation failed: {e}")
#
# async def get_relevant_documents(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> List[
# Tuple[int, str, str, float]]:
# try:
# hypothetical_doc = await self.generate_hypothetical_document(query, llm_function)
# hyde_embedding = self.model.encode([hypothetical_doc])[0]
#
# documents = await self.get_documents()
# similarities = [
# (id, title, content, cosine_similarity([hyde_embedding], [doc_embedding])[0][0])
# for id, title, content, doc_embedding in documents
# ]
# similarities.sort(key=lambda x: x[3], reverse=True)
# logger.info(f"Retrieved top {top_k} relevant documents using HyDE")
# return similarities[:top_k]
# except Exception as e:
# logger.error(f"Error in getting relevant documents with HyDE: {e}")
# raise RAGException(f"HyDE retrieval of relevant documents failed: {e}")
#
# async def rag_query(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> str:
# try:
# relevant_docs = await self.get_relevant_documents(query, llm_function, top_k)
# context = "\n\n".join([f"Title: {title}\nContent: {content}" for _, title, content, _ in relevant_docs])
#
# llm_prompt = f"Based on the following context, please answer the query:\n\nContext:\n{context}\n\nQuery: {query}"
#
# response = llm_function(llm_prompt)
# logger.info("Generated response for query using HyDE")
# return response
# except Exception as e:
# logger.error(f"Error in HyDE RAG query: {e}")
# raise RAGException(f"HyDE RAG query failed: {e}")
#
#
# # Example usage with error handling
# def mock_llm(prompt: str) -> str:
# if "write a short paragraph" in prompt:
# return "Paris, the capital of France, is renowned for its iconic Eiffel Tower and rich cultural heritage."
# else:
# return f"This is a mock LLM response for the prompt: {prompt}"
#
#
# async def main():
# use_hyde = False # Set this to True when you want to enable HyDE
#
# try:
# if use_hyde:
# rag_system = AsyncHyDERAGSystem('rag_database.db')
# logger.info("Using Async HyDE RAG System")
# else:
# rag_system = AsyncStandardRAGSystem('rag_database.db')
# logger.info("Using Async Standard RAG System")
#
# await rag_system.init_db()
#
# # Add sample documents
# sample_docs = [
# ("Paris", "Paris is the capital of France and is known for the Eiffel Tower."),
# ("London", "London is the capital of the United Kingdom and home to Big Ben."),
# ("Tokyo", "Tokyo is the capital of Japan and is famous for its bustling city life.")
# ]
#
# await rag_system.add_documents(sample_docs)
#
# query = "What is the capital of France?"
# result = await rag_system.rag_query(query, mock_llm)
# print(f"Query: {query}")
# print(f"Result: {result}")
#
# except RAGException as e:
# logger.error(f"RAG system error: {e}")
# print(f"An error occurred: {e}")
# except Exception as e:
# logger.error(f"Unexpected error: {e}")
# print(f"An unexpected error occurred: {e}")
#
#
# if __name__ == "__main__":
# asyncio.run(main())
#
# from fastapi import FastAPI, HTTPException
#
# app = FastAPI()
# rag_system = AsyncStandardRAGSystem('rag_database.db')
#
# @app.on_event("startup")
# async def startup_event():
# await rag_system.init_db()
#
# @app.get("/query")
# async def query(q: str):
# try:
# result = await rag_system.rag_query(q, mock_llm)
# return {"query": q, "result": result}
# except RAGException as e:
# raise HTTPException(status_code=500, detail=str(e))
#
############################################################################################
# Using FAISS
#
#
#
# Update DB
# async def init_db(self):
# try:
# async with aiosqlite.connect(self.db_path) as db:
# await db.execute('''
# CREATE TABLE IF NOT EXISTS documents (
# id INTEGER PRIMARY KEY,
# title TEXT,
# content TEXT,
# embedding BLOB,
# source TEXT
# )
# ''')
# await db.commit()
# logger.info("Initialized database schema")
# except aiosqlite.Error as e:
# logger.error(f"Failed to initialize database schema: {e}")
# raise RAGException(f"Database schema initialization failed: {e}")
#
#
# import os
# import asyncio
# from typing import List, Tuple, Callable, Optional
# import aiosqlite
# import numpy as np
# from sentence_transformers import SentenceTransformer
# import faiss
# import logging
# from dotenv import load_dotenv
#
# load_dotenv()
#
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# logger = logging.getLogger(__name__)
#
#
# class RAGException(Exception):
# """Custom exception class for RAG-related errors"""
# pass
#
#
# class AsyncFAISSRAGSystem:
# def __init__(self, db_path: str, model_name: Optional[str] = None):
# self.db_path = db_path
# self.model_name = model_name or os.getenv('DEFAULT_MODEL_NAME', 'all-MiniLM-L6-v2')
# try:
# self.model = SentenceTransformer(self.model_name)
# logger.info(f"Initialized SentenceTransformer with model: {self.model_name}")
# except Exception as e:
# logger.error(f"Failed to initialize SentenceTransformer: {e}")
# raise RAGException(f"Model initialization failed: {e}")
#
# self.index = None
# self.document_lookup = {}
#
# async def init_db(self):
# try:
# async with aiosqlite.connect(self.db_path) as db:
# await db.execute('''
# CREATE TABLE IF NOT EXISTS documents (
# id INTEGER PRIMARY KEY,
# title TEXT,
# content TEXT
# )
# ''')
# await db.commit()
# logger.info("Initialized database schema")
# except aiosqlite.Error as e:
# logger.error(f"Failed to initialize database schema: {e}")
# raise RAGException(f"Database schema initialization failed: {e}")
#
# async def add_documents(self, documents: List[Tuple[str, str, str]]):
# try:
# embeddings = self.model.encode([content for _, content, _ in documents])
# async with aiosqlite.connect(self.db_path) as db:
# await db.executemany(
# 'INSERT INTO documents (title, content, embedding, source) VALUES (?, ?, ?, ?)',
# [(title, content, embedding.tobytes(), source) for (title, content, source), embedding in
# zip(documents, embeddings)]
# )
# await db.commit()
# logger.info(f"Added {len(documents)} documents in batch")
# except Exception as e:
# logger.error(f"Failed to add documents in batch: {e}")
# raise RAGException(f"Batch document addition failed: {e}")
#
# async def get_relevant_documents(self, query: str, top_k: int = 3) -> List[Tuple[int, str, str, float, str]]:
# try:
# query_embedding = self.model.encode([query])[0]
# documents = await self.get_documents()
# similarities = [
# (id, title, content, cosine_similarity([query_embedding], [doc_embedding])[0][0], source)
# for id, title, content, doc_embedding, source in documents
# ]
# similarities.sort(key=lambda x: x[3], reverse=True)
# logger.info(f"Retrieved top {top_k} relevant documents for query")
# return similarities[:top_k]
# except Exception as e:
# logger.error(f"Error in getting relevant documents: {e}")
# raise RAGException(f"Retrieval of relevant documents failed: {e}")
#
# async def rag_query(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> str:
# try:
# relevant_docs = await self.get_relevant_documents(query, top_k)
# context = "\n\n".join([f"Title: {title}\nContent: {content}" for _, title, content, _ in relevant_docs])
#
# llm_prompt = f"Based on the following context, please answer the query:\n\nContext:\n{context}\n\nQuery: {query}"
#
# response = llm_function(llm_prompt)
# logger.info("Generated response for query")
# return response
# except Exception as e:
# logger.error(f"Error in RAG query: {e}")
# raise RAGException(f"RAG query failed: {e}")
#
#
# class AsyncFAISSHyDERAGSystem(AsyncFAISSRAGSystem):
# async def generate_hypothetical_document(self, query: str, llm_function: Callable[[str], str]) -> str:
# try:
# prompt = f"Given the question '{query}', write a short paragraph that would answer this question. Do not include the question itself in your response."
# hypothetical_doc = llm_function(prompt)
# logger.info("Generated hypothetical document")
# return hypothetical_doc
# except Exception as e:
# logger.error(f"Error generating hypothetical document: {e}")
# raise RAGException(f"Hypothetical document generation failed: {e}")
#
# async def get_relevant_documents(self, query: str, llm_function: Callable[[str], str], top_k: int = 3) -> List[
# Tuple[int, str, str, float]]:
# try:
# hypothetical_doc = await self.generate_hypothetical_document(query, llm_function)
# hyde_embedding = self.model.encode([hypothetical_doc])[0]
#
# distances, indices = self.index.search(np.array([hyde_embedding]), top_k)
#
# results = []
# for i, idx in enumerate(indices[0]):
# doc_id = list(self.document_lookup.keys())[idx]
# title, content = self.document_lookup[doc_id]
# results.append((doc_id, title, content, distances[0][i]))
#
# logger.info(f"Retrieved top {top_k} relevant documents using HyDE")
# return results
# except Exception as e:
# logger.error(f"Error in getting relevant documents with HyDE: {e}")
# raise RAGException(f"HyDE retrieval of relevant documents failed: {e}")
#
#
# # Example usage
# def mock_llm(prompt: str) -> str:
# if "write a short paragraph" in prompt:
# return "Paris, the capital of France, is renowned for its iconic Eiffel Tower and rich cultural heritage."
# else:
# return f"This is a mock LLM response for the prompt: {prompt}"
#
#
# async def main():
# use_hyde = False # Set this to True when you want to enable HyDE
#
# try:
# if use_hyde:
# rag_system = AsyncFAISSHyDERAGSystem('rag_database.db')
# logger.info("Using Async FAISS HyDE RAG System")
# else:
# rag_system = AsyncFAISSRAGSystem('rag_database.db')
# logger.info("Using Async FAISS RAG System")
#
# await rag_system.init_db()
#
# # Add sample documents
# sample_docs = [
# ("Paris", "Paris is the capital of France and is known for the Eiffel Tower."),
# ("London", "London is the capital of the United Kingdom and home to Big Ben."),
# ("Tokyo", "Tokyo is the capital of Japan and is famous for its bustling city life.")
# ]
#
# await rag_system.add_documents(sample_docs)
#
# query = "What is the capital of France?"
# result = await rag_system.rag_query(query, mock_llm)
# print(f"Query: {query}")
# print(f"Result: {result}")
#
# except RAGException as e:
# logger.error(f"RAG system error: {e}")
# print(f"An error occurred: {e}")
# except Exception as e:
# logger.error(f"Unexpected error: {e}")
# print(f"An unexpected error occurred: {e}")
#
#
# if __name__ == "__main__":
# asyncio.run(main())
"""
Key changes in this FAISS-integrated version:
We've replaced the cosine similarity search with FAISS indexing and search.
The add_documents method now adds embeddings to the FAISS index as well as storing documents in the SQLite database.
We maintain a document_lookup dictionary to quickly retrieve document content based on FAISS search results.
The get_relevant_documents method now uses FAISS for similarity search instead of computing cosine similarities manually.
We've kept the asynchronous structure for database operations, while FAISS operations remain synchronous (as FAISS doesn't have built-in async support).
Benefits of using FAISS:
Scalability: FAISS can handle millions of vectors efficiently, making it suitable for large document collections.
Speed: FAISS is optimized for fast similarity search, which can significantly improve query times as your dataset grows.
Memory Efficiency: FAISS provides various index types that can trade off between search accuracy and memory usage, allowing you to optimize for your specific use case.
Considerations:
This implementation uses a simple IndexFlatL2 FAISS index, which performs exact search. For larger datasets, you might want to consider approximate search methods like IndexIVFFlat for better scalability.
The current implementation keeps all document content in memory (in the document_lookup dictionary). For very large datasets, you might want to modify this to fetch document content from the database as needed.
If you're dealing with a very large number of documents, you might want to implement batch processing for adding documents to the FAISS index.
This FAISS-integrated version should provide better performance for similarity search, especially as your document collection grows larger
"""
###############################################################################################################
# Web Search
# Output from Sonnet 3.5 regarding how to add web searches to the RAG system
# Integrating web search into your RAG system can significantly enhance its capabilities by providing up-to-date information. Here's how you can modify your RAG system to include web search:
#
# First, you'll need to choose a web search API. Some popular options include:
#
# Google Custom Search API
# Bing Web Search API
# DuckDuckGo API
# SerpAPI (which can interface with multiple search engines)
#
#
#
# For this example, let's use the DuckDuckGo API, as it's free and doesn't require authentication.
#
# Install the required library:
# `pip install duckduckgo-search`
#
# Add a new method to your RAG system for web search:
# ```
# from duckduckgo_search import ddg
#
# class AsyncRAGSystem:
# # ... (existing code) ...
#
# async def web_search(self, query: str, num_results: int = 3) -> List[Dict[str, str]]:
# try:
# results = ddg(query, max_results=num_results)
# return [{'title': r['title'], 'content': r['body'], 'source': r['href']} for r in results]
# except Exception as e:
# logger.error(f"Error in web search: {e}")
# raise RAGException(f"Web search failed: {e}")
#
# async def add_web_results_to_db(self, results: List[Dict[str, str]]):
# try:
# documents = [(r['title'], r['content'], r['source']) for r in results]
# await self.add_documents(documents)
# logger.info(f"Added {len(documents)} web search results to the database")
# except Exception as e:
# logger.error(f"Error adding web search results to database: {e}")
# raise RAGException(f"Adding web search results failed: {e}")
#
# async def rag_query_with_web_search(self, query: str, llm_function: Callable[[str], str], top_k: int = 3,
# use_web_search: bool = True, num_web_results: int = 3) -> str:
# try:
# if use_web_search:
# web_results = await self.web_search(query, num_web_results)
# await self.add_web_results_to_db(web_results)
#
# relevant_docs = await self.get_relevant_documents(query, top_k)
# context = "\n\n".join([f"Title: {title}\nContent: {content}\nSource: {source}"
# for _, title, content, _, source in relevant_docs])
#
# llm_prompt = f"Based on the following context, please answer the query. Include citations in your response using [Source] format:\n\nContext:\n{context}\n\nQuery: {query}"
#
# response = llm_function(llm_prompt)
# logger.info("Generated response for query with web search")
# return response
# except Exception as e:
# logger.error(f"Error in RAG query with web search: {e}")
# raise RAGException(f"RAG query with web search failed: {e}")
# ```
#
# Update your main function to use the new web search capability:
# ```
# async def main():
# use_hyde = False # Set this to True when you want to enable HyDE
# use_web_search = True # Set this to False if you don't want to use web search
#
# try:
# if use_hyde:
# rag_system = AsyncHyDERAGSystem('rag_database.db')
# logger.info("Using Async HyDE RAG System")
# else:
# rag_system = AsyncStandardRAGSystem('rag_database.db')
# logger.info("Using Async Standard RAG System")
#
# await rag_system.init_db()
#
# # Add sample documents
# sample_docs = [
# ("Paris", "Paris is the capital of France and is known for the Eiffel Tower.", "Local Database"),
# ("London", "London is the capital of the United Kingdom and home to Big Ben.", "Local Database"),
# ("Tokyo", "Tokyo is the capital of Japan and is famous for its bustling city life.", "Local Database")
# ]
#
# await rag_system.add_documents(sample_docs)
#
# query = "What is the capital of France?"
# result = await rag_system.rag_query_with_web_search(query, mock_llm, use_web_search=use_web_search)
# print(f"Query: {query}")
# print(f"Result: {result}")
#
# except RAGException as e:
# logger.error(f"RAG system error: {e}")
# print(f"An error occurred: {e}")
# except Exception as e:
# logger.error(f"Unexpected error: {e}")
# print(f"An unexpected error occurred: {e}")
# ```
#
#
# This implementation does the following:
#
# It adds a web_search method that uses the DuckDuckGo API to perform web searches.
# It adds an add_web_results_to_db method that adds the web search results to your existing database.
# It modifies the rag_query method (now called rag_query_with_web_search) to optionally perform a web search before retrieving relevant documents.
#
# When use_web_search is set to True, the system will:
#
# Perform a web search for the given query.
# Add the web search results to the database.
# Retrieve relevant documents (which now may include the newly added web search results).
# Use these documents to generate a response.
#
# This approach allows your RAG system to combine information from your existing database with fresh information from the web, potentially providing more up-to-date and comprehensive answers.
# Remember to handle rate limiting and respect the terms of service of the web search API you choose to use. Also, be aware that adding web search results to your database will increase its size over time, so you may need to implement a strategy to manage this growth (e.g., removing old web search results periodically).
|