utils.py 18 KB

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