"""CLI entry points for guac-coder.""" import argparse import json import logging import os import sys from guac_coder.config import GRPOConfig, RewardConfig from guac_coder.data import build_prompt from guac_coder.rewards import compute_total_reward from guac_coder.training import train_grpo def _read_code_file(path: str) -> str: """Read a Python file, exiting with a clean message if it is missing.""" if not os.path.isfile(path): raise SystemExit(f"error: no such file: {path}") with open(path, "r", encoding="utf-8") as fh: return fh.read() RATER_CHOICES = ("static", "decision", "llm") def _add_rater_args(parser: argparse.ArgumentParser) -> None: """Attach the shared rater-selection flags to a subparser.""" parser.add_argument( "--rater", default="static", choices=list(RATER_CHOICES), help=( "Scoring backend: static (13 regex/AST rules), decision (Ollama " "System-One decision model, e.g. clef), or llm (generative judge)" ), ) parser.add_argument( "--rater-model", default="clef", help="Decision model tag for --rater decision (e.g. clef, clef:cloud)", ) parser.add_argument( "--rater-base-url", default="http://localhost:11434", help="Ollama base URL for the decision rater", ) parser.add_argument( "--rater-threshold", type=float, default=0.5, help="Probability cutoff for multi-state decision rules", ) parser.add_argument( "--rater-on-error", default="static", choices=["static", "zero", "raise"], help="Behaviour when the decision endpoint fails", ) def _reward_config_from_args(args: argparse.Namespace) -> RewardConfig: """Build a RewardConfig from the rater flags on ``args``.""" kwargs = {} if getattr(args, "judge_model", None): kwargs["judge_model"] = args.judge_model if getattr(args, "rater", None): kwargs["rater"] = args.rater if getattr(args, "rater_model", None): kwargs["decision_model"] = args.rater_model if getattr(args, "rater_base_url", None): kwargs["decision_base_url"] = args.rater_base_url if getattr(args, "rater_threshold", None) is not None: kwargs["decision_threshold"] = args.rater_threshold if getattr(args, "rater_on_error", None): kwargs["decision_on_error"] = args.rater_on_error return RewardConfig(**kwargs) def _resolve_llm_judge(): """Return an LLM judge callable for the legacy rewards.py path. Uses npcpy.llm_funcs.get_llm_response when importable. Falls back to a judge that returns no scores, which makes the LLM component contribute zero rather than failing the run. """ try: from npcpy.llm_funcs import get_llm_response return get_llm_response except Exception as exc: # pragma: no cover - depends on environment logging.warning("LLM judge unavailable (%s); scoring static components only", exc) def _no_judge(**kwargs): return {} return _no_judge def _setup_logging(level: int = logging.INFO) -> None: # force=True: npcpy and friends install root handlers at import time, and # plain basicConfig() would silently no-op, swallowing our INFO progress. logging.basicConfig( level=level, format="%(asctime)s [%(levelname)s] %(message)s", stream=sys.stdout, force=True, ) logging.getLogger("guac_coder").setLevel(level) def main() -> None: parser = argparse.ArgumentParser(description="guac-coder: research code LLM") subparsers = parser.add_subparsers(dest="command") # train train_parser = subparsers.add_parser("train", help="Run GRPO training") train_parser.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B") train_parser.add_argument("--output-dir", default="./grpo_output") train_parser.add_argument("--data", default=None, help="Path to JSONL training data") train_parser.add_argument("--iterations", type=int, default=100) train_parser.add_argument("--group-size", type=int, default=8) train_parser.add_argument("--lr", type=float, default=1e-5) train_parser.add_argument("--resume-from", default=None) train_parser.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"]) train_parser.add_argument( "--legacy-rewards", action="store_true", help="Optimize the legacy rewards.py score instead of the 13-rule grpo_rewards", ) _add_rater_args(train_parser) # eval eval_parser = subparsers.add_parser("eval", help="Evaluate code with reward function") eval_parser.add_argument("code", nargs="?", help="Python code string or '-' for stdin") eval_parser.add_argument("--file", default=None, help="Python file to evaluate") eval_parser.add_argument("--judge-model", default="gpt-4o") eval_parser.add_argument("--json", action="store_true", help="Output JSON") _add_rater_args(eval_parser) # reward reward_parser = subparsers.add_parser("reward", help="Compute reward for a code snippet") reward_parser.add_argument("--task", required=True, help="Task description") reward_parser.add_argument("--code", required=True, help="Code snippet or file path") reward_parser.add_argument("--llm-judge", action="store_true", help="Include LLM judge") reward_parser.add_argument( "--legacy", action="store_true", help="Use the legacy rewards.py path instead of the 13-rule grpo_rewards", ) reward_parser.add_argument("--json", action="store_true", help="Output JSON") _add_rater_args(reward_parser) # trace trace_parser = subparsers.add_parser( "trace", help="Generate scored traces from local Ollama models" ) trace_parser.add_argument("--models", required=True, help="Comma-separated model names") trace_parser.add_argument("--output-dir", default="./traces") trace_parser.add_argument("--tasks", default=None) trace_parser.add_argument("--limit", type=int, default=None) trace_parser.add_argument("--n-samples", type=int, default=1) trace_parser.add_argument("--num-predict", type=int, default=1024) trace_parser.add_argument("--temperature", type=float, default=0.8) trace_parser.add_argument("--seed", type=int, default=42) trace_parser.add_argument("--base-url", default="http://localhost:11434") trace_parser.add_argument("--timeout", type=float, default=600.0) trace_parser.add_argument("--no-think", action="store_true") trace_parser.add_argument("--no-resume", action="store_true") trace_parser.add_argument( "--model-opt", action="append", default=None, help="Per-model setting, repeatable: MODEL:key=value[,key=value]. " "Keys: num_predict, think, temperature, timeout", ) trace_parser.add_argument("--json", action="store_true") _add_rater_args(trace_parser) # export export_parser = subparsers.add_parser( "export", help="Convert traces into SFT / preference / GRPO datasets" ) export_parser.add_argument("--traces", required=True, help="Path to traces JSONL") export_parser.add_argument("--output-dir", default=None) export_parser.add_argument("--min-reward", type=float, default=None) export_parser.add_argument("--min-gap", type=float, default=0.15) export_parser.add_argument("--json", action="store_true") # audit audit_parser = subparsers.add_parser( "audit", help="Measure per-rule agreement between two raters" ) audit_parser.add_argument("--corpus", required=True, help="Directory of .py cases") audit_parser.add_argument("--rater-a", default="static") audit_parser.add_argument("--rater-b", default="decision") audit_parser.add_argument("--rater-model", default=None) audit_parser.add_argument("--output", default=None, help="Write JSON report here") audit_parser.add_argument("--json", action="store_true") args = parser.parse_args() if args.command == "train": train_command(args) elif args.command == "eval": eval_command(args) elif args.command == "reward": reward_command(args) elif args.command == "trace": trace_command(args) elif args.command == "export": export_command(args) elif args.command == "audit": audit_command(args) else: parser.print_help() def train_command(args: argparse.Namespace | None = None) -> None: """Run GRPO training.""" if args is None: args = _parse_train_args() _setup_logging() cfg = GRPOConfig( model_name=args.model, output_dir=args.output_dir, num_iterations=args.iterations, group_size=args.group_size, learning_rate=args.lr, resume_from_checkpoint=args.resume_from, backend=getattr(args, "backend", "auto"), ) reward_cfg = _reward_config_from_args(args) use_grpo_rewards = not getattr(args, "legacy_rewards", False) rater = getattr(args, "rater", "static") if getattr(args, "legacy_rewards", False): rater = "llm" # The LLM judge is only consulted on the legacy path; static and decision # raters never call it. get_llm_response_fn = _resolve_llm_judge() if rater == "llm" else (lambda **kwargs: {}) train_grpo( cfg, reward_cfg, get_llm_response_fn, data_path=args.data, use_grpo_rewards=use_grpo_rewards, rater=rater, ) def eval_command(args: argparse.Namespace | None = None) -> None: """Evaluate code with the legacy 12-rule reward function (static + LLM judge).""" if args is None: args = _parse_eval_args() _setup_logging() if args.file: code = _read_code_file(args.file) elif args.code and args.code != "-": code = args.code else: code = sys.stdin.read() reward_cfg = _reward_config_from_args(args) rater = getattr(args, "rater", "static") if rater == "llm": result = compute_total_reward(code, _resolve_llm_judge(), reward_cfg) else: from guac_coder.training import score_completion _total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater) rules = details.get("rules", {}) result = { "total": _total, "rater": rater, "static": _total if rater == "static" else 0.0, "llm": 0.0, "static_components": rules if rater == "static" else {}, "rules": rules, "llm_components": {}, } if args.json: print(json.dumps(result, indent=2)) else: print(f"Rater: {result.get('rater', 'llm')}") print(f"Total reward: {result['total']:.3f}") if result.get("rater") == "llm": print(f" Static: {result['static']:.3f}") print(f" LLM judge: {result['llm']:.3f}") print("\nStatic components:") for k, v in result.get("static_components", {}).items(): print(f" {k}: {v:+.3f}") print("\nLLM components:") for k, v in result.get("llm_components", {}).items(): print(f" {k}: {v:+.3f}") else: print("\nPer-rule rewards:") for k, v in result.get("rules", {}).items(): print(f" {k}: {v:+.3f}") def reward_command(args: argparse.Namespace | None = None) -> None: """Compute reward for a task/code pair.""" if args is None: args = _parse_reward_args() _setup_logging() code = args.code if code.endswith(".py") and "\n" not in code: code = _read_code_file(code) prompt = build_prompt(args.task) # --legacy / --llm-judge force the generative judge path; otherwise --rater # selects between the static rules and a decision model. use_legacy = getattr(args, "legacy", False) or getattr(args, "llm_judge", False) if getattr(args, "llm_judge", False) and not getattr(args, "legacy", False): logging.info("--llm-judge requires the legacy reward path; using --legacy") reward_cfg = _reward_config_from_args(args) rater = "llm" if use_legacy else getattr(args, "rater", "static") as_json = getattr(args, "json", False) if rater == "llm": judge = _resolve_llm_judge() if getattr(args, "llm_judge", False) else None get_llm_response_fn = judge or (lambda **kwargs: {}) result = compute_total_reward(code, get_llm_response_fn, reward_cfg) total = result["total"] breakdown = result.get("static_components", {}) extra = {"static": result["static"], "llm": result["llm"]} else: from guac_coder.training import score_completion total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater) breakdown = details.get("rules", {}) extra = {} if as_json: print( json.dumps( { "task": args.task, "rater": rater, "total": total, **extra, "rules": breakdown, }, indent=2, ) ) return print(f"Task: {args.task}") print(f"Rater: {rater}") print(f"Prompt length: {len(prompt)} chars") print(f"Code length: {len(code)} chars") print(f"Total reward: {total:.3f}") for key, value in extra.items(): print(f" {key}: {value:+.3f}") print("\nPer-rule rewards:") for name, value in breakdown.items(): print(f" {name}: {value:+.3f}") def _parse_model_opts(specs) -> dict: """Parse --model-opt MODEL:key=value[,key=value] into per-model settings.""" overrides = {} for spec in specs or []: # Model names contain colons (lfm3:latest), so split on the first # known key marker rather than on the first colon. marker = None for candidate in ("num_predict=", "think=", "temperature=", "timeout="): idx = spec.find(candidate) if idx != -1 and (marker is None or idx < marker): marker = idx if marker is None: raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec) head = spec[:marker].rstrip() if not head.endswith(":"): raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec) model = head[:-1].strip() rest = spec[marker:] settings = overrides.setdefault(model, {}) for pair in rest.split(","): key, _, value = pair.partition("=") key, value = key.strip(), value.strip() if not key or not value: raise SystemExit("error: malformed --model-opt pair '%s'" % pair) if key == "num_predict" or key == "timeout": try: value = int(float(value)) if key == "num_predict" else float(value) except ValueError: raise SystemExit( "error: --model-opt %s needs a number, got '%s'" % (key, value) ) elif key == "temperature": try: value = float(value) except ValueError: raise SystemExit("error: --model-opt temperature needs a number") elif key == "think": value = value.lower() in ("1", "true", "yes", "on") else: raise SystemExit("error: unknown --model-opt key '%s'" % key) settings[key] = value return overrides def trace_command(args: argparse.Namespace | None = None) -> None: """Generate scored traces from local Ollama models.""" if args is None: args = _parse_trace_args() _setup_logging() from guac_coder.data import load_research_tasks from guac_coder.trace import run_experiment models = [m.strip() for m in args.models.split(",") if m.strip()] tasks = load_research_tasks(args.tasks) if args.tasks else load_research_tasks() if args.limit: tasks = tasks[: args.limit] summary = run_experiment( models=models, output_dir=args.output_dir, tasks=tasks, n_samples=args.n_samples, base_url=args.base_url, num_predict=args.num_predict, temperature=args.temperature, seed=args.seed, think=not args.no_think, timeout=args.timeout, resume=not args.no_resume, model_overrides=_parse_model_opts(getattr(args, "model_opt", None)), rater=getattr(args, "rater", "static"), reward_cfg=_reward_config_from_args(args), ) if args.json: print(json.dumps(summary, indent=2)) return print("\nTraces: %s" % summary["traces_path"]) print("New this run: %d" % summary["new_traces_this_run"]) for model, stats in summary["models"].items(): print("\n== %s ==" % model) print( " n=%d scored=%d sources=%s" % (stats["n"], stats["n_scored"], stats["code_sources"]) ) if stats.get("empty_reasons"): print(" empty: %s" % stats["empty_reasons"]) print( " mean_reward=%s std=%s min=%s max=%s" % ( stats["mean_reward"], stats["std_reward"], stats["min_reward"], stats["max_reward"], ) ) print(" mean_code_chars=%s" % stats["mean_code_chars"]) if stats["rules"]: print(" per-rule means (fired fraction):") for rule, rs in stats["rules"].items(): print(" %-34s %+.3f (%.0f%%)" % (rule, rs["mean"], rs["fired_frac"] * 100)) def audit_command(args: argparse.Namespace | None = None) -> None: """Measure per-rule agreement between two raters over a labeled corpus.""" if args is None: args = _parse_audit_args() _setup_logging() from guac_coder.rater_audit import format_report, run_audit report = run_audit( corpus_dir=args.corpus, rater_a=args.rater_a, rater_b=args.rater_b, rater_model=args.rater_model, ) if args.output: with open(args.output, "w", encoding="utf-8") as fh: json.dump(report, fh, indent=2) logging.info("Wrote audit report to %s", args.output) if args.json: print(json.dumps(report, indent=2)) return print(format_report(report)) def export_command(args: argparse.Namespace | None = None) -> None: """Convert a traces JSONL into training datasets.""" if args is None: args = _parse_export_args() _setup_logging() from guac_coder.trace_export import export_all output_dir = args.output_dir or os.path.join(os.path.dirname(args.traces) or ".", "datasets") manifest = export_all( traces_path=args.traces, output_dir=output_dir, min_reward=args.min_reward, min_gap=args.min_gap, ) if args.json: print(json.dumps(manifest, indent=2)) return print( "Traces: %s (%d rows, %d scored)" % (manifest["traces_path"], manifest["n_traces"], manifest["n_scored"]) ) print("SFT: %d -> %s" % (manifest["sft"]["n"], manifest["sft"]["path"])) print("Preference: %d -> %s" % (manifest["preference"]["n"], manifest["preference"]["path"])) print("GRPO: %d -> %s" % (manifest["grpo"]["n"], manifest["grpo"]["path"])) def _parse_export_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Export traces to training datasets") p.add_argument("--traces", required=True) p.add_argument("--output-dir", default=None) p.add_argument("--min-reward", type=float, default=None) p.add_argument("--min-gap", type=float, default=0.15) p.add_argument("--json", action="store_true") return p.parse_args() def _parse_trace_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Collect scored traces from local models") p.add_argument("--models", required=True, help="Comma-separated Ollama model names") p.add_argument("--output-dir", default="./traces") p.add_argument("--tasks", default=None, help="Task list file (.txt or .jsonl)") p.add_argument("--limit", type=int, default=None, help="Use only the first N tasks") p.add_argument("--n-samples", type=int, default=1) p.add_argument("--num-predict", type=int, default=1024) p.add_argument("--temperature", type=float, default=0.8) p.add_argument("--seed", type=int, default=42) p.add_argument("--base-url", default="http://localhost:11434") p.add_argument("--timeout", type=float, default=600.0) p.add_argument("--no-think", action="store_true", help="Disable model thinking traces") p.add_argument("--no-resume", action="store_true", help="Ignore existing traces") p.add_argument("--model-opt", action="append", default=None) p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args() def _parse_audit_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Rater agreement audit") p.add_argument("--corpus", required=True) p.add_argument("--rater-a", default="static") p.add_argument("--rater-b", default="decision") p.add_argument("--rater-model", default=None) p.add_argument("--output", default=None) p.add_argument("--json", action="store_true") return p.parse_args() def _parse_train_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B") p.add_argument("--output-dir", default="./grpo_output") p.add_argument("--data", default=None) p.add_argument("--iterations", type=int, default=100) p.add_argument("--group-size", type=int, default=8) p.add_argument("--lr", type=float, default=1e-5) p.add_argument("--resume-from", default=None) p.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"]) p.add_argument("--legacy-rewards", action="store_true") _add_rater_args(p) return p.parse_args() def _parse_eval_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("code", nargs="?", default="-") p.add_argument("--file", default=None) p.add_argument("--judge-model", default="gpt-4o") p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args() def _parse_reward_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("--task", required=True) p.add_argument("--code", required=True) p.add_argument("--legacy", action="store_true") p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args() if __name__ == "__main__": main()