| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import argparse |
| 8 | |
| 9 | from llama_stack.cli.subcommand import Subcommand |
| 10 | from llama_stack.distribution.utils.config_dirs import BUILDS_BASE_DIR |
| 11 | from llama_stack.distribution.datatypes import * # noqa: F403 |
| 12 | |
| 13 | |
| 14 | class StackConfigure(Subcommand): |
| 15 | """Llama cli for configuring llama toolchain configs""" |
| 16 | |
| 17 | def __init__(self, subparsers: argparse._SubParsersAction): |
| 18 | super().__init__() |
| 19 | self.parser = subparsers.add_parser( |
| 20 | "configure", |
| 21 | prog="llama stack configure", |
| 22 | description="configure a llama stack distribution", |
| 23 | formatter_class=argparse.RawTextHelpFormatter, |
| 24 | ) |
| 25 | self._add_arguments() |
| 26 | self.parser.set_defaults(func=self._run_stack_configure_cmd) |
| 27 | |
| 28 | def _add_arguments(self): |
| 29 | self.parser.add_argument( |
| 30 | "config", |
| 31 | type=str, |
| 32 | help="Path to the build config file (e.g. ~/.llama/builds/<image_type>/<name>-build.yaml). For docker, this could also be the name of the docker image. ", |
| 33 | ) |
| 34 | |
| 35 | self.parser.add_argument( |
| 36 | "--output-dir", |
| 37 | type=str, |
| 38 | help="Path to the output directory to store generated run.yaml config file. If not specified, will use ~/.llama/build/<image_type>/<name>-run.yaml", |
| 39 | ) |
| 40 | |
| 41 | def _run_stack_configure_cmd(self, args: argparse.Namespace) -> None: |
| 42 | import os |
| 43 | from pathlib import Path |
| 44 | |
| 45 | import pkg_resources |
| 46 | |
| 47 | import yaml |
| 48 | from termcolor import cprint |
| 49 | |
| 50 | from llama_stack.distribution.build import ImageType |
| 51 | from llama_stack.distribution.utils.exec import run_with_pty |
| 52 | |
| 53 | docker_image = None |
| 54 | |
| 55 | build_config_file = Path(args.config) |
| 56 | |
| 57 | if build_config_file.exists(): |
| 58 | with open(build_config_file, "r") as f: |
| 59 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 60 | self._configure_llama_distribution(build_config, args.output_dir) |
| 61 | return |
| 62 | |
| 63 | # if we get here, we need to try to find the conda build config file |
| 64 | cprint( |
| 65 | f"Could not find {build_config_file}. Trying conda build name instead...", |
| 66 | color="green", |
| 67 | ) |
| 68 | if os.getenv("CONDA_PREFIX"): |
| 69 | conda_dir = ( |
| 70 | Path(os.getenv("CONDA_PREFIX")).parent / f"llamastack-{args.config}" |
| 71 | ) |
| 72 | build_config_file = Path(conda_dir) / f"{args.config}-build.yaml" |
| 73 | |
| 74 | if build_config_file.exists(): |
| 75 | with open(build_config_file, "r") as f: |
| 76 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 77 | |
| 78 | self._configure_llama_distribution(build_config, args.output_dir) |
| 79 | return |
| 80 | |
| 81 | # if we get here, we need to try to find the docker image |
| 82 | cprint( |
| 83 | f"Could not find {build_config_file}. Trying docker image name instead...", |
| 84 | color="green", |
| 85 | ) |
| 86 | docker_image = args.config |
| 87 | builds_dir = BUILDS_BASE_DIR / ImageType.docker.value |
| 88 | if args.output_dir: |
| 89 | builds_dir = Path(output_dir) |
| 90 | os.makedirs(builds_dir, exist_ok=True) |
| 91 | |
| 92 | script = pkg_resources.resource_filename( |
| 93 | "llama_stack", "distribution/configure_container.sh" |
| 94 | ) |
| 95 | script_args = [script, docker_image, str(builds_dir)] |
| 96 | |
| 97 | return_code = run_with_pty(script_args) |
| 98 | |
| 99 | # we have regenerated the build config file with script, now check if it exists |
| 100 | if return_code != 0: |
| 101 | self.parser.error( |
| 102 | f"Failed to configure container {docker_image} with return code {return_code}. Please run `llama stack build first`. " |
| 103 | ) |
| 104 | return |
| 105 | |
| 106 | build_name = docker_image.removeprefix("llamastack-") |
| 107 | saved_file = str(builds_dir / f"{build_name}-run.yaml") |
| 108 | cprint( |
| 109 | f"YAML configuration has been written to {saved_file}. You can now run `llama stack run {saved_file}`", |
| 110 | color="green", |
| 111 | ) |
| 112 | return |
| 113 | |
| 114 | def _configure_llama_distribution( |
| 115 | self, |
| 116 | build_config: BuildConfig, |
| 117 | output_dir: Optional[str] = None, |
| 118 | ): |
| 119 | import json |
| 120 | import os |
| 121 | from pathlib import Path |
| 122 | |
| 123 | import yaml |
| 124 | from termcolor import cprint |
| 125 | |
| 126 | from llama_stack.distribution.configure import configure_api_providers |
| 127 | from llama_stack.distribution.utils.serialize import EnumEncoder |
| 128 | |
| 129 | builds_dir = BUILDS_BASE_DIR / build_config.image_type |
| 130 | if output_dir: |
| 131 | builds_dir = Path(output_dir) |
| 132 | os.makedirs(builds_dir, exist_ok=True) |
| 133 | image_name = build_config.name.replace("::", "-") |
| 134 | run_config_file = builds_dir / f"{image_name}-run.yaml" |
| 135 | |
| 136 | if run_config_file.exists(): |
| 137 | cprint( |
| 138 | f"Configuration already exists at `{str(run_config_file)}`. Will overwrite...", |
| 139 | "yellow", |
| 140 | attrs=["bold"], |
| 141 | ) |
| 142 | config = StackRunConfig(**yaml.safe_load(run_config_file.read_text())) |
| 143 | else: |
| 144 | config = StackRunConfig( |
| 145 | built_at=datetime.now(), |
| 146 | image_name=image_name, |
| 147 | apis_to_serve=[], |
| 148 | api_providers={}, |
| 149 | ) |
| 150 | |
| 151 | config = configure_api_providers(config, build_config.distribution_spec) |
| 152 | |
| 153 | config.docker_image = ( |
| 154 | image_name if build_config.image_type == "docker" else None |
| 155 | ) |
| 156 | config.conda_env = image_name if build_config.image_type == "conda" else None |
| 157 | |
| 158 | with open(run_config_file, "w") as f: |
| 159 | to_write = json.loads(json.dumps(config.dict(), cls=EnumEncoder)) |
| 160 | f.write(yaml.dump(to_write, sort_keys=False)) |
| 161 | |
| 162 | cprint( |
| 163 | f"> YAML configuration has been written to `{run_config_file}`.", |
| 164 | color="blue", |
| 165 | ) |
| 166 | |
| 167 | cprint( |
| 168 | f"You can now run `llama stack run {image_name} --port PORT`", |
| 169 | color="green", |
| 170 | ) |