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]
Review: Proper bookkeeping with retries
Kilian Lieretb07ad1a3950e
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 4e38f8e9..90d9b775 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -1,5 +1,6 @@from __future__ import annotations+import copyimport jsonimport refrom collections import defaultdict@@ -19,7 +20,6 @@ from sweagent.agent.models import (ContextWindowExceededError,CostLimitExceededError,ModelArguments,- ReplayModel,get_model,)from sweagent.agent.parsing import FormatError, ParseFunction@@ -250,6 +250,10 @@ class Agent:def __init__(self, name: str, args: AgentArguments):self.name = name+ # todo: currently only used to get the model name, so might remove this later+ self._args = args+ #: Model used by the agent. Note: Will initialize a separate model together with the reviewer+ #: (if any) to disentangle costs.self.model = get_model(args.model, args.config._commands + args.config.subroutine_types)self.config = args.configassert self.config is not None # mypy@@ -335,6 +339,7 @@ class Agent:hook.on_query_message_added(**item)self.history.append(item)+ # todo: klieret: Long term: Might make more sense to reinitialize the agent class for every instance instead of thisdef setup(self, instance_args: dict[str, Any], init_model_stats: APIStats | None = None) -> None:"""Setup the agent for a new instance. This includesformatting the system message and adding demonstrations to the history.@@ -343,22 +348,39 @@ class Agent:instance_args: Arguments for the instance"""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)+ if self.config.review_loop_config is not None:+ rmodel = get_model(self._args.model, [])+ rmodel.reset_stats()+ self._rloop = get_review_loop_from_config(self.config.review_loop_config, instance_args, rmodel)++ self._i_attempt = 0+ 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)++ for hook in self.hooks:+ hook.on_setup_done()++ def setup_attempt(self, *, init_model_stats: APIStats | None = None) -> None:+ """Setup the agent for a new attempt. This includes resetting the model stats."""+ assert self.config is not None # mypy+ if self._i_attempt > 0 and init_model_stats is not None:+ msg = (+ "We might be dealing with nested retries, where subroutines are mixed with retries. "+ "Currently, this messes up accounting with init_model_stats."+ )+ raise ValueError(msg)+ self.model.reset_stats(init_model_stats)+ # self.model = get_model(self._args.model, self.config._commands + self.config.subroutine_types)+ # fixme: This doesn't reset total costsystem_msg = self.config.system_template.format(**self.system_args)self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")-- self.history: History = []- self.trajectory = []- self.info = {}self._append_history(HistoryItem({"role": "system", "content": system_msg, "agent": self.name}))-if "history_to_messages" in dir(self.model):for demonstration_path in self.config.demonstrations:if self.config.demonstration_template is None and not self.config.put_demos_in_history:@@ -397,8 +419,6 @@ class Agent:"role": "user",},)- for hook in self.hooks:- hook.on_setup_done()@propertydef state_command(self) -> str:@@ -410,22 +430,49 @@ class Agent:"""Return the history of the agent since the last reset."""return self.config.history_processor([entry for entry in self.history if entry["agent"] == self.name])+ def _get_total_stats(self) -> APIStats:+ """Combine model stats of different attempts and the reviewer"""+ total_stats = APIStats()+ for stats in self._info_by_attempt.values():+ assert "model_stats" in stats # mypy+ attempt_stats = APIStats(**stats["model_stats"])+ 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(self,) -> None:"""Save the trajectory to disk.This includes the history, the environment state, and the model stats."""- assert self._env is not None- log_dict = {- "environment": self._env.name,- "trajectory": self.trajectory,- "history": self.history,- "info": self.info,- }- data = log_dict++ def get_attempt_data(attempt_idx: int = -1) -> dict[str, Any]:+ """Get data saved for every attempt"""+ assert self._env is not None+ # The deepcopy here is important because else the+ # data["info"]["model_stats"] update will create havoc!+ return copy.deepcopy(+ {+ "environment": self._env.name,+ "trajectory": self._trajectory_by_attempt[attempt_idx],+ "history": self._history_by_attempt[attempt_idx],+ "info": self._info_by_attempt[attempt_idx],+ }+ )+if self._rloop is not None:- pass+ best_attempt_idx = self._rloop.get_best()+ data = {+ "attempts": [get_attempt_data(i) for i in range(self._i_attempt + 1)],+ **get_attempt_data(best_attempt_idx),+ }+ data["info"]["model_stats"] = self._get_total_stats().to_dict()+ else:+ data = {**get_attempt_data(), "extra_info": self._extra_info}assert self.traj_path is not Noneself.traj_path.write_text(json.dumps(data, indent=2))@@ -845,7 +892,7 @@ class Agent:return_type=return_type,init_model_stats=self.model.stats,)- self._history_by_attempt += sub_agent.history+ self.history += sub_agent.historyself.set_environment_vars(env, env_vars)env.communicate(f"cd {cwd}")self.model.stats.replace(sub_agent.model.stats)@@ -922,7 +969,6 @@ class Agent:self.trajectory.append(trajectory_step)model_stats: APIStats = self.model.statsself.info["model_stats"] = model_stats.to_dict()- self.save_trajectory()for hook in self.hooks:hook.on_step_done(trajectory_step=trajectory_step, model_stats=model_stats)return observation, done@@ -982,12 +1028,17 @@ class Agent:if self._rloop is not None:# Note: The trajectory/info will not include the last `submit` commandself._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()if retry:- self.reset_agent_for_retry()+ self._i_attempt += 1+ self.setup_attempt()done = not retryelse:+ self.save_trajectory()done = True+ # note: Don't pull out save_trajectory here because it deppends on _i_attemptfor hook in self.hooks:hook.on_run_done(trajectory=self.trajectory, info=self.info)@@ -998,9 +1049,3 @@ class Agent:if return_type == "info_trajectory":return self.info, self.trajectoryreturn self.trajectory[-1][return_type]-- def reset_agent_for_retry(self):- """When using a retry loop, this method is called to reset the history,- info, environment, etc. in order to prepare for a new attempt to solve the issue.- """- ...diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 26fe58da..95433f85 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -1,5 +1,6 @@from __future__ import annotations+import copyimport jsonimport loggingimport os@@ -121,7 +122,8 @@ class BaseModel:self.stats = APIStats(total_cost=self.stats.total_cost)logger.info("Resetting model stats")else:- self.stats = other+ # Make sure to copy the stats to avoid modifying the original+ self.stats = copy.deepcopy(other)def update_stats(self, input_tokens: int, output_tokens: int) -> float:"""diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.pyindex 1d3b540c..96e0a24b 100644--- a/sweagent/agent/reviewer.py+++ b/sweagent/agent/reviewer.py@@ -8,7 +8,7 @@ from abc import ABC, abstractmethodfrom dataclasses import asdict, dataclass, fieldfrom typing import Any, Literal-from sweagent.agent.models import BaseModel+from sweagent.agent.models import APIStats, BaseModelfrom sweagent.types import ReviewSubmission, Trajectoryfrom sweagent.utils.log import get_logger@@ -68,9 +68,28 @@ class AbstractReviewLoop(ABC):"""Called when the agent submits a solution"""@abstractmethod- def get_best(self):+ def get_best(self) -> int:"""Returns the best solution"""+ @property+ @abstractmethod+ def model_stats(self) -> APIStats:+ """Returns the API stats of the model (if any)"""++ @property+ @abstractmethod+ def reviews(self) -> list[ReviewerResult]: ...++ @property+ @abstractmethod+ def comparisons(self) -> list[tuple[int, int, BinaryReviewerResult]]:+ """Get information about comparisons++ Returns:+ A list of tuples, where each tuple contains the indices of the+ compared submissions and the result of the comparison.+ """+# --- CONFIGS ---@@ -123,6 +142,7 @@ class Reviewer(AbstractReviewer):def __init__(self, config: ReviewerConfig, model: BaseModel):self._config = configself._model = model+ print("Reviewer model id", id(self._model))def format_messages(self, instance: INSTANCE_TYPE, submission: ReviewSubmission):system_message = self._config.system_template@@ -146,7 +166,9 @@ 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)@@ -248,8 +270,11 @@ class ReviewLoop(AbstractReviewLoop):instance: INSTANCE_TYPE,model: BaseModel,):+ self._model = model+ print("Review loop model id", id(self._model))self._instance = instanceself._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)@@ -280,10 +305,16 @@ class ReviewLoop(AbstractReviewLoop):def _n_accepted(self) -> int:return sum([r.accept for r in self._reviews])+ @property+ def model_stats(self) -> APIStats:+ return self._model.stats+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])diff --git a/tests/test_reviewer.py b/tests/test_reviewer.pyindex 70151de0..e56c329c 100644--- a/tests/test_reviewer.py+++ b/tests/test_reviewer.py@@ -1,5 +1,9 @@from __future__ import annotations+import json+import logging+import pprint+import pytestfrom run import ActionsArguments, Main, ScriptArguments@@ -37,16 +41,35 @@ def dummy_review_loop_config(dummy_reviewer_config, dummy_binary_reviewer_configclass DeterminedModel(BaseModel):+ MODELS = {+ "determined_model": {+ "max_context": 100_000,+ "max_tokens_to_sample": 4096,+ "cost_per_input_token": 0,+ "cost_per_output_token": 0,+ }+ }+def __init__(self, replies: list[str]):+ ma = ModelArguments("determined_model")+ super().__init__(ma, []) # type: ignoreself._replies = repliesself._idx = 0def query(self, messages):reply = self._replies[self._idx]self._idx += 1+ self.update_stats(0, 0)return reply+def test_determined_model_costs():+ model = DeterminedModel([""])+ assert model.stats.api_calls == 0+ model.query([{"role": "system", "content": ""}])+ assert model.stats.api_calls == 1++def test_get_from_config(dummy_review_loop_config):get_review_loop_from_config(dummy_review_loop_config, instance={}, model=DeterminedModel([]))@@ -107,12 +130,14 @@ def test_loop_comparison(dummy_reviewer_config, dummy_binary_reviewer_config):else:assert loop.get_best() == 2assert loop._n_samples == 3+ assert rmodel.stats.api_calls == 3+ assert bmodel.stats.api_calls == 1def test_loop_stop_max_fail(dummy_reviewer_config, dummy_binary_reviewer_config):rmodel = DeterminedModel(["fail"] * 5)# Only have one comparison: The two successes- bmodel = DeterminedModel(["second"] * 5)+ bmodel = DeterminedModel(["second"] * 4)lconfig = ReviewLoopConfig("ReviewLoop", dummy_reviewer_config, dummy_binary_reviewer_config, max_samples=5)loop = ReviewLoop(lconfig, instance={}, model=rmodel)loop._breviewer._model = bmodel@@ -125,6 +150,8 @@ def test_loop_stop_max_fail(dummy_reviewer_config, dummy_binary_reviewer_config)else:assert not loop.retry()assert loop.get_best() == i+ assert rmodel.stats.api_calls == 5+ assert bmodel.stats.api_calls == 4def get_agent_arguments(review_loop_config) -> AgentArguments:@@ -172,11 +199,11 @@ def test_agent_with_reviewer(dummy_reviewer_config, dummy_binary_reviewer_configdef on_setup_done(self):# Same setup as in test_loop_comparison- rmodel = DeterminedModel(["success", "fail", "success", "fail"])- bmodel = DeterminedModel(["second"])+ model = DeterminedModel(["success", "fail", "success", "second"])rloop: ReviewLoop = self._agent._rloop # type: ignore- rloop._reviewer._model = rmodel # type: ignore- rloop._breviewer._model = bmodel # type: ignore+ rloop._reviewer._model = model # type: ignore+ rloop._breviewer._model = model # type: ignore+ rloop._model = modeldef on_run_done(self, trajectory, info):rloop: ReviewLoop = self._agent._rloop # type: ignore@@ -184,8 +211,19 @@ def test_agent_with_reviewer(dummy_reviewer_config, dummy_binary_reviewer_configassert rloop._n_samples == 3assert rloop.get_best() == 2assert info["exit_status"] == "submitted"- assert info["model_stats"]["api_calls"] == 3 * 2+ assert info["model_stats"]["api_calls"] == 2main = Main(sa)main.agent.add_hook(InjectRModelsTests())+ 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+ full_info["attempts"] = [+ {k: v for k, v in attempt.items() if k not in ["trajectory", "history"]} for attempt in full_info["attempts"]+ ]+ del full_info["trajectory"]+ del full_info["history"]+ pprint.pprint(full_info)+ assert len(full_info["attempts"]) == 3+ assert full_info["info"]["model_stats"]["api_calls"] == 3 * 2 + 4