utils.py 16 KB

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