Datasets:
File size: 5,324 Bytes
12f64c4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | """Beyond pass rate: cost, time, steps and waste per model from a LayerLens trace bundle.
Usage: python trace_efficiency.py traces.jsonl | traces-<env>.zip --set <task_set> [--after ISO] [--volume 10000]
[--pass-rule "<python expr over r>"]
Writes efficiency_runs.csv (one row per run) and efficiency_summary.csv (one row per model and task),
and prints the summary. A run's `ok` defaults to the platform judge verdict == "pass".
"""
import argparse, csv, json, statistics, zipfile
from collections import defaultdict
from datetime import datetime
def ts(s): return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
def pct(a, p):
a = sorted(a); return a[min(len(a) - 1, int(p * (len(a) - 1) + 0.5))] if a else None
def iter_attempts(path):
"""Yield attempts from a LayerLens trace bundle (.zip) or a traces.jsonl file."""
if path.endswith(".zip"):
with zipfile.ZipFile(path) as z:
for n in z.namelist():
if n.startswith("attempts/"):
yield json.loads(z.read(n))
else:
with open(path) as f:
for line in f:
if line.strip():
yield json.loads(line)
def run_row(att):
tr = att["transcript"]; t0, tn = ts(tr[0]["created_at"]), ts(tr[-1]["created_at"])
think = tool = 0.0; turns = search = errors = dups = 0; seen = set(); tools_used = set()
for prev, m in zip(tr, tr[1:]):
dt = ts(m["created_at"]) - ts(prev["created_at"])
if m["role"] == "assistant": turns += 1; think += dt
if m["role"] == "tool" and m.get("tool_call"):
tool += dt; name = m["tool_call"]["tool"]; args = m["tool_call"].get("args") or {}
out = m["content"] if isinstance(m["content"], str) else json.dumps(m["content"])
if name == "tool_search": search += 1; continue
tools_used.add(name)
if any(k in out.lower() for k in ('"error"', "error:", "not_found", "bad_arguments")): errors += 1
key = name + json.dumps(args, sort_keys=True)
dups += key in seen; seen.add(key)
u = att.get("usage") or {}
return dict(attempt_id=att["attempt_id"], model=att["model"], task=att["task"][:80],
verdict=att.get("verdict"), ok=att.get("verdict") == "pass", stop=att.get("stop_reason"),
cost=u.get("cost_usd", att.get("cost_usd") or 0.0), in_tok=u.get("input_tokens", 0),
out_tok=u.get("output_tokens", 0), tool_calls=u.get("tool_calls", 0), search_calls=search,
error_calls=errors, duplicate_calls=dups, distinct_tools=len(tools_used), turns=turns,
wall_s=round(tn - t0, 1), agent_s=round(think, 1), env_s=round(tool, 1),
answer_chars=len(str(att.get("agent_claimed") or "")))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("bundle"); ap.add_argument("--set", required=True); ap.add_argument("--after", default="")
ap.add_argument("--volume", type=int, default=10000); ap.add_argument("--pass-rule", default="")
a = ap.parse_args(); runs = []
for att in iter_attempts(a.bundle):
if att.get("set_name") != a.set or str(att.get("created_at", "")) < a.after: continue
r = run_row(att)
if a.pass_rule: r["ok"] = bool(eval(a.pass_rule, {}, {"r": r, "att": att}))
runs.append(r)
if not runs: raise SystemExit("no attempts matched")
with open("efficiency_runs.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(runs[0])); w.writeheader(); w.writerows(runs)
groups = defaultdict(list)
for r in runs: groups[(r["model"], r["task"])].append(r)
summary = []
for (model, task), rs in sorted(groups.items()):
c = [r["cost"] for r in rs]; ok = sum(r["ok"] for r in rs); total = sum(c)
summary.append(dict(model=model, task=task, runs=len(rs), ok=ok,
cost_p50=round(pct(c, .5), 4), cost_p90=round(pct(c, .9), 4),
cost_per_ok=round(total / ok, 4) if ok else None,
cost_at_volume=round(statistics.mean(c) * a.volume, 2),
agent_s_p50=pct([r["agent_s"] for r in rs], .5), env_s_p50=pct([r["env_s"] for r in rs], .5),
wall_s_p50=pct([r["wall_s"] for r in rs], .5),
tool_calls_mean=round(statistics.mean(r["tool_calls"] for r in rs), 1),
turns_mean=round(statistics.mean(r["turns"] for r in rs), 1),
in_tok_mean=round(statistics.mean(r["in_tok"] for r in rs)),
out_tok_mean=round(statistics.mean(r["out_tok"] for r in rs)),
error_calls_per_run=round(statistics.mean(r["error_calls"] for r in rs), 2),
duplicate_calls_per_run=round(statistics.mean(r["duplicate_calls"] for r in rs), 2),
answer_chars_mean=round(statistics.mean(r["answer_chars"] for r in rs)),
stops=dict((s, sum(r["stop"] == s for r in rs)) for s in {r["stop"] for r in rs})))
with open("efficiency_summary.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(summary[0])); w.writeheader(); w.writerows(summary)
for s in summary: print(s)
env = sum(r["env_s"] for r in runs); wall = sum(r["wall_s"] for r in runs) or 1
print(f"runs {len(runs)}; environment share of wall time {env / wall:.0%}")
if __name__ == "__main__":
main()
|