cli.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import json
  2. import os
  3. import re
  4. import shutil
  5. import subprocess
  6. import click
  7. import pkg_resources
  8. from rich.console import Console
  9. from embedchain.telemetry.posthog import AnonymousTelemetry
  10. console = Console()
  11. @click.group()
  12. def cli():
  13. pass
  14. anonymous_telemetry = AnonymousTelemetry()
  15. def get_pkg_path_from_name(template: str):
  16. try:
  17. # Determine the installation location of the embedchain package
  18. package_path = pkg_resources.resource_filename("embedchain", "")
  19. except ImportError:
  20. console.print("❌ [bold red]Failed to locate the 'embedchain' package. Is it installed?[/bold red]")
  21. return
  22. # Construct the source path from the embedchain package
  23. src_path = os.path.join(package_path, "deployment", template)
  24. if not os.path.exists(src_path):
  25. console.print(f"❌ [bold red]Template '{template}' not found.[/bold red]")
  26. return
  27. return src_path
  28. def setup_fly_io_app(extra_args):
  29. fly_launch_command = ["fly", "launch", "--region", "sjc", "--no-deploy"] + list(extra_args)
  30. try:
  31. console.print(f"🚀 [bold cyan]Running: {' '.join(fly_launch_command)}[/bold cyan]")
  32. subprocess.run(fly_launch_command, check=True)
  33. console.print("✅ [bold green]'fly launch' executed successfully.[/bold green]")
  34. except subprocess.CalledProcessError as e:
  35. console.print(f"❌ [bold red]An error occurred: {e}[/bold red]")
  36. except FileNotFoundError:
  37. console.print(
  38. "❌ [bold red]'fly' command not found. Please ensure Fly CLI is installed and in your PATH.[/bold red]"
  39. )
  40. def setup_modal_com_app(extra_args):
  41. modal_setup_file = os.path.join(os.path.expanduser("~"), ".modal.toml")
  42. if os.path.exists(modal_setup_file):
  43. console.print(
  44. """✅ [bold green]Modal setup already done. You can now install the dependencies by doing \n
  45. `pip install -r requirements.txt`[/bold green]"""
  46. )
  47. return
  48. modal_setup_cmd = ["modal", "setup"] + list(extra_args)
  49. console.print(f"🚀 [bold cyan]Running: {' '.join(modal_setup_cmd)}[/bold cyan]")
  50. subprocess.run(modal_setup_cmd, check=True)
  51. shutil.move(".env.example", ".env")
  52. console.print("Great! Now you can install the dependencies by doing `pip install -r requirements.txt`")
  53. @cli.command()
  54. @click.option("--template", default="fly.io", help="The template to use.")
  55. @click.argument("extra_args", nargs=-1, type=click.UNPROCESSED)
  56. def create(template, extra_args):
  57. anonymous_telemetry.capture(
  58. event_name="ec_create", properties={"template_used": template}
  59. )
  60. src_path = get_pkg_path_from_name(template)
  61. shutil.copytree(src_path, os.getcwd(), dirs_exist_ok=True)
  62. env_sample_path = os.path.join(src_path, ".env.example")
  63. if os.path.exists(env_sample_path):
  64. shutil.copy(env_sample_path, os.path.join(os.getcwd(), ".env"))
  65. console.print(f"✅ [bold green]Successfully created app from template '{template}'.[/bold green]")
  66. if template == "fly.io":
  67. setup_fly_io_app(extra_args)
  68. elif template == "modal.com":
  69. setup_modal_com_app(extra_args)
  70. else:
  71. raise ValueError(f"Unknown template '{template}'.")
  72. embedchain_config = {"provider": template}
  73. with open("embedchain.json", "w") as file:
  74. json.dump(embedchain_config, file, indent=4)
  75. console.print(
  76. f"🎉 [green]All done! Successfully created `embedchain.json` with '{template}' as provider.[/green]"
  77. )
  78. def run_dev_fly_io(debug, host, port):
  79. uvicorn_command = ["uvicorn", "app:app"]
  80. if debug:
  81. uvicorn_command.append("--reload")
  82. uvicorn_command.extend(["--host", host, "--port", str(port)])
  83. try:
  84. console.print(f"🚀 [bold cyan]Running FastAPI app with command: {' '.join(uvicorn_command)}[/bold cyan]")
  85. subprocess.run(uvicorn_command, check=True)
  86. except subprocess.CalledProcessError as e:
  87. console.print(f"❌ [bold red]An error occurred: {e}[/bold red]")
  88. except KeyboardInterrupt:
  89. console.print("\n🛑 [bold yellow]FastAPI server stopped[/bold yellow]")
  90. def run_dev_modal_com():
  91. modal_run_cmd = ["modal", "serve", "app"]
  92. try:
  93. console.print(f"🚀 [bold cyan]Running FastAPI app with command: {' '.join(modal_run_cmd)}[/bold cyan]")
  94. subprocess.run(modal_run_cmd, check=True)
  95. except subprocess.CalledProcessError as e:
  96. console.print(f"❌ [bold red]An error occurred: {e}[/bold red]")
  97. except KeyboardInterrupt:
  98. console.print("\n🛑 [bold yellow]FastAPI server stopped[/bold yellow]")
  99. @cli.command()
  100. @click.option("--debug", is_flag=True, help="Enable or disable debug mode.")
  101. @click.option("--host", default="127.0.0.1", help="The host address to run the FastAPI app on.")
  102. @click.option("--port", default=8000, help="The port to run the FastAPI app on.")
  103. def dev(debug, host, port):
  104. template = ""
  105. with open("embedchain.json", "r") as file:
  106. embedchain_config = json.load(file)
  107. template = embedchain_config["provider"]
  108. anonymous_telemetry.capture(
  109. event_name="ec_dev", properties={"template_used": template}
  110. )
  111. if template == "fly.io":
  112. run_dev_fly_io(debug, host, port)
  113. elif template == "modal.com":
  114. run_dev_modal_com()
  115. else:
  116. raise ValueError(f"Unknown template '{template}'.")
  117. def read_env_file(env_file_path):
  118. """
  119. Reads an environment file and returns a dictionary of key-value pairs.
  120. Args:
  121. env_file_path (str): The path to the .env file.
  122. Returns:
  123. dict: Dictionary of environment variables.
  124. """
  125. env_vars = {}
  126. with open(env_file_path, "r") as file:
  127. for line in file:
  128. # Ignore comments and empty lines
  129. if line.strip() and not line.strip().startswith("#"):
  130. # Assume each line is in the format KEY=VALUE
  131. key_value_match = re.match(r"(\w+)=(.*)", line.strip())
  132. if key_value_match:
  133. key, value = key_value_match.groups()
  134. env_vars[key] = value
  135. return env_vars
  136. def deploy_fly():
  137. app_name = ""
  138. with open("fly.toml", "r") as file:
  139. for line in file:
  140. if line.strip().startswith("app ="):
  141. app_name = line.split("=")[1].strip().strip('"')
  142. if not app_name:
  143. console.print("❌ [bold red]App name not found in fly.toml[/bold red]")
  144. return
  145. env_vars = read_env_file(".env")
  146. secrets_command = ["flyctl", "secrets", "set", "-a", app_name] + [f"{k}={v}" for k, v in env_vars.items()]
  147. deploy_command = ["fly", "deploy"]
  148. try:
  149. # Set secrets
  150. console.print(f"🔐 [bold cyan]Setting secrets for {app_name}[/bold cyan]")
  151. subprocess.run(secrets_command, check=True)
  152. # Deploy application
  153. console.print(f"🚀 [bold cyan]Running: {' '.join(deploy_command)}[/bold cyan]")
  154. subprocess.run(deploy_command, check=True)
  155. console.print("✅ [bold green]'fly deploy' executed successfully.[/bold green]")
  156. except subprocess.CalledProcessError as e:
  157. console.print(f"❌ [bold red]An error occurred: {e}[/bold red]")
  158. except FileNotFoundError:
  159. console.print(
  160. "❌ [bold red]'fly' command not found. Please ensure Fly CLI is installed and in your PATH.[/bold red]"
  161. )
  162. def deploy_modal():
  163. modal_deploy_cmd = ["modal", "deploy", "app"]
  164. try:
  165. console.print(f"🚀 [bold cyan]Running: {' '.join(modal_deploy_cmd)}[/bold cyan]")
  166. subprocess.run(modal_deploy_cmd, check=True)
  167. console.print("✅ [bold green]'modal deploy' executed successfully.[/bold green]")
  168. except subprocess.CalledProcessError as e:
  169. console.print(f"❌ [bold red]An error occurred: {e}[/bold red]")
  170. except FileNotFoundError:
  171. console.print(
  172. "❌ [bold red]'modal' command not found. Please ensure Modal CLI is installed and in your PATH.[/bold red]"
  173. )
  174. @cli.command()
  175. def deploy():
  176. # Check for platform-specific files
  177. template = ""
  178. with open("embedchain.json", "r") as file:
  179. embedchain_config = json.load(file)
  180. template = embedchain_config["provider"]
  181. anonymous_telemetry.capture(
  182. event_name="ec_deploy", properties={"template_used": template}
  183. )
  184. if template == "fly.io":
  185. deploy_fly()
  186. elif template == "modal.com":
  187. deploy_modal()
  188. else:
  189. console.print("❌ [bold red]No recognized deployment platform found.[/bold red]")