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: Handling cost limits
Kilian Lieret2a8fe91398af
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex bb79997f..063aa85f 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -30,7 +30,7 @@ from sweagent.agent.models import (get_model,)from sweagent.agent.problem_statement import ProblemStatement, ProblemStatementConfig-from sweagent.agent.reviewer import RetryLoopConfig, get_retry_loop_from_config+from sweagent.agent.reviewer import RetryLoopConfig, ReviewSubmission, get_retry_loop_from_configfrom sweagent.environment.swe_env import SWEEnvfrom sweagent.exceptions import (ContentPolicyViolationError,@@ -43,7 +43,7 @@ from sweagent.tools.parsing import (ThoughtActionParser,)from sweagent.tools.tools import ToolConfig, ToolHandler-from sweagent.types import AgentInfo, AgentRunResult, ReviewSubmission, StepOutput, Trajectory, TrajectoryStep+from sweagent.types import AgentInfo, AgentRunResult, StepOutput, Trajectory, TrajectoryStepfrom sweagent.utils.config import _convert_paths_to_abspath, _strip_abspath_from_dictfrom sweagent.utils.jinja_warnings import _warn_probably_wrong_jinja_syntaxfrom sweagent.utils.log import get_logger@@ -151,7 +151,6 @@ class RetryAgentConfig(BaseModel):retry_loop: RetryLoopConfigtype: Literal["retry"] = "retry"model_config = ConfigDict(extra="forbid")- total_cost_limit: floatAgentConfig = Annotated[DefaultAgentConfig | RetryAgentConfig, Field(discriminator="type")]@@ -250,13 +249,13 @@ class RetryAgent(AbstractAgent):def step(self) -> StepOutput:assert self._agent is not Nonecurrent_total_cost = self._total_instance_stats.instance_cost + self._agent.model.stats.instance_cost- if current_total_cost > self.config.total_cost_limit:+ if current_total_cost > self.config.retry_loop.cost_limit:# This is a bit of a hack to raise exit_cost within the sub-agent,# which ensures we handle the cost limit properly within the sub-agent (autosubmission etc.)self.logger.warning("Cost limit (all attempts) exceeded: %s > %s. Setting current agent's per-instance cost limit to 0.0",current_total_cost,- self.config.total_cost_limit,+ self.config.retry_loop.cost_limit,)self._agent.model.config.per_instance_cost_limit = 0.0try:@@ -284,7 +283,7 @@ class RetryAgent(AbstractAgent):}data["info"]["best_attempt_idx"] = best_attempt_idx# Overwrite model stats with total stats- data["info"]["model_stats"] = self._total_instance_stats.model_dump()+ data["info"]["model_stats"] = (self._total_instance_stats + self._rloop.model_stats).model_dump()return data@@ -321,7 +320,13 @@ class RetryAgent(AbstractAgent):if step_output.done:self._finalize_agent_run()if self._rloop is not None:- self._rloop.on_submit(ReviewSubmission(trajectory=self._agent.trajectory, info=self._agent.info))+ self._rloop.on_submit(+ ReviewSubmission(+ trajectory=self._agent.trajectory,+ info=self._agent.info,+ model_stats=self._agent.model.stats,+ )+ )self._agent.info["review"] = self._rloop.reviews[-1].model_dump() # type: ignoreself.save_trajectory()if self._rloop.retry():diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex b23c44d8..f0c49d25 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -363,6 +363,10 @@ class HumanModel(AbstractModel):else:# Input has escaped things like \n, so we need to unescape itaction = action.encode("utf8").decode("unicode_escape")+ if action.strip().split()[0] == "spend_money":+ money = float(action.strip().split()[1])+ self.stats.instance_cost += money+ action = f"echo 'Spent {money} dollars'"_handle_raise_commands(action)self._update_stats()return {"message": action}diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.pyindex 909180d3..0308af2a 100644--- a/sweagent/agent/reviewer.py+++ b/sweagent/agent/reviewer.py@@ -22,9 +22,45 @@ from sweagent.agent.models import ()from sweagent.agent.problem_statement import ProblemStatementfrom sweagent.tools.tools import ToolConfig-from sweagent.types import ReviewerResult, ReviewSubmission, Trajectory, TrajectoryStep+from sweagent.types import AgentInfo, Trajectory, TrajectoryStepfrom sweagent.utils.log import get_logger++class ReviewSubmission(BaseModel):+ """Information that's passed to the reviewer"""++ #: Total trajectory (including several retries)+ trajectory: Trajectory+ #: Aggregate info dict (including several retries)+ info: AgentInfo+ #: Model stats for this attempt+ model_stats: InstanceStats++ def to_format_dict(self, *, suffix="") -> dict[str, Any]:+ """Return all the data that is used to format the+ messages. Trajectory is excluded because it needs special treatment.+ """+ out = {}+ info = copy.deepcopy(self.info)+ if not info.get("submission"):+ # Observed that not all exit_cost lead to autosubmission+ # so sometimes this might be missing.+ info["submission"] = ""+ for k, v in info.items():+ if isinstance(v, str):+ out[f"{k}{suffix}"] = v+ elif isinstance(v, dict):+ for k2, v2 in v.items():+ out[f"{k}_{k2}{suffix}"] = v2+ return out+++class ReviewerResult(BaseModel):+ accept: bool | float+ outputs: list[str]+ messages: list[dict[str, Any]]++# --- INTERFACES ---@@ -126,6 +162,8 @@ class ScoreRetryLoopConfig(BaseModel):#: Override model temperature for first len(list) attemptstemperature_override: list[float] = [0.0]+ cost_limit: float+model: ModelConfigmodel_config = ConfigDict(extra="forbid")@@ -137,7 +175,7 @@ class ScoreRetryLoopConfig(BaseModel):def __post_init__(self):self.validate()- def get_retry_loop(self, problem_statement: ProblemStatement) -> AbstractRetryLoop:+ def get_retry_loop(self, problem_statement: ProblemStatement) -> ScoreRetryLoop:return ScoreRetryLoop(self, problem_statement)@@ -267,21 +305,20 @@ class TrajectoryFormatter:class ScoreRetryLoop(AbstractRetryLoop):def __init__(self,- loop_config: ScoreRetryLoopConfig,+ config: ScoreRetryLoopConfig,problem_statement: ProblemStatement,):- self._model = get_model(loop_config.model, tools=ToolConfig())+ # This model will not share instance cost with the parent agent+ self._model = get_model(config.model, tools=ToolConfig())self._problem_statement = problem_statement- self._reviewer: AbstractReviewer = loop_config.reviewer_config.get_reviewer(self._model)- self._loop_config = loop_config+ self._reviewer: AbstractReviewer = config.reviewer_config.get_reviewer(self._model)+ self._config = config# Note: These are "cumulative" submissions, i.e., they include all retries# up to that point.self._submissions: list[ReviewSubmission] = []self._reviews: list[ReviewerResult] = []#: Number of consecutive exit cost submissionsself._n_consec_exit_cost: int = 0- #: Original temperature- self._terminal_temperature: float | None = Noneself.logger = get_logger("review_loop", emoji="🔄")# Properties@@ -295,6 +332,14 @@ class ScoreRetryLoop(AbstractRetryLoop):def _n_attempts(self) -> int:return len(self._submissions)+ @property+ def model_stats(self) -> InstanceStats:+ return self._model.stats++ @property+ def _total_attempt_stats(self) -> InstanceStats:+ return sum((s.model_stats for s in self._submissions), start=InstanceStats())+# -------def _override_temperature(self, i_attempt: int) -> None:@@ -305,8 +350,8 @@ class ScoreRetryLoop(AbstractRetryLoop):if i_attempt == 0:self._terminal_temperature = self._model.config.temperatureself.logger.debug(f"Set terminal temperature to {self._terminal_temperature}")- if i_attempt < len(self._loop_config.temperature_override):- self._model.config.temperature = self._loop_config.temperature_override[i_attempt]+ if i_attempt < len(self._config.temperature_override):+ self._model.config.temperature = self._config.temperature_override[i_attempt]else:assert self._terminal_temperature is not Noneself._model.config.temperature = self._terminal_temperature@@ -333,9 +378,16 @@ class ScoreRetryLoop(AbstractRetryLoop):max_score = max([r.accept for r in self._reviews])stat_str = f"n_samples={self._n_attempts}, max_score={max_score}"+ if self._config.cost_limit > 0 and self._total_attempt_stats.instance_cost > self._config.cost_limit:+ self.logger.info(+ f"Exiting retry loop ({stat_str}): Total attempt cost ({self._total_attempt_stats.instance_cost}) "+ f"exceeds cost limit ({self._config.cost_limit})"+ )+ return False+# Given a maximum score, look up what the minimum and maximum number of attempts arefor _score, _max_attempts in sorted(- self._loop_config.max_attempts_for_score.items(), reverse=True, key=lambda x: x[0]+ self._config.max_attempts_for_score.items(), reverse=True, key=lambda x: x[0]):if max_score >= _score:max_attempts = _max_attempts@@ -349,18 +401,19 @@ class ScoreRetryLoop(AbstractRetryLoop):)return False- max_n_exit_cost = self._loop_config.max_n_consec_exit_cost+ max_n_exit_cost = self._config.max_n_consec_exit_costif self._n_consec_exit_cost >= max_n_exit_cost > 0:self.logger.info(f"Exiting retry loop ({stat_str}): {max_n_exit_cost} exit cost attempts reached")return False# Todo: Check if there's enough budget left for a new reasonable attempt- remaining_budget = self._model.instance_cost_limit - self._model.stats.instance_cost- if (- self._loop_config.min_budget_for_new_attempt > 0- and remaining_budget < self._loop_config.min_budget_for_new_attempt- ):- self.logger.info(f"Exiting retry loop ({stat_str}): Not enough budget left for a new attempt")+ remaining_budget = self._config.cost_limit - self._total_attempt_stats.instance_cost+ if self._config.min_budget_for_new_attempt > 0 and remaining_budget < self._config.min_budget_for_new_attempt:+ msg = (+ f"Exiting retry loop ({stat_str}): Not enough budget left for a new attempt "+ f"({remaining_budget} remaining, {self._config.min_budget_for_new_attempt} required)"+ )+ self.logger.info(msg)return Falsereturn True@@ -375,7 +428,7 @@ class ScoreRetryLoop(AbstractRetryLoop):def get_retry_loop_from_config(config: RetryLoopConfig | None, problem_statement: ProblemStatement-) -> AbstractRetryLoop | None:+) -> ScoreRetryLoop | None:if config is None:return Nonereturn config.get_retry_loop(problem_statement=problem_statement)diff --git a/sweagent/types.py b/sweagent/types.pyindex 27aee1c9..4f066ec2 100644--- a/sweagent/types.py+++ b/sweagent/types.py@@ -6,7 +6,6 @@ because of circular dependencies.from __future__ import annotations-import copyfrom typing import Any, Literalfrom pydantic import BaseModel@@ -93,46 +92,6 @@ class AgentInfo(TypedDict, total=False):swe_rex_hash: str-class ReviewSubmission(BaseModel):- """Information that's passed to the reviewer"""-- #: Total trajectory (including several retries)- trajectory: Trajectory- #: Aggregate info dict (including several retries)- info: AgentInfo-- def to_format_dict(self, *, suffix="") -> dict[str, Any]:- """Return all the data that is used to format the- messages. Trajectory is excluded because it needs special treatment.- """- out = {}- info = copy.deepcopy(self.info)- if not info.get("submission"):- # Observed that not all exit_cost lead to autosubmission- # so sometimes this might be missing.- info["submission"] = ""- for k, v in info.items():- if isinstance(v, str):- out[f"{k}{suffix}"] = v- elif isinstance(v, dict):- for k2, v2 in v.items():- out[f"{k}_{k2}{suffix}"] = v2- return out---class ReviewerResult(BaseModel):- accept: bool | float- outputs: list[str]- messages: list[dict[str, Any]]---class BinaryReviewerResult(BaseModel):- choice: Literal[0, 1]- output: str- messages: list[dict[str, str]]- confidence: float = 1.0--class AgentRunResult(BaseModel):info: AgentInfotrajectory: Trajectory