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]
Basic replay working again
Kilian Lieret7e34e587fe54
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 0ca3b84d..4579d960 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -218,6 +218,7 @@ class SubAction(TypedDict):args: str+# todo: separate out from_config. In particular separate out model (as a class, etc.)# todo: Can this class be split up into separate responsibilities?class Agent:"""Agent handles the behaviour of the model and how it interacts with the environment."""@@ -241,7 +242,7 @@ class Agent:self._parse_command_patterns()self.last_container_id = Noneself.hooks = []- self.logger = get_logger("agent")+ self.logger = get_logger("agent", emoji="🤠")# Requires instance, so is set in `setup` methodsself._rloop = None@@ -765,8 +766,6 @@ class Agent:self.logger.warning(f"Failed to set environment variables: {traceback.format_exc()}")raise ecommand_files = list()- print(self.config.command_files)- print([type(f) for f in self.config.command_files])for file in self.config.command_files:datum = dict()with open(file) as f:diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 309d676f..22d95d68 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -24,11 +24,12 @@ from sweagent.agent.commands import Commandfrom sweagent.utils.config import keys_configfrom sweagent.utils.log import get_logger-logger = get_logger("api_models")+logger = get_logger("lm", emoji="🤖")_MAX_RETRIES = int(keys_config.get("SWE_AGENT_MODEL_MAX_RETRIES", 10))+# todo: Separate out human model and replay modelclass ModelArguments(PydanticBaseModel):"""Arguments configuring the model and its behavior."""diff --git a/sweagent/environment/config/deployment.py b/sweagent/environment/config/deployment.pyindex a26e63ac..d7615d11 100644--- a/sweagent/environment/config/deployment.py+++ b/sweagent/environment/config/deployment.py@@ -1,12 +1,24 @@from typing import Literalfrom pydantic import BaseModel+from swerex.deployment import get_deployment+from swerex.deployment.abstract import AbstractDeployment+++def _get_deployment(config) -> AbstractDeployment:+ dtype = config.type+ config_dict = config.model_dump()+ del config_dict["type"]+ return get_deployment(dtype, **config_dict)class LocalDeploymentConfig(BaseModel):type: Literal["local"] = "local""""Discriminator for (de)serialization/CLI. Do not change."""+ def get_deployment(self) -> AbstractDeployment:+ return _get_deployment(self)+class DockerDeploymentConfig(BaseModel):"""Configuration for the deployment of the environment"""@@ -16,6 +28,9 @@ class DockerDeploymentConfig(BaseModel):type: Literal["docker"] = "docker""""Discriminator for (de)serialization/CLI. Do not change."""+ def get_deployment(self) -> AbstractDeployment:+ return _get_deployment(self)+class ModalDeploymentConfig(BaseModel):image: str = "sweagent/swe-agent:latest"@@ -23,5 +38,8 @@ class ModalDeploymentConfig(BaseModel):type: Literal["modal"] = "modal""""Discriminator for (de)serialization/CLI. Do not change."""+ def get_deployment(self) -> AbstractDeployment:+ return _get_deployment(self)+DeploymentConfig = DockerDeploymentConfig | ModalDeploymentConfig | LocalDeploymentConfigdiff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.pyindex 7a117e49..904e581d 100644--- a/sweagent/environment/config/repo.py+++ b/sweagent/environment/config/repo.py@@ -1,5 +1,6 @@import asyncioimport os+from abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Literal, Self@@ -12,7 +13,13 @@ from swerex.runtime.abstract import Command, UploadRequestfrom sweagent.utils.config import keys_config-class LocalRepoConfig(BaseModel):+class AbstractRepoConfig(ABC):+ @abstractmethod+ def copy(self, deployment: AbstractDeployment):+ pass+++class LocalRepoConfig(BaseModel, AbstractRepoConfig):path: str = ""base_commit: str = "HEAD"@@ -43,7 +50,7 @@ class LocalRepoConfig(BaseModel):raise RuntimeError(msg)-class GithubRepoConfig(BaseModel):+class GithubRepoConfig(BaseModel, AbstractRepoConfig):url: str = ""base_commit: str = "HEAD"diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 8a4b587c..abb6a0e2 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -5,16 +5,15 @@ import loggingimport reimport shlexfrom pathlib import PurePath-from typing import Any, Self+from typing import Selffrom pydantic import BaseModel, Field-from swerex.deployment import get_deploymentfrom swerex.deployment.abstract import AbstractDeploymentfrom swerex.runtime.abstract import BashAction, CreateBashSessionRequest, WriteFileRequestfrom sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfigfrom sweagent.environment.config.problem_statement import EmptyProblemStatement, ProblemStatementConfig-from sweagent.environment.config.repo import RepoConfig+from sweagent.environment.config.repo import AbstractRepoConfig, RepoConfigfrom sweagent.environment.hooks.abstract import EnvHookfrom sweagent.types import AgentInfofrom sweagent.utils.config import keys_config@@ -30,15 +29,10 @@ class EnvironmentInstanceConfig(BaseModel):"""Configure data sources and setup instructions for the environment in which we solve the tasks."""problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)- deployment: DeploymentConfig | None = None+ deployment: DeploymentConfig = Field(default_factory=DockerDeploymentConfig)repo: RepoConfig | None = Nonestartup_commands: list[str] = []- def model_post_init(self, __context: Any) -> None:- print("In model_post_init")- if self.deployment is None:- self.deployment = DockerDeploymentConfig()-class SWEEnv:"""Gym environment for SWE-bench. This class should handle all communication with the docker container."""@@ -50,17 +44,19 @@ class SWEEnv:*,deployment: AbstractDeployment,# todo: Should None be included in RepoConfig?- repo: RepoConfig | None,+ repo: AbstractRepoConfig | None,problem_statement: ProblemStatementConfig,startup_commands: list[str],hooks: list[EnvHook] | None = None,+ _catch_errors: bool = False,):super().__init__()+ self._catch_errors = _catch_errorsself.deployment = deploymentself.repo = repoself.problem_statement = problem_statementself._startup_commands = startup_commands- self.logger = get_logger("🌱 SWEEnv")+ self.logger = get_logger("swe_env", emoji="🌱")# todo: get rid of thisself.returncode: None | int = None@@ -76,10 +72,8 @@ class SWEEnv:@classmethoddef from_config(cls, config: EnvironmentInstanceConfig) -> Self:- deployment_kwargs = {k: v for k, v in config.deployment.model_dump().items() if k != "type"}- deployment = get_deployment(config.deployment.type, **deployment_kwargs) # type: ignorereturn cls(- deployment=deployment,+ deployment=config.deployment.get_deployment(),repo=config.repo,problem_statement=config.problem_statement,startup_commands=config.startup_commands,@@ -289,6 +283,8 @@ class SWEEnv:set_last_action=True,)except RuntimeError as e:+ if not self._catch_errors:+ raiseobservation += e.args[1] if len(e.args) > 1 else ""observation += "\nCOMMAND FAILED TO EXECUTE. RESTARTING PROCESS."info["exit_status"] = "early_exit"@@ -296,6 +292,8 @@ class SWEEnv:self.reset_container()return observation, 0, True, infoexcept Exception:+ if not self._catch_errors:+ raiseobservation += "\nEXECUTION FAILED OR COMMAND MALFORMED"self.logger.exception("Unknown exception")@@ -336,7 +334,7 @@ class SWEEnv:"""asyncio.run(self.deployment.start())asyncio.run(self.deployment.runtime.create_session(CreateBashSessionRequest(startup_source=["/root/.bashrc"])))- self.logger.info("🌱 Environment Initialized")+ self.logger.info("Environment Initialized")def _init_scripts(self):"""diff --git a/sweagent/run/_common.py b/sweagent/run/_common.pyindex df68adb8..6d62882b 100644--- a/sweagent/run/_common.py+++ b/sweagent/run/_common.py@@ -10,8 +10,9 @@ from sweagent import CONFIG_DIRclass BasicCLI:- def __init__(self, arg_type: type[BaseSettings]):+ def __init__(self, arg_type: type[BaseSettings], default_settings: bool = True):self.arg_type = arg_type+ self.default_settings = default_settingsdef get_args(self, args=None) -> BaseSettings:# The defaults if no config file is provided@@ -24,11 +25,12 @@ class BasicCLI:default=[],help="Load additional config files. Use this option multiple times to load multiple files, e.g., --config config1.yaml --config config2.yaml",)- parser.add_argument(- "--no-config-file",- action="store_true",- help="Do not load default config file when no config file is provided",- )+ if self.default_settings:+ parser.add_argument(+ "--no-config-file",+ action="store_true",+ help="Do not load default config file when no config file is provided",+ )parser.add_argument("--print-options",action="store_true",@@ -46,15 +48,12 @@ class BasicCLI:for _f in cli_args.config:_loaded = yaml.safe_load(Path(_f).read_text())config_merged.update(_loaded)- elif not cli_args.no_config_file:+ elif self.default_settings and not cli_args.no_config_file:config_merged = yaml.safe_load((CONFIG_DIR / "default.yaml").read_text())else:- config_merged = self.arg_type().model_dump()+ config_merged = {}# args = ScriptArguments.model_validate(config_merged)- print("-------")- print(remaining_args)- print("-------")args = CliApp.run(self.arg_type, remaining_args, **config_merged) # type: ignoreif cli_args.print_config: # type: ignoreprint(yaml.dump(args.model_dump()))diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.pyindex 7fca994a..69487fd1 100644--- a/sweagent/run/hooks/apply_patch.py+++ b/sweagent/run/hooks/apply_patch.py@@ -13,7 +13,7 @@ class SaveApplyPatchHook(RunHook):"""This hook saves patches to a separate directory and optionally applies them to a local repository."""def __init__(self, apply_patch_locally: bool = False):- self.logger = get_logger("⚡️ SaveApplyPatchHook")+ self.logger = get_logger("SaveApplyPatchHook", emoji="⚡️")self._apply_patch_locally = apply_patch_locallydef on_init(self, *, run):diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.pynew file mode 100644index 00000000..07c83187--- /dev/null+++ b/sweagent/run/run_replay.py@@ -0,0 +1,103 @@+"""Run on a single instance taken from github or similar."""++import json+import tempfile+from pathlib import Path+from typing import Self++import yaml+from pydantic import Field+from pydantic_settings import BaseSettings+from swerex.deployment.abstract import AbstractDeployment++from sweagent import CONFIG_DIR+from sweagent.agent.agents import Agent, AgentConfig+from sweagent.agent.models import ModelArguments+from sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfig+from sweagent.environment.config.problem_statement import EmptyProblemStatement+from sweagent.environment.config.repo import RepoConfig+from sweagent.environment.swe_env import SWEEnv+from sweagent.run._common import BasicCLI+from sweagent.run.run_single import RunSingle+from sweagent.utils.log import get_logger+++class RunReplayConfig(BaseSettings):+ traj_path: str+ config_path: str = str(CONFIG_DIR / "default.yaml")+ deployment: DeploymentConfig = Field(default_factory=DockerDeploymentConfig)+ repo: RepoConfig | None = None+ output_dir: str = "."+++class RunReplay:+ def __init__(+ self,+ *,+ traj_path: str,+ config_path: str,+ deployment: AbstractDeployment,+ repo: RepoConfig | None,+ output_dir: str,+ _catch_errors: bool = False,+ ):+ self.traj_path = traj_path+ self.config_path = config_path+ self.deployment = deployment+ self.repo = repo+ self.output_dir = output_dir+ self._replay_action_trajs_path = Path(tempfile.NamedTemporaryFile(suffix=".json").name)+ self.logger = get_logger("RunReplay", emoji="🏃")+ self._catch_errors = _catch_errors++ @property+ def instance_id(self) -> str:+ return Path(self.traj_path).stem++ @classmethod+ def from_config(cls, config: RunReplayConfig, **kwargs) -> Self:+ return cls(+ traj_path=config.traj_path,+ config_path=config.config_path,+ deployment=config.deployment.get_deployment(),+ repo=config.repo,+ output_dir=config.output_dir,+ **kwargs,+ )++ def _create_actions_file(self) -> None:+ traj_path = Path(self.traj_path)+ traj_data = json.loads(traj_path.read_text())+ actions = [x["content"] for x in traj_data["history"] if x["role"] == "assistant"]+ self._replay_action_trajs_path.write_text(json.dumps({self.instance_id: actions}))++ def _get_env(self) -> SWEEnv:+ return SWEEnv(+ deployment=self.deployment,+ repo=self.repo,+ problem_statement=EmptyProblemStatement(),+ startup_commands=[],+ _catch_errors=self._catch_errors,+ )++ def _get_agent(self) -> Agent:+ _agent_config = yaml.safe_load(Path(self.config_path).read_text())+ agent_config = AgentConfig(**_agent_config["agent"])+ agent_config.model = ModelArguments(name="replay", replay_path=str(self._replay_action_trajs_path))+ return Agent("replay", agent_config)++ def _get_run_single(self) -> RunSingle:+ return RunSingle(self._get_env(), self._get_agent())++ def main(self):+ self._create_actions_file()+ run_single = self._get_run_single()+ run_single.run()+++def main(args: RunReplayConfig):+ RunReplay.from_config(args).main()+++if __name__ == "__main__":+ main(BasicCLI(RunReplayConfig, default_settings=False).get_args()) # type: ignorediff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.pyindex f1ba03ce..a28129fa 100644--- a/sweagent/run/run_single.py+++ b/sweagent/run/run_single.py@@ -47,16 +47,18 @@ class RunSingle:*,traj_dir: str = ".",hooks: list[RunHook] | None = None,- actions: RunSingleActionConfig,+ actions: RunSingleActionConfig | None = None,):"""Note: When initializing this class, make sure to add the hooks that are required by your actions.See `from_config` for an example."""- self.logger = get_logger("PlaygroundMain")+ self.logger = get_logger("Run", emoji="🏃")self.env = envself.agent = agentself.traj_dir = traj_dirself._hooks = []+ if actions is not None:+ actions = RunSingleActionConfig()self.actions = actionsself._chooks = CombinedRunHooks()for hook in hooks or []:@@ -84,7 +86,7 @@ class RunSingle:hook.on_init(run=self)self._chooks.add_hook(hook)- def main(self):+ def run(self):self._chooks.on_start()self.logger.info("Starting environment")self.env.start()@@ -104,7 +106,7 @@ class RunSingle:def main(args: RunSingleConfig):- RunSingle.from_config(args).main()+ RunSingle.from_config(args).run()if __name__ == "__main__":diff --git a/sweagent/utils/log.py b/sweagent/utils/log.pyindex fd9bb5a6..5ef0ee18 100644--- a/sweagent/utils/log.py+++ b/sweagent/utils/log.py@@ -5,6 +5,7 @@ import osfrom pathlib import PurePathfrom rich.logging import RichHandler+from rich.text import Text_SET_UP_LOGGERS = set()_ADDITIONAL_HANDLERS = []@@ -25,7 +26,19 @@ _STREAM_LEVEL = _interpret_level_from_env(os.environ.get("SWE_AGENT_LOG_STREAM_L_FILE_LEVEL = _interpret_level_from_env(os.environ.get("SWE_AGENT_LOG_FILE_LEVEL"), default=logging.TRACE)-def get_logger(name: str) -> logging.Logger:+class _RichHandlerWithEmoji(RichHandler):+ def __init__(self, emoji: str, *args, **kwargs):+ super().__init__(*args, **kwargs)+ if not emoji.endswith(" "):+ emoji += " "+ self.emoji = emoji++ def get_level_text(self, record: logging.LogRecord) -> Text:+ level_name = record.levelname+ return Text.styled((self.emoji + level_name).ljust(10), f"logging.level.{level_name.lower()}")+++def get_logger(name: str, *, emoji: str = "") -> logging.Logger:"""Get logger. Use this instead of `logging.getLogger` to ensurethat the logger is set up with the correct handlers."""@@ -33,7 +46,8 @@ def get_logger(name: str) -> logging.Logger:if name in _SET_UP_LOGGERS:# Already set upreturn logger- handler = RichHandler(+ handler = _RichHandlerWithEmoji(+ emoji=emoji,show_time=bool(os.environ.get("SWE_AGENT_LOG_TIME", False)),show_path=False,)diff --git a/tests/_test_replay.py b/tests/test_replay.pysimilarity index 89%rename from tests/_test_replay.pyrename to tests/test_replay.pyindex 05968e79..725283c5 100644--- a/tests/_test_replay.py+++ b/tests/test_replay.py@@ -9,6 +9,23 @@ import pytestfrom run_replay import get_args, mainfrom sweagent import CONFIG_DIR+from sweagent.environment.config.deployment import DockerDeploymentConfig+from sweagent.run.run_replay import RunReplay, RunReplayConfig+++def test_replay(test_trajectories_path, tmp_path):+ 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"+ ),+ config_path=str(CONFIG_DIR / "default_from_url.yaml"),+ deployment=DockerDeploymentConfig(),+ output_dir=str(tmp_path),+ )+ rr = RunReplay.from_config(rc, _catch_errors=False)+ rr.main()@pytest.fixturediff --git a/tests/test_run.py b/tests/test_run.pyindex a35b8bed..1b9cbe13 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -1,7 +1,6 @@from __future__ import annotationsimport subprocess-from typing import Anyimport pytest@@ -22,7 +21,7 @@ def test_run_cli_help():class RaisesExceptionHook(RunHook):- def on_instance_start(self, *, index: int, instance: dict[str, Any]):+ def on_instance_start(self, *args, **kwargs):msg = "test exception"raise ValueError(msg)@@ -32,7 +31,7 @@ def test_run_single_raises_exception():rs = RunSingle.from_config(RunSingleConfig())rs.add_hook(RaisesExceptionHook())with pytest.raises(ValueError, match="test exception"):- rs.main()+ rs.run()@pytest.fixture@@ -54,4 +53,4 @@ def test_run_instant_empty_submit(agent_config_with_commands):agent=ac,)rs = RunSingle.from_config(rsc)- rs.main()+ rs.run()