utils.py 16 KB

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