Datasets:
Download analyze.py from tesraghavan/agent-trace: direct link, hf CLI and curl.
- Browser
- Download file 6.53 kB
-
https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/analyze.py
- Command line
-
hf download hf://datasets/tesraghavan/agent-trace/analyze.py
-
curl -L -o analyze.py https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/analyze.py
6.53 kB
| """Analyze collected traces and print summary statistics.""" | |
| import argparse | |
| import json | |
| import sys | |
| from collections import Counter | |
| from pathlib import Path | |
| def load_traces(path: str) -> list[dict]: | |
| traces = [] | |
| with open(path) as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| traces.append(json.loads(line)) | |
| return traces | |
| def print_section(title: str): | |
| print(f"\n{'=' * 60}") | |
| print(f" {title}") | |
| print(f"{'=' * 60}") | |
| def percentile(values: list[float], p: int) -> float: | |
| if not values: | |
| return 0.0 | |
| k = (len(values) - 1) * p / 100 | |
| f = int(k) | |
| c = f + 1 if f + 1 < len(values) else f | |
| return values[f] + (k - f) * (values[c] - values[f]) | |
| def analyze(traces: list[dict]): | |
| # ── Overview ── | |
| print_section("Overview") | |
| n = len(traces) | |
| all_spans = [s for t in traces for s in t.get("spans", [])] | |
| all_steps = [s for t in traces for s in t.get("llm_steps", [])] | |
| print(f" Traces: {n}") | |
| print(f" Tool spans: {len(all_spans)}") | |
| print(f" LLM steps: {len(all_steps)}") | |
| models = Counter(t.get("model") for t in traces) | |
| for model, count in models.most_common(): | |
| print(f" Model: {model} ({count} traces)") | |
| sources = Counter(t.get("metadata", {}).get("source", "unknown") for t in traces) | |
| for src, count in sources.most_common(): | |
| print(f" Source: {src} ({count} traces)") | |
| # ── Trace duration ── | |
| print_section("Trace Duration") | |
| durations = sorted([t["total_duration_ms"] for t in traces if t.get("total_duration_ms")]) | |
| if durations: | |
| print(f" Min: {durations[0]:>10.0f} ms") | |
| print(f" P25: {percentile(durations, 25):>10.0f} ms") | |
| print(f" Median: {percentile(durations, 50):>10.0f} ms") | |
| print(f" P75: {percentile(durations, 75):>10.0f} ms") | |
| print(f" P95: {percentile(durations, 95):>10.0f} ms") | |
| print(f" Max: {durations[-1]:>10.0f} ms") | |
| print(f" Total: {sum(durations)/1000:>10.1f} s") | |
| # ── Steps per trace ── | |
| print_section("Steps per Trace") | |
| steps_per = sorted([len(t.get("llm_steps", [])) for t in traces]) | |
| spans_per = sorted([len(t.get("spans", [])) for t in traces]) | |
| if steps_per: | |
| step_counts = Counter(steps_per) | |
| print(f" LLM steps: min={steps_per[0]}, median={percentile(steps_per, 50):.0f}, max={steps_per[-1]}") | |
| print(f" Tool spans: min={spans_per[0]}, median={percentile(spans_per, 50):.0f}, max={spans_per[-1]}") | |
| print(f" Distribution (LLM steps):") | |
| for count in sorted(step_counts): | |
| bar = "#" * step_counts[count] | |
| print(f" {count:>2} steps: {step_counts[count]:>3} traces {bar}") | |
| # ── Tool usage ── | |
| print_section("Tool Usage") | |
| tool_counts = Counter(s["tool_name"] for s in all_spans) | |
| tool_durations: dict[str, list[float]] = {} | |
| for s in all_spans: | |
| name = s["tool_name"] | |
| tool_durations.setdefault(name, []).append(s["duration_ms"]) | |
| for tool, count in tool_counts.most_common(): | |
| durs = sorted(tool_durations[tool]) | |
| med = percentile(durs, 50) | |
| print(f" {tool}: {count} calls, median={med:.1f}ms, total={sum(durs)/1000:.1f}s") | |
| # ── Token usage ── | |
| print_section("Token Usage") | |
| input_tokens = [s.get("input_tokens", 0) for s in all_steps if s.get("input_tokens")] | |
| output_tokens = [s.get("output_tokens", 0) for s in all_steps if s.get("output_tokens")] | |
| if input_tokens: | |
| print(f" Input tokens: total={sum(input_tokens):,}, mean={sum(input_tokens)/len(input_tokens):,.0f}") | |
| if output_tokens: | |
| print(f" Output tokens: total={sum(output_tokens):,}, mean={sum(output_tokens)/len(output_tokens):,.0f}") | |
| if input_tokens and output_tokens: | |
| print(f" Total tokens: {sum(input_tokens) + sum(output_tokens):,}") | |
| # ── Reasoning ── | |
| print_section("Reasoning Content") | |
| steps_with_reasoning = [s for s in all_steps if s.get("reasoning_content")] | |
| reasoning_lengths = [len(s["reasoning_content"]) for s in steps_with_reasoning] | |
| print(f" Steps with reasoning: {len(steps_with_reasoning)}/{len(all_steps)}") | |
| if reasoning_lengths: | |
| reasoning_lengths.sort() | |
| print(f" Reasoning length (chars): min={reasoning_lengths[0]}, median={percentile(reasoning_lengths, 50):.0f}, max={reasoning_lengths[-1]}") | |
| print(f" Total reasoning chars: {sum(reasoning_lengths):,}") | |
| # ── Telemetry (rusage) ── | |
| print_section("Telemetry (resource usage)") | |
| cpu_times = [] | |
| max_rss = [] | |
| for s in all_spans: | |
| tel = s.get("telemetry", {}) | |
| cpu = tel.get("user_time_s", 0) + tel.get("system_time_s", 0) | |
| if cpu > 0: | |
| cpu_times.append(cpu) | |
| rss = tel.get("max_rss_bytes", 0) | |
| if rss > 0: | |
| max_rss.append(rss) | |
| if cpu_times: | |
| cpu_times.sort() | |
| print(f" Spans with CPU time: {len(cpu_times)}/{len(all_spans)}") | |
| print(f" CPU time (s): min={cpu_times[0]:.4f}, median={percentile(cpu_times, 50):.4f}, max={cpu_times[-1]:.4f}") | |
| else: | |
| print(f" No spans with CPU time (PythonInterpreterTool runs in-process)") | |
| if max_rss: | |
| max_rss.sort() | |
| max_rss_mb = [r / 1024 / 1024 for r in max_rss] | |
| print(f" Max RSS (MB): min={max_rss_mb[0]:.1f}, median={percentile(max_rss_mb, 50):.1f}, max={max_rss_mb[-1]:.1f}") | |
| # ── Errors ── | |
| print_section("Errors") | |
| error_spans = [s for s in all_spans if s.get("exit_code", 0) != 0] | |
| # NOTE: LLMStep currently does not include an `error` field, so avoid | |
| # printing a misleading zero-valued metric until the schema supports it. | |
| print(f" Tool spans with errors: {len(error_spans)}/{len(all_spans)}") | |
| print(f" LLM step errors: n/a (current schema does not record them)") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Analyze collected traces") | |
| parser.add_argument("input", nargs="?", default="datasets/mbpp_traces.jsonl", help="Input JSONL file") | |
| args = parser.parse_args() | |
| path = Path(args.input) | |
| if not path.exists(): | |
| print(f"File not found: {path}", file=sys.stderr) | |
| sys.exit(1) | |
| traces = load_traces(str(path)) | |
| if not traces: | |
| print("No traces found", file=sys.stderr) | |
| sys.exit(1) | |
| print(f"Analyzing {path} ({len(traces)} traces)") | |
| analyze(traces) | |
| print() | |
| if __name__ == "__main__": | |
| main() | |