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]

Set sensible default trajectory paths

Kilian Lieret9ab026282b54
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index cdcc9cb8..873bc909 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -61,6 +61,10 @@ class GenericAPIModelConfig(PydanticBaseModel):
# pydantic
model_config = ConfigDict(extra="forbid")
+ @property
+ def id(self) -> str:
+ return f"{self.name}__t-{self.temperature:.2f}__p-{self.top_p:.2f}__c-{self.per_instance_cost_limit:.2f}"
+
class ReplayModelConfig(GenericAPIModelConfig):
replay_path: Path
diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.py
index 738771bd..045869c0 100644
--- a/sweagent/run/batch_instances.py
+++ b/sweagent/run/batch_instances.py
@@ -97,6 +97,10 @@ class InstancesFromFile(BaseModel, AbstractInstanceSource):
instances = [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]
return _filter_batch_items(instances, self.filter)
+ @property
+ def id(self) -> str:
+ return self.path.stem
+
class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):
"""Load instances from HuggingFace."""
@@ -118,6 +122,10 @@ class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):
instances = [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]
return _filter_batch_items(instances, self.filter)
+ @property
+ def id(self) -> str:
+ return "".join(l for l in self.dataset_name if l.isalnum())
+
class SWEBenchInstances(BaseModel, AbstractInstanceSource):
"""Load instances from SWE-bench."""
@@ -135,6 +143,10 @@ class SWEBenchInstances(BaseModel, AbstractInstanceSource):
def get_instance_configs(self) -> list[BatchInstance]:
raise NotImplementedError
+ @property
+ def id(self) -> str:
+ return f"swe_bench_{self.flavor}"
+
class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
"""Load instances from a file. The difference to `InstancesFromFile` is that the instances are configured as full
@@ -152,5 +164,9 @@ class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
instances = [BatchInstance(**instance_dict) for instance_dict in instance_dicts]
return _filter_batch_items(instances, self.filter)
+ @property
+ def id(self) -> str:
+ return self.path.stem
+
BatchInstanceSourceConfig = InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances | ExpertInstancesFromFile
diff --git a/sweagent/run/common.py b/sweagent/run/common.py
index edfafd4e..809639d0 100644
--- a/sweagent/run/common.py
+++ b/sweagent/run/common.py
@@ -50,7 +50,9 @@ class BasicCLI:
exit(0)
config_merged = {}
+ config_files = []
if cli_args.config:
+ config_files.extend(cli_args.config)
for _f in cli_args.config:
txt = Path(_f).read_text()
if not txt.strip():
@@ -60,6 +62,7 @@ class BasicCLI:
config_merged.update(_loaded)
elif self.default_settings and not cli_args.no_config_file:
config_file = CONFIG_DIR / "default.yaml"
+ config_files.append(config_file)
self.logger.info(f"Loading default config from {config_file}")
txt = config_file.read_text()
if not txt.strip():
@@ -81,6 +84,8 @@ class BasicCLI:
if cli_args.print_config: # type: ignore
print(yaml.dump(args.model_dump()))
exit(0)
+
+ args._config_files = config_files # type: ignore
return args
diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.py
index acaade5b..0334262c 100644
--- a/sweagent/run/hooks/apply_patch.py
+++ b/sweagent/run/hooks/apply_patch.py
@@ -22,7 +22,7 @@ class SaveApplyPatchHook(RunHook):
self._apply_patch_locally = apply_patch_locally
def on_init(self, *, run):
- self._traj_dir = Path(run.traj_dir)
+ self._output_dir = Path(run.output_dir)
def on_instance_start(self, *, index: int, env: SWEEnv, problem_statement: ProblemStatementConfig):
self._env = env
@@ -74,7 +74,7 @@ class SaveApplyPatchHook(RunHook):
Returns:
The path to the patch file, if it was saved. Otherwise, returns None.
"""
- patch_output_dir = self._traj_dir
+ patch_output_dir = self._output_dir
patch_output_dir.mkdir(exist_ok=True, parents=True)
patch_output_file = patch_output_dir / f"{instance_id}.patch"
if info.get("submission") is None:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 998c9847..73af8f08 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -2,6 +2,7 @@
Run on a batch of instances/issues. For example run on all of SWE-bench.
"""
+import getpass
import json
import sys
import traceback
@@ -23,12 +24,24 @@ from sweagent.utils.log import get_logger
class RunBatchConfig(BaseSettings, cli_implicit_flags=True):
instances: BatchInstanceSourceConfig
agent: AgentConfig
- traj_dir: Path = Path(".")
+ output_dir: Path = Path("DEFAULT")
raise_exceptions: bool = False
redo_existing: bool = False
env_var_path: Path | None = None
"""Path to a .env file to load environment variables from."""
+ def set_default_output_dir(self) -> None:
+ # Needs to be called explicitly, because self._config_files will be setup
+ # post-init.
+ if self.output_dir == Path("DEFAULT"):
+ user_id = getpass.getuser()
+ source_id = self.instances.id
+ model_id = self.agent.model.id
+ config_file = getattr(self, "_config_files", ["no_config"])[0]
+ if isinstance(config_file, Path):
+ config_file = config_file.name
+ self.output_dir = Path.cwd() / "trajectories" / user_id / f"{config_file}__{model_id}___{source_id}"
+
class _BreakLoop(Exception):
"""Used for internal control flow"""
@@ -40,7 +53,7 @@ class RunBatch:
instances: list[BatchInstance],
agent: Agent,
*,
- traj_dir: Path = Path("."),
+ output_dir: Path = Path("."),
hooks: list[RunHook] | None = None,
raise_exceptions: bool = False,
redo_existing: bool = False,
@@ -54,7 +67,7 @@ class RunBatch:
self.logger = get_logger("Run", emoji="🏃")
self.instances = instances
self.agent = agent
- self.traj_dir = traj_dir
+ self.output_dir = output_dir
self._hooks = []
self._raise_exceptions = raise_exceptions
self._chooks = CombinedRunHooks()
@@ -65,6 +78,8 @@ class RunBatch:
@classmethod
def from_config(cls, config: RunBatchConfig) -> Self:
load_environment_variables(config.env_var_path)
+ config.set_default_output_dir()
+ config.output_dir.mkdir(parents=True, exist_ok=True)
logger = get_logger("RunBatch", emoji="🏃")
logger.debug("Loading instances from %s", f"{config.instances!r}")
instances = config.instances.get_instance_configs()
@@ -79,7 +94,7 @@ class RunBatch:
return cls(
instances=instances,
agent=Agent.from_config(config.agent),
- traj_dir=config.traj_dir,
+ output_dir=config.output_dir,
raise_exceptions=config.raise_exceptions,
)
@@ -128,9 +143,9 @@ class RunBatch:
result = self.agent.run(
problem_statement=instance.problem_statement,
env=env,
- output_dir=Path(self.traj_dir),
+ output_dir=Path(self.output_dir),
)
- save_predictions(self.traj_dir, instance.problem_statement.id, result)
+ save_predictions(self.output_dir, instance.problem_statement.id, result)
self._chooks.on_instance_completed(result=result)
env.close()
@@ -140,7 +155,7 @@ class RunBatch:
return False
# Check if there's an existing trajectory for this instance
- log_path = self.traj_dir / (instance.problem_statement.id + ".traj")
+ log_path = self.output_dir / (instance.problem_statement.id + ".traj")
if not log_path.exists():
return False
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index 1801dcc5..734d017f 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -3,8 +3,9 @@
import json
import sys
import tempfile
+from getpass import getpass
from pathlib import Path
-from typing import Self
+from typing import Any, Self
import yaml
from pydantic import Field
@@ -25,24 +26,32 @@ from sweagent.utils.log import get_logger
class RunReplayConfig(BaseSettings):
- traj_path: str
- config_path: str = str(CONFIG_DIR / "default.yaml")
+ traj_path: Path
+ config_path: Path = CONFIG_DIR / "default.yaml"
deployment: DeploymentConfig = Field(default_factory=DockerDeploymentConfig)
repo: RepoConfig | None = None
- output_dir: str = "."
+ output_dir: Path = Path("DEFAULT")
env_var_path: Path | None = None
"""Path to a .env file to load environment variables from."""
+ def model_post_init(self, __context: Any) -> None:
+ if self.output_dir == Path("DEFAULT"):
+ user_id = getpass.getuser()
+ self.output_dir = (
+ Path.cwd() / "trajectories" / user_id / f"{self.config_path.name}__replay___{self.traj_path.stem}"
+ )
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
class RunReplay:
def __init__(
self,
*,
- traj_path: str,
- config_path: str,
+ traj_path: Path,
+ config_path: Path,
deployment: AbstractDeployment,
repo: RepoConfig | None,
- output_dir: str,
+ output_dir: Path,
_catch_errors: bool = False,
_require_zero_exit_code: bool = False,
):
@@ -87,7 +96,7 @@ class RunReplay:
def _get_agent(self) -> Agent:
_agent_config = yaml.safe_load(Path(self.config_path).read_text())["agent"]
- _agent_config["model"] = ReplayModelConfig(replay_path=str(self._replay_action_trajs_path)).model_dump()
+ _agent_config["model"] = ReplayModelConfig(replay_path=self._replay_action_trajs_path).model_dump()
agent_config = AgentConfig(**_agent_config)
agent = Agent.from_config(agent_config)
agent._catch_errors = self._catch_errors
@@ -99,7 +108,7 @@ class RunReplay:
self._get_env(),
self._get_agent(),
problem_statement=EmptyProblemStatement(),
- traj_dir=Path(self.output_dir),
+ output_dir=Path(self.output_dir),
)
def main(self):
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index 98ac68a5..309bbdde 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 getpass
import sys
from pathlib import Path
from typing import Self
@@ -37,7 +38,11 @@ class RunSingleConfig(BaseSettings, cli_implicit_flags=True):
env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
agent: AgentConfig
problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
- traj_dir: Path = Path(".")
+ output_dir: Path = Path("DEFAULT")
+ """Directory to save the trajectory and similar output files to. If None, a default location
+ based on user ID, problem statement ID and model is used.
+ """
+
actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
print_config: bool = False
@@ -49,6 +54,18 @@ class RunSingleConfig(BaseSettings, cli_implicit_flags=True):
# pydantic config
model_config = ConfigDict(extra="forbid") # type: ignore
+ def set_default_output_dir(self) -> None:
+ # Needs to be called explicitly, because self._config_files will be setup
+ # post-init.
+ if self.output_dir == Path("DEFAULT"):
+ user_id = getpass.getuser()
+ problem_id = self.problem_statement.id
+ model_id = self.agent.model.id
+ config_file = getattr(self, "_config_files", ["no_config"])[0]
+ if isinstance(config_file, Path):
+ config_file = config_file.name
+ self.output_dir = Path.cwd() / "trajectories" / user_id / f"{config_file}__{model_id}___{problem_id}"
+
class RunSingle:
def __init__(
@@ -57,7 +74,7 @@ class RunSingle:
agent: Agent,
problem_statement: ProblemStatement | ProblemStatementConfig,
*,
- traj_dir: Path = Path("."),
+ output_dir: Path = Path("."),
hooks: list[RunHook] | None = None,
actions: RunSingleActionConfig | None = None,
):
@@ -67,7 +84,7 @@ class RunSingle:
self.logger = get_logger("Run", emoji="🏃")
self.env = env
self.agent = agent
- self.traj_dir = traj_dir
+ self.output_dir = output_dir
self._hooks = []
if actions is not None:
actions = RunSingleActionConfig()
@@ -88,11 +105,13 @@ class RunSingle:
config_str = yaml.dump(config.model_dump())
logger.info(f"Config:\n {config_str}")
load_environment_variables(config.env_var_path)
+ config.set_default_output_dir()
+ config.output_dir.mkdir(parents=True, exist_ok=True)
self = cls(
env=SWEEnv.from_config(config.env),
agent=Agent.from_config(config.agent),
problem_statement=config.problem_statement,
- traj_dir=config.traj_dir,
+ output_dir=config.output_dir,
actions=config.actions,
)
self.add_hook(SaveApplyPatchHook(apply_patch_locally=config.actions.apply_patch_locally))
@@ -116,12 +135,12 @@ class RunSingle:
result = self.agent.run(
problem_statement=self.problem_statement,
env=self.env,
- output_dir=Path(self.traj_dir),
+ output_dir=Path(self.output_dir),
)
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)
+ save_predictions(self.output_dir, self.problem_statement.id, result)
self.env.close()
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index d3ab854f..e8f2d5cc 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -5,8 +5,8 @@ from pathlib import Path
from typing import Any, Self
from pydantic import BaseModel, Field
-from swerex.runtime.abstract import BashAction, WriteFileRequest
from swerex.runtime.abstract import Command as RexCommand
+from swerex.runtime.abstract import WriteFileRequest
from sweagent.environment.swe_env import SWEEnv
from sweagent.tools.commands import Command, ParseCommand, ParseCommandBash
@@ -196,26 +196,18 @@ class ToolHandler:
env.deployment.runtime.write_file(WriteFileRequest(content=contents, path=f"/root/commands/{name}"))
)
if source:
- self._reset_commands.append(f"source /root/commands/{name}")
+ self._reset_commands.append(f"source '/root/commands/{name}'")
if mark_executable:
asyncio.run(
env.deployment.runtime.execute(
- RexCommand(command=f"chmod +x /root/commands/{name}", shell=True, check=True)
+ RexCommand(command=f"chmod +x '/root/commands/{name}'", shell=True, check=True)
)
)
for command in self.config.install_commands:
- asyncio.run(
- env.deployment.runtime.run_in_session(
- BashAction(command=command, timeout=self.config.install_timeout, check=True)
- )
- )
+ env.communicate(command, check=True, timeout=self.config.install_timeout)
def _make_state_command_available(self, env: SWEEnv) -> None:
- asyncio.run(
- env.deployment.runtime.run_in_session(
- BashAction(command=self.config.state_command.code, timeout=1, check=True)
- )
- )
+ env.communicate(self.config.state_command.code, check=True, timeout=1)
def _set_env_variables(self, env: SWEEnv) -> None:
_env_setters = [f"export {k}={v}" for k, v in self.config.env_variables.items()]
diff --git a/tests/test_run_batch.py b/tests/test_run_batch.py
index a146ab6e..9838fe0e 100644
--- a/tests/test_run_batch.py
+++ b/tests/test_run_batch.py
@@ -17,7 +17,7 @@ def test_expert_instances(test_data_sources_path: Path, tmp_path: Path):
"expert_file",
"--instances.path",
str(ds_path),
- "--traj_dir",
+ "--output_dir",
str(tmp_path),
"--raise_exceptions",
]
@@ -36,7 +36,7 @@ def test_simple_instances(test_data_sources_path: Path, tmp_path: Path):
"instant_empty_submit",
"--instances.path",
str(ds_path),
- "--traj_dir",
+ "--output_dir",
str(tmp_path),
"--raise_exceptions",
]
@@ -53,7 +53,7 @@ def test_empty_instances_simple(test_data_sources_path: Path, tmp_path: Path):
"instant_empty_submit",
"--instances.path",
str(ds_path),
- "--traj_dir",
+ "--output_dir",
str(tmp_path),
"--raise_exceptions",
"--instances.filter",
@@ -74,7 +74,7 @@ def test_empty_instances_expert(test_data_sources_path: Path, tmp_path: Path):
str(ds_path),
"--instances.type",
"expert_file",
- "--traj_dir",
+ "--output_dir",
str(tmp_path),
"--raise_exceptions",
"--instances.filter",
diff --git a/tests/test_run_single.py b/tests/test_run_single.py
index 6d6acf21..2527c80b 100644
--- a/tests/test_run_single.py
+++ b/tests/test_run_single.py
@@ -44,7 +44,7 @@ def test_run_ies(tmpdir, agent_config_with_commands):
rsc = RunSingleConfig(
env=EnvironmentConfig(),
agent=ac,
- traj_dir=Path(tmpdir),
+ output_dir=Path(tmpdir),
)
rs = RunSingle.from_config(rsc)
rs.run()
@@ -79,7 +79,7 @@ def test_run_ies_repo_ps_matrix(
args = [
"--agent.model.name=instant_empty_submit",
"--print_config",
- "--traj_dir",
+ "--output_dir",
str(tmpdir),
*ps_args,
*repo_args,