|
| 1 | +"""CLI commands for weco observe. |
| 2 | +
|
| 3 | +All commands follow the fire-and-forget pattern: they print warnings to |
| 4 | +stderr on failure but always exit 0 so they never crash an agent's loop. |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import json |
| 9 | +import sys |
| 10 | +import warnings |
| 11 | + |
| 12 | +from weco.auth import handle_authentication |
| 13 | +from weco.observe import api |
| 14 | + |
| 15 | + |
| 16 | +def configure_observe_parser(observe_parser: argparse.ArgumentParser) -> None: |
| 17 | + """Configure the observe command parser and all its subcommands.""" |
| 18 | + subparsers = observe_parser.add_subparsers(dest="observe_command", help="Observe commands") |
| 19 | + |
| 20 | + # --- init --- |
| 21 | + init_parser = subparsers.add_parser("init", help="Initialize an external run for tracking") |
| 22 | + init_parser.add_argument("--name", type=str, default=None, help="Run name") |
| 23 | + init_parser.add_argument("--metric", type=str, required=True, help="Primary metric name (e.g. val_bpb)") |
| 24 | + init_parser.add_argument( |
| 25 | + "-g", |
| 26 | + "--goal", |
| 27 | + type=str, |
| 28 | + choices=["maximize", "max", "minimize", "min"], |
| 29 | + default="minimize", |
| 30 | + help="Specify 'maximize'/'max' or 'minimize'/'min' (default: minimize)", |
| 31 | + ) |
| 32 | + init_source_group = init_parser.add_mutually_exclusive_group(required=True) |
| 33 | + init_source_group.add_argument( |
| 34 | + "-s", "--source", type=str, help="Path to a single source code file to track (e.g. train.py)" |
| 35 | + ) |
| 36 | + init_source_group.add_argument( |
| 37 | + "--sources", nargs="+", type=str, help="Paths to multiple source code files to track (e.g. train.py prepare.py)" |
| 38 | + ) |
| 39 | + init_parser.add_argument( |
| 40 | + "-i", "--additional-instructions", type=str, default=None, help="Additional instructions for the run" |
| 41 | + ) |
| 42 | + |
| 43 | + # --- log --- |
| 44 | + log_parser = subparsers.add_parser("log", help="Log a step for an external run") |
| 45 | + log_parser.add_argument("--run-id", type=str, required=True, help="Run ID (from weco observe init)") |
| 46 | + log_parser.add_argument("--step", type=int, required=True, help="Step number") |
| 47 | + log_parser.add_argument( |
| 48 | + "--status", type=str, default="completed", choices=["completed", "failed"], help="Step status (default: completed)" |
| 49 | + ) |
| 50 | + log_parser.add_argument("--description", type=str, default=None, help="Description of what was tried") |
| 51 | + log_parser.add_argument("--metrics", type=str, default=None, help="Metrics as JSON (e.g. '{\"val_bpb\": 1.03}')") |
| 52 | + log_source_group = log_parser.add_mutually_exclusive_group() |
| 53 | + log_source_group.add_argument("-s", "--source", type=str, default=None, help="Single source code file to snapshot") |
| 54 | + log_source_group.add_argument( |
| 55 | + "--sources", nargs="+", type=str, default=None, help="Multiple source code files to snapshot" |
| 56 | + ) |
| 57 | + log_parser.add_argument("--parent-step", type=int, default=None, help="Parent step number for tree lineage") |
| 58 | + |
| 59 | + # --- complete/fail are no longer needed --- |
| 60 | + # External run lifecycle is managed by the dashboard, not the CLI. |
| 61 | + # Logging a step to a closed run will silently reopen it. |
| 62 | + |
| 63 | + |
| 64 | +def _read_code_files(paths: list[str]) -> dict[str, str]: |
| 65 | + """Read source code files from disk.""" |
| 66 | + source_code = {} |
| 67 | + for path in paths: |
| 68 | + try: |
| 69 | + with open(path) as f: |
| 70 | + source_code[path] = f.read() |
| 71 | + except FileNotFoundError: |
| 72 | + warnings.warn(f"weco observe: file not found: {path}", stacklevel=2) |
| 73 | + except Exception as e: |
| 74 | + warnings.warn(f"weco observe: error reading {path}: {e}", stacklevel=2) |
| 75 | + return source_code |
| 76 | + |
| 77 | + |
| 78 | +def execute_observe_command(args: argparse.Namespace) -> None: |
| 79 | + """Execute an observe subcommand. Always exits 0.""" |
| 80 | + if not args.observe_command: |
| 81 | + print("Usage: weco observe {init,log,complete,fail}", file=sys.stderr) |
| 82 | + sys.exit(0) |
| 83 | + |
| 84 | + # Authenticate |
| 85 | + try: |
| 86 | + _, auth_headers = handle_authentication(None) |
| 87 | + if not auth_headers: |
| 88 | + print("weco observe: not logged in. Run `weco login` first.", file=sys.stderr) |
| 89 | + sys.exit(0) |
| 90 | + except Exception as e: |
| 91 | + print(f"weco observe: authentication failed: {e}", file=sys.stderr) |
| 92 | + sys.exit(0) |
| 93 | + |
| 94 | + if args.observe_command == "init": |
| 95 | + _handle_init(args, auth_headers) |
| 96 | + elif args.observe_command == "log": |
| 97 | + _handle_log(args, auth_headers) |
| 98 | + |
| 99 | + |
| 100 | +def _handle_init(args: argparse.Namespace, auth_headers: dict) -> None: |
| 101 | + """Handle `weco observe init`.""" |
| 102 | + source_arg = args.sources if args.sources is not None else [args.source] |
| 103 | + source_code = _read_code_files(source_arg) |
| 104 | + if not source_code: |
| 105 | + print("weco observe: no source files could be read", file=sys.stderr) |
| 106 | + sys.exit(0) |
| 107 | + |
| 108 | + maximize = args.goal in ("maximize", "max") |
| 109 | + |
| 110 | + result = api.create_run( |
| 111 | + source_code=source_code, |
| 112 | + metric_name=args.metric, |
| 113 | + maximize=maximize, |
| 114 | + name=args.name, |
| 115 | + additional_instructions=args.additional_instructions, |
| 116 | + auth_headers=auth_headers, |
| 117 | + ) |
| 118 | + |
| 119 | + if result and result.get("run_id"): |
| 120 | + # Print only the run_id to stdout so it can be captured by $(...) |
| 121 | + print(result["run_id"]) |
| 122 | + else: |
| 123 | + print("weco observe: failed to create run", file=sys.stderr) |
| 124 | + |
| 125 | + |
| 126 | +def _handle_log(args: argparse.Namespace, auth_headers: dict) -> None: |
| 127 | + """Handle `weco observe log`.""" |
| 128 | + # Parse metrics JSON |
| 129 | + metrics = {} |
| 130 | + if args.metrics: |
| 131 | + try: |
| 132 | + metrics = json.loads(args.metrics) |
| 133 | + except json.JSONDecodeError as e: |
| 134 | + print(f"weco observe: invalid metrics JSON: {e}", file=sys.stderr) |
| 135 | + sys.exit(0) |
| 136 | + |
| 137 | + # Read source files if specified |
| 138 | + code = None |
| 139 | + source_arg = args.sources if args.sources is not None else ([args.source] if args.source else None) |
| 140 | + if source_arg: |
| 141 | + code = _read_code_files(source_arg) |
| 142 | + |
| 143 | + api.log_step( |
| 144 | + run_id=args.run_id, |
| 145 | + step=args.step, |
| 146 | + status=args.status, |
| 147 | + description=args.description, |
| 148 | + metrics=metrics, |
| 149 | + code=code, |
| 150 | + parent_step=args.parent_step, |
| 151 | + auth_headers=auth_headers, |
| 152 | + ) |
0 commit comments