utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. GenerateEmbedForm,
  12. generate_ollama_batch_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_embedding: list[float],
  52. k: int,
  53. ):
  54. try:
  55. result = VECTOR_DB_CLIENT.search(
  56. collection_name=collection_name,
  57. vectors=query_embedding,
  58. limit=k,
  59. )
  60. log.info(f"query_doc:result {result}")
  61. return result
  62. except Exception as e:
  63. print(e)
  64. raise e
  65. def query_doc_with_hybrid_search(
  66. collection_name: str,
  67. query: str,
  68. embedding_function,
  69. k: int,
  70. reranking_function,
  71. r: float,
  72. ) -> dict:
  73. try:
  74. result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
  75. bm25_retriever = BM25Retriever.from_texts(
  76. texts=result.documents[0],
  77. metadatas=result.metadatas[0],
  78. )
  79. bm25_retriever.k = k
  80. vector_search_retriever = VectorSearchRetriever(
  81. collection_name=collection_name,
  82. embedding_function=embedding_function,
  83. top_k=k,
  84. )
  85. ensemble_retriever = EnsembleRetriever(
  86. retrievers=[bm25_retriever, vector_search_retriever], weights=[0.5, 0.5]
  87. )
  88. compressor = RerankCompressor(
  89. embedding_function=embedding_function,
  90. top_n=k,
  91. reranking_function=reranking_function,
  92. r_score=r,
  93. )
  94. compression_retriever = ContextualCompressionRetriever(
  95. base_compressor=compressor, base_retriever=ensemble_retriever
  96. )
  97. result = compression_retriever.invoke(query)
  98. result = {
  99. "distances": [[d.metadata.get("score") for d in result]],
  100. "documents": [[d.page_content for d in result]],
  101. "metadatas": [[d.metadata for d in result]],
  102. }
  103. log.info(f"query_doc_with_hybrid_search:result {result}")
  104. return result
  105. except Exception as e:
  106. raise e
  107. def merge_and_sort_query_results(
  108. query_results: list[dict], k: int, reverse: bool = False
  109. ) -> list[dict]:
  110. # Initialize lists to store combined data
  111. combined_distances = []
  112. combined_documents = []
  113. combined_metadatas = []
  114. for data in query_results:
  115. combined_distances.extend(data["distances"][0])
  116. combined_documents.extend(data["documents"][0])
  117. combined_metadatas.extend(data["metadatas"][0])
  118. # Create a list of tuples (distance, document, metadata)
  119. combined = list(zip(combined_distances, combined_documents, combined_metadatas))
  120. # Sort the list based on distances
  121. combined.sort(key=lambda x: x[0], reverse=reverse)
  122. # We don't have anything :-(
  123. if not combined:
  124. sorted_distances = []
  125. sorted_documents = []
  126. sorted_metadatas = []
  127. else:
  128. # Unzip the sorted list
  129. sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
  130. # Slicing the lists to include only k elements
  131. sorted_distances = list(sorted_distances)[:k]
  132. sorted_documents = list(sorted_documents)[:k]
  133. sorted_metadatas = list(sorted_metadatas)[:k]
  134. # Create the output dictionary
  135. result = {
  136. "distances": [sorted_distances],
  137. "documents": [sorted_documents],
  138. "metadatas": [sorted_metadatas],
  139. }
  140. return result
  141. def query_collection(
  142. collection_names: list[str],
  143. query: str,
  144. embedding_function,
  145. k: int,
  146. ) -> dict:
  147. results = []
  148. query_embedding = embedding_function(query)
  149. for collection_name in collection_names:
  150. if collection_name:
  151. try:
  152. result = query_doc(
  153. collection_name=collection_name,
  154. k=k,
  155. query_embedding=query_embedding,
  156. )
  157. if result is not None:
  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. embedding_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. model=embedding_model,
  227. input=query,
  228. )
  229. elif embedding_engine == "openai":
  230. func = lambda query: generate_openai_embeddings(
  231. model=embedding_model,
  232. text=query,
  233. key=openai_key,
  234. url=openai_url,
  235. )
  236. def generate_multiple(query, f):
  237. if isinstance(query, list):
  238. embeddings = []
  239. for i in range(0, len(query), embedding_batch_size):
  240. embeddings.extend(f(query[i : i + embedding_batch_size]))
  241. return embeddings
  242. else:
  243. return f(query)
  244. return lambda query: generate_multiple(query, func)
  245. def get_rag_context(
  246. files,
  247. messages,
  248. embedding_function,
  249. k,
  250. reranking_function,
  251. r,
  252. hybrid_search,
  253. ):
  254. log.debug(f"files: {files} {messages} {embedding_function} {reranking_function}")
  255. query = get_last_user_message(messages)
  256. extracted_collections = []
  257. relevant_contexts = []
  258. for file in files:
  259. if file.get("context") == "full":
  260. context = {
  261. "documents": [[file.get("file").get("data", {}).get("content")]],
  262. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  263. }
  264. else:
  265. context = None
  266. collection_names = []
  267. if file.get("type") == "collection":
  268. if file.get("legacy"):
  269. collection_names = file.get("collection_names", [])
  270. else:
  271. collection_names.append(file["id"])
  272. elif file.get("collection_name"):
  273. collection_names.append(file["collection_name"])
  274. elif file.get("id"):
  275. if file.get("legacy"):
  276. collection_names.append(f"{file['id']}")
  277. else:
  278. collection_names.append(f"file-{file['id']}")
  279. collection_names = set(collection_names).difference(extracted_collections)
  280. if not collection_names:
  281. log.debug(f"skipping {file} as it has already been extracted")
  282. continue
  283. try:
  284. context = None
  285. if file.get("type") == "text":
  286. context = file["content"]
  287. else:
  288. if hybrid_search:
  289. try:
  290. context = query_collection_with_hybrid_search(
  291. collection_names=collection_names,
  292. query=query,
  293. embedding_function=embedding_function,
  294. k=k,
  295. reranking_function=reranking_function,
  296. r=r,
  297. )
  298. except Exception as e:
  299. log.debug(
  300. "Error when using hybrid search, using"
  301. " non hybrid search as fallback."
  302. )
  303. if (not hybrid_search) or (context is None):
  304. context = query_collection(
  305. collection_names=collection_names,
  306. query=query,
  307. embedding_function=embedding_function,
  308. k=k,
  309. )
  310. except Exception as e:
  311. log.exception(e)
  312. extracted_collections.extend(collection_names)
  313. if context:
  314. relevant_contexts.append({**context, "file": file})
  315. contexts = []
  316. citations = []
  317. for context in relevant_contexts:
  318. try:
  319. if "documents" in context:
  320. contexts.append(
  321. "\n\n".join(
  322. [text for text in context["documents"][0] if text is not None]
  323. )
  324. )
  325. if "metadatas" in context:
  326. citations.append(
  327. {
  328. "source": context["file"],
  329. "document": context["documents"][0],
  330. "metadata": context["metadatas"][0],
  331. }
  332. )
  333. except Exception as e:
  334. log.exception(e)
  335. return contexts, citations
  336. def get_model_path(model: str, update_model: bool = False):
  337. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  338. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  339. local_files_only = not update_model
  340. snapshot_kwargs = {
  341. "cache_dir": cache_dir,
  342. "local_files_only": local_files_only,
  343. }
  344. log.debug(f"model: {model}")
  345. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  346. # Inspiration from upstream sentence_transformers
  347. if (
  348. os.path.exists(model)
  349. or ("\\" in model or model.count("/") > 1)
  350. and local_files_only
  351. ):
  352. # If fully qualified path exists, return input, else set repo_id
  353. return model
  354. elif "/" not in model:
  355. # Set valid repo_id for model short-name
  356. model = "sentence-transformers" + "/" + model
  357. snapshot_kwargs["repo_id"] = model
  358. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  359. try:
  360. model_repo_path = snapshot_download(**snapshot_kwargs)
  361. log.debug(f"model_repo_path: {model_repo_path}")
  362. return model_repo_path
  363. except Exception as e:
  364. log.exception(f"Cannot determine model snapshot path: {e}")
  365. return model
  366. def generate_openai_embeddings(
  367. model: str,
  368. text: Union[str, list[str]],
  369. key: str,
  370. url: str = "https://api.openai.com/v1",
  371. ):
  372. if isinstance(text, list):
  373. embeddings = generate_openai_batch_embeddings(model, text, key, url)
  374. else:
  375. embeddings = generate_openai_batch_embeddings(model, [text], key, url)
  376. return embeddings[0] if isinstance(text, str) else embeddings
  377. def generate_openai_batch_embeddings(
  378. model: str, texts: list[str], key: str, url: str = "https://api.openai.com/v1"
  379. ) -> Optional[list[list[float]]]:
  380. try:
  381. r = requests.post(
  382. f"{url}/embeddings",
  383. headers={
  384. "Content-Type": "application/json",
  385. "Authorization": f"Bearer {key}",
  386. },
  387. json={"input": texts, "model": model},
  388. )
  389. r.raise_for_status()
  390. data = r.json()
  391. if "data" in data:
  392. return [elem["embedding"] for elem in data["data"]]
  393. else:
  394. raise "Something went wrong :/"
  395. except Exception as e:
  396. print(e)
  397. return None
  398. def generate_ollama_embeddings(
  399. model: str, input: list[str]
  400. ) -> Optional[list[list[float]]]:
  401. if isinstance(input, list):
  402. embeddings = generate_ollama_batch_embeddings(
  403. GenerateEmbedForm(**{"model": model, "input": input})
  404. )
  405. else:
  406. embeddings = generate_ollama_batch_embeddings(
  407. GenerateEmbedForm(**{"model": model, "input": [input]})
  408. )
  409. return embeddings["embeddings"]
  410. import operator
  411. from typing import Optional, Sequence
  412. from langchain_core.callbacks import Callbacks
  413. from langchain_core.documents import BaseDocumentCompressor, Document
  414. class RerankCompressor(BaseDocumentCompressor):
  415. embedding_function: Any
  416. top_n: int
  417. reranking_function: Any
  418. r_score: float
  419. class Config:
  420. extra = "forbid"
  421. arbitrary_types_allowed = True
  422. def compress_documents(
  423. self,
  424. documents: Sequence[Document],
  425. query: str,
  426. callbacks: Optional[Callbacks] = None,
  427. ) -> Sequence[Document]:
  428. reranking = self.reranking_function is not None
  429. if reranking:
  430. scores = self.reranking_function.predict(
  431. [(query, doc.page_content) for doc in documents]
  432. )
  433. else:
  434. from sentence_transformers import util
  435. query_embedding = self.embedding_function(query)
  436. document_embedding = self.embedding_function(
  437. [doc.page_content for doc in documents]
  438. )
  439. scores = util.cos_sim(query_embedding, document_embedding)[0]
  440. docs_with_scores = list(zip(documents, scores.tolist()))
  441. if self.r_score:
  442. docs_with_scores = [
  443. (d, s) for d, s in docs_with_scores if s >= self.r_score
  444. ]
  445. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  446. final_results = []
  447. for doc, doc_score in result[: self.top_n]:
  448. metadata = doc.metadata
  449. metadata["score"] = doc_score
  450. doc = Document(
  451. page_content=doc.page_content,
  452. metadata=metadata,
  453. )
  454. final_results.append(doc)
  455. return final_results