utils.py 37 KB

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