utils.py 19 KB

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