utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. deployment=None,
  333. version=None,
  334. ):
  335. if embedding_engine == "":
  336. return lambda query, prefix=None, user=None: embedding_function.encode(
  337. query, **({"prompt": prefix} if prefix else {})
  338. ).tolist()
  339. elif embedding_engine in ["ollama", "openai", "azure_openai"]:
  340. func = lambda query, prefix=None, user=None: generate_embeddings(
  341. engine=embedding_engine,
  342. model=embedding_model,
  343. text=query,
  344. prefix=prefix,
  345. url=url,
  346. key=key,
  347. user=user,
  348. deployment=deployment,
  349. version=version,
  350. )
  351. def generate_multiple(query, prefix, user, func):
  352. if isinstance(query, list):
  353. embeddings = []
  354. for i in range(0, len(query), embedding_batch_size):
  355. embeddings.extend(
  356. func(
  357. query[i : i + embedding_batch_size],
  358. prefix=prefix,
  359. user=user,
  360. )
  361. )
  362. return embeddings
  363. else:
  364. return func(query, prefix, user)
  365. return lambda query, prefix=None, user=None: generate_multiple(
  366. query, prefix, user, func
  367. )
  368. else:
  369. raise ValueError(f"Unknown embedding engine: {embedding_engine}")
  370. def get_sources_from_files(
  371. request,
  372. files,
  373. queries,
  374. embedding_function,
  375. k,
  376. reranking_function,
  377. k_reranker,
  378. r,
  379. hybrid_bm25_weight,
  380. hybrid_search,
  381. full_context=False,
  382. ):
  383. log.debug(
  384. f"files: {files} {queries} {embedding_function} {reranking_function} {full_context}"
  385. )
  386. extracted_collections = []
  387. relevant_contexts = []
  388. for file in files:
  389. context = None
  390. if file.get("docs"):
  391. # BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL
  392. context = {
  393. "documents": [[doc.get("content") for doc in file.get("docs")]],
  394. "metadatas": [[doc.get("metadata") for doc in file.get("docs")]],
  395. }
  396. elif file.get("context") == "full":
  397. # Manual Full Mode Toggle
  398. context = {
  399. "documents": [[file.get("file").get("data", {}).get("content")]],
  400. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  401. }
  402. elif (
  403. file.get("type") != "web_search"
  404. and request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
  405. ):
  406. # BYPASS_EMBEDDING_AND_RETRIEVAL
  407. if file.get("type") == "collection":
  408. file_ids = file.get("data", {}).get("file_ids", [])
  409. documents = []
  410. metadatas = []
  411. for file_id in file_ids:
  412. file_object = Files.get_file_by_id(file_id)
  413. if file_object:
  414. documents.append(file_object.data.get("content", ""))
  415. metadatas.append(
  416. {
  417. "file_id": file_id,
  418. "name": file_object.filename,
  419. "source": file_object.filename,
  420. }
  421. )
  422. context = {
  423. "documents": [documents],
  424. "metadatas": [metadatas],
  425. }
  426. elif file.get("id"):
  427. file_object = Files.get_file_by_id(file.get("id"))
  428. if file_object:
  429. context = {
  430. "documents": [[file_object.data.get("content", "")]],
  431. "metadatas": [
  432. [
  433. {
  434. "file_id": file.get("id"),
  435. "name": file_object.filename,
  436. "source": file_object.filename,
  437. }
  438. ]
  439. ],
  440. }
  441. elif file.get("file").get("data"):
  442. context = {
  443. "documents": [[file.get("file").get("data", {}).get("content")]],
  444. "metadatas": [
  445. [file.get("file").get("data", {}).get("metadata", {})]
  446. ],
  447. }
  448. else:
  449. collection_names = []
  450. if file.get("type") == "collection":
  451. if file.get("legacy"):
  452. collection_names = file.get("collection_names", [])
  453. else:
  454. collection_names.append(file["id"])
  455. elif file.get("collection_name"):
  456. collection_names.append(file["collection_name"])
  457. elif file.get("id"):
  458. if file.get("legacy"):
  459. collection_names.append(f"{file['id']}")
  460. else:
  461. collection_names.append(f"file-{file['id']}")
  462. collection_names = set(collection_names).difference(extracted_collections)
  463. if not collection_names:
  464. log.debug(f"skipping {file} as it has already been extracted")
  465. continue
  466. if full_context:
  467. try:
  468. context = get_all_items_from_collections(collection_names)
  469. except Exception as e:
  470. log.exception(e)
  471. else:
  472. try:
  473. context = None
  474. if file.get("type") == "text":
  475. context = file["content"]
  476. else:
  477. if hybrid_search:
  478. try:
  479. context = query_collection_with_hybrid_search(
  480. collection_names=collection_names,
  481. queries=queries,
  482. embedding_function=embedding_function,
  483. k=k,
  484. reranking_function=reranking_function,
  485. k_reranker=k_reranker,
  486. r=r,
  487. hybrid_bm25_weight=hybrid_bm25_weight,
  488. )
  489. except Exception as e:
  490. log.debug(
  491. "Error when using hybrid search, using"
  492. " non hybrid search as fallback."
  493. )
  494. if (not hybrid_search) or (context is None):
  495. context = query_collection(
  496. collection_names=collection_names,
  497. queries=queries,
  498. embedding_function=embedding_function,
  499. k=k,
  500. )
  501. except Exception as e:
  502. log.exception(e)
  503. extracted_collections.extend(collection_names)
  504. if context:
  505. if "data" in file:
  506. del file["data"]
  507. relevant_contexts.append({**context, "file": file})
  508. sources = []
  509. for context in relevant_contexts:
  510. try:
  511. if "documents" in context:
  512. if "metadatas" in context:
  513. source = {
  514. "source": context["file"],
  515. "document": context["documents"][0],
  516. "metadata": context["metadatas"][0],
  517. }
  518. if "distances" in context and context["distances"]:
  519. source["distances"] = context["distances"][0]
  520. sources.append(source)
  521. except Exception as e:
  522. log.exception(e)
  523. return sources
  524. def get_model_path(model: str, update_model: bool = False):
  525. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  526. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  527. local_files_only = not update_model
  528. if OFFLINE_MODE:
  529. local_files_only = True
  530. snapshot_kwargs = {
  531. "cache_dir": cache_dir,
  532. "local_files_only": local_files_only,
  533. }
  534. log.debug(f"model: {model}")
  535. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  536. # Inspiration from upstream sentence_transformers
  537. if (
  538. os.path.exists(model)
  539. or ("\\" in model or model.count("/") > 1)
  540. and local_files_only
  541. ):
  542. # If fully qualified path exists, return input, else set repo_id
  543. return model
  544. elif "/" not in model:
  545. # Set valid repo_id for model short-name
  546. model = "sentence-transformers" + "/" + model
  547. snapshot_kwargs["repo_id"] = model
  548. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  549. try:
  550. model_repo_path = snapshot_download(**snapshot_kwargs)
  551. log.debug(f"model_repo_path: {model_repo_path}")
  552. return model_repo_path
  553. except Exception as e:
  554. log.exception(f"Cannot determine model snapshot path: {e}")
  555. return model
  556. def generate_openai_batch_embeddings(
  557. model: str,
  558. texts: list[str],
  559. url: str = "https://api.openai.com/v1",
  560. key: str = "",
  561. prefix: str = None,
  562. user: UserModel = None,
  563. ) -> Optional[list[list[float]]]:
  564. try:
  565. log.debug(
  566. f"generate_openai_batch_embeddings:model {model} batch size: {len(texts)}"
  567. )
  568. json_data = {"input": texts, "model": model}
  569. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  570. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  571. r = requests.post(
  572. f"{url}/embeddings",
  573. headers={
  574. "Content-Type": "application/json",
  575. "Authorization": f"Bearer {key}",
  576. **(
  577. {
  578. "X-OpenWebUI-User-Name": user.name,
  579. "X-OpenWebUI-User-Id": user.id,
  580. "X-OpenWebUI-User-Email": user.email,
  581. "X-OpenWebUI-User-Role": user.role,
  582. }
  583. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  584. else {}
  585. ),
  586. },
  587. json=json_data,
  588. )
  589. r.raise_for_status()
  590. data = r.json()
  591. if "data" in data:
  592. return [elem["embedding"] for elem in data["data"]]
  593. else:
  594. raise "Something went wrong :/"
  595. except Exception as e:
  596. log.exception(f"Error generating openai batch embeddings: {e}")
  597. return None
  598. def generate_azure_openai_batch_embeddings(
  599. deployment: str,
  600. texts: list[str],
  601. url: str,
  602. key: str = "",
  603. model: str = "",
  604. version: str = "",
  605. prefix: str = None,
  606. user: UserModel = None,
  607. ) -> Optional[list[list[float]]]:
  608. try:
  609. log.debug(
  610. f"generate_azure_openai_batch_embeddings:deployment {deployment} batch size: {len(texts)}"
  611. )
  612. json_data = {"input": texts, "model": model}
  613. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  614. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  615. url = f"{url}/openai/deployments/{deployment}/embeddings?api-version={version}"
  616. for _ in range(5):
  617. r = requests.post(
  618. url,
  619. headers={
  620. "Content-Type": "application/json",
  621. "api-key": key,
  622. **(
  623. {
  624. "X-OpenWebUI-User-Name": user.name,
  625. "X-OpenWebUI-User-Id": user.id,
  626. "X-OpenWebUI-User-Email": user.email,
  627. "X-OpenWebUI-User-Role": user.role,
  628. }
  629. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  630. else {}
  631. ),
  632. },
  633. json=json_data,
  634. )
  635. if r.status_code == 429:
  636. retry = float(r.headers.get("Retry-After", "1"))
  637. time.sleep(retry)
  638. continue
  639. r.raise_for_status()
  640. data = r.json()
  641. if "data" in data:
  642. return [elem["embedding"] for elem in data["data"]]
  643. else:
  644. raise Exception("Something went wrong :/")
  645. return None
  646. except Exception as e:
  647. log.exception(f"Error generating azure openai batch embeddings: {e}")
  648. return None
  649. def generate_ollama_batch_embeddings(
  650. model: str,
  651. texts: list[str],
  652. url: str,
  653. key: str = "",
  654. prefix: str = None,
  655. user: UserModel = None,
  656. ) -> Optional[list[list[float]]]:
  657. try:
  658. log.debug(
  659. f"generate_ollama_batch_embeddings:model {model} batch size: {len(texts)}"
  660. )
  661. json_data = {"input": texts, "model": model}
  662. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  663. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  664. r = requests.post(
  665. f"{url}/api/embed",
  666. headers={
  667. "Content-Type": "application/json",
  668. "Authorization": f"Bearer {key}",
  669. **(
  670. {
  671. "X-OpenWebUI-User-Name": user.name,
  672. "X-OpenWebUI-User-Id": user.id,
  673. "X-OpenWebUI-User-Email": user.email,
  674. "X-OpenWebUI-User-Role": user.role,
  675. }
  676. if ENABLE_FORWARD_USER_INFO_HEADERS
  677. else {}
  678. ),
  679. },
  680. json=json_data,
  681. )
  682. r.raise_for_status()
  683. data = r.json()
  684. if "embeddings" in data:
  685. return data["embeddings"]
  686. else:
  687. raise "Something went wrong :/"
  688. except Exception as e:
  689. log.exception(f"Error generating ollama batch embeddings: {e}")
  690. return None
  691. def generate_embeddings(
  692. engine: str,
  693. model: str,
  694. text: Union[str, list[str]],
  695. prefix: Union[str, None] = None,
  696. **kwargs,
  697. ):
  698. url = kwargs.get("url", "")
  699. key = kwargs.get("key", "")
  700. user = kwargs.get("user")
  701. if prefix is not None and RAG_EMBEDDING_PREFIX_FIELD_NAME is None:
  702. if isinstance(text, list):
  703. text = [f"{prefix}{text_element}" for text_element in text]
  704. else:
  705. text = f"{prefix}{text}"
  706. if engine == "ollama":
  707. if isinstance(text, list):
  708. embeddings = generate_ollama_batch_embeddings(
  709. **{
  710. "model": model,
  711. "texts": text,
  712. "url": url,
  713. "key": key,
  714. "prefix": prefix,
  715. "user": user,
  716. }
  717. )
  718. else:
  719. embeddings = generate_ollama_batch_embeddings(
  720. **{
  721. "model": model,
  722. "texts": [text],
  723. "url": url,
  724. "key": key,
  725. "prefix": prefix,
  726. "user": user,
  727. }
  728. )
  729. return embeddings[0] if isinstance(text, str) else embeddings
  730. elif engine == "openai":
  731. if isinstance(text, list):
  732. embeddings = generate_openai_batch_embeddings(
  733. model, text, url, key, prefix, user
  734. )
  735. else:
  736. embeddings = generate_openai_batch_embeddings(
  737. model, [text], url, key, prefix, user
  738. )
  739. return embeddings[0] if isinstance(text, str) else embeddings
  740. elif engine == "azure_openai":
  741. deployment = kwargs.get("deployment", "")
  742. version = kwargs.get("version", "")
  743. if isinstance(text, list):
  744. embeddings = generate_azure_openai_batch_embeddings(
  745. deployment,
  746. text,
  747. url,
  748. key,
  749. model,
  750. version,
  751. prefix,
  752. user,
  753. )
  754. else:
  755. embeddings = generate_azure_openai_batch_embeddings(
  756. deployment,
  757. [text],
  758. url,
  759. key,
  760. model,
  761. version,
  762. prefix,
  763. user,
  764. )
  765. return embeddings[0] if isinstance(text, str) else embeddings
  766. import operator
  767. from typing import Optional, Sequence
  768. from langchain_core.callbacks import Callbacks
  769. from langchain_core.documents import BaseDocumentCompressor, Document
  770. class RerankCompressor(BaseDocumentCompressor):
  771. embedding_function: Any
  772. top_n: int
  773. reranking_function: Any
  774. r_score: float
  775. class Config:
  776. extra = "forbid"
  777. arbitrary_types_allowed = True
  778. def compress_documents(
  779. self,
  780. documents: Sequence[Document],
  781. query: str,
  782. callbacks: Optional[Callbacks] = None,
  783. ) -> Sequence[Document]:
  784. reranking = self.reranking_function is not None
  785. if reranking:
  786. scores = self.reranking_function.predict(
  787. [(query, doc.page_content) for doc in documents]
  788. )
  789. else:
  790. from sentence_transformers import util
  791. query_embedding = self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)
  792. document_embedding = self.embedding_function(
  793. [doc.page_content for doc in documents], RAG_EMBEDDING_CONTENT_PREFIX
  794. )
  795. scores = util.cos_sim(query_embedding, document_embedding)[0]
  796. docs_with_scores = list(
  797. zip(documents, scores.tolist() if not isinstance(scores, list) else scores)
  798. )
  799. if self.r_score:
  800. docs_with_scores = [
  801. (d, s) for d, s in docs_with_scores if s >= self.r_score
  802. ]
  803. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  804. final_results = []
  805. for doc, doc_score in result[: self.top_n]:
  806. metadata = doc.metadata
  807. metadata["score"] = doc_score
  808. doc = Document(
  809. page_content=doc.page_content,
  810. metadata=metadata,
  811. )
  812. final_results.append(doc)
  813. return final_results