app.py 21 KB

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