utils.py 34 KB

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