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]
Main entry point in PATH; saving output files
Kilian Lieret1193d96775be
diff --git a/pyproject.toml b/pyproject.tomlindex 6e62f07a..fde28a13 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,6 +36,9 @@ classifiers = ["Programming Language :: Python :: 3 :: Only",]+[project.scripts]+sweagent = "sweagent.run.run:main"+[project.optional-dependencies]dev = ["mkdocs-material",diff --git a/run.py b/run.pydeleted file mode 100644index da10854f..00000000--- a/run.py+++ /dev/null@@ -1,366 +0,0 @@-from __future__ import annotations--# try:-# import rich-# except ModuleNotFoundError as e:-# msg = (-# "You probably either forgot to install the dependencies "-# "or forgot to activate your conda or virtual environment."-# )-# raise RuntimeError(msg) from e-import json-import logging-import re-import traceback-from argparse import ArgumentParser-from pprint import pprint--from sweagent.environment.config.deployment import DockerDeploymentConfig-from sweagent.run.hooks.abstract import RunHook-from sweagent.run.run_single import RunSingleActionConfig-from sweagent.utils.log import add_file_handler, get_logger--try:- from rich_argparse import RichHelpFormatter-except ImportError:- msg = "Please install the rich_argparse package with `pip install rich_argparse`."- raise ImportError(msg)-import datetime-from getpass import getuser-from pathlib import Path--import yaml-from pydantic import Field-from pydantic_settings import BaseSettings, CliApp-from rich.markdown import Markdown-from swebench.harness.constants import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION-from unidiff import PatchSet--from sweagent.agent.agents import Agent, AgentConfig-from sweagent.agent.models import ModelArguments-from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv--__doc__: str = """ Run inference. Usage examples:--```bash-# Run over a github issue:-python run.py --model_name "gpt4" --data_path "https://github.com/pvlib/pvlib-python/issues/1603" --config_file "config/default_from_url.yaml"-# Apply a patch in a local repository to an issue specified as Markdown file and run a custom installer script in the container-python run.py --model_name "gpt4" --data_path "/path/to/my_issue.md" --repo_path "/path/to/my/local/repo" --environment_setup "/path/to/setup.sh" --config_file "config/default_from_url.yaml" --apply_patch_locally-```--**For more information**: https://princeton-nlp.github.io/SWE-agent/usage/cl_tutorial/-"""---logger = get_logger("swe-agent-run")-logging.getLogger("simple_parsing").setLevel(logging.WARNING)---class ScriptArguments(BaseSettings):- """Configure the control flow of the run.py script"""-- environment: EnvironmentConfig = Field(..., default_factory=EnvironmentConfig)- agent: AgentConfig = Field(..., default_factory=AgentConfig)- actions: RunSingleActionConfig = Field(..., default_factory=RunSingleActionConfig)- # Only run instances that completely match this regex- instance_filter: str = ".*"- # Skip instances with existing trajectories- skip_existing: bool = True- # Suffix for the run name (used for example in trajectory directory naming)- suffix: str = ""- # Raise unhandled exceptions during the run (useful for debugging)- raise_exceptions: bool = False- # Dump the entire config to the log- print_config: bool = True- # Run the agent in CTF mode (SWE-agent: EnIGMA)- ctf: bool = False-- run_name: str = ""-- def model_post_init(self, __context):- if not self.run_name:- self.run_name = self._generate_run_name()-- def _generate_run_name(self) -> str:- """Generate a unique name for this run based on the arguments."""- model_name = self.agent.model.name.replace(":", "-")- # todo: Need to set this properly- data_stem = "todo" # get_data_path_name(self.environment.data_path)- # assert self.agent.config_file is not None # mypy- # config_stem = Path(self.agent.config_file).stem-- temp = self.agent.model.temperature- top_p = self.agent.model.top_p-- per_instance_cost_limit = self.agent.model.per_instance_cost_limit- # install_env = self.environment.install_environment-- return (- f"{model_name}__{data_stem}__t-{temp:.2f}__p-{top_p:.2f}"- + f"__c-{per_instance_cost_limit:.2f}"- + (f"__{self.suffix}" if self.suffix else "")- )---class _ContinueLoop(Exception):- """Used for internal control flow"""---class Main:- def __init__(self, args: ScriptArguments):- self.traj_dir = Path("trajectories") / Path(getuser()) / args.run_name- self.traj_dir.mkdir(parents=True, exist_ok=True)- timestamp = datetime.datetime.now().strftime("%y%m%d%H%M%S")- log_path = self.traj_dir / f"run-{timestamp}.log"- logger.info("Logging to %s", log_path)- add_file_handler(log_path)- if args.print_config:- dump = yaml.dump(args.model_dump())- logger.info(f"📙 Arguments: {dump}")- self.args = args- self.agent = Agent("primary", args.agent)- self.env = SWEEnv(args.environment)- self._save_arguments()- default_hooks = [- # SaveApplyPatchHook(),- # OpenPRHook(),- ]- self.hooks: list[RunHook] = []- for hook in default_hooks:- self.add_hook(hook)-- def add_hook(self, hook: RunHook):- hook.on_init(args=self.args, agent=self.agent, env=self.env, traj_dir=self.traj_dir)- self.hooks.append(hook)-- def run(self, index: int) -> None:- # Reset environment- instance_id = self.env.data[index]["instance_id"]- for hook in self.hooks:- hook.on_instance_start(index=index, instance=self.env.data[index])- assert isinstance(instance_id, str) # mypy- if self.should_skip(instance_id):- for hook in self.hooks:- hook.on_instance_skipped()- raise _ContinueLoop- logger.info("▶️ Beginning task " + str(index))-- observation, info = self.env.reset(index)- if info is None:- raise _ContinueLoop-- # Get info, patch information- issue = getattr(self.env, "query", None)- files = []- assert self.env.record is not None # mypy- if "patch" in self.env.record:- files = "\n".join([f"- {x.path}" for x in PatchSet(self.env.record["patch"]).modified_files])- # Get test files, F2P tests information- test_files = []- if "test_patch" in self.env.record:- test_patch_obj = PatchSet(self.env.record["test_patch"])- test_files = "\n".join([f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files])- tests = ""- if "FAIL_endTO_PASS" in self.env.record:- tests = "\n".join([f"- {x}" for x in self.env.record["FAIL_TO_PASS"]])-- setup_args = {"issue": issue, "files": files, "test_files": test_files, "tests": tests}- # challenge = self.env.challenge- # if challenge is not None:- # setup_args["flag_format"] = extract_flag_format(challenge["flag"])- # setup_args["name"] = challenge["name"]- # setup_args["description"] = challenge["description"]- # setup_args["category_friendly"] = challenge["category_friendly"]- # setup_args["points"] = challenge["points"]- # setup_args["files"] = challenge["files"] or "No files included in this challenge."- # setup_args["box"] = challenge.get("server_name")- # setup_args["port"] = challenge.get("port")- # setup_args["server_description"] = challenge.get("server_description")- info, trajectory = self.agent.run(- problem_statement=setup_args,- env=self.env,- observation=observation,- traj_dir=self.traj_dir,- )- challenge = None- self._save_predictions(instance_id, info, challenge)- for hook in self.hooks:- hook.on_instance_completed(info=info, trajectory=trajectory)-- def main(self):- for hook in self.hooks:- hook.on_start()- for index in range(len(self.env.data)):- try:- self.run(index)- except _ContinueLoop:- continue- except KeyboardInterrupt:- logger.info("Exiting InterCode environment...")- self.env.close()- break- except SystemExit:- logger.critical("❌ Exiting because SystemExit was called")- self.env.close()- logger.info("Container closed")- raise- except Exception as e:- logger.warning(traceback.format_exc())- if self.args.raise_exceptions:- self.env.close()- raise e- if self.env.record:- logger.warning(f"❌ Failed on {self.env.record['instance_id']}: {e}")- else:- logger.warning("❌ Failed on unknown instance")- self.env.reset_container()- continue- self.env.close()- for hook in self.hooks:- hook.on_end()-- def _save_arguments(self) -> None:- """Save the arguments to a yaml file to the run's trajectory directory."""- log_path = self.traj_dir / "args.yaml"-- if log_path.exists():- try:- other_args = ScriptArguments.model_validate(yaml.safe_load(log_path.read_text()))- if other_args != self.args:- logger.warning("**************************************************")- logger.warning("Found existing args.yaml with different arguments!")- logger.warning("**************************************************")- except Exception:- logger.warning(f"Failed to load existing args.yaml: {traceback.format_exc()}")-- log_path.write_text(yaml.dump(self.args.model_dump()))-- def should_skip(self, instance_id: str) -> bool:- """Check if we should skip this instance based on the instance filter and skip_existing flag."""- # Skip instances that don't match the instance filter- if re.match(self.args.instance_filter, instance_id) is None:- logger.info(f"⏭️ Instance filter not matched. Skipping instance {instance_id}")- return True-- # If flag is set to False, don't skip- if not self.args.skip_existing:- return False-- # Check if there's an existing trajectory for this instance- log_path = self.traj_dir / (instance_id + ".traj")- if not log_path.exists():- return False-- content = log_path.read_text()- if not content.strip():- logger.warning("Found empty trajectory: %s. Removing.", log_path)- log_path.unlink()- return False-- data = json.loads(content)- # If the trajectory has no exit status, it's incomplete and we will redo it- exit_status = data["info"].get("exit_status", None)- if exit_status == "early_exit" or exit_status is None:- logger.warning(f"Found existing trajectory with no exit status: {log_path}. Removing.")- log_path.unlink()- return False-- logger.info(f"⏭️ Skipping existing trajectory: {log_path}")- return True-- def _save_predictions(self, instance_id: str, info, challenge: dict[str, str] | None):- output_file = self.traj_dir / "all_preds.jsonl"- model_patch = info["submission"] if "submission" in info else None- datum = {- KEY_MODEL: Path(self.traj_dir).name,- KEY_INSTANCE_ID: instance_id,- KEY_PREDICTION: model_patch,- }- # if challenge is not None:- # challenge_datum = {- # "challenge_name": challenge["name"],- # "challenge_category": challenge["category"],- # "challenge_path": challenge["file_path"],- # }- # datum.update(challenge_datum)- with open(output_file, "a+") as fp:- print(json.dumps(datum), file=fp, flush=True)- logger.info(f"Saved predictions to {output_file}")---def get_args(args=None) -> ScriptArguments:- """Parse command line arguments and return a ScriptArguments object.-- Args:- args: Optional list of arguments to parse. If not provided, uses sys.argv.- """- # The defaults if no config file is provided- # Otherwise, the configs from the respective classes will be used- no_config_defaults = ScriptArguments(- suffix="",- environment=EnvironmentConfig(- deployment=DockerDeploymentConfig(),- # data_path="princeton-nlp/SWE-bench_Lite",- # split="dev",- # verbose=True,- # install_environment=True,- ),- skip_existing=True,- agent=AgentConfig(- system_template="",- instance_template="",- model=ModelArguments(- name="gpt4",- total_cost_limit=0.0,- per_instance_cost_limit=3.0,- temperature=0.0,- top_p=0.95,- ),- ),- actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),- ctf=False,- )-- parser = ArgumentParser(- description=Markdown(__doc__),- formatter_class=RichHelpFormatter,- )- parser.add_argument("--config", type=str, action="append", default=[])-- args, remaining_args = parser.parse_known_args(args)-- config_merged = {}- if args.config:- for _f in args.config:- _loaded = yaml.safe_load(Path(_f).read_text())- config_merged.update(_loaded)- else:- config_merged = no_config_defaults.model_dump()-- # args = ScriptArguments.model_validate(config_merged)- print("Config merged")- pprint(config_merged)- args = ScriptArguments.model_validate(config_merged)- return CliApp.run(ScriptArguments, remaining_args, **config_merged)- # args = CliApp.run(ScriptArguments, remaining_args, model_init_data=config_merged)-- # todo: Do we need this?- # Nicer yaml dumping of multiline strings- # def multiline_representer(dumper, data):- # """configures yaml for dumping multiline strings- # Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data- # """- # if data.count("\n") > 0: # check for multiline string- # return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")- # return dumper.represent_scalar("tag:yaml.org,2002:str", data)-- # yaml.add_representer(str, multiline_representer)---def main(args: ScriptArguments):- Main(args).main()---if __name__ == "__main__":- main(get_args())diff --git a/run_replay.py b/run_replay.pydeleted file mode 100644index 90d2d097..00000000--- a/run_replay.py+++ /dev/null@@ -1,138 +0,0 @@-"""Replay a trajectory"""--from __future__ import annotations--import json-import os-from argparse import ArgumentParser-from pathlib import Path-from typing import Any--import yaml--import run as runscript---def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix: str, *, forward_args: list[str]):- """-- Args:- traj_path (str): _description_- config_file (str): _description_- data_path (str): _description_- suffix (str): _description_- forward_args (List[str]): Passed to run.py-- Raises:- ValueError: Incorrect paths or other config issue-- Returns:- None- """- replay_action_trajs_path = "temp_replay.jsonl"-- # Open trajectory file, extract responses as actions- if traj_path.endswith(".yaml"):- traj_data = dict()- with open(traj_path) as f:- traj_data["history"] = yaml.safe_load(f)- else:- with open(traj_path) as file:- traj_data = json.load(file)- actions = [x["content"] for x in traj_data["history"] if x["role"] == "assistant"]- instance_id = traj_path.split("/")[-1].split(".")[0]- with open(replay_action_trajs_path, "w") as f:- print(json.dumps({instance_id: actions}), file=f, end="\n", flush=True)-- # Get data_path from args.yaml- if data_path is None:- args_path = Path(traj_path).parent / "args.yaml"- with open(args_path) as f:- args = yaml.safe_load(f)- data_path = args["environment"]["data_path"]-- # Identify the relevant task instance and create it- def create_task_instances_tmp_file(data: list[dict[str, Any]]) -> str:- """Helper function to create a temporary file to write task instances to.- Returns path to the temporary file.- """- data = [d for d in data if d["instance_id"] == instance_id]- tmp_path = instance_id + ".jsonl"- with open(tmp_path, "w") as f:- for d in data:- print(json.dumps(d), file=f, end="\n", flush=True)- return tmp_path-- is_other = False- is_ctf = False- if data_path.endswith(".jsonl"):- replay_task_instances_path = create_task_instances_tmp_file(- [json.loads(x) for x in Path(data_path).read_text().splitlines(keepends=True)],- )- elif data_path.endswith("challenge.json"):- replay_task_instances_path = data_path- is_other = True- is_ctf = True- elif data_path.endswith(".json"):- with open(data_path) as file:- data = json.load(file)- replay_task_instances_path = create_task_instances_tmp_file(data)- else:- # Assume data_path is a github url or local url- is_other = True- replay_task_instances_path = data_path-- # Call run.py via subprocess- run_args = [- "--config",- config_file,- f"environment.data_path={replay_task_instances_path}",- "environment.install_environment=True",- "agent.model.model_name=replay",- f"agent.model.replay_path={replay_action_trajs_path}",- *forward_args,- ]- if is_other:- # Not sure if this only applies to github urls for data_path- run_args.extend(["--skip_existing", "False"])- if suffix is not None:- run_args.extend(["--suffix", suffix])- if is_ctf:- run_args.extend(["--repo_path", str(Path(data_path).parent)])- run_args.extend(["--image_name", "sweagent/enigma:latest"])- script_args = runscript.get_args(run_args)- runscript.main(script_args)-- os.remove(replay_action_trajs_path)- if not is_other:- os.remove(replay_task_instances_path)---def main(- traj_path: str,- config_file: str,- data_path: str,- suffix: str,- *,- forward_args: list[str],-):- process_single_traj(traj_path, config_file, data_path, suffix, forward_args=forward_args)---def get_args(args=None):- parser = ArgumentParser(description=__doc__)- parser.add_argument("--traj_path", help="Path to trajectory to replay", required=True)- parser.add_argument("--config_file", help="Path to template", required=True)- parser.add_argument(- "--data_path",- help="(Optional) Path to data file containing task instances ref'ed by replay trajectories",- default=None,- )- parser.add_argument("--suffix", help="(Optional) Suffix argument appended to end of traj path", default=None)- args, remaining_args = parser.parse_known_args(args=args)- return args, remaining_args---if __name__ == "__main__":- args, remaining_args = get_args()- main(**vars(args), forward_args=remaining_args)diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 416728f1..be739de5 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -28,9 +28,9 @@ from sweagent.agent.parsing import FormatError, ParseFunction# from sweagent.agent.summarizer import SummarizerConfigfrom sweagent.agent.utils import _guard_multiline_input-from sweagent.environment.config.problem_statement import ProblemStatement+from sweagent.environment.config.problem_statement import ProblemStatement, ProblemStatementConfigfrom sweagent.environment.swe_env import SWEEnv-from sweagent.types import AgentInfo, History, HistoryItem, Trajectory, TrajectoryStep+from sweagent.types import AgentInfo, AgentRunResult, History, HistoryItem, Trajectory, TrajectoryStepfrom sweagent.utils.config import _convert_paths_to_abspathfrom sweagent.utils.log import get_logger@@ -207,7 +207,7 @@ class Agent:# Set in run methodself._env: SWEEnv | None = None- self._problem_statement: ProblemStatement | None = None+ self._problem_statement: ProblemStatement | ProblemStatementConfig | None = Noneself.traj_path: Path | None = None#: Number of attempts to solve the issue when using a review loop@@ -703,14 +703,6 @@ class Agent:command_files.append(datum)self._env.add_commands(command_files)- # todo: Move to SWEEnv?- def get_environment_vars(self, env: SWEEnv) -> dict[str, Any]:- """Get environment variables inside of the container"""- env_vars = dict()- for var in self.config.env_variables:- env_vars[var] = env.communicate(f"echo ${var}").strip()- return env_vars-def get_state(self) -> dict[str, str]:"""If a state command is defined, execute it in the environment and return the result as a dictionary."""if not self.config.state_command:@@ -771,12 +763,12 @@ class Agent:# todo: Set env already in setup?def run(self,- problem_statement: ProblemStatement,+ problem_statement: ProblemStatement | ProblemStatementConfig,env: SWEEnv,observation: str = "",traj_dir: Path = Path("."),init_model_stats: APIStats | None = None,- ) -> tuple[AgentInfo, Trajectory]:+ ) -> AgentRunResult:"""Run the agent on a problem instance. This method contains themain loop that repeatedly calls `self._step` until the problem is solved.@@ -786,10 +778,6 @@ class Agent:observation: Output from environment setuptraj_dir: Directory to save the trajectory toinit_model_stats: Initial model stats to use for the run.-- Returns:- If return_type is "info_trajectory", returns a tuple of- the info dictionary and the trajectory (list of dictionaries)."""self._problem_statement = problem_statementself._env = env@@ -816,4 +804,4 @@ class Agent:self.logger.info("Trajectory saved to %s", self.traj_path)- return self.info, self.trajectory+ return AgentRunResult(info=self.info, trajectory=self.trajectory)diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.pyindex 200e194c..524b65e2 100644--- a/sweagent/agent/commands.py+++ b/sweagent/agent/commands.py@@ -29,7 +29,8 @@ class Command(BaseModel):code: strname: strdocstring: str | None = None- end_name: str | None = None # if there is an end_name, then it is a multi-line command+ # if there is an end_name, then it is a multi-line command+ end_name: str | None = Nonearguments: dict | None = Nonesignature: str | None = Nonediff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.pyindex 4d6fd8bd..2a408c64 100644--- a/sweagent/environment/config/repo.py+++ b/sweagent/environment/config/repo.py@@ -17,6 +17,7 @@ class Repo(Protocol):"""Protocol for repository configurations."""base_commit: str+ repo_name: strdef copy(self, deployment: AbstractDeployment): ...diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex c94a388d..1507b9f7 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -39,7 +39,7 @@ class SWEEnv:self,*,deployment: AbstractDeployment,- repo: Repo | None,+ repo: Repo | RepoConfig | None,startup_commands: list[str],hooks: list[EnvHook] | None = None,_catch_errors: bool = False,@@ -61,7 +61,7 @@ class SWEEnv:def start(self) -> None:"""Start the environment"""- self._init_container()+ self._init_deployment()self._init_scripts()@classmethod@@ -89,12 +89,6 @@ class SWEEnv:for hook in self.hooks:getattr(hook, hook_name)(*args, **kwargs)- # @property- # def _repo_name(self) -> str:- # """Name of the local copy of the repository"""- # return self.record["repo"].replace("/", "__").replace(" ", "-").replace("'", "")-- # todo: Ideally move that to the RepoClassesdef _copy_repo(self) -> None:"""Clone/copy repository/codebase in container"""if self.repo is None:@@ -107,7 +101,7 @@ class SWEEnv:self._fire_hooks("on_copy_repo_started", self.repo)self.repo.copy(self.deployment)- # todo: have named return type here+ # todo: Get rid of return type here?def reset(self) -> tuple[str | None, dict]:"""Reset the container between each task instance.@@ -124,53 +118,22 @@ class SWEEnv:info: additional information (e.g. debugging information)"""info = {}-- ### Reset Container ###- # self._init_docker_compose()-- # Init docker network- # self._init_docker_network()-- # Clone repository if not already clonedself.communicate(input="cd /")self._copy_repo()-self._reset_repository()self._reset_environment_variables()-- # Set up environment- # self.communicate_with_handling(- # "source /root/miniconda3/etc/profile.d/conda.sh",- # error_msg="Failed to source conda",- # )-- # system = self.communicate("uname -s").strip().lower()- # arch = self.communicate("uname -m").strip().lower()- # if system == "linux" and arch == "x86_64":- # self.communicate_with_handling(- # "apt update; apt install build-essential -y",- # error_msg="Failed to install build-essential",- # timeout_duration=LONG_TIMEOUT,- # )-- # Call install environment helper function if specified- # if self.install_environment:self.on_environment_startup()- # Install mypy for linting purposes- # self.communicate_with_handling("pip install flake8", error_msg="Failed to install flake8 (lint library)")-- # Write any metadata to info if necessaryreturn None, infodef _reset_repository(self) -> None:"""Clean repository of any modifications + Checkout base commit"""if self.repo is not None:+ # todo: This is part of our commands, not the environmentstartup_commands = ["echo -n > /root/files_to_edit.txt",f"cd /{self.repo.repo_name}","export ROOT=$(pwd -P)",]- # if self.challenge is None:startup_commands += ["git status","git restore .",@@ -183,6 +146,7 @@ class SWEEnv:error_msg="Failed to clean repository",)+ # todo: This is part of our commands, not the environmentdef _reset_environment_variables(self) -> None:"""Reset environment variables (`CURRENT_FILE`) etc. within container"""cmd = [@@ -314,10 +278,10 @@ class SWEEnv:def reset_container(self) -> None:self.close()- self._init_container()+ self._init_deployment()self._init_scripts()- def _init_container(+ def _init_deployment(self,) -> None:"""Handles container initialization. Defines container name and creates it.@@ -327,6 +291,7 @@ class SWEEnv:asyncio.run(self.deployment.runtime.create_session(CreateBashSessionRequest(startup_source=["/root/.bashrc"])))self.logger.info("Environment Initialized")+ # todo: this part is part of our commands, not the environmentdef _init_scripts(self):"""Initialize custom commands within container"""self.communicate(diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex c754e439..cdf2949b 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -7,7 +7,7 @@ from typing import Any, Literalfrom pydantic import BaseModel, TypeAdapterfrom sweagent.environment.config.deployment import DeploymentConfig, LocalDeploymentConfig-from sweagent.environment.config.problem_statement import ProblemStatement, TextProblemStatement+from sweagent.environment.config.problem_statement import ProblemStatementConfig, TextProblemStatementfrom sweagent.environment.swe_env import EnvironmentConfig@@ -40,7 +40,7 @@ class BatchInstance(BaseModel):"""env: EnvironmentConfig- problem_statement: ProblemStatement+ problem_statement: ProblemStatementConfigdef _filter_batch_items(instances: list[BatchInstance], filter: str) -> list[BatchInstance]:diff --git a/sweagent/run/_common.py b/sweagent/run/common.pysimilarity index 74%rename from sweagent/run/_common.pyrename to sweagent/run/common.pyindex 1033dcfb..7108178c 100644--- a/sweagent/run/_common.py+++ b/sweagent/run/common.py@@ -1,5 +1,6 @@"""Common functionality for the run scripts."""+import jsonfrom argparse import ArgumentParserfrom pathlib import Path@@ -7,6 +8,7 @@ import yamlfrom pydantic_settings import BaseSettings, CliAppfrom sweagent import CONFIG_DIR+from sweagent.types import AgentInfo, AgentRunResult# todo: Parameterize type hints@@ -60,3 +62,22 @@ class BasicCLI:print(yaml.dump(args.model_dump()))exit(0)return args+++def save_predictions(traj_dir: Path, instance_id: str, result: AgentRunResult):+ """Save predictions in a file readable by SWE-bench"""+ output_file = traj_dir / (instance_id + ".pred")+ datum = {+ "model_name_or_path": traj_dir.name,+ "instance_id": instance_id,+ "model_patch": result.info.get("submission"),+ }+ output_file.write_text(json.dumps(datum))+++def _is_promising_patch(info: AgentInfo) -> bool:+ """Do we actually believe that the patch will solve the issue?+ Or are we just submitting the last patch we generated before hitting an error?+ """+ # The exit status can also be `submitted (exit_cost)` etc.+ return info.get("exit_status") == "submitted" and info.get("submission") is not Nonediff --git a/sweagent/run/hooks/abstract.py b/sweagent/run/hooks/abstract.pyindex 397bb7b8..e349504f 100644--- a/sweagent/run/hooks/abstract.py+++ b/sweagent/run/hooks/abstract.py@@ -1,19 +1,11 @@-from typing import Any-+from sweagent.environment.config.problem_statement import ProblemStatement, ProblemStatementConfigfrom sweagent.environment.swe_env import SWEEnv+from sweagent.types import AgentRunResultclass RunHook:"""Hook structure for the web server or other addons to interface with"""- @staticmethod- def _is_promising_patch(info: dict[str, Any]) -> bool:- """Do we actually believe that the patch will solve the issue?- Or are we just submitting the last patch we generated before hitting an error?- """- # The exit status can also be `submitted (exit_cost)` etc.- return info["exit_status"] == "submitted" and info.get("submission") is not None-def on_init(self, *, run):"""Called when hook is initialized"""@@ -23,7 +15,9 @@ class RunHook:def on_end(self):"""Called at the end of `Main.main`"""- def on_instance_start(self, *, index: int, env: SWEEnv):+ def on_instance_start(+ self, *, index: int, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig+ ):"""Called at the beginning of each instance loop in `Main.run`"""def on_instance_skipped(@@ -31,7 +25,7 @@ class RunHook:):"""Called when an instance is skipped in `Main.run`"""- def on_instance_completed(self, *, info, trajectory):+ def on_instance_completed(self, *, result: AgentRunResult):"""Called when an instance is completed in `Main.run`"""@@ -58,14 +52,16 @@ class CombinedRunHooks(RunHook):for hook in self._hooks:hook.on_end()- def on_instance_start(self, *, index: int, env: SWEEnv):+ def on_instance_start(+ self, *, index: int, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig+ ):for hook in self._hooks:- hook.on_instance_start(index=index, env=env)+ hook.on_instance_start(index=index, env=env, problem_statement=problem_statement)def on_instance_skipped(self):for hook in self._hooks:hook.on_instance_skipped()- def on_instance_completed(self, *, info, trajectory):+ def on_instance_completed(self, *, result: AgentRunResult):for hook in self._hooks:- hook.on_instance_completed(info=info, trajectory=trajectory)+ hook.on_instance_completed(result=result)diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.pyindex 88bd0bfc..e37717a7 100644--- a/sweagent/run/hooks/apply_patch.py+++ b/sweagent/run/hooks/apply_patch.py@@ -5,9 +5,12 @@ import richimport rich.markdownimport rich.panel+from sweagent.environment.config.problem_statement import ProblemStatementConfigfrom sweagent.environment.config.repo import LocalRepoConfigfrom sweagent.environment.swe_env import SWEEnv+from sweagent.run.common import _is_promising_patchfrom sweagent.run.hooks.abstract import RunHook+from sweagent.types import AgentRunResultfrom sweagent.utils.log import get_logger@@ -24,16 +27,16 @@ class SaveApplyPatchHook(RunHook):self._env = run.envself._problem_statement = run.problem_statement- def on_instance_start(self, *, index: int, env: SWEEnv):+ def on_instance_start(self, *, index: int, env: SWEEnv, problem_statement: ProblemStatementConfig):self._env = env- def on_instance_completed(self, *, info, trajectory):+ def on_instance_completed(self, *, result: AgentRunResult):instance_id = self._problem_statement.id- patch_path = self._save_patch(instance_id, info)+ patch_path = self._save_patch(instance_id, result.info)if patch_path:if not self._apply_patch_locally:return- if not self._is_promising_patch(info):+ if not _is_promising_patch(result.info):returnif self._env.repo is None:return@@ -73,7 +76,7 @@ class SaveApplyPatchHook(RunHook):Returns:The path to the patch file, if it was saved. Otherwise, returns None."""- patch_output_dir = self._traj_dir / "patches"+ patch_output_dir = self._traj_dirpatch_output_dir.mkdir(exist_ok=True, parents=True)patch_output_file = patch_output_dir / f"{instance_id}.patch"if info.get("submission") is None:@@ -81,7 +84,7 @@ class SaveApplyPatchHook(RunHook):return Nonemodel_patch = info["submission"]patch_output_file.write_text(model_patch)- if self._is_promising_patch(info):+ if _is_promising_patch(info):# Only print big congratulations if we actually believe# the patch will solve the issueself._print_patch_message(patch_output_file)diff --git a/sweagent/run/run.py b/sweagent/run/run.pynew file mode 100644index 00000000..65f38cf9--- /dev/null+++ b/sweagent/run/run.py@@ -0,0 +1,50 @@+"""Main command line interface for SWE-agent.+Specify one of the subcommands.+"""++import argparse+import sys++from sweagent.run.run_batch import run_from_cli as run_batch_main+from sweagent.run.run_replay import run_from_cli as run_replay_main+from sweagent.run.run_single import run_from_cli as run_single_main+++def get_cli():+ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("command", choices=["run", "run-batch", "run-replay"], nargs="?")+ parser.add_argument("-h", "--help", action="store_true", help="Show this help message and exit")+ return parser+++def main(args: list[str] | None = None):+ if args is None:+ args = sys.argv[1:]+ cli = get_cli()+ parsed_args, remaining_args = cli.parse_known_args(args) # type: ignore+ command = parsed_args.command+ show_help = parsed_args.help+ if show_help:+ if not command:+ # Show main help+ cli.print_help()+ sys.exit(0)+ else:+ # Add to remaining_args+ remaining_args.append("--help")+ elif not command:+ cli.print_help()+ sys.exit(2)+ if command == "run":+ run_single_main(remaining_args)+ elif command == "run-batch":+ run_batch_main(remaining_args)+ elif command == "run-replay":+ run_replay_main(remaining_args)+ else:+ msg = f"Unknown command: {command}"+ raise ValueError(msg)+++if __name__ == "__main__":+ main()diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.pyindex 93e46350..450c5bad 100644--- a/sweagent/run/run_batch.py+++ b/sweagent/run/run_batch.py@@ -2,6 +2,9 @@Run on a batch of instances/issues. For example run on all of SWE-bench."""+import json+import sys+import tracebackfrom pathlib import Pathfrom typing import Self@@ -9,10 +12,11 @@ from pydantic_settings import BaseSettingsfrom sweagent.agent.agents import Agent, AgentConfigfrom sweagent.agent.models import ModelArguments-from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv-from sweagent.run._common import BasicCLI-from sweagent.run.batch_instances import BatchInstanceSourceConfig-from sweagent.run.hooks.abstract import RunHook+from sweagent.environment.swe_env import SWEEnv+from sweagent.run.batch_instances import BatchInstance, BatchInstanceSourceConfig+from sweagent.run.common import BasicCLI, save_predictions+from sweagent.run.hooks.abstract import CombinedRunHooks, RunHook+from sweagent.run.hooks.apply_patch import SaveApplyPatchHookfrom sweagent.utils.log import get_logger@@ -21,73 +25,138 @@ class RunBatchConfig(BaseSettings):agent: AgentConfig = AgentConfig(model=ModelArguments(name="human"), next_step_template="Observation: {observation}")- traj_dir: str = "."+ traj_dir: Path = Path(".")raise_exceptions: bool = False+ skip_existing: bool = True+++class _BreakLoop(Exception):+ """Used for internal control flow"""class RunBatch:def __init__(self,- instances: list[EnvironmentConfig],+ instances: list[BatchInstance],agent: Agent,*,- traj_dir: str = ".",+ traj_dir: Path = Path("."),hooks: list[RunHook] | None = None,+ raise_exceptions: bool = False,+ skip_existing: bool = True,):"""Note: When initializing this class, make sure to add the hooks that are required by your actions.See `from_config` for an example.++ Args:+ hooks: If not specified, the default hooks will be used."""- self.logger = get_logger("🤠 Run")+ self.logger = get_logger("Run", emoji="🏃")self.instances = instancesself.agent = agentself.traj_dir = traj_dirself._hooks = []- for hook in hooks or []:+ self._raise_exceptions = raise_exceptions+ self._chooks = CombinedRunHooks()+ self._skip_existing = skip_existing+ for hook in hooks or [SaveApplyPatchHook()]:self.add_hook(hook)- @property- def hooks(self) -> list[RunHook]:- return self._hooks-@classmethoddef from_config(cls, config: RunBatchConfig) -> Self:return cls(instances=config.instances.get_instance_configs(),agent=Agent("main", config.agent),traj_dir=config.traj_dir,+ raise_exceptions=config.raise_exceptions,)def add_hook(self, hook: RunHook) -> None:hook.on_init(run=self)self._hooks.append(hook)- def _fire_hooks(self, hook_name: str, *args, **kwargs) -> None:- for hook in self.hooks:- getattr(hook, hook_name)(*args, **kwargs)-def main(self):- self._fire_hooks("on_start")+ self._chooks.on_start()for instance in self.instances:- self.logger.info("Starting environment")- env = SWEEnv.from_config(instance)- env.start()- self.logger.info("Resetting environment")- env.reset()- self.logger.info("Running agent")- self._fire_hooks("on_instance_start", index=0, instance=instance.model_dump())- info, trajectory = self.agent.run(- problem_statement=instance.problem_statement,- env=env,- traj_dir=Path(self.traj_dir),- )- self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)+ try:+ self.run_instance(instance)+ except _BreakLoop:+ self.logger.info("Stopping loop over instances")+ breakself.logger.info("Done")- self._fire_hooks("on_end")+ self._chooks.on_end()++ def run_instance(self, instance: BatchInstance):+ # Either catch and silence exception, or raise _BreakLoop to stop the loop+ # over the instances+ try:+ self._run_instance(instance)+ except KeyboardInterrupt:+ raise _BreakLoop+ except SystemExit:+ self.logger.critical("❌ Exiting because SystemExit was called")+ raise _BreakLoop+ except Exception as e:+ self.logger.error(traceback.format_exc())+ if self._raise_exceptions:+ raise _BreakLoop+ self.logger.warning(f"❌ Failed on {instance.problem_statement.id}: {e}")++ def _run_instance(self, instance: BatchInstance):+ if self.should_skip(instance):+ return+ self.logger.info("Starting environment")+ env = SWEEnv.from_config(instance.env)+ env.start()+ self.logger.info("Resetting environment")+ env.reset()+ self.logger.info("Running agent")+ self._chooks.on_instance_start(index=0, env=env, problem_statement=instance.problem_statement)+ result = self.agent.run(+ problem_statement=instance.problem_statement,+ env=env,+ traj_dir=Path(self.traj_dir),+ )+ self._chooks.on_instance_completed(result=result)+ save_predictions(self.traj_dir, instance.problem_statement.id, result)++ def should_skip(self, instance: BatchInstance) -> bool:+ """Check if we should skip this instance"""+ if not self._skip_existing:+ return False++ # Check if there's an existing trajectory for this instance+ log_path = self.traj_dir / (instance.problem_statement.id + ".traj")+ if not log_path.exists():+ return False++ content = log_path.read_text()+ if not content.strip():+ self.logger.warning("Found empty trajectory: %s. Removing.", log_path)+ log_path.unlink()+ return False++ data = json.loads(content)+ # If the trajectory has no exit status, it's incomplete and we will redo it+ exit_status = data["info"].get("exit_status", None)+ if exit_status == "early_exit" or exit_status is None:+ self.logger.warning(f"Found existing trajectory with no exit status: {log_path}. Removing.")+ log_path.unlink()+ return False++ self.logger.info(f"⏭️ Skipping existing trajectory: {log_path}")+ return True+++def run_from_config(args: RunBatchConfig):+ RunBatch.from_config(args).main()-def main(args: RunBatchConfig):- RunBatch.from_config(args).main()+def run_from_cli(args: list[str] | None = None):+ if args is None:+ args = sys.argv[1:]+ run_from_config(BasicCLI(RunBatchConfig).get_args(args)) # type: ignoreif __name__ == "__main__":- main(BasicCLI(RunBatchConfig).get_args()) # type: ignore+ run_from_cli()diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.pyindex 60412b88..f8ce68ce 100644--- a/sweagent/run/run_replay.py+++ b/sweagent/run/run_replay.py@@ -1,6 +1,7 @@"""Run on a single instance taken from github or similar."""import json+import sysimport tempfilefrom pathlib import Pathfrom typing import Self@@ -17,7 +18,7 @@ from sweagent.environment.config.deployment import DeploymentConfig, DockerDeplofrom sweagent.environment.config.problem_statement import EmptyProblemStatementfrom sweagent.environment.config.repo import RepoConfigfrom sweagent.environment.swe_env import SWEEnv-from sweagent.run._common import BasicCLI+from sweagent.run.common import BasicCLIfrom sweagent.run.run_single import RunSinglefrom sweagent.utils.log import get_logger@@ -97,9 +98,15 @@ class RunReplay:run_single.run()-def main(args: RunReplayConfig):+def run_from_config(args: RunReplayConfig):RunReplay.from_config(args).main()+def run_from_cli(args: list[str] | None = None):+ if args is None:+ args = sys.argv[1:]+ run_from_config(BasicCLI(RunReplayConfig, default_settings=False).get_args(args)) # type: ignore++if __name__ == "__main__":- main(BasicCLI(RunReplayConfig, default_settings=False).get_args()) # type: ignore+ run_from_cli()diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.pyindex 5b11e632..be90eeef 100644--- a/sweagent/run/run_single.py+++ b/sweagent/run/run_single.py@@ -1,5 +1,6 @@"""Run on a single instance taken from github or similar."""+import sysfrom pathlib import Pathfrom typing import Self@@ -14,7 +15,7 @@ from sweagent.environment.config.problem_statement import (ProblemStatementConfig,)from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv-from sweagent.run._common import BasicCLI+from sweagent.run.common import BasicCLI, save_predictionsfrom sweagent.run.hooks.abstract import CombinedRunHooks, RunHookfrom sweagent.run.hooks.apply_patch import SaveApplyPatchHookfrom sweagent.run.hooks.open_pr import OpenPRConfig, OpenPRHook@@ -37,7 +38,7 @@ class RunSingleConfig(BaseSettings):model=ModelArguments(name="human"), next_step_template="Observation: {observation}")problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)- traj_dir: str = "."+ traj_dir: Path = Path(".")actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)# todo: implement thisraise_exceptions: bool = True@@ -50,9 +51,9 @@ class RunSingle:self,env: SWEEnv,agent: Agent,- problem_statement: ProblemStatement,+ problem_statement: ProblemStatement | ProblemStatementConfig,*,- traj_dir: str = ".",+ traj_dir: Path = Path("."),hooks: list[RunHook] | None = None,actions: RunSingleActionConfig | None = None,):@@ -102,20 +103,27 @@ class RunSingle:self.logger.info("Resetting environment")self.env.reset()self.logger.info("Running agent")- self._chooks.on_instance_start(index=0, env=self.env)- info, trajectory = self.agent.run(+ self._chooks.on_instance_start(index=0, env=self.env, problem_statement=self.problem_statement)+ result = self.agent.run(problem_statement=self.problem_statement,env=self.env,traj_dir=Path(self.traj_dir),)- self._chooks.on_instance_completed(info=info, trajectory=trajectory)+ self._chooks.on_instance_completed(result=result)self.logger.info("Done")self._chooks.on_end()+ save_predictions(self.traj_dir, self.problem_statement.id, result)-def main(args: RunSingleConfig):+def run_from_config(args: RunSingleConfig):RunSingle.from_config(args).run()+def run_from_cli(args: list[str] | None = None):+ if args is None:+ args = sys.argv[1:]+ run_from_config(BasicCLI(RunSingleConfig).get_args(args)) # type: ignore++if __name__ == "__main__":- main(BasicCLI(RunSingleConfig).get_args()) # type: ignore+ run_from_cli()diff --git a/sweagent/types.py b/sweagent/types.pyindex 13304774..90d833c5 100644--- a/sweagent/types.py+++ b/sweagent/types.py@@ -8,9 +8,11 @@ from __future__ import annotationsimport copyfrom dataclasses import dataclass-from typing import Any, Literal, TypedDict+from typing import Any, Literal+from pydantic import BaseModelfrom simple_parsing.helpers.serialization.serializable import FrozenSerializable+from typing_extensions import TypedDictclass TrajectoryStep(TypedDict):@@ -95,3 +97,8 @@ class BinaryReviewerResult(FrozenSerializable):choice: Literal[0, 1]output: strmessages: list[dict[str, str]]+++class AgentRunResult(BaseModel):+ info: AgentInfo+ trajectory: Trajectorydiff --git a/tests/test_server.py b/tests/_test_server.pysimilarity index 100%rename from tests/test_server.pyrename to tests/_test_server.pydiff --git a/tests/test_run.py b/tests/test_run.pyindex 59b483c5..87db113c 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -1,24 +1,49 @@from __future__ import annotationsimport subprocess+from pathlib import Pathimport pytestfrom sweagent.agent.agents import AgentConfigfrom sweagent.environment.swe_env import EnvironmentConfig-from sweagent.run._common import BasicCLI+from sweagent.run.common import BasicCLIfrom sweagent.run.hooks.abstract import RunHookfrom sweagent.run.run_single import RunSingle, RunSingleConfig-def test_run_cli_help():+def test_run_cli_no_arg_error():+ args = [+ "sweagent",+ ]+ output = subprocess.run(args, check=False, capture_output=True)+ assert output.returncode == 2+ assert "run-batch" in output.stdout.decode()+ assert "run-replay" in output.stdout.decode()+ assert "run" in output.stdout.decode()+++def test_run_cli_main_help():+ args = [+ "sweagent",+ "--help",+ ]+ output = subprocess.run(args, check=True, capture_output=True)+ assert output.returncode == 0+ assert "run-batch" in output.stdout.decode()+ assert "run-replay" in output.stdout.decode()+ assert "run" in output.stdout.decode()+++def test_run_cli_subcommand_help():args = [- "python",- "sweagent/run/run_single.py",+ "sweagent",+ "run","--help",]- subprocess.run(args, check=True)+ output = subprocess.run(args, check=True, capture_output=True)+ assert output.returncode == 0+ assert "--config" in output.stdout.decode()class RaisesExceptionHook(RunHook):@@ -67,6 +92,9 @@ def test_run_ies_repo_ps_matrix(repo,problem_statement_source,):+ output_formats = ["traj", "pred", "patch"]+ for fmt in output_formats:+ assert not list(Path(tmpdir).glob(f"*.{fmt}"))if problem_statement_source == "github":ps_args = ["--problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]elif problem_statement_source == "local":@@ -94,3 +122,6 @@ def test_run_ies_repo_ps_matrix(with tmpdir.as_cwd():# Test that we can run run.py also independently from repo dirrs.run()+ for fmt in output_formats:+ assert len(list(Path(tmpdir).glob(f"*.{fmt}"))) == 1+ print(fmt, list(Path(tmpdir).iterdir()))