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]

Basic run functionality restored

Kilian Lieret74a516cfd2ca
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index d98c7ea6..0ca3b84d 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -186,9 +186,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_action_started(self, *, action: str): ...
- def on_sub_action_executed(self, *, obs: str, done: bool): ...
+ def on_action_executed(self, *, obs: str, done: bool): ...
def on_step_done(self, *, trajectory_step: TrajectoryStep, model_stats: APIStats): ...
@@ -305,7 +305,7 @@ class Agent:
The path is reset for every new instance.
"""
if self.traj_dir and self._env is not None:
- return self.traj_dir / (self._env.instance.id + ".traj")
+ return self.traj_dir / (self._env.problem_statement.id + ".traj")
return None
def add_hook(self, hook: AgentHook) -> None:
@@ -509,50 +509,8 @@ class Agent:
rem_action = ""
return "\n".join(parsed_action)
- # todo: Do we still need that now that we don't have subroutines
- def split_actions(self, action: str, pattern_type="subroutine") -> list[SubAction]:
- """Split an action into a list of actions in a greedy manner, each of which is a subroutine call or a single command."""
- parsed_action: list[SubAction] = list()
- rem_action = action
- while rem_action.strip():
- first_match = self._get_first_match(rem_action, pattern_type)
- if first_match:
- pre_action = rem_action[: first_match.start()]
- match_action = rem_action[first_match.start() : first_match.end()]
- rem_action = rem_action[first_match.end() :]
- if pre_action.strip():
- parsed_action.append({"agent": self.name, "action": pre_action, "cmd_name": None, "args": ""})
- if match_action.strip():
- if match_action.split()[0] == self.config.submit_command:
- parsed_action.append(
- SubAction(
- {
- "agent": self.name,
- "action": match_action,
- "cmd_name": first_match.group(1),
- "args": "",
- },
- )
- ) # submit command is not a subroutine
- else:
- parsed_action.append(
- SubAction(
- {
- "agent": first_match.group(1),
- "args": first_match.group(2),
- "action": match_action,
- "cmd_name": first_match.group(1),
- },
- )
- )
- else:
- parsed_action.append(
- SubAction({"agent": self.name, "action": rem_action, "cmd_name": None, "args": ""})
- )
- rem_action = ""
- return parsed_action
-
def _parse_command_patterns(self) -> None:
+ """Sets self.command_patterns and self.subroutine_patterns"""
assert self.config is not None # mypy
self.command_patterns = dict()
for command in self.config.commands:
@@ -577,7 +535,8 @@ class Agent:
self.command_patterns[self.config.submit_command] = submit_pat
def forward(self, observation: str | None, available_actions: list[str], state: str) -> tuple[str, str, str]:
- """Forwards the model
+ """Forwards the model, i.e., queries the model with the current trajectory and observation.
+ This is identical to `self.forward_with_error_check`, but adds the output to the trajectory.
Args:
observation: Observation
@@ -608,6 +567,7 @@ class Agent:
def forward_model(self, observation: str | None, state: str) -> str:
"""Query the model with the current state and observation with the appropriate template.
+ In most cases you want to use `self.forward_with_error_check` instead to handle requeueing etc.
Returns:
output: raw model output (not output of the command)
@@ -699,7 +659,8 @@ class Agent:
self,
output: str,
) -> tuple[str, str, str]:
- """Query the model with the current state and observation with the appropriate template.
+ """Checks model output. If the output is malformatted or the action is blocked, call
+ `self.retry_after_format_fail` or `self.retry_after_blocklist_fail`.
Try to parse the output into a thought and action. Retry if the output is malformatted or the action is blocked.
@@ -843,20 +804,7 @@ class Agent:
env_vars[var] = env.communicate(f"echo ${var}").strip()
return env_vars
- # def _update_summarizer_stats(self, cost: APIStats):
- # """Update stats for summarizer"""
- # self.model.stats += cost
- # if "summarizer" not in self.info:
- # self.info["summarizer"] = {
- # "model_stats": APIStats().to_dict(),
- # "n_calls": 0,
- # }
- # total_cost = APIStats(**self.info["summarizer"]["model_stats"])
- # total_cost += cost
- # self.info["summarizer"]["model_stats"] = total_cost.to_dict()
- # self.info["summarizer"]["n_calls"] += 1
-
- def _run_sub_action(self, sub_action: SubAction) -> tuple[str | None, bool]:
+ def _run_action(self, action: str) -> tuple[str | None, bool]:
"""Execute a sub-action. If the sub-action is a command, execute it.
Returns:
@@ -867,20 +815,13 @@ class Agent:
assert self.config is not None
# Normal command, not a subroutine
- self._fire_hooks("on_sub_action_started", sub_action=sub_action)
- observation, _, done, _info = self._env.step(sub_action["action"])
- # observation, additional_cost = self.config.summarizer_config.function( # type: ignore
- # sub_action["action"], observation, self._env, self.summarizer_model
- # )
- # self._update_summarizer_stats(additional_cost)
+ self._fire_hooks("on_action_started", action=action)
+ observation, _, done, _info = self._env.step(action)
self.info.update(_info)
- self._fire_hooks("on_sub_action_executed", obs=observation, done=done)
- if sub_action["cmd_name"] == self.config.submit_command:
- done = True
-
+ self._fire_hooks("on_action_executed", obs=observation, done=done)
return observation, done
- def _run_step(self, observation: str | None) -> tuple[str | None, bool]:
+ def _step(self, observation: str | None) -> tuple[str | None, bool]:
"""Run a step of the agent: Forward the last observation to the LM,
then execute the action and save the trajectory.
@@ -901,18 +842,8 @@ class Agent:
run_action: str = self._guard_multiline_input(action)
# Loop over sub-actions (if any)
- done = False
- observations: list[str | None] = list()
execution_t0 = time.perf_counter()
- breakpoint()
- for sub_action in self.split_actions(run_action):
- observation, done = self._run_sub_action(sub_action)
- # If the last sub-action is done, the observation is not
- # appended.
- if done:
- break
- observations.append(observation)
- observation = "\n".join([obs for obs in observations if obs is not None])
+ observation, done = self._run_action(run_action)
execution_time = time.perf_counter() - execution_t0
trajectory_step = TrajectoryStep(
@@ -972,7 +903,7 @@ class Agent:
self._fire_hooks("on_run_start")
done = False
while not done:
- observation, done = self._run_step(observation)
+ observation, done = self._step(observation)
self.save_trajectory()
self._fire_hooks("on_run_done", trajectory=self.trajectory, info=self.info)
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 003ae11a..8a4b587c 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -51,14 +51,14 @@ class SWEEnv:
deployment: AbstractDeployment,
# todo: Should None be included in RepoConfig?
repo: RepoConfig | None,
- instance: ProblemStatementConfig,
+ problem_statement: ProblemStatementConfig,
startup_commands: list[str],
hooks: list[EnvHook] | None = None,
):
super().__init__()
self.deployment = deployment
self.repo = repo
- self.instance = instance
+ self.problem_statement = problem_statement
self._startup_commands = startup_commands
self.logger = get_logger("🌱 SWEEnv")
# todo: get rid of this
@@ -81,7 +81,7 @@ class SWEEnv:
return cls(
deployment=deployment,
repo=config.repo,
- instance=config.problem_statement,
+ problem_statement=config.problem_statement,
startup_commands=config.startup_commands,
)
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
index a65dd867..ea4ce90d 100644
--- a/sweagent/main/run_basic.py
+++ b/sweagent/main/run_basic.py
@@ -44,7 +44,7 @@ class BasicMain:
observation, info = self.env.reset()
self.logger.info("Running agent")
info, trajectory = self.agent.run(
- setup_args={"problem_statement": self.env.instance.get_problem_statement()},
+ setup_args={"problem_statement": self.env.problem_statement.get_problem_statement()},
env=self.env,
observation=observation,
traj_dir=Path(self.traj_dir),
diff --git a/sweagent/run/hooks/abstract.py b/sweagent/run/hooks/abstract.py
index 9a55d47a..397bb7b8 100644
--- a/sweagent/run/hooks/abstract.py
+++ b/sweagent/run/hooks/abstract.py
@@ -1,5 +1,7 @@
from typing import Any
+from sweagent.environment.swe_env import SWEEnv
+
class RunHook:
"""Hook structure for the web server or other addons to interface with"""
@@ -21,7 +23,7 @@ class RunHook:
def on_end(self):
"""Called at the end of `Main.main`"""
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
+ def on_instance_start(self, *, index: int, env: SWEEnv):
"""Called at the beginning of each instance loop in `Main.run`"""
def on_instance_skipped(
@@ -31,3 +33,39 @@ class RunHook:
def on_instance_completed(self, *, info, trajectory):
"""Called when an instance is completed in `Main.run`"""
+
+
+class CombinedRunHooks(RunHook):
+ def __init__(self, hooks: list[RunHook] | None = None):
+ self._hooks = hooks or []
+
+ def add_hook(self, hook: RunHook) -> None:
+ self._hooks.append(hook)
+
+ @property
+ def hooks(self) -> list[RunHook]:
+ return self._hooks
+
+ def on_init(self, *, run):
+ for hook in self._hooks:
+ hook.on_init(run=run)
+
+ def on_start(self):
+ for hook in self._hooks:
+ hook.on_start()
+
+ def on_end(self):
+ for hook in self._hooks:
+ hook.on_end()
+
+ def on_instance_start(self, *, index: int, env: SWEEnv):
+ for hook in self._hooks:
+ hook.on_instance_start(index=index, env=env)
+
+ def on_instance_skipped(self):
+ for hook in self._hooks:
+ hook.on_instance_skipped()
+
+ def on_instance_completed(self, *, info, trajectory):
+ for hook in self._hooks:
+ hook.on_instance_completed(info=info, trajectory=trajectory)
diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.py
index 90d0b58c..7fca994a 100644
--- a/sweagent/run/hooks/apply_patch.py
+++ b/sweagent/run/hooks/apply_patch.py
@@ -1,9 +1,10 @@
import subprocess
from pathlib import Path
-from typing import Any
import rich
+from sweagent.environment.config.repo import LocalRepoConfig
+from sweagent.environment.swe_env import SWEEnv
from sweagent.run.hooks.abstract import RunHook
from sweagent.utils.log import get_logger
@@ -16,26 +17,27 @@ class SaveApplyPatchHook(RunHook):
self._apply_patch_locally = apply_patch_locally
def on_init(self, *, run):
- self._traj_dir = run.traj_dir
+ self._traj_dir = Path(run.traj_dir)
self._apply_patch_locally = run.actions.apply_patch_locally
- self._instance = None
+ self._env: SWEEnv | None = None
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- self._instance = instance
+ def on_instance_start(self, *, index: int, env: SWEEnv):
+ self._env = env
def on_instance_completed(self, *, info, trajectory):
- assert self._instance is not None # mypy
- instance_id = self._instance["instance_id"]
+ assert self._env is not None # mypy
+ instance_id = self._env.problem_statement.id
patch_path = self._save_patch(instance_id, info)
if patch_path:
if not self._apply_patch_locally:
return
if not self._is_promising_patch(info):
return
- assert self._instance # mypy
- if self._instance["repo_type"] != "local":
+ if self._env.repo is None:
return
- local_dir = Path(self._instance["repo"])
+ if not isinstance(self._env.repo, LocalRepoConfig):
+ return
+ local_dir = Path(self._env.repo.path)
self._apply_patch(patch_path, local_dir)
@staticmethod
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index 717953e9..f1ba03ce 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -10,7 +10,7 @@ from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
from sweagent.run._common import BasicCLI
-from sweagent.run.hooks.abstract import RunHook
+from sweagent.run.hooks.abstract import CombinedRunHooks, RunHook
from sweagent.run.hooks.apply_patch import SaveApplyPatchHook
from sweagent.run.hooks.open_pr import OpenPRConfig, OpenPRHook
from sweagent.utils.log import get_logger
@@ -58,12 +58,13 @@ class RunSingle:
self.traj_dir = traj_dir
self._hooks = []
self.actions = actions
+ self._chooks = CombinedRunHooks()
for hook in hooks or []:
self.add_hook(hook)
@property
def hooks(self) -> list[RunHook]:
- return self._hooks
+ return self._chooks.hooks
@classmethod
def from_config(cls, config: RunSingleConfig) -> Self:
@@ -81,29 +82,25 @@ class RunSingle:
def add_hook(self, hook: RunHook) -> None:
hook.on_init(run=self)
- self._hooks.append(hook)
-
- def _fire_hooks(self, hook_name: str, *args, **kwargs) -> None:
- for hook in self.hooks:
- getattr(hook, hook_name)(*args, **kwargs)
+ self._chooks.add_hook(hook)
def main(self):
- self._fire_hooks("on_start")
+ self._chooks.on_start()
self.logger.info("Starting environment")
self.env.start()
self.logger.info("Resetting environment")
observation, info = self.env.reset()
self.logger.info("Running agent")
- self._fire_hooks("on_instance_start", index=0, instance=self.env.instance.model_dump())
+ self._chooks.on_instance_start(index=0, env=self.env)
info, trajectory = self.agent.run(
- setup_args={"problem_statement": self.env.instance.get_problem_statement()},
+ setup_args={"problem_statement": self.env.problem_statement.get_problem_statement()},
env=self.env,
observation=observation,
traj_dir=Path(self.traj_dir),
)
- self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)
+ self._chooks.on_instance_completed(info=info, trajectory=trajectory)
self.logger.info("Done")
- self._fire_hooks("on_end")
+ self._chooks.on_end()
def main(args: RunSingleConfig):
diff --git a/tests/test_run.py b/tests/test_run.py
index 86464748..a35b8bed 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -6,7 +6,6 @@ from typing import Any
import pytest
from sweagent.agent.agents import AgentConfig
-from sweagent.agent.models import ModelArguments
from sweagent.environment.swe_env import EnvironmentInstanceConfig
from sweagent.run.hooks.abstract import RunHook
from sweagent.run.run_single import RunSingle, RunSingleConfig
@@ -36,11 +35,23 @@ def test_run_single_raises_exception():
rs.main()
+def agent_config_with_commands():
+ ac = AgentConfig()
+ ac.command_files = [
+ f"config/commands/{name}"
+ for name in ["defaults.sh", "search.sh", "edit_linting.sh", "_split_string.py", "submit.sh"]
+ ]
+ return ac
+
+
@pytest.mark.slow
-def test_run_instant_empty_submit():
+def test_run_instant_empty_submit(agent_config_with_commands):
+ ac = agent_config_with_commands
+ ac.model.name = "instant_empty_submit"
rsc = RunSingleConfig(
env=EnvironmentInstanceConfig(),
- agent=AgentConfig(model=ModelArguments(name="instant_empty_submit")),
+ agent=ac,
)
rs = RunSingle.from_config(rsc)
rs.main()