Download auto-impl/analysis/trace_analysis/narrative.py from Jerry999/RSIChallenge: direct link, hf CLI and curl.
- Browser
- Download file 5.48 kB
-
https://huggingface.co/datasets/Jerry999/RSIChallenge/resolve/main/auto-impl/analysis/trace_analysis/narrative.py
- Command line
-
hf download hf://datasets/Jerry999/RSIChallenge/auto-impl/analysis/trace_analysis/narrative.py
-
curl -L -o narrative.py https://huggingface.co/datasets/Jerry999/RSIChallenge/resolve/main/auto-impl/analysis/trace_analysis/narrative.py
5.48 kB
| """Readable narratives: what a run actually did, in order, on one page. | |
| The numeric features say how much; this says what. Each narrative keeps only | |
| the load-bearing moments -- the plan it wrote down, every training and | |
| evaluation job, every error and the move that followed it, and the summary it | |
| signed off with -- so a run that took ten hours and 180 tool calls can be read | |
| in a minute and compared against another. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import textwrap | |
| from .parse import Run, ToolCall | |
| from .taxonomy import classify_action | |
| MILESTONE_ACTIONS = {"train", "generate", "eval_official", "eval_custom", "data_prep"} | |
| SCORE_RES = [ | |
| re.compile(r"(?<![\w_])accuracy\s{2,}([01]?\.\d+)"), | |
| re.compile(r"(?<![\w_])[\"']accuracy[\"']\s*:\s*([01]?\.\d+)"), | |
| ] | |
| def _hhmm(t: float) -> str: | |
| return f"{int(t // 3600):d}:{int(t % 3600) // 60:02d}" | |
| def _one_line(s: str, n: int = 150) -> str: | |
| s = re.sub(r"\s+", " ", (s or "").strip()) | |
| return s[:n] + ("…" if len(s) > n else "") | |
| def _scores_in(text: str) -> list[str]: | |
| return [m for pat in SCORE_RES for m in pat.findall(text or "")] | |
| def _error_kind(tc: ToolCall) -> str | None: | |
| """Name the failure in a tool result, if there is one. | |
| `is_error` alone is too narrow: a training script that dies with a | |
| traceback still exits through a normal tool result, and that is exactly | |
| the kind of failure we want to watch the agent recover from. | |
| """ | |
| t = tc.result_text or "" | |
| if "CUDA out of memory" in t or "OutOfMemoryError" in t: | |
| return "CUDA OOM" | |
| if re.search(r"^Traceback \(most recent call last\)", t, re.M): | |
| last = [ln for ln in t.strip().splitlines() if ln.strip()][-1:] | |
| return f"exception: {_one_line(last[0], 90)}" if last else "exception" | |
| if "ModuleNotFoundError" in t or "ImportError" in t: | |
| return "missing package" | |
| if "EAI_AGAIN" in t or "Temporary failure in name resolution" in t: | |
| return "network blocked (offline sandbox)" | |
| if "No space left on device" in t: | |
| return "disk full" | |
| if tc.is_error: | |
| return f"tool error: {_one_line(t, 90)}" | |
| return None | |
| def narrative(run: Run) -> str: | |
| out: list[str] = [] | |
| out.append(f"# {run.run_id}") | |
| out.append("") | |
| out.append(f"- task: **{run.task}**, base model: **{run.base_model}**") | |
| out.append(f"- harness accuracy: **{run.accuracy}**") | |
| out.append(f"- wall clock: {_hhmm(run.wall_s)}, tool calls: {len(run.tool_calls)}") | |
| if run.result: | |
| out.append( | |
| f"- terminal: {run.result.get('terminal_reason')} " | |
| f"(api_error={run.result.get('api_error_status')}), " | |
| f"cost ${run.result.get('total_cost_usd', 0):.2f}" | |
| ) | |
| out.append("") | |
| # The plan, as the agent wrote it down. | |
| todos = [tc for tc in run.tool_calls if tc.name in ("TaskCreate", "TaskUpdate")] | |
| if todos: | |
| out.append("## Plan as first written") | |
| seen = 0 | |
| for tc in todos: | |
| desc = tc.inp.get("description") or tc.inp.get("prompt") or json.dumps(tc.inp)[:200] | |
| out.append(f"- {_one_line(desc, 120)}") | |
| seen += 1 | |
| if seen >= 12: | |
| break | |
| out.append("") | |
| first_text = next( | |
| ( | |
| c.get("text", "") | |
| for ev in run.events | |
| if ev.kind == "assistant" | |
| for c in (ev.raw.get("message", {}).get("content") or []) | |
| if isinstance(c, dict) and c.get("type") == "text" and len(c.get("text", "")) > 80 | |
| ), | |
| "", | |
| ) | |
| if first_text: | |
| out.append("## First stated intent") | |
| out.append(textwrap.indent(_one_line(first_text, 700), "> ")) | |
| out.append("") | |
| out.append("## Milestones") | |
| out.append("") | |
| out.append("| t | action | what | scores seen |") | |
| out.append("|---|---|---|---|") | |
| for tc in run.tool_calls: | |
| act = classify_action(tc) | |
| if act not in MILESTONE_ACTIONS: | |
| continue | |
| payload = tc.command or tc.inp.get("file_path", "") | |
| scores = _scores_in(tc.result_text) | |
| out.append( | |
| f"| {_hhmm(tc.t_rel)} | {act} | `{_one_line(payload, 110)}` | " | |
| f"{', '.join(scores[:4]) if scores else ''} |" | |
| ) | |
| out.append("") | |
| out.append("## Failures and what happened next") | |
| out.append("") | |
| n = 0 | |
| for i, tc in enumerate(run.tool_calls): | |
| kind = _error_kind(tc) | |
| if not kind: | |
| continue | |
| n += 1 | |
| nxt = run.tool_calls[i + 1] if i + 1 < len(run.tool_calls) else None | |
| follow = _one_line(nxt.text_payload, 140) if nxt else "(end of run)" | |
| out.append(f"- **{_hhmm(tc.t_rel)} {kind}**") | |
| out.append(f" - was running: `{_one_line(tc.text_payload, 120)}`") | |
| out.append(f" - next move: `{follow}`") | |
| if n >= 25: | |
| out.append(f"- … and more (showing first 25)") | |
| break | |
| if n == 0: | |
| out.append("_none detected_") | |
| out.append("") | |
| if run.final_message: | |
| out.append("## Final summary the agent wrote") | |
| out.append("") | |
| out.append(run.final_message) | |
| out.append("") | |
| return "\n".join(out) | |
| def write_all(runs: list[Run], out_dir: str) -> None: | |
| os.makedirs(out_dir, exist_ok=True) | |
| for r in runs: | |
| with open(os.path.join(out_dir, f"{r.run_id}.md"), "w") as fh: | |
| fh.write(narrative(r)) | |
| print(f" wrote {len(runs)} narratives to {out_dir}") | |