Skip to content

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]

Consolidate different communicate methods

Kilian Lieret26f13b85c245
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index abb6a0e2..252f93c4 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -49,9 +49,11 @@ class SWEEnv:
startup_commands: list[str],
hooks: list[EnvHook] | None = None,
_catch_errors: bool = False,
+ _always_require_zero_exit_code: bool = False,
):
super().__init__()
self._catch_errors = _catch_errors
+ self._require_zero_exit_code = _always_require_zero_exit_code
self.deployment = deployment
self.repo = repo
self.problem_statement = problem_statement
@@ -184,8 +186,9 @@ class SWEEnv:
f"git reset --hard {self.repo.base_commit}",
"git clean -fdxq",
]
- self.communicate_with_handling(
+ self.communicate(
input=" && ".join(startup_commands),
+ require_zero_exit_code=True,
error_msg="Failed to clean repository",
)
@@ -198,8 +201,9 @@ class SWEEnv:
"export SEARCH_FILES=()",
"export SEARCH_INDEX=0",
]
- self.communicate_with_handling(
+ self.communicate(
input=" && ".join(cmd),
+ require_zero_exit_code=True,
error_msg="Failed to reset environment variables",
)
@@ -279,7 +283,6 @@ class SWEEnv:
observation = self.communicate(
input=action,
timeout_duration=AGENT_ACTION_TIMEOUT,
- no_output_timeout_duration=AGENT_ACTION_NO_OUTPUT_TIMEOUT,
set_last_action=True,
)
except RuntimeError as e:
@@ -340,96 +343,67 @@ class SWEEnv:
"""
Initialize custom commands within container
"""
- self.communicate_with_handling(
+ self.communicate(
"mkdir -p /root/commands",
+ require_zero_exit_code=True,
error_msg="Failed to create commands directory",
)
- self.communicate_with_handling(
+ self.communicate(
"touch /root/commands/__init__.py",
+ require_zero_exit_code=True,
error_msg="Failed to create __init__.py",
)
- self.communicate_with_handling(
+ self.communicate(
"export PATH=$PATH:/root/commands",
+ require_zero_exit_code=True,
error_msg="Failed to add commands directory to PATH",
)
- def _communicate(
- self,
- input: str,
- timeout_duration: int | float = 25,
- *,
- no_output_timeout_duration: int | float = 25,
- ) -> str:
- """Runs command in container and returns output.
- This is the internal version of `communicate` that does not handle the "exit" command etc.
- """
- self.returncode = None
- r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout_duration)))
- self.returncode = r.exit_code
- return r.output
-
def communicate(
self,
input: str,
timeout_duration: int | float = 25,
*,
- no_output_timeout_duration: int | float | None = None,
set_last_action: bool = False,
+ require_zero_exit_code: bool = False,
+ error_msg: str = "Command failed",
) -> str:
"""Sends input to container and returns output
Args:
input: input to send to container
timeout_duration: duration to wait for output
- no_output_timeout_duration: duration to wait when the process stopped produce any output
set_last_action: whether to set the LAST_ACTION environment variable
-
+ require_zero_exit_code: whether to raise an error if the exit code is non-zero
+ error_msg: error message to raise if the command fails
Returns:
output: output from container
"""
- if no_output_timeout_duration is None:
- no_output_timeout_duration = timeout_duration
-
if input.strip() == "exit":
asyncio.run(self.deployment.stop())
self.returncode = 0
return ""
self.logger.log(logging.TRACE, "Input:\n%s", input) # type: ignore
- output = self._communicate(
- input,
- timeout_duration=timeout_duration,
- no_output_timeout_duration=no_output_timeout_duration,
- )
+ self.returncode = None
+ r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout_duration)))
+ self.returncode = r.exit_code
+ output = r.output
self.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:
+ self.logger.error(f"{error_msg}: {output}")
+ self.close()
+ msg = f"{error_msg} (command: {input})"
+ raise RuntimeError(msg)
+ # todo: What do we do with this?
if set_last_action:
# Cannot merge this with last command, because of multiline command
# handling.
last_action_string = shlex.quote(input.strip())
input = f"export LAST_ACTION={last_action_string}"
- self._communicate(input, timeout_duration=5, no_output_timeout_duration=5)
+ r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=1)))
return output
- def communicate_with_handling(self, input: str, error_msg: str, timeout_duration: int | float = 25) -> str:
- """
- Wrapper for communicate function that raises error if return code is non-zero
-
- Args:
- input: input to send to container
- error_msg: error message to raise if return code is non-zero
- timeout_duration: duration to wait for output
-
- Returns:
- output: output from container
- """
- logs = self.communicate(input, timeout_duration=timeout_duration)
- if self.returncode != 0:
- self.logger.error(f"{error_msg}: {logs}")
- self.close()
- msg = f"{error_msg} (command: {input})"
- raise RuntimeError(msg)
- return logs
-
def get_available_actions(self) -> list[str]:
"""
Returns list of available actions in current environment state
@@ -471,16 +445,18 @@ class SWEEnv:
self.deployment.runtime.write_file(WriteFileRequest(content=contents, path=f"/root/commands/{name}"))
)
if command["type"] == "source_file":
- self.communicate_with_handling(
+ self.communicate(
f"source /root/commands/{name}",
+ require_zero_exit_code=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)."
),
)
elif command["type"] == "script":
- self.communicate_with_handling(
+ self.communicate(
f"chmod +x /root/commands/{name}",
+ require_zero_exit_code=True,
error_msg=f"Failed to chmod {name}",
)
elif command["type"] == "utility":
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index 07c83187..cb972c81 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -40,6 +40,7 @@ class RunReplay:
repo: RepoConfig | None,
output_dir: str,
_catch_errors: bool = False,
+ _require_zero_exit_code: bool = False,
):
self.traj_path = traj_path
self.config_path = config_path
@@ -49,6 +50,7 @@ class RunReplay:
self._replay_action_trajs_path = Path(tempfile.NamedTemporaryFile(suffix=".json").name)
self.logger = get_logger("RunReplay", emoji="🏃")
self._catch_errors = _catch_errors
+ self._require_zero_exit_code = _require_zero_exit_code
@property
def instance_id(self) -> str:
@@ -78,6 +80,7 @@ class RunReplay:
problem_statement=EmptyProblemStatement(),
startup_commands=[],
_catch_errors=self._catch_errors,
+ _always_require_zero_exit_code=self._require_zero_exit_code,
)
def _get_agent(self) -> Agent:
diff --git a/tests/test_env.py b/tests/test_env.py
index a4a38659..ef065c36 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_with_handling("echo 'hello world'", error_msg="Failed to echo", timeout_duration=1)
+ env.communicate("echo 'hello world'", require_zero_exit_code=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_with_handling("sleep 10", error_msg="Failed to sleep", timeout_duration=0.2)
+ env.communicate("sleep 10", require_zero_exit_code=True, error_msg="Failed to sleep")
@pytest.mark.slow
diff --git a/tests/test_replay.py b/tests/test_replay.py
index 725283c5..268e592a 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -10,21 +10,19 @@ import pytest
from run_replay import get_args, main
from sweagent import CONFIG_DIR
from sweagent.environment.config.deployment import DockerDeploymentConfig
+from sweagent.environment.config.repo import LocalRepoConfig
from sweagent.run.run_replay import RunReplay, RunReplayConfig
-def test_replay(test_trajectories_path, tmp_path):
+def test_replay(swe_agent_test_repo_traj, tmp_path, swe_agent_test_repo_clone):
rc = RunReplayConfig(
- traj_path=str(
- 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"
- ),
+ 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)
+ rr = RunReplay.from_config(rc, _catch_errors=False, _require_zero_exit_code=True)
rr.main()