1
0

utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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 RAG_EMBEDDING_QUERY_PREFIX, RAG_EMBEDDING_PASSAGE_PREFIX
  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,RAG_EMBEDDING_QUERY_PREFIX)],
  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, RAG_EMBEDDING_QUERY_PREFIX)
  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. return merge_and_sort_query_results(results, k=k)
  167. def query_collection_with_hybrid_search(
  168. collection_names: list[str],
  169. queries: list[str],
  170. embedding_function,
  171. k: int,
  172. reranking_function,
  173. r: float,
  174. ) -> dict:
  175. results = []
  176. error = False
  177. for collection_name in collection_names:
  178. try:
  179. for query in queries:
  180. result = query_doc_with_hybrid_search(
  181. collection_name=collection_name,
  182. query=query,
  183. embedding_function=embedding_function,
  184. k=k,
  185. reranking_function=reranking_function,
  186. r=r,
  187. )
  188. results.append(result)
  189. except Exception as e:
  190. log.exception(
  191. "Error when querying the collection with " f"hybrid_search: {e}"
  192. )
  193. error = True
  194. if error:
  195. raise Exception(
  196. "Hybrid search failed for all collections. Using Non hybrid search as fallback."
  197. )
  198. return merge_and_sort_query_results(results, k=k, reverse=True)
  199. def get_embedding_function(
  200. embedding_engine,
  201. embedding_model,
  202. embedding_function,
  203. url,
  204. key,
  205. embedding_batch_size,
  206. ):
  207. if embedding_engine == "":
  208. return lambda query, prefix: embedding_function.encode(query, prompt = prefix if prefix else None).tolist()
  209. elif embedding_engine in ["ollama", "openai"]:
  210. func = lambda query, prefix: generate_embeddings(
  211. engine=embedding_engine,
  212. model=embedding_model,
  213. text=query,
  214. prefix=prefix,
  215. url=url,
  216. key=key,
  217. )
  218. def generate_multiple(query, prefix, func):
  219. if isinstance(query, list):
  220. embeddings = []
  221. for i in range(0, len(query), embedding_batch_size):
  222. embeddings.extend(func(query[i : i + embedding_batch_size], prefix))
  223. return embeddings
  224. else:
  225. return func(query)
  226. return lambda query, prefix: generate_multiple(query, prefix, func)
  227. def get_sources_from_files(
  228. files,
  229. queries,
  230. embedding_function,
  231. k,
  232. reranking_function,
  233. r,
  234. hybrid_search,
  235. ):
  236. log.debug(f"files: {files} {queries} {embedding_function} {reranking_function}")
  237. extracted_collections = []
  238. relevant_contexts = []
  239. for file in files:
  240. if file.get("context") == "full":
  241. context = {
  242. "documents": [[file.get("file").get("data", {}).get("content")]],
  243. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  244. }
  245. else:
  246. context = None
  247. collection_names = []
  248. if file.get("type") == "collection":
  249. if file.get("legacy"):
  250. collection_names = file.get("collection_names", [])
  251. else:
  252. collection_names.append(file["id"])
  253. elif file.get("collection_name"):
  254. collection_names.append(file["collection_name"])
  255. elif file.get("id"):
  256. if file.get("legacy"):
  257. collection_names.append(f"{file['id']}")
  258. else:
  259. collection_names.append(f"file-{file['id']}")
  260. collection_names = set(collection_names).difference(extracted_collections)
  261. if not collection_names:
  262. log.debug(f"skipping {file} as it has already been extracted")
  263. continue
  264. try:
  265. context = None
  266. if file.get("type") == "text":
  267. context = file["content"]
  268. else:
  269. if hybrid_search:
  270. try:
  271. context = query_collection_with_hybrid_search(
  272. collection_names=collection_names,
  273. queries=queries,
  274. embedding_function=embedding_function,
  275. k=k,
  276. reranking_function=reranking_function,
  277. r=r,
  278. )
  279. except Exception as e:
  280. log.debug(
  281. "Error when using hybrid search, using"
  282. " non hybrid search as fallback."
  283. )
  284. if (not hybrid_search) or (context is None):
  285. context = query_collection(
  286. collection_names=collection_names,
  287. queries=queries,
  288. embedding_function=embedding_function,
  289. k=k,
  290. )
  291. except Exception as e:
  292. log.exception(e)
  293. extracted_collections.extend(collection_names)
  294. if context:
  295. if "data" in file:
  296. del file["data"]
  297. relevant_contexts.append({**context, "file": file})
  298. sources = []
  299. for context in relevant_contexts:
  300. try:
  301. if "documents" in context:
  302. if "metadatas" in context:
  303. source = {
  304. "source": context["file"],
  305. "document": context["documents"][0],
  306. "metadata": context["metadatas"][0],
  307. }
  308. if "distances" in context and context["distances"]:
  309. source["distances"] = context["distances"][0]
  310. sources.append(source)
  311. except Exception as e:
  312. log.exception(e)
  313. return sources
  314. def get_model_path(model: str, update_model: bool = False):
  315. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  316. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  317. local_files_only = not update_model
  318. if OFFLINE_MODE:
  319. local_files_only = True
  320. snapshot_kwargs = {
  321. "cache_dir": cache_dir,
  322. "local_files_only": local_files_only,
  323. }
  324. log.debug(f"model: {model}")
  325. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  326. # Inspiration from upstream sentence_transformers
  327. if (
  328. os.path.exists(model)
  329. or ("\\" in model or model.count("/") > 1)
  330. and local_files_only
  331. ):
  332. # If fully qualified path exists, return input, else set repo_id
  333. return model
  334. elif "/" not in model:
  335. # Set valid repo_id for model short-name
  336. model = "sentence-transformers" + "/" + model
  337. snapshot_kwargs["repo_id"] = model
  338. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  339. try:
  340. model_repo_path = snapshot_download(**snapshot_kwargs)
  341. log.debug(f"model_repo_path: {model_repo_path}")
  342. return model_repo_path
  343. except Exception as e:
  344. log.exception(f"Cannot determine model snapshot path: {e}")
  345. return model
  346. def generate_openai_batch_embeddings(
  347. model: str, texts: list[str], url: str = "https://api.openai.com/v1", key: str = "", prefix: str = None
  348. ) -> Optional[list[list[float]]]:
  349. try:
  350. r = requests.post(
  351. f"{url}/embeddings",
  352. headers={
  353. "Content-Type": "application/json",
  354. "Authorization": f"Bearer {key}",
  355. },
  356. json={"input": texts, "model": model} if not prefix else {"input": texts, "model": model, "prefix": prefix},
  357. )
  358. r.raise_for_status()
  359. data = r.json()
  360. if "data" in data:
  361. return [elem["embedding"] for elem in data["data"]]
  362. else:
  363. raise "Something went wrong :/"
  364. except Exception as e:
  365. print(e)
  366. return None
  367. def generate_ollama_batch_embeddings(
  368. model: str, texts: list[str], url: str, key: str = "", prefix: str = None
  369. ) -> Optional[list[list[float]]]:
  370. try:
  371. r = requests.post(
  372. f"{url}/api/embed",
  373. headers={
  374. "Content-Type": "application/json",
  375. "Authorization": f"Bearer {key}",
  376. },
  377. json={"input": texts, "model": model} if not prefix else {"input": texts, "model": model, "prefix": prefix},
  378. )
  379. r.raise_for_status()
  380. data = r.json()
  381. if "embeddings" in data:
  382. return data["embeddings"]
  383. else:
  384. raise "Something went wrong :/"
  385. except Exception as e:
  386. print(e)
  387. return None
  388. def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], prefix: Union[str , None] = None, **kwargs):
  389. url = kwargs.get("url", "")
  390. key = kwargs.get("key", "")
  391. if engine == "ollama":
  392. if isinstance(text, list):
  393. embeddings = generate_ollama_batch_embeddings(
  394. **{"model": model, "texts": text, "url": url, "key": key, "prefix": prefix}
  395. )
  396. else:
  397. embeddings = generate_ollama_batch_embeddings(
  398. **{"model": model, "texts": [text], "url": url, "key": key, "prefix": prefix}
  399. )
  400. return embeddings[0] if isinstance(text, str) else embeddings
  401. elif engine == "openai":
  402. if isinstance(text, list):
  403. embeddings = generate_openai_batch_embeddings(model, text, url, key, prefix)
  404. else:
  405. embeddings = generate_openai_batch_embeddings(model, [text], url, key, prefix)
  406. return embeddings[0] if isinstance(text, str) else embeddings
  407. import operator
  408. from typing import Optional, Sequence
  409. from langchain_core.callbacks import Callbacks
  410. from langchain_core.documents import BaseDocumentCompressor, Document
  411. class RerankCompressor(BaseDocumentCompressor):
  412. embedding_function: Any
  413. top_n: int
  414. reranking_function: Any
  415. r_score: float
  416. class Config:
  417. extra = "forbid"
  418. arbitrary_types_allowed = True
  419. def compress_documents(
  420. self,
  421. documents: Sequence[Document],
  422. query: str,
  423. callbacks: Optional[Callbacks] = None,
  424. ) -> Sequence[Document]:
  425. reranking = self.reranking_function is not None
  426. if reranking:
  427. scores = self.reranking_function.predict(
  428. [(query, doc.page_content) for doc in documents]
  429. )
  430. else:
  431. from sentence_transformers import util
  432. query_embedding = self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)
  433. document_embedding = self.embedding_function(
  434. [doc.page_content for doc in documents],
  435. RAG_EMBEDDING_PASSAGE_PREFIX
  436. )
  437. scores = util.cos_sim(query_embedding, document_embedding)[0]
  438. docs_with_scores = list(zip(documents, scores.tolist()))
  439. if self.r_score:
  440. docs_with_scores = [
  441. (d, s) for d, s in docs_with_scores if s >= self.r_score
  442. ]
  443. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  444. final_results = []
  445. for doc, doc_score in result[: self.top_n]:
  446. metadata = doc.metadata
  447. metadata["score"] = doc_score
  448. doc = Document(
  449. page_content=doc.page_content,
  450. metadata=metadata,
  451. )
  452. final_results.append(doc)
  453. return final_results