pipeline.py 13 KB

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