app.py 20 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. 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. logger.debug("4.0")
  77. # Initialize the metadata db for the app
  78. setup_engine(database_uri=os.environ.get("EMBEDCHAIN_DB_URI"))
  79. init_db()
  80. logger.debug("4.0")
  81. self.auto_deploy = auto_deploy
  82. # Store the dict config as an attribute to be able to send it
  83. self.config_data = config_data if (config_data and validate_config(config_data)) else None
  84. self.client = None
  85. # pipeline_id from the backend
  86. self.id = None
  87. self.chunker = ChunkerConfig(**chunker) if chunker else None
  88. self.cache_config = cache_config
  89. self.config = config or AppConfig()
  90. self.name = self.config.name
  91. self.config.id = self.local_id = "default-app-id" if self.config.id is None else self.config.id
  92. if id is not None:
  93. # Init client first since user is trying to fetch the pipeline
  94. # details from the platform
  95. self._init_client()
  96. pipeline_details = self._get_pipeline(id)
  97. self.config.id = self.local_id = pipeline_details["metadata"]["local_id"]
  98. self.id = id
  99. if name is not None:
  100. self.name = name
  101. self.embedding_model = embedding_model or OpenAIEmbedder()
  102. self.db = db or ChromaDB()
  103. self.llm = llm or OpenAILlm()
  104. self._init_db()
  105. logger.debug("4.1")
  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. logger.debug("4.2")
  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. 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. 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.type, "data_value": row.value, "metadata": row.meta_data})
  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. logger.debug("6")
  300. # Backward compatibility for yaml_path
  301. if yaml_path and not config_path:
  302. config_path = yaml_path
  303. if config_path and config:
  304. raise ValueError("Please provide only one of config_path or config.")
  305. config_data = None
  306. if config_path:
  307. file_extension = os.path.splitext(config_path)[1]
  308. with open(config_path, "r", encoding="UTF-8") as file:
  309. if file_extension in [".yaml", ".yml"]:
  310. config_data = yaml.safe_load(file)
  311. elif file_extension == ".json":
  312. config_data = json.load(file)
  313. else:
  314. raise ValueError("config_path must be a path to a YAML or JSON file.")
  315. elif config and isinstance(config, dict):
  316. config_data = config
  317. else:
  318. logger.error(
  319. "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
  320. )
  321. config_data = {}
  322. # Validate the config
  323. validate_config(config_data)
  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. logger.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. logger.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