utils.py 17 KB

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