utils.py 15 KB

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