utils.py 16 KB

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