Elffuss BraidHub

kikocis/llama-stack public

52f9a9a2a96d · 5.5 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 conda_dir = Path(os.getenv("CONDA_PREFIX")).parent / f"llamastack-{args.config}"
57 build_config_file = Path(conda_dir) / f"{args.config}-build.yaml"
58
59 if not build_config_file.exists():
60 cprint(
61 f"Could not find {build_config_file}. Trying docker image name instead...",
62 color="green",
63 )
64 docker_image = args.config
65
66 builds_dir = BUILDS_BASE_DIR / ImageType.docker.value
67 if args.output_dir:
68 builds_dir = Path(output_dir)
69 os.makedirs(builds_dir, exist_ok=True)
70
71 script = pkg_resources.resource_filename(
72 "llama_stack", "distribution/configure_container.sh"
73 )
74 script_args = [script, docker_image, str(builds_dir)]
75
76 return_code = run_with_pty(script_args)
77
78 # we have regenerated the build config file with script, now check if it exists
79 if return_code != 0:
80 self.parser.error(
81 f"Can not find {build_config_file}. Please run llama stack build first or check if docker image exists"
82 )
83
84 build_name = docker_image.removeprefix("llamastack-")
85 saved_file = str(builds_dir / f"{build_name}-run.yaml")
86 cprint(
87 f"YAML configuration has been written to {saved_file}. You can now run `llama stack run {saved_file}`",
88 color="green",
89 )
90 return
91
92 with open(build_config_file, "r") as f:
93 build_config = BuildConfig(**yaml.safe_load(f))
94
95 self._configure_llama_distribution(build_config, args.output_dir)
96
97 def _configure_llama_distribution(
98 self,
99 build_config: BuildConfig,
100 output_dir: Optional[str] = None,
101 ):
102 import json
103 import os
104 from pathlib import Path
105
106 import yaml
107 from llama_stack.distribution.configure import configure_api_providers
108
109 from llama_stack.distribution.utils.exec import run_with_pty
110 from llama_stack.distribution.utils.serialize import EnumEncoder
111 from termcolor import cprint
112
113 builds_dir = BUILDS_BASE_DIR / build_config.image_type
114 if output_dir:
115 builds_dir = Path(output_dir)
116 os.makedirs(builds_dir, exist_ok=True)
117 image_name = build_config.name.replace("::", "-")
118 run_config_file = builds_dir / f"{image_name}-run.yaml"
119
120 if run_config_file.exists():
121 cprint(
122 f"Configuration already exists at `{str(run_config_file)}`. Will overwrite...",
123 "yellow",
124 attrs=["bold"],
125 )
126 config = StackRunConfig(**yaml.safe_load(run_config_file.read_text()))
127 else:
128 config = StackRunConfig(
129 built_at=datetime.now(),
130 image_name=image_name,
131 apis_to_serve=[],
132 provider_map={},
133 )
134
135 config = configure_api_providers(config, build_config.distribution_spec)
136
137 config.docker_image = (
138 image_name if build_config.image_type == "docker" else None
139 )
140 config.conda_env = image_name if build_config.image_type == "conda" else None
141
142 with open(run_config_file, "w") as f:
143 to_write = json.loads(json.dumps(config.dict(), cls=EnumEncoder))
144 f.write(yaml.dump(to_write, sort_keys=False))
145
146 cprint(
147 f"> YAML configuration has been written to {run_config_file}.",
148 color="blue",
149 )
150
151 cprint(
152 f"You can now run `llama stack run {image_name} --port PORT` or `llama stack run {run_config_file} --port PORT`",
153 color="green",
154 )