| 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 | |
| 7 | import argparse |
| 8 | |
| 9 | from pathlib import Path |
| 10 | |
| 11 | import yaml |
| 12 | |
| 13 | from llama_stack.cli.subcommand import Subcommand |
| 14 | from llama_stack.distribution.datatypes import * # noqa: F403 |
| 15 | |
| 16 | |
| 17 | class StackRun(Subcommand): |
| 18 | def __init__(self, subparsers: argparse._SubParsersAction): |
| 19 | super().__init__() |
| 20 | self.parser = subparsers.add_parser( |
| 21 | "run", |
| 22 | prog="llama stack run", |
| 23 | description="""start the server for a Llama Stack Distribution. You should have already built (or downloaded) and configured the distribution.""", |
| 24 | formatter_class=argparse.RawTextHelpFormatter, |
| 25 | ) |
| 26 | self._add_arguments() |
| 27 | self.parser.set_defaults(func=self._run_stack_run_cmd) |
| 28 | |
| 29 | def _add_arguments(self): |
| 30 | self.parser.add_argument( |
| 31 | "config", |
| 32 | type=str, |
| 33 | help="Path to config file to use for the run", |
| 34 | ) |
| 35 | self.parser.add_argument( |
| 36 | "--port", |
| 37 | type=int, |
| 38 | help="Port to run the server on. Defaults to 5000", |
| 39 | default=5000, |
| 40 | ) |
| 41 | self.parser.add_argument( |
| 42 | "--disable-ipv6", |
| 43 | action="store_true", |
| 44 | help="Disable IPv6 support", |
| 45 | default=False, |
| 46 | ) |
| 47 | |
| 48 | def _run_stack_run_cmd(self, args: argparse.Namespace) -> None: |
| 49 | import pkg_resources |
| 50 | |
| 51 | from llama_stack.distribution.utils.exec import run_with_pty |
| 52 | |
| 53 | if not args.config: |
| 54 | self.parser.error("Must specify a config file to run") |
| 55 | return |
| 56 | |
| 57 | path = args.config |
| 58 | config_file = Path(path) |
| 59 | |
| 60 | if not config_file.exists(): |
| 61 | self.parser.error( |
| 62 | f"File {str(config_file)} does not exist. Did you run `llama stack build`?" |
| 63 | ) |
| 64 | return |
| 65 | |
| 66 | with open(config_file, "r") as f: |
| 67 | config = StackRunConfig(**yaml.safe_load(f)) |
| 68 | |
| 69 | if config.docker_image: |
| 70 | script = pkg_resources.resource_filename( |
| 71 | "llama_stack", |
| 72 | "distribution/start_container.sh", |
| 73 | ) |
| 74 | run_args = [script, config.docker_image] |
| 75 | else: |
| 76 | script = pkg_resources.resource_filename( |
| 77 | "llama_stack", |
| 78 | "distribution/start_conda_env.sh", |
| 79 | ) |
| 80 | run_args = [ |
| 81 | script, |
| 82 | config.conda_env, |
| 83 | ] |
| 84 | |
| 85 | run_args.extend([str(config_file), str(args.port)]) |
| 86 | if args.disable_ipv6: |
| 87 | run_args.append("--disable-ipv6") |
| 88 | |
| 89 | run_with_pty(run_args) |