Elffuss BraidHub

kikocis/llama-stack public

7b7b9b1ba243 · 5.3 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
8import json
9from pathlib import Path
10
11import yaml
12
13from llama_stack.cli.subcommand import Subcommand
14from llama_stack.distribution.utils.config_dirs import BUILDS_BASE_DIR
15
16from llama_stack.distribution.utils.exec import run_with_pty
17from llama_stack.distribution.datatypes import * # noqa: F403
18import os
19
20
21class StackConfigure(Subcommand):
22 """Llama cli for configuring llama toolchain configs"""
23
24 def __init__(self, subparsers: argparse._SubParsersAction):
25 super().__init__()
26 self.parser = subparsers.add_parser(
27 "configure",
28 prog="llama stack configure",
29 description="configure a llama stack distribution",
30 formatter_class=argparse.RawTextHelpFormatter,
31 )
32 self._add_arguments()
33 self.parser.set_defaults(func=self._run_stack_configure_cmd)
34
35 def _add_arguments(self):
36 self.parser.add_argument(
37 "config",
38 type=str,
39 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. ",
40 )
41
42 self.parser.add_argument(
43 "--output-dir",
44 type=str,
45 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",
46 )
47
48 def _run_stack_configure_cmd(self, args: argparse.Namespace) -> None:
49 import pkg_resources
50
51 from llama_stack.distribution.build import ImageType
52 from termcolor import cprint
53
54 docker_image = None
55 conda_dir = Path(os.getenv("CONDA_PREFIX")).parent / f"llamastack-{args.config}"
56 build_config_file = Path(conda_dir) / f"{args.config}-build.yaml"
57
58 if not build_config_file.exists():
59 cprint(
60 f"Could not find {build_config_file}. Trying docker image name instead...",
61 color="green",
62 )
63 docker_image = args.config
64
65 builds_dir = BUILDS_BASE_DIR / ImageType.docker.value
66 if args.output_dir:
67 builds_dir = Path(output_dir)
68 os.makedirs(builds_dir, exist_ok=True)
69
70 script = pkg_resources.resource_filename(
71 "llama_stack", "distribution/configure_container.sh"
72 )
73 script_args = [script, docker_image, str(builds_dir)]
74
75 return_code = run_with_pty(script_args)
76
77 # we have regenerated the build config file with script, now check if it exists
78 if return_code != 0:
79 self.parser.error(
80 f"Can not find {build_config_file}. Please run llama stack build first or check if docker image exists"
81 )
82
83 build_name = docker_image.removeprefix("llamastack-")
84 saved_file = str(builds_dir / f"{build_name}-run.yaml")
85 cprint(
86 f"YAML configuration has been written to {saved_file}. You can now run `llama stack run {saved_file}`",
87 color="green",
88 )
89 return
90
91 with open(build_config_file, "r") as f:
92 build_config = BuildConfig(**yaml.safe_load(f))
93
94 self._configure_llama_distribution(build_config, args.output_dir)
95
96 def _configure_llama_distribution(
97 self,
98 build_config: BuildConfig,
99 output_dir: Optional[str] = None,
100 ):
101 from llama_stack.distribution.configure import configure_api_providers
102 from llama_stack.distribution.utils.serialize import EnumEncoder
103 from termcolor import cprint
104
105 builds_dir = BUILDS_BASE_DIR / build_config.image_type
106 if output_dir:
107 builds_dir = Path(output_dir)
108 os.makedirs(builds_dir, exist_ok=True)
109 image_name = build_config.name.replace("::", "-")
110 run_config_file = builds_dir / f"{image_name}-run.yaml"
111
112 if run_config_file.exists():
113 cprint(
114 f"Configuration already exists at `{str(run_config_file)}`. Will overwrite...",
115 "yellow",
116 attrs=["bold"],
117 )
118 config = StackRunConfig(**yaml.safe_load(run_config_file.read_text()))
119 else:
120 config = StackRunConfig(
121 built_at=datetime.now(),
122 image_name=image_name,
123 apis_to_serve=[],
124 provider_map={},
125 )
126
127 config = configure_api_providers(config, build_config.distribution_spec)
128
129 config.docker_image = (
130 image_name if build_config.image_type == "docker" else None
131 )
132 config.conda_env = image_name if build_config.image_type == "conda" else None
133
134 with open(run_config_file, "w") as f:
135 to_write = json.loads(json.dumps(config.dict(), cls=EnumEncoder))
136 f.write(yaml.dump(to_write, sort_keys=False))
137
138 cprint(
139 f"> YAML configuration has been written to {run_config_file}.",
140 color="blue",
141 )
142
143 cprint(
144 f"You can now run `llama stack run {image_name} --port PORT` or `llama stack run {run_config_file} --port PORT`",
145 color="green",
146 )