utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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_rag_context(
  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. contexts = []
  326. citations = []
  327. for context in relevant_contexts:
  328. try:
  329. if "documents" in context:
  330. file_names = list(
  331. set(
  332. [
  333. metadata["name"]
  334. for metadata in context["metadatas"][0]
  335. if metadata is not None and "name" in metadata
  336. ]
  337. )
  338. )
  339. contexts.append(
  340. ((", ".join(file_names) + ":\n\n") if file_names else "")
  341. + "\n\n".join(
  342. [text for text in context["documents"][0] if text is not None]
  343. )
  344. )
  345. if "metadatas" in context:
  346. citation = {
  347. "source": context["file"],
  348. "document": context["documents"][0],
  349. "metadata": context["metadatas"][0],
  350. }
  351. if "distances" in context and context["distances"]:
  352. citation["distances"] = context["distances"][0]
  353. citations.append(citation)
  354. except Exception as e:
  355. log.exception(e)
  356. print("contexts", contexts)
  357. print("citations", citations)
  358. return contexts, citations
  359. def get_model_path(model: str, update_model: bool = False):
  360. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  361. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  362. local_files_only = not update_model
  363. snapshot_kwargs = {
  364. "cache_dir": cache_dir,
  365. "local_files_only": local_files_only,
  366. }
  367. log.debug(f"model: {model}")
  368. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  369. # Inspiration from upstream sentence_transformers
  370. if (
  371. os.path.exists(model)
  372. or ("\\" in model or model.count("/") > 1)
  373. and local_files_only
  374. ):
  375. # If fully qualified path exists, return input, else set repo_id
  376. return model
  377. elif "/" not in model:
  378. # Set valid repo_id for model short-name
  379. model = "sentence-transformers" + "/" + model
  380. snapshot_kwargs["repo_id"] = model
  381. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  382. try:
  383. model_repo_path = snapshot_download(**snapshot_kwargs)
  384. log.debug(f"model_repo_path: {model_repo_path}")
  385. return model_repo_path
  386. except Exception as e:
  387. log.exception(f"Cannot determine model snapshot path: {e}")
  388. return model
  389. def generate_openai_batch_embeddings(
  390. model: str, texts: list[str], url: str = "https://api.openai.com/v1", key: str = ""
  391. ) -> Optional[list[list[float]]]:
  392. try:
  393. r = requests.post(
  394. f"{url}/embeddings",
  395. headers={
  396. "Content-Type": "application/json",
  397. "Authorization": f"Bearer {key}",
  398. },
  399. json={"input": texts, "model": model},
  400. )
  401. r.raise_for_status()
  402. data = r.json()
  403. if "data" in data:
  404. return [elem["embedding"] for elem in data["data"]]
  405. else:
  406. raise "Something went wrong :/"
  407. except Exception as e:
  408. print(e)
  409. return None
  410. def generate_ollama_batch_embeddings(
  411. model: str, texts: list[str], url: str, key: str
  412. ) -> Optional[list[list[float]]]:
  413. try:
  414. r = requests.post(
  415. f"{url}/api/embed",
  416. headers={
  417. "Content-Type": "application/json",
  418. "Authorization": f"Bearer {key}",
  419. },
  420. json={"input": texts, "model": model},
  421. )
  422. r.raise_for_status()
  423. data = r.json()
  424. print(data)
  425. if "embeddings" in data:
  426. return data["embeddings"]
  427. else:
  428. raise "Something went wrong :/"
  429. except Exception as e:
  430. print(e)
  431. return None
  432. def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], **kwargs):
  433. url = kwargs.get("url", "")
  434. key = kwargs.get("key", "")
  435. if engine == "ollama":
  436. if isinstance(text, list):
  437. embeddings = generate_ollama_batch_embeddings(
  438. **{"model": model, "texts": text, "url": url, "key": key}
  439. )
  440. else:
  441. embeddings = generate_ollama_batch_embeddings(
  442. **{"model": model, "texts": [text], "url": url, "key": key}
  443. )
  444. return embeddings[0] if isinstance(text, str) else embeddings
  445. elif engine == "openai":
  446. if isinstance(text, list):
  447. embeddings = generate_openai_batch_embeddings(model, text, url, key)
  448. else:
  449. embeddings = generate_openai_batch_embeddings(model, [text], url, key)
  450. return embeddings[0] if isinstance(text, str) else embeddings
  451. import operator
  452. from typing import Optional, Sequence
  453. from langchain_core.callbacks import Callbacks
  454. from langchain_core.documents import BaseDocumentCompressor, Document
  455. class RerankCompressor(BaseDocumentCompressor):
  456. embedding_function: Any
  457. top_n: int
  458. reranking_function: Any
  459. r_score: float
  460. class Config:
  461. extra = "forbid"
  462. arbitrary_types_allowed = True
  463. def compress_documents(
  464. self,
  465. documents: Sequence[Document],
  466. query: str,
  467. callbacks: Optional[Callbacks] = None,
  468. ) -> Sequence[Document]:
  469. reranking = self.reranking_function is not None
  470. if reranking:
  471. scores = self.reranking_function.predict(
  472. [(query, doc.page_content) for doc in documents]
  473. )
  474. else:
  475. from sentence_transformers import util
  476. query_embedding = self.embedding_function(query)
  477. document_embedding = self.embedding_function(
  478. [doc.page_content for doc in documents]
  479. )
  480. scores = util.cos_sim(query_embedding, document_embedding)[0]
  481. docs_with_scores = list(zip(documents, scores.tolist()))
  482. if self.r_score:
  483. docs_with_scores = [
  484. (d, s) for d, s in docs_with_scores if s >= self.r_score
  485. ]
  486. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  487. final_results = []
  488. for doc, doc_score in result[: self.top_n]:
  489. metadata = doc.metadata
  490. metadata["score"] = doc_score
  491. doc = Document(
  492. page_content=doc.page_content,
  493. metadata=metadata,
  494. )
  495. final_results.append(doc)
  496. return final_results