utils.py 21 KB

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