utils.py 16 KB

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