​call_me_maybe /
src / cli.py
52 commits
13-08-2026
142 lines 4.5 kB
  1"""The command line: parse the arguments, run everything, report failures.
  2
  3The mandated invocation is:
  4
  5    uv run python -m src [--functions_definition <file>] [--input <file>] [--output <file>]
  6
  7main catches everything, because a traceback on the terminal counts as a
  8program that does not work.
  9"""
 10
 11import argparse
 12import sys
 13from pathlib import Path
 14from typing import Optional, Sequence
 15
 16from pydantic import BaseModel, ConfigDict, Field
 17
 18from .io_utils import InputError, OutputError, load_function_definitions, load_prompts, write_results
 19from .pipeline import DEFAULT_MODEL, PipelineError, build_pipeline
 20
 21DEFAULT_FUNCTIONS_DEFINITION = Path("data/input/functions_definition.json")
 22DEFAULT_INPUT = Path("data/input/function_calling_tests.json")
 23DEFAULT_OUTPUT = Path("data/output/function_calling_results.json")
 24
 25
 26class RunConfig(BaseModel):
 27    """Everything one run needs to know.
 28
 29    Attributes:
 30        functions_definition: The file describing the callable functions.
 31        input_path: The file holding the prompts.
 32        output_path: The file to write the calls to.
 33        model_name: The model to drive.
 34        verbose: Whether to report each answer on stderr.
 35        trace: Whether to report every step of every generation on stderr.
 36    """
 37
 38    model_config = ConfigDict(extra="forbid", frozen=True, protected_namespaces=())
 39
 40    functions_definition: Path = Field(default=DEFAULT_FUNCTIONS_DEFINITION)
 41    input_path: Path = Field(default=DEFAULT_INPUT)
 42    output_path: Path = Field(default=DEFAULT_OUTPUT)
 43    model_name: str = Field(default=DEFAULT_MODEL, min_length=1)
 44    verbose: bool = False
 45    trace: bool = False
 46
 47
 48def parse_args(argv: Optional[Sequence[str]] = None) -> RunConfig:
 49    """Read the command line.
 50
 51    Args:
 52        argv: The arguments to parse, or None for the real command line.
 53
 54    Returns:
 55        The configuration for this run.
 56    """
 57    parser = argparse.ArgumentParser(
 58        prog="python -m src",
 59        description="Turn natural-language prompts into JSON function calls.",
 60    )
 61    parser.add_argument(
 62        "--functions_definition",
 63        type=Path,
 64        default=DEFAULT_FUNCTIONS_DEFINITION,
 65        metavar="<file>",
 66        help=f"function definitions file (default: {DEFAULT_FUNCTIONS_DEFINITION})",
 67    )
 68    parser.add_argument(
 69        "--input",
 70        dest="input_path",
 71        type=Path,
 72        default=DEFAULT_INPUT,
 73        metavar="<file>",
 74        help=f"prompts file (default: {DEFAULT_INPUT})",
 75    )
 76    parser.add_argument(
 77        "--output",
 78        dest="output_path",
 79        type=Path,
 80        default=DEFAULT_OUTPUT,
 81        metavar="<file>",
 82        help=f"results file (default: {DEFAULT_OUTPUT})",
 83    )
 84    parser.add_argument(
 85        "--model",
 86        dest="model_name",
 87        type=str,
 88        default=DEFAULT_MODEL,
 89        metavar="<name>",
 90        help=f"model to drive (default: {DEFAULT_MODEL})",
 91    )
 92    parser.add_argument(
 93        "-v",
 94        "--verbose",
 95        action="store_true",
 96        help="report each answer on stderr",
 97    )
 98    parser.add_argument(
 99        "--trace",
100        action="store_true",
101        help="report every step of every generation on stderr",
102    )
103    return RunConfig.model_validate(vars(parser.parse_args(argv)))
104
105
106def main(argv: Optional[Sequence[str]] = None) -> int:
107    """Read the inputs, answer every prompt, write the results.
108
109    Args:
110        argv: The arguments to parse, or None for the real command line.
111
112    Returns:
113        Zero on success, one on failure.
114    """
115    try:
116        config = parse_args(argv)
117        definitions = load_function_definitions(config.functions_definition)
118        prompts = load_prompts(config.input_path)
119        pipeline = build_pipeline(definitions, config.model_name, config.verbose, config.trace)
120        write_results(config.output_path, pipeline.run(prompts))
121    except (InputError, OutputError, PipelineError) as error:
122        return _fail(str(error))
123    except KeyboardInterrupt:
124        return _fail("interrupted")
125    except Exception as error:
126        return _fail(f"unexpected failure: {type(error).__name__}: {error}")
127
128    print(f"wrote {config.output_path}")
129    return 0
130
131
132def _fail(message: str) -> int:
133    """Report a fatal problem on stderr.
134
135    Args:
136        message: What went wrong.
137
138    Returns:
139        The exit status to end the program with.
140    """
141    print(f"error: {message}", file=sys.stderr)
142    return 1