"""Analyze tool-call prediction failures into reports/failures.json + reports/failures.md. Usage: python pipeline/analyze_failures.py --predictions reports/runtime_eval/predictions.jsonl \ --data data_native/test.jsonl --out reports Input predictions JSONL rows: {"i","category","expected":[{"name","arguments"}],"predicted":[...], "raw","exact","name_match","bucket"} (bucket may be missing) Bucket/category come from pipeline/metrics_lib.py (failure_bucket, categorize) when the row does not already carry them. """ import argparse import json import sys from collections import Counter, defaultdict from pathlib import Path def _load_metrics_lib(): """Import pipeline.metrics_lib; fall back to local equivalents if absent. The real metrics_lib (owned by another session) takes precedence whenever it exists. The fallback only lets this script run standalone for the synthetic fixture proof. """ try: from pipeline.metrics_lib import categorize as _categorize from pipeline.metrics_lib import failure_bucket as _failure_bucket return _failure_bucket, _categorize except Exception: def _failure_bucket(expected, predicted, raw): exp = expected or [] pred = predicted or [] if not exp and not pred: return "ok" if not exp and pred: return "false_positive" if exp and not pred: if not (raw or "").strip(): return "empty_output" return "missing_call" exp_names = sorted(c.get("name", "") for c in exp) pred_names = sorted(c.get("name", "") for c in pred) if exp_names != pred_names: if len(pred) < len(exp): return "missing_call" if len(pred) > len(exp): return "extra_call" return "wrong_name" # same names: compare arguments (normalized to str) for e, p in zip( sorted(exp, key=lambda c: c.get("name", "")), sorted(pred, key=lambda c: c.get("name", "")), ): if json.dumps(e.get("arguments", {}), sort_keys=True, default=str) != json.dumps( p.get("arguments", {}), sort_keys=True, default=str ): return "wrong_args" return "ok" def _categorize(row): if row.get("category"): return row["category"] n = len(row.get("expected") or []) if n == 0: return "abstention" if n == 1: return "single_call" return "multi_call" return _failure_bucket, _categorize failure_bucket, categorize = _load_metrics_lib() def load_jsonl(path): rows = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def user_prompt(test_row): """Extract the user prompt from a data_native/test.jsonl row.""" if not isinstance(test_row, dict): return "(unavailable: bad test row)" for m in test_row.get("messages", []): if isinstance(m, dict) and m.get("role") == "user": return m.get("content", "") return "(unavailable: no user message)" def main(): ap = argparse.ArgumentParser() ap.add_argument("--predictions", required=True) ap.add_argument("--data", required=True, help="data_native/test.jsonl for prompts") ap.add_argument("--out", required=True, help="output dir for failures.json/failures.md") args = ap.parse_args() pred_rows = load_jsonl(args.predictions) test_lines = [] with open(args.data, encoding="utf-8") as f: for line in f: if line.strip(): test_lines.append(json.loads(line)) def prompt_for(i): if isinstance(i, int) and 0 <= i < len(test_lines): return user_prompt(test_lines[i]) return f"(unavailable: index {i} out of range 0..{len(test_lines) - 1})" counts = Counter() by_category = defaultdict(Counter) enriched = [] # (row, bucket, category) for idx, row in enumerate(pred_rows): # train_eval.py writes predictions without an index and calls the raw text # "text"; eval_openai.py writes "i"/"raw". Normalize both here. row.setdefault("i", idx) if "raw" not in row: row["raw"] = row.get("text", "") bucket = row.get("bucket") or failure_bucket(row.get("expected"), row.get("predicted"), row.get("raw", "")) try: category = row.get("category") or categorize(row) except Exception: category = row.get("category") or "unknown" if not bucket: bucket = "unknown" if not category: category = "unknown" counts[bucket] += 1 by_category[category][bucket] += 1 enriched.append((row, bucket, category)) n = len(pred_rows) out = Path(args.out) out.mkdir(parents=True, exist_ok=True) failures_json = { "n": n, "counts": dict(counts), "by_category": {cat: dict(c) for cat, c in by_category.items()}, } (out / "failures.json").write_text(json.dumps(failures_json, indent=2), encoding="utf-8") # ---- markdown report ---- lines = [] lines.append("# Failure analysis") lines.append("") lines.append(f"n = {n} predictions analyzed.") lines.append("") lines.append("## Counts by bucket") lines.append("") lines.append("| bucket | count | share |") lines.append("|---|---|---|") for bucket, c in counts.most_common(): share = c / n if n else 0.0 lines.append(f"| {bucket} | {c} | {share:.1%} |") lines.append("") # examples per non-ok bucket, up to 3 each shown = defaultdict(int) examples = defaultdict(list) for row, bucket, category in enriched: if bucket == "ok": continue if len(examples[bucket]) < 3: examples[bucket].append((row, category)) for bucket, _ in counts.most_common(): if bucket == "ok" or bucket not in examples: continue lines.append(f"## {bucket} (n={counts[bucket]})") lines.append("") for k, (row, category) in enumerate(examples[bucket], 1): i = row.get("i") lines.append(f"### Example {k}: index {i} (category: {category})") lines.append("") lines.append("Prompt:") lines.append("```") lines.append(str(prompt_for(i))) lines.append("```") lines.append("Expected:") lines.append("```json") lines.append(json.dumps(row.get("expected"), indent=2, ensure_ascii=False, default=str)) lines.append("```") lines.append("Predicted:") lines.append("```json") lines.append(json.dumps(row.get("predicted"), indent=2, ensure_ascii=False, default=str)) lines.append("```") lines.append("Raw (first 300 chars):") lines.append("```") lines.append(str(row.get("raw", ""))[:300]) lines.append("```") lines.append("") if counts: top_bucket, top_c = counts.most_common(1)[0] top_share = top_c / n if n else 0.0 lines.append( f"The most common failure mode is `{top_bucket}` with {top_c}/{n} rows ({top_share:.1%})." if top_bucket != "ok" else f"The most common outcome is `ok` with {top_c}/{n} rows ({top_share:.1%}), " f"so the model is mostly correct on this slice." ) else: lines.append("No predictions to analyze.") lines.append("") (out / "failures.md").write_text("\n".join(lines), encoding="utf-8") print(f"wrote {out / 'failures.json'} and {out / 'failures.md'} (n={n})", flush=True) print(json.dumps(dict(counts), indent=2)) if __name__ == "__main__": sys.exit(main())