utils.py 30 KB

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