utils.py 23 KB

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