utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import logging
  2. import os
  3. import uuid
  4. from typing import Optional, Union
  5. import asyncio
  6. import requests
  7. from huggingface_hub import snapshot_download
  8. from langchain.retrievers import ContextualCompressionRetriever, EnsembleRetriever
  9. from langchain_community.retrievers import BM25Retriever
  10. from langchain_core.documents import Document
  11. from open_webui.apps.retrieval.vector.connector import VECTOR_DB_CLIENT
  12. from open_webui.utils.misc import get_last_user_message
  13. from open_webui.env import SRC_LOG_LEVELS
  14. from open_webui.config import DEFAULT_RAG_TEMPLATE
  15. log = logging.getLogger(__name__)
  16. log.setLevel(SRC_LOG_LEVELS["RAG"])
  17. from typing import Any
  18. from langchain_core.callbacks import CallbackManagerForRetrieverRun
  19. from langchain_core.retrievers import BaseRetriever
  20. class VectorSearchRetriever(BaseRetriever):
  21. collection_name: Any
  22. embedding_function: Any
  23. top_k: int
  24. def _get_relevant_documents(
  25. self,
  26. query: str,
  27. *,
  28. run_manager: CallbackManagerForRetrieverRun,
  29. ) -> list[Document]:
  30. result = VECTOR_DB_CLIENT.search(
  31. collection_name=self.collection_name,
  32. vectors=[self.embedding_function(query)],
  33. limit=self.top_k,
  34. )
  35. ids = result.ids[0]
  36. metadatas = result.metadatas[0]
  37. documents = result.documents[0]
  38. results = []
  39. for idx in range(len(ids)):
  40. results.append(
  41. Document(
  42. metadata=metadatas[idx],
  43. page_content=documents[idx],
  44. )
  45. )
  46. return results
  47. def query_doc(
  48. collection_name: str,
  49. query_embedding: list[float],
  50. k: int,
  51. ):
  52. try:
  53. result = VECTOR_DB_CLIENT.search(
  54. collection_name=collection_name,
  55. vectors=[query_embedding],
  56. limit=k,
  57. )
  58. log.info(f"query_doc:result {result.ids} {result.metadatas}")
  59. return result
  60. except Exception as e:
  61. print(e)
  62. raise e
  63. def query_doc_with_hybrid_search(
  64. collection_name: str,
  65. query: str,
  66. embedding_function,
  67. k: int,
  68. reranking_function,
  69. r: float,
  70. ) -> dict:
  71. try:
  72. result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
  73. bm25_retriever = BM25Retriever.from_texts(
  74. texts=result.documents[0],
  75. metadatas=result.metadatas[0],
  76. )
  77. bm25_retriever.k = k
  78. vector_search_retriever = VectorSearchRetriever(
  79. collection_name=collection_name,
  80. embedding_function=embedding_function,
  81. top_k=k,
  82. )
  83. ensemble_retriever = EnsembleRetriever(
  84. retrievers=[bm25_retriever, vector_search_retriever], weights=[0.5, 0.5]
  85. )
  86. compressor = RerankCompressor(
  87. embedding_function=embedding_function,
  88. top_n=k,
  89. reranking_function=reranking_function,
  90. r_score=r,
  91. )
  92. compression_retriever = ContextualCompressionRetriever(
  93. base_compressor=compressor, base_retriever=ensemble_retriever
  94. )
  95. result = compression_retriever.invoke(query)
  96. result = {
  97. "distances": [[d.metadata.get("score") for d in result]],
  98. "documents": [[d.page_content for d in result]],
  99. "metadatas": [[d.metadata for d in result]],
  100. }
  101. log.info(
  102. "query_doc_with_hybrid_search:result "
  103. + f'{result["metadatas"]} {result["distances"]}'
  104. )
  105. return result
  106. except Exception as e:
  107. raise e
  108. def merge_and_sort_query_results(
  109. query_results: list[dict], k: int, reverse: bool = False
  110. ) -> list[dict]:
  111. # Initialize lists to store combined data
  112. combined_distances = []
  113. combined_documents = []
  114. combined_metadatas = []
  115. for data in query_results:
  116. combined_distances.extend(data["distances"][0])
  117. combined_documents.extend(data["documents"][0])
  118. combined_metadatas.extend(data["metadatas"][0])
  119. # Create a list of tuples (distance, document, metadata)
  120. combined = list(zip(combined_distances, combined_documents, combined_metadatas))
  121. # Sort the list based on distances
  122. combined.sort(key=lambda x: x[0], reverse=reverse)
  123. # We don't have anything :-(
  124. if not combined:
  125. sorted_distances = []
  126. sorted_documents = []
  127. sorted_metadatas = []
  128. else:
  129. # Unzip the sorted list
  130. sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
  131. # Slicing the lists to include only k elements
  132. sorted_distances = list(sorted_distances)[:k]
  133. sorted_documents = list(sorted_documents)[:k]
  134. sorted_metadatas = list(sorted_metadatas)[:k]
  135. # Create the output dictionary
  136. result = {
  137. "distances": [sorted_distances],
  138. "documents": [sorted_documents],
  139. "metadatas": [sorted_metadatas],
  140. }
  141. return result
  142. def query_collection(
  143. collection_names: list[str],
  144. queries: list[str],
  145. embedding_function,
  146. k: int,
  147. ) -> dict:
  148. results = []
  149. for query in queries:
  150. query_embedding = embedding_function(query)
  151. for collection_name in collection_names:
  152. if collection_name:
  153. try:
  154. result = query_doc(
  155. collection_name=collection_name,
  156. k=k,
  157. query_embedding=query_embedding,
  158. )
  159. if result is not None:
  160. results.append(result.model_dump())
  161. except Exception as e:
  162. log.exception(f"Error when querying the collection: {e}")
  163. else:
  164. pass
  165. return merge_and_sort_query_results(results, k=k)
  166. def query_collection_with_hybrid_search(
  167. collection_names: list[str],
  168. queries: list[str],
  169. embedding_function,
  170. k: int,
  171. reranking_function,
  172. r: float,
  173. ) -> dict:
  174. results = []
  175. error = False
  176. for collection_name in collection_names:
  177. try:
  178. for query in queries:
  179. result = query_doc_with_hybrid_search(
  180. collection_name=collection_name,
  181. query=query,
  182. embedding_function=embedding_function,
  183. k=k,
  184. reranking_function=reranking_function,
  185. r=r,
  186. )
  187. results.append(result)
  188. except Exception as e:
  189. log.exception(
  190. "Error when querying the collection with " f"hybrid_search: {e}"
  191. )
  192. error = True
  193. if error:
  194. raise Exception(
  195. "Hybrid search failed for all collections. Using Non hybrid search as fallback."
  196. )
  197. return merge_and_sort_query_results(results, k=k, reverse=True)
  198. def rag_template(template: str, context: str, query: str):
  199. if template == "":
  200. template = DEFAULT_RAG_TEMPLATE
  201. if "[context]" not in template and "{{CONTEXT}}" not in template:
  202. log.debug(
  203. "WARNING: The RAG template does not contain the '[context]' or '{{CONTEXT}}' placeholder."
  204. )
  205. if "<context>" in context and "</context>" in context:
  206. log.debug(
  207. "WARNING: Potential prompt injection attack: the RAG "
  208. "context contains '<context>' and '</context>'. This might be "
  209. "nothing, or the user might be trying to hack something."
  210. )
  211. query_placeholders = []
  212. if "[query]" in context:
  213. query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
  214. template = template.replace("[query]", query_placeholder)
  215. query_placeholders.append(query_placeholder)
  216. if "{{QUERY}}" in context:
  217. query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
  218. template = template.replace("{{QUERY}}", query_placeholder)
  219. query_placeholders.append(query_placeholder)
  220. template = template.replace("[context]", context)
  221. template = template.replace("{{CONTEXT}}", context)
  222. template = template.replace("[query]", query)
  223. template = template.replace("{{QUERY}}", query)
  224. for query_placeholder in query_placeholders:
  225. template = template.replace(query_placeholder, query)
  226. return template
  227. def get_embedding_function(
  228. embedding_engine,
  229. embedding_model,
  230. embedding_function,
  231. url,
  232. key,
  233. embedding_batch_size,
  234. ):
  235. if embedding_engine == "":
  236. return lambda query: embedding_function.encode(query).tolist()
  237. elif embedding_engine in ["ollama", "openai"]:
  238. func = lambda query: generate_embeddings(
  239. engine=embedding_engine,
  240. model=embedding_model,
  241. text=query,
  242. url=url,
  243. key=key,
  244. )
  245. def generate_multiple(query, func):
  246. if isinstance(query, list):
  247. embeddings = []
  248. for i in range(0, len(query), embedding_batch_size):
  249. embeddings.extend(func(query[i : i + embedding_batch_size]))
  250. return embeddings
  251. else:
  252. return func(query)
  253. return lambda query: generate_multiple(query, func)
  254. def get_sources_from_files(
  255. files,
  256. queries,
  257. embedding_function,
  258. k,
  259. reranking_function,
  260. r,
  261. hybrid_search,
  262. ):
  263. log.debug(f"files: {files} {queries} {embedding_function} {reranking_function}")
  264. extracted_collections = []
  265. relevant_contexts = []
  266. for file in files:
  267. if file.get("context") == "full":
  268. context = {
  269. "documents": [[file.get("file").get("data", {}).get("content")]],
  270. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  271. }
  272. else:
  273. context = None
  274. collection_names = []
  275. if file.get("type") == "collection":
  276. if file.get("legacy"):
  277. collection_names = file.get("collection_names", [])
  278. else:
  279. collection_names.append(file["id"])
  280. elif file.get("collection_name"):
  281. collection_names.append(file["collection_name"])
  282. elif file.get("id"):
  283. if file.get("legacy"):
  284. collection_names.append(f"{file['id']}")
  285. else:
  286. collection_names.append(f"file-{file['id']}")
  287. collection_names = set(collection_names).difference(extracted_collections)
  288. if not collection_names:
  289. log.debug(f"skipping {file} as it has already been extracted")
  290. continue
  291. try:
  292. context = None
  293. if file.get("type") == "text":
  294. context = file["content"]
  295. else:
  296. if hybrid_search:
  297. try:
  298. context = query_collection_with_hybrid_search(
  299. collection_names=collection_names,
  300. queries=queries,
  301. embedding_function=embedding_function,
  302. k=k,
  303. reranking_function=reranking_function,
  304. r=r,
  305. )
  306. except Exception as e:
  307. log.debug(
  308. "Error when using hybrid search, using"
  309. " non hybrid search as fallback."
  310. )
  311. if (not hybrid_search) or (context is None):
  312. context = query_collection(
  313. collection_names=collection_names,
  314. queries=queries,
  315. embedding_function=embedding_function,
  316. k=k,
  317. )
  318. except Exception as e:
  319. log.exception(e)
  320. extracted_collections.extend(collection_names)
  321. if context:
  322. if "data" in file:
  323. del file["data"]
  324. relevant_contexts.append({**context, "file": file})
  325. sources = []
  326. for context in relevant_contexts:
  327. try:
  328. if "documents" in context:
  329. if "metadatas" in context:
  330. source = {
  331. "source": context["file"],
  332. "document": context["documents"][0],
  333. "metadata": context["metadatas"][0],
  334. }
  335. if "distances" in context and context["distances"]:
  336. source["distances"] = context["distances"][0]
  337. sources.append(source)
  338. except Exception as e:
  339. log.exception(e)
  340. return sources
  341. def get_model_path(model: str, update_model: bool = False):
  342. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  343. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  344. local_files_only = not update_model
  345. snapshot_kwargs = {
  346. "cache_dir": cache_dir,
  347. "local_files_only": local_files_only,
  348. }
  349. log.debug(f"model: {model}")
  350. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  351. # Inspiration from upstream sentence_transformers
  352. if (
  353. os.path.exists(model)
  354. or ("\\" in model or model.count("/") > 1)
  355. and local_files_only
  356. ):
  357. # If fully qualified path exists, return input, else set repo_id
  358. return model
  359. elif "/" not in model:
  360. # Set valid repo_id for model short-name
  361. model = "sentence-transformers" + "/" + model
  362. snapshot_kwargs["repo_id"] = model
  363. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  364. try:
  365. model_repo_path = snapshot_download(**snapshot_kwargs)
  366. log.debug(f"model_repo_path: {model_repo_path}")
  367. return model_repo_path
  368. except Exception as e:
  369. log.exception(f"Cannot determine model snapshot path: {e}")
  370. return model
  371. def generate_openai_batch_embeddings(
  372. model: str, texts: list[str], url: str = "https://api.openai.com/v1", key: str = ""
  373. ) -> Optional[list[list[float]]]:
  374. try:
  375. r = requests.post(
  376. f"{url}/embeddings",
  377. headers={
  378. "Content-Type": "application/json",
  379. "Authorization": f"Bearer {key}",
  380. },
  381. json={"input": texts, "model": model},
  382. )
  383. r.raise_for_status()
  384. data = r.json()
  385. if "data" in data:
  386. return [elem["embedding"] for elem in data["data"]]
  387. else:
  388. raise "Something went wrong :/"
  389. except Exception as e:
  390. print(e)
  391. return None
  392. def generate_ollama_batch_embeddings(
  393. model: str, texts: list[str], url: str, key: str
  394. ) -> Optional[list[list[float]]]:
  395. try:
  396. r = requests.post(
  397. f"{url}/api/embed",
  398. headers={
  399. "Content-Type": "application/json",
  400. "Authorization": f"Bearer {key}",
  401. },
  402. json={"input": texts, "model": model},
  403. )
  404. r.raise_for_status()
  405. data = r.json()
  406. if "embeddings" in data:
  407. return data["embeddings"]
  408. else:
  409. raise "Something went wrong :/"
  410. except Exception as e:
  411. print(e)
  412. return None
  413. def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], **kwargs):
  414. url = kwargs.get("url", "")
  415. key = kwargs.get("key", "")
  416. if engine == "ollama":
  417. if isinstance(text, list):
  418. embeddings = generate_ollama_batch_embeddings(
  419. **{"model": model, "texts": text, "url": url, "key": key}
  420. )
  421. else:
  422. embeddings = generate_ollama_batch_embeddings(
  423. **{"model": model, "texts": [text], "url": url, "key": key}
  424. )
  425. return embeddings[0] if isinstance(text, str) else embeddings
  426. elif engine == "openai":
  427. if isinstance(text, list):
  428. embeddings = generate_openai_batch_embeddings(model, text, url, key)
  429. else:
  430. embeddings = generate_openai_batch_embeddings(model, [text], url, key)
  431. return embeddings[0] if isinstance(text, str) else embeddings
  432. import operator
  433. from typing import Optional, Sequence
  434. from langchain_core.callbacks import Callbacks
  435. from langchain_core.documents import BaseDocumentCompressor, Document
  436. class RerankCompressor(BaseDocumentCompressor):
  437. embedding_function: Any
  438. top_n: int
  439. reranking_function: Any
  440. r_score: float
  441. class Config:
  442. extra = "forbid"
  443. arbitrary_types_allowed = True
  444. def compress_documents(
  445. self,
  446. documents: Sequence[Document],
  447. query: str,
  448. callbacks: Optional[Callbacks] = None,
  449. ) -> Sequence[Document]:
  450. reranking = self.reranking_function is not None
  451. if reranking:
  452. scores = self.reranking_function.predict(
  453. [(query, doc.page_content) for doc in documents]
  454. )
  455. else:
  456. from sentence_transformers import util
  457. query_embedding = self.embedding_function(query)
  458. document_embedding = self.embedding_function(
  459. [doc.page_content for doc in documents]
  460. )
  461. scores = util.cos_sim(query_embedding, document_embedding)[0]
  462. docs_with_scores = list(zip(documents, scores.tolist()))
  463. if self.r_score:
  464. docs_with_scores = [
  465. (d, s) for d, s in docs_with_scores if s >= self.r_score
  466. ]
  467. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  468. final_results = []
  469. for doc, doc_score in result[: self.top_n]:
  470. metadata = doc.metadata
  471. metadata["score"] = doc_score
  472. doc = Document(
  473. page_content=doc.page_content,
  474. metadata=metadata,
  475. )
  476. final_results.append(doc)
  477. return final_results