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]

Enh: Review & retry: Add attempt cost limits

Kilian Lieretae373422c735
diff --git a/config/function_calling_anthropic_replace_late_repro_review_submit_retry.yaml b/config/function_calling_anthropic_replace_late_repro_review_submit_retry.yaml
index 33e581fd..9eeed406 100644
--- a/config/function_calling_anthropic_replace_late_repro_review_submit_retry.yaml
+++ b/config/function_calling_anthropic_replace_late_repro_review_submit_retry.yaml
@@ -339,4 +339,6 @@ agent:
max_samples: 5
min_draws: 2
max_accepted_draws: 0
- max_n_consec_exit_cost: 3
\ No newline at end of file
+ max_n_consec_exit_cost: 3
+ attempt_cost_limit: 2
+ min_budget_for_new_attempt: 1
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index f439a339..83d63227 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -692,6 +692,7 @@ class Agent:
step = StepOutput()
try:
# Forward model and get actions
+ self._rloop.on_model_query(attempt_stats=self.attempt_model_stats)
self._chook.on_model_query(messages=history, agent=self.name)
output = self.model.query(history) # type: ignore
step.output = output["message"]
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index da0730b8..c3d7e525 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -206,6 +206,11 @@ class AbstractModel(ABC):
@abstractmethod
def query(self, history: History, action_prompt: str = "> ") -> dict: ...
+ @property
+ def instance_cost_limit(self) -> float:
+ """Cost limit for the model. Returns 0 if there is no limit."""
+ return 0
+
def _handle_raise_commands(action: str) -> None:
if action == "raise_runtime":
@@ -443,6 +448,11 @@ class LiteLLMModel(AbstractModel):
self.lm_provider = litellm.model_cost[self.config.name]["litellm_provider"]
self.logger = get_logger("swea-lm", emoji="🤖")
+ @property
+ def instance_cost_limit(self) -> float:
+ """Cost limit for the model. Returns 0 if there is no limit."""
+ return self.config.per_instance_cost_limit
+
def _update_stats(self, *, input_tokens: int, output_tokens: int, cost: float) -> None:
with GLOBAL_STATS_LOCK:
GLOBAL_STATS.total_cost += cost
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index ffe91c52..3b80aab0 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -13,6 +13,7 @@ from pydantic import BaseModel
from sweagent.agent.models import AbstractModel, InstanceStats
from sweagent.agent.problem_statement import ProblemStatement
+from sweagent.exceptions import AttemptCostLimitExceededError
from sweagent.types import BinaryReviewerResult, History, ReviewerResult, ReviewSubmission, Trajectory, TrajectoryStep
from sweagent.utils.log import get_logger
@@ -74,23 +75,22 @@ class AbstractReviewLoop(ABC):
the issue and how it selects the best solution.
"""
- @abstractmethod
def retry(self) -> bool:
"""Returns True if the agent should retry solving the issue"""
+ return False
- @abstractmethod
def on_submit(self, submission: ReviewSubmission) -> None:
"""Called when the agent submits a solution"""
+ def on_model_query(self, attempt_stats: InstanceStats):
+ """Called before the model is queried. Can be used to implement
+ stop conditions based on attempt cost etc.
+ """
+
@abstractmethod
def get_best(self) -> int:
"""Returns the best solution"""
- @property
- @abstractmethod
- def model_stats(self) -> InstanceStats:
- """Returns the API stats of the model"""
-
@property
@abstractmethod
def reviews(self) -> list[ReviewerResult]: ...
@@ -173,6 +173,10 @@ class ReviewLoopConfig(BaseModel):
#: If set > 0 and there are more than this number of consecutive attempts
#: with an 'exit cost' exit stats, the review loop will quit.
max_n_consec_exit_cost: int = 0
+ #: Cost limit for attempt (<=0: no limit)
+ attempt_cost_limit: float = 0.0
+ #: Minimal $ that need to be left in order for us to start a new attempt
+ min_budget_for_new_attempt: float = 0.0
def validate(self):
"""Checks config. Raises `ValueError` in case of misconfiguration"""
@@ -432,6 +436,9 @@ class ReviewLoop(AbstractReviewLoop):
#: Number of consecutive exit cost submissions
self._n_consec_exit_cost: int = 0
+ # Properties
+ # ----------
+
@property
def reviews(self) -> list[ReviewerResult]:
return self._reviews
@@ -448,15 +455,18 @@ class ReviewLoop(AbstractReviewLoop):
def _n_accepted(self) -> int:
return sum([r.accept for r in self._reviews])
- @property
- def model_stats(self) -> InstanceStats:
- return self._model.stats
+ # -------
def on_submit(self, submission: ReviewSubmission) -> None:
self._submissions.append(submission)
self._review()
self._compare()
+ def on_model_query(self, attempt_stats: InstanceStats):
+ if 0 < self._loop_config.attempt_cost_limit <= attempt_stats.instance_cost:
+ logger.info(f"{self.LOG_PREFIX}Exiting retry loop: Cost limit exceeded")
+ raise AttemptCostLimitExceededError()
+
def _review(self) -> bool:
review = self._reviewer.review(self._instance, self._submissions[-1])
self._reviews.append(review)
@@ -519,6 +529,15 @@ class ReviewLoop(AbstractReviewLoop):
)
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
+ ):
+ logger.info(f"{self.LOG_PREFIX}Exiting retry loop ({stat_str}): Not enough budget left for a new attempt")
+ return False
+
return True
def get_best(self) -> int:
diff --git a/sweagent/exceptions.py b/sweagent/exceptions.py
index c1da7681..800f6213 100644
--- a/sweagent/exceptions.py
+++ b/sweagent/exceptions.py
@@ -38,3 +38,7 @@ class InstanceCostLimitExceededError(CostLimitExceededError):
class TotalCostLimitExceededError(CostLimitExceededError):
"""Raised when we exceed the total cost limit"""
+
+
+class AttemptCostLimitExceededError(CostLimitExceededError):
+ """Raised when we exceed the cost limit for an attempt"""