utils.py 21 KB

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