utils.py 24 KB

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