| 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_toolchain.cli.subcommand import Subcommand |
| 10 | from llama_toolchain.core.datatypes import * # noqa: F403 |
| 11 | import yaml |
| 12 | |
| 13 | |
| 14 | def parse_api_provider_tuples( |
| 15 | tuples: str, parser: argparse.ArgumentParser |
| 16 | ) -> Dict[str, ProviderSpec]: |
| 17 | from llama_toolchain.core.distribution import api_providers |
| 18 | |
| 19 | all_providers = api_providers() |
| 20 | |
| 21 | deps = {} |
| 22 | for dep in tuples.split(","): |
| 23 | dep = dep.strip() |
| 24 | if not dep: |
| 25 | continue |
| 26 | api_str, provider = dep.split("=") |
| 27 | api = Api(api_str) |
| 28 | |
| 29 | provider = provider.strip() |
| 30 | if provider not in all_providers[api]: |
| 31 | parser.error(f"Provider `{provider}` is not available for API `{api}`") |
| 32 | return |
| 33 | deps[api] = all_providers[api][provider] |
| 34 | |
| 35 | return deps |
| 36 | |
| 37 | |
| 38 | class StackBuild(Subcommand): |
| 39 | def __init__(self, subparsers: argparse._SubParsersAction): |
| 40 | super().__init__() |
| 41 | self.parser = subparsers.add_parser( |
| 42 | "build", |
| 43 | prog="llama stack build", |
| 44 | description="Build a Llama stack container", |
| 45 | formatter_class=argparse.RawTextHelpFormatter, |
| 46 | ) |
| 47 | self._add_arguments() |
| 48 | self.parser.set_defaults(func=self._run_stack_build_command) |
| 49 | |
| 50 | def _add_arguments(self): |
| 51 | from llama_toolchain.core.distribution_registry import ( |
| 52 | available_distribution_specs, |
| 53 | ) |
| 54 | from llama_toolchain.core.package import ImageType |
| 55 | |
| 56 | allowed_ids = [d.distribution_type for d in available_distribution_specs()] |
| 57 | self.parser.add_argument( |
| 58 | "--config", |
| 59 | type=str, |
| 60 | help="Path to a config file to use for the build", |
| 61 | ) |
| 62 | |
| 63 | def _run_stack_build_command_from_build_config( |
| 64 | self, build_config: BuildConfig |
| 65 | ) -> None: |
| 66 | import json |
| 67 | import os |
| 68 | |
| 69 | from llama_toolchain.common.config_dirs import DISTRIBS_BASE_DIR |
| 70 | from llama_toolchain.common.serialize import EnumEncoder |
| 71 | from llama_toolchain.core.distribution_registry import resolve_distribution_spec |
| 72 | from llama_toolchain.core.package import ApiInput, build_package, ImageType |
| 73 | from termcolor import cprint |
| 74 | |
| 75 | api_inputs = [] |
| 76 | if build_config.distribution == "adhoc": |
| 77 | if not build_config.api_providers: |
| 78 | self.parser.error( |
| 79 | "You must specify API providers with (api=provider,...) for building an adhoc distribution" |
| 80 | ) |
| 81 | return |
| 82 | |
| 83 | parsed = parse_api_provider_tuples(build_config.api_providers, self.parser) |
| 84 | for api, provider_spec in parsed.items(): |
| 85 | for dep in provider_spec.api_dependencies: |
| 86 | if dep not in parsed: |
| 87 | self.parser.error( |
| 88 | f"API {api} needs dependency {dep} provided also" |
| 89 | ) |
| 90 | return |
| 91 | |
| 92 | api_inputs.append( |
| 93 | ApiInput( |
| 94 | api=api, |
| 95 | provider=provider_spec.provider_type, |
| 96 | ) |
| 97 | ) |
| 98 | docker_image = None |
| 99 | else: |
| 100 | if build_config.api_providers: |
| 101 | self.parser.error( |
| 102 | "You cannot specify API providers for pre-registered distributions" |
| 103 | ) |
| 104 | return |
| 105 | |
| 106 | dist = resolve_distribution_spec(build_config.distribution) |
| 107 | if dist is None: |
| 108 | self.parser.error( |
| 109 | f"Could not find distribution {build_config.distribution}" |
| 110 | ) |
| 111 | return |
| 112 | |
| 113 | for api, provider_type in dist.providers.items(): |
| 114 | api_inputs.append( |
| 115 | ApiInput( |
| 116 | api=api, |
| 117 | provider=provider_type, |
| 118 | ) |
| 119 | ) |
| 120 | docker_image = dist.docker_image |
| 121 | |
| 122 | build_package( |
| 123 | api_inputs, |
| 124 | image_type=ImageType(build_config.image_type), |
| 125 | name=build_config.name, |
| 126 | distribution_type=build_config.distribution, |
| 127 | docker_image=docker_image, |
| 128 | ) |
| 129 | |
| 130 | # save build.yaml spec for building same distribution again |
| 131 | build_dir = ( |
| 132 | DISTRIBS_BASE_DIR / build_config.distribution / build_config.image_type |
| 133 | ) |
| 134 | os.makedirs(build_dir, exist_ok=True) |
| 135 | build_file_path = build_dir / f"{build_config.name}-build.yaml" |
| 136 | |
| 137 | with open(build_file_path, "w") as f: |
| 138 | to_write = json.loads(json.dumps(build_config.dict(), cls=EnumEncoder)) |
| 139 | f.write(yaml.dump(to_write, sort_keys=False)) |
| 140 | |
| 141 | cprint( |
| 142 | f"Build spec configuration saved at {str(build_file_path)}", |
| 143 | color="green", |
| 144 | ) |
| 145 | |
| 146 | def _run_stack_build_command(self, args: argparse.Namespace) -> None: |
| 147 | from llama_toolchain.common.prompt_for_config import prompt_for_config |
| 148 | from llama_toolchain.core.dynamic import instantiate_class_type |
| 149 | |
| 150 | if args.config: |
| 151 | with open(args.config, "r") as f: |
| 152 | try: |
| 153 | build_config = BuildConfig(**yaml.safe_load(f)) |
| 154 | except Exception as e: |
| 155 | self.parser.error(f"Could not parse config file {args.config}: {e}") |
| 156 | return |
| 157 | self._run_stack_build_command_from_build_config(build_config) |
| 158 | return |
| 159 | |
| 160 | build_config = prompt_for_config(BuildConfig, None) |
| 161 | self._run_stack_build_command_from_build_config(build_config) |