utils.py 18 KB

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