app.py 20 KB

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