app.py 22 KB

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