utils.py 32 KB

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