utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. query: str,
  145. embedding_function,
  146. k: int,
  147. ) -> dict:
  148. results = []
  149. query_embedding = embedding_function(query)
  150. for collection_name in collection_names:
  151. if collection_name:
  152. try:
  153. result = query_doc(
  154. collection_name=collection_name,
  155. k=k,
  156. query_embedding=query_embedding,
  157. )
  158. if result is not None:
  159. results.append(result.model_dump())
  160. except Exception as e:
  161. log.exception(f"Error when querying the collection: {e}")
  162. else:
  163. pass
  164. return merge_and_sort_query_results(results, k=k)
  165. def query_collection_with_hybrid_search(
  166. collection_names: list[str],
  167. query: str,
  168. embedding_function,
  169. k: int,
  170. reranking_function,
  171. r: float,
  172. ) -> dict:
  173. results = []
  174. error = False
  175. for collection_name in collection_names:
  176. try:
  177. result = query_doc_with_hybrid_search(
  178. collection_name=collection_name,
  179. query=query,
  180. embedding_function=embedding_function,
  181. k=k,
  182. reranking_function=reranking_function,
  183. r=r,
  184. )
  185. results.append(result)
  186. except Exception as e:
  187. log.exception(
  188. "Error when querying the collection with " f"hybrid_search: {e}"
  189. )
  190. error = True
  191. if error:
  192. raise Exception(
  193. "Hybrid search failed for all collections. Using Non hybrid search as fallback."
  194. )
  195. return merge_and_sort_query_results(results, k=k, reverse=True)
  196. def rag_template(template: str, context: str, query: str):
  197. if template == "":
  198. template = DEFAULT_RAG_TEMPLATE
  199. if "[context]" not in template and "{{CONTEXT}}" not in template:
  200. log.debug(
  201. "WARNING: The RAG template does not contain the '[context]' or '{{CONTEXT}}' placeholder."
  202. )
  203. if "<context>" in context and "</context>" in context:
  204. log.debug(
  205. "WARNING: Potential prompt injection attack: the RAG "
  206. "context contains '<context>' and '</context>'. This might be "
  207. "nothing, or the user might be trying to hack something."
  208. )
  209. query_placeholders = []
  210. if "[query]" in context:
  211. query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
  212. template = template.replace("[query]", query_placeholder)
  213. query_placeholders.append(query_placeholder)
  214. if "{{QUERY}}" in context:
  215. query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
  216. template = template.replace("{{QUERY}}", query_placeholder)
  217. query_placeholders.append(query_placeholder)
  218. template = template.replace("[context]", context)
  219. template = template.replace("{{CONTEXT}}", context)
  220. template = template.replace("[query]", query)
  221. template = template.replace("{{QUERY}}", query)
  222. for query_placeholder in query_placeholders:
  223. template = template.replace(query_placeholder, query)
  224. return template
  225. def get_embedding_function(
  226. embedding_engine,
  227. embedding_model,
  228. embedding_function,
  229. url,
  230. key,
  231. embedding_batch_size,
  232. ):
  233. if embedding_engine == "":
  234. return lambda query: embedding_function.encode(query).tolist()
  235. elif embedding_engine in ["ollama", "openai"]:
  236. func = lambda query: generate_embeddings(
  237. engine=embedding_engine,
  238. model=embedding_model,
  239. text=query,
  240. url=url,
  241. key=key,
  242. )
  243. def generate_multiple(query, func):
  244. if isinstance(query, list):
  245. embeddings = []
  246. for i in range(0, len(query), embedding_batch_size):
  247. embeddings.extend(func(query[i : i + embedding_batch_size]))
  248. return embeddings
  249. else:
  250. return func(query)
  251. return lambda query: generate_multiple(query, func)
  252. def get_rag_context(
  253. files,
  254. messages,
  255. embedding_function,
  256. k,
  257. reranking_function,
  258. r,
  259. hybrid_search,
  260. ):
  261. log.debug(f"files: {files} {messages} {embedding_function} {reranking_function}")
  262. query = get_last_user_message(messages)
  263. extracted_collections = []
  264. relevant_contexts = []
  265. for file in files:
  266. if file.get("context") == "full":
  267. context = {
  268. "documents": [[file.get("file").get("data", {}).get("content")]],
  269. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  270. }
  271. else:
  272. context = None
  273. collection_names = []
  274. if file.get("type") == "collection":
  275. if file.get("legacy"):
  276. collection_names = file.get("collection_names", [])
  277. else:
  278. collection_names.append(file["id"])
  279. elif file.get("collection_name"):
  280. collection_names.append(file["collection_name"])
  281. elif file.get("id"):
  282. if file.get("legacy"):
  283. collection_names.append(f"{file['id']}")
  284. else:
  285. collection_names.append(f"file-{file['id']}")
  286. collection_names = set(collection_names).difference(extracted_collections)
  287. if not collection_names:
  288. log.debug(f"skipping {file} as it has already been extracted")
  289. continue
  290. try:
  291. context = None
  292. if file.get("type") == "text":
  293. context = file["content"]
  294. else:
  295. if hybrid_search:
  296. try:
  297. context = query_collection_with_hybrid_search(
  298. collection_names=collection_names,
  299. query=query,
  300. embedding_function=embedding_function,
  301. k=k,
  302. reranking_function=reranking_function,
  303. r=r,
  304. )
  305. except Exception as e:
  306. log.debug(
  307. "Error when using hybrid search, using"
  308. " non hybrid search as fallback."
  309. )
  310. if (not hybrid_search) or (context is None):
  311. context = query_collection(
  312. collection_names=collection_names,
  313. query=query,
  314. embedding_function=embedding_function,
  315. k=k,
  316. )
  317. except Exception as e:
  318. log.exception(e)
  319. extracted_collections.extend(collection_names)
  320. if context:
  321. if "data" in file:
  322. del file["data"]
  323. relevant_contexts.append({**context, "file": file})
  324. contexts = []
  325. citations = []
  326. for context in relevant_contexts:
  327. try:
  328. if "documents" in context:
  329. file_names = list(
  330. set(
  331. [
  332. metadata["name"]
  333. for metadata in context["metadatas"][0]
  334. if metadata is not None and "name" in metadata
  335. ]
  336. )
  337. )
  338. contexts.append(
  339. ((", ".join(file_names) + ":\n\n") if file_names else "")
  340. + "\n\n".join(
  341. [text for text in context["documents"][0] if text is not None]
  342. )
  343. )
  344. if "metadatas" in context:
  345. citation = {
  346. "source": context["file"],
  347. "document": context["documents"][0],
  348. "metadata": context["metadatas"][0],
  349. }
  350. if "distances" in context and context["distances"]:
  351. citation["distances"] = context["distances"][0]
  352. citations.append(citation)
  353. except Exception as e:
  354. log.exception(e)
  355. print("contexts", contexts)
  356. print("citations", citations)
  357. return contexts, citations
  358. def get_model_path(model: str, update_model: bool = False):
  359. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  360. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  361. local_files_only = not update_model
  362. snapshot_kwargs = {
  363. "cache_dir": cache_dir,
  364. "local_files_only": local_files_only,
  365. }
  366. log.debug(f"model: {model}")
  367. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  368. # Inspiration from upstream sentence_transformers
  369. if (
  370. os.path.exists(model)
  371. or ("\\" in model or model.count("/") > 1)
  372. and local_files_only
  373. ):
  374. # If fully qualified path exists, return input, else set repo_id
  375. return model
  376. elif "/" not in model:
  377. # Set valid repo_id for model short-name
  378. model = "sentence-transformers" + "/" + model
  379. snapshot_kwargs["repo_id"] = model
  380. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  381. try:
  382. model_repo_path = snapshot_download(**snapshot_kwargs)
  383. log.debug(f"model_repo_path: {model_repo_path}")
  384. return model_repo_path
  385. except Exception as e:
  386. log.exception(f"Cannot determine model snapshot path: {e}")
  387. return model
  388. def generate_openai_batch_embeddings(
  389. model: str, texts: list[str], url: str = "https://api.openai.com/v1", key: str = ""
  390. ) -> Optional[list[list[float]]]:
  391. try:
  392. r = requests.post(
  393. f"{url}/embeddings",
  394. headers={
  395. "Content-Type": "application/json",
  396. "Authorization": f"Bearer {key}",
  397. },
  398. json={"input": texts, "model": model},
  399. )
  400. r.raise_for_status()
  401. data = r.json()
  402. if "data" in data:
  403. return [elem["embedding"] for elem in data["data"]]
  404. else:
  405. raise "Something went wrong :/"
  406. except Exception as e:
  407. print(e)
  408. return None
  409. def generate_ollama_batch_embeddings(
  410. model: str, texts: list[str], url: str, key: str
  411. ) -> Optional[list[list[float]]]:
  412. try:
  413. r = requests.post(
  414. f"{url}/api/embed",
  415. headers={
  416. "Content-Type": "application/json",
  417. "Authorization": f"Bearer {key}",
  418. },
  419. json={"input": texts, "model": model},
  420. )
  421. r.raise_for_status()
  422. data = r.json()
  423. print(data)
  424. if "embeddings" in data:
  425. return data["embeddings"]
  426. else:
  427. raise "Something went wrong :/"
  428. except Exception as e:
  429. print(e)
  430. return None
  431. def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], **kwargs):
  432. url = kwargs.get("url", "")
  433. key = kwargs.get("key", "")
  434. if engine == "ollama":
  435. if isinstance(text, list):
  436. embeddings = generate_ollama_batch_embeddings(
  437. **{"model": model, "texts": text, "url": url, "key": key}
  438. )
  439. else:
  440. embeddings = generate_ollama_batch_embeddings(
  441. **{"model": model, "texts": [text], "url": url, "key": key}
  442. )
  443. return embeddings[0] if isinstance(text, str) else embeddings
  444. elif engine == "openai":
  445. if isinstance(text, list):
  446. embeddings = generate_openai_batch_embeddings(model, text, url, key)
  447. else:
  448. embeddings = generate_openai_batch_embeddings(model, [text], url, key)
  449. return embeddings[0] if isinstance(text, str) else embeddings
  450. import operator
  451. from typing import Optional, Sequence
  452. from langchain_core.callbacks import Callbacks
  453. from langchain_core.documents import BaseDocumentCompressor, Document
  454. class RerankCompressor(BaseDocumentCompressor):
  455. embedding_function: Any
  456. top_n: int
  457. reranking_function: Any
  458. r_score: float
  459. class Config:
  460. extra = "forbid"
  461. arbitrary_types_allowed = True
  462. def compress_documents(
  463. self,
  464. documents: Sequence[Document],
  465. query: str,
  466. callbacks: Optional[Callbacks] = None,
  467. ) -> Sequence[Document]:
  468. reranking = self.reranking_function is not None
  469. if reranking:
  470. scores = self.reranking_function.predict(
  471. [(query, doc.page_content) for doc in documents]
  472. )
  473. else:
  474. from sentence_transformers import util
  475. query_embedding = self.embedding_function(query)
  476. document_embedding = self.embedding_function(
  477. [doc.page_content for doc in documents]
  478. )
  479. scores = util.cos_sim(query_embedding, document_embedding)[0]
  480. docs_with_scores = list(zip(documents, scores.tolist()))
  481. if self.r_score:
  482. docs_with_scores = [
  483. (d, s) for d, s in docs_with_scores if s >= self.r_score
  484. ]
  485. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  486. final_results = []
  487. for doc, doc_score in result[: self.top_n]:
  488. metadata = doc.metadata
  489. metadata["score"] = doc_score
  490. doc = Document(
  491. page_content=doc.page_content,
  492. metadata=metadata,
  493. )
  494. final_results.append(doc)
  495. return final_results