utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. import logging
  2. import os
  3. from typing import Optional, Union
  4. import requests
  5. import hashlib
  6. from concurrent.futures import ThreadPoolExecutor
  7. import time
  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.factory import VECTOR_DB_CLIENT
  14. from open_webui.models.users import UserModel
  15. from open_webui.models.files import Files
  16. from open_webui.retrieval.vector.main import GetResult
  17. from open_webui.env import (
  18. SRC_LOG_LEVELS,
  19. OFFLINE_MODE,
  20. ENABLE_FORWARD_USER_INFO_HEADERS,
  21. )
  22. from open_webui.config import (
  23. RAG_EMBEDDING_QUERY_PREFIX,
  24. RAG_EMBEDDING_CONTENT_PREFIX,
  25. RAG_EMBEDDING_PREFIX_FIELD_NAME,
  26. )
  27. log = logging.getLogger(__name__)
  28. log.setLevel(SRC_LOG_LEVELS["RAG"])
  29. from typing import Any
  30. from langchain_core.callbacks import CallbackManagerForRetrieverRun
  31. from langchain_core.retrievers import BaseRetriever
  32. class VectorSearchRetriever(BaseRetriever):
  33. collection_name: Any
  34. embedding_function: Any
  35. top_k: int
  36. def _get_relevant_documents(
  37. self,
  38. query: str,
  39. *,
  40. run_manager: CallbackManagerForRetrieverRun,
  41. ) -> list[Document]:
  42. result = VECTOR_DB_CLIENT.search(
  43. collection_name=self.collection_name,
  44. vectors=[self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)],
  45. limit=self.top_k,
  46. )
  47. ids = result.ids[0]
  48. metadatas = result.metadatas[0]
  49. documents = result.documents[0]
  50. results = []
  51. for idx in range(len(ids)):
  52. results.append(
  53. Document(
  54. metadata=metadatas[idx],
  55. page_content=documents[idx],
  56. )
  57. )
  58. return results
  59. def query_doc(
  60. collection_name: str, query_embedding: list[float], k: int, user: UserModel = None
  61. ):
  62. try:
  63. log.debug(f"query_doc:doc {collection_name}")
  64. result = VECTOR_DB_CLIENT.search(
  65. collection_name=collection_name,
  66. vectors=[query_embedding],
  67. limit=k,
  68. )
  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 querying doc {collection_name} with limit {k}: {e}")
  74. raise e
  75. def get_doc(collection_name: str, user: UserModel = None):
  76. try:
  77. log.debug(f"get_doc:doc {collection_name}")
  78. result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
  79. if result:
  80. log.info(f"query_doc:result {result.ids} {result.metadatas}")
  81. return result
  82. except Exception as e:
  83. log.exception(f"Error getting doc {collection_name}: {e}")
  84. raise e
  85. def query_doc_with_hybrid_search(
  86. collection_name: str,
  87. collection_result: GetResult,
  88. query: str,
  89. embedding_function,
  90. k: int,
  91. reranking_function,
  92. k_reranker: int,
  93. r: float,
  94. hybrid_bm25_weight: float,
  95. ) -> dict:
  96. try:
  97. log.debug(f"query_doc_with_hybrid_search:doc {collection_name}")
  98. bm25_retriever = BM25Retriever.from_texts(
  99. texts=collection_result.documents[0],
  100. metadatas=collection_result.metadatas[0],
  101. )
  102. bm25_retriever.k = k
  103. vector_search_retriever = VectorSearchRetriever(
  104. collection_name=collection_name,
  105. embedding_function=embedding_function,
  106. top_k=k,
  107. )
  108. if hybrid_bm25_weight <= 0:
  109. ensemble_retriever = EnsembleRetriever(
  110. retrievers=[vector_search_retriever], weights=[1.0]
  111. )
  112. elif hybrid_bm25_weight >= 1:
  113. ensemble_retriever = EnsembleRetriever(
  114. retrievers=[bm25_retriever], weights=[1.0]
  115. )
  116. else:
  117. ensemble_retriever = EnsembleRetriever(
  118. retrievers=[bm25_retriever, vector_search_retriever],
  119. weights=[hybrid_bm25_weight, 1.0 - hybrid_bm25_weight],
  120. )
  121. compressor = RerankCompressor(
  122. embedding_function=embedding_function,
  123. top_n=k_reranker,
  124. reranking_function=reranking_function,
  125. r_score=r,
  126. )
  127. compression_retriever = ContextualCompressionRetriever(
  128. base_compressor=compressor, base_retriever=ensemble_retriever
  129. )
  130. result = compression_retriever.invoke(query)
  131. distances = [d.metadata.get("score") for d in result]
  132. documents = [d.page_content for d in result]
  133. metadatas = [d.metadata for d in result]
  134. # retrieve only min(k, k_reranker) items, sort and cut by distance if k < k_reranker
  135. if k < k_reranker:
  136. sorted_items = sorted(
  137. zip(distances, metadatas, documents), key=lambda x: x[0], reverse=True
  138. )
  139. sorted_items = sorted_items[:k]
  140. distances, documents, metadatas = map(list, zip(*sorted_items))
  141. result = {
  142. "distances": [distances],
  143. "documents": [documents],
  144. "metadatas": [metadatas],
  145. }
  146. log.info(
  147. "query_doc_with_hybrid_search:result "
  148. + f'{result["metadatas"]} {result["distances"]}'
  149. )
  150. return result
  151. except Exception as e:
  152. log.exception(f"Error querying doc {collection_name} with hybrid search: {e}")
  153. raise e
  154. def merge_get_results(get_results: list[dict]) -> dict:
  155. # Initialize lists to store combined data
  156. combined_documents = []
  157. combined_metadatas = []
  158. combined_ids = []
  159. for data in get_results:
  160. combined_documents.extend(data["documents"][0])
  161. combined_metadatas.extend(data["metadatas"][0])
  162. combined_ids.extend(data["ids"][0])
  163. # Create the output dictionary
  164. result = {
  165. "documents": [combined_documents],
  166. "metadatas": [combined_metadatas],
  167. "ids": [combined_ids],
  168. }
  169. return result
  170. def merge_and_sort_query_results(query_results: list[dict], k: int) -> dict:
  171. # Initialize lists to store combined data
  172. combined = dict() # To store documents with unique document hashes
  173. for data in query_results:
  174. distances = data["distances"][0]
  175. documents = data["documents"][0]
  176. metadatas = data["metadatas"][0]
  177. for distance, document, metadata in zip(distances, documents, metadatas):
  178. if isinstance(document, str):
  179. doc_hash = hashlib.sha256(
  180. document.encode()
  181. ).hexdigest() # Compute a hash for uniqueness
  182. if doc_hash not in combined.keys():
  183. combined[doc_hash] = (distance, document, metadata)
  184. continue # if doc is new, no further comparison is needed
  185. # if doc is alredy in, but new distance is better, update
  186. if distance > combined[doc_hash][0]:
  187. combined[doc_hash] = (distance, document, metadata)
  188. combined = list(combined.values())
  189. # Sort the list based on distances
  190. combined.sort(key=lambda x: x[0], reverse=True)
  191. # Slice to keep only the top k elements
  192. sorted_distances, sorted_documents, sorted_metadatas = (
  193. zip(*combined[:k]) if combined else ([], [], [])
  194. )
  195. # Create and return the output dictionary
  196. return {
  197. "distances": [list(sorted_distances)],
  198. "documents": [list(sorted_documents)],
  199. "metadatas": [list(sorted_metadatas)],
  200. }
  201. def get_all_items_from_collections(collection_names: list[str]) -> dict:
  202. results = []
  203. for collection_name in collection_names:
  204. if collection_name:
  205. try:
  206. result = get_doc(collection_name=collection_name)
  207. if result is not None:
  208. results.append(result.model_dump())
  209. except Exception as e:
  210. log.exception(f"Error when querying the collection: {e}")
  211. else:
  212. pass
  213. return merge_get_results(results)
  214. def query_collection(
  215. collection_names: list[str],
  216. queries: list[str],
  217. embedding_function,
  218. k: int,
  219. ) -> dict:
  220. results = []
  221. error = False
  222. def process_query_collection(collection_name, query_embedding):
  223. try:
  224. if collection_name:
  225. result = query_doc(
  226. collection_name=collection_name,
  227. k=k,
  228. query_embedding=query_embedding,
  229. )
  230. if result is not None:
  231. return result.model_dump(), None
  232. return None, None
  233. except Exception as e:
  234. log.exception(f"Error when querying the collection: {e}")
  235. return None, e
  236. # Generate all query embeddings (in one call)
  237. query_embeddings = embedding_function(queries, prefix=RAG_EMBEDDING_QUERY_PREFIX)
  238. log.debug(
  239. f"query_collection: processing {len(queries)} queries across {len(collection_names)} collections"
  240. )
  241. with ThreadPoolExecutor() as executor:
  242. future_results = []
  243. for query_embedding in query_embeddings:
  244. for collection_name in collection_names:
  245. result = executor.submit(
  246. process_query_collection, collection_name, query_embedding
  247. )
  248. future_results.append(result)
  249. task_results = [future.result() for future in future_results]
  250. for result, err in task_results:
  251. if err is not None:
  252. error = True
  253. elif result is not None:
  254. results.append(result)
  255. if error and not results:
  256. log.warning("All collection queries failed. No results returned.")
  257. return merge_and_sort_query_results(results, k=k)
  258. def query_collection_with_hybrid_search(
  259. collection_names: list[str],
  260. queries: list[str],
  261. embedding_function,
  262. k: int,
  263. reranking_function,
  264. k_reranker: int,
  265. r: float,
  266. hybrid_bm25_weight: float,
  267. ) -> dict:
  268. results = []
  269. error = False
  270. # Fetch collection data once per collection sequentially
  271. # Avoid fetching the same data multiple times later
  272. collection_results = {}
  273. for collection_name in collection_names:
  274. try:
  275. log.debug(
  276. f"query_collection_with_hybrid_search:VECTOR_DB_CLIENT.get:collection {collection_name}"
  277. )
  278. collection_results[collection_name] = VECTOR_DB_CLIENT.get(
  279. collection_name=collection_name
  280. )
  281. except Exception as e:
  282. log.exception(f"Failed to fetch collection {collection_name}: {e}")
  283. collection_results[collection_name] = None
  284. log.info(
  285. f"Starting hybrid search for {len(queries)} queries in {len(collection_names)} collections..."
  286. )
  287. def process_query(collection_name, query):
  288. try:
  289. result = query_doc_with_hybrid_search(
  290. collection_name=collection_name,
  291. collection_result=collection_results[collection_name],
  292. query=query,
  293. embedding_function=embedding_function,
  294. k=k,
  295. reranking_function=reranking_function,
  296. k_reranker=k_reranker,
  297. r=r,
  298. hybrid_bm25_weight=hybrid_bm25_weight,
  299. )
  300. return result, None
  301. except Exception as e:
  302. log.exception(f"Error when querying the collection with hybrid_search: {e}")
  303. return None, e
  304. # Prepare tasks for all collections and queries
  305. # Avoid running any tasks for collections that failed to fetch data (have assigned None)
  306. tasks = [
  307. (cn, q)
  308. for cn in collection_names
  309. if collection_results[cn] is not None
  310. for q in queries
  311. ]
  312. with ThreadPoolExecutor() as executor:
  313. future_results = [executor.submit(process_query, cn, q) for cn, q in tasks]
  314. task_results = [future.result() for future in future_results]
  315. for result, err in task_results:
  316. if err is not None:
  317. error = True
  318. elif result is not None:
  319. results.append(result)
  320. if error and not results:
  321. raise Exception(
  322. "Hybrid search failed for all collections. Using Non-hybrid search as fallback."
  323. )
  324. return merge_and_sort_query_results(results, k=k)
  325. def get_embedding_function(
  326. embedding_engine,
  327. embedding_model,
  328. embedding_function,
  329. url,
  330. key,
  331. embedding_batch_size,
  332. azure_api_version=None,
  333. ):
  334. if embedding_engine == "":
  335. return lambda query, prefix=None, user=None: embedding_function.encode(
  336. query, **({"prompt": prefix} if prefix else {})
  337. ).tolist()
  338. elif embedding_engine in ["ollama", "openai", "azure_openai"]:
  339. func = lambda query, prefix=None, user=None: generate_embeddings(
  340. engine=embedding_engine,
  341. model=embedding_model,
  342. text=query,
  343. prefix=prefix,
  344. url=url,
  345. key=key,
  346. user=user,
  347. azure_api_version=azure_api_version,
  348. )
  349. def generate_multiple(query, prefix, user, func):
  350. if isinstance(query, list):
  351. embeddings = []
  352. for i in range(0, len(query), embedding_batch_size):
  353. embeddings.extend(
  354. func(
  355. query[i : i + embedding_batch_size],
  356. prefix=prefix,
  357. user=user,
  358. )
  359. )
  360. return embeddings
  361. else:
  362. return func(query, prefix, user)
  363. return lambda query, prefix=None, user=None: generate_multiple(
  364. query, prefix, user, func
  365. )
  366. else:
  367. raise ValueError(f"Unknown embedding engine: {embedding_engine}")
  368. def get_sources_from_files(
  369. request,
  370. files,
  371. queries,
  372. embedding_function,
  373. k,
  374. reranking_function,
  375. k_reranker,
  376. r,
  377. hybrid_bm25_weight,
  378. hybrid_search,
  379. full_context=False,
  380. ):
  381. log.debug(
  382. f"files: {files} {queries} {embedding_function} {reranking_function} {full_context}"
  383. )
  384. extracted_collections = []
  385. relevant_contexts = []
  386. for file in files:
  387. context = None
  388. if file.get("docs"):
  389. # BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL
  390. context = {
  391. "documents": [[doc.get("content") for doc in file.get("docs")]],
  392. "metadatas": [[doc.get("metadata") for doc in file.get("docs")]],
  393. }
  394. elif file.get("context") == "full":
  395. # Manual Full Mode Toggle
  396. context = {
  397. "documents": [[file.get("file").get("data", {}).get("content")]],
  398. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  399. }
  400. elif (
  401. file.get("type") != "web_search"
  402. and request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
  403. ):
  404. # BYPASS_EMBEDDING_AND_RETRIEVAL
  405. if file.get("type") == "collection":
  406. file_ids = file.get("data", {}).get("file_ids", [])
  407. documents = []
  408. metadatas = []
  409. for file_id in file_ids:
  410. file_object = Files.get_file_by_id(file_id)
  411. if file_object:
  412. documents.append(file_object.data.get("content", ""))
  413. metadatas.append(
  414. {
  415. "file_id": file_id,
  416. "name": file_object.filename,
  417. "source": file_object.filename,
  418. }
  419. )
  420. context = {
  421. "documents": [documents],
  422. "metadatas": [metadatas],
  423. }
  424. elif file.get("id"):
  425. file_object = Files.get_file_by_id(file.get("id"))
  426. if file_object:
  427. context = {
  428. "documents": [[file_object.data.get("content", "")]],
  429. "metadatas": [
  430. [
  431. {
  432. "file_id": file.get("id"),
  433. "name": file_object.filename,
  434. "source": file_object.filename,
  435. }
  436. ]
  437. ],
  438. }
  439. elif file.get("file").get("data"):
  440. context = {
  441. "documents": [[file.get("file").get("data", {}).get("content")]],
  442. "metadatas": [
  443. [file.get("file").get("data", {}).get("metadata", {})]
  444. ],
  445. }
  446. else:
  447. collection_names = []
  448. if file.get("type") == "collection":
  449. if file.get("legacy"):
  450. collection_names = file.get("collection_names", [])
  451. else:
  452. collection_names.append(file["id"])
  453. elif file.get("collection_name"):
  454. collection_names.append(file["collection_name"])
  455. elif file.get("id"):
  456. if file.get("legacy"):
  457. collection_names.append(f"{file['id']}")
  458. else:
  459. collection_names.append(f"file-{file['id']}")
  460. collection_names = set(collection_names).difference(extracted_collections)
  461. if not collection_names:
  462. log.debug(f"skipping {file} as it has already been extracted")
  463. continue
  464. if full_context:
  465. try:
  466. context = get_all_items_from_collections(collection_names)
  467. except Exception as e:
  468. log.exception(e)
  469. else:
  470. try:
  471. context = None
  472. if file.get("type") == "text":
  473. context = file["content"]
  474. else:
  475. if hybrid_search:
  476. try:
  477. context = query_collection_with_hybrid_search(
  478. collection_names=collection_names,
  479. queries=queries,
  480. embedding_function=embedding_function,
  481. k=k,
  482. reranking_function=reranking_function,
  483. k_reranker=k_reranker,
  484. r=r,
  485. hybrid_bm25_weight=hybrid_bm25_weight,
  486. )
  487. except Exception as e:
  488. log.debug(
  489. "Error when using hybrid search, using"
  490. " non hybrid search as fallback."
  491. )
  492. if (not hybrid_search) or (context is None):
  493. context = query_collection(
  494. collection_names=collection_names,
  495. queries=queries,
  496. embedding_function=embedding_function,
  497. k=k,
  498. )
  499. except Exception as e:
  500. log.exception(e)
  501. extracted_collections.extend(collection_names)
  502. if context:
  503. if "data" in file:
  504. del file["data"]
  505. relevant_contexts.append({**context, "file": file})
  506. sources = []
  507. for context in relevant_contexts:
  508. try:
  509. if "documents" in context:
  510. if "metadatas" in context:
  511. source = {
  512. "source": context["file"],
  513. "document": context["documents"][0],
  514. "metadata": context["metadatas"][0],
  515. }
  516. if "distances" in context and context["distances"]:
  517. source["distances"] = context["distances"][0]
  518. sources.append(source)
  519. except Exception as e:
  520. log.exception(e)
  521. return sources
  522. def get_model_path(model: str, update_model: bool = False):
  523. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  524. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  525. local_files_only = not update_model
  526. if OFFLINE_MODE:
  527. local_files_only = True
  528. snapshot_kwargs = {
  529. "cache_dir": cache_dir,
  530. "local_files_only": local_files_only,
  531. }
  532. log.debug(f"model: {model}")
  533. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  534. # Inspiration from upstream sentence_transformers
  535. if (
  536. os.path.exists(model)
  537. or ("\\" in model or model.count("/") > 1)
  538. and local_files_only
  539. ):
  540. # If fully qualified path exists, return input, else set repo_id
  541. return model
  542. elif "/" not in model:
  543. # Set valid repo_id for model short-name
  544. model = "sentence-transformers" + "/" + model
  545. snapshot_kwargs["repo_id"] = model
  546. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  547. try:
  548. model_repo_path = snapshot_download(**snapshot_kwargs)
  549. log.debug(f"model_repo_path: {model_repo_path}")
  550. return model_repo_path
  551. except Exception as e:
  552. log.exception(f"Cannot determine model snapshot path: {e}")
  553. return model
  554. def generate_openai_batch_embeddings(
  555. model: str,
  556. texts: list[str],
  557. url: str = "https://api.openai.com/v1",
  558. key: str = "",
  559. prefix: str = None,
  560. user: UserModel = None,
  561. ) -> Optional[list[list[float]]]:
  562. try:
  563. log.debug(
  564. f"generate_openai_batch_embeddings:model {model} batch size: {len(texts)}"
  565. )
  566. json_data = {"input": texts, "model": model}
  567. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  568. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  569. r = requests.post(
  570. f"{url}/embeddings",
  571. headers={
  572. "Content-Type": "application/json",
  573. "Authorization": f"Bearer {key}",
  574. **(
  575. {
  576. "X-OpenWebUI-User-Name": user.name,
  577. "X-OpenWebUI-User-Id": user.id,
  578. "X-OpenWebUI-User-Email": user.email,
  579. "X-OpenWebUI-User-Role": user.role,
  580. }
  581. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  582. else {}
  583. ),
  584. },
  585. json=json_data,
  586. )
  587. r.raise_for_status()
  588. data = r.json()
  589. if "data" in data:
  590. return [elem["embedding"] for elem in data["data"]]
  591. else:
  592. raise "Something went wrong :/"
  593. except Exception as e:
  594. log.exception(f"Error generating openai batch embeddings: {e}")
  595. return None
  596. def generate_azure_openai_batch_embeddings(
  597. model: str,
  598. texts: list[str],
  599. url: str,
  600. key: str = "",
  601. version: str = "",
  602. prefix: str = None,
  603. user: UserModel = None,
  604. ) -> Optional[list[list[float]]]:
  605. try:
  606. log.debug(
  607. f"generate_azure_openai_batch_embeddings:deployment {model} batch size: {len(texts)}"
  608. )
  609. json_data = {"input": texts}
  610. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  611. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  612. url = f"{url}/openai/deployments/{model}/embeddings?api-version={version}"
  613. for _ in range(5):
  614. r = requests.post(
  615. url,
  616. headers={
  617. "Content-Type": "application/json",
  618. "api-key": key,
  619. **(
  620. {
  621. "X-OpenWebUI-User-Name": user.name,
  622. "X-OpenWebUI-User-Id": user.id,
  623. "X-OpenWebUI-User-Email": user.email,
  624. "X-OpenWebUI-User-Role": user.role,
  625. }
  626. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  627. else {}
  628. ),
  629. },
  630. json=json_data,
  631. )
  632. if r.status_code == 429:
  633. retry = float(r.headers.get("Retry-After", "1"))
  634. time.sleep(retry)
  635. continue
  636. r.raise_for_status()
  637. data = r.json()
  638. if "data" in data:
  639. return [elem["embedding"] for elem in data["data"]]
  640. else:
  641. raise Exception("Something went wrong :/")
  642. return None
  643. except Exception as e:
  644. log.exception(f"Error generating azure openai batch embeddings: {e}")
  645. return None
  646. def generate_ollama_batch_embeddings(
  647. model: str,
  648. texts: list[str],
  649. url: str,
  650. key: str = "",
  651. prefix: str = None,
  652. user: UserModel = None,
  653. ) -> Optional[list[list[float]]]:
  654. try:
  655. log.debug(
  656. f"generate_ollama_batch_embeddings:model {model} batch size: {len(texts)}"
  657. )
  658. json_data = {"input": texts, "model": model}
  659. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  660. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  661. r = requests.post(
  662. f"{url}/api/embed",
  663. headers={
  664. "Content-Type": "application/json",
  665. "Authorization": f"Bearer {key}",
  666. **(
  667. {
  668. "X-OpenWebUI-User-Name": user.name,
  669. "X-OpenWebUI-User-Id": user.id,
  670. "X-OpenWebUI-User-Email": user.email,
  671. "X-OpenWebUI-User-Role": user.role,
  672. }
  673. if ENABLE_FORWARD_USER_INFO_HEADERS
  674. else {}
  675. ),
  676. },
  677. json=json_data,
  678. )
  679. r.raise_for_status()
  680. data = r.json()
  681. if "embeddings" in data:
  682. return data["embeddings"]
  683. else:
  684. raise "Something went wrong :/"
  685. except Exception as e:
  686. log.exception(f"Error generating ollama batch embeddings: {e}")
  687. return None
  688. def generate_embeddings(
  689. engine: str,
  690. model: str,
  691. text: Union[str, list[str]],
  692. prefix: Union[str, None] = None,
  693. **kwargs,
  694. ):
  695. url = kwargs.get("url", "")
  696. key = kwargs.get("key", "")
  697. user = kwargs.get("user")
  698. if prefix is not None and RAG_EMBEDDING_PREFIX_FIELD_NAME is None:
  699. if isinstance(text, list):
  700. text = [f"{prefix}{text_element}" for text_element in text]
  701. else:
  702. text = f"{prefix}{text}"
  703. if engine == "ollama":
  704. embeddings = generate_ollama_batch_embeddings(
  705. **{
  706. "model": model,
  707. "texts": text if isinstance(text, list) else [text],
  708. "url": url,
  709. "key": key,
  710. "prefix": prefix,
  711. "user": user,
  712. }
  713. )
  714. return embeddings[0] if isinstance(text, str) else embeddings
  715. elif engine == "openai":
  716. embeddings = generate_openai_batch_embeddings(
  717. model, text if isinstance(text, list) else [text], url, key, prefix, user
  718. )
  719. return embeddings[0] if isinstance(text, str) else embeddings
  720. elif engine == "azure_openai":
  721. azure_api_version = kwargs.get("azure_api_version", "")
  722. embeddings = generate_azure_openai_batch_embeddings(
  723. model,
  724. text if isinstance(text, list) else [text],
  725. url,
  726. key,
  727. azure_api_version,
  728. prefix,
  729. user,
  730. )
  731. return embeddings[0] if isinstance(text, str) else embeddings
  732. import operator
  733. from typing import Optional, Sequence
  734. from langchain_core.callbacks import Callbacks
  735. from langchain_core.documents import BaseDocumentCompressor, Document
  736. class RerankCompressor(BaseDocumentCompressor):
  737. embedding_function: Any
  738. top_n: int
  739. reranking_function: Any
  740. r_score: float
  741. class Config:
  742. extra = "forbid"
  743. arbitrary_types_allowed = True
  744. def compress_documents(
  745. self,
  746. documents: Sequence[Document],
  747. query: str,
  748. callbacks: Optional[Callbacks] = None,
  749. ) -> Sequence[Document]:
  750. reranking = self.reranking_function is not None
  751. if reranking:
  752. scores = self.reranking_function.predict(
  753. [(query, doc.page_content) for doc in documents]
  754. )
  755. else:
  756. from sentence_transformers import util
  757. query_embedding = self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)
  758. document_embedding = self.embedding_function(
  759. [doc.page_content for doc in documents], RAG_EMBEDDING_CONTENT_PREFIX
  760. )
  761. scores = util.cos_sim(query_embedding, document_embedding)[0]
  762. docs_with_scores = list(
  763. zip(documents, scores.tolist() if not isinstance(scores, list) else scores)
  764. )
  765. if self.r_score:
  766. docs_with_scores = [
  767. (d, s) for d, s in docs_with_scores if s >= self.r_score
  768. ]
  769. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  770. final_results = []
  771. for doc, doc_score in result[: self.top_n]:
  772. metadata = doc.metadata
  773. metadata["score"] = doc_score
  774. doc = Document(
  775. page_content=doc.page_content,
  776. metadata=metadata,
  777. )
  778. final_results.append(doc)
  779. return final_results