| 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.datatypes import * # noqa: F403 |
| 11 | import os |
| 12 | from functools import lru_cache |
| 13 | from pathlib import Path |
| 14 | |
| 15 | TEMPLATES_PATH = ( |
| 16 | Path(os.path.relpath(__file__)).parent.parent.parent / "distribution" / "templates" |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | @lru_cache() |
| 21 | def available_templates_specs() -> List[BuildConfig]: |
| 22 | import yaml |
| 23 | |
| 24 | template_specs = [] |
| 25 | for p in TEMPLATES_PATH.rglob("*.yaml"): |
| 26 | with open(p, "r") as f: |
| 27 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 28 | template_specs.append(build_config) |
| 29 | |
| 30 | return template_specs |
| 31 | |
| 32 | |
| 33 | class StackBuild(Subcommand): |
| 34 | def __init__(self, subparsers: argparse._SubParsersAction): |
| 35 | super().__init__() |
| 36 | self.parser = subparsers.add_parser( |
| 37 | "build", |
| 38 | prog="llama stack build", |
| 39 | description="Build a Llama stack container", |
| 40 | formatter_class=argparse.RawTextHelpFormatter, |
| 41 | ) |
| 42 | self._add_arguments() |
| 43 | self.parser.set_defaults(func=self._run_stack_build_command) |
| 44 | |
| 45 | def _add_arguments(self): |
| 46 | self.parser.add_argument( |
| 47 | "--config", |
| 48 | type=str, |
| 49 | default=None, |
| 50 | help="Path to a config file to use for the build. You can find example configs in llama_stack/distribution/example_configs. If this argument is not provided, you will be prompted to enter information interactively", |
| 51 | ) |
| 52 | |
| 53 | self.parser.add_argument( |
| 54 | "--template", |
| 55 | type=str, |
| 56 | default=None, |
| 57 | help="Name of the example template config to use for build. You may use `llama stack build --list-templates` to check out the available templates", |
| 58 | ) |
| 59 | |
| 60 | self.parser.add_argument( |
| 61 | "--list-templates", |
| 62 | type=bool, |
| 63 | default=False, |
| 64 | action=argparse.BooleanOptionalAction, |
| 65 | help="Show the available templates for building a Llama Stack distribution", |
| 66 | ) |
| 67 | |
| 68 | self.parser.add_argument( |
| 69 | "--name", |
| 70 | type=str, |
| 71 | help="Name of the Llama Stack build to override from template config. This name will be used as paths to store configuration files, build conda environments/docker images. If not specified, will use the name from the template config. ", |
| 72 | ) |
| 73 | |
| 74 | self.parser.add_argument( |
| 75 | "--image-type", |
| 76 | type=str, |
| 77 | help="Image Type to use for the build. This can be either conda or docker. If not specified, will use conda by default", |
| 78 | default="conda", |
| 79 | ) |
| 80 | |
| 81 | def _run_stack_build_command_from_build_config( |
| 82 | self, build_config: BuildConfig |
| 83 | ) -> None: |
| 84 | import json |
| 85 | import os |
| 86 | |
| 87 | import yaml |
| 88 | |
| 89 | from llama_stack.distribution.build import ApiInput, build_image, ImageType |
| 90 | |
| 91 | from llama_stack.distribution.utils.config_dirs import DISTRIBS_BASE_DIR |
| 92 | from llama_stack.distribution.utils.serialize import EnumEncoder |
| 93 | from termcolor import cprint |
| 94 | |
| 95 | # save build.yaml spec for building same distribution again |
| 96 | if build_config.image_type == ImageType.docker.value: |
| 97 | # docker needs build file to be in the llama-stack repo dir to be able to copy over to the image |
| 98 | llama_stack_path = Path(os.path.abspath(__file__)).parent.parent.parent.parent |
| 99 | build_dir = ( |
| 100 | llama_stack_path / "tmp/configs/" |
| 101 | ) |
| 102 | else: |
| 103 | build_dir = ( |
| 104 | Path(os.getenv("CONDA_PREFIX")).parent |
| 105 | / f"llamastack-{build_config.name}" |
| 106 | ) |
| 107 | |
| 108 | os.makedirs(build_dir, exist_ok=True) |
| 109 | build_file_path = build_dir / f"{build_config.name}-build.yaml" |
| 110 | |
| 111 | with open(build_file_path, "w") as f: |
| 112 | to_write = json.loads(json.dumps(build_config.dict(), cls=EnumEncoder)) |
| 113 | f.write(yaml.dump(to_write, sort_keys=False)) |
| 114 | |
| 115 | return_code = build_image(build_config, build_file_path) |
| 116 | if return_code != 0: |
| 117 | return |
| 118 | |
| 119 | cprint( |
| 120 | f"Build spec configuration saved at {str(build_file_path)}", |
| 121 | color="blue", |
| 122 | ) |
| 123 | |
| 124 | configure_name = ( |
| 125 | build_config.name |
| 126 | if build_config.image_type == "conda" |
| 127 | else (f"llamastack-{build_config.name}") |
| 128 | ) |
| 129 | cprint( |
| 130 | f"You can now run `llama stack configure {configure_name}`", |
| 131 | color="green", |
| 132 | ) |
| 133 | |
| 134 | def _run_template_list_cmd(self, args: argparse.Namespace) -> None: |
| 135 | import json |
| 136 | |
| 137 | import yaml |
| 138 | |
| 139 | from llama_stack.cli.table import print_table |
| 140 | |
| 141 | # eventually, this should query a registry at llama.meta.com/llamastack/distributions |
| 142 | headers = [ |
| 143 | "Template Name", |
| 144 | "Providers", |
| 145 | "Description", |
| 146 | ] |
| 147 | |
| 148 | rows = [] |
| 149 | for spec in available_templates_specs(): |
| 150 | rows.append( |
| 151 | [ |
| 152 | spec.name, |
| 153 | json.dumps(spec.distribution_spec.providers, indent=2), |
| 154 | spec.distribution_spec.description, |
| 155 | ] |
| 156 | ) |
| 157 | print_table( |
| 158 | rows, |
| 159 | headers, |
| 160 | separate_rows=True, |
| 161 | ) |
| 162 | |
| 163 | def _run_stack_build_command(self, args: argparse.Namespace) -> None: |
| 164 | import yaml |
| 165 | from llama_stack.distribution.distribution import ( |
| 166 | Api, |
| 167 | api_providers, |
| 168 | builtin_automatically_routed_apis, |
| 169 | ) |
| 170 | from llama_stack.distribution.utils.dynamic import instantiate_class_type |
| 171 | from prompt_toolkit import prompt |
| 172 | from prompt_toolkit.validation import Validator |
| 173 | from termcolor import cprint |
| 174 | |
| 175 | if args.list_templates: |
| 176 | self._run_template_list_cmd(args) |
| 177 | return |
| 178 | |
| 179 | if args.template: |
| 180 | if not args.name: |
| 181 | self.parser.error( |
| 182 | "You must specify a name for the build using --name when using a template" |
| 183 | ) |
| 184 | return |
| 185 | build_path = TEMPLATES_PATH / f"{args.template}-build.yaml" |
| 186 | if not build_path.exists(): |
| 187 | self.parser.error( |
| 188 | f"Could not find template {args.template}. Please run `llama stack build --list-templates` to check out the available templates" |
| 189 | ) |
| 190 | return |
| 191 | with open(build_path, "r") as f: |
| 192 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 193 | build_config.name = args.name |
| 194 | build_config.image_type = args.image_type |
| 195 | self._run_stack_build_command_from_build_config(build_config) |
| 196 | |
| 197 | return |
| 198 | |
| 199 | if not args.config and not args.template: |
| 200 | if not args.name: |
| 201 | name = prompt( |
| 202 | "> Enter a name for your Llama Stack (e.g. my-local-stack): " |
| 203 | ) |
| 204 | else: |
| 205 | name = args.name |
| 206 | |
| 207 | image_type = prompt( |
| 208 | "> Enter the image type you want your Llama Stack to be built as (docker or conda): ", |
| 209 | validator=Validator.from_callable( |
| 210 | lambda x: x in ["docker", "conda"], |
| 211 | error_message="Invalid image type, please enter conda or docker", |
| 212 | ), |
| 213 | default="conda", |
| 214 | ) |
| 215 | |
| 216 | cprint( |
| 217 | f"\n Llama Stack is composed of several APIs working together. Let's configure the providers (implementations) you want to use for these APIs.", |
| 218 | color="green", |
| 219 | ) |
| 220 | |
| 221 | providers = dict() |
| 222 | all_providers = api_providers() |
| 223 | routing_table_apis = set( |
| 224 | x.routing_table_api for x in builtin_automatically_routed_apis() |
| 225 | ) |
| 226 | |
| 227 | for api in Api: |
| 228 | if api in routing_table_apis: |
| 229 | continue |
| 230 | |
| 231 | providers_for_api = all_providers[api] |
| 232 | |
| 233 | api_provider = prompt( |
| 234 | "> Enter provider for the {} API: (default=meta-reference): ".format( |
| 235 | api.value |
| 236 | ), |
| 237 | validator=Validator.from_callable( |
| 238 | lambda x: x in providers_for_api, |
| 239 | error_message="Invalid provider, please enter one of the following: {}".format( |
| 240 | list(providers_for_api.keys()) |
| 241 | ), |
| 242 | ), |
| 243 | default=( |
| 244 | "meta-reference" |
| 245 | if "meta-reference" in providers_for_api |
| 246 | else list(providers_for_api.keys())[0] |
| 247 | ), |
| 248 | ) |
| 249 | |
| 250 | providers[api.value] = api_provider |
| 251 | |
| 252 | description = prompt( |
| 253 | "\n > (Optional) Enter a short description for your Llama Stack: ", |
| 254 | default="", |
| 255 | ) |
| 256 | |
| 257 | distribution_spec = DistributionSpec( |
| 258 | providers=providers, |
| 259 | description=description, |
| 260 | ) |
| 261 | |
| 262 | build_config = BuildConfig( |
| 263 | name=name, image_type=image_type, distribution_spec=distribution_spec |
| 264 | ) |
| 265 | self._run_stack_build_command_from_build_config(build_config) |
| 266 | return |
| 267 | |
| 268 | with open(args.config, "r") as f: |
| 269 | try: |
| 270 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 271 | except Exception as e: |
| 272 | self.parser.error(f"Could not parse config file {args.config}: {e}") |
| 273 | return |
| 274 | self._run_stack_build_command_from_build_config(build_config) |