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]
First version of anthropic str_replace_editor
Kilian Lieret2e4eb5332531
diff --git a/config/function_calling_replace_more_anthropic.yaml b/config/function_calling_anthropic_openhands.yamlsimilarity index 98%rename from config/function_calling_replace_more_anthropic.yamlrename to config/function_calling_anthropic_openhands.yamlindex e23ad9bc..3ab61a2a 100644--- a/config/function_calling_replace_more_anthropic.yaml+++ b/config/function_calling_anthropic_openhands.yaml@@ -1,3 +1,4 @@+# This template is heavily inspired by anthropic and openhandsagent:templates:system_template: |-@@ -91,9 +92,7 @@ agent:OVERLAP: 2bundles:- path: tools/defaults- - path: tools/search- # - path: tools/edit_linting- - path: tools/edit_replace+ - path: tools/edit_anthropic- path: tools/submitenable_bash_tool: trueparse_function:diff --git a/tools/edit_anthropic/bin/str_replace_editor b/tools/edit_anthropic/bin/str_replace_editornew file mode 100644index 00000000..f54e48ff--- /dev/null+++ b/tools/edit_anthropic/bin/str_replace_editor@@ -0,0 +1,359 @@+#!/usr/bin/env python3++"""This is an adaptation of the Anthropic Text Editor tool from+https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/edit.py+However, we made it python 3.6 compatible.+"""++import argparse+import subprocess+import sys+from collections import defaultdict+from pathlib import Path+from typing import List, Optional, Any+import json+import os++TRUNCATED_MESSAGE: str = "<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>"+MAX_RESPONSE_LEN: int = 16000+++def maybe_truncate(content: str, truncate_after: Optional[int] = MAX_RESPONSE_LEN):+ """Truncate content and append a notice if content exceeds the specified length."""+ return (+ content+ if not truncate_after or len(content) <= truncate_after+ else content[:truncate_after] + TRUNCATED_MESSAGE+ )+++Command = str+SNIPPET_LINES: int = 4+++class EnvRegistry:+ """Read and write variables into a file. This is used to persist state between tool+ calls without using environment variables (which are problematic because you cannot+ set them in a subprocess).++ The default file location is `/root/.swe-agent-env`, though this can be overridden+ by the `env_file` argument or the `SWE_AGENT_ENV_FILE` environment variable.+ """++ def __init__(self, env_file: Optional[Path] = None):+ self._env_file = env_file++ @property+ def env_file(self) -> Path:+ if self._env_file is None:+ env_file = Path(os.environ.get("SWE_AGENT_ENV_FILE", "/root/.swe-agent-env"))+ else:+ env_file = self._env_file+ if not env_file.exists():+ env_file.write_text("{}")+ return env_file++ def __getitem__(self, key: str) -> str:+ return json.loads(self.env_file.read_text())[key]++ def get(self, key: str, default_value: Any = None) -> Any:+ return json.loads(self.env_file.read_text()).get(key, default_value)++ def get_if_none(self, value: Any, key: str, default_value: Any = None) -> Any:+ if value is not None:+ return value+ return self.get(key, default_value)++ def __setitem__(self, key: str, value: Any):+ env = json.loads(self.env_file.read_text())+ env[key] = value+ self.env_file.write_text(json.dumps(env))+++REGISTRY = EnvRegistry()+++class EditTool:+ """+ An filesystem editor tool that allows the agent to view, create, and edit files.+ The tool parameters are defined by Anthropic and are not editable.+ """++ name = "str_replace_editor"++ def __init__(self):+ super().__init__()++ @property+ def _file_history(self):+ return json.loads(REGISTRY["file_history"])++ @_file_history.setter+ def _file_history(self, value: dict):+ REGISTRY["file_history"] = json.dumps(value)++ def __call__(+ self,+ *,+ command: Command,+ path: str,+ file_text: Optional[str] = None,+ view_range: Optional[List[int]] = None,+ old_str: Optional[str] = None,+ new_str: Optional[str] = None,+ insert_line: Optional[int] = None,+ **kwargs,+ ):+ _path = Path(path)+ self.validate_path(command, _path)+ if command == "view":+ return self.view(_path, view_range)+ elif command == "create":+ if file_text is None:+ print("Parameter `file_text` is required for command: create")+ sys.exit(1)+ self.write_file(_path, file_text)+ self._file_history[_path].append(file_text)+ print(f"File created successfully at: {_path}")+ return None+ elif command == "str_replace":+ if old_str is None:+ print("Parameter `old_str` is required for command: str_replace")+ sys.exit(2)+ return self.str_replace(_path, old_str, new_str)+ elif command == "insert":+ if insert_line is None:+ print("Parameter `insert_line` is required for command: insert")+ sys.exit(3)+ if new_str is None:+ print("Parameter `new_str` is required for command: insert")+ sys.exit(4)+ return self.insert(_path, insert_line, new_str)+ elif command == "undo_edit":+ return self.undo_edit(_path)+ print(+ f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: "view", "create", "str_replace", "insert", "undo_edit"'+ )+ sys.exit(5)++ def validate_path(self, command: str, path: Path):+ """+ Check that the path/command combination is valid.+ """+ # Check if its an absolute path+ if not path.is_absolute():+ suggested_path = Path.cwd() / path+ print(+ f"The path {path} is not an absolute path, it should start with `/`. Maybe you meant {suggested_path}?"+ )+ sys.exit(6)+ # Check if path exists+ if not path.exists() and command != "create":+ print(f"The path {path} does not exist. Please provide a valid path.")+ sys.exit(7)+ if path.exists() and command == "create":+ print(f"File already exists at: {path}. Cannot overwrite files using command `create`.")+ sys.exit(8)+ # Check if the path points to a directory+ if path.is_dir():+ if command != "view":+ print(f"The path {path} is a directory and only the `view` command can be used on directories")+ sys.exit(9)++ def view(self, path: Path, view_range: Optional[List[int]] = None):+ """Implement the view command"""+ if path.is_dir():+ if view_range:+ print("The `view_range` parameter is not allowed when `path` points to a directory.")+ sys.exit(10)++ out = subprocess.run(+ rf"find {path} -maxdepth 2 -not -path '*/\.*'",+ shell=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ stdout = out.stdout.decode()+ stderr = out.stderr.decode()++ if not stderr:+ stdout = f"Here's the files and directories up to 2 levels deep in {path}, excluding hidden items:\n{stdout}\n"+ print(stdout)+ return++ file_content = self.read_file(path)+ init_line = 1+ if view_range:+ if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):+ print("Invalid `view_range`. It should be a list of two integers.")+ sys.exit(11)+ file_lines = file_content.split("\n")+ n_lines_file = len(file_lines)+ init_line, final_line = view_range+ if init_line < 1 or init_line > n_lines_file:+ print(+ f"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}"+ )+ sys.exit(12)+ if final_line > n_lines_file:+ print(+ f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`"+ )+ sys.exit(13)+ if final_line != -1 and final_line < init_line:+ print(+ f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be larger or equal than its first `{init_line}`"+ )+ sys.exit(14)++ if final_line == -1:+ file_content = "\n".join(file_lines[init_line - 1 :])+ else:+ file_content = "\n".join(file_lines[init_line - 1 : final_line])++ print(self._make_output(file_content, str(path), init_line=init_line))++ def str_replace(self, path: Path, old_str: str, new_str: Optional[str]):+ """Implement the str_replace command, which replaces old_str with new_str in the file content"""+ # Read the file content+ file_content = self.read_file(path).expandtabs()+ old_str = old_str.expandtabs()+ new_str = new_str.expandtabs() if new_str is not None else ""++ # Check if old_str is unique in the file+ occurrences = file_content.count(old_str)+ if occurrences == 0:+ print(f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}.")+ sys.exit(15)+ elif occurrences > 1:+ file_content_lines = file_content.split("\n")+ lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]+ print(+ f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"+ )+ sys.exit(16)++ # Replace old_str with new_str+ new_file_content = file_content.replace(old_str, new_str)++ # Write the new content to the file+ self.write_file(path, new_file_content)++ # Save the content to history+ self._file_history[path].append(file_content)++ # Create a snippet of the edited section+ replacement_line = file_content.split(old_str)[0].count("\n")+ start_line = max(0, replacement_line - SNIPPET_LINES)+ end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")+ snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])++ # Prepare the success message+ success_msg = f"The file {path} has been edited. "+ success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)+ success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."++ print(success_msg)++ def insert(self, path: Path, insert_line: int, new_str: str):+ """Implement the insert command, which inserts new_str at the specified line in the file content."""+ file_text = self.read_file(path).expandtabs()+ new_str = new_str.expandtabs()+ file_text_lines = file_text.split("\n")+ n_lines_file = len(file_text_lines)++ if insert_line < 0 or insert_line > n_lines_file:+ print(+ f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}"+ )+ sys.exit(17)++ new_str_lines = new_str.split("\n")+ new_file_text_lines = file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]+ snippet_lines = (+ file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]+ + new_str_lines+ + file_text_lines[insert_line : insert_line + SNIPPET_LINES]+ )++ new_file_text = "\n".join(new_file_text_lines)+ snippet = "\n".join(snippet_lines)++ self.write_file(path, new_file_text)+ self._file_history[path].append(file_text)++ success_msg = f"The file {path} has been edited. "+ success_msg += self._make_output(+ snippet,+ "a snippet of the edited file",+ max(1, insert_line - SNIPPET_LINES + 1),+ )+ success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary."+ print(success_msg)++ def undo_edit(self, path: Path):+ """Implement the undo_edit command."""+ if not self._file_history[path]:+ print(f"No edit history found for {path}.")+ sys.exit(18)++ old_text = self._file_history[path].pop()+ self.write_file(path, old_text)++ print(f"Last edit to {path} undone successfully. {self._make_output(old_text, str(path))}")++ def read_file(self, path: Path):+ """Read the content of a file from a given path; raise a ToolError if an error occurs."""+ try:+ return path.read_text()+ except Exception as e:+ print(f"Ran into {e} while trying to read {path}")+ sys.exit(19)++ def write_file(self, path: Path, file: str):+ """Write the content of a file to a given path; raise a ToolError if an error occurs."""+ try:+ path.write_text(file)+ except Exception as e:+ print(f"Ran into {e} while trying to write to {path}")+ sys.exit(20)++ def _make_output(+ self,+ file_content: str,+ file_descriptor: str,+ init_line: int = 1,+ expand_tabs: bool = True,+ ):+ """Generate output for the CLI based on the content of a file."""+ file_content = maybe_truncate(file_content)+ if expand_tabs:+ file_content = file_content.expandtabs()+ file_content = "\n".join([f"{i + init_line:6}\t{line}" for i, line in enumerate(file_content.split("\n"))])+ return f"Here's the result of running `cat -n` on {file_descriptor}:\n" + file_content + "\n"+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("command", type=str)+ parser.add_argument("path", type=str)+ parser.add_argument("--file_text", type=str)+ parser.add_argument("--view_range", type=str)+ parser.add_argument("--old_str", type=str)+ parser.add_argument("--new_str", type=str)+ parser.add_argument("--insert_line", type=int)+ args = parser.parse_args()+ tool = EditTool()+ tool(+ command=args.command,+ path=args.path,+ file_text=args.file_text,+ view_range=args.view_range,+ old_str=args.old_str,+ new_str=args.new_str,+ insert_line=args.insert_line,+ )+++if __name__ == "__main__":+ main()diff --git a/tools/edit_anthropic/config.yaml b/tools/edit_anthropic/config.yamlnew file mode 100644index 00000000..ce2168c5--- /dev/null+++ b/tools/edit_anthropic/config.yaml@@ -0,0 +1,40 @@+tools:+ str_replace_editor:+ signature: |+ str_replace_editor <command> <path> [<file_text>] [<view_range>] [<old_str>] [<new_str>] [<insert_line>]+ docstring: >+ Create, view, or edit a file.+ arguments:+ - name: command+ type: string+ description: "command to run: view, create, str_replace, insert, undo_edit"+ required: true+ - name: path+ type: string+ description: "path to file"+ required: true+ - name: file_text+ type: string+ description: "Text to insert when evoking `create` (required for `create`)"+ required: false+ argument_format: "--file_text {value}"+ - name: view_range+ type: list+ description: "Range of lines to display when evoking `view`. If not provided, the entire file is displayed."+ required: false+ argument_format: "--view_range {value}"+ - name: old_str+ type: string+ description: "String to replace when evoking `str_replace`"+ required: false+ argument_format: "--old_str {value}"+ - name: new_str+ type: string+ description: "Replacement string when evoking `str_replace`"+ required: false+ argument_format: "--new_str {value}"+ - name: insert_line+ type: integer+ description: "Required for `insert`: Line number to insert text after."+ required: false+ argument_format: "--insert_line {value}"diff --git a/tools/edit_anthropic/install.sh b/tools/edit_anthropic/install.shnew file mode 100644index 00000000..e69de29b