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]
Add reflexion capabilities
Kilian Lieret2793f7b23bfd
diff --git a/config/default_retry.yaml b/config/default_retry.yamlindex cc9de66a..ed85407a 100644--- a/config/default_retry.yaml+++ b/config/default_retry.yaml@@ -58,6 +58,7 @@ instance_template: |-6. When editing files, it is easy to accidentally specify a wrong line number or to write code with incorrect indentation. Always check the code after you issue an edit to make sure that it reflects what you wanted to accomplish. If it didn't, issue another command to fix it.+ {failed_verdicts_with_submissions}(Open file: {open_file})(Current directory: {working_dir})@@ -231,4 +232,4 @@ review_loop_config:max_samples: 10min_draws: 100max_accepted_draws: 2-+ gtc_classname: GraveToCradlediff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 447a581a..d60189ef 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -282,6 +282,10 @@ class Agent:self._trajectory_by_attempt: dict[int, Trajectory] = defaultdict(list)self._info_by_attempt: dict[int, AgentInfo] = defaultdict(dict)+ #: Variables to be referenced in the templates that are forwarded from one+ #: solution attempt to the next+ self._forwarded_vars: dict[str, Any] = {}+@propertydef history(self) -> History:"""History that is passed on to the model.@@ -355,6 +359,9 @@ class Agent:self._history_by_attempt = defaultdict(list)self._trajectory_by_attempt = defaultdict(list)self._info_by_attempt = defaultdict(dict) # type: ignore+ self._forwarded_vars = {}+ if self._rloop is not None:+ self._forwarded_vars = self._rloop.get_forwarded_vars()self.setup_attempt(init_model_stats=init_model_stats)@@ -674,6 +681,7 @@ class Agent:**self.system_args,**state_vars,observation=(observation if observation is not None else ""),+ **self._forwarded_vars,),)@@ -1031,6 +1039,7 @@ class Agent:self._rloop.on_submit(ReviewSubmission(trajectory=self.trajectory, info=self.info))# (make sure to save trajectory after self._rloop.on_submit)retry = self._rloop.retry()+ self._forwarded_vars = self._rloop.get_forwarded_vars()self.info["review"] = self._rloop.reviews[-1].to_dict()# Call save_trajectory again to save the updated info with the final reviewsself.save_trajectory()diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.pyindex 9b4e68d8..75274517 100644--- a/sweagent/agent/reviewer.py+++ b/sweagent/agent/reviewer.py@@ -43,6 +43,27 @@ class AbstractBinaryReviewer(ABC):"""Returns 0 if sub1 is better, 1 if sub2 is better"""+class AbstractGraveToCradle(ABC):+ """Forward messages from past attempts to the next one"""++ @abstractmethod+ def get_forwarded_vars(+ self,+ submissions: list[ReviewSubmission],+ reviews: list[ReviewerResult],+ breviews: list[tuple[int, int, BinaryReviewerResult]],+ ) -> dict[str, Any]:+ """Get the variables that should be forwarded to the next iteration.++ Note: Must return a dictionary with the correct keys even when called+ with empty lists. This is because else we cannot use the variables in the template+ when we call for the first attempt.++ Returns:+ A dictionary of variables that should be forwarded to the next iteration.+ """++class AbstractReviewLoop(ABC):"""The review loop controls how often the agent tries to solvethe issue and how it selects the best solution.@@ -79,6 +100,14 @@ class AbstractReviewLoop(ABC):compared submissions and the result of the comparison."""+ def get_forwarded_vars(self) -> dict[str, Any]:+ """Get the variables that should be forwarded to the next iteration.++ Returns:+ A dictionary of variables that should be forwarded to the next iteration.+ """+ return {}+# --- CONFIGS ---@@ -110,15 +139,22 @@ class BinaryReviewerConfig(FrozenSerializable):traj_item_template: str = "Model: {response}\n\nObservation: {observation}"+@dataclass(frozen=True)+class GTCConfig(FrozenSerializable):+ """The configuration for the GraveToCradle"""++@dataclass(frozen=True)class ReviewLoopConfig(FrozenSerializable):"""The configuration for the review loop"""reviewer_config: ReviewerConfigbinary_reviewer_config: BinaryReviewerConfig+ gtc_config: GTCConfig | None = Nonereview_loop_classname: str = "ReviewLoop"reviewer_classname: str = "Reviewer"binary_reviewer_classname: str = "BinaryReviewer"+ gtc_classname: str = ""max_samples: int = 2min_draws: int = 1max_accepted_draws: int = 0@@ -261,6 +297,33 @@ class BinaryReviewer(AbstractBinaryReviewer):return BinaryReviewerResult(idx, output=answer, messages=messages)+class GraveToCradle(AbstractGraveToCradle):+ def __init__(self, config: GTCConfig, model: BaseModel):+ self._config = config+ self._model = model++ def get_forwarded_vars(+ self,+ submissions: list[ReviewSubmission],+ reviews: list[ReviewerResult],+ breviews: list[tuple[int, int, BinaryReviewerResult]],+ ) -> dict[str, Any]:+ assert len(submissions) == len(reviews)+ failed_idxs = [i for i, r in enumerate(reviews) if not r.accept]+ if not failed_idxs:+ return {"failed_verdicts_with_submissions": ""}+ msg_lines = ["The following previous submissions were deemed to be incorrect:"]+ for i, idx in enumerate(failed_idxs):+ info = submissions[idx].info+ if not info.get("submission"):+ continue+ submission = info["submission"]+ review = reviews[idx].output+ msg_lines.append(f"Submission {i+1}:\n\n{submission}\n\nReview {i+1}:\n\n{review}")+ msg = "\n\n".join(msg_lines)+ return {"failed_verdicts_with_submissions": msg}++class ReviewLoop(AbstractReviewLoop):LOG_PREFIX = "🔄 Review Loop: "@@ -276,6 +339,9 @@ class ReviewLoop(AbstractReviewLoop):self._breviewer: AbstractBinaryReviewer = globals()[loop_config.binary_reviewer_classname](loop_config.binary_reviewer_config, model)+ self._gtc: AbstractGraveToCradle | None = None+ if loop_config.gtc_classname:+ self._gtc = globals()[loop_config.gtc_classname](loop_config.gtc_config, model)self._loop_config = loop_config# Note: These are "cumulative" submissions, i.e., they include all retries# up to that point.@@ -354,6 +420,11 @@ class ReviewLoop(AbstractReviewLoop):assert len(self._reviews) == len(self._submissions)return self._best_idx+ def get_forwarded_vars(self) -> dict[str, Any]:+ if self._gtc is None:+ return {}+ return self._gtc.get_forwarded_vars(self._submissions, self._reviews, self._comparisons)+def get_review_loop_from_config(config: ReviewLoopConfig | None, instance: INSTANCE_TYPE, model: BaseModeldiff --git a/tests/test_reviewer.py b/tests/test_reviewer.pyindex 1c0227f7..8661dcc3 100644--- a/tests/test_reviewer.py+++ b/tests/test_reviewer.py@@ -12,6 +12,7 @@ from sweagent.agent.models import BaseModel, ModelArgumentsfrom sweagent.agent.reviewer import (BinaryReviewer,BinaryReviewerConfig,+ GTCConfig,Reviewer,ReviewerConfig,ReviewLoop,@@ -185,12 +186,13 @@ def get_agent_arguments(review_loop_config) -> AgentArguments:@pytest.mark.slow()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,+ GTCConfig(),max_samples=100,min_draws=100,max_accepted_draws=2,+ gtc_classname="GraveToCradle",)agent_args = get_agent_arguments(rl_config)assert agent_args.config.review_loop_config is not None