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]
Adding more hooks to env and agent (#265)
Kilian Lieret19173bcfb42f
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 09d6c3cc..cbade019 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -225,6 +225,9 @@ class AgentHook:def on_actions_generated(self, *, thought: str, action: str, output: str):...+ def on_sub_action_started(self, *, sub_action: str):+ ...+def on_sub_action_executed(self, *, obs: str, done: bool):...@@ -233,6 +236,13 @@ class AgentHook:def on_run_done(self):...++ def on_model_query(self, *, query: str, agent: str):+ """Actually query the model with the complete history."""+ ...++ def on_query_message_added(self, *, role: str, content: str, agent: str, is_demo: bool = False, thought: str = "", action: str = ""):+ ...class Agent:@@ -258,7 +268,11 @@ class Agent:def add_hook(self, hook: AgentHook):hook.on_init()self.hooks.append(hook)-++ def _append_history(self, item: Dict):+ for hook in self.hooks:+ hook.on_query_message_added(**item)+ self.history.append(item)def setup(self, instance_args, init_model_stats=None) -> None:"""Setup the agent for a new instance."""@@ -269,9 +283,8 @@ class Agent:system_msg = self.config.system_template.format(**self.system_args)logger.info(f"SYSTEM ({self.name})\n{system_msg}")- self.history: List[Dict[str, Any]] = [- {"role": "system", "content": system_msg, "agent": self.name},- ]+ self.history: List[Dict[str, Any]] = []+ self._append_history({"role": "system", "content": system_msg, "agent": self.name})if len(self.config.demonstrations) > 0 and "history_to_messages" in dir(self.model@@ -304,7 +317,7 @@ class Agent:for entry in demo_history:if entry["role"] != "system":entry["is_demo"] = True- self.history.append(entry)+ self._append_history(entry)else:# Add demonstration as single message to historydemo_message = self.model.history_to_messages(@@ -314,7 +327,7 @@ class Agent:demonstration = self.config.demonstration_template.format(**{"demonstration": demo_message})- self.history.append(+ self._append_history({"agent": self.name,"content": demonstration,@@ -323,6 +336,7 @@ class Agent:})+@propertydef state_command(self) -> str:"""Return the bash command that will be used to extract the environment state."""@@ -494,7 +508,7 @@ class Agent:) -> Tuple[str, str, str]:thought, action, output = self.forward_with_error_check(observation, state)- self.history.append(+ self._append_history({"role": "assistant","content": output,@@ -548,8 +562,12 @@ class Agent:message = "\n".join(messages)logger.info(f"🤖 MODEL INPUT\n{message}")- self.history.append({"role": "user", "content": message, "agent": self.name})+ self._append_history(+ {"role": "user", "content": message, "agent": self.name}+ )+ for hook in self.hooks:+ hook.on_model_query(query=self.local_history, agent=self.name)return self.model.query(self.local_history)def retry_after_format_fail(self, output):@@ -738,7 +756,7 @@ class Agent:else:obs = Noneif env.returncode != 0:- self.history.append({"role": "user", "content": obs, "agent": agent_name})+ self._append_history({"role": "user", "content": obs, "agent": agent_name})raise RuntimeError(f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}")@@ -805,6 +823,8 @@ class Agent:sub_action["agent"] == self.nameor sub_action["cmd_name"] == self.config.submit_command):+ for hook in self.hooks:+ hook.on_sub_action_started(sub_action=sub_action)obs, _, done, info = env.step(sub_action["action"])for hook in self.hooks:hook.on_sub_action_executed(obs=obs, done=done)diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 4633528f..d117d9a3 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -77,6 +77,18 @@ class EnvironmentArguments(FrozenSerializable):repo_path: str = ""++class EnvHook:+ def on_init(self):+ ...++ def on_copy_repo_started(self, *, repo_type: str, repo_path: str):+ ...++ def on_install_env_started(self):+ ...++class SWEEnv(gym.Env):"""Gym environment for SWE-bench. This class should handle all communication with the docker container."""@@ -127,6 +139,11 @@ class SWEEnv(gym.Env):self.timeout = self.args.timeoutself.idx = 0self.clean_multi_line_functions = lambda x: x+ self.hooks = []++ def add_hook(self, hook: EnvHook):+ hook.on_init()+ self.hooks.append(hook)@propertydef _repo_name(self) -> str:@@ -140,6 +157,8 @@ class SWEEnv(gym.Env):folder name of clone"""assert self.record is not None # mypy+ for hook in self.hooks:+ hook.on_copy_repo_started(repo_type=self.record["repo_type"], repo_path=self.record["repo"])if self.record["repo_type"] == "local":copy_anything_to_container(self.container_obj, self.record["repo"].removeprefix("local://"), "/"+self._repo_name)self.communicate_with_handling(@@ -629,6 +648,8 @@ class SWEEnv(gym.Env):"Skipping conda environment installation."))return+ for hook in self.hooks:+ hook.on_install_env_started()if self.args.environment_setup is not None:assert isinstance(self.args.environment_setup, (str, os.PathLike))if Path(self.args.environment_setup).suffix in [".yml", ".yaml"]:diff --git a/tests/test_env.py b/tests/test_env.pyindex b1d7e7eb..8baa9aab 100644--- a/tests/test_env.py+++ b/tests/test_env.py@@ -4,7 +4,7 @@ from pathlib import Pathimport subprocessimport pytestimport yaml-from sweagent.environment.swe_env import EnvironmentArguments, SWEEnv+from sweagent.environment.swe_env import EnvHook, EnvironmentArguments, SWEEnvfrom contextlib import contextmanagerimport docker@@ -104,4 +104,11 @@ def test_communicate_old(test_env_args):except:raisefinally:- os.environ["SWE_AGENT_EXPERIMENTAL_COMMUNICATE"] = "1"\ No newline at end of file+ os.environ["SWE_AGENT_EXPERIMENTAL_COMMUNICATE"] = "1"+++def test_env_with_hook(test_env_args):+ with swe_env_context(test_env_args) as env:+ env.add_hook(EnvHook())+ env.reset()\ No newline at end of file