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]
All tests pass again
Kilian Lieret89687648a8a3
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 4579d960..8ca88e5c 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -756,10 +756,7 @@ class Agent:)commands = "\n".join(commands_to_execute)try:- output = env.communicate(commands)- if env.returncode != 0:- msg = f"Nonzero return code: {env.returncode}\nOutput: {output}"- raise RuntimeError(msg)+ env.communicate(commands, require_zero=True)except KeyboardInterrupt:raiseexcept Exception as e:diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.pyindex bcccb822..3eb6b8b5 100644--- a/sweagent/environment/config/problem_statement.py+++ b/sweagent/environment/config/problem_statement.py@@ -19,17 +19,17 @@ class EmptyProblemStatement(BaseModel):class TextProblemStatement(BaseModel):- problem_statement: str = ""+ text: str = ""type: Literal["text"] = "text""""Discriminator for (de)serialization/CLI. Do not change."""@propertydef id(self) -> str:- return hashlib.sha256(self.problem_statement.encode()).hexdigest()[:6]+ return hashlib.sha256(self.text.encode()).hexdigest()[:6]def get_problem_statement(self) -> str:- return self.problem_statement+ return self.textclass FileProblemStatement(BaseModel):@@ -47,18 +47,18 @@ class FileProblemStatement(BaseModel):class GithubIssue(BaseModel):- issue_url: str = ""+ url: str = ""type: Literal["github"] = "github""""Discriminator for (de)serialization/CLI. Do not change."""@propertydef id(self) -> str:- owner, repo, issue_number = _parse_gh_issue_url(self.issue_url)+ owner, repo, issue_number = _parse_gh_issue_url(self.url)return f"{owner}__{repo}-i{issue_number}"def get_problem_statement(self) -> str:- owner, repo, issue_number = _parse_gh_issue_url(self.issue_url)+ owner, repo, issue_number = _parse_gh_issue_url(self.url)return _get_problem_statement_from_github_issue(owner, repo, issue_number, token=keys_config.get("GITHUB_TOKEN"))diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 252f93c4..01f7116d 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -59,8 +59,6 @@ class SWEEnv:self.problem_statement = problem_statementself._startup_commands = startup_commandsself.logger = get_logger("swe_env", emoji="🌱")- # todo: get rid of this- self.returncode: None | int = Noneself.clean_multi_line_functions = lambda x: xself._hooks: list[EnvHook] = []@@ -188,7 +186,7 @@ class SWEEnv:]self.communicate(input=" && ".join(startup_commands),- require_zero_exit_code=True,+ require_zero=True,error_msg="Failed to clean repository",)@@ -203,7 +201,7 @@ class SWEEnv:]self.communicate(input=" && ".join(cmd),- require_zero_exit_code=True,+ require_zero=True,error_msg="Failed to reset environment variables",)@@ -282,7 +280,7 @@ class SWEEnv:try:observation = self.communicate(input=action,- timeout_duration=AGENT_ACTION_TIMEOUT,+ timeout=AGENT_ACTION_TIMEOUT,set_last_action=True,)except RuntimeError as e:@@ -345,27 +343,27 @@ class SWEEnv:"""self.communicate("mkdir -p /root/commands",- require_zero_exit_code=True,+ require_zero=True,error_msg="Failed to create commands directory",)self.communicate("touch /root/commands/__init__.py",- require_zero_exit_code=True,+ require_zero=True,error_msg="Failed to create __init__.py",)self.communicate("export PATH=$PATH:/root/commands",- require_zero_exit_code=True,+ require_zero=True,error_msg="Failed to add commands directory to PATH",)def communicate(self,input: str,- timeout_duration: int | float = 25,+ timeout: int | float = 25,*,set_last_action: bool = False,- require_zero_exit_code: bool = False,+ require_zero: bool = False,error_msg: str = "Command failed",) -> str:"""Sends input to container and returns output@@ -381,16 +379,13 @@ class SWEEnv:"""if input.strip() == "exit":asyncio.run(self.deployment.stop())- self.returncode = 0return ""self.logger.log(logging.TRACE, "Input:\n%s", input) # type: ignore- self.returncode = None- r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout_duration)))- self.returncode = r.exit_code+ r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout)))output = r.outputself.logger.log(logging.TRACE, "Output:\n%s", output) # type: ignore- if (self._require_zero_exit_code or require_zero_exit_code) and self.returncode != 0:+ if (self._require_zero_exit_code or require_zero) and r.exit_code != 0:self.logger.error(f"{error_msg}: {output}")self.close()msg = f"{error_msg} (command: {input})"@@ -447,7 +442,7 @@ class SWEEnv:if command["type"] == "source_file":self.communicate(f"source /root/commands/{name}",- require_zero_exit_code=True,+ require_zero=True,error_msg=(f"Failed to source {name}. If you meant to make a script,"" start the file with a shebang (e.g. #!/usr/bin/env python)."@@ -456,7 +451,7 @@ class SWEEnv:elif command["type"] == "script":self.communicate(f"chmod +x /root/commands/{name}",- require_zero_exit_code=True,+ require_zero=True,error_msg=f"Failed to chmod {name}",)elif command["type"] == "utility":diff --git a/sweagent/run/_common.py b/sweagent/run/_common.pyindex 6d62882b..1033dcfb 100644--- a/sweagent/run/_common.py+++ b/sweagent/run/_common.py@@ -9,6 +9,7 @@ from pydantic_settings import BaseSettings, CliAppfrom sweagent import CONFIG_DIR+# todo: Parameterize type hintsclass BasicCLI:def __init__(self, arg_type: type[BaseSettings], default_settings: bool = True):self.arg_type = arg_typediff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex 49a73f3c..4fb6e8fe 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -50,7 +50,7 @@ class BatchInstance(BaseModel):# Combine image name and deployment options into a DeploymentConfig object. Because this can be one of many# subclasses, we use a TypeAdapter to validate/instantiate the object.deployment = TypeAdapter(DeploymentConfig).validate_python(dict(image=self.image_name, **deployment_kwargs))- problem_statement = TextProblemStatement(problem_statement=self.problem_statement)+ problem_statement = TextProblemStatement(text=self.problem_statement)return EnvironmentInstanceConfig(deployment=deployment, problem_statement=problem_statement, repo=None)diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.pyindex 69487fd1..d6f3d843 100644--- a/sweagent/run/hooks/apply_patch.py+++ b/sweagent/run/hooks/apply_patch.py@@ -2,6 +2,8 @@ import subprocessfrom pathlib import Pathimport rich+import rich.markdown+import rich.panelfrom sweagent.environment.config.repo import LocalRepoConfigfrom sweagent.environment.swe_env import SWEEnvdiff --git a/tests/conftest.py b/tests/conftest.pyindex 1b633759..b357fd7e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -104,3 +104,22 @@ def swe_env_context(env_args):yield envfinally:env.close()+++def swe_agent_test_repo_clone(tmp_path):+ local_repo_path = tmp_path / "test-repo"+ clone_cmd = ["git", "clone", "https://github.com/swe-agent/test-repo", local_repo_path]+ subprocess.run(clone_cmd, check=True)+ return local_repo_path+++def swe_agent_test_repo_traj(test_trajectories_path) -> Path:+ p = (+ test_trajectories_path+ / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1"+ / "6e44b9__sweagenttestrepo-1c2844.traj"+ )+ assert p.is_file()+ return pdiff --git a/tests/test_env.py b/tests/test_env.pyindex ef065c36..33c92d13 100644--- a/tests/test_env.py+++ b/tests/test_env.py@@ -51,7 +51,7 @@ def test_env_with_hook(test_env_args):def test_env_communicate_with_handling(test_env_args):with swe_env_context(test_env_args) as env:env.reset()- env.communicate("echo 'hello world'", require_zero_exit_code=True, error_msg="Failed to echo")+ env.communicate("echo 'hello world'", require_zero=True, error_msg="Failed to echo")@pytest.mark.slow@@ -59,7 +59,7 @@ def test_env_communicate_with_handling_timeout(test_env_args):with swe_env_context(test_env_args) as env:env.reset()with pytest.raises(CommandTimeoutError):- env.communicate("sleep 10", require_zero_exit_code=True, error_msg="Failed to sleep")+ env.communicate("sleep 10", require_zero=True, error_msg="Failed to sleep", timeout=0.2)@pytest.mark.slowdiff --git a/tests/test_replay.py b/tests/test_replay.pyindex 268e592a..d12f677c 100644--- a/tests/test_replay.py+++ b/tests/test_replay.py@@ -1,171 +1,35 @@from __future__ import annotations-import osimport subprocess-from pathlib import Path-from unittest import mockimport pytest-from run_replay import get_args, mainfrom sweagent import CONFIG_DIRfrom sweagent.environment.config.deployment import DockerDeploymentConfigfrom sweagent.environment.config.repo import LocalRepoConfigfrom sweagent.run.run_replay import RunReplay, RunReplayConfig-def test_replay(swe_agent_test_repo_traj, tmp_path, swe_agent_test_repo_clone):- rc = RunReplayConfig(+def rr_config(swe_agent_test_repo_traj, tmp_path, swe_agent_test_repo_clone):+ return RunReplayConfig(traj_path=str(swe_agent_test_repo_traj),config_path=str(CONFIG_DIR / "default_from_url.yaml"),deployment=DockerDeploymentConfig(),output_dir=str(tmp_path),repo=LocalRepoConfig(path=str(swe_agent_test_repo_clone)),)- rr = RunReplay.from_config(rc, _catch_errors=False, _require_zero_exit_code=True)- rr.main()---def swe_agent_test_repo_clone(tmp_path):- local_repo_path = tmp_path / "test-repo"- clone_cmd = ["git", "clone", "https://github.com/swe-agent/test-repo", local_repo_path]- subprocess.run(clone_cmd, check=True)- return local_repo_path---def swe_agent_test_repo_traj(test_trajectories_path) -> Path:- p = (- test_trajectories_path- / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1"- / "6e44b9__sweagenttestrepo-1c2844.traj"- )- assert p.is_file()- return p---def swe_agent_test_repo_local_problem_stmt(swe_agent_test_repo_clone) -> Path:- problem_stmt = swe_agent_test_repo_clone / "problem_statements" / "1.md"- assert problem_stmt.is_file()- return problem_stmt-[email protected]("problem_statement_source", ["github", "local"])-def test_model_replay_github_repo(- tmpdir,- swe_agent_test_repo_traj,- problem_statement_source,- swe_agent_test_repo_local_problem_stmt,-):- if problem_statement_source == "github":- data_path = "https://github.com/swe-agent/test-repo/issues/1"- elif problem_statement_source == "local":- data_path = str(swe_agent_test_repo_local_problem_stmt)- args = [- "--traj_path",- str(swe_agent_test_repo_traj.resolve()),- "--data_path",- data_path,- "--config_file",- str(CONFIG_DIR / "default_from_url.yaml"),- "--raise_exceptions",- ]- if problem_statement_source == "local":- args.extend(["--repo_path", "https://github.com/swe-agent/test-repo/"])- args, remaining_args = get_args(args)- with tmpdir.as_cwd():- # Test that we can run run.py also independently from repo dir- main(**vars(args), forward_args=remaining_args)--def test_model_replay_from_json(test_trajectories_path, test_data_sources_path):- traj_path = (- test_trajectories_path- / "gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1"- / "pydicom__pydicom-1458.traj"- )- assert traj_path.is_file()- data_path = test_data_sources_path / "swe-bench-dev-easy_first_only.json"- assert data_path.is_file()- args = [- "--traj_path",- str(traj_path),- "--data_path",- str(data_path),- "--config_file",- "config/default.yaml",- "raise_exceptions=True",- ]- args, remaining_args = get_args(args)- main(**vars(args), forward_args=remaining_args)+def test_replay(rr_config):+ rr = RunReplay.from_config(rr_config, _catch_errors=False, _require_zero_exit_code=True)+ rr.main()def test_run_cli_help():args = ["python",- "run_replay.py",+ "sweagent/run/run_replay.py","--help",]subprocess.run(args, check=True)--[email protected]("problem_statement_source", ["github", "local"])-def test_model_replay_local_repo(swe_agent_test_repo_clone, swe_agent_test_repo_traj, problem_statement_source):- local_repo_path = swe_agent_test_repo_clone- if problem_statement_source == "github":- problem_statement_path = "https://github.com/swe-agent/test-repo/issues/1"- elif problem_statement_source == "local":- problem_statement_path = local_repo_path / "problem_statements" / "1.md"- assert problem_statement_path.is_file()- else:- raise ValueError(problem_statement_source)- run_cmd = [- "--traj_path",- str(swe_agent_test_repo_traj),- "--repo_path",- str(local_repo_path),- "--config_file",- "config/default_from_url.yaml",- "--data_path",- str(problem_statement_path),- "--apply_patch",- "--raise_exceptions",- ]- print(run_cmd)- args, remaining_args = get_args(run_cmd)- main(**vars(args), forward_args=remaining_args)- solution = (swe_agent_test_repo_traj.parent / "solution_missing_colon.py").read_text().strip()- solution_retrieved = (local_repo_path / "tests" / "missing_colon.py").read_text().strip()- assert solution == solution_retrieved---def test_exception_replay_local_dirty(swe_agent_test_repo_clone, swe_agent_test_repo_traj):- """Test that swe-agent refuses to work if the local repo is dirty"""- problem_statement_path = swe_agent_test_repo_clone / "problem_statements" / "1.md"- test_file = swe_agent_test_repo_clone / "tests" / "missing_colon.py"- assert test_file.is_file()- test_file.write_text(test_file.read_text().replace("division", "division_function"))- run_cmd = [- "--traj_path",- str(swe_agent_test_repo_traj),- "--repo_path",- str(swe_agent_test_repo_clone),- "--config_file",- "config/default_from_url.yaml",- "--data_path",- str(problem_statement_path),- "--apply_patch",- "--raise_exceptions",- ]- args, remaining_args = get_args(run_cmd)- # In the code, we exclude testing from this check because of tests hosted in the repo- # so here we pretend we're not in a test- modified_environ = {k: v for k, v in os.environ.items() if k != "PYTEST_CURRENT_TEST"}- with mock.patch.dict(os.environ, modified_environ, clear=True):- with pytest.raises(ValueError, match=".*dirty.*"):- main(**vars(args), forward_args=remaining_args)diff --git a/tests/test_run.py b/tests/test_run.pyindex 1b9cbe13..4fe2a73b 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -6,6 +6,7 @@ import pytestfrom sweagent.agent.agents import AgentConfigfrom sweagent.environment.swe_env import EnvironmentInstanceConfig+from sweagent.run._common import BasicCLIfrom sweagent.run.hooks.abstract import RunHookfrom sweagent.run.run_single import RunSingle, RunSingleConfig@@ -45,7 +46,8 @@ def agent_config_with_commands():@pytest.mark.slow-def test_run_instant_empty_submit(agent_config_with_commands):+def test_run_ies(agent_config_with_commands):+ # ies = instant empty submitac = agent_config_with_commandsac.model.name = "instant_empty_submit"rsc = RunSingleConfig(@@ -54,3 +56,41 @@ def test_run_instant_empty_submit(agent_config_with_commands):)rs = RunSingle.from_config(rsc)rs.run()++[email protected]("repo", ["local", "github"])[email protected]("problem_statement_source", ["github", "local", "text"])+def test_run_ies_repo_ps_matrix(+ tmpdir,+ swe_agent_test_repo_clone,+ repo,+ problem_statement_source,+):+ if problem_statement_source == "github":+ ps_args = ["--env.problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]+ elif problem_statement_source == "local":+ ps_args = ["--env.problem_statement.path", str(swe_agent_test_repo_clone / "problem_statements" / "1.md")]+ elif problem_statement_source == "text":+ ps_args = ["--env.problem_statement.text='this is a test'"]+ else:+ raise ValueError(problem_statement_source)+ if repo == "local":+ repo_args = ["--env.repo.path", str(swe_agent_test_repo_clone)]+ elif repo == "github":+ repo_args = ["--env.repo.url", "https://github.com/swe-agent/test-repo"]+ else:+ raise ValueError(repo)+ args = [+ "--agent.model.name=instant_empty_submit",+ "--raise_exceptions=True",+ *ps_args,+ *repo_args,+ ]+ print(args)+ rs_config = BasicCLI(RunSingleConfig).get_args(args)+ print(rs_config)+ rs = RunSingle.from_config(rs_config) # type: ignore+ with tmpdir.as_cwd():+ # Test that we can run run.py also independently from repo dir+ rs.run()