Files
2026-10-29 01:46:05 +07:00

163 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""agent-evals harness — metrics over a corpus of real agent runs.
Public layer: reads a corpus of run records, emits AGGREGATES ONLY.
Task text, prompts and reports never leave the machine (see PRIVACY.md).
Record schema (one JSON object per line):
id, lane, worker, model, effort, status, elapsed_s, out_tokens,
thinking_tokens, cache_read, n_files, ask_chars, report_chars
Fields `ask` / `report` may exist in the source corpus and are ignored by design.
Usage:
python3 harness.py --corpus /path/to/tickets.jsonl --out .
"""
import argparse
import collections
import json
import os
import statistics
import sys
PUBLIC_FIELDS = (
"id", "lane", "worker", "model", "effort", "status", "elapsed_s",
"out_tokens", "thinking_tokens", "cache_read", "n_files",
"ask_chars", "report_chars",
)
# Observed hard ceiling of the pipeline under test, in seconds.
RUN_CAP_S = 25 * 60
def load(path):
rows, bad = [], 0
for line in open(path, encoding="utf-8"):
if not line.strip():
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
bad += 1
continue
rows.append({k: obj.get(k) for k in PUBLIC_FIELDS})
return rows, bad
def median(values):
values = [v for v in values if isinstance(v, (int, float))]
return statistics.median(values) if values else None
def percentile(values, p):
values = sorted(v for v in values if isinstance(v, (int, float)))
if not values:
return None
idx = min(len(values) - 1, int(round((p / 100.0) * (len(values) - 1))))
return values[idx]
def summarize(rows):
ok = [r for r in rows if r.get("status") == "done"]
lat = [r.get("elapsed_s") or 0 for r in rows]
return {
"runs": len(rows),
"success_rate": round(len(ok) / len(rows), 4) if rows else None,
"status_counts": dict(collections.Counter(r.get("status") or "unknown" for r in rows)),
"latency_s": {
"median": round(median(lat), 1) if median(lat) is not None else None,
"p95": percentile(lat, 95),
"max": max(lat) if lat else None,
},
"output_tokens": {
"median": median([r.get("out_tokens") for r in rows]),
"p95": percentile([r.get("out_tokens") for r in rows], 95),
},
"cache_read_tokens": {"median": median([r.get("cache_read") for r in rows])},
"produced_files_share": round(
sum(1 for r in rows if (r.get("n_files") or 0) > 0) / len(rows), 4
) if rows else None,
"hit_run_cap_share": round(
sum(1 for r in rows if (r.get("elapsed_s") or 0) >= RUN_CAP_S - 60) / len(rows), 4
) if rows else None,
}
def by(rows, key):
groups = collections.defaultdict(list)
for r in rows:
groups[r.get(key) or "unspecified"].append(r)
out = {}
for name, g in sorted(groups.items(), key=lambda kv: -len(kv[1])):
out[name] = {
"runs": len(g),
"success_rate": round(sum(1 for r in g if r.get("status") == "done") / len(g), 4),
"latency_s_median": round(median([r.get("elapsed_s") for r in g]) or 0, 1),
"output_tokens_median": median([r.get("out_tokens") for r in g]),
}
return out
def render_md(agg):
L = []
L.append("# agent-evals — run metrics over a real agent corpus\n")
L.append(f"Corpus: **{agg['overall']['runs']} runs**, one observation per agent run "
"(not per task). Aggregates only — no task text.\n")
o = agg["overall"]
L.append("## Overall\n")
L.append(f"- Success rate (`done`): **{o['success_rate']:.1%}**")
L.append(f"- Latency: median **{o['latency_s']['median']:.0f}s**, p95 **{o['latency_s']['p95']}s**, "
f"max **{o['latency_s']['max']:.0f}s**")
L.append(f"- Output tokens: median **{o['output_tokens']['median']}**")
L.append(f"- Runs that produced files: **{o['produced_files_share']:.1%}**")
L.append(f"- Runs that hit the pipeline time cap: **{o['hit_run_cap_share']:.1%}**")
L.append(f"- Statuses: " + ", ".join(f"`{k}` {v}" for k, v in o["status_counts"].items()))
for dim, title in (("by_model", "By model"), ("by_worker", "By worker"), ("by_lane", "By lane")):
L.append(f"\n## {title}\n")
L.append("| value | runs | success | median latency | median out tokens |")
L.append("|---|---|---|---|---|")
for name, s in agg[dim].items():
L.append(f"| {name} | {s['runs']} | {s['success_rate']:.1%} | "
f"{s['latency_s_median']:.0f}s | {s['output_tokens_median']} |")
L.append("\n## What these numbers do and do not say\n")
L.append("- The corpus measures cost, time and outcome of runs. It does **not** measure "
"answer quality — that needs a separate grader with its own ground truth.")
L.append("- Hitting the time cap is a property of the harness under test, not an error of the model; "
"such runs are reported separately, not excluded.")
L.append("- Report length is not quality and is not used as a quality proxy here.")
L.append("- Effort level is missing in early records, so effort comparisons are underpowered.")
return "\n".join(L) + "\n"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--corpus", required=True)
ap.add_argument("--out", default=".")
ap.add_argument("--json-only", action="store_true")
args = ap.parse_args()
rows, bad = load(args.corpus)
if not rows:
print("no readable rows", file=sys.stderr)
return 2
os.makedirs(args.out, exist_ok=True)
agg = {
"overall": summarize(rows),
"by_model": by(rows, "model"),
"by_worker": by(rows, "worker"),
"by_lane": by(rows, "lane"),
"parse_errors": bad,
"policy": "aggregates only; task text, prompts and reports are never emitted",
}
json.dump(agg, open(os.path.join(args.out, "aggregate.json"), "w", encoding="utf-8"),
ensure_ascii=False, indent=2)
print("aggregate.json written:", os.path.join(args.out, "aggregate.json"))
if not args.json_only:
md = render_md(agg)
open(os.path.join(args.out, "report.md"), "w", encoding="utf-8").write(md)
print("report.md written")
return 0
if __name__ == "__main__":
raise SystemExit(main())