app.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import ast
  2. import json
  3. import logging
  4. import os
  5. import sqlite3
  6. import uuid
  7. from typing import Any, Dict, Optional
  8. import requests
  9. import yaml
  10. from embedchain.client import Client
  11. from embedchain.config import AppConfig, ChunkerConfig
  12. from embedchain.constants import SQLITE_PATH
  13. from embedchain.embedchain import EmbedChain
  14. from embedchain.embedder.base import BaseEmbedder
  15. from embedchain.embedder.openai import OpenAIEmbedder
  16. from embedchain.factory import EmbedderFactory, LlmFactory, VectorDBFactory
  17. from embedchain.helpers.json_serializable import register_deserializable
  18. from embedchain.llm.base import BaseLlm
  19. from embedchain.llm.openai import OpenAILlm
  20. from embedchain.telemetry.posthog import AnonymousTelemetry
  21. from embedchain.utils import validate_config
  22. from embedchain.vectordb.base import BaseVectorDB
  23. from embedchain.vectordb.chroma import ChromaDB
  24. # Setup the user directory if doesn't exist already
  25. Client.setup_dir()
  26. @register_deserializable
  27. class App(EmbedChain):
  28. """
  29. EmbedChain App lets you create a LLM powered app for your unstructured
  30. data by defining your chosen data source, embedding model,
  31. and vector database.
  32. """
  33. def __init__(
  34. self,
  35. id: str = None,
  36. name: str = None,
  37. config: AppConfig = None,
  38. db: BaseVectorDB = None,
  39. embedding_model: BaseEmbedder = None,
  40. llm: BaseLlm = None,
  41. config_data: dict = None,
  42. log_level=logging.WARN,
  43. auto_deploy: bool = False,
  44. chunker: ChunkerConfig = None,
  45. ):
  46. """
  47. Initialize a new `App` instance.
  48. :param config: Configuration for the pipeline, defaults to None
  49. :type config: AppConfig, optional
  50. :param db: The database to use for storing and retrieving embeddings, defaults to None
  51. :type db: BaseVectorDB, optional
  52. :param embedding_model: The embedding model used to calculate embeddings, defaults to None
  53. :type embedding_model: BaseEmbedder, optional
  54. :param llm: The LLM model used to calculate embeddings, defaults to None
  55. :type llm: BaseLlm, optional
  56. :param config_data: Config dictionary, defaults to None
  57. :type config_data: dict, optional
  58. :param log_level: Log level to use, defaults to logging.WARN
  59. :type log_level: int, optional
  60. :param auto_deploy: Whether to deploy the pipeline automatically, defaults to False
  61. :type auto_deploy: bool, optional
  62. :raises Exception: If an error occurs while creating the pipeline
  63. """
  64. if id and config_data:
  65. raise Exception("Cannot provide both id and config. Please provide only one of them.")
  66. if id and name:
  67. raise Exception("Cannot provide both id and name. Please provide only one of them.")
  68. if name and config:
  69. raise Exception("Cannot provide both name and config. Please provide only one of them.")
  70. logging.basicConfig(level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
  71. self.logger = logging.getLogger(__name__)
  72. self.auto_deploy = auto_deploy
  73. # Store the dict config as an attribute to be able to send it
  74. self.config_data = config_data if (config_data and validate_config(config_data)) else None
  75. self.client = None
  76. # pipeline_id from the backend
  77. self.id = None
  78. self.chunker = None
  79. if chunker:
  80. self.chunker = ChunkerConfig(**chunker)
  81. self.config = config or AppConfig()
  82. self.name = self.config.name
  83. self.config.id = self.local_id = str(uuid.uuid4()) if self.config.id is None else self.config.id
  84. if id is not None:
  85. # Init client first since user is trying to fetch the pipeline
  86. # details from the platform
  87. self._init_client()
  88. pipeline_details = self._get_pipeline(id)
  89. self.config.id = self.local_id = pipeline_details["metadata"]["local_id"]
  90. self.id = id
  91. if name is not None:
  92. self.name = name
  93. self.embedding_model = embedding_model or OpenAIEmbedder()
  94. self.db = db or ChromaDB()
  95. self.llm = llm or OpenAILlm()
  96. self._init_db()
  97. # Send anonymous telemetry
  98. self._telemetry_props = {"class": self.__class__.__name__}
  99. self.telemetry = AnonymousTelemetry(enabled=self.config.collect_metrics)
  100. # Establish a connection to the SQLite database
  101. self.connection = sqlite3.connect(SQLITE_PATH, check_same_thread=False)
  102. self.cursor = self.connection.cursor()
  103. # Create the 'data_sources' table if it doesn't exist
  104. self.cursor.execute(
  105. """
  106. CREATE TABLE IF NOT EXISTS data_sources (
  107. pipeline_id TEXT,
  108. hash TEXT,
  109. type TEXT,
  110. value TEXT,
  111. metadata TEXT,
  112. is_uploaded INTEGER DEFAULT 0,
  113. PRIMARY KEY (pipeline_id, hash)
  114. )
  115. """
  116. )
  117. self.connection.commit()
  118. # Send anonymous telemetry
  119. self.telemetry.capture(event_name="init", properties=self._telemetry_props)
  120. self.user_asks = []
  121. if self.auto_deploy:
  122. self.deploy()
  123. def _init_db(self):
  124. """
  125. Initialize the database.
  126. """
  127. self.db._set_embedder(self.embedding_model)
  128. self.db._initialize()
  129. self.db.set_collection_name(self.db.config.collection_name)
  130. def _init_client(self):
  131. """
  132. Initialize the client.
  133. """
  134. config = Client.load_config()
  135. if config.get("api_key"):
  136. self.client = Client()
  137. else:
  138. api_key = input(
  139. "🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/ \n" # noqa: E501
  140. )
  141. self.client = Client(api_key=api_key)
  142. def _get_pipeline(self, id):
  143. """
  144. Get existing pipeline
  145. """
  146. print("🛠️ Fetching pipeline details from the platform...")
  147. url = f"{self.client.host}/api/v1/pipelines/{id}/cli/"
  148. r = requests.get(
  149. url,
  150. headers={"Authorization": f"Token {self.client.api_key}"},
  151. )
  152. if r.status_code == 404:
  153. raise Exception(f"❌ Pipeline with id {id} not found!")
  154. print(
  155. f"🎉 Pipeline loaded successfully! Pipeline url: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  156. )
  157. return r.json()
  158. def _create_pipeline(self):
  159. """
  160. Create a pipeline on the platform.
  161. """
  162. print("🛠️ Creating pipeline on the platform...")
  163. # self.config_data is a dict. Pass it inside the key 'yaml_config' to the backend
  164. payload = {
  165. "yaml_config": json.dumps(self.config_data),
  166. "name": self.name,
  167. "local_id": self.local_id,
  168. }
  169. url = f"{self.client.host}/api/v1/pipelines/cli/create/"
  170. r = requests.post(
  171. url,
  172. json=payload,
  173. headers={"Authorization": f"Token {self.client.api_key}"},
  174. )
  175. if r.status_code not in [200, 201]:
  176. raise Exception(f"❌ Error occurred while creating pipeline. API response: {r.text}")
  177. if r.status_code == 200:
  178. print(
  179. f"🎉🎉🎉 Existing pipeline found! View your pipeline: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  180. ) # noqa: E501
  181. elif r.status_code == 201:
  182. print(
  183. f"🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/{r.json()['id']}\n" # noqa: E501
  184. )
  185. return r.json()
  186. def _get_presigned_url(self, data_type, data_value):
  187. payload = {"data_type": data_type, "data_value": data_value}
  188. r = requests.post(
  189. f"{self.client.host}/api/v1/pipelines/{self.id}/cli/presigned_url/",
  190. json=payload,
  191. headers={"Authorization": f"Token {self.client.api_key}"},
  192. )
  193. r.raise_for_status()
  194. return r.json()
  195. def search(self, query, num_documents=3):
  196. """
  197. Search for similar documents related to the query in the vector database.
  198. """
  199. # Send anonymous telemetry
  200. self.telemetry.capture(event_name="search", properties=self._telemetry_props)
  201. # TODO: Search will call the endpoint rather than fetching the data from the db itself when deploy=True.
  202. if self.id is None:
  203. where = {"app_id": self.local_id}
  204. context = self.db.query(
  205. query,
  206. n_results=num_documents,
  207. where=where,
  208. skip_embedding=False,
  209. citations=True,
  210. )
  211. result = []
  212. for c in context:
  213. result.append(
  214. {
  215. "context": c[0],
  216. "source": c[1],
  217. "document_id": c[2],
  218. }
  219. )
  220. return result
  221. else:
  222. # Make API call to the backend to get the results
  223. NotImplementedError("Search is not implemented yet for the prod mode.")
  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") 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. app_config = AppConfig(**app_config_data)
  355. db_provider = db_config_data.get("provider", "chroma")
  356. db = VectorDBFactory.create(db_provider, db_config_data.get("config", {}))
  357. if llm_config_data:
  358. llm_provider = llm_config_data.get("provider", "openai")
  359. llm = LlmFactory.create(llm_provider, llm_config_data.get("config", {}))
  360. else:
  361. llm = None
  362. embedding_model_provider = embedding_model_config_data.get("provider", "openai")
  363. embedding_model = EmbedderFactory.create(
  364. embedding_model_provider, embedding_model_config_data.get("config", {})
  365. )
  366. # Send anonymous telemetry
  367. event_properties = {"init_type": "config_data"}
  368. AnonymousTelemetry().capture(event_name="init", properties=event_properties)
  369. return cls(
  370. config=app_config,
  371. llm=llm,
  372. db=db,
  373. embedding_model=embedding_model,
  374. config_data=config_data,
  375. auto_deploy=auto_deploy,
  376. chunker=chunker_config_data,
  377. )