utils.py 23 KB

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