utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. import os
  2. import logging
  3. import requests
  4. from typing import List
  5. from apps.ollama.main import (
  6. generate_ollama_embeddings,
  7. GenerateEmbeddingsForm,
  8. )
  9. from huggingface_hub import snapshot_download
  10. from langchain_core.documents import Document
  11. from langchain_community.retrievers import BM25Retriever
  12. from langchain.retrievers import (
  13. ContextualCompressionRetriever,
  14. EnsembleRetriever,
  15. )
  16. from typing import Optional
  17. from apps.rag.search.brave import search_brave
  18. from apps.rag.search.google_pse import search_google_pse
  19. from apps.rag.search.main import SearchResult
  20. from apps.rag.search.searxng import search_searxng
  21. from apps.rag.search.serper import search_serper
  22. from apps.rag.search.serpstack import search_serpstack
  23. from config import (
  24. SRC_LOG_LEVELS,
  25. CHROMA_CLIENT,
  26. SEARXNG_QUERY_URL,
  27. GOOGLE_PSE_API_KEY,
  28. GOOGLE_PSE_ENGINE_ID,
  29. BRAVE_SEARCH_API_KEY,
  30. SERPSTACK_API_KEY,
  31. SERPSTACK_HTTPS,
  32. SERPER_API_KEY,
  33. )
  34. log = logging.getLogger(__name__)
  35. log.setLevel(SRC_LOG_LEVELS["RAG"])
  36. def query_doc(
  37. collection_name: str,
  38. query: str,
  39. embedding_function,
  40. k: int,
  41. ):
  42. try:
  43. collection = CHROMA_CLIENT.get_collection(name=collection_name)
  44. query_embeddings = embedding_function(query)
  45. result = collection.query(
  46. query_embeddings=[query_embeddings],
  47. n_results=k,
  48. )
  49. log.info(f"query_doc:result {result}")
  50. return result
  51. except Exception as e:
  52. raise e
  53. def query_doc_with_hybrid_search(
  54. collection_name: str,
  55. query: str,
  56. embedding_function,
  57. k: int,
  58. reranking_function,
  59. r: float,
  60. ):
  61. try:
  62. collection = CHROMA_CLIENT.get_collection(name=collection_name)
  63. documents = collection.get() # get all documents
  64. bm25_retriever = BM25Retriever.from_texts(
  65. texts=documents.get("documents"),
  66. metadatas=documents.get("metadatas"),
  67. )
  68. bm25_retriever.k = k
  69. chroma_retriever = ChromaRetriever(
  70. collection=collection,
  71. embedding_function=embedding_function,
  72. top_n=k,
  73. )
  74. ensemble_retriever = EnsembleRetriever(
  75. retrievers=[bm25_retriever, chroma_retriever], weights=[0.5, 0.5]
  76. )
  77. compressor = RerankCompressor(
  78. embedding_function=embedding_function,
  79. top_n=k,
  80. reranking_function=reranking_function,
  81. r_score=r,
  82. )
  83. compression_retriever = ContextualCompressionRetriever(
  84. base_compressor=compressor, base_retriever=ensemble_retriever
  85. )
  86. result = compression_retriever.invoke(query)
  87. result = {
  88. "distances": [[d.metadata.get("score") for d in result]],
  89. "documents": [[d.page_content for d in result]],
  90. "metadatas": [[d.metadata for d in result]],
  91. }
  92. log.info(f"query_doc_with_hybrid_search:result {result}")
  93. return result
  94. except Exception as e:
  95. raise e
  96. def merge_and_sort_query_results(query_results, k, reverse=False):
  97. # Initialize lists to store combined data
  98. combined_distances = []
  99. combined_documents = []
  100. combined_metadatas = []
  101. for data in query_results:
  102. combined_distances.extend(data["distances"][0])
  103. combined_documents.extend(data["documents"][0])
  104. combined_metadatas.extend(data["metadatas"][0])
  105. # Create a list of tuples (distance, document, metadata)
  106. combined = list(zip(combined_distances, combined_documents, combined_metadatas))
  107. # Sort the list based on distances
  108. combined.sort(key=lambda x: x[0], reverse=reverse)
  109. # We don't have anything :-(
  110. if not combined:
  111. sorted_distances = []
  112. sorted_documents = []
  113. sorted_metadatas = []
  114. else:
  115. # Unzip the sorted list
  116. sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
  117. # Slicing the lists to include only k elements
  118. sorted_distances = list(sorted_distances)[:k]
  119. sorted_documents = list(sorted_documents)[:k]
  120. sorted_metadatas = list(sorted_metadatas)[:k]
  121. # Create the output dictionary
  122. result = {
  123. "distances": [sorted_distances],
  124. "documents": [sorted_documents],
  125. "metadatas": [sorted_metadatas],
  126. }
  127. return result
  128. def query_collection(
  129. collection_names: List[str],
  130. query: str,
  131. embedding_function,
  132. k: int,
  133. ):
  134. results = []
  135. for collection_name in collection_names:
  136. try:
  137. result = query_doc(
  138. collection_name=collection_name,
  139. query=query,
  140. k=k,
  141. embedding_function=embedding_function,
  142. )
  143. results.append(result)
  144. except:
  145. pass
  146. return merge_and_sort_query_results(results, k=k)
  147. def query_collection_with_hybrid_search(
  148. collection_names: List[str],
  149. query: str,
  150. embedding_function,
  151. k: int,
  152. reranking_function,
  153. r: float,
  154. ):
  155. results = []
  156. for collection_name in collection_names:
  157. try:
  158. result = query_doc_with_hybrid_search(
  159. collection_name=collection_name,
  160. query=query,
  161. embedding_function=embedding_function,
  162. k=k,
  163. reranking_function=reranking_function,
  164. r=r,
  165. )
  166. results.append(result)
  167. except:
  168. pass
  169. return merge_and_sort_query_results(results, k=k, reverse=True)
  170. def rag_template(template: str, context: str, query: str):
  171. template = template.replace("[context]", context)
  172. template = template.replace("[query]", query)
  173. return template
  174. def get_embedding_function(
  175. embedding_engine,
  176. embedding_model,
  177. embedding_function,
  178. openai_key,
  179. openai_url,
  180. ):
  181. if embedding_engine == "":
  182. return lambda query: embedding_function.encode(query).tolist()
  183. elif embedding_engine in ["ollama", "openai"]:
  184. if embedding_engine == "ollama":
  185. func = lambda query: generate_ollama_embeddings(
  186. GenerateEmbeddingsForm(
  187. **{
  188. "model": embedding_model,
  189. "prompt": query,
  190. }
  191. )
  192. )
  193. elif embedding_engine == "openai":
  194. func = lambda query: generate_openai_embeddings(
  195. model=embedding_model,
  196. text=query,
  197. key=openai_key,
  198. url=openai_url,
  199. )
  200. def generate_multiple(query, f):
  201. if isinstance(query, list):
  202. return [f(q) for q in query]
  203. else:
  204. return f(query)
  205. return lambda query: generate_multiple(query, func)
  206. def rag_messages(
  207. docs,
  208. messages,
  209. template,
  210. embedding_function,
  211. k,
  212. reranking_function,
  213. r,
  214. hybrid_search,
  215. ):
  216. log.debug(f"docs: {docs} {messages} {embedding_function} {reranking_function}")
  217. last_user_message_idx = None
  218. for i in range(len(messages) - 1, -1, -1):
  219. if messages[i]["role"] == "user":
  220. last_user_message_idx = i
  221. break
  222. user_message = messages[last_user_message_idx]
  223. if isinstance(user_message["content"], list):
  224. # Handle list content input
  225. content_type = "list"
  226. query = ""
  227. for content_item in user_message["content"]:
  228. if content_item["type"] == "text":
  229. query = content_item["text"]
  230. break
  231. elif isinstance(user_message["content"], str):
  232. # Handle text content input
  233. content_type = "text"
  234. query = user_message["content"]
  235. else:
  236. # Fallback in case the input does not match expected types
  237. content_type = None
  238. query = ""
  239. extracted_collections = []
  240. relevant_contexts = []
  241. for doc in docs:
  242. context = None
  243. collection = doc.get("collection_name")
  244. if collection:
  245. collection = [collection]
  246. else:
  247. collection = doc.get("collection_names", [])
  248. collection = set(collection).difference(extracted_collections)
  249. if not collection:
  250. log.debug(f"skipping {doc} as it has already been extracted")
  251. continue
  252. try:
  253. if doc["type"] == "text":
  254. context = doc["content"]
  255. else:
  256. if hybrid_search:
  257. context = query_collection_with_hybrid_search(
  258. collection_names=(
  259. doc["collection_names"]
  260. if doc["type"] == "collection"
  261. else [doc["collection_name"]]
  262. ),
  263. query=query,
  264. embedding_function=embedding_function,
  265. k=k,
  266. reranking_function=reranking_function,
  267. r=r,
  268. )
  269. else:
  270. context = query_collection(
  271. collection_names=(
  272. doc["collection_names"]
  273. if doc["type"] == "collection"
  274. else [doc["collection_name"]]
  275. ),
  276. query=query,
  277. embedding_function=embedding_function,
  278. k=k,
  279. )
  280. except Exception as e:
  281. log.exception(e)
  282. context = None
  283. if context:
  284. relevant_contexts.append(context)
  285. extracted_collections.extend(collection)
  286. context_string = ""
  287. for context in relevant_contexts:
  288. try:
  289. if "documents" in context:
  290. items = [item for item in context["documents"][0] if item is not None]
  291. context_string += "\n\n".join(items)
  292. except Exception as e:
  293. log.exception(e)
  294. context_string = context_string.strip()
  295. ra_content = rag_template(
  296. template=template,
  297. context=context_string,
  298. query=query,
  299. )
  300. log.debug(f"ra_content: {ra_content}")
  301. if content_type == "list":
  302. new_content = []
  303. for content_item in user_message["content"]:
  304. if content_item["type"] == "text":
  305. # Update the text item's content with ra_content
  306. new_content.append({"type": "text", "text": ra_content})
  307. else:
  308. # Keep other types of content as they are
  309. new_content.append(content_item)
  310. new_user_message = {**user_message, "content": new_content}
  311. else:
  312. new_user_message = {
  313. **user_message,
  314. "content": ra_content,
  315. }
  316. messages[last_user_message_idx] = new_user_message
  317. return messages
  318. def get_model_path(model: str, update_model: bool = False):
  319. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  320. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  321. local_files_only = not update_model
  322. snapshot_kwargs = {
  323. "cache_dir": cache_dir,
  324. "local_files_only": local_files_only,
  325. }
  326. log.debug(f"model: {model}")
  327. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  328. # Inspiration from upstream sentence_transformers
  329. if (
  330. os.path.exists(model)
  331. or ("\\" in model or model.count("/") > 1)
  332. and local_files_only
  333. ):
  334. # If fully qualified path exists, return input, else set repo_id
  335. return model
  336. elif "/" not in model:
  337. # Set valid repo_id for model short-name
  338. model = "sentence-transformers" + "/" + model
  339. snapshot_kwargs["repo_id"] = model
  340. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  341. try:
  342. model_repo_path = snapshot_download(**snapshot_kwargs)
  343. log.debug(f"model_repo_path: {model_repo_path}")
  344. return model_repo_path
  345. except Exception as e:
  346. log.exception(f"Cannot determine model snapshot path: {e}")
  347. return model
  348. def generate_openai_embeddings(
  349. model: str, text: str, key: str, url: str = "https://api.openai.com/v1"
  350. ):
  351. try:
  352. r = requests.post(
  353. f"{url}/embeddings",
  354. headers={
  355. "Content-Type": "application/json",
  356. "Authorization": f"Bearer {key}",
  357. },
  358. json={"input": text, "model": model},
  359. )
  360. r.raise_for_status()
  361. data = r.json()
  362. if "data" in data:
  363. return data["data"][0]["embedding"]
  364. else:
  365. raise "Something went wrong :/"
  366. except Exception as e:
  367. print(e)
  368. return None
  369. from typing import Any
  370. from langchain_core.retrievers import BaseRetriever
  371. from langchain_core.callbacks import CallbackManagerForRetrieverRun
  372. class ChromaRetriever(BaseRetriever):
  373. collection: Any
  374. embedding_function: Any
  375. top_n: int
  376. def _get_relevant_documents(
  377. self,
  378. query: str,
  379. *,
  380. run_manager: CallbackManagerForRetrieverRun,
  381. ) -> List[Document]:
  382. query_embeddings = self.embedding_function(query)
  383. results = self.collection.query(
  384. query_embeddings=[query_embeddings],
  385. n_results=self.top_n,
  386. )
  387. ids = results["ids"][0]
  388. metadatas = results["metadatas"][0]
  389. documents = results["documents"][0]
  390. results = []
  391. for idx in range(len(ids)):
  392. results.append(
  393. Document(
  394. metadata=metadatas[idx],
  395. page_content=documents[idx],
  396. )
  397. )
  398. return results
  399. import operator
  400. from typing import Optional, Sequence
  401. from langchain_core.documents import BaseDocumentCompressor, Document
  402. from langchain_core.callbacks import Callbacks
  403. from langchain_core.pydantic_v1 import Extra
  404. from sentence_transformers import util
  405. class RerankCompressor(BaseDocumentCompressor):
  406. embedding_function: Any
  407. top_n: int
  408. reranking_function: Any
  409. r_score: float
  410. class Config:
  411. extra = Extra.forbid
  412. arbitrary_types_allowed = True
  413. def compress_documents(
  414. self,
  415. documents: Sequence[Document],
  416. query: str,
  417. callbacks: Optional[Callbacks] = None,
  418. ) -> Sequence[Document]:
  419. reranking = self.reranking_function is not None
  420. if reranking:
  421. scores = self.reranking_function.predict(
  422. [(query, doc.page_content) for doc in documents]
  423. )
  424. else:
  425. query_embedding = self.embedding_function(query)
  426. document_embedding = self.embedding_function(
  427. [doc.page_content for doc in documents]
  428. )
  429. scores = util.cos_sim(query_embedding, document_embedding)[0]
  430. docs_with_scores = list(zip(documents, scores.tolist()))
  431. if self.r_score:
  432. docs_with_scores = [
  433. (d, s) for d, s in docs_with_scores if s >= self.r_score
  434. ]
  435. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  436. final_results = []
  437. for doc, doc_score in result[: self.top_n]:
  438. metadata = doc.metadata
  439. metadata["score"] = doc_score
  440. doc = Document(
  441. page_content=doc.page_content,
  442. metadata=metadata,
  443. )
  444. final_results.append(doc)
  445. return final_results
  446. def search_web(query: str) -> list[SearchResult]:
  447. """Search the web using a search engine and return the results as a list of SearchResult objects.
  448. Will look for a search engine API key in environment variables in the following order:
  449. - SEARXNG_QUERY_URL
  450. - GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID
  451. - BRAVE_SEARCH_API_KEY
  452. - SERPSTACK_API_KEY
  453. - SERPER_API_KEY
  454. Args:
  455. query (str): The query to search for
  456. """
  457. if SEARXNG_QUERY_URL:
  458. return search_searxng(SEARXNG_QUERY_URL, query)
  459. elif GOOGLE_PSE_API_KEY and GOOGLE_PSE_ENGINE_ID:
  460. return search_google_pse(GOOGLE_PSE_API_KEY, GOOGLE_PSE_ENGINE_ID, query)
  461. elif BRAVE_SEARCH_API_KEY:
  462. return search_brave(BRAVE_SEARCH_API_KEY, query)
  463. elif SERPSTACK_API_KEY:
  464. return search_serpstack(SERPSTACK_API_KEY, query, https_enabled=SERPSTACK_HTTPS)
  465. elif SERPER_API_KEY:
  466. return search_serper(SERPER_API_KEY, query)
  467. else:
  468. raise Exception("No search engine API key found in environment variables")