Elffuss BraidHub

kikocis/llama-stack public

22356ba7a140 · 9.2 KiBRawPermalink
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
7import argparse
8
9from llama_stack.cli.subcommand import Subcommand
10from llama_stack.distribution.datatypes import * # noqa: F403
11import os
12from functools import lru_cache
13from pathlib import Path
14
15TEMPLATES_PATH = (
16 Path(os.path.relpath(__file__)).parent.parent.parent / "distribution" / "templates"
17)
18
19
20@lru_cache()
21def 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
33class 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.relpath(__file__)).parent.parent.parent
99 build_dir = (
100 llama_stack_path / "configs/distributions" / build_config.image_type
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 build_image(build_config, build_file_path)
116
117 cprint(
118 f"Build spec configuration saved at {str(build_file_path)}",
119 color="blue",
120 )
121
122 configure_name = (
123 build_config.name
124 if build_config.image_type == "conda"
125 else (f"llamastack-{build_config.name}")
126 )
127 cprint(
128 f"You may now run `llama stack configure {configure_name}` or `llama stack configure {str(build_file_path)}`",
129 color="green",
130 )
131
132 def _run_template_list_cmd(self, args: argparse.Namespace) -> None:
133 import json
134
135 import yaml
136
137 from llama_stack.cli.table import print_table
138
139 # eventually, this should query a registry at llama.meta.com/llamastack/distributions
140 headers = [
141 "Template Name",
142 "Providers",
143 "Description",
144 ]
145
146 rows = []
147 for spec in available_templates_specs():
148 rows.append(
149 [
150 spec.name,
151 json.dumps(spec.distribution_spec.providers, indent=2),
152 spec.distribution_spec.description,
153 ]
154 )
155 print_table(
156 rows,
157 headers,
158 separate_rows=True,
159 )
160
161 def _run_stack_build_command(self, args: argparse.Namespace) -> None:
162 import yaml
163 from llama_stack.distribution.distribution import Api, api_providers
164 from llama_stack.distribution.utils.dynamic import instantiate_class_type
165 from prompt_toolkit import prompt
166 from prompt_toolkit.validation import Validator
167 from termcolor import cprint
168
169 if args.list_templates:
170 self._run_template_list_cmd(args)
171 return
172
173 if args.template:
174 if not args.name:
175 self.parser.error(
176 "You must specify a name for the build using --name when using a template"
177 )
178 return
179 build_path = TEMPLATES_PATH / f"{args.template}-build.yaml"
180 if not build_path.exists():
181 self.parser.error(
182 f"Could not find template {args.template}. Please run `llama stack build --list-templates` to check out the available templates"
183 )
184 return
185 with open(build_path, "r") as f:
186 build_config = BuildConfig(**yaml.safe_load(f))
187 build_config.name = args.name
188 build_config.image_type = args.image_type
189 self._run_stack_build_command_from_build_config(build_config)
190
191 return
192
193 if not args.config and not args.template:
194 name = prompt("> Enter a name for your Llama Stack (e.g. my-local-stack): ")
195 image_type = prompt(
196 "> Enter the image type you want your Llama Stack to be built as (docker or conda): ",
197 validator=Validator.from_callable(
198 lambda x: x in ["docker", "conda"],
199 error_message="Invalid image type, please enter conda or docker",
200 ),
201 default="conda",
202 )
203
204 cprint(
205 f"\n Llama Stack is composed of several APIs working together. Let's configure the providers (implementations) you want to use for these APIs.",
206 color="green",
207 )
208
209 providers = dict()
210 for api in Api:
211 all_providers = api_providers()
212 providers_for_api = all_providers[api]
213
214 api_provider = prompt(
215 "> Enter provider for the {} API: (default=meta-reference): ".format(
216 api.value
217 ),
218 validator=Validator.from_callable(
219 lambda x: x in providers_for_api,
220 error_message="Invalid provider, please enter one of the following: {}".format(
221 providers_for_api.keys()
222 ),
223 ),
224 default=(
225 "meta-reference"
226 if "meta-reference" in providers_for_api
227 else list(providers_for_api.keys())[0]
228 ),
229 )
230
231 providers[api.value] = api_provider
232
233 description = prompt(
234 "\n > (Optional) Enter a short description for your Llama Stack: ",
235 default="",
236 )
237
238 distribution_spec = DistributionSpec(
239 providers=providers,
240 description=description,
241 )
242
243 build_config = BuildConfig(
244 name=name, image_type=image_type, distribution_spec=distribution_spec
245 )
246 self._run_stack_build_command_from_build_config(build_config)
247 return
248
249 with open(args.config, "r") as f:
250 try:
251 build_config = BuildConfig(**yaml.safe_load(f))
252 except Exception as e:
253 self.parser.error(f"Could not parse config file {args.config}: {e}")
254 return
255 self._run_stack_build_command_from_build_config(build_config)