app.py 21 KB

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