1
0

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