app.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import ast
  2. import concurrent.futures
  3. import json
  4. import logging
  5. import os
  6. import uuid
  7. from typing import Any, Optional, Union
  8. import requests
  9. import yaml
  10. from tqdm import tqdm
  11. from embedchain.cache import (Config, ExactMatchEvaluation,
  12. SearchDistanceEvaluation, cache,
  13. gptcache_data_manager, gptcache_pre_function)
  14. from embedchain.client import Client
  15. from embedchain.config import AppConfig, CacheConfig, ChunkerConfig
  16. from embedchain.core.db.database import get_session, init_db, setup_engine
  17. from embedchain.core.db.models import DataSource
  18. from embedchain.embedchain import EmbedChain
  19. from embedchain.embedder.base import BaseEmbedder
  20. from embedchain.embedder.openai import OpenAIEmbedder
  21. from embedchain.evaluation.base import BaseMetric
  22. from embedchain.evaluation.metrics import (AnswerRelevance, ContextRelevance,
  23. Groundedness)
  24. from embedchain.factory import EmbedderFactory, LlmFactory, VectorDBFactory
  25. from embedchain.helpers.json_serializable import register_deserializable
  26. from embedchain.llm.base import BaseLlm
  27. from embedchain.llm.openai import OpenAILlm
  28. from embedchain.telemetry.posthog import AnonymousTelemetry
  29. from embedchain.utils.evaluation import EvalData, EvalMetric
  30. from embedchain.utils.misc import validate_config
  31. from embedchain.vectordb.base import BaseVectorDB
  32. from embedchain.vectordb.chroma import ChromaDB
  33. @register_deserializable
  34. class App(EmbedChain):
  35. """
  36. EmbedChain App lets you create a LLM powered app for your unstructured
  37. data by defining your chosen data source, embedding model,
  38. and vector database.
  39. """
  40. def __init__(
  41. self,
  42. id: str = None,
  43. name: str = None,
  44. config: AppConfig = None,
  45. db: BaseVectorDB = None,
  46. embedding_model: BaseEmbedder = None,
  47. llm: BaseLlm = None,
  48. config_data: dict = None,
  49. log_level=logging.WARN,
  50. auto_deploy: bool = False,
  51. chunker: ChunkerConfig = None,
  52. cache_config: CacheConfig = None,
  53. ):
  54. """
  55. Initialize a new `App` instance.
  56. :param config: Configuration for the pipeline, defaults to None
  57. :type config: AppConfig, optional
  58. :param db: The database to use for storing and retrieving embeddings, defaults to None
  59. :type db: BaseVectorDB, optional
  60. :param embedding_model: The embedding model used to calculate embeddings, defaults to None
  61. :type embedding_model: BaseEmbedder, optional
  62. :param llm: The LLM model used to calculate embeddings, defaults to None
  63. :type llm: BaseLlm, optional
  64. :param config_data: Config dictionary, defaults to None
  65. :type config_data: dict, optional
  66. :param log_level: Log level to use, defaults to logging.WARN
  67. :type log_level: int, optional
  68. :param auto_deploy: Whether to deploy the pipeline automatically, defaults to False
  69. :type auto_deploy: bool, optional
  70. :raises Exception: If an error occurs while creating the pipeline
  71. """
  72. if id and config_data:
  73. raise Exception("Cannot provide both id and config. Please provide only one of them.")
  74. if id and name:
  75. raise Exception("Cannot provide both id and name. Please provide only one of them.")
  76. if name and config:
  77. raise Exception("Cannot provide both name and config. Please provide only one of them.")
  78. logging.basicConfig(level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
  79. self.logger = logging.getLogger(__name__)
  80. # Initialize the metadata db for the app
  81. setup_engine(database_uri=os.environ.get("EMBEDCHAIN_DB_URI"))
  82. init_db()
  83. self.auto_deploy = auto_deploy
  84. # Store the dict config as an attribute to be able to send it
  85. self.config_data = config_data if (config_data and validate_config(config_data)) else None
  86. self.client = None
  87. # pipeline_id from the backend
  88. self.id = None
  89. self.chunker = ChunkerConfig(**chunker) if chunker else None
  90. self.cache_config = cache_config
  91. self.config = config or AppConfig()
  92. self.name = self.config.name
  93. self.config.id = self.local_id = str(uuid.uuid4()) if self.config.id is None else self.config.id
  94. if id is not None:
  95. # Init client first since user is trying to fetch the pipeline
  96. # details from the platform
  97. self._init_client()
  98. pipeline_details = self._get_pipeline(id)
  99. self.config.id = self.local_id = pipeline_details["metadata"]["local_id"]
  100. self.id = id
  101. if name is not None:
  102. self.name = name
  103. self.embedding_model = embedding_model or OpenAIEmbedder()
  104. self.db = db or ChromaDB()
  105. self.llm = llm or OpenAILlm()
  106. self._init_db()
  107. # Session for the metadata db
  108. self.db_session = get_session()
  109. # If cache_config is provided, initializing the cache ...
  110. if self.cache_config is not None:
  111. self._init_cache()
  112. # Send anonymous telemetry
  113. self._telemetry_props = {"class": self.__class__.__name__}
  114. self.telemetry = AnonymousTelemetry(enabled=self.config.collect_metrics)
  115. self.telemetry.capture(event_name="init", properties=self._telemetry_props)
  116. self.user_asks = []
  117. if self.auto_deploy:
  118. self.deploy()
  119. def _init_db(self):
  120. """
  121. Initialize the database.
  122. """
  123. self.db._set_embedder(self.embedding_model)
  124. self.db._initialize()
  125. self.db.set_collection_name(self.db.config.collection_name)
  126. def _init_cache(self):
  127. if self.cache_config.similarity_eval_config.strategy == "exact":
  128. similarity_eval_func = ExactMatchEvaluation()
  129. else:
  130. similarity_eval_func = SearchDistanceEvaluation(
  131. max_distance=self.cache_config.similarity_eval_config.max_distance,
  132. positive=self.cache_config.similarity_eval_config.positive,
  133. )
  134. cache.init(
  135. pre_embedding_func=gptcache_pre_function,
  136. embedding_func=self.embedding_model.to_embeddings,
  137. data_manager=gptcache_data_manager(vector_dimension=self.embedding_model.vector_dimension),
  138. similarity_evaluation=similarity_eval_func,
  139. config=Config(**self.cache_config.init_config.as_dict()),
  140. )
  141. def _init_client(self):
  142. """
  143. Initialize the client.
  144. """
  145. config = Client.load_config()
  146. if config.get("api_key"):
  147. self.client = Client()
  148. else:
  149. api_key = input(
  150. "🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/ \n" # noqa: E501
  151. )
  152. self.client = Client(api_key=api_key)
  153. def _get_pipeline(self, id):
  154. """
  155. Get existing pipeline
  156. """
  157. print("🛠️ Fetching pipeline details from the platform...")
  158. url = f"{self.client.host}/api/v1/pipelines/{id}/cli/"
  159. r = requests.get(
  160. url,
  161. headers={"Authorization": f"Token {self.client.api_key}"},
  162. )
  163. if r.status_code == 404:
  164. raise Exception(f"❌ Pipeline with id {id} not found!")
  165. print(
  166. f"🎉 Pipeline loaded successfully! Pipeline url: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  167. )
  168. return r.json()
  169. def _create_pipeline(self):
  170. """
  171. Create a pipeline on the platform.
  172. """
  173. print("🛠️ Creating pipeline on the platform...")
  174. # self.config_data is a dict. Pass it inside the key 'yaml_config' to the backend
  175. payload = {
  176. "yaml_config": json.dumps(self.config_data),
  177. "name": self.name,
  178. "local_id": self.local_id,
  179. }
  180. url = f"{self.client.host}/api/v1/pipelines/cli/create/"
  181. r = requests.post(
  182. url,
  183. json=payload,
  184. headers={"Authorization": f"Token {self.client.api_key}"},
  185. )
  186. if r.status_code not in [200, 201]:
  187. raise Exception(f"❌ Error occurred while creating pipeline. API response: {r.text}")
  188. if r.status_code == 200:
  189. print(
  190. f"🎉🎉🎉 Existing pipeline found! View your pipeline: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  191. ) # noqa: E501
  192. elif r.status_code == 201:
  193. print(
  194. f"🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  195. )
  196. return r.json()
  197. def _get_presigned_url(self, data_type, data_value):
  198. payload = {"data_type": data_type, "data_value": data_value}
  199. r = requests.post(
  200. f"{self.client.host}/api/v1/pipelines/{self.id}/cli/presigned_url/",
  201. json=payload,
  202. headers={"Authorization": f"Token {self.client.api_key}"},
  203. )
  204. r.raise_for_status()
  205. return r.json()
  206. def _upload_file_to_presigned_url(self, presigned_url, file_path):
  207. try:
  208. with open(file_path, "rb") as file:
  209. response = requests.put(presigned_url, data=file)
  210. response.raise_for_status()
  211. return response.status_code == 200
  212. except Exception as e:
  213. self.logger.exception(f"Error occurred during file upload: {str(e)}")
  214. print("❌ Error occurred during file upload!")
  215. return False
  216. def _upload_data_to_pipeline(self, data_type, data_value, metadata=None):
  217. payload = {
  218. "data_type": data_type,
  219. "data_value": data_value,
  220. "metadata": metadata,
  221. }
  222. try:
  223. self._send_api_request(f"/api/v1/pipelines/{self.id}/cli/add/", payload)
  224. # print the local file path if user tries to upload a local file
  225. printed_value = metadata.get("file_path") if metadata.get("file_path") else data_value
  226. print(f"✅ Data of type: {data_type}, value: {printed_value} added successfully.")
  227. except Exception as e:
  228. print(f"❌ Error occurred during data upload for type {data_type}!. Error: {str(e)}")
  229. def _send_api_request(self, endpoint, payload):
  230. url = f"{self.client.host}{endpoint}"
  231. headers = {"Authorization": f"Token {self.client.api_key}"}
  232. response = requests.post(url, json=payload, headers=headers)
  233. response.raise_for_status()
  234. return response
  235. def _process_and_upload_data(self, data_hash, data_type, data_value):
  236. if os.path.isabs(data_value):
  237. presigned_url_data = self._get_presigned_url(data_type, data_value)
  238. presigned_url = presigned_url_data["presigned_url"]
  239. s3_key = presigned_url_data["s3_key"]
  240. if self._upload_file_to_presigned_url(presigned_url, file_path=data_value):
  241. metadata = {"file_path": data_value, "s3_key": s3_key}
  242. data_value = presigned_url
  243. else:
  244. self.logger.error(f"File upload failed for hash: {data_hash}")
  245. return False
  246. else:
  247. if data_type == "qna_pair":
  248. data_value = list(ast.literal_eval(data_value))
  249. metadata = {}
  250. try:
  251. self._upload_data_to_pipeline(data_type, data_value, metadata)
  252. self._mark_data_as_uploaded(data_hash)
  253. return True
  254. except Exception:
  255. print(f"❌ Error occurred during data upload for hash {data_hash}!")
  256. return False
  257. def _mark_data_as_uploaded(self, data_hash):
  258. self.db_session.query(DataSource).filter_by(hash=data_hash, app_id=self.local_id).update({"is_uploaded": 1})
  259. def get_data_sources(self):
  260. data_sources = self.db_session.query(DataSource).filter_by(app_id=self.local_id).all()
  261. results = []
  262. for row in data_sources:
  263. results.append({"data_type": row.data_type, "data_value": row.data_value, "metadata": row.metadata})
  264. return results
  265. def deploy(self):
  266. if self.client is None:
  267. self._init_client()
  268. pipeline_data = self._create_pipeline()
  269. self.id = pipeline_data["id"]
  270. results = self.db_session.query(DataSource).filter_by(app_id=self.local_id, is_uploaded=0).all()
  271. if len(results) > 0:
  272. print("🛠️ Adding data to your pipeline...")
  273. for result in results:
  274. data_hash, data_type, data_value = result.hash, result.data_type, result.data_value
  275. self._process_and_upload_data(data_hash, data_type, data_value)
  276. # Send anonymous telemetry
  277. self.telemetry.capture(event_name="deploy", properties=self._telemetry_props)
  278. @classmethod
  279. def from_config(
  280. cls,
  281. config_path: Optional[str] = None,
  282. config: Optional[dict[str, Any]] = None,
  283. auto_deploy: bool = False,
  284. yaml_path: Optional[str] = None,
  285. ):
  286. """
  287. Instantiate a App object from a configuration.
  288. :param config_path: Path to the YAML or JSON configuration file.
  289. :type config_path: Optional[str]
  290. :param config: A dictionary containing the configuration.
  291. :type config: Optional[dict[str, Any]]
  292. :param auto_deploy: Whether to deploy the app automatically, defaults to False
  293. :type auto_deploy: bool, optional
  294. :param yaml_path: (Deprecated) Path to the YAML configuration file. Use config_path instead.
  295. :type yaml_path: Optional[str]
  296. :return: An instance of the App class.
  297. :rtype: App
  298. """
  299. # Backward compatibility for yaml_path
  300. if yaml_path and not config_path:
  301. config_path = yaml_path
  302. if config_path and config:
  303. raise ValueError("Please provide only one of config_path or config.")
  304. config_data = None
  305. if config_path:
  306. file_extension = os.path.splitext(config_path)[1]
  307. with open(config_path, "r", encoding="UTF-8") as file:
  308. if file_extension in [".yaml", ".yml"]:
  309. config_data = yaml.safe_load(file)
  310. elif file_extension == ".json":
  311. config_data = json.load(file)
  312. else:
  313. raise ValueError("config_path must be a path to a YAML or JSON file.")
  314. elif config and isinstance(config, dict):
  315. config_data = config
  316. else:
  317. logging.error(
  318. "Please provide either a config file path (YAML or JSON) or a config dictionary. Falling back to defaults because no config is provided.", # noqa: E501
  319. )
  320. config_data = {}
  321. try:
  322. validate_config(config_data)
  323. except Exception as e:
  324. raise Exception(f"Error occurred while validating the config. Error: {str(e)}")
  325. app_config_data = config_data.get("app", {}).get("config", {})
  326. vector_db_config_data = config_data.get("vectordb", {})
  327. embedding_model_config_data = config_data.get("embedding_model", config_data.get("embedder", {}))
  328. llm_config_data = config_data.get("llm", {})
  329. chunker_config_data = config_data.get("chunker", {})
  330. cache_config_data = config_data.get("cache", None)
  331. app_config = AppConfig(**app_config_data)
  332. vector_db_provider = vector_db_config_data.get("provider", "chroma")
  333. vector_db = VectorDBFactory.create(vector_db_provider, vector_db_config_data.get("config", {}))
  334. if llm_config_data:
  335. llm_provider = llm_config_data.get("provider", "openai")
  336. llm = LlmFactory.create(llm_provider, llm_config_data.get("config", {}))
  337. else:
  338. llm = None
  339. embedding_model_provider = embedding_model_config_data.get("provider", "openai")
  340. embedding_model = EmbedderFactory.create(
  341. embedding_model_provider, embedding_model_config_data.get("config", {})
  342. )
  343. if cache_config_data is not None:
  344. cache_config = CacheConfig.from_config(cache_config_data)
  345. else:
  346. cache_config = None
  347. return cls(
  348. config=app_config,
  349. llm=llm,
  350. db=vector_db,
  351. embedding_model=embedding_model,
  352. config_data=config_data,
  353. auto_deploy=auto_deploy,
  354. chunker=chunker_config_data,
  355. cache_config=cache_config,
  356. )
  357. def _eval(self, dataset: list[EvalData], metric: Union[BaseMetric, str]):
  358. """
  359. Evaluate the app on a dataset for a given metric.
  360. """
  361. metric_str = metric.name if isinstance(metric, BaseMetric) else metric
  362. eval_class_map = {
  363. EvalMetric.CONTEXT_RELEVANCY.value: ContextRelevance,
  364. EvalMetric.ANSWER_RELEVANCY.value: AnswerRelevance,
  365. EvalMetric.GROUNDEDNESS.value: Groundedness,
  366. }
  367. if metric_str in eval_class_map:
  368. return eval_class_map[metric_str]().evaluate(dataset)
  369. # Handle the case for custom metrics
  370. if isinstance(metric, BaseMetric):
  371. return metric.evaluate(dataset)
  372. else:
  373. raise ValueError(f"Invalid metric: {metric}")
  374. def evaluate(
  375. self,
  376. questions: Union[str, list[str]],
  377. metrics: Optional[list[Union[BaseMetric, str]]] = None,
  378. num_workers: int = 4,
  379. ):
  380. """
  381. Evaluate the app on a question.
  382. param: questions: A question or a list of questions to evaluate.
  383. type: questions: Union[str, list[str]]
  384. param: metrics: A list of metrics to evaluate. Defaults to all metrics.
  385. type: metrics: Optional[list[Union[BaseMetric, str]]]
  386. param: num_workers: Number of workers to use for parallel processing.
  387. type: num_workers: int
  388. return: A dictionary containing the evaluation results.
  389. rtype: dict
  390. """
  391. if "OPENAI_API_KEY" not in os.environ:
  392. raise ValueError("Please set the OPENAI_API_KEY environment variable with permission to use `gpt4` model.")
  393. queries, answers, contexts = [], [], []
  394. if isinstance(questions, list):
  395. with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
  396. future_to_data = {executor.submit(self.query, q, citations=True): q for q in questions}
  397. for future in tqdm(
  398. concurrent.futures.as_completed(future_to_data),
  399. total=len(future_to_data),
  400. desc="Getting answer and contexts for questions",
  401. ):
  402. question = future_to_data[future]
  403. queries.append(question)
  404. answer, context = future.result()
  405. answers.append(answer)
  406. contexts.append(list(map(lambda x: x[0], context)))
  407. else:
  408. answer, context = self.query(questions, citations=True)
  409. queries = [questions]
  410. answers = [answer]
  411. contexts = [list(map(lambda x: x[0], context))]
  412. metrics = metrics or [
  413. EvalMetric.CONTEXT_RELEVANCY.value,
  414. EvalMetric.ANSWER_RELEVANCY.value,
  415. EvalMetric.GROUNDEDNESS.value,
  416. ]
  417. logging.info(f"Collecting data from {len(queries)} questions for evaluation...")
  418. dataset = []
  419. for q, a, c in zip(queries, answers, contexts):
  420. dataset.append(EvalData(question=q, answer=a, contexts=c))
  421. logging.info(f"Evaluating {len(dataset)} data points...")
  422. result = {}
  423. with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
  424. future_to_metric = {executor.submit(self._eval, dataset, metric): metric for metric in metrics}
  425. for future in tqdm(
  426. concurrent.futures.as_completed(future_to_metric),
  427. total=len(future_to_metric),
  428. desc="Evaluating metrics",
  429. ):
  430. metric = future_to_metric[future]
  431. if isinstance(metric, BaseMetric):
  432. result[metric.name] = future.result()
  433. else:
  434. result[metric] = future.result()
  435. if self.config.collect_metrics:
  436. telemetry_props = self._telemetry_props
  437. metrics_names = []
  438. for metric in metrics:
  439. if isinstance(metric, BaseMetric):
  440. metrics_names.append(metric.name)
  441. else:
  442. metrics_names.append(metric)
  443. telemetry_props["metrics"] = metrics_names
  444. self.telemetry.capture(event_name="evaluate", properties=telemetry_props)
  445. return result