utils.py 33 KB

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