Elffuss BraidHub

kikocis/llama-stack public

7ef69e0d6d29 · 6.0 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.utils.config_dirs import BUILDS_BASE_DIR
11from llama_stack.distribution.datatypes import * # noqa: F403
12
13
14class 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 json
43 import os
44 from pathlib import Path
45
46 import pkg_resources
47
48 import yaml
49
50 from llama_stack.distribution.build import ImageType
51
52 from llama_stack.distribution.utils.exec import run_with_pty
53 from termcolor import cprint
54
55 docker_image = None
56
57 build_config_file = Path(args.config)
58
59 if build_config_file.exists():
60 with open(build_config_file, "r") as f:
61 build_config = BuildConfig(**yaml.safe_load(f))
62 self._configure_llama_distribution(build_config, args.output_dir)
63 return
64
65 # if we get here, we need to try to find the conda build config file
66 cprint(
67 f"Could not find {build_config_file}. Trying conda build name instead...",
68 color="green",
69 )
70 conda_dir = Path(os.getenv("CONDA_PREFIX")).parent / f"llamastack-{args.config}"
71 build_config_file = Path(conda_dir) / f"{args.config}-build.yaml"
72
73 if build_config_file.exists():
74 with open(build_config_file, "r") as f:
75 build_config = BuildConfig(**yaml.safe_load(f))
76
77 self._configure_llama_distribution(build_config, args.output_dir)
78 return
79
80 # if we get here, we need to try to find the docker image
81 cprint(
82 f"Could not find {build_config_file}. Trying docker image name instead...",
83 color="green",
84 )
85 docker_image = args.config
86 builds_dir = BUILDS_BASE_DIR / ImageType.docker.value
87 if args.output_dir:
88 builds_dir = Path(output_dir)
89 os.makedirs(builds_dir, exist_ok=True)
90
91 script = pkg_resources.resource_filename(
92 "llama_stack", "distribution/configure_container.sh"
93 )
94 script_args = [script, docker_image, str(builds_dir)]
95
96 return_code = run_with_pty(script_args)
97
98 # we have regenerated the build config file with script, now check if it exists
99 if return_code != 0:
100 self.parser.error(
101 f"Failed to configure container {docker_image} with return code {return_code}. Please run `llama stack build first`. "
102 )
103 return
104
105 build_name = docker_image.removeprefix("llamastack-")
106 saved_file = str(builds_dir / f"{build_name}-run.yaml")
107 cprint(
108 f"YAML configuration has been written to {saved_file}. You can now run `llama stack run {saved_file}`",
109 color="green",
110 )
111 return
112
113 def _configure_llama_distribution(
114 self,
115 build_config: BuildConfig,
116 output_dir: Optional[str] = None,
117 ):
118 import json
119 import os
120 from pathlib import Path
121
122 import yaml
123 from llama_stack.distribution.configure import configure_api_providers
124
125 from llama_stack.distribution.utils.exec import run_with_pty
126 from llama_stack.distribution.utils.serialize import EnumEncoder
127 from termcolor import cprint
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 provider_map={},
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` or `llama stack run {run_config_file} --port PORT`",
169 color="green",
170 )