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]
Ref, WIP: Move most changes to new run_shell entry
Kilian Lieret1e7151f6fcc2
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 2fa07dfe..01549fe3 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -24,7 +24,6 @@ from sweagent.agent.hooks.abstract import AbstractAgentHook, CombinedAgentHookfrom sweagent.agent.models import (AbstractModel,HumanModel,- HumanModelConfig,HumanThoughtModel,InstanceStats,ModelConfig,@@ -1227,9 +1226,7 @@ class DefaultAgent(AbstractAgent):self,env: SWEEnv,problem_statement: ProblemStatement | ProblemStatementConfig,- *,output_dir: Path = Path("."),- interactive: bool = False,) -> AgentRunResult:"""Run the agent on a problem instance. This method contains themain loop that repeatedly calls `self._step` until the problem is solved.@@ -1238,7 +1235,6 @@ class DefaultAgent(AbstractAgent):setup_args: Arguments to pass to the agent's setup method.env: The environment to run the agent on.traj_dir: Directory to save the trajectory to- interruptible: Whether the human can jump in by pressing ^C"""self.setup(env=env, problem_statement=problem_statement, output_dir=output_dir)@@ -1246,26 +1242,8 @@ class DefaultAgent(AbstractAgent):self._chook.on_run_start()step_output = StepOutput()while not step_output.done:- try:- step_output = self.step()- self.save_trajectory()- except KeyboardInterrupt:- if interactive and not isinstance(self.model, HumanModel):- self.human_step_in()- continue- raise- except EOFError:- if not interactive:- raise- # Can only happen if we have a human model, so switch back- self.logger.info("Detected ^D - switching back to AI mode")- self.human_step_out()- continue- if interactive and step_output.done and not isinstance(self.model, HumanModel):- # Human has to submit the solution- self.logger.info("Robot is done! Please submit the solution.")- self.human_step_in()- step_output.done = False+ step_output = self.step()+ self.save_trajectory()self._chook.on_run_done(trajectory=self.trajectory, info=self.info)self.logger.info("Trajectory saved to %s", self.traj_path)@@ -1274,31 +1252,3 @@ class DefaultAgent(AbstractAgent):# be the best submission instead of the last one, etc.), so we get it from the traj filedata = self.get_trajectory_data()return AgentRunResult(info=data["info"], trajectory=data["trajectory"])-- def human_step_in(self) -> None:- """Replace the current model with a HumanModel instance.- This allows for human intervention during agent execution.- """- self._original_model = self.model- self._original_parser = self.tools.config.parse_function-- human_config = HumanModelConfig(name="human", catch_eof=False)- self.model = get_model(human_config, self.tools.config)- self.tools.config.parse_function = ActionOnlyParser()-- self.logger.info("Switched to human mode. Agent will now accept human input. Press ^D to switch back.")-- def human_step_out(self) -> None:- """Switch back to the original model from human mode.- This is called when ^D is pressed in human mode.- """- if not hasattr(self, "_original_model") or self._original_model is None:- self.logger.info("No previous model to switch back to. Remaining in current mode.")- return-- self.model = self._original_model- self.tools.config.parse_function = self._original_parser # type: ignore- self._original_model = None- self._original_parser = None-- self.logger.info("Switched back to AI model mode.")diff --git a/sweagent/agent/extra/shell_agent.py b/sweagent/agent/extra/shell_agent.pynew file mode 100644index 00000000..1a10e165--- /dev/null+++ b/sweagent/agent/extra/shell_agent.py@@ -0,0 +1,94 @@+from pathlib import Path++from sweagent.agent.agents import DefaultAgent+from sweagent.agent.models import HumanModel, HumanModelConfig, get_model+from sweagent.agent.problem_statement import ProblemStatement, ProblemStatementConfig+from sweagent.environment.swe_env import SWEEnv+from sweagent.tools.parsing import ActionOnlyParser+from sweagent.types import AgentRunResult, StepOutput+++# todo: use different config class+class ShellAgent(DefaultAgent):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)++ def human_step_in(self) -> None:+ """Replace the current model with a HumanModel instance.+ This allows for human intervention during agent execution.+ """+ self._original_model = self.model+ self._original_parser = self.tools.config.parse_function++ human_config = HumanModelConfig(name="human", catch_eof=False)+ self.model = get_model(human_config, self.tools.config)+ self.tools.config.parse_function = ActionOnlyParser()++ self.logger.info("Switched to human mode. Agent will now accept human input. Press ^D to switch back.")++ def human_step_out(self) -> None:+ """Switch back to the original model from human mode.+ This is called when ^D is pressed in human mode.+ """+ if not hasattr(self, "_original_model") or self._original_model is None:+ self.logger.info("No previous model to switch back to. Remaining in current mode.")+ return++ self.model = self._original_model+ self.tools.config.parse_function = self._original_parser # type: ignore+ self._original_model = None+ self._original_parser = None++ self.logger.info("Switched back to AI model mode.")++ def run(+ self,+ env: SWEEnv,+ problem_statement: ProblemStatement | ProblemStatementConfig,+ *,+ output_dir: Path = Path("."),+ interactive: bool = False,+ ) -> AgentRunResult:+ """Run the agent on a problem instance. This method contains the+ main loop that repeatedly calls `self._step` until the problem is solved.++ Args:+ setup_args: Arguments to pass to the agent's setup method.+ env: The environment to run the agent on.+ traj_dir: Directory to save the trajectory to+ interruptible: Whether the human can jump in by pressing ^C+ """+ self.setup(env=env, problem_statement=problem_statement, output_dir=output_dir)++ # Run action/observation loop+ self._chook.on_run_start()+ step_output = StepOutput()+ while not step_output.done:+ try:+ step_output = self.step()+ self.save_trajectory()+ except KeyboardInterrupt:+ if interactive and not isinstance(self.model, HumanModel):+ self.human_step_in()+ continue+ raise+ except EOFError:+ if not interactive:+ raise+ # Can only happen if we have a human model, so switch back+ self.logger.info("Detected ^D - switching back to AI mode")+ self.human_step_out()+ continue+ if interactive and step_output.done and not isinstance(self.model, HumanModel):+ # Human has to submit the solution+ self.logger.info("Robot is done! Please submit the solution.")+ self.human_step_in()+ step_output.done = False+ self._chook.on_run_done(trajectory=self.trajectory, info=self.info)++ self.logger.info("Trajectory saved to %s", self.traj_path)++ # Here we want to return the "global" information (e.g., submission should+ # be the best submission instead of the last one, etc.), so we get it from the traj file+ data = self.get_trajectory_data()+ return AgentRunResult(info=data["info"], trajectory=data["trajectory"])diff --git a/sweagent/run/run_shell.py b/sweagent/run/run_shell.pynew file mode 100644index 00000000..85e46132--- /dev/null+++ b/sweagent/run/run_shell.py@@ -0,0 +1,174 @@+"""[cyan][bold]Run SWE-agent in semi-interactive mode.[/bold][/cyan]++[cyan][bold]sweagen-sh is EXPERIMENTAL[/bold][/cyan]++[cyan][bold]=== BASIC OPTIONS ===[/bold][/cyan]++ -h --help Show help text and exit+ --help_option Print specific help text and exit+ --config CONFIG Load additional config files. Use this option multiple times to load+ multiple files, e.g., --config config1.yaml --config config2.yaml++"""++import getpass+import sys+from pathlib import Path+from typing import Self++import yaml+from pydantic import Field+from pydantic_settings import BaseSettings, SettingsConfigDict++from sweagent.agent.agents import AbstractAgent, AgentConfig, get_agent_from_config+from sweagent.agent.problem_statement import (+ EmptyProblemStatement,+ ProblemStatement,+ ProblemStatementConfig,+)+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv+from sweagent.run.common import AutoCorrectSuggestion as ACS+from sweagent.run.common import BasicCLI, ConfigHelper, save_predictions+from sweagent.run.hooks.abstract import CombinedRunHooks, RunHook+from sweagent.utils.config import load_environment_variables+from sweagent.utils.log import add_file_handler, get_logger+++class RunSingleConfig(BaseSettings, cli_implicit_flags=False):+ env: EnvironmentConfig = Field(default_factory=EnvironmentConfig, description="Environment options.")+ agent: AgentConfig = Field(description="Agent options.")+ problem_statement: ProblemStatementConfig = Field(+ default_factory=EmptyProblemStatement, description="Problem statement options."+ )+ output_dir: Path = Field(default=Path("DEFAULT"), description="Output directory.")++ env_var_path: Path | None = None+ """Path to a .env file to load environment variables from."""++ interactive: bool = False+ """Whether to make the agent interactive (i.e., allow the human to jump in by pressing ^C)."""++ # pydantic config+ model_config = SettingsConfigDict(extra="forbid", env_prefix="SWE_AGENT_")++ 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+ try:+ model_id = self.agent.model.id # type: ignore[attr-defined]+ except AttributeError:+ model_id = "unknown_model"+ config_file = getattr(self, "_config_files", ["no_config"])[0]+ if isinstance(config_file, Path):+ config_file = config_file.stem+ self.output_dir = Path.cwd() / "trajectories" / user_id / f"{config_file}__{model_id}___{problem_id}"++ @classmethod+ def _get_auto_correct(cls) -> list[ACS]:+ return [+ ACS("model", "agent.model.name"),+ ACS("agent.model", "agent.model.name"),+ ACS("model.name", "agent.model.name"),+ ACS("per_instance_cost_limit", "agent.model.per_instance_cost_limit"),+ ACS("model.per_instance_cost_limit", "agent.model.per_instance_cost_limit"),+ ACS("config_file", "config"),+ ]+++class RunSingle:+ def __init__(+ self,+ env: SWEEnv,+ agent: AbstractAgent,+ problem_statement: ProblemStatement | ProblemStatementConfig,+ *,+ output_dir: Path = Path("."),+ hooks: list[RunHook] | None = None,+ interactive: bool = False,+ ):+ """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("swea-run", emoji="🏃")+ instance_id = problem_statement.id+ _log_filename_template = f"{instance_id}.{{level}}.log"+ for level in ["trace", "debug", "info"]:+ add_file_handler(+ output_dir / instance_id / _log_filename_template.format(level=level),+ level=level,+ id_=f"{instance_id}-{level}",+ )+ self.env = env+ self.agent = agent+ self.output_dir = output_dir+ self._hooks = []+ self._chooks = CombinedRunHooks()+ self.problem_statement = problem_statement+ for hook in hooks or []:+ self.add_hook(hook)+ self.interactive = interactive++ @property+ def hooks(self) -> list[RunHook]:+ return self._chooks.hooks++ @classmethod+ def from_config(cls, config: RunSingleConfig) -> Self:+ load_environment_variables(config.env_var_path)+ config.set_default_output_dir()+ config.output_dir.mkdir(parents=True, exist_ok=True)+ agent = get_agent_from_config(config.agent)+ agent.replay_config = config # type: ignore[attr-defined]+ return cls(+ env=SWEEnv.from_config(config.env),+ agent=agent,+ problem_statement=config.problem_statement,+ output_dir=config.output_dir,+ interactive=config.interactive,+ )++ def add_hook(self, hook: RunHook) -> None:+ hook.on_init(run=self)+ self._chooks.add_hook(hook)++ def run(self):+ self._chooks.on_start()+ self.logger.info("Starting environment")+ self.env.start()+ self.logger.info("Running agent")+ self._chooks.on_instance_start(index=0, env=self.env, problem_statement=self.problem_statement)+ output_dir = self.output_dir / self.problem_statement.id+ output_dir.mkdir(parents=True, exist_ok=True)+ if self.agent.replay_config is not None: # type: ignore[attr-defined]+ (output_dir / "config.yaml").write_text(yaml.dump(self.agent.replay_config.model_dump_json(), indent=2)) # type: ignore[attr-defined]+ result = self.agent.run(+ problem_statement=self.problem_statement,+ env=self.env,+ output_dir=output_dir,+ )+ self._chooks.on_instance_completed(result=result)+ self.logger.info("Done")+ self._chooks.on_end()+ save_predictions(self.output_dir, self.problem_statement.id, result)+ self.env.close()+++def run_from_config(config: RunSingleConfig):+ RunSingle.from_config(config).run()+++def run_from_cli(args: list[str] | None = None):+ if args is None:+ args = sys.argv[1:]+ assert __doc__ is not None+ help_text = ( # type: ignore+ __doc__ + "\n[cyan][bold]=== ALL THE OPTIONS ===[/bold][/cyan]\n\n" + ConfigHelper().get_help(RunSingleConfig)+ )+ run_from_config(BasicCLI(RunSingleConfig, help_text=help_text).get_config(args)) # type: ignore+++if __name__ == "__main__":+ run_from_cli()diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.pyindex dfcdc43c..8ba4f77b 100644--- a/sweagent/run/run_single.py+++ b/sweagent/run/run_single.py@@ -78,9 +78,6 @@ class RunSingleConfig(BaseSettings, cli_implicit_flags=False):env_var_path: Path | None = None"""Path to a .env file to load environment variables from."""- interactive: bool = False- """Whether to make the agent interactive (i.e., allow the human to jump in by pressing ^C)."""-# pydantic configmodel_config = SettingsConfigDict(extra="forbid", env_prefix="SWE_AGENT_")@@ -130,7 +127,6 @@ class RunSingle:output_dir: Path = Path("."),hooks: list[RunHook] | None = None,actions: RunSingleActionConfig | None = None,- interactive: bool = False,):"""Note: When initializing this class, make sure to add the hooks that are required by your actions.See `from_config` for an example.@@ -155,7 +151,6 @@ class RunSingle:self.problem_statement = problem_statementfor hook in hooks or []:self.add_hook(hook)- self.interactive = interactive@propertydef hooks(self) -> list[RunHook]:@@ -174,7 +169,6 @@ class RunSingle:problem_statement=config.problem_statement,output_dir=config.output_dir,actions=config.actions,- interactive=config.interactive,)self.add_hook(SaveApplyPatchHook(apply_patch_locally=config.actions.apply_patch_locally))if config.actions.open_pr:@@ -200,7 +194,6 @@ class RunSingle:problem_statement=self.problem_statement,env=self.env,output_dir=output_dir,- interactive=self.interactive,)self._chooks.on_instance_completed(result=result)self.logger.info("Done")