app.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 search(self, query, num_documents=3):
  225. """
  226. Search for similar documents related to the query in the vector database.
  227. """
  228. # Send anonymous telemetry
  229. self.telemetry.capture(event_name="search", properties=self._telemetry_props)
  230. # TODO: Search will call the endpoint rather than fetching the data from the db itself when deploy=True.
  231. if self.id is None:
  232. where = {"app_id": self.local_id}
  233. context = self.db.query(
  234. query,
  235. n_results=num_documents,
  236. where=where,
  237. citations=True,
  238. )
  239. result = []
  240. for c in context:
  241. result.append({"context": c[0], "metadata": c[1]})
  242. return result
  243. else:
  244. # Make API call to the backend to get the results
  245. NotImplementedError("Search is not implemented yet for the prod mode.")
  246. def _upload_file_to_presigned_url(self, presigned_url, file_path):
  247. try:
  248. with open(file_path, "rb") as file:
  249. response = requests.put(presigned_url, data=file)
  250. response.raise_for_status()
  251. return response.status_code == 200
  252. except Exception as e:
  253. self.logger.exception(f"Error occurred during file upload: {str(e)}")
  254. print("❌ Error occurred during file upload!")
  255. return False
  256. def _upload_data_to_pipeline(self, data_type, data_value, metadata=None):
  257. payload = {
  258. "data_type": data_type,
  259. "data_value": data_value,
  260. "metadata": metadata,
  261. }
  262. try:
  263. self._send_api_request(f"/api/v1/pipelines/{self.id}/cli/add/", payload)
  264. # print the local file path if user tries to upload a local file
  265. printed_value = metadata.get("file_path") if metadata.get("file_path") else data_value
  266. print(f"✅ Data of type: {data_type}, value: {printed_value} added successfully.")
  267. except Exception as e:
  268. print(f"❌ Error occurred during data upload for type {data_type}!. Error: {str(e)}")
  269. def _send_api_request(self, endpoint, payload):
  270. url = f"{self.client.host}{endpoint}"
  271. headers = {"Authorization": f"Token {self.client.api_key}"}
  272. response = requests.post(url, json=payload, headers=headers)
  273. response.raise_for_status()
  274. return response
  275. def _process_and_upload_data(self, data_hash, data_type, data_value):
  276. if os.path.isabs(data_value):
  277. presigned_url_data = self._get_presigned_url(data_type, data_value)
  278. presigned_url = presigned_url_data["presigned_url"]
  279. s3_key = presigned_url_data["s3_key"]
  280. if self._upload_file_to_presigned_url(presigned_url, file_path=data_value):
  281. metadata = {"file_path": data_value, "s3_key": s3_key}
  282. data_value = presigned_url
  283. else:
  284. self.logger.error(f"File upload failed for hash: {data_hash}")
  285. return False
  286. else:
  287. if data_type == "qna_pair":
  288. data_value = list(ast.literal_eval(data_value))
  289. metadata = {}
  290. try:
  291. self._upload_data_to_pipeline(data_type, data_value, metadata)
  292. self._mark_data_as_uploaded(data_hash)
  293. return True
  294. except Exception:
  295. print(f"❌ Error occurred during data upload for hash {data_hash}!")
  296. return False
  297. def _mark_data_as_uploaded(self, data_hash):
  298. self.cursor.execute(
  299. "UPDATE data_sources SET is_uploaded = 1 WHERE hash = ? AND pipeline_id = ?",
  300. (data_hash, self.local_id),
  301. )
  302. self.connection.commit()
  303. def get_data_sources(self):
  304. db_data = self.cursor.execute("SELECT * FROM data_sources WHERE pipeline_id = ?", (self.local_id,)).fetchall()
  305. data_sources = []
  306. for data in db_data:
  307. data_sources.append({"data_type": data[2], "data_value": data[3], "metadata": data[4]})
  308. return data_sources
  309. def deploy(self):
  310. if self.client is None:
  311. self._init_client()
  312. pipeline_data = self._create_pipeline()
  313. self.id = pipeline_data["id"]
  314. results = self.cursor.execute(
  315. "SELECT * FROM data_sources WHERE pipeline_id = ? AND is_uploaded = 0", (self.local_id,) # noqa:E501
  316. ).fetchall()
  317. if len(results) > 0:
  318. print("🛠️ Adding data to your pipeline...")
  319. for result in results:
  320. data_hash, data_type, data_value = result[1], result[2], result[3]
  321. self._process_and_upload_data(data_hash, data_type, data_value)
  322. # Send anonymous telemetry
  323. self.telemetry.capture(event_name="deploy", properties=self._telemetry_props)
  324. @classmethod
  325. def from_config(
  326. cls,
  327. config_path: Optional[str] = None,
  328. config: Optional[dict[str, Any]] = None,
  329. auto_deploy: bool = False,
  330. yaml_path: Optional[str] = None,
  331. ):
  332. """
  333. Instantiate a Pipeline object from a configuration.
  334. :param config_path: Path to the YAML or JSON configuration file.
  335. :type config_path: Optional[str]
  336. :param config: A dictionary containing the configuration.
  337. :type config: Optional[dict[str, Any]]
  338. :param auto_deploy: Whether to deploy the pipeline automatically, defaults to False
  339. :type auto_deploy: bool, optional
  340. :param yaml_path: (Deprecated) Path to the YAML configuration file. Use config_path instead.
  341. :type yaml_path: Optional[str]
  342. :return: An instance of the Pipeline class.
  343. :rtype: Pipeline
  344. """
  345. # Backward compatibility for yaml_path
  346. if yaml_path and not config_path:
  347. config_path = yaml_path
  348. if config_path and config:
  349. raise ValueError("Please provide only one of config_path or config.")
  350. config_data = None
  351. if config_path:
  352. file_extension = os.path.splitext(config_path)[1]
  353. with open(config_path, "r", encoding="UTF-8") as file:
  354. if file_extension in [".yaml", ".yml"]:
  355. config_data = yaml.safe_load(file)
  356. elif file_extension == ".json":
  357. config_data = json.load(file)
  358. else:
  359. raise ValueError("config_path must be a path to a YAML or JSON file.")
  360. elif config and isinstance(config, dict):
  361. config_data = config
  362. else:
  363. logging.error(
  364. "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
  365. )
  366. config_data = {}
  367. try:
  368. validate_config(config_data)
  369. except Exception as e:
  370. raise Exception(f"Error occurred while validating the config. Error: {str(e)}")
  371. app_config_data = config_data.get("app", {}).get("config", {})
  372. db_config_data = config_data.get("vectordb", {})
  373. embedding_model_config_data = config_data.get("embedding_model", config_data.get("embedder", {}))
  374. llm_config_data = config_data.get("llm", {})
  375. chunker_config_data = config_data.get("chunker", {})
  376. cache_config_data = config_data.get("cache", None)
  377. app_config = AppConfig(**app_config_data)
  378. db_provider = db_config_data.get("provider", "chroma")
  379. db = VectorDBFactory.create(db_provider, db_config_data.get("config", {}))
  380. if llm_config_data:
  381. llm_provider = llm_config_data.get("provider", "openai")
  382. llm = LlmFactory.create(llm_provider, llm_config_data.get("config", {}))
  383. else:
  384. llm = None
  385. embedding_model_provider = embedding_model_config_data.get("provider", "openai")
  386. embedding_model = EmbedderFactory.create(
  387. embedding_model_provider, embedding_model_config_data.get("config", {})
  388. )
  389. if cache_config_data is not None:
  390. cache_config = CacheConfig.from_config(cache_config_data)
  391. else:
  392. cache_config = None
  393. # Send anonymous telemetry
  394. event_properties = {"init_type": "config_data"}
  395. AnonymousTelemetry().capture(event_name="init", properties=event_properties)
  396. return cls(
  397. config=app_config,
  398. llm=llm,
  399. db=db,
  400. embedding_model=embedding_model,
  401. config_data=config_data,
  402. auto_deploy=auto_deploy,
  403. chunker=chunker_config_data,
  404. cache_config=cache_config,
  405. )
  406. def _eval(self, dataset: list[EvalData], metric: Union[BaseMetric, str]):
  407. """
  408. Evaluate the app on a dataset for a given metric.
  409. """
  410. metric_str = metric.name if isinstance(metric, BaseMetric) else metric
  411. eval_class_map = {
  412. EvalMetric.CONTEXT_RELEVANCY.value: ContextRelevance,
  413. EvalMetric.ANSWER_RELEVANCY.value: AnswerRelevance,
  414. EvalMetric.GROUNDEDNESS.value: Groundedness,
  415. }
  416. if metric_str in eval_class_map:
  417. return eval_class_map[metric_str]().evaluate(dataset)
  418. # Handle the case for custom metrics
  419. if isinstance(metric, BaseMetric):
  420. return metric.evaluate(dataset)
  421. else:
  422. raise ValueError(f"Invalid metric: {metric}")
  423. def evaluate(
  424. self,
  425. questions: Union[str, list[str]],
  426. metrics: Optional[list[Union[BaseMetric, str]]] = None,
  427. num_workers: int = 4,
  428. ):
  429. """
  430. Evaluate the app on a question.
  431. param: questions: A question or a list of questions to evaluate.
  432. type: questions: Union[str, list[str]]
  433. param: metrics: A list of metrics to evaluate. Defaults to all metrics.
  434. type: metrics: Optional[list[Union[BaseMetric, str]]]
  435. param: num_workers: Number of workers to use for parallel processing.
  436. type: num_workers: int
  437. return: A dictionary containing the evaluation results.
  438. rtype: dict
  439. """
  440. if "OPENAI_API_KEY" not in os.environ:
  441. raise ValueError("Please set the OPENAI_API_KEY environment variable with permission to use `gpt4` model.")
  442. queries, answers, contexts = [], [], []
  443. if isinstance(questions, list):
  444. with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
  445. future_to_data = {executor.submit(self.query, q, citations=True): q for q in questions}
  446. for future in tqdm(
  447. concurrent.futures.as_completed(future_to_data),
  448. total=len(future_to_data),
  449. desc="Getting answer and contexts for questions",
  450. ):
  451. question = future_to_data[future]
  452. queries.append(question)
  453. answer, context = future.result()
  454. answers.append(answer)
  455. contexts.append(list(map(lambda x: x[0], context)))
  456. else:
  457. answer, context = self.query(questions, citations=True)
  458. queries = [questions]
  459. answers = [answer]
  460. contexts = [list(map(lambda x: x[0], context))]
  461. metrics = metrics or [
  462. EvalMetric.CONTEXT_RELEVANCY.value,
  463. EvalMetric.ANSWER_RELEVANCY.value,
  464. EvalMetric.GROUNDEDNESS.value,
  465. ]
  466. logging.info(f"Collecting data from {len(queries)} questions for evaluation...")
  467. dataset = []
  468. for q, a, c in zip(queries, answers, contexts):
  469. dataset.append(EvalData(question=q, answer=a, contexts=c))
  470. logging.info(f"Evaluating {len(dataset)} data points...")
  471. result = {}
  472. with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
  473. future_to_metric = {executor.submit(self._eval, dataset, metric): metric for metric in metrics}
  474. for future in tqdm(
  475. concurrent.futures.as_completed(future_to_metric),
  476. total=len(future_to_metric),
  477. desc="Evaluating metrics",
  478. ):
  479. metric = future_to_metric[future]
  480. if isinstance(metric, BaseMetric):
  481. result[metric.name] = future.result()
  482. else:
  483. result[metric] = future.result()
  484. if self.config.collect_metrics:
  485. telemetry_props = self._telemetry_props
  486. metrics_names = []
  487. for metric in metrics:
  488. if isinstance(metric, BaseMetric):
  489. metrics_names.append(metric.name)
  490. else:
  491. metrics_names.append(metric)
  492. telemetry_props["metrics"] = metrics_names
  493. self.telemetry.capture(event_name="evaluate", properties=telemetry_props)
  494. return result