pipeline.py 15 KB

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