utils.py 35 KB

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