Elffuss BraidHub

kikocis/llama-stack public

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