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]
Action sampling: Give more control over querying
Kilian Lieretc9f62f36ec68
diff --git a/sweagent/agent/action_sampler.py b/sweagent/agent/action_sampler.pyindex 91f12ecc..891ba1c2 100644--- a/sweagent/agent/action_sampler.py+++ b/sweagent/agent/action_sampler.py@@ -33,7 +33,6 @@ class AbstractActionSampler(BaseModel):problem_statement: ProblemStatement,trajectory: Trajectory,history: list[dict[str, Any]],- completions: list[dict[str, Any]],) -> ActionSamplerOutput:"""Returns action with tool calls"""pass@@ -42,6 +41,8 @@ class AbstractActionSampler(BaseModel):class AskColleagues(AbstractActionSampler):type: Literal["ask_colleagues"] = "ask_colleagues"+ n_samples: int = 2+def get_colleague_discussion(self, completions: list[dict[str, Any]]) -> str:"""Concat all completions into a single string"""out = "Your colleagues had the following ideas: \n\n"@@ -69,9 +70,9 @@ class AskColleagues(AbstractActionSampler):problem_statement: ProblemStatement,trajectory: Trajectory,history: list[dict[str, Any]],- completions: list[dict[str, Any]],) -> ActionSamplerOutput:"""Returns action with tool calls"""+ completions = self._model.query(history, n=self.n_samples) # type: ignorediscussion = self.get_colleague_discussion(completions)logger.info(f"COLLEAGUE DISCUSSION:\n{discussion}")new_messages = [@@ -87,6 +88,11 @@ class AskColleagues(AbstractActionSampler):class BinaryTrajectoryComparison(AbstractActionSampler):type: Literal["binary_trajectory_comparison"] = "binary_trajectory_comparison"+ n_samples: int = 2++ comparison_temperature: float | None = None+ """Override the model's temperature. If None, take the temperature configured for the model."""+system_template: str = """<setting>You are an expert software engineer overseeing junior developers. They suggest actions to take to solve a problem. You must choose the best action to take. </setting>"""instance_template: str = dedent("""We're solving the following problem@@ -220,8 +226,8 @@ class BinaryTrajectoryComparison(AbstractActionSampler):problem_statement: ProblemStatement,trajectory: Trajectory,history: list[dict[str, Any]],- completions: list[dict[str, Any]],) -> ActionSamplerOutput:+ completions = self._model.query(history, n=self.n_samples) # type: ignoreparsed_completions = self.parse_completions(completions)parsed_completions = self.filter_duplicates(parsed_completions)if len(parsed_completions) == 1:@@ -238,7 +244,7 @@ class BinaryTrajectoryComparison(AbstractActionSampler):action2=parsed_completions[i][1],use_cache_control=len(parsed_completions) >= 3,)- response = self._model.query(messages)["message"] # type: ignore+ response = self._model.query(messages, temperature=self.comparison_temperature)["message"] # type: ignorelogger.info(f"RESPONSE: {response}")idx = self.interpret(response)comparison_log.append(diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 42df518e..14d369e9 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -132,7 +132,7 @@ class AgentConfig(BaseModel):formatting error, a blocked action, or a bash syntax error."""review_loop: ReviewLoopConfig | None = None- best_response_picker: ActionSampler | None = None+ action_sampler: ActionSampler | None = None# pydantic configmodel_config = ConfigDict(extra="forbid")@@ -165,8 +165,7 @@ class Agent:_catch_errors: bool = True,_always_require_zero_exit_code: bool = False,review_loop_config: ReviewLoopConfig | None = None,- best_response_picker: ActionSampler | None = None,- n_samples: int = 1,+ action_sampler: ActionSampler | None = None,):"""The agent handles the behaviour of the model and how it interacts with the environment.@@ -212,12 +211,10 @@ class Agent:It can be used to replay the agent's trajectory in an environment."""- self._best_response_picker = best_response_picker+ self._action_sampler = action_sampler- if self._best_response_picker is not None:- self._best_response_picker.setup(self.model, self.tools)-- self._n_samples = n_samples+ if self._action_sampler is not None:+ self._action_sampler.setup(self.model, self.tools)@classmethoddef from_config(cls, config: AgentConfig) -> Self:@@ -229,8 +226,7 @@ class Agent:model=model,max_requeries=config.max_requeries,review_loop_config=config.review_loop,- best_response_picker=config.best_response_picker,- n_samples=config.n_samples,+ action_sampler=config.action_sampler,)def add_hook(self, hook: AbstractAgentHook) -> None:@@ -735,19 +731,19 @@ class Agent:if self._rloop is not None: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, n=self._n_samples if self._n_samples > 1 else None) # type: ignore# todo: Add all options to the extra info- if self._best_response_picker is not None:+ if self._action_sampler is not None:assert self._problem_statement is not None- best = self._best_response_picker.get_action(+ best = self._action_sampler.get_action(problem_statement=self._problem_statement,trajectory=self.trajectory,history=history,- completions=output,)output = best.completion# todo: Handle history and trajectorystep.extra_info.update(best.extra_info)+ else:+ output = self.model.query(history) # type: ignorestep.output = output["message"]# todo: Can't I override the parser in __init__?step.thought, step.action = self.tools.parse_actions(output)diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex d4a8ed09..a3c1e3e8 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -507,7 +507,9 @@ class LiteLLMModel(AbstractModel):if elapsed_time < self.config.delay:time.sleep(self.config.delay - elapsed_time)- def _single_query(self, messages: list[dict[str, str]], n: int | None = None) -> list[dict]:+ def _single_query(+ self, messages: list[dict[str, str]], n: int | None = None, temperature: float | None = None+ ) -> list[dict]:self._sleep()input_tokens: int = litellm.utils.token_counter(messages=messages, model=self.config.name)if self.model_max_input_tokens is None:@@ -528,7 +530,7 @@ class LiteLLMModel(AbstractModel):response: litellm.types.utils.ModelResponse = litellm.completion( # type: ignoremodel=self.config.name,messages=messages,- temperature=self.config.temperature,+ temperature=self.config.temperature if temperature is None else temperature,top_p=self.config.top_p,api_version=self.config.api_version,api_key=self._get_api_key(),@@ -557,16 +559,18 @@ class LiteLLMModel(AbstractModel):self._update_stats(input_tokens=input_tokens, output_tokens=output_tokens, cost=cost)return outputs- def _query(self, messages: list[dict[str, str]], n: int | None = None) -> list[dict]:+ def _query(+ self, messages: list[dict[str, str]], n: int | None = None, temperature: float | None = None+ ) -> list[dict]:if n is None:- return self._single_query(messages)+ return self._single_query(messages, temperature=temperature)outputs = []# not needed for openai, but oh well.for _ in range(n):outputs.extend(self._single_query(messages))return outputs- def query(self, history: History, n: int = 1) -> list[dict] | dict:+ def query(self, history: History, n: int = 1, temperature: float | None = None) -> list[dict] | dict:messages = self._history_to_messages(history)for attempt in Retrying(stop=stop_after_attempt(self.config.retry.retries),@@ -596,7 +600,7 @@ class LiteLLMModel(AbstractModel):f"(slept for {attempt.retry_state.idle_for:.2f}s)"f"{exception_info}")- result = self._query(messages, n=n)+ result = self._query(messages, n=n, temperature=temperature)if n is None or n == 1:return result[0]return result