utils.py 16 KB

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