app.py 18 KB

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