utils.py 23 KB

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