utils.py 22 KB

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