1
0

utils.py 33 KB

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