utils.py 22 KB

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