utils.py 23 KB

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