Elffuss BraidHub

kikocis/llama-stack public

7e907e713048 · 4.9 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_stack.cli.subcommand import Subcommand
17from llama_stack.distribution.utils.config_dirs import BUILDS_BASE_DIR
18
19from llama_stack.distribution.utils.exec import run_with_pty
20from llama_stack.distribution.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_stack.distribution.build 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_stack", "distribution/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_stack.distribution.configure import configure_api_providers
99 from llama_stack.distribution.utils.serialize import EnumEncoder
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 if run_config_file.exists():
109 cprint(
110 f"Configuration already exists at `{str(run_config_file)}`. Will overwrite...",
111 "yellow",
112 attrs=["bold"],
113 )
114 config = StackRunConfig(**yaml.safe_load(run_config_file.read_text()))
115 else:
116 config = StackRunConfig(
117 built_at=datetime.now(),
118 image_name=image_name,
119 apis_to_serve=[],
120 provider_map={},
121 )
122
123 config = configure_api_providers(config, build_config.distribution_spec)
124
125 config.docker_image = (
126 image_name if build_config.image_type == "docker" else None
127 )
128 config.conda_env = image_name if build_config.image_type == "conda" else None
129
130 with open(run_config_file, "w") as f:
131 to_write = json.loads(json.dumps(config.dict(), cls=EnumEncoder))
132 f.write(yaml.dump(to_write, sort_keys=False))
133
134 cprint(
135 f"> YAML configuration has been written to {run_config_file}",
136 color="blue",
137 )