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]
Merge branch 'talor-branch' into reviewer
Kilian Lieretb7b1264e0028
diff --cc .github/workflows/pytest.yamlindex 3e953446,527a00f6..7d2bc59a--- a/.github/workflows/pytest.yaml+++ b/.github/workflows/pytest.yaml@@@ -8,7 -8,7 +8,8 @@@ onpush:branches:- main+ - reviewer+ - talor-branchpaths-ignore:- 'docs/**'- 'README.md'@@@ -16,7 -16,7 +17,8 @@@pull_request:branches:- main+ - reviewer+ - talor-branchpaths-ignore:- 'docs/**'- 'README.md'diff --cc sweagent/agent/agents.pyindex 209aaaa8,c2d97b73..56eafcaf--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@@ -23,9 -21,8 +23,10 @@@ from sweagent.agent.models importget_model,)from sweagent.agent.parsing import FormatError, ParseFunction+from sweagent.agent.reviewer import AbstractReviewLoop, ReviewLoopConfig, get_review_loop_from_config+ from sweagent.agent.summarizer import SummarizeFunctionfrom sweagent.environment.swe_env import SWEEnv+from sweagent.types import AgentInfo, History, HistoryItem, ReviewSubmission, Trajectory, TrajectoryStepfrom sweagent.utils.config import convert_paths_to_abspathfrom sweagent.utils.log import get_logger@@@ -250,11 -255,8 +264,12 @@@ class Agentdef __init__(self, name: str, args: AgentArguments):self.name = name+ # todo: currently only used to get the model name, so might remove this later+ self._args = args+ #: Model used by the agent. Note: Will initialize a separate model together with the reviewer+ #: (if any) to disentangle costs.self.model = get_model(args.model, args.config._commands + args.config.subroutine_types)+ self.summarizer_model = get_model(args.config.summarizer_model if args.config.summarizer_model is not None else args.model)self.config = args.configassert self.config is not None # mypyself.system_args = {@@@ -348,44 -288,15 +363,44 @@@instance_args: Arguments for the instance"""assert self.config is not None # mypy- self.model.reset_stats(init_model_stats)self.instance_args = instance_args- system_msg = self.config.system_template.format(**self.system_args, **self.instance_args)- self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")+ if self.config.review_loop_config is not None:+ rmodel = get_model(self._args.model, [])+ rmodel.reset_stats()+ self._rloop = get_review_loop_from_config(self.config.review_loop_config, instance_args, rmodel)++ self._i_attempt = 0+ 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.history: list[dict[str, Any]] = []- self._append_history({"role": "system", "content": system_msg, "agent": self.name})+ self.setup_attempt(init_model_stats=init_model_stats)+ for hook in self.hooks:+ hook.on_setup_done()++ def setup_attempt(self, *, init_model_stats: APIStats | None = None) -> None:+ """Setup the agent for a new attempt. This includes resetting the model stats."""+ assert self.config is not None # mypy+ if self._i_attempt > 0 and init_model_stats is not None:+ msg = (+ "We might be dealing with nested retries, where subroutines are mixed with retries. "+ "Currently, this messes up accounting with init_model_stats."+ )+ raise ValueError(msg)+ if self._i_attempt > 0:+ assert self._env is not None # mypy+ self._env.reset_for_new_attempt()+ self.model.reset_stats(init_model_stats)+ # self.model = get_model(self._args.model, self.config._commands + self.config.subroutine_types)+ # fixme: This doesn't reset total cost- system_msg = self.config.system_template.format(**self.system_args)++ system_msg = self.config.system_template.format(**self.system_args, **self.instance_args)+ self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")+ self._append_history(HistoryItem({"role": "system", "content": system_msg, "agent": self.name}))if "history_to_messages" in dir(self.model):for demonstration_path in self.config.demonstrations:if self.config.demonstration_template is None and not self.config.put_demos_in_history:@@@ -905,83 -772,6 +920,85 @@@self.model.stats.replace(sub_agent.model.stats)return sub_agent_output+ def _run_sub_action(self, sub_action: SubAction) -> tuple[str | None, bool]:+ """Execute a sub-action. If the sub-action is a command, execute it.+ If it is a subroutine, call the subroutine.++ Returns:+ observation: Observation+ done: Whether `submit` or another exit reason was called+ """+ assert self._env is not None+ assert self.config is not None+ if sub_action["agent"] == self.name or sub_action["cmd_name"] == self.config.submit_command:+ # Normal command, not a subroutine+ for hook in self.hooks:+ hook.on_sub_action_started(sub_action=sub_action)+ observation, _, done, _info = self._env.step(sub_action["action"])++ observation, additional_cost = self.config.summarizer_function(sub_action["action"], observation, self._env, self.summarizer_model)++ self.model.stats += additional_cost+ self.info.update(_info)+ for hook in self.hooks:+ hook.on_sub_action_executed(obs=observation, done=done)+ if sub_action["cmd_name"] == self.config.submit_command:+ done = True+ else:+ agent_name = sub_action["agent"]+ sub_agent_output = self.call_subroutine(agent_name, sub_action, self._env)+ observation = sub_agent_output+ assert isinstance(observation, str) or observation is None+ done = False+ return observation, done++ def _run_step(self, observation: str | None) -> tuple[str | None, bool]:+ """Run a step of the agent (forward, execute, and save).++ Returns:+ observation: Observation+ done: Whether `submit` or another exit reason was called+ """++ assert self.config is not None # mypy+ assert self._env is not None++ for hook in self.hooks:+ hook.on_step_start()++ # fixme: This will probably fail if the state command is not set+ state = self._env.communicate(self.state_command) if self.state_command else None+ thought, action, output = self.forward(observation, self._env.get_available_actions(), state)+ for hook in self.hooks:+ hook.on_actions_generated(thought=thought, action=action, output=output)+ run_action: str = self._guard_multiline_input(action)++ # Loop over sub-actions (if any)+ done = False+ observations: list[str | None] = list()+ for sub_action in self.split_actions(run_action):+ observation, done = self._run_sub_action(sub_action)+ # If the last sub-action is done, the observation is not+ # appended.+ if done:+ break+ observations.append(observation)+ observation = "\n".join([obs for obs in observations if obs is not None])++ trajectory_step = TrajectoryStep(+ {+ "action": action,+ "observation": observation,+ "response": output,+ "state": state,+ "thought": thought,+ },+ )+ self.trajectory.append(trajectory_step)+ model_stats: APIStats = self.model.stats+ self.info["model_stats"] = model_stats.to_dict()+ for hook in self.hooks:+ hook.on_step_done(trajectory_step=trajectory_step, model_stats=model_stats)+ return observation, done+def run(self,setup_args: dict[str, Any],@@@ -1017,46 -811,70 +1034,47 @@@self.last_container_id = env.container_obj.id# Re-initialize primaryself.setup(setup_args, init_model_stats)+ self.config.summarizer_function.setup(setup_args, self.config)- for hook in self.hooks:- hook.on_run_start()+ # Save/reset some attributes+ self.trajectory = Trajectory()+ self._env = env+ self.info = AgentInfo()+ self.traj_dir = traj_dir++ self.logger.info("Trajectory will be saved to %s", self.traj_path)# Run action/observation loop- trajectory = []- info = {}- traj_log_path = traj_dir / (env.record["instance_id"] + ".traj")- self.logger.info("Trajectory will be saved to %s", traj_log_path)+ for hook in self.hooks:+ hook.on_run_start()+ done = Falsewhile not done:- for hook in self.hooks:- hook.on_step_start()- state = env.communicate(self.state_command) if self.state_command else None- thought, action, output = self.forward(observation, env.get_available_actions(), state)- for hook in self.hooks:- hook.on_actions_generated(thought=thought, action=action, output=output)- 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:- for hook in self.hooks:- hook.on_sub_action_started(sub_action=sub_action)- obs, _, done, info = env.step(sub_action["action"])- obs, additional_cost = self.config.summarizer_function(sub_action["action"], obs, env, self.summarizer_model)- self.model.stats += additional_cost- for hook in self.hooks:- hook.on_sub_action_executed(obs=obs, done=done)- observations.append(obs)- if sub_action["cmd_name"] == self.config.submit_command:- done = True- if done:- break+ observation, done = self._run_step(observation)+ self.save_trajectory()+ if done:+ # fixme: Would have to fix this for replay model+ if self._rloop is not None:+ # Note: The trajectory/info will not include the last `submit` command+ self._rloop.on_submit(ReviewSubmission(trajectory=self.trajectory, info=self.info))+ # (make sure to save trajectory after self._rloop.on_submit)+ retry: bool = 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 reviews+ self.save_trajectory()+ if retry:+ self._i_attempt += 1+ self.setup_attempt()+ done = not retryelse:- 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])-- trajectory_step = TrajectoryStep(- {- "action": action,- "observation": observation,- "response": output,- "state": state,- "thought": thought,- },- )- trajectory.append(trajectory_step)- model_stats: APIStats = self.model.stats- info["model_stats"] = model_stats.to_dict()- if traj_dir:- self.save_trajectory(trajectory, traj_log_path, env_name=env.name, info=info)- for hook in self.hooks:- hook.on_step_done(trajectory_step=trajectory_step, model_stats=model_stats)-+ done = Truefor hook in self.hooks:- hook.on_run_done()+ hook.on_run_done(trajectory=self.trajectory, info=self.info)- self.logger.info("Trajectory saved to %s", traj_log_path)+ self.logger.info("Trajectory saved to %s", self.traj_path)if return_type == "info":- return info+ return self.infoif return_type == "info_trajectory":- return info, trajectory- return trajectory[-1][return_type]+ return self.info, self.trajectory+ return self.trajectory[-1][return_type]diff --cc sweagent/environment/swe_env.pyindex abe237d1,8dbd54b6..21d48169--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@@ -31,7 -30,7 +31,8 @@@ from sweagent.environment.utils importPROCESS_DONE_MARKER_END,PROCESS_DONE_MARKER_START,InvalidGithubURL,+ PatchFormatter,+ attach_network_interface_to_container,copy_anything_to_container,copy_file_to_container,format_trajectory_markdown,@@@ -42,8 -42,8 +44,9 @@@parse_gh_issue_url,read_with_timeout,read_with_timeout_experimental,+ terminate_docker_compose,)+from sweagent.types import AgentInfofrom sweagent.utils.config import keys_configfrom sweagent.utils.log import default_logger, get_logger@@@ -368,45 -414,6 +389,47 @@@ class SWEEnv(gym.Env)# Write any metadata to info if necessaryreturn None, info+ def _reset_repository(self) -> None:+ """Clean repository of any modifications + Checkout base commit"""- cmds = [++ startup_commands = [+ "echo -n > /root/files_to_edit.txt",+ f"cd /{self._repo_name}",+ "export ROOT=$(pwd -P)",- "git status",- "git restore .",- f"git reset --hard {self.base_commit}",- "git clean -fdxq",+ ]++ if self.challenge is None:++ startup_commands += ["git status",++ "git restore .",++ f"git reset --hard {self.base_commit}",++ "git clean -fdxq",++ ]+ self.communicate_with_handling(- input=" && ".join(cmds),++ input=" && ".join(startup_commands),+ error_msg="Failed to clean repository",+ )++ def _reset_environment_variables(self) -> None:+ """Reset environment variables (`CURRENT_FILE`) etc. within container"""+ cmd = [+ 'export CURRENT_FILE=""',+ "export CURRENT_LINE=0",+ "export SEARCH_RESULTS=()",+ "export SEARCH_FILES=()",+ "export SEARCH_INDEX=0",+ ]+ self.communicate_with_handling(+ input=" && ".join(cmd),+ error_msg="Failed to reset environment variables",+ )++ def reset_for_new_attempt(+ self,+ ) -> None:+ """Compared to `reset`, which prepares the container for a new instance,+ this prepares the container for taking another shot at the same instance.+ """+ self._reset_repository()+ self._reset_environment_variables()+def _apply_test_patch(self):"""Apply test patch for oracle setting@@@ -512,12 -505,17 +535,17 @@@# Record submission and end episode if `submit` keyword foundsubmission = self.get_submission(observation)if submission is not None:- self.logger.info(f"Found submission: {submission}")- info["exit_status"] = "submitted"- info["submission"] = submission if submission.strip() != "" else None- info.update(self._get_edited_files_with_context(patch=submission)) # type: ignore- observation = submission if submission.strip() != "" else None- return observation, 0, True, info+ if self.validate_submission(submission):+ self.logger.info(f"Found submission: {submission}")+ info["exit_status"] = "submitted"+ info["submission"] = submission if submission.strip() != "" else None++ info.update(self._get_edited_files_with_context(patch=submission)) # type: ignore+ observation = submission if submission.strip() != "" else None+ return observation, 0, True, info+ else:- self.logger.error(f"Wrong submission found: {submission}")++ self.logger.warning(f"Wrong submission found: {submission}")+ observation = "Wrong flag!"+ return observation, 0, False, info-return observation, 0, False, infodef close(self) -> None:diff --cc sweagent/environment/utils.pyindex f907c674,1f9eefc4..35edf1d7--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@@ -790,143 -889,6 +891,146 @@@ def format_trajectory_markdown(trajectoreturn "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)+class PatchFormatter:+ def __init__(+ self,+ patch: str,+ read_method: Callable[[str], str],+ ):+ """Given the final patch and access to the container that contains the repository,+ extract relevant lines from the modified file.++ Args:+ patch: The patch as a string.+ read_method: Callable with path to file (relative to repository root) as argument+ that returns the file content as a string.+ """+ self._patch = PatchSet(patch)+ self._patched_files: dict[str, str] = {}+ self._original_files: dict[str, str] = {}+ self._patch_applied = True+ self._read_file = read_method+ self._read_files(original=False)++ @staticmethod+ def _merge_intervals(starts: list[int], stops: list[int]) -> tuple[list[int], list[int]]:+ """Given two lists of integers, starts and stops, merges all overlapping intervals.++ For example `starts=[1, 5, 18]`, `stops=[10, 13, 20]`+ should return `starts=[1, 18]`, `stops=[13, 20]`+ """++ intervals = sorted(zip(starts, stops))+ merged = []+ for start, stop in intervals:+ if not merged or merged[-1][1] < start:+ # No overlap+ merged.append([start, stop])+ else:+ # Overlap+ merged[-1][1] = max(merged[-1][1], stop)+ # Unzip again+ merged_starts, merged_stops = zip(*merged)+ return list(merged_starts), list(merged_stops)++ def format_file(self, text: str, starts: list[int], stops: list[int], *, linenos: bool = True) -> str:+ """Reads file and returns string representation of the relevant lines.++ Args:+ path: The path to the file within the repo location+ starts: The starting line numbers of the relevant lines. The first line is line 1.+ stops: The stopping line numbers of the relevant lines. The stop is not inclusive.+ The first line is line 1.+ linenos: Whether to include line numbers+ """+ assert len(starts) == len(stops)+ assert all(start >= 1 for start in starts)+ assert all(start < stop for start, stop in zip(starts, stops))+ starts, stops = self._merge_intervals(starts, stops)+ assert all(hunk1_start < hunk2_start for hunk1_start, hunk2_start in zip(starts, starts[1:]))+ out: list[str] = []+ if starts[0] > 1:+ # Count from 1+ out.append(f"[{starts[0]-1} lines above omitted]")+ last_stop: int | None = None+ lines = text.splitlines()+ for start, stop in zip(starts, stops):+ assert start >= 1+ if last_stop is not None:+ n_omitted = start - last_stop+ # Check that we have non-overlapping hunks+ assert n_omitted >= 0+ if n_omitted:+ out.append(f"\n[{n_omitted} lines omitted]\n")+ # Count from 1+ these_lines = lines[start - 1 : stop - 1]+ if linenos:+ out.append("\n".join([f"{i:6d}: {l}" for i, l in enumerate(these_lines, start=start)]))+ else:+ out.append("\n".join(these_lines))+ last_stop = stop+ if last_stop < len(lines):+ # Stop is not inclusive+ omitted = len(lines) - last_stop+ assert omitted > 0+ out.append(f"[{omitted} lines below omitted]")+ return "\n".join(out)++ def _get_hunk_lines(self, original: bool, *, context_length: int) -> dict[str, tuple[list[int], list[int]]]:+ """Get the starts and stops for all files in the patch.++ Args:+ original: Whether to read the original file or the patched file+ context_length: The number of lines to include above and below the hunk++ Returns:+ A dictionary with the file path as key and a tuple of lists of starts and stops as value.+ """+ out: dict[str, tuple[list[int], list[int]]] = {}+ for patch in self._patch:+ if not patch.is_modified_file:+ continue+ starts: list[int] = []+ stops: list[int] = []+ for hunk in patch:+ if original:+ # 1 is the lowest line number+ start = max(1, hunk.source_start - context_length)+ stop = hunk.source_start + hunk.source_length + context_length+ else:+ start = max(1, hunk.target_start - context_length)+ stop = hunk.target_start + hunk.target_length + context_length+ starts.append(start)+ stops.append(stop)+ out[patch.path] = (starts, stops)+ return out++ def _read_files(self, original: bool) -> None:+ for patch in self._patch:+ path = patch.path+ if not patch.is_modified_file:+ continue+ if original:+ msg = "Original file reading not implemented"+ raise NotImplementedError(msg)+ else:+ assert self._patch_applied+ self._patched_files[path] = self._read_file(path)++ @staticmethod+ def concat_files_strings(files: dict[str, str]) -> str:+ """Concatenate multiple `read_files` outputs into a single string."""+ out = []+ for path, content in files.items():+ out.append(f"[File: {path}]\n{content}")+ return "\n\n".join(out)++ def get_files_str(self, *, original: bool, context_length: int | None = 50, linenos: bool = True) -> str:+ hunk_lines = self._get_hunk_lines(original=original, context_length=context_length)+ sources = self._original_files if original else self._patched_files+ return self.concat_files_strings(+ {path: self.format_file(text, *hunk_lines[path], linenos=linenos) for path, text in sources.items()}+ )+ def extract_flag_format(flag: str) -> str:+ flag_format = re.sub(r"{.*}$", "{...}", flag)- return flag_format if flag_format != flag else "..."++ return flag_format if flag_format != flag else "..."