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]

Move get/set env vars to SWEEnv class; run post_startup_cmds

Kilian Lieretb74822694b04
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 83e49011..edcc6932 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -25,10 +25,9 @@ class EnvironmentConfig(BaseModel):
default=None,
description="Repository options.",
)
- # fixme: Actually run these
- startup_commands: list[str] = []
- """Execute these commands before starting to run the agent. They will be executed in the same
- shell as the agent."""
+ post_startup_commands: list[str] = []
+ """Execute these commands before starting to run the agent but after all other setup steps.
+ They will be executed in the same shell as the agent."""
# pydantic config
model_config = ConfigDict(extra="forbid")
@@ -42,15 +41,24 @@ class SWEEnv:
*,
deployment: AbstractDeployment,
repo: Repo | RepoConfig | None,
- startup_commands: list[str],
+ post_startup_commands: list[str],
hooks: list[EnvHook] | None = None,
name: str = "main",
):
- """This class represents the environment in which we solve the tasks."""
+ """This class represents the environment in which we solve the tasks.
+
+ Args:
+ deployment: SWE-ReX deployment instance
+ repo: Repository configuration object, or anything following the `Repo` protocol
+ post_startup_commands: Commands to execute before starting the agent
+ hooks: Environment hooks (used to inject custom functionality)
+ Equivalent to calling `add_hook` for each hook after initialization.
+ name: Name of the environment
+ """
super().__init__()
self.deployment = deployment
self.repo = repo
- self._startup_commands = startup_commands
+ self._post_startup_commands = post_startup_commands
self.logger = get_logger("swea-env", emoji="🌱")
self.name = name
self.clean_multi_line_functions = lambda x: x
@@ -60,10 +68,14 @@ class SWEEnv:
@classmethod
def from_config(cls, config: EnvironmentConfig) -> Self:
+ """Create an environment instance from a configuration object.
+ This is the recommended way to create an environment instance, unless you need
+ more flexibility.
+ """
return cls(
deployment=get_deployment(config.deployment),
repo=config.repo,
- startup_commands=config.startup_commands,
+ post_startup_commands=config.post_startup_commands,
name=config.name,
)
@@ -80,6 +92,8 @@ class SWEEnv:
"""Start the environment and reset it to a clean state."""
self._init_deployment()
self.reset()
+ for command in self._post_startup_commands:
+ self.communicate(command, check=True)
def _copy_repo(self) -> None:
"""Clone/copy repository/codebase in container"""
@@ -205,3 +219,16 @@ class SWEEnv:
path_in_container = f"/{self.repo.repo_name}/{path}"
return self.communicate(f"cat {str(path_in_container)}")
+
+ def get_env_vars(self) -> dict[str, str]:
+ """Get all environment variables set in the environment."""
+ env_output = self.communicate("env", check=True).strip()
+ if not env_output:
+ return {}
+ return dict(line.split("=", 1) for line in env_output.split("\n"))
+
+ def set_env_variables(self, env_variables: dict[str, str]) -> None:
+ """Set environment variables in the environment."""
+ _env_setters = [f"export {k}={v}" for k, v in env_variables.items()]
+ command = " && ".join(_env_setters)
+ self.communicate(command, check=True)
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index 9ec0bae5..58e2a769 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -92,7 +92,7 @@ class RunReplay:
return SWEEnv(
deployment=self.deployment,
repo=self.repo,
- startup_commands=[],
+ post_startup_commands=[],
)
def _get_agent(self) -> Agent:
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index 61cbc4f7..f48c8878 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -189,7 +189,7 @@ class ToolHandler:
def reset(self, env: SWEEnv) -> None:
self.logger.info("Resetting tools")
- self._set_env_variables(env)
+ env.set_env_variables(self.config.env_variables)
env.communicate(" && ".join(self._reset_commands), check=True, timeout=self.config.install_timeout)
async def _upload_bundles(self, env: SWEEnv) -> None:
@@ -216,7 +216,7 @@ class ToolHandler:
def _install_commands(self, env: SWEEnv) -> None:
"""Make sure all commands are available in the container"""
- self._set_env_variables(env)
+ env.set_env_variables(self.config.env_variables)
cwd = env.communicate("pwd", check=True).strip()
asyncio.run(self._upload_bundles(env))
for bundle in self.config.bundles:
@@ -233,20 +233,9 @@ class ToolHandler:
timeout=self.config.install_timeout,
)
env.communicate(f"cd {cwd}", check=True)
- env_vars = self._get_env_vars(env)
+ env_vars = env.get_env_vars()
asyncio.run(self._check_available_commands(env, env_vars))
- def _get_env_vars(self, env: SWEEnv) -> dict[str, str]:
- env_output = env.communicate("env", check=True).strip()
- if not env_output:
- return {}
- return dict(line.split("=", 1) for line in env_output.split("\n"))
-
- def _set_env_variables(self, env: SWEEnv) -> None:
- _env_setters = [f"export {k}={v}" for k, v in self.config.env_variables.items()]
- command = " && ".join(_env_setters)
- env.communicate(command, check=True)
-
# Getting state
# -------------
diff --git a/tools/defaults/lib/flake8_utils.py b/tools/defaults/lib/flake8_utils.py
index 16783f46..a67c721f 100644
--- a/tools/defaults/lib/flake8_utils.py
+++ b/tools/defaults/lib/flake8_utils.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
-"""This helper command is used to print flake8 output"""
+"""This helper command is used to parse and print flake8 output."""
# ruff: noqa: UP007 UP006 UP035