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: Move call to ReviewLoop; fix tests

Kilian Lieret2f0f3e1d5a9d
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 18f34b4d..65f5248e 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -18,6 +18,7 @@ from sweagent.agent.models import (
ContextWindowExceededError,
CostLimitExceededError,
ModelArguments,
+ ReplayModel,
get_model,
)
from sweagent.agent.parsing import FormatError, ParseFunction
@@ -298,7 +299,11 @@ 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)
+ if isinstance(self.model, ReplayModel) and self._rloop is not None:
+ msg = "Cannot use a replay model with a review loop model yet"
+ raise NotImplementedError(msg)
system_msg = self.config.system_template.format(**self.system_args)
self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
@@ -812,14 +817,7 @@ class Agent:
for hook in self.hooks:
hook.on_sub_action_executed(obs=observation, done=done)
if sub_action["cmd_name"] == self.config.submit_command:
- if self._rloop is not None:
- # Note: The trajectory/info will not include the last `submit` command
- self._rloop.on_submit(ReviewSubmission(trajectory=self._trajectory, info=self._info))
- done = self._rloop.retry()
- # fixme: If we vote retry, we still need to finish this attempt, then
- # add a "reset" command to the history and then continue.
- else:
- done = True
+ done = True
else:
agent_name = sub_action["agent"]
sub_agent_output = self.call_subroutine(agent_name, sub_action, self._env)
@@ -926,6 +924,15 @@ class Agent:
done = False
while not done:
observation, done = self._run_step(observation)
+ if done:
+ # fixme: Would have to fix this for replay model
+ if self._rloop is not None:
+ # Note: The trajectory/info will not include the last `submit` command
+ self._rloop.on_submit(ReviewSubmission(trajectory=self._trajectory, info=self._info))
+ retry = self._rloop.retry()
+ done = not retry
+ else:
+ done = True
for hook in self.hooks:
hook.on_run_done(trajectory=self._trajectory, info=self._info)
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 0ba090f8..26fe58da 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -841,7 +841,14 @@ class ReplayModel(BaseModel):
class InstantEmptySubmitTestModel(BaseModel):
- MODELS = {"instant_empty_submit": {}}
+ MODELS = {
+ "instant_empty_submit": {
+ "max_context": 100_000,
+ "max_tokens_to_sample": 4096,
+ "cost_per_input_token": 0,
+ "cost_per_output_token": 0,
+ }
+ }
def __init__(self, args: ModelArguments, commands: list[Command]):
"""This model immediately submits. Useful for testing purposes"""
@@ -856,6 +863,7 @@ class InstantEmptySubmitTestModel(BaseModel):
elif self._action_idx == 1:
self._action_idx = 0
action = "DISCUSSION\nThe task should be resolved, so let's submit the patch.\n\n```\nsubmit\n```\n"
+ self.update_stats(0, 0)
return action
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index 08c13855..1d3b540c 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -5,7 +5,7 @@ solving the issue and to select the best solution.
from __future__ import annotations
from abc import ABC, abstractmethod
-from dataclasses import dataclass, field
+from dataclasses import asdict, dataclass, field
from typing import Any, Literal
from sweagent.agent.models import BaseModel
@@ -126,7 +126,10 @@ class Reviewer(AbstractReviewer):
def format_messages(self, instance: INSTANCE_TYPE, submission: ReviewSubmission):
system_message = self._config.system_template
- user_message = self._config.instance_template.format(**instance, **submission)
+ # fixme: Add submission details
+ user_message = self._config.instance_template.format(
+ **instance,
+ )
return [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message},
@@ -195,12 +198,13 @@ class BinaryReviewer(AbstractBinaryReviewer):
def format_messages(self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission):
system_message = self._config.system_template
+ # fixme: Correct access to the elements!
user_message = self._config.instance_template.format(
**instance,
- **{f"{k}1": v for k, v in sub1.items() if k != "traj"},
- **{f"{k}2": v for k, v in sub1.items() if k != "traj"},
- traj1=self._traj_formatter.format_trajectory(sub1["traj"]["trajectory"], i_traj=1),
- traj2=self._traj_formatter.format_trajectory(sub2["traj"]["trajectory"], i_traj=2),
+ # **{f"{k}1": v for k, v in sub1.items() if k != "traj"},
+ # **{f"{k}2": v for k, v in sub1.items() if k != "traj"},
+ # traj1=self._traj_formatter.format_trajectory(sub1["traj"]["trajectory"], i_traj=1),
+ # traj2=self._traj_formatter.format_trajectory(sub2["traj"]["trajectory"], i_traj=2),
)
return [
{"role": "system", "content": system_message},
@@ -283,6 +287,7 @@ class ReviewLoop(AbstractReviewLoop):
def _review(self) -> bool:
review = self._reviewer.review(self._instance, self._submissions[-1])
+ logger.debug("Review result: %s", asdict(review))
self._reviews.append(review)
return review.accept
@@ -293,9 +298,10 @@ class ReviewLoop(AbstractReviewLoop):
# Require that the best submission is accepted, so don't
# even need to compare here
return
- sub1 = self._submissions[-2]
+ sub1 = self._submissions[self._best_idx]
sub2 = self._submissions[-1]
cresult = self._breviewer.compare_submissions(self._instance, sub1, sub2)
+ logger.debug(f"Comparison between {self._best_idx} and -1 result: %s", asdict(cresult))
self._comparisons.append((self._n_samples - 2, self._n_samples - 1, cresult))
assert cresult.choice in [0, 1]
# this was a comparison between the current best and the last one
@@ -303,15 +309,21 @@ class ReviewLoop(AbstractReviewLoop):
def retry(self) -> bool:
if self._n_samples >= self._loop_config.max_samples:
- logger.debug("Exiting retry loop: max_samples reached")
+ logger.debug(
+ f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): max_samples reached"
+ )
return False
if self._reviews[-1].accept and self._n_samples >= self._loop_config.min_draws > 0:
- logger.debug("Exiting retry loop: min_draws reached and last submission was accepted")
+ logger.debug(
+ f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): min_draws reached and last submission was accepted"
+ )
return False
if self._n_accepted >= self._loop_config.max_accepted_draws > 0:
- logger.debug("Exiting retry loop: max_accepted_draws reached")
+ logger.debug(
+ f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): max_accepted_draws reached"
+ )
return False
return True
diff --git a/tests/test_env.py b/tests/test_env.py
index 655b379d..13121424 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -7,13 +7,14 @@ 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
+from .conftest import swe_env_context
+
@pytest.mark.slow()
def test_init_swe_env(test_env_args):
diff --git a/tests/test_reviewer.py b/tests/test_reviewer.py
index 2130ef42..70151de0 100644
--- a/tests/test_reviewer.py
+++ b/tests/test_reviewer.py
@@ -127,28 +127,37 @@ def test_loop_stop_max_fail(dummy_reviewer_config, dummy_binary_reviewer_config)
assert loop.get_best() == i
-def agent_arguments(dummy_review_loop_config) -> AgentArguments:
+def get_agent_arguments(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__(config, "review_loop_config", review_loop_config)
object.__setattr__(args, "config", config)
return args
@pytest.mark.slow()
-def test_agent_with_reviewer(agent_arguments, test_env_args):
- assert agent_arguments.config.review_loop_config is not None
+def test_agent_with_reviewer(dummy_reviewer_config, dummy_binary_reviewer_config, test_env_args):
+ rl_config = ReviewLoopConfig(
+ "ReviewLoop",
+ dummy_reviewer_config,
+ dummy_binary_reviewer_config,
+ max_samples=100,
+ min_draws=100,
+ max_accepted_draws=2,
+ )
+ agent_args = get_agent_arguments(rl_config)
+ assert agent_args.config.review_loop_config is not None
sa = ScriptArguments(
environment=test_env_args,
- agent=agent_arguments,
+ agent=agent_args,
actions=ActionsArguments(),
print_config=False,
skip_existing=False,
+ raise_exceptions=True,
)
class InjectRModelsTests(AgentHook):
@@ -159,6 +168,7 @@ def test_agent_with_reviewer(agent_arguments, test_env_args):
def on_init(self, agent: Agent):
self._agent = agent
+ print("hook initialized")
def on_setup_done(self):
# Same setup as in test_loop_comparison
@@ -166,7 +176,7 @@ def test_agent_with_reviewer(agent_arguments, test_env_args):
bmodel = DeterminedModel(["second"])
rloop: ReviewLoop = self._agent._rloop # type: ignore
rloop._reviewer._model = rmodel # type: ignore
- rloop._reviewer._model = bmodel # type: ignore
+ rloop._breviewer._model = bmodel # type: ignore
def on_run_done(self, trajectory, info):
rloop: ReviewLoop = self._agent._rloop # type: ignore
@@ -174,7 +184,7 @@ def test_agent_with_reviewer(agent_arguments, test_env_args):
assert rloop._n_samples == 3
assert rloop.get_best() == 2
assert info["exit_status"] == "submitted"
- assert info["api_calls"] == 3 * 2
+ assert info["model_stats"]["api_calls"] == 3 * 2
main = Main(sa)
main.agent.add_hook(InjectRModelsTests())