utils.py 23 KB

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