utils.py 21 KB

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