utils.py 15 KB

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