utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. count = template.count("[context]")
  165. assert count == 1, (
  166. f"RAG template contains an unexpected number of '[context]' : {count}"
  167. )
  168. assert "[context]" in template, "RAG template does not contain '[context]'"
  169. template = template.replace("[context]", context)
  170. template = template.replace("[query]", query)
  171. return template
  172. def get_embedding_function(
  173. embedding_engine,
  174. embedding_model,
  175. embedding_function,
  176. openai_key,
  177. openai_url,
  178. batch_size,
  179. ):
  180. if embedding_engine == "":
  181. return lambda query: embedding_function.encode(query).tolist()
  182. elif embedding_engine in ["ollama", "openai"]:
  183. if embedding_engine == "ollama":
  184. func = lambda query: generate_ollama_embeddings(
  185. GenerateEmbeddingsForm(
  186. **{
  187. "model": embedding_model,
  188. "prompt": query,
  189. }
  190. )
  191. )
  192. elif embedding_engine == "openai":
  193. func = lambda query: generate_openai_embeddings(
  194. model=embedding_model,
  195. text=query,
  196. key=openai_key,
  197. url=openai_url,
  198. )
  199. def generate_multiple(query, f):
  200. if isinstance(query, list):
  201. if embedding_engine == "openai":
  202. embeddings = []
  203. for i in range(0, len(query), batch_size):
  204. embeddings.extend(f(query[i : i + batch_size]))
  205. return embeddings
  206. else:
  207. return [f(q) for q in query]
  208. else:
  209. return f(query)
  210. return lambda query: generate_multiple(query, func)
  211. def get_rag_context(
  212. files,
  213. messages,
  214. embedding_function,
  215. k,
  216. reranking_function,
  217. r,
  218. hybrid_search,
  219. ):
  220. log.debug(f"files: {files} {messages} {embedding_function} {reranking_function}")
  221. query = get_last_user_message(messages)
  222. extracted_collections = []
  223. relevant_contexts = []
  224. for file in files:
  225. context = None
  226. collection_names = (
  227. file["collection_names"]
  228. if file["type"] == "collection"
  229. else [file["collection_name"]] if file["collection_name"] else []
  230. )
  231. collection_names = set(collection_names).difference(extracted_collections)
  232. if not collection_names:
  233. log.debug(f"skipping {file} as it has already been extracted")
  234. continue
  235. try:
  236. context = None
  237. if file["type"] == "text":
  238. context = file["content"]
  239. else:
  240. if hybrid_search:
  241. try:
  242. context = query_collection_with_hybrid_search(
  243. collection_names=collection_names,
  244. query=query,
  245. embedding_function=embedding_function,
  246. k=k,
  247. reranking_function=reranking_function,
  248. r=r,
  249. )
  250. except Exception as e:
  251. log.debug("Error when using hybrid search, using"
  252. " non hybrid search as fallback.")
  253. if (not hybrid_search) or (context is None):
  254. context = query_collection(
  255. collection_names=collection_names,
  256. query=query,
  257. embedding_function=embedding_function,
  258. k=k,
  259. )
  260. except Exception as e:
  261. log.exception(e)
  262. if context:
  263. relevant_contexts.append({**context, "source": file})
  264. extracted_collections.extend(collection_names)
  265. contexts = []
  266. citations = []
  267. for context in relevant_contexts:
  268. try:
  269. if "documents" in context:
  270. contexts.append(
  271. "\n\n".join(
  272. [text for text in context["documents"][0] if text is not None]
  273. )
  274. )
  275. if "metadatas" in context:
  276. citations.append(
  277. {
  278. "source": context["source"],
  279. "document": context["documents"][0],
  280. "metadata": context["metadatas"][0],
  281. }
  282. )
  283. except Exception as e:
  284. log.exception(e)
  285. return contexts, citations
  286. def get_model_path(model: str, update_model: bool = False):
  287. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  288. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  289. local_files_only = not update_model
  290. snapshot_kwargs = {
  291. "cache_dir": cache_dir,
  292. "local_files_only": local_files_only,
  293. }
  294. log.debug(f"model: {model}")
  295. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  296. # Inspiration from upstream sentence_transformers
  297. if (
  298. os.path.exists(model)
  299. or ("\\" in model or model.count("/") > 1)
  300. and local_files_only
  301. ):
  302. # If fully qualified path exists, return input, else set repo_id
  303. return model
  304. elif "/" not in model:
  305. # Set valid repo_id for model short-name
  306. model = "sentence-transformers" + "/" + model
  307. snapshot_kwargs["repo_id"] = model
  308. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  309. try:
  310. model_repo_path = snapshot_download(**snapshot_kwargs)
  311. log.debug(f"model_repo_path: {model_repo_path}")
  312. return model_repo_path
  313. except Exception as e:
  314. log.exception(f"Cannot determine model snapshot path: {e}")
  315. return model
  316. def generate_openai_embeddings(
  317. model: str,
  318. text: Union[str, list[str]],
  319. key: str,
  320. url: str = "https://api.openai.com/v1",
  321. ):
  322. if isinstance(text, list):
  323. embeddings = generate_openai_batch_embeddings(model, text, key, url)
  324. else:
  325. embeddings = generate_openai_batch_embeddings(model, [text], key, url)
  326. return embeddings[0] if isinstance(text, str) else embeddings
  327. def generate_openai_batch_embeddings(
  328. model: str, texts: list[str], key: str, url: str = "https://api.openai.com/v1"
  329. ) -> Optional[list[list[float]]]:
  330. try:
  331. r = requests.post(
  332. f"{url}/embeddings",
  333. headers={
  334. "Content-Type": "application/json",
  335. "Authorization": f"Bearer {key}",
  336. },
  337. json={"input": texts, "model": model},
  338. )
  339. r.raise_for_status()
  340. data = r.json()
  341. if "data" in data:
  342. return [elem["embedding"] for elem in data["data"]]
  343. else:
  344. raise "Something went wrong :/"
  345. except Exception as e:
  346. print(e)
  347. return None
  348. from typing import Any
  349. from langchain_core.callbacks import CallbackManagerForRetrieverRun
  350. from langchain_core.retrievers import BaseRetriever
  351. class ChromaRetriever(BaseRetriever):
  352. collection: Any
  353. embedding_function: Any
  354. top_n: int
  355. def _get_relevant_documents(
  356. self,
  357. query: str,
  358. *,
  359. run_manager: CallbackManagerForRetrieverRun,
  360. ) -> list[Document]:
  361. query_embeddings = self.embedding_function(query)
  362. results = self.collection.query(
  363. query_embeddings=[query_embeddings],
  364. n_results=self.top_n,
  365. )
  366. ids = results["ids"][0]
  367. metadatas = results["metadatas"][0]
  368. documents = results["documents"][0]
  369. results = []
  370. for idx in range(len(ids)):
  371. results.append(
  372. Document(
  373. metadata=metadatas[idx],
  374. page_content=documents[idx],
  375. )
  376. )
  377. return results
  378. import operator
  379. from typing import Optional, Sequence
  380. from langchain_core.callbacks import Callbacks
  381. from langchain_core.documents import BaseDocumentCompressor, Document
  382. from langchain_core.pydantic_v1 import Extra
  383. class RerankCompressor(BaseDocumentCompressor):
  384. embedding_function: Any
  385. top_n: int
  386. reranking_function: Any
  387. r_score: float
  388. class Config:
  389. extra = Extra.forbid
  390. arbitrary_types_allowed = True
  391. def compress_documents(
  392. self,
  393. documents: Sequence[Document],
  394. query: str,
  395. callbacks: Optional[Callbacks] = None,
  396. ) -> Sequence[Document]:
  397. reranking = self.reranking_function is not None
  398. if reranking:
  399. scores = self.reranking_function.predict(
  400. [(query, doc.page_content) for doc in documents]
  401. )
  402. else:
  403. from sentence_transformers import util
  404. query_embedding = self.embedding_function(query)
  405. document_embedding = self.embedding_function(
  406. [doc.page_content for doc in documents]
  407. )
  408. scores = util.cos_sim(query_embedding, document_embedding)[0]
  409. docs_with_scores = list(zip(documents, scores.tolist()))
  410. if self.r_score:
  411. docs_with_scores = [
  412. (d, s) for d, s in docs_with_scores if s >= self.r_score
  413. ]
  414. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  415. final_results = []
  416. for doc, doc_score in result[: self.top_n]:
  417. metadata = doc.metadata
  418. metadata["score"] = doc_score
  419. doc = Document(
  420. page_content=doc.page_content,
  421. metadata=metadata,
  422. )
  423. final_results.append(doc)
  424. return final_results