pipeline.py 16 KB

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