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: Add log messages and output data

Kilian Lieret9b760e2c9a9e
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index ce2a5a1a..8cc1db13 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -282,10 +282,6 @@ class Agent:
self._trajectory_by_attempt: dict[int, Trajectory] = defaultdict(list)
self._info_by_attempt: dict[int, AgentInfo] = defaultdict(dict)
- #: Any additional information that is not run-dependent that is added to the output
- #: file (also called trajectory)
- self._extra_info: dict[str, Any] = {}
-
@property
def history(self) -> History:
"""History that is passed on to the model.
@@ -359,7 +355,6 @@ class Agent:
self._history_by_attempt = defaultdict(list)
self._trajectory_by_attempt = defaultdict(list)
self._info_by_attempt = defaultdict(dict) # type: ignore
- self._extra_info = {}
self.setup_attempt(init_model_stats=init_model_stats)
@@ -442,8 +437,6 @@ class Agent:
total_stats += attempt_stats
if self._rloop is not None:
total_stats += self._rloop.model_stats
- print("loop from sum", self._rloop.model_stats)
- print("total", total_stats)
return total_stats
def save_trajectory(
@@ -474,8 +467,11 @@ class Agent:
**get_attempt_data(best_attempt_idx),
}
data["info"]["model_stats"] = self._get_total_stats().to_dict()
+ data["extra_info"] = {"comparisons": [(a, b, comp.to_dict()) for a, b, comp in self._rloop.comparisons]}
else:
- data = {**get_attempt_data(), "extra_info": self._extra_info}
+ data = {
+ **get_attempt_data(),
+ }
assert self.traj_path is not None
self.traj_path.write_text(json.dumps(data, indent=2))
@@ -1032,8 +1028,9 @@ class Agent:
# Note: The trajectory/info will not include the last `submit` command
self._rloop.on_submit(ReviewSubmission(trajectory=self.trajectory, info=self.info))
# (make sure to save trajectory after self._rloop.on_submit)
- self.save_trajectory()
retry = self._rloop.retry()
+ self.info["review"] = self._rloop.reviews[-1].to_dict()
+ self.save_trajectory()
if retry:
self._i_attempt += 1
self.setup_attempt()
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 95433f85..fc392bd0 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -147,14 +147,14 @@ class BaseModel:
self.stats.tokens_received += output_tokens
self.stats.api_calls += 1
- # Log updated cost values to std. out.
- logger.info(
+ # Log updated cost values to std. err
+ logger.debug(
f"input_tokens={input_tokens:,}, "
f"output_tokens={output_tokens:,}, "
f"instance_cost={self.stats.instance_cost:.2f}, "
f"cost={cost:.2f}",
)
- logger.info(
+ logger.debug(
f"total_tokens_sent={self.stats.tokens_sent:,}, "
f"total_tokens_received={self.stats.tokens_received:,}, "
f"total_cost={self.stats.total_cost:.2f}, "
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index 96e0a24b..3c316fa6 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -9,20 +9,14 @@ from dataclasses import asdict, dataclass, field
from typing import Any, Literal
from sweagent.agent.models import APIStats, BaseModel
-from sweagent.types import ReviewSubmission, Trajectory
+from sweagent.types import BinaryReviewerResult, ReviewerResult, ReviewSubmission
from sweagent.utils.log import get_logger
INSTANCE_TYPE = dict[str, Any]
logger = get_logger("reviewer")
-
# --- INTERFACES ---
-@dataclass
-class ReviewerResult:
- accept: bool
- output: str
- messages: list[dict[str, str]]
class AbstractReviewer(ABC):
@@ -35,13 +29,6 @@ class AbstractReviewer(ABC):
"""Returns True if the submission is believed to be correct"""
-@dataclass
-class BinaryReviewerResult:
- choice: Literal[0, 1]
- output: str
- messages: list[dict[str, str]]
-
-
class AbstractBinaryReviewer(ABC):
"""The binary reviewer checks two solutions and tries to predict
which one is better.
@@ -139,17 +126,20 @@ class ReviewLoopConfig(AbstractReviewLoopConfig):
# fixme: Reviewer should insta-reject on exit_cost
class Reviewer(AbstractReviewer):
+ LOG_PREFIX = "🧑‍⚖️ Reviewer: "
+
def __init__(self, config: ReviewerConfig, model: BaseModel):
self._config = config
self._model = model
- print("Reviewer model id", id(self._model))
def format_messages(self, instance: INSTANCE_TYPE, submission: ReviewSubmission):
system_message = self._config.system_template
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (system)\n{system_message}")
# fixme: Add submission details
user_message = self._config.instance_template.format(
**instance,
)
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (user)\n{user_message}")
return [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message},
@@ -166,10 +156,11 @@ class Reviewer(AbstractReviewer):
def review(self, instance: dict[str, Any], submission: ReviewSubmission) -> ReviewerResult:
messages = self.format_messages(instance, submission)
- print("reviewer stats before query", self._model.stats, id(self._model))
answer = self._model.query(messages)
- print("reviewer stats after query", self._model.stats, id(self._model))
- return ReviewerResult(self.interpret(answer), answer, messages=messages)
+ accept = self.interpret(answer)
+ accept_emoji = "✅" if accept else "❌"
+ logger.info(f"{self.LOG_PREFIX}{accept_emoji}\n{answer}")
+ return ReviewerResult(accept, answer, messages=messages)
# todo: Couldn't I just replace the whole thing with Jinja templates?
@@ -210,6 +201,8 @@ class TrajectoryFormatter:
class BinaryReviewer(AbstractBinaryReviewer):
+ LOG_PREFIX = "⚖️ Binary Reviewer: "
+
def __init__(self, config: BinaryReviewerConfig, model: BaseModel):
self._config = config
self._model = model
@@ -220,6 +213,7 @@ class BinaryReviewer(AbstractBinaryReviewer):
def format_messages(self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission):
system_message = self._config.system_template
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (system)\n{system_message}")
# fixme: Correct access to the elements!
user_message = self._config.instance_template.format(
**instance,
@@ -228,6 +222,7 @@ class BinaryReviewer(AbstractBinaryReviewer):
# traj1=self._traj_formatter.format_trajectory(sub1["traj"]["trajectory"], i_traj=1),
# traj2=self._traj_formatter.format_trajectory(sub2["traj"]["trajectory"], i_traj=2),
)
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (user)\n{user_message}")
return [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message},
@@ -248,22 +243,16 @@ class BinaryReviewer(AbstractBinaryReviewer):
) -> BinaryReviewerResult:
messages = self.format_messages(instance, sub1, sub2)
answer = self._model.query(messages)
- return BinaryReviewerResult(self.interpret(answer), output=answer, messages=messages)
-
-
-def split_trajectory(trajectory: Trajectory, submit_command: str) -> list[Trajectory]:
- """Split a "cumulative" trajectory that includes
- multiple retries into the individual parts. This basically means
- finding the `submit` command and splitting along that.
-
- Args:
- trajectory: The cumulative trajectory
- submit_command: The command that submits the solution
- will probably be `submit`.
- """
+ idx = self.interpret(answer)
+ # Use words because else confusion with 0-based vs 1-based indices
+ choice_emoji = "first" if idx == 0 else "second"
+ logger.info(f"{self.LOG_PREFIX}{choice_emoji}\n{answer}")
+ return BinaryReviewerResult(idx, output=answer, messages=messages)
class ReviewLoop(AbstractReviewLoop):
+ LOG_PREFIX = "🔄 Review Loop: "
+
def __init__(
self,
loop_config: ReviewLoopConfig,
@@ -271,10 +260,8 @@ class ReviewLoop(AbstractReviewLoop):
model: BaseModel,
):
self._model = model
- print("Review loop model id", id(self._model))
self._instance = instance
self._reviewer: AbstractReviewer = globals()[loop_config.reviewer_classname](loop_config.reviewer_config, model)
- print("Reviewer id ", id(self._reviewer))
self._breviewer: AbstractBinaryReviewer = globals()[loop_config.binary_reviewer_classname](
loop_config.binary_reviewer_config, model
)
@@ -311,14 +298,11 @@ class ReviewLoop(AbstractReviewLoop):
def on_submit(self, submission: ReviewSubmission) -> None:
self._submissions.append(submission)
- print("before submit", self._model.stats, id(self._model), id(self._reviewer))
self._review()
self._compare()
- print("after submit", self._model.stats, id(self._model), id(self._reviewer))
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
@@ -339,22 +323,19 @@ class ReviewLoop(AbstractReviewLoop):
self._best_idx = [self._best_idx, self._n_samples - 1][cresult.choice]
def retry(self) -> bool:
+ stat_str = f"n_samples={self._n_samples}, n_accepted={self._n_accepted}"
if self._n_samples >= self._loop_config.max_samples:
- logger.debug(
- f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): max_samples reached"
- )
+ logger.info(f"{self.LOG_PREFIX}Exiting retry loop ({stat_str}): `max_samples` reached")
return False
if self._reviews[-1].accept and self._n_samples >= self._loop_config.min_draws > 0:
- logger.debug(
- f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): min_draws reached and last submission was accepted"
+ logger.info(
+ f"{self.LOG_PREFIX}Existing retry loop ({stat_str}): `min_draws` reached and last submission was accepted"
)
return False
if self._n_accepted >= self._loop_config.max_accepted_draws > 0:
- logger.debug(
- f"Exiting retry loop (n_samples={self._n_samples}, n_accepted={self._n_accepted}): max_accepted_draws reached"
- )
+ logger.info(f"{self.LOG_PREFIX}Exiting retry loop ({stat_str}): `max_accepted_draws` reached")
return False
return True
diff --git a/sweagent/types.py b/sweagent/types.py
index 203f7a9f..affa94c2 100644
--- a/sweagent/types.py
+++ b/sweagent/types.py
@@ -7,7 +7,9 @@ because of circular dependencies.
from __future__ import annotations
from dataclasses import dataclass
-from typing import TypedDict
+from typing import Any, Literal, TypedDict
+
+from simple_parsing.helpers.serialization.serializable import FrozenSerializable
class TrajectoryStep(TypedDict):
@@ -34,11 +36,14 @@ History = list[HistoryItem]
Trajectory = list[TrajectoryStep]
+# todo: Make this actually have the dataclasses instead of dict versions
class AgentInfo(TypedDict, total=False):
# same as `APIStats` from models.py
model_stats: dict[str, float]
exit_status: str
submission: str | None
+ # same as `ReviewerResult`
+ review: dict[str, Any]
@dataclass
@@ -49,3 +54,17 @@ class ReviewSubmission:
trajectory: Trajectory
#: Aggregate info dict (including several retries)
info: AgentInfo
+
+
+@dataclass(frozen=True)
+class ReviewerResult(FrozenSerializable):
+ accept: bool
+ output: str
+ messages: list[dict[str, str]]
+
+
+@dataclass(frozen=True)
+class BinaryReviewerResult(FrozenSerializable):
+ choice: Literal[0, 1]
+ output: str
+ messages: list[dict[str, str]]
diff --git a/tests/test_reviewer.py b/tests/test_reviewer.py
index e56c329c..b0eae933 100644
--- a/tests/test_reviewer.py
+++ b/tests/test_reviewer.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import json
-import logging
import pprint
import pytest
@@ -215,7 +214,7 @@ def test_agent_with_reviewer(dummy_reviewer_config, dummy_binary_reviewer_config
main = Main(sa)
main.agent.add_hook(InjectRModelsTests())
- main.agent.logger.setLevel(logging.ERROR)
+ # main.agent.logger.setLevel(logging.ERROR)
main.main()
assert main.agent._rloop.model_stats.api_calls == 4
full_info = json.loads(main.agent.traj_path.read_text()) # type: ignore