utils.py 19 KB

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