golive-gate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ """golive-gate: agent eval cases, checks and go-live gates in one command."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .agents import http_agent # noqa: E402
6
+ from .analysis import ablate, diff # noqa: E402
7
+ from .cases import Case, load_cases # noqa: E402
8
+ from .checks import FAIL, NA, PASS, Check, CheckSet, Verdict # noqa: E402
9
+ from .gates import GO, NO_GO, PARTIAL, Gate, GateResult, Rule, evaluate # noqa: E402
10
+ from .judge import ClaudeJudge, JudgeReply, judge_check, parse_verdict # noqa: E402
11
+ from .runner import CaseRun, Response, RunResult, run_eval # noqa: E402
12
+
13
+ __all__ = [
14
+ "Case",
15
+ "CaseRun",
16
+ "ClaudeJudge",
17
+ "JudgeReply",
18
+ "Check",
19
+ "CheckSet",
20
+ "FAIL",
21
+ "GO",
22
+ "Gate",
23
+ "GateResult",
24
+ "NA",
25
+ "NO_GO",
26
+ "PARTIAL",
27
+ "PASS",
28
+ "Response",
29
+ "Rule",
30
+ "RunResult",
31
+ "Verdict",
32
+ "__version__",
33
+ "ablate",
34
+ "diff",
35
+ "evaluate",
36
+ "http_agent",
37
+ "judge_check",
38
+ "parse_verdict",
39
+ "load_cases",
40
+ "run_eval",
41
+ ]
golive_gate/agents.py ADDED
@@ -0,0 +1,31 @@
1
+ """Ways to reach an agent other than a Python function."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.request
7
+ from typing import Any, Callable
8
+
9
+ from .runner import Response
10
+
11
+
12
+ def http_agent(url: str, headers: dict[str, str] | None = None, timeout: float = 60.0) -> Callable[[Any], Any]:
13
+ """POST {"input": <case input>} as JSON to ``url``.
14
+
15
+ The endpoint answers with JSON. If it has an "output" key, that is the output and an
16
+ optional "cost_usd" is recorded; otherwise the whole body is the output.
17
+ """
18
+ base_headers = {"Content-Type": "application/json", "User-Agent": "golive-gate"}
19
+ base_headers.update(headers or {})
20
+
21
+ def call(case_input: Any) -> Any:
22
+ body = json.dumps({"input": case_input}).encode("utf-8")
23
+ req = urllib.request.Request(url, data=body, headers=base_headers, method="POST")
24
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
25
+ data = json.loads(resp.read().decode("utf-8"))
26
+ if isinstance(data, dict) and "output" in data:
27
+ return Response(data["output"], float(data.get("cost_usd", 0.0) or 0.0))
28
+ return data
29
+
30
+ call.__name__ = f"http_agent({url})"
31
+ return call
@@ -0,0 +1,98 @@
1
+ """Ablation and regression diffs, both computed from results that already exist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from .gates import Gate, evaluate
9
+ from .runner import RunResult
10
+
11
+
12
+ @dataclass
13
+ class AblationRow:
14
+ check: str
15
+ critical: bool
16
+ decision: str # the gate decision if this check did not exist
17
+ cases_caught: list[str] # cases that fail with the check and pass without it
18
+
19
+ @property
20
+ def load_bearing(self) -> bool:
21
+ return bool(self.cases_caught)
22
+
23
+
24
+ def ablate(gate: Gate, result: RunResult) -> tuple[str, list[AblationRow]]:
25
+ """Switch off each check in turn and see what the gate would have said.
26
+
27
+ No agent or judge calls are made: the stored outputs are re-graded without one check.
28
+ A check that catches no case on its own is either redundant or untested by this case set.
29
+ """
30
+ baseline = evaluate(gate, result).decision
31
+ rows = []
32
+ for check in result.checks:
33
+ reduced = result.without_checks(check.id)
34
+ caught = sorted(
35
+ {full.case_id for full, red in zip(result.case_runs, reduced.case_runs) if not full.passed and red.passed}
36
+ )
37
+ rows.append(AblationRow(check.id, check.critical, evaluate(gate, reduced).decision, caught))
38
+ return baseline, rows
39
+
40
+
41
+ def ablation_markdown(baseline: str, rows: list[AblationRow]) -> str:
42
+ lines = [
43
+ f"# Ablation (gate with every check: {baseline.upper()})",
44
+ "",
45
+ "| Check switched off | Critical | Gate would say | Cases only this check catches |",
46
+ "|---|---|---|---|",
47
+ ]
48
+ for r in rows:
49
+ caught = ", ".join(r.cases_caught) or "none"
50
+ lines.append(f"| {r.check} | {'yes' if r.critical else ''} | {r.decision.upper()} | {caught} |")
51
+ return "\n".join(lines) + "\n"
52
+
53
+
54
+ @dataclass
55
+ class Diff:
56
+ before: str
57
+ after: str
58
+ regressed: list[str] # passed on every run before, not now
59
+ fixed: list[str] # failed before, passes on every run now
60
+ added: list[str]
61
+ removed: list[str]
62
+
63
+ @property
64
+ def has_regressions(self) -> bool:
65
+ return bool(self.regressed) or _rank(self.after) < _rank(self.before)
66
+
67
+
68
+ def diff(before: dict[str, Any], after: dict[str, Any]) -> Diff:
69
+ """Compare two results.json files. A case counts as passing only if it passed on every run."""
70
+ b, a = _passes(before), _passes(after)
71
+ return Diff(
72
+ before=before["decision"],
73
+ after=after["decision"],
74
+ regressed=sorted(k for k in a if k in b and b[k] and not a[k]),
75
+ fixed=sorted(k for k in a if k in b and not b[k] and a[k]),
76
+ added=sorted(set(a) - set(b)),
77
+ removed=sorted(set(b) - set(a)),
78
+ )
79
+
80
+
81
+ def diff_markdown(d: Diff) -> str:
82
+ lines = [f"# Regression diff: {d.before.upper()} -> {d.after.upper()}", ""]
83
+ for label, items in (
84
+ ("Regressed (passed before, fails now)", d.regressed),
85
+ ("Fixed (failed before, passes now)", d.fixed),
86
+ ("New cases", d.added),
87
+ ("Removed cases", d.removed),
88
+ ):
89
+ lines.append(f"- {label}: {', '.join(items) if items else 'none'}")
90
+ return "\n".join(lines) + "\n"
91
+
92
+
93
+ def _passes(results: dict[str, Any]) -> dict[str, bool]:
94
+ return {c["id"]: all(r["passed"] for r in c["runs"]) for c in results["cases"]}
95
+
96
+
97
+ def _rank(decision: str) -> int:
98
+ return {"no-go": 0, "partial": 1, "go": 2}[decision]
golive_gate/cases.py ADDED
@@ -0,0 +1,74 @@
1
+ """Eval cases: one input, what a correct answer looks like, and a group for gate rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Case:
16
+ id: str
17
+ input: Any
18
+ expected: Any = None
19
+ group: str = "default"
20
+ title: str = ""
21
+ tags: tuple = ()
22
+ meta: dict = field(default_factory=dict)
23
+
24
+ @classmethod
25
+ def from_dict(cls, raw: dict) -> Case:
26
+ if "id" not in raw:
27
+ raise ValueError(f"case is missing an id: {raw!r}")
28
+ if "input" not in raw:
29
+ raise ValueError(f"case {raw['id']!r} is missing an input")
30
+ known = {"id", "input", "expected", "group", "title", "tags"}
31
+ return cls(
32
+ id=str(raw["id"]),
33
+ input=raw["input"],
34
+ expected=raw.get("expected"),
35
+ group=str(raw.get("group", "default")),
36
+ title=str(raw.get("title", "")),
37
+ tags=tuple(raw.get("tags", ())),
38
+ meta={k: v for k, v in raw.items() if k not in known},
39
+ )
40
+
41
+
42
+ def load_cases(source: str | Path | Iterable[dict]) -> list[Case]:
43
+ """Load cases from a .yml/.yaml, .json or .jsonl file, or from a list of dicts."""
44
+ if isinstance(source, (str, Path)):
45
+ raw = _read(Path(source))
46
+ else:
47
+ raw = list(source)
48
+ cases = [c if isinstance(c, Case) else Case.from_dict(c) for c in raw]
49
+ seen: set[str] = set()
50
+ for c in cases:
51
+ if c.id in seen:
52
+ raise ValueError(f"duplicate case id {c.id!r}")
53
+ seen.add(c.id)
54
+ if not cases:
55
+ raise ValueError("no cases loaded")
56
+ return cases
57
+
58
+
59
+ def _read(path: Path) -> list[dict]:
60
+ text = path.read_text(encoding="utf-8")
61
+ suffix = path.suffix.lower()
62
+ if suffix == ".jsonl":
63
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
64
+ if suffix == ".json":
65
+ data = json.loads(text)
66
+ elif suffix in (".yml", ".yaml"):
67
+ data = yaml.safe_load(text)
68
+ else:
69
+ raise ValueError(f"unsupported case file type: {path.suffix}")
70
+ if isinstance(data, dict) and "cases" in data:
71
+ data = data["cases"]
72
+ if not isinstance(data, list):
73
+ raise ValueError(f"{path} must hold a list of cases (or a 'cases' key)")
74
+ return data
golive_gate/checks.py ADDED
@@ -0,0 +1,90 @@
1
+ """Checks: yes/no tests on one agent output. Each returns pass, fail or na."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from typing import Any, Callable
8
+
9
+ PASS, FAIL, NA = "pass", "fail", "na"
10
+ VERDICTS = (PASS, FAIL, NA)
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Verdict:
15
+ result: str
16
+ reason: str = ""
17
+ cost_usd: float = 0.0 # what grading cost, e.g. an LLM judge call
18
+
19
+ def __post_init__(self) -> None:
20
+ if self.result not in VERDICTS:
21
+ raise ValueError(f"verdict must be one of {VERDICTS}, got {self.result!r}")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Check:
26
+ """One yes/no criterion.
27
+
28
+ ``fn(case, output)`` returns "pass", "fail", "na", a bool, or a Verdict.
29
+ ``critical`` means a single failure anywhere blocks the gate.
30
+ """
31
+
32
+ id: str
33
+ fn: Callable[[Any, Any], Any]
34
+ text: str = ""
35
+ critical: bool = False
36
+
37
+ def run(self, case: Any, output: Any) -> Verdict:
38
+ try:
39
+ raw = self.fn(case, output)
40
+ except Exception as exc: # a crashing check is a failed check, with the reason kept
41
+ return Verdict(FAIL, f"check raised {type(exc).__name__}: {exc}")
42
+ return _coerce(raw)
43
+
44
+
45
+ def _coerce(raw: Any) -> Verdict:
46
+ if isinstance(raw, Verdict):
47
+ return raw
48
+ if isinstance(raw, bool):
49
+ return Verdict(PASS if raw else FAIL)
50
+ if raw is None:
51
+ return Verdict(NA)
52
+ if isinstance(raw, tuple) and len(raw) == 2:
53
+ return Verdict(str(raw[0]), str(raw[1]))
54
+ return Verdict(str(raw))
55
+
56
+
57
+ class CheckSet:
58
+ """A named, ordered collection of checks, filled with the ``@checks.check`` decorator."""
59
+
60
+ def __init__(self, checks: Iterable[Check] = ()) -> None:
61
+ self._checks: dict[str, Check] = {}
62
+ for c in checks:
63
+ self.add(c)
64
+
65
+ def add(self, c: Check) -> None:
66
+ if c.id in self._checks:
67
+ raise ValueError(f"duplicate check id {c.id!r}")
68
+ self._checks[c.id] = c
69
+
70
+ def check(self, id: str, text: str = "", critical: bool = False):
71
+ def register(fn: Callable) -> Callable:
72
+ self.add(Check(id=id, fn=fn, text=text or (fn.__doc__ or "").strip(), critical=critical))
73
+ return fn
74
+
75
+ return register
76
+
77
+ def without(self, *ids: str) -> CheckSet:
78
+ missing = set(ids) - set(self._checks)
79
+ if missing:
80
+ raise KeyError(f"unknown check ids: {sorted(missing)}")
81
+ return CheckSet(c for c in self if c.id not in ids)
82
+
83
+ def __iter__(self):
84
+ return iter(self._checks.values())
85
+
86
+ def __len__(self) -> int:
87
+ return len(self._checks)
88
+
89
+ def __getitem__(self, id: str) -> Check:
90
+ return self._checks[id]
golive_gate/cli.py ADDED
@@ -0,0 +1,109 @@
1
+ """Command line.
2
+
3
+ golive run [golive.yml] run every case, grade it, apply the gate
4
+ golive ablate [golive.yml] which checks the gate actually depends on
5
+ golive diff BEFORE AFTER compare two results.json files
6
+
7
+ Exit codes for run: 0 go, 1 no-go, 2 partial when --strict is set (partial exits 0
8
+ otherwise), 3 config error. With --baseline, a regression against the baseline also
9
+ exits 1. diff exits 1 when anything regressed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from collections.abc import Sequence
18
+ from pathlib import Path
19
+
20
+ from . import __version__, report
21
+ from .analysis import ablate, ablation_markdown, diff, diff_markdown
22
+ from .config import load_project
23
+ from .gates import NO_GO, PARTIAL, evaluate
24
+ from .runner import run_eval
25
+
26
+ CONFIG_ERRORS = (ValueError, TypeError, ImportError, AttributeError, FileNotFoundError, KeyError)
27
+
28
+
29
+ def main(argv: Sequence[str] | None = None) -> int:
30
+ parser = argparse.ArgumentParser(prog="golive", description="Run agent evals against a go-live gate.")
31
+ parser.add_argument("--version", action="version", version=f"golive-gate {__version__}")
32
+ sub = parser.add_subparsers(dest="command", required=True)
33
+
34
+ run = sub.add_parser("run", help="run every case, grade it, and apply the gate")
35
+ _project_args(run)
36
+ run.add_argument("--out", default=None, help="folder for report.md and results.json")
37
+ run.add_argument("--strict", action="store_true", help="exit 2 on a partial result")
38
+ run.add_argument("--baseline", help="an earlier results.json to diff against; a regression exits 1")
39
+
40
+ abl = sub.add_parser("ablate", help="switch off each check in turn and show what the gate would say")
41
+ _project_args(abl)
42
+ abl.add_argument("--out", default=None, help="folder for ablation.md")
43
+
44
+ dif = sub.add_parser("diff", help="compare two results.json files")
45
+ dif.add_argument("before")
46
+ dif.add_argument("after")
47
+
48
+ args = parser.parse_args(argv)
49
+ if args.command == "diff":
50
+ return _diff(args)
51
+
52
+ try:
53
+ project = load_project(args.config, agent=args.agent, runs=args.runs)
54
+ baseline = json.loads(Path(args.baseline).read_text()) if getattr(args, "baseline", None) else None
55
+ except CONFIG_ERRORS as exc:
56
+ print(f"golive: config error: {exc}", file=sys.stderr)
57
+ return 3
58
+
59
+ result = run_eval(project.agent, project.cases, project.checks, runs=project.runs)
60
+ out_dir = Path(args.out) if args.out else project.root / "reports"
61
+
62
+ if args.command == "ablate":
63
+ decision, rows = ablate(project.gate, result)
64
+ text = ablation_markdown(decision, rows)
65
+ out_dir.mkdir(parents=True, exist_ok=True)
66
+ (out_dir / "ablation.md").write_text(text, encoding="utf-8")
67
+ print(text, end="")
68
+ return 0
69
+
70
+ outcome = evaluate(project.gate, result)
71
+ paths = report.write(out_dir, result, project.gate, outcome, agent=project.agent_ref)
72
+ print(f"{project.gate.name}: {outcome.decision.upper()}")
73
+ for r in outcome.reasons:
74
+ print(f" {r}")
75
+ print(f"report: {paths['markdown']}")
76
+
77
+ regressed = False
78
+ if baseline is not None:
79
+ d = diff(baseline, report.to_dict(result, project.gate, outcome, agent=project.agent_ref))
80
+ print(diff_markdown(d), end="")
81
+ regressed = d.has_regressions
82
+
83
+ if outcome.decision == NO_GO or regressed:
84
+ return 1
85
+ if outcome.decision == PARTIAL and args.strict:
86
+ return 2
87
+ return 0
88
+
89
+
90
+ def _project_args(p: argparse.ArgumentParser) -> None:
91
+ p.add_argument("config", nargs="?", default="golive.yml", help="path to golive.yml")
92
+ p.add_argument("--agent", help="override the agent: module:attribute or an http(s) URL")
93
+ p.add_argument("--runs", type=int, help="override the number of runs")
94
+
95
+
96
+ def _diff(args: argparse.Namespace) -> int:
97
+ try:
98
+ before = json.loads(Path(args.before).read_text())
99
+ after = json.loads(Path(args.after).read_text())
100
+ d = diff(before, after)
101
+ except (OSError, ValueError, KeyError) as exc:
102
+ print(f"golive: cannot diff: {exc}", file=sys.stderr)
103
+ return 3
104
+ print(diff_markdown(d), end="")
105
+ return 1 if d.has_regressions else 0
106
+
107
+
108
+ if __name__ == "__main__":
109
+ raise SystemExit(main())
golive_gate/config.py ADDED
@@ -0,0 +1,105 @@
1
+ """golive.yml: where the cases, checks, agent and gate live.
2
+
3
+ cases: cases.yml # .yml, .json or .jsonl, relative to this file
4
+ checks: checks:checks # module:attribute holding a CheckSet
5
+ agent: agent:spec_agent # module:attribute called with each case's input, or an http(s) URL
6
+ agent_headers: # optional, for an http agent; ${VARS} are read from the environment
7
+ Authorization: Bearer ${AGENT_TOKEN}
8
+ gate: gate.yml # a file, or the gate written inline as a mapping
9
+ runs: 3
10
+
11
+ Modules are imported from the folder that holds golive.yml.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import importlib
17
+ import os
18
+ import sys
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import yaml
24
+
25
+ from .agents import http_agent
26
+ from .cases import Case, load_cases
27
+ from .checks import CheckSet
28
+ from .gates import Gate
29
+
30
+
31
+ @dataclass
32
+ class Project:
33
+ root: Path
34
+ cases: list[Case]
35
+ checks: CheckSet
36
+ agent: Any
37
+ agent_ref: str
38
+ gate: Gate
39
+ runs: int
40
+
41
+
42
+ def load_project(path: str | Path, agent: str | None = None, runs: int | None = None) -> Project:
43
+ path = Path(path).resolve()
44
+ root = path.parent
45
+ raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
46
+ for key in ("cases", "checks", "agent", "gate"):
47
+ if key not in raw and not (key == "agent" and agent):
48
+ raise ValueError(f"{path.name} is missing '{key}'")
49
+
50
+ _use_root(root)
51
+
52
+ checks = resolve(raw["checks"])
53
+ if not isinstance(checks, CheckSet):
54
+ raise TypeError(f"'checks' must point to a CheckSet, got {type(checks).__name__}")
55
+ agent_ref = agent or raw["agent"]
56
+ if agent_ref.startswith(("http://", "https://")):
57
+ headers = {k: os.path.expandvars(str(v)) for k, v in (raw.get("agent_headers") or {}).items()}
58
+ agent_fn = http_agent(agent_ref, headers=headers)
59
+ else:
60
+ agent_fn = resolve(agent_ref)
61
+ if not callable(agent_fn):
62
+ raise TypeError(f"agent {agent_ref!r} is not callable")
63
+
64
+ gate_raw = raw["gate"]
65
+ gate = Gate.from_dict(gate_raw) if isinstance(gate_raw, dict) else Gate.load(root / gate_raw)
66
+
67
+ return Project(
68
+ root=root,
69
+ cases=load_cases(root / raw["cases"]),
70
+ checks=checks,
71
+ agent=agent_fn,
72
+ agent_ref=agent_ref,
73
+ gate=gate,
74
+ runs=int(runs if runs is not None else raw.get("runs", 1)),
75
+ )
76
+
77
+
78
+ def _use_root(root: Path) -> None:
79
+ """Import project modules from ``root`` first.
80
+
81
+ Two projects often both have an ``agent.py`` or ``checks.py``. Forget any already
82
+ imported module whose name is also a module or package in this root, so each project
83
+ gets its own.
84
+ """
85
+ if str(root) in sys.path:
86
+ sys.path.remove(str(root))
87
+ sys.path.insert(0, str(root))
88
+ local = {p.stem for p in root.glob("*.py")} | {p.name for p in root.iterdir() if (p / "__init__.py").exists()}
89
+ for name in list(sys.modules):
90
+ if name.split(".")[0] in local:
91
+ module_file = getattr(sys.modules[name], "__file__", None) or ""
92
+ if not module_file.startswith(str(root)):
93
+ del sys.modules[name]
94
+
95
+
96
+ def resolve(ref: str) -> Any:
97
+ """Import 'package.module:attribute'."""
98
+ if ":" not in ref:
99
+ raise ValueError(f"expected 'module:attribute', got {ref!r}")
100
+ module_name, attr = ref.split(":", 1)
101
+ module = importlib.import_module(module_name)
102
+ obj: Any = module
103
+ for part in attr.split("."):
104
+ obj = getattr(obj, part)
105
+ return obj