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]
CI: Test OpenAI model (#166)
Kilian Lieret31d143c1a4f5
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 3dde9343..f3a37342 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -27,7 +27,9 @@ logger = logging.getLogger(LOGGER_NAME)class Subroutine(FrozenSerializable):name: stragent_file: str- return_type: str = None # one of "action", "observation", "response", "state", "thought"+ return_type: str = (+ None # one of "action", "observation", "response", "state", "thought"+ )init_observation: Optional[str] = Noneend_name: Optional[str] = Nonesignature: Optional[str] = None@@ -45,8 +47,12 @@ class AgentConfig(FrozenSerializable):strategy_template: Optional[str] = Nonedemonstration_template: Optional[str] = Nonedemonstrations: list[str] = field(default_factory=list)- put_demos_in_history: bool = False # if True, add demonstration to history instead of as a single message- format_error_template: str = None # defaults to format_error_template in ParseFunction+ put_demos_in_history: bool = (+ False # if True, add demonstration to history instead of as a single message+ )+ format_error_template: str = (+ None # defaults to format_error_template in ParseFunction+ )command_files: list[str] = field(default_factory=list)env_variables: dict[str, str] = field(default_factory=dict)util_functions: list[str] = field(default_factory=list)@@ -56,7 +62,9 @@ class AgentConfig(FrozenSerializable):history_processor: str = "DefaultHistoryProcessor"history_processor_args: dict[str, Any] = field(default_factory=dict)command_docs: str = None- blocklist_error_template: str = "Interactive operation '{name}' is not supported by this environment"+ blocklist_error_template: str = (+ "Interactive operation '{name}' is not supported by this environment"+ )blocklist: Tuple[str] = ("vim","vi",@@ -114,23 +122,27 @@ class AgentConfig(FrozenSerializable):self, "util_functions", self.util_functions + util_functions)object.__setattr__(self, "_commands", self._commands + commands)-+for subroutine in self.subroutine_types:- if subroutine.name == 'submit':+ if subroutine.name == "submit":raise ValueError("Cannot use 'submit' as a subroutine name")agent_args = AgentArguments(model=subroutine.model,config_file=subroutine.agent_file,- )+ )object.__setattr__(subroutine, "agent_args", agent_args)- object.__setattr__(self, "_subroutines", {**self._subroutines, subroutine.name: subroutine})+ object.__setattr__(+ self, "_subroutines", {**self._subroutines, subroutine.name: subroutine}+ )multi_line_command_endings = {command.name: command.end_namefor command in [*self._commands, *self._subroutines.values()]if command.end_name is not None}- object.__setattr__(self, "multi_line_command_endings", multi_line_command_endings)+ object.__setattr__(+ self, "multi_line_command_endings", multi_line_command_endings+ )object.__setattr__(self,"command_docs",@@ -138,24 +150,31 @@ class AgentConfig(FrozenSerializable):self._commands,self.subroutine_types,**self.env_variables,- ),- )- object.__setattr__(self, "parse_function", ParseFunction.get(self.parse_function))+ ),+ )+ object.__setattr__(+ self, "parse_function", ParseFunction.get(self.parse_function)+ )if self.format_error_template is None:object.__setattr__(self,"format_error_template",self.parse_function.format_error_template,- )- object.__setattr__(self, "format_error_template", self.format_error_template.format(**self.__dict__))+ )+ object.__setattr__(+ self,+ "format_error_template",+ self.format_error_template.format(**self.__dict__),+ )for command in self._commands:if command.name == self.submit_command:object.__setattr__(self, "submit_command_end_name", command.end_name)breakobject.__setattr__(- self, "history_processor",- HistoryProcessor.get(self.history_processor, **self.history_processor_args)- )+ self,+ "history_processor",+ HistoryProcessor.get(self.history_processor, **self.history_processor_args),+ )@dataclass(frozen=True)@@ -174,8 +193,14 @@ class AgentArguments(FlattenedAccess, FrozenSerializable):assert self.config is not Nonefor subroutine in getattr(self.config, "subroutines", {}).values():model_args = getattr(subroutine, "model")- object.__setattr__(model_args, "per_instance_cost_limit", self.model.per_instance_cost_limit)- object.__setattr__(model_args, "total_cost_limit", self.model.total_cost_limit)+ object.__setattr__(+ model_args,+ "per_instance_cost_limit",+ self.model.per_instance_cost_limit,+ )+ object.__setattr__(+ model_args, "total_cost_limit", self.model.total_cost_limit+ )class Agent:@@ -183,7 +208,9 @@ class Agent:def __init__(self, name: str, args: AgentArguments):self.name = name- self.model = get_model(args.model, args.config._commands + args.config.subroutine_types)+ self.model = get_model(+ args.model, args.config._commands + args.config.subroutine_types+ )self.config = args.configself.system_args = {"command_docs": self.config.command_docs,@@ -210,21 +237,29 @@ class Agent:self.model):for demonstration_path in self.config.demonstrations:- if self.config.demonstration_template is None and not self.config.put_demos_in_history:- raise ValueError("Cannot use demonstrations without a demonstration template or put_demos_in_history=True")+ if (+ self.config.demonstration_template is None+ and not self.config.put_demos_in_history+ ):+ raise ValueError(+ "Cannot use demonstrations without a demonstration template or put_demos_in_history=True"+ )# Load historylogger.info(f"DEMONSTRATION: {demonstration_path}")demo_history = json.load(open(demonstration_path, "r"))["history"]demo_history = [- entry for entry in demo_history- if ("agent" not in entry) or- ("agent" in entry and entry["agent"] == self.name)+ entry+ for entry in demo_history+ if ("agent" not in entry)+ or ("agent" in entry and entry["agent"] == self.name)]if self.config.put_demos_in_history:if self.config.demonstration_template is not None:- logger.warning("Demonstration template is ignored for put_demos_in_history=True")+ logger.warning(+ "Demonstration template is ignored for put_demos_in_history=True"+ )# Add demonstration to history directly as separate messagesfor entry in demo_history:if entry["role"] != "system":@@ -239,25 +274,29 @@ class Agent:demonstration = self.config.demonstration_template.format(**{"demonstration": demo_message})- self.history.append({- "agent": self.name,- "content": demonstration,- "is_demo": True,- "role": "user",- })+ self.history.append(+ {+ "agent": self.name,+ "content": demonstration,+ "is_demo": True,+ "role": "user",+ }+ )@propertydef state_command(self) -> str:"""Return the bash command that will be used to extract the environment state."""return self.config.state_command.name-+@propertydef local_history(self) -> list[dict[str, str]]:"""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])+ return self.config.history_processor(+ [entry for entry in self.history if entry["agent"] == self.name]+ )def save_trajectory(self, trajectory, traj_dir, env, info):- log_path = traj_dir / (env.record['instance_id'] + ".traj")+ log_path = traj_dir / (env.record["instance_id"] + ".traj")log_dict = {"environment": env.name,"trajectory": trajectory,@@ -273,10 +312,23 @@ class Agent:if pattern_type == "subroutine":patterns = {k: v for k, v in self.subroutine_patterns.items()}elif pattern_type == "multi_line":- patterns = {k: v for k, v in self.command_patterns.items() if k in self.config.multi_line_command_endings or k == self.config.submit_command}- patterns += {k: v for k, v in self.subroutine_patterns.items() if k in self.config.multi_line_command_endings}+ patterns = {+ k: v+ for k, v in self.command_patterns.items()+ if k in self.config.multi_line_command_endings+ or k == self.config.submit_command+ }+ patterns += {+ k: v+ for k, v in self.subroutine_patterns.items()+ if k in self.config.multi_line_command_endings+ }elif pattern_type == "multi_line_no_subroutines":- patterns = {k: v for k, v in self.command_patterns.items() if k in self.config.multi_line_command_endings}+ patterns = {+ k: v+ for k, v in self.command_patterns.items()+ if k in self.config.multi_line_command_endings+ }else:raise ValueError(f"Unknown pattern type: {pattern_type}")matches = list()@@ -292,7 +344,7 @@ class Agent:def _guard_multiline_input(self, action: str) -> str:"""Split action by multiline commands, then append the first line in each multiline command with "<< '{end_name}'".Multiline commands (which are specified by an end_name) are commands that span multiple lines and are terminated by a specific end_name.-+Their multi-line argument is sent using a heredoc, which is a way to send a multi-line string to a command in bash."""parsed_action = list()@@ -300,20 +352,18 @@ class Agent:while rem_action.strip():first_match = self._get_first_match(rem_action, "multi_line_no_subroutines")if first_match:- pre_action = rem_action[:first_match.start()]- match_action = rem_action[first_match.start():first_match.end()]- rem_action = rem_action[first_match.end():]+ pre_action = rem_action[: first_match.start()]+ match_action = rem_action[first_match.start() : first_match.end()]+ rem_action = rem_action[first_match.end() :]if pre_action.strip():parsed_action.append(pre_action)if match_action.strip():eof = first_match.group(3).strip()- if not match_action.split('\n')[0].strip().endswith(f"<< '{eof}'"):- guarded_command = match_action[first_match.start():]- first_line = guarded_command.split('\n')[0]+ if not match_action.split("\n")[0].strip().endswith(f"<< '{eof}'"):+ guarded_command = match_action[first_match.start() :]+ first_line = guarded_command.split("\n")[0]guarded_command = guarded_command.replace(- first_line,- first_line + f" << '{eof}'",- 1+ first_line, first_line + f" << '{eof}'", 1)parsed_action.append(guarded_command)else:@@ -321,7 +371,7 @@ class Agent:else:parsed_action.append(rem_action)rem_action = ""- return '\n'.join(parsed_action)+ return "\n".join(parsed_action)def split_actions(self, action: str, pattern_type="subroutine") -> list[str]:"""Split an action into a list of actions in a greedy manner, each of which is a subroutine call or a single command."""@@ -330,55 +380,86 @@ class Agent:while rem_action.strip():first_match = self._get_first_match(rem_action, pattern_type)if first_match:- pre_action = rem_action[:first_match.start()]- match_action = rem_action[first_match.start():first_match.end()]- rem_action = rem_action[first_match.end():]+ pre_action = rem_action[: first_match.start()]+ match_action = rem_action[first_match.start() : first_match.end()]+ rem_action = rem_action[first_match.end() :]if pre_action.strip():- parsed_action.append({'agent': self.name, 'action': pre_action, 'cmd_name': None})+ parsed_action.append(+ {"agent": self.name, "action": pre_action, "cmd_name": None}+ )if match_action.strip():if match_action.split()[0] == self.config.submit_command:- parsed_action.append({'agent': self.name, 'action': match_action, 'cmd_name': first_match.group(1)}) # submit command is not a subroutine+ parsed_action.append(+ {+ "agent": self.name,+ "action": match_action,+ "cmd_name": first_match.group(1),+ }+ ) # submit command is not a subroutineelse:- parsed_action.append({'agent': first_match.group(1), 'args': first_match.group(2), 'action': match_action, 'cmd_name': first_match.group(1)})+ parsed_action.append(+ {+ "agent": first_match.group(1),+ "args": first_match.group(2),+ "action": match_action,+ "cmd_name": first_match.group(1),+ }+ )else:- parsed_action.append({'agent': self.name, 'action': rem_action, 'cmd_name': None})+ parsed_action.append(+ {"agent": self.name, "action": rem_action, "cmd_name": None}+ )rem_action = ""return parsed_action-+def _parse_command_patterns(self):self.command_patterns = dict()for command in self.config._commands:if command.end_name is not None:- pat = re.compile(fr'^\s*({command.name})\s*(.*?)^({command.end_name})\s*$', re.DOTALL | re.MULTILINE)+ pat = re.compile(+ rf"^\s*({command.name})\s*(.*?)^({command.end_name})\s*$",+ re.DOTALL | re.MULTILINE,+ )self.command_patterns[command.name] = patelse:- pat = re.compile(fr'^\s*({command.name})\s*(.*?)$', re.MULTILINE)+ pat = re.compile(rf"^\s*({command.name})\s*(.*?)$", re.MULTILINE)self.command_patterns[command.name] = patself.subroutine_patterns = dict()for _, subroutine in self.config._subroutines.items():if subroutine.end_name is None:- pat = re.compile(fr'^\s*({subroutine.name})\s*(.*?)$', re.MULTILINE)+ pat = re.compile(rf"^\s*({subroutine.name})\s*(.*?)$", re.MULTILINE)self.subroutine_patterns[subroutine.name,] = patelse:- pat = re.compile(fr'^\s*({subroutine.name})\s*(.*?)^({subroutine.end_name})\s*$', re.DOTALL | re.MULTILINE)+ pat = re.compile(+ rf"^\s*({subroutine.name})\s*(.*?)^({subroutine.end_name})\s*$",+ re.DOTALL | re.MULTILINE,+ )self.subroutine_patterns[subroutine.name] = pat- if hasattr(self.config, 'submit_command_end_name'):- submit_pat = re.compile(rf'^\s*({self.config.submit_command})\s*(.*?)^({self.config.submit_command_end_name})\s*$', re.DOTALL | re.MULTILINE)+ if hasattr(self.config, "submit_command_end_name"):+ submit_pat = re.compile(+ rf"^\s*({self.config.submit_command})\s*(.*?)^({self.config.submit_command_end_name})\s*$",+ re.DOTALL | re.MULTILINE,+ )else:- submit_pat = re.compile(rf'^\s*({self.config.submit_command})(\s*)$', re.MULTILINE) # group 2 is nothing+ submit_pat = re.compile(+ rf"^\s*({self.config.submit_command})(\s*)$", re.MULTILINE+ ) # group 2 is nothingself.subroutine_patterns[self.config.submit_command] = submit_patself.command_patterns[self.config.submit_command] = submit_pat- def forward(self, observation: str, available_actions: list[str], state: str) -> Tuple[str, str, str]:+ def forward(+ self, observation: str, available_actions: list[str], state: str+ ) -> Tuple[str, str, str]:thought, action, output = self.forward_with_error_check(observation, state)self.history.append(- {"role": "assistant",- "content": output,- "thought": thought,- "action": action,- "agent": self.name,- }+ {+ "role": "assistant",+ "content": output,+ "thought": thought,+ "action": action,+ "agent": self.name,+ })logger.info(f"💭 THOUGHT ({self.name})\n{thought}")@@ -395,7 +476,9 @@ class Agent:templates = []# Determine observation template based on what prior observation was- if self.history[-1]["role"] == "system" or self.history[-1].get("is_demo", False):+ if self.history[-1]["role"] == "system" or self.history[-1].get(+ "is_demo", False+ ):# Show instance template if prev. obs. was initial system messagetemplates = [self.config.instance_template]if self.config.strategy_template is not None:@@ -466,7 +549,8 @@ class Agent:return Falsedef check_format_and_requery(- self, output: str,+ self,+ output: str,) -> Tuple[str, str, str]:"""Query the model with the current state and observation with the appropriate template.@@ -508,7 +592,9 @@ class Agent:logger.warning(f"Malformat limit reached: \n{output}")return "Exit due to format error", "exit_format", output- def forward_with_error_check(self, observation: str, state: str) -> Tuple[str, str, str]:+ def forward_with_error_check(+ self, observation: str, state: str+ ) -> Tuple[str, str, str]:try:output = self.forward_model(observation, state)except KeyboardInterrupt:@@ -522,7 +608,11 @@ class Agent:)except ContextWindowExceededError as e:logger.warning(f"Context window exceeded")- return "Exit due to context window", "exit_context", "Exit due to context window"+ return (+ "Exit due to context window",+ "exit_context",+ "Exit due to context window",+ )except CostLimitExceededError as e:logger.warning(f"Cost limit exceeded")return "Exit due to cost limit", "exit_cost", "Exit due to cost limit"@@ -534,81 +624,88 @@ class Agent:f"exit due to retry error: {e}",)return self.check_format_and_requery(output)-+def init_environment_vars(self, env):self.set_environment_vars(env, self.config.env_variables)def set_environment_vars(self, env, env_variables):commands_to_execute = (- [self.config.state_command.code] ++ [self.config.state_command.code]+ +# [code for code in self.config.util_functions] +# [command.code for command in self.config._commands] +- [f"{k}={v}" for k,v in env_variables.items()]+ [f"{k}={v}" for k, v in env_variables.items()])commands = "\n".join(commands_to_execute)try:output = env.communicate(commands)if env.returncode != 0:- raise RuntimeError(f"Nonzero return code: {env.returncode}\nOutput: {output}")+ raise RuntimeError(+ f"Nonzero return code: {env.returncode}\nOutput: {output}"+ )except KeyboardInterrupt:- raise+ raiseexcept Exception as e:- logger.warning("Failed to set environment variables")- raise e+ logger.warning("Failed to set environment variables")+ raise ecommand_files = list()for file in self.config.command_files:datum = dict()- contents = open(file, 'r').read()- datum['contents'] = contents+ contents = open(file, "r").read()+ datum["contents"] = contentsfilename = Path(file).name- if not contents.strip().startswith('#!'):- if filename.endswith('.sh'):+ if not contents.strip().startswith("#!"):+ if filename.endswith(".sh"):# files are sourced, so they are not executable- datum['name'] = Path(file).name- datum['type'] = 'source_file'- elif filename.startswith('_'):+ datum["name"] = Path(file).name+ datum["type"] = "source_file"+ elif filename.startswith("_"):# files are sourced, so they are not executable- datum['name'] = Path(file).name- datum['type'] = 'utility'+ datum["name"] = Path(file).name+ datum["type"] = "utility"else:- raise ValueError((- f"Non-shell script file {file} does not start with shebang.\n"- "Either add a shebang (#!) or change the file extension to .sh if you want to source it.\n"- "You can override this behavior by adding an underscore to the file name (e.g. _utils.py)."- ))+ raise ValueError(+ (+ f"Non-shell script file {file} does not start with shebang.\n"+ "Either add a shebang (#!) or change the file extension to .sh if you want to source it.\n"+ "You can override this behavior by adding an underscore to the file name (e.g. _utils.py)."+ )+ )else:# scripts are made executable- datum['name'] = Path(file).name.rsplit('.', 1)[0]- datum['type'] = 'script'+ datum["name"] = Path(file).name.rsplit(".", 1)[0]+ datum["type"] = "script"command_files.append(datum)env.add_commands(command_files)-+def get_environment_vars(self, env):env_vars = dict()for var in self.config.env_variables:env_vars[var] = env.communicate(f"echo ${var}").strip()return env_vars-+def call_subroutine(self, agent_name, sub_action, env):env_vars = self.get_environment_vars(env)cwd = env.communicate("pwd -P").strip()init_observation = self.config._subroutines[agent_name].init_observationif init_observation is not None:- obs, _, _, _ = env.step(init_observation.format(args=sub_action['args']))+ obs, _, _, _ = env.step(init_observation.format(args=sub_action["args"]))else:obs = Noneif env.returncode != 0:self.history.append({"role": "user", "content": obs, "agent": agent_name})- raise RuntimeError(f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}")+ raise RuntimeError(+ f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}"+ )return_type = self.config._subroutines[agent_name].return_typesub_agent = Agent(agent_name, self.config._subroutines[agent_name].agent_args)sub_agent_output = sub_agent.run(- {"issue": sub_action['args']},+ {"issue": sub_action["args"]},env,observation=obs,return_type=return_type,init_model_stats=self.model.stats,- )+ )self.history += sub_agent.historyself.set_environment_vars(env, env_vars)env.communicate(f"cd {cwd}")@@ -616,14 +713,14 @@ class Agent:return sub_agent_outputdef run(- self,- setup_args,- env: SWEEnv,- observation: str = None,- traj_dir: Optional[Path] = None,- return_type: Optional[str] = "info",- init_model_stats: Optional[APIStats] = None,- ):+ self,+ setup_args,+ env: SWEEnv,+ observation: str = None,+ traj_dir: Optional[Path] = None,+ return_type: Optional[str] = "info",+ init_model_stats: Optional[APIStats] = None,+ ):"""Run the agent on an environment.Return the final value of the specified return type.@@ -631,7 +728,9 @@ class Agent:done = Falseif env.container_obj.id != self.last_container_id:- logger.info(f"Initializing agent settings for container {env.container_obj.id}")+ logger.info(+ f"Initializing agent settings for container {env.container_obj.id}"+ )self.init_environment_vars(env)self.last_container_id = env.container_obj.id# Re-initialize primary@@ -643,25 +742,27 @@ class Agent:while not done:state = env.communicate(self.state_command) if self.state_command else Nonethought, action, output = self.forward(- observation,- env.get_available_actions(),- state)+ observation, env.get_available_actions(), state+ )observations = list()run_action = self._guard_multiline_input(action)for sub_action in self.split_actions(run_action):- if sub_action['agent'] == self.name or sub_action['cmd_name'] == self.config.submit_command:- obs, _, done, info = env.step(sub_action['action'])+ if (+ sub_action["agent"] == self.name+ or sub_action["cmd_name"] == self.config.submit_command+ ):+ obs, _, done, info = env.step(sub_action["action"])observations.append(obs)- if sub_action['cmd_name'] == self.config.submit_command:+ if sub_action["cmd_name"] == self.config.submit_command:done = Trueif done:breakelse:- agent_name = sub_action['agent']+ agent_name = sub_action["agent"]sub_agent_output = self.call_subroutine(agent_name, sub_action, env)observations.append(sub_agent_output)- observation = '\n'.join([obs for obs in observations if obs is not None])+ observation = "\n".join([obs for obs in observations if obs is not None])trajectory.append({@@ -672,7 +773,7 @@ class Agent:"thought": thought,})- info['model_stats'] = self.model.stats.to_dict()+ info["model_stats"] = self.model.stats.to_dict()if traj_dir:self.save_trajectory(trajectory, traj_dir, env, info)if return_type == "info":diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex cade1d3a..48c907ea 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -110,7 +110,7 @@ class BaseModel:else:self.stats = other- def update_stats(self, input_tokens, output_tokens):+ def update_stats(self, input_tokens: int, output_tokens: int) -> float:"""Calculates the cost of a response from the openai API.@@ -223,6 +223,8 @@ class OpenAIModel(BaseModel):# Set OpenAI keycfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))+ print(">>>>>>>>", cfg)+ print(">>>>>>", OpenAI)if self.args.model_name.startswith("azure"):self.api_model = cfg["AZURE_OPENAI_DEPLOYMENT"]self.client = AzureOpenAI(api_key=cfg["AZURE_OPENAI_API_KEY"], azure_endpoint=cfg["AZURE_OPENAI_ENDPOINT"], api_version=cfg.get("AZURE_OPENAI_API_VERSION", "2024-02-01"))diff --git a/tests/test_models.py b/tests/test_models.pynew file mode 100644index 00000000..8ae84a60--- /dev/null+++ b/tests/test_models.py@@ -0,0 +1,35 @@+from tkinter.filedialog import Open+from unittest.mock import MagicMock, Mock, patch+from sweagent.agent.models import OpenAIModel, ModelArguments, AnthropicModel+import pytest+++def openai_mock_client():+ model = Mock()+ reponse = Mock()+ choice = Mock()+ choice.message.content = "test"+ reponse.choices = [choice]+ reponse.usage.prompt_tokens = 10+ reponse.usage.completion_tokens = 10+ model.chat.completions.create = MagicMock(return_value=reponse)++ return model+++TEST_HISTORY = [+ {+ "role": "system",+ "content": "Hello, how are you?"+ }+]+++def test_openai_model(openai_mock_client):+ for model_name in list(OpenAIModel.MODELS) + list(OpenAIModel.SHORTCUTS):+ TEST_MODEL_ARGUMENTS = ModelArguments(model_name)+ with patch("sweagent.agent.models.config.Config"), patch("sweagent.agent.models.OpenAI"):+ model = OpenAIModel(TEST_MODEL_ARGUMENTS, [])+ model.client = openai_mock_client+ model.query(TEST_HISTORY)