utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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.rag.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. print("result", result)
  62. log.info(f"query_doc:result {result}")
  63. return result
  64. except Exception as e:
  65. print(e)
  66. raise e
  67. def query_doc_with_hybrid_search(
  68. collection_name: str,
  69. query: str,
  70. embedding_function,
  71. k: int,
  72. reranking_function,
  73. r: float,
  74. ) -> dict:
  75. try:
  76. result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
  77. bm25_retriever = BM25Retriever.from_texts(
  78. texts=result.documents,
  79. metadatas=result.metadatas,
  80. )
  81. bm25_retriever.k = k
  82. vector_search_retriever = VectorSearchRetriever(
  83. collection_name=collection_name,
  84. embedding_function=embedding_function,
  85. top_k=k,
  86. )
  87. ensemble_retriever = EnsembleRetriever(
  88. retrievers=[bm25_retriever, vector_search_retriever], weights=[0.5, 0.5]
  89. )
  90. compressor = RerankCompressor(
  91. embedding_function=embedding_function,
  92. top_n=k,
  93. reranking_function=reranking_function,
  94. r_score=r,
  95. )
  96. compression_retriever = ContextualCompressionRetriever(
  97. base_compressor=compressor, base_retriever=ensemble_retriever
  98. )
  99. result = compression_retriever.invoke(query)
  100. result = {
  101. "distances": [[d.metadata.get("score") for d in result]],
  102. "documents": [[d.page_content for d in result]],
  103. "metadatas": [[d.metadata for d in result]],
  104. }
  105. log.info(f"query_doc_with_hybrid_search:result {result}")
  106. return result
  107. except Exception as e:
  108. raise e
  109. def merge_and_sort_query_results(query_results: list[dict], k: int, reverse: bool = False) -> 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. for collection_name in collection_names:
  149. if collection_name:
  150. try:
  151. result = query_doc(
  152. collection_name=collection_name,
  153. query=query,
  154. k=k,
  155. embedding_function=embedding_function,
  156. )
  157. results.append(result)
  158. except Exception as e:
  159. log.exception(f"Error when querying the collection: {e}")
  160. else:
  161. pass
  162. return merge_and_sort_query_results(results, k=k)
  163. def query_collection_with_hybrid_search(
  164. collection_names: list[str],
  165. query: str,
  166. embedding_function,
  167. k: int,
  168. reranking_function,
  169. r: float,
  170. ) -> dict:
  171. results = []
  172. failed = 0
  173. for collection_name in collection_names:
  174. try:
  175. result = query_doc_with_hybrid_search(
  176. collection_name=collection_name,
  177. query=query,
  178. embedding_function=embedding_function,
  179. k=k,
  180. reranking_function=reranking_function,
  181. r=r,
  182. )
  183. results.append(result)
  184. except Exception as e:
  185. log.exception(
  186. "Error when querying the collection with "
  187. f"hybrid_search: {e}"
  188. )
  189. failed += 1
  190. if failed == len(collection_names):
  191. raise Exception("Hybrid search failed for all collections. Using "
  192. "Non hybrid search as fallback.")
  193. return merge_and_sort_query_results(results, k=k, reverse=True)
  194. def rag_template(template: str, context: str, query: str):
  195. count = template.count("[context]")
  196. assert count == 1, (
  197. f"RAG template contains an unexpected number of '[context]' : {count}"
  198. )
  199. assert "[context]" in template, "RAG template does not contain '[context]'"
  200. if "<context>" in context and "</context>" in context:
  201. log.debug(
  202. "WARNING: Potential prompt injection attack: the RAG "
  203. "context contains '<context>' and '</context>'. This might be "
  204. "nothing, or the user might be trying to hack something."
  205. )
  206. if "[query]" in context:
  207. query_placeholder = str(uuid.uuid4())
  208. template = template.replace("[QUERY]", query_placeholder)
  209. template = template.replace("[context]", context)
  210. template = template.replace(query_placeholder, query)
  211. else:
  212. template = template.replace("[context]", context)
  213. template = template.replace("[query]", query)
  214. return template
  215. def get_embedding_function(
  216. embedding_engine,
  217. embedding_model,
  218. embedding_function,
  219. openai_key,
  220. openai_url,
  221. batch_size,
  222. ):
  223. if embedding_engine == "":
  224. return lambda query: embedding_function.encode(query).tolist()
  225. elif embedding_engine in ["ollama", "openai"]:
  226. if embedding_engine == "ollama":
  227. func = lambda query: generate_ollama_embeddings(
  228. GenerateEmbeddingsForm(
  229. **{
  230. "model": embedding_model,
  231. "prompt": query,
  232. }
  233. )
  234. )
  235. elif embedding_engine == "openai":
  236. func = lambda query: generate_openai_embeddings(
  237. model=embedding_model,
  238. text=query,
  239. key=openai_key,
  240. url=openai_url,
  241. )
  242. def generate_multiple(query, f):
  243. if isinstance(query, list):
  244. if embedding_engine == "openai":
  245. embeddings = []
  246. for i in range(0, len(query), batch_size):
  247. embeddings.extend(f(query[i : i + batch_size]))
  248. return embeddings
  249. else:
  250. return [f(q) for q in query]
  251. else:
  252. return f(query)
  253. return lambda query: generate_multiple(query, func)
  254. def get_rag_context(
  255. files,
  256. messages,
  257. embedding_function,
  258. k,
  259. reranking_function,
  260. r,
  261. hybrid_search,
  262. ):
  263. log.debug(f"files: {files} {messages} {embedding_function} {reranking_function}")
  264. query = get_last_user_message(messages)
  265. extracted_collections = []
  266. relevant_contexts = []
  267. for file in files:
  268. context = None
  269. collection_names = (
  270. file["collection_names"]
  271. if file["type"] == "collection"
  272. else [file["collection_name"]] if file["collection_name"] else []
  273. )
  274. collection_names = set(collection_names).difference(extracted_collections)
  275. if not collection_names:
  276. log.debug(f"skipping {file} as it has already been extracted")
  277. continue
  278. try:
  279. context = None
  280. if file["type"] == "text":
  281. context = file["content"]
  282. else:
  283. if hybrid_search:
  284. try:
  285. context = query_collection_with_hybrid_search(
  286. collection_names=collection_names,
  287. query=query,
  288. embedding_function=embedding_function,
  289. k=k,
  290. reranking_function=reranking_function,
  291. r=r,
  292. )
  293. except Exception as e:
  294. log.debug("Error when using hybrid search, using"
  295. " non hybrid search as fallback.")
  296. if (not hybrid_search) or (context is None):
  297. context = query_collection(
  298. collection_names=collection_names,
  299. query=query,
  300. embedding_function=embedding_function,
  301. k=k,
  302. )
  303. except Exception as e:
  304. log.exception(e)
  305. if context:
  306. relevant_contexts.append({**context, "source": file})
  307. extracted_collections.extend(collection_names)
  308. contexts = []
  309. citations = []
  310. for context in relevant_contexts:
  311. try:
  312. if "documents" in context:
  313. contexts.append(
  314. "\n\n".join(
  315. [text for text in context["documents"][0] if text is not None]
  316. )
  317. )
  318. if "metadatas" in context:
  319. citations.append(
  320. {
  321. "source": context["source"],
  322. "document": context["documents"][0],
  323. "metadata": context["metadatas"][0],
  324. }
  325. )
  326. except Exception as e:
  327. log.exception(e)
  328. return contexts, citations
  329. def get_model_path(model: str, update_model: bool = False):
  330. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  331. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  332. local_files_only = not update_model
  333. snapshot_kwargs = {
  334. "cache_dir": cache_dir,
  335. "local_files_only": local_files_only,
  336. }
  337. log.debug(f"model: {model}")
  338. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  339. # Inspiration from upstream sentence_transformers
  340. if (
  341. os.path.exists(model)
  342. or ("\\" in model or model.count("/") > 1)
  343. and local_files_only
  344. ):
  345. # If fully qualified path exists, return input, else set repo_id
  346. return model
  347. elif "/" not in model:
  348. # Set valid repo_id for model short-name
  349. model = "sentence-transformers" + "/" + model
  350. snapshot_kwargs["repo_id"] = model
  351. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  352. try:
  353. model_repo_path = snapshot_download(**snapshot_kwargs)
  354. log.debug(f"model_repo_path: {model_repo_path}")
  355. return model_repo_path
  356. except Exception as e:
  357. log.exception(f"Cannot determine model snapshot path: {e}")
  358. return model
  359. def generate_openai_embeddings(
  360. model: str,
  361. text: Union[str, list[str]],
  362. key: str,
  363. url: str = "https://api.openai.com/v1",
  364. ):
  365. if isinstance(text, list):
  366. embeddings = generate_openai_batch_embeddings(model, text, key, url)
  367. else:
  368. embeddings = generate_openai_batch_embeddings(model, [text], key, url)
  369. return embeddings[0] if isinstance(text, str) else embeddings
  370. def generate_openai_batch_embeddings(
  371. model: str, texts: list[str], key: str, url: str = "https://api.openai.com/v1"
  372. ) -> Optional[list[list[float]]]:
  373. try:
  374. r = requests.post(
  375. f"{url}/embeddings",
  376. headers={
  377. "Content-Type": "application/json",
  378. "Authorization": f"Bearer {key}",
  379. },
  380. json={"input": texts, "model": model},
  381. )
  382. r.raise_for_status()
  383. data = r.json()
  384. if "data" in data:
  385. return [elem["embedding"] for elem in data["data"]]
  386. else:
  387. raise "Something went wrong :/"
  388. except Exception as e:
  389. print(e)
  390. return None
  391. import operator
  392. from typing import Optional, Sequence
  393. from langchain_core.callbacks import Callbacks
  394. from langchain_core.documents import BaseDocumentCompressor, Document
  395. from langchain_core.pydantic_v1 import Extra
  396. class RerankCompressor(BaseDocumentCompressor):
  397. embedding_function: Any
  398. top_n: int
  399. reranking_function: Any
  400. r_score: float
  401. class Config:
  402. extra = Extra.forbid
  403. arbitrary_types_allowed = True
  404. def compress_documents(
  405. self,
  406. documents: Sequence[Document],
  407. query: str,
  408. callbacks: Optional[Callbacks] = None,
  409. ) -> Sequence[Document]:
  410. reranking = self.reranking_function is not None
  411. if reranking:
  412. scores = self.reranking_function.predict(
  413. [(query, doc.page_content) for doc in documents]
  414. )
  415. else:
  416. from sentence_transformers import util
  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