Elffuss BraidHub

kikocis/llama-stack public

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