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]

Reviewer: First integration between Agent and ReviewLoop

Kilian Lierete06b4e590055
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index b2cdb378..9443e993 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -4,7 +4,7 @@ import json
import re
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, TypedDict
+from typing import Any
from simple_parsing.helpers.fields import field
from simple_parsing.helpers.flatten import FlattenedAccess
@@ -21,7 +21,9 @@ from sweagent.agent.models import (
get_model,
)
from sweagent.agent.parsing import FormatError, ParseFunction
+from sweagent.agent.reviewer import AbstractReviewLoop, ReviewLoopConfig, get_review_loop_from_config
from sweagent.environment.swe_env import SWEEnv
+from sweagent.types import TRAJECTORY_TYPE, AgentInfo, ReviewSubmission, TrajectoryStep
from sweagent.utils.config import convert_paths_to_abspath
from sweagent.utils.log import get_logger
@@ -99,6 +101,7 @@ class AgentConfig(FrozenSerializable):
_commands: list[Command] = field(default_factory=list)
_subroutines: dict[str, Subroutine] = field(default_factory=dict)
subroutine_types: list[Subroutine] = field(default_factory=list)
+ review_loop_config: ReviewLoopConfig | None = None
def __post_init__(self):
object.__setattr__(self, "command_files", convert_paths_to_abspath(self.command_files))
@@ -194,16 +197,11 @@ class AgentArguments(FlattenedAccess, FrozenSerializable):
object.__setattr__(model_args, "total_cost_limit", self.model.total_cost_limit)
-class TrajectoryStep(TypedDict):
- action: str
- observation: str
- response: str
- state: str | None
- thought: str
-
-
class AgentHook:
- def on_init(self): ...
+ def on_init(self, *, agent: Agent):
+ """Note: Depending on the internals of `Agent` should be done with care,
+ it's best to use this as little as possible.
+ """
def on_run_start(
self,
@@ -219,7 +217,7 @@ class AgentHook:
def on_step_done(self, *, trajectory_step: TrajectoryStep, model_stats: APIStats): ...
- def on_run_done(self): ...
+ def on_run_done(self, *, trajectory: TRAJECTORY_TYPE, info: AgentInfo): ...
def on_model_query(self, *, query: str, agent: str):
"""Actually query the model with the complete history."""
@@ -235,6 +233,8 @@ class AgentHook:
action: str = "",
): ...
+ def on_setup_done(self): ...
+
class Agent:
"""Agent handles the behaviour of the model and how it interacts with the environment."""
@@ -254,10 +254,12 @@ class Agent:
self.last_container_id = None
self.hooks = []
self.logger = get_logger("agent")
+ # Requires instance, so is set in `setup` methods
+ self._rloop: AbstractReviewLoop | None = None
def add_hook(self, hook: AgentHook):
"""Add hook to agent"""
- hook.on_init()
+ hook.on_init(self)
self.hooks.append(hook)
def _append_history(self, item: dict):
@@ -265,7 +267,7 @@ class Agent:
hook.on_query_message_added(**item)
self.history.append(item)
- def setup(self, instance_args, init_model_stats=None) -> None:
+ def setup(self, instance_args: dict[str, Any], init_model_stats: APIStats | None = None) -> None:
"""Setup the agent for a new instance. This includes
formatting the system message and adding demonstrations to the history.
@@ -275,6 +277,7 @@ class Agent:
assert self.config is not None # mypy
self.model.reset_stats(init_model_stats)
self.instance_args = instance_args
+ self._rloop = get_review_loop_from_config(self.config.review_loop_config, instance_args, self.model)
system_msg = self.config.system_template.format(**self.system_args)
self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
@@ -320,6 +323,8 @@ class Agent:
"role": "user",
},
)
+ for hook in self.hooks:
+ hook.on_setup_done()
@property
def state_command(self) -> str:
@@ -471,7 +476,7 @@ class Agent:
self.subroutine_patterns[self.config.submit_command] = submit_pat
self.command_patterns[self.config.submit_command] = submit_pat
- def forward(self, observation: str, available_actions: list[str], state: str) -> tuple[str, str, str]:
+ def forward(self, observation: str | None, available_actions: list[str], state: str) -> tuple[str, str, str]:
"""Forwards the model
Args:
@@ -501,7 +506,7 @@ class Agent:
return thought, action, output
- def forward_model(self, observation: str, state: str) -> str:
+ def forward_model(self, observation: str | None, state: str) -> str:
"""Query the model with the current state and observation with the appropriate template.
Returns:
@@ -632,7 +637,7 @@ class Agent:
self.logger.warning(f"Malformat limit reached: \n{output}")
return "Exit due to format error", "exit_format", output
- def forward_with_error_check(self, observation: str, state: str) -> tuple[str, str, str]:
+ def forward_with_error_check(self, observation: str | None, state: str) -> tuple[str, str, str]:
"""Wrapper around `self.forward_model` that handles errors and retries
due to format errors or blocked actions.
@@ -668,6 +673,7 @@ class Agent:
return self.check_format_and_requery(output)
def init_environment_vars(self, env: SWEEnv):
+ assert self.config is not None
self.set_environment_vars(env, self.config.env_variables)
def set_environment_vars(self, env: SWEEnv, env_variables: dict[str, Any]) -> None:
@@ -801,10 +807,11 @@ class Agent:
hook.on_run_start()
# Run action/observation loop
- trajectory = []
- info = {}
- traj_log_path = traj_dir / (env.record["instance_id"] + ".traj")
- self.logger.info("Trajectory will be saved to %s", traj_log_path)
+ trajectory: list[TrajectoryStep] = []
+ info: AgentInfo = {}
+ if traj_dir:
+ traj_log_path = traj_dir / (env.record["instance_id"] + ".traj")
+ self.logger.info("Trajectory will be saved to %s", traj_log_path)
while not done:
for hook in self.hooks:
hook.on_step_start()
@@ -823,7 +830,11 @@ class Agent:
hook.on_sub_action_executed(obs=obs, done=done)
observations.append(obs)
if sub_action["cmd_name"] == self.config.submit_command:
- done = True
+ if self._rloop is not None:
+ self._rloop.on_submit(ReviewSubmission(trajectory=trajectory, info=info))
+ done = self._rloop.retry()
+ else:
+ done = True
if done:
break
else:
@@ -851,7 +862,7 @@ class Agent:
hook.on_step_done(trajectory_step=trajectory_step, model_stats=model_stats)
for hook in self.hooks:
- hook.on_run_done()
+ hook.on_run_done(trajectory, info)
self.logger.info("Trajectory saved to %s", traj_log_path)
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index 9fa20002..72cc6ea3 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -9,10 +9,10 @@ from dataclasses import dataclass, field
from typing import Any, Literal
from sweagent.agent.models import BaseModel
+from sweagent.types import ReviewSubmission
from sweagent.utils.log import get_logger
INSTANCE_TYPE = dict[str, Any]
-SUBMISSION_TYPE = dict[str, Any]
logger = get_logger("reviewer")
@@ -49,7 +49,7 @@ class AbstractBinaryReviewer(ABC):
@abstractmethod
def compare_submissions(
- self, instance: INSTANCE_TYPE, sub1: SUBMISSION_TYPE, sub2: SUBMISSION_TYPE
+ self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission
) -> BinaryReviewerResult:
"""Returns 0 if sub1 is better, 1 if sub2 is better"""
@@ -64,7 +64,7 @@ class AbstractReviewLoop(ABC):
"""Returns True if the agent should retry solving the issue"""
@abstractmethod
- def on_submit(self, submission: SUBMISSION_TYPE) -> None:
+ def on_submit(self, submission: ReviewSubmission) -> None:
"""Called when the agent submits a solution"""
@abstractmethod
@@ -118,7 +118,7 @@ class Reviewer(AbstractReviewer):
self._config = config
self._model = model
- def format_messages(self, instance: INSTANCE_TYPE, submission: SUBMISSION_TYPE):
+ def format_messages(self, instance: INSTANCE_TYPE, submission: ReviewSubmission):
system_message = self._config.system_template
user_message = self._config.instance_template.format(**instance, **submission)
return [
@@ -135,7 +135,7 @@ class Reviewer(AbstractReviewer):
logger.warning("Could not interpret response: %s, will reject submission.", response)
return False
- def review(self, instance: dict[str, Any], submission: SUBMISSION_TYPE) -> ReviewerResult:
+ def review(self, instance: dict[str, Any], submission: ReviewSubmission) -> ReviewerResult:
messages = self.format_messages(instance, submission)
answer = self._model.query(messages)
return ReviewerResult(self.interpret(answer), answer, messages=messages)
@@ -187,7 +187,7 @@ class BinaryReviewer(AbstractBinaryReviewer):
traj_item_template=config.traj_item_template,
)
- def format_messages(self, instance: INSTANCE_TYPE, sub1: SUBMISSION_TYPE, sub2: SUBMISSION_TYPE):
+ def format_messages(self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission):
system_message = self._config.system_template
user_message = self._config.instance_template.format(
**instance,
@@ -212,7 +212,7 @@ class BinaryReviewer(AbstractBinaryReviewer):
return 0
def compare_submissions(
- self, instance: INSTANCE_TYPE, sub1: SUBMISSION_TYPE, sub2: SUBMISSION_TYPE
+ self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission
) -> BinaryReviewerResult:
messages = self.format_messages(instance, sub1, sub2)
answer = self._model.query(messages)
@@ -232,7 +232,7 @@ class ReviewLoop(AbstractReviewLoop):
loop_config.binary_reviewer_config, model
)
self._loop_config = loop_config
- self._submissions: list[SUBMISSION_TYPE] = []
+ self._submissions: list[ReviewSubmission] = []
self._reviews: list[ReviewerResult] = []
self._comparisons: list[tuple[int, int, BinaryReviewerResult]] = []
# Once we have k submissions, there will always be one voted at the
@@ -256,7 +256,7 @@ class ReviewLoop(AbstractReviewLoop):
def _n_accepted(self) -> int:
return sum([r.accept for r in self._reviews])
- def on_submit(self, submission: SUBMISSION_TYPE) -> None:
+ def on_submit(self, submission: ReviewSubmission) -> None:
self._submissions.append(submission)
self._review()
self._compare()
@@ -301,5 +301,8 @@ class ReviewLoop(AbstractReviewLoop):
return self._best_idx
-def get_review_loop_from_config(config, instance: INSTANCE_TYPE, model: BaseModel) -> AbstractReviewLoop:
+def get_review_loop_from_config(config, instance: INSTANCE_TYPE, model: BaseModel) -> AbstractReviewLoop | None:
+ if not config.review_loop_classname:
+ logger.debug("Running without review loop")
+ return None
return globals()[config.review_loop_classname](config, instance, model)
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 929997c8..1f315167 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -39,6 +39,7 @@ from sweagent.environment.utils import (
read_with_timeout,
read_with_timeout_experimental,
)
+from sweagent.types import AgentInfo
from sweagent.utils.config import keys_config
from sweagent.utils.log import default_logger, get_logger
@@ -405,7 +406,7 @@ class SWEEnv(gym.Env):
)
os.remove(path_to_patch)
- def step(self, action: str) -> tuple[str | None, int, bool, dict]:
+ def step(self, action: str) -> tuple[str | None, int, bool, AgentInfo]:
"""
Runs given action in environment and returns corresponding output
@@ -418,7 +419,7 @@ class SWEEnv(gym.Env):
done: whether task is over
info: additional information (e.g. debugging information)
"""
- info = {}
+ info: AgentInfo = {}
observation = ""
# Handle special actions
diff --git a/sweagent/types.py b/sweagent/types.py
new file mode 100644
index 00000000..4ea41143
--- /dev/null
+++ b/sweagent/types.py
@@ -0,0 +1,36 @@
+"""This file has types/dataclass definitions that are used in the SWE agent
+for exchanging data between different modules/functions/classes.
+They oftentimes cannot be defined in the same file where they are used
+because of circular dependencies.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TypedDict
+
+
+class TrajectoryStep(TypedDict):
+ action: str
+ observation: str
+ response: str
+ state: str | None
+ thought: str
+
+
+TRAJECTORY_TYPE = list[TrajectoryStep]
+
+
+class AgentInfo(TypedDict, total=False):
+ # same as `APIStats` from models.py
+ model_stats: dict[str, float]
+ exit_status: str
+ submission: str | None
+
+
+@dataclass
+class ReviewSubmission:
+ """Information that's passed to the reviewer"""
+
+ trajectory: TRAJECTORY_TYPE
+ info: AgentInfo
diff --git a/tests/conftest.py b/tests/conftest.py
index 03563c03..8a9f086a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,11 +1,18 @@
from __future__ import annotations
import json
+import subprocess
import sys
+from collections.abc import Generator
+from contextlib import contextmanager
from pathlib import Path
import pytest
+import docker
+import docker.errors
+from sweagent.environment.swe_env import EnvironmentArguments, SWEEnv
+
# this is a hack and should be removed when we have a better solution
_this_dir = Path(__file__).resolve().parent
root_dir = _this_dir.parent
@@ -49,3 +56,46 @@ def test_trajectory_path(test_trajectories_path) -> Path:
@pytest.fixture()
def test_trajectory(test_trajectory_path):
return json.loads(test_trajectory_path.read_text())
+
+
[email protected](scope="module")
+def test_env_args(
+ tmpdir_factory,
+) -> Generator[EnvironmentArguments]:
+ """This will use a persistent container"""
+ local_repo_path = tmpdir_factory.getbasetemp() / "swe-agent-test-repo"
+ clone_cmd = ["git", "clone", "https://github.com/klieret/swe-agent-test-repo", local_repo_path]
+ subprocess.run(clone_cmd, check=True)
+ data_path = local_repo_path / "problem_statements" / "1.md"
+ test_env_args = EnvironmentArguments(
+ data_path=str(data_path),
+ repo_path=str(local_repo_path),
+ image_name="sweagent/swe-agent:latest",
+ container_name="test-container-this-is-a-random-string",
+ verbose=True,
+ )
+ yield test_env_args
+ # Cleanup (after session ends)
+ client = docker.from_env()
+ # fixme (?): What happens if user changed container_name?
+ try:
+ assert test_env_args.container_name is not None # mypy
+ container = client.containers.get(test_env_args.container_name)
+ container.remove(force=True)
+ except docker.errors.NotFound:
+ # Can happen if this fixture never runs because we only do a partial
+ # test run
+ pass
+
+
+@contextmanager
+def swe_env_context(env_args):
+ """Context manager to make sure we close the shell on the container
+ so that we can reuse it.
+ """
+
+ env = SWEEnv(env_args)
+ try:
+ yield env
+ finally:
+ env.close()
diff --git a/tests/test_env.py b/tests/test_env.py
index e2eecaea..655b379d 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -1,61 +1,18 @@
from __future__ import annotations
import dataclasses
-import subprocess
import time
-from contextlib import contextmanager
from pathlib import Path
from unittest import mock
import pytest
import yaml
+from conftest import swe_env_context
import docker
import docker.errors
from sweagent import CONFIG_DIR
-from sweagent.environment.swe_env import EnvHook, EnvironmentArguments, SWEEnv
-
-
[email protected](scope="module")
-def test_env_args(
- tmpdir_factory,
-):
- """This will use a persistent container"""
- local_repo_path = tmpdir_factory.getbasetemp() / "swe-agent-test-repo"
- clone_cmd = ["git", "clone", "https://github.com/klieret/swe-agent-test-repo", local_repo_path]
- subprocess.run(clone_cmd, check=True)
- data_path = local_repo_path / "problem_statements" / "1.md"
- test_env_args = EnvironmentArguments(
- data_path=str(data_path),
- repo_path=str(local_repo_path),
- image_name="sweagent/swe-agent:latest",
- container_name="test-container-this-is-a-random-string",
- verbose=True,
- )
- yield test_env_args
- # Cleanup (after session ends)
- client = docker.from_env()
- # fixme (?): What happens if user changed container_name?
- try:
- container = client.containers.get(test_env_args.container_name)
- container.remove(force=True)
- except docker.errors.NotFound:
- # Can happen if this fixture never runs because we only do a partial
- # test run
- pass
-
-
-@contextmanager
-def swe_env_context(env_args):
- """Context manager to make sure we close the shell on the container
- so that we can reuse it.
- """
-
- env = SWEEnv(env_args)
- try:
- yield env
- finally:
- env.close()
+from sweagent.environment.swe_env import EnvHook, EnvironmentArguments
@pytest.mark.slow()
diff --git a/tests/test_reviewer.py b/tests/test_reviewer.py
index 23a6827a..79601ea9 100644
--- a/tests/test_reviewer.py
+++ b/tests/test_reviewer.py
@@ -2,7 +2,10 @@ from __future__ import annotations
import pytest
-from sweagent.agent.models import BaseModel
+from run import ActionsArguments, Main, ScriptArguments
+from sweagent import CONFIG_DIR
+from sweagent.agent.agents import Agent, AgentArguments, AgentHook
+from sweagent.agent.models import BaseModel, ModelArguments
from sweagent.agent.reviewer import (
BinaryReviewer,
BinaryReviewerConfig,
@@ -97,6 +100,7 @@ def test_loop_comparison(dummy_reviewer_config, dummy_binary_reviewer_config):
assert loop.get_best() == 0
else:
assert loop.get_best() == 2
+ assert loop._n_samples == 3
def test_loop_stop_max_fail(dummy_reviewer_config, dummy_binary_reviewer_config):
@@ -115,3 +119,57 @@ def test_loop_stop_max_fail(dummy_reviewer_config, dummy_binary_reviewer_config)
else:
assert not loop.retry()
assert loop.get_best() == i
+
+
+def agent_arguments(dummy_review_loop_config) -> AgentArguments:
+ args = AgentArguments(
+ model=ModelArguments(model_name="instant_empty_submit"),
+ config_file=CONFIG_DIR / "default_from_url.yaml",
+ config=None,
+ )
+ config = args.config
+ object.__setattr__(config, "review_loop_config", dummy_review_loop_config)
+ object.__setattr__(args, "config", config)
+ return args
+
+
+def test_agent_with_reviewer(agent_arguments, test_env_args):
+ assert agent_arguments.config.review_loop_config is not None
+ sa = ScriptArguments(
+ environment=test_env_args,
+ agent=agent_arguments,
+ actions=ActionsArguments(),
+ print_config=False,
+ skip_existing=False,
+ )
+
+ class InjectRModelsTests(AgentHook):
+ """We need to intercept the initialization of the reviewer as well
+ as the run loop of main to inject our models for testing
+ as well as the actual tests
+ """
+
+ def on_init(self, agent: Agent):
+ self._agent = agent
+
+ def on_setup_done(self):
+ # Same setup as in test_loop_comparison
+ rmodel = DeterminedModel(["success", "fail", "success", "fail"])
+ bmodel = DeterminedModel(["second"])
+ rloop: ReviewLoop = self._agent._rloop # type: ignore
+ rloop._reviewer._model = rmodel # type: ignore
+ rloop._reviewer._model = bmodel # type: ignore
+
+ def on_run_done(self, trajectory, info):
+ rloop: ReviewLoop = self._agent._rloop # type: ignore
+ assert rloop is not None
+ assert rloop._n_samples == 3
+ assert rloop.get_best() == 2
+ assert info["exit_status"] == "submitted"
+ assert info["api_calls"] == 3 * 2
+
+ main = Main(sa)
+ main.agent.add_hook(InjectRModelsTests())
+ main.main()