utils.py 23 KB

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