utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. print("context", context)
  343. except Exception as e:
  344. log.exception(e)
  345. else:
  346. try:
  347. context = None
  348. if file.get("type") == "text":
  349. context = file["content"]
  350. else:
  351. if hybrid_search:
  352. try:
  353. context = query_collection_with_hybrid_search(
  354. collection_names=collection_names,
  355. queries=queries,
  356. embedding_function=embedding_function,
  357. k=k,
  358. reranking_function=reranking_function,
  359. r=r,
  360. )
  361. except Exception as e:
  362. log.debug(
  363. "Error when using hybrid search, using"
  364. " non hybrid search as fallback."
  365. )
  366. if (not hybrid_search) or (context is None):
  367. context = query_collection(
  368. collection_names=collection_names,
  369. queries=queries,
  370. embedding_function=embedding_function,
  371. k=k,
  372. )
  373. except Exception as e:
  374. log.exception(e)
  375. extracted_collections.extend(collection_names)
  376. if context:
  377. if "data" in file:
  378. del file["data"]
  379. relevant_contexts.append({**context, "file": file})
  380. sources = []
  381. for context in relevant_contexts:
  382. try:
  383. if "documents" in context:
  384. if "metadatas" in context:
  385. source = {
  386. "source": context["file"],
  387. "document": context["documents"][0],
  388. "metadata": context["metadatas"][0],
  389. }
  390. if "distances" in context and context["distances"]:
  391. source["distances"] = context["distances"][0]
  392. sources.append(source)
  393. except Exception as e:
  394. log.exception(e)
  395. return sources
  396. def get_model_path(model: str, update_model: bool = False):
  397. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  398. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  399. local_files_only = not update_model
  400. if OFFLINE_MODE:
  401. local_files_only = True
  402. snapshot_kwargs = {
  403. "cache_dir": cache_dir,
  404. "local_files_only": local_files_only,
  405. }
  406. log.debug(f"model: {model}")
  407. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  408. # Inspiration from upstream sentence_transformers
  409. if (
  410. os.path.exists(model)
  411. or ("\\" in model or model.count("/") > 1)
  412. and local_files_only
  413. ):
  414. # If fully qualified path exists, return input, else set repo_id
  415. return model
  416. elif "/" not in model:
  417. # Set valid repo_id for model short-name
  418. model = "sentence-transformers" + "/" + model
  419. snapshot_kwargs["repo_id"] = model
  420. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  421. try:
  422. model_repo_path = snapshot_download(**snapshot_kwargs)
  423. log.debug(f"model_repo_path: {model_repo_path}")
  424. return model_repo_path
  425. except Exception as e:
  426. log.exception(f"Cannot determine model snapshot path: {e}")
  427. return model
  428. def generate_openai_batch_embeddings(
  429. model: str,
  430. texts: list[str],
  431. url: str = "https://api.openai.com/v1",
  432. key: str = "",
  433. user: UserModel = None,
  434. ) -> Optional[list[list[float]]]:
  435. try:
  436. r = requests.post(
  437. f"{url}/embeddings",
  438. headers={
  439. "Content-Type": "application/json",
  440. "Authorization": f"Bearer {key}",
  441. **(
  442. {
  443. "X-OpenWebUI-User-Name": user.name,
  444. "X-OpenWebUI-User-Id": user.id,
  445. "X-OpenWebUI-User-Email": user.email,
  446. "X-OpenWebUI-User-Role": user.role,
  447. }
  448. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  449. else {}
  450. ),
  451. },
  452. json={"input": texts, "model": model},
  453. )
  454. r.raise_for_status()
  455. data = r.json()
  456. if "data" in data:
  457. return [elem["embedding"] for elem in data["data"]]
  458. else:
  459. raise "Something went wrong :/"
  460. except Exception as e:
  461. print(e)
  462. return None
  463. def generate_ollama_batch_embeddings(
  464. model: str, texts: list[str], url: str, key: str = "", user: UserModel = None
  465. ) -> Optional[list[list[float]]]:
  466. try:
  467. r = requests.post(
  468. f"{url}/api/embed",
  469. headers={
  470. "Content-Type": "application/json",
  471. "Authorization": f"Bearer {key}",
  472. **(
  473. {
  474. "X-OpenWebUI-User-Name": user.name,
  475. "X-OpenWebUI-User-Id": user.id,
  476. "X-OpenWebUI-User-Email": user.email,
  477. "X-OpenWebUI-User-Role": user.role,
  478. }
  479. if ENABLE_FORWARD_USER_INFO_HEADERS
  480. else {}
  481. ),
  482. },
  483. json={"input": texts, "model": model},
  484. )
  485. r.raise_for_status()
  486. data = r.json()
  487. if "embeddings" in data:
  488. return data["embeddings"]
  489. else:
  490. raise "Something went wrong :/"
  491. except Exception as e:
  492. print(e)
  493. return None
  494. def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], **kwargs):
  495. url = kwargs.get("url", "")
  496. key = kwargs.get("key", "")
  497. user = kwargs.get("user")
  498. if engine == "ollama":
  499. if isinstance(text, list):
  500. embeddings = generate_ollama_batch_embeddings(
  501. **{"model": model, "texts": text, "url": url, "key": key, "user": user}
  502. )
  503. else:
  504. embeddings = generate_ollama_batch_embeddings(
  505. **{
  506. "model": model,
  507. "texts": [text],
  508. "url": url,
  509. "key": key,
  510. "user": user,
  511. }
  512. )
  513. return embeddings[0] if isinstance(text, str) else embeddings
  514. elif engine == "openai":
  515. if isinstance(text, list):
  516. embeddings = generate_openai_batch_embeddings(model, text, url, key, user)
  517. else:
  518. embeddings = generate_openai_batch_embeddings(model, [text], url, key, user)
  519. return embeddings[0] if isinstance(text, str) else embeddings
  520. import operator
  521. from typing import Optional, Sequence
  522. from langchain_core.callbacks import Callbacks
  523. from langchain_core.documents import BaseDocumentCompressor, Document
  524. class RerankCompressor(BaseDocumentCompressor):
  525. embedding_function: Any
  526. top_n: int
  527. reranking_function: Any
  528. r_score: float
  529. class Config:
  530. extra = "forbid"
  531. arbitrary_types_allowed = True
  532. def compress_documents(
  533. self,
  534. documents: Sequence[Document],
  535. query: str,
  536. callbacks: Optional[Callbacks] = None,
  537. ) -> Sequence[Document]:
  538. reranking = self.reranking_function is not None
  539. if reranking:
  540. scores = self.reranking_function.predict(
  541. [(query, doc.page_content) for doc in documents]
  542. )
  543. else:
  544. from sentence_transformers import util
  545. query_embedding = self.embedding_function(query)
  546. document_embedding = self.embedding_function(
  547. [doc.page_content for doc in documents]
  548. )
  549. scores = util.cos_sim(query_embedding, document_embedding)[0]
  550. docs_with_scores = list(zip(documents, scores.tolist()))
  551. if self.r_score:
  552. docs_with_scores = [
  553. (d, s) for d, s in docs_with_scores if s >= self.r_score
  554. ]
  555. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  556. final_results = []
  557. for doc, doc_score in result[: self.top_n]:
  558. metadata = doc.metadata
  559. metadata["score"] = doc_score
  560. doc = Document(
  561. page_content=doc.page_content,
  562. metadata=metadata,
  563. )
  564. final_results.append(doc)
  565. return final_results