app.py 17 KB

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