utils.py 17 KB

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