utils.py 33 KB

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