SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Feat: Add quick-stats tool (#1125)
Kilian Lieretbe0def1e3685
diff --git a/sweagent/run/quick_stats.py b/sweagent/run/quick_stats.pynew file mode 100644index 00000000..20192d32--- /dev/null+++ b/sweagent/run/quick_stats.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+import argparse+import collections+import json+from pathlib import Path++import numpy as np++from sweagent.utils.log import get_logger++"""Calculate statistics from .traj files."""++logger = get_logger("quick-stats", emoji="📊")+++def quick_stats(directory: Path | str = ".") -> str:+ """Calculate statistics from .traj files.++ Args:+ directory: Directory to search for .traj files (default: current directory)++ Returns:+ str: Summary of statistics+ """+ directory = Path(directory)+ # Find all .traj files+ traj_files = list(directory.glob("**/*.traj"))++ if not traj_files:+ logger.warning("No .traj files found in %s", directory)+ return "No .traj files found."++ # Extract api_calls from each file+ api_calls = []+ files_by_exit_status = collections.defaultdict(list)++ for file_path in traj_files:+ try:+ data = json.loads(file_path.read_text())+ # Extract the api_calls value using dictionary path+ if "info" in data and "model_stats" in data["info"] and "api_calls" in data["info"]["model_stats"]:+ api_calls.append(data["info"]["model_stats"]["api_calls"])+ if "info" in data and "exit_status" in data["info"]:+ status = data["info"]["exit_status"]+ files_by_exit_status[status].append(file_path)+ except Exception as e:+ logger.error("Error processing %s: %s", file_path, e)++ files_by_exit_status = dict(sorted(files_by_exit_status.items(), key=lambda x: len(x[1]), reverse=True))++ if not api_calls:+ logger.warning("No valid api_calls data found in the .traj files")+ return "No valid api_calls data found in the .traj files."++ # Calculate and return the average+ logger.info("Exit statuses:")+ # Sort exit statuses by count (highest to lowest)+ for status, files in files_by_exit_status.items():+ logger.info("%s: %d", status, len(files))++ average_api_calls = np.mean(api_calls)+ logger.info("Avg api calls: %s", average_api_calls)++ # Print exit statuses in the requested format+ result = []+ for status, files in files_by_exit_status.items():+ result.append(f"\n## `{status}`\n")+ # Extract unique subdirectories instead of full paths+ subdirs = {str(Path(file_path).parent) for file_path in files}+ result.append(" ".join(subdirs))++ return "\n".join(result)+++def get_cli_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "directory",+ type=Path,+ nargs="?",+ default=Path("."),+ help="Directory to search for .traj files (default: current directory)",+ )+ return parser+++def run_from_cli(args: list[str] | None = None) -> None:+ cli_parser = get_cli_parser()+ cli_args = cli_parser.parse_args(args)++ result = quick_stats(cli_args.directory)+ print(result)+++if __name__ == "__main__":+ run_from_cli()diff --git a/sweagent/run/run.py b/sweagent/run/run.pyindex 3168a278..1806187d 100644--- a/sweagent/run/run.py+++ b/sweagent/run/run.py@@ -25,6 +25,7 @@ Display usage instructions for a specific command:[bold][green]traj-to-demo[/green][/bold]: Convert a trajectory file to an easy to edit demo file.[bold][green]run-api[/green][/bold]: Run swe-agent as a backend for a GUI[bold][green]remove-unfinished[/green][/bold] or [bold][green]ru[/green][/bold]: Remove unfinished trajectories+[bold][green]quick-stats[/green][/bold] or [bold][green]qs[/green][/bold]: Calculate quick stats from a directory of trajectories"""import argparse@@ -55,6 +56,8 @@ def get_cli():"cr","remove-unfinished","ru",+ "quick-stats",+ "qs",],nargs="?",)@@ -125,6 +128,10 @@ def main(args: list[str] | None = None):from sweagent.run.remove_unfinished import run_from_cli as remove_unfinished_mainremove_unfinished_main(remaining_args)+ elif command in ["quick-stats", "qs"]:+ from sweagent.run.quick_stats import run_from_cli as quick_stats_main++ quick_stats_main(remaining_args)else:msg = f"Unknown command: {command}"raise ValueError(msg)diff --git a/test_config.yaml b/test_config.yamlnew file mode 100644index 00000000..59c9c680--- /dev/null+++ b/test_config.yaml@@ -0,0 +1,6 @@+agent:+ model:+ name: human+env:+ deployment:+ image: tinydiff --git a/tests/test_quick_stats.py b/tests/test_quick_stats.pynew file mode 100644index 00000000..d9ad0b16--- /dev/null+++ b/tests/test_quick_stats.py@@ -0,0 +1,42 @@+from __future__ import annotations++import json+import tempfile+from pathlib import Path++from sweagent.run.quick_stats import quick_stats+++def test_quick_stats_empty_directory():+ """Test that quick_stats handles empty directories properly."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ result = quick_stats(tmp_dir)+ assert result == "No .traj files found."+++def test_quick_stats_test_data(test_trajectories_path: Path):+ """Test that quick_stats works on the test data directory."""+ # Create a sample .traj file with required structure+ with tempfile.TemporaryDirectory() as tmp_dir:+ tmp_path = Path(tmp_dir)+ traj_file = tmp_path / "test.traj"++ # Create a minimal valid .traj file+ traj_data = {"info": {"model_stats": {"api_calls": 42}, "exit_status": "success"}}++ traj_file.write_text(json.dumps(traj_data))++ # Run quick_stats on the directory with our test file+ result = quick_stats(tmp_path)++ # Check that the result contains our exit status+ assert "## `success`" in result++ # Run quick_stats on the test_trajectories_path+ result = quick_stats(test_trajectories_path)++ # The result should not be empty when run on test data+ assert result != "No .traj files found."++ # The result should contain some exit status sections+ assert "## `" in result