utils.py 22 KB

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