Skip to content

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 first draft of search_replace editor

Kilian Lieretb2e86431007c
diff --git a/config/function_calling_replace.yaml b/config/function_calling_replace.yaml
new file mode 100644
index 00000000..d06da625
--- /dev/null
+++ b/config/function_calling_replace.yaml
@@ -0,0 +1,96 @@
+agent:
+ templates:
+ system_template: |-
+ SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.
+
+ The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.
+ In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.
+
+ Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.
+ If you'd like to add the line ' print(x)' you must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run.
+
+ RESPONSE FORMAT:
+ Your shell prompt is formatted as follows:
+ (Open file: <path>) <cwd> $
+
+ First, you should _always_ include a general thought about what you're going to do next.
+ Then, for every response, you must include exactly _ONE_ command to execute.
+ All of the tools you need to use are listed for your reference.
+
+ Remember, you should only include a _SINGLE_ command in the command section and then wait for a response from the shell before continuing with more discussion and commands. Everything you include in the DISCUSSION section will be saved for future reference.
+ If you'd like to issue two commands at once, PLEASE DO NOT DO THAT! Please instead first submit just the first command, and then after receiving a response you'll be able to issue the second command.
+ You're free to use any other bash commands you want (e.g. find, grep, cat, ls, cd) in addition to the special commands listed above.
+ However, the environment does NOT support interactive session commands (e.g. python, vim), so please do not invoke them.
+ instance_template: |-
+ We're currently solving the following issue within our repository. Here's the issue text:
+ ISSUE:
+ {problem_statement}
+
+ INSTRUCTIONS:
+ Now, you're going to solve this issue on your own. Your terminal session has started and you're in the repository's root directory. You can use any bash commands or the special interface to help you. Edit all the files you need to and run any checks or tests that you want.
+ Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.
+ When you're satisfied with all of the changes you've made, you can submit your changes to the code base by simply running the submit command.
+ Note however that you cannot use any interactive session commands (e.g. python, vim) in this environment, but you can write scripts and run them. E.g. you can write a python script and then run it with `python <script_name>.py`.
+
+ NOTE ABOUT THE EDIT COMMAND: Indentation really matters! When editing a file, make sure to insert appropriate indentation before each line!
+
+ IMPORTANT TIPS:
+ 1. Always start by trying to replicate the bug that the issues discusses.
+ If the issue includes code for reproducing the bug, we recommend that you re-implement that in your environment, and run it to make sure you can reproduce the bug.
+ Then start trying to fix it.
+ When you think you've fixed the bug, re-run the bug reproduction script to make sure that the bug has indeed been fixed.
+
+ If the bug reproduction script does not print anything when it successfully runs, we recommend adding a print("Script completed successfully, no errors.") command at the end of the file,
+ so that you can be sure that the script indeed ran fine all the way through.
+
+ 2. If you run a command and it doesn't work, try running a different command. A command that did not work once will not work the second time unless you modify it!
+
+ 3. If you open a file and need to get to an area around a specific line that is not in the first 100 lines, say line 583, don't just use the scroll_down command multiple times. Instead, use the goto 583 command. It's much quicker.
+
+ 4. If the bug reproduction script requires inputting/reading a specific file, such as buggy-input.png, and you'd like to understand how to input that file, conduct a search in the existing repo code, to see whether someone else has already done that. Do this by running the command: find_file "buggy-input.png" If that doesn't work, use the linux 'find' command.
+
+ 5. Always make sure to look at the currently open file and the current working directory (which appears right after the currently open file). The currently open file might be in a different directory than the working directory! Note that some commands, such as 'create', open files, so they might change the current open file.
+
+ 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.
+
+
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+ next_step_template: |-
+ {observation}
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+ next_step_no_output_template: |-
+ Your command ran successfully and did not produce any output.
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+ # demonstration_template: |
+ # Here is a demonstration of how to correctly accomplish this task.
+ # It is included to show you how to correctly use the interface.
+ # You do not need to follow exactly what is done in the demonstration.
+ # --- DEMONSTRATION ---
+ # {demonstration}
+ # --- END OF DEMONSTRATION ---
+ # demonstrations:
+ # - trajectories/demonstrations/replay__marshmallow-code__marshmallow-1867__default_sys-env_window100__t-0.20__p-0.95__c-2.00__install-1/marshmallow-code__marshmallow-1867.traj
+ tools:
+ env_variables:
+ WINDOW: 100
+ OVERLAP: 2
+ bundles:
+ - tools/defaults
+ - tools/search
+ # - tools/edit_linting
+ - tools/edit_replace
+ - tools/submit
+ - tools/state
+ enable_bash_tool: true
+ state_command: _state
+ parse_function:
+ type: function_calling
+ history_processor:
+ type: last_n_observations
+ n: 5
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 9203dceb..da000d7c 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -571,7 +571,7 @@ class Agent:
step.thought, step.action = "", output["message"]
else:
step.thought, step.action = self.tools.parse_actions(output)
- if output.get("tool_calls", None) is not None:
+ if output.get("tool_calls") is not None:
step.tool_call_ids = [call["id"] for call in output["tool_calls"]]
step.tool_calls = output["tool_calls"]
self.logger.info(f"💭 THOUGHT\n{step.thought}\n🎬 ACTION\n{step.action.strip()}")
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 0c767a88..d0de80ba 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -198,6 +198,9 @@ class HumanModel(AbstractModel):
break
buffer.append(action)
action = "\n".join(buffer)
+ else:
+ # Input has escaped things like \n, so we need to unescape it
+ action = action.encode("utf8").decode("unicode_escape")
return action
def query(self, history: History, action_prompt: str = "> ") -> dict:
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index b56fde4e..cb275d14 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -214,7 +214,7 @@ class ToolHandler:
) # check false because bin might not exist
if (bundle / "install.sh").exists():
env.communicate(
- f"cd /root/tools/{bundle.name}; bash install.sh", check=True, timeout=self.config.install_timeout
+ f"cd /root/tools/{bundle.name}; source install.sh", check=True, timeout=self.config.install_timeout
)
# always make all files in bin executable
asyncio.run(
diff --git a/tools/defaults/bin/_read_env b/tools/defaults/bin/_read_env
index e43868ad..d2bcdb3e 100644
--- a/tools/defaults/bin/_read_env
+++ b/tools/defaults/bin/_read_env
@@ -1,19 +1,8 @@
#!/usr/bin/env python
-import json
-import os
import sys
-SWE_AGENT_ENV_FILE = os.environ.get("SWE_AGENT_ENV_FILE", "/root/.swe-agent-env")
-
-def read_env(var_name, default_value=None):
- if not os.path.exists(SWE_AGENT_ENV_FILE):
- with open(SWE_AGENT_ENV_FILE, "w") as f:
- json.dump({}, f)
- return default_value
- with open(SWE_AGENT_ENV_FILE, "r") as f:
- env = json.load(f)
- return env.get(var_name, default_value)
+from default_utils import read_env # type: ignore
if __name__ == "__main__":
var_name = sys.argv[1]
diff --git a/tools/defaults/bin/_write_env b/tools/defaults/bin/_write_env
index 27e7c1b7..433bcf83 100644
--- a/tools/defaults/bin/_write_env
+++ b/tools/defaults/bin/_write_env
@@ -1,20 +1,8 @@
#!/usr/bin/env python
-import json
-import os
import sys
-SWE_AGENT_ENV_FILE = os.environ.get("SWE_AGENT_ENV_FILE", "/root/.swe-agent-env")
-
-def write_env(var_name, var_value):
- if not os.path.exists(SWE_AGENT_ENV_FILE):
- with open(SWE_AGENT_ENV_FILE, "w") as f:
- json.dump({}, f)
- with open(SWE_AGENT_ENV_FILE, "r") as f:
- env = json.load(f)
- env[var_name] = var_value
- with open(SWE_AGENT_ENV_FILE, "w") as f:
- json.dump(env, f)
+from default_utils import write_env # type: ignore
if __name__ == "__main__":
var_name = sys.argv[1]
diff --git a/tools/defaults/install.sh b/tools/defaults/install.sh
index 58044980..b03d2258 100644
--- a/tools/defaults/install.sh
+++ b/tools/defaults/install.sh
@@ -1,12 +1,13 @@
#!/usr/bin/env bash
-set -euo pipefail
-SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
+# script_dir=$(dirname "$(readlink -f "$0")")
+bundle_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
-if [ -f "$SCRIPT_DIR/lib/utils.sh" ]; then
- source "$SCRIPT_DIR/lib/utils.sh"
-fi
+# source "$script_dir/lib/utils.sh"
+export PYTHONPATH="$bundle_dir/lib"
+
+# Write default environment variables into the environment storage
_write_env "WINDOW" "${WINDOW:-100}"
_write_env "OVERLAP" "${OVERLAP:-2}"
_write_env "CURRENT_LINE" "${CURRENT_LINE:-0}"
diff --git a/tools/defaults/lib/__init__.py b/tools/defaults/lib/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tools/defaults/lib/default_utils.py b/tools/defaults/lib/default_utils.py
new file mode 100644
index 00000000..d8a694aa
--- /dev/null
+++ b/tools/defaults/lib/default_utils.py
@@ -0,0 +1,65 @@
+import json
+import os
+from pathlib import Path, PurePath
+
+SWE_AGENT_ENV_FILE = Path(os.environ.get("SWE_AGENT_ENV_FILE", "/root/.swe-agent-env"))
+
+
+def read_env(var_name, default_value=None):
+ if not SWE_AGENT_ENV_FILE.exists():
+ SWE_AGENT_ENV_FILE.write_text("{}")
+ return default_value
+ env = json.loads(SWE_AGENT_ENV_FILE.read_text())
+ return env.get(var_name, default_value)
+
+
+def write_env(var_name, var_value):
+ if not SWE_AGENT_ENV_FILE.exists():
+ SWE_AGENT_ENV_FILE.write_text("{}")
+ env = json.loads(SWE_AGENT_ENV_FILE.read_text())
+ env[var_name] = var_value
+ SWE_AGENT_ENV_FILE.write_text(json.dumps(env))
+
+
+def get_current_file():
+ return Path(read_env("CURRENT_FILE")) # type: ignore
+
+
+def get_current_line():
+ return int(read_env("CURRENT_LINE")) # type: ignore
+
+
+def get_current_file_with_line_range(file_path: str | PurePath | None = None) -> tuple[Path, int, int]:
+ """Returns 0-based index of the first and last line to print."""
+ if file_path is None:
+ _spec = read_env("CURRENT_FILE")
+ assert _spec, "CURRENT_FILE is not set"
+ file_path = Path(_spec)
+ else:
+ file_path = Path(file_path)
+ current_line = int(read_env("CURRENT_LINE")) # type: ignore
+ window = int(read_env("WINDOW")) # type: ignore
+ n_lines = file_path.read_text().count("\n") + 1
+ return (
+ file_path,
+ max(0, current_line - 1 - window // 2),
+ min(current_line - 1 + window // 2, n_lines - 1),
+ )
+
+
+def print_window(file_path: str | PurePath | None = None, start_line: int | None = None, end_line: int | None = None):
+ """
+
+ Args:
+ start_line: 0-indexed line number
+ end_line: 0-indexed line number (inclusive)
+ """
+ file_path, start_line, end_line = get_current_file_with_line_range(file_path)
+ lines = Path(file_path).read_text().splitlines()
+ print(f"[File: {file_path} ({len(lines)} lines total)]")
+ if start_line > 0:
+ print(f"({start_line} more lines above)")
+ for i, line in enumerate(lines[start_line : end_line + 1]):
+ print(f"{i+1}:{line}")
+ if end_line < len(lines) - 1:
+ print(f"({len(lines) - end_line - 1} more lines below)")
diff --git a/tools/edit_linting/install.sh b/tools/edit_linting/install.sh
index fd758a67..75639deb 100644
--- a/tools/edit_linting/install.sh
+++ b/tools/edit_linting/install.sh
@@ -1,10 +1,5 @@
source /root/tools/defaults/lib/utils.sh
-if [ -z "$WINDOW" ]; then
- echo "Error: WINDOW not set"
- exit 1
-fi
-
_write_env "CURRENT_FILE" "${CURRENT_FILE:-}"
_write_env "CURRENT_LINE" "${CURRENT_LINE:-0}"
_write_env "WINDOW" "$WINDOW"
diff --git a/tools/edit_replace/bin/_split_string b/tools/edit_replace/bin/_split_string
new file mode 100644
index 00000000..b4a4a780
--- /dev/null
+++ b/tools/edit_replace/bin/_split_string
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+
+"""This helper command is used to print flake8 output
+
+Usage:
+ python _split_string.py <flake8_output>
+ python _split_string.py <flake8_output> <previous_errors> <edit_window_start> <edit_window_end> <n_lines>
+
+Where:
+ <flake8_output> is the output of flake8
+ <previous_errors> is the previous errors as a string
+ <edit_window_start> is the start of the edit window
+ <edit_window_end> is the end of the edit window
+ <n_lines> is the number of lines added in the edit
+"""
+
+# ruff: noqa: UP007 UP006 UP035
+
+import sys
+from dataclasses import dataclass
+from typing import List, Optional, Tuple
+
+
+@dataclass
+class Flake8Error:
+ """A class to represent a single flake8 error"""
+
+ filename: str
+ line_number: int
+ col_number: int
+ problem: str
+
+ @classmethod
+ def from_line(cls, line: str):
+ try:
+ prefix, _sep, problem = line.partition(": ")
+ filename, line_number, col_number = prefix.split(":")
+ except (ValueError, IndexError) as e:
+ msg = f"Invalid flake8 error line: {line}"
+ raise ValueError(msg) from e
+ return cls(filename, int(line_number), int(col_number), problem)
+
+
+def _update_previous_errors(
+ previous_errors: List[Flake8Error], replacement_window: Tuple[int, int], replacement_n_lines: int
+) -> List[Flake8Error]:
+ """Update the line numbers of the previous errors to what they would be after the edit window.
+ This is a helper function for `_filter_previous_errors`.
+
+ All previous errors that are inside of the edit window should not be ignored,
+ so they are removed from the previous errors list.
+
+ Args:
+ previous_errors: list of errors with old line numbers
+ replacement_window: the window of the edit/lines that will be replaced
+ replacement_n_lines: the number of lines that will be used to replace the text
+
+ Returns:
+ list of errors with updated line numbers
+ """
+ updated = []
+ lines_added = replacement_n_lines - (replacement_window[1] - replacement_window[0] + 1)
+ for error in previous_errors:
+ if error.line_number < replacement_window[0]:
+ # no need to adjust the line number
+ updated.append(error)
+ continue
+ if replacement_window[0] <= error.line_number <= replacement_window[1]:
+ # The error is within the edit window, so let's not ignore it
+ # either way (we wouldn't know how to adjust the line number anyway)
+ continue
+ # We're out of the edit window, so we need to adjust the line number
+ updated.append(Flake8Error(error.filename, error.line_number + lines_added, error.col_number, error.problem))
+ return updated
+
+
+def format_flake8_output(
+ input_string: str,
+ show_line_numbers: bool = False,
+ *,
+ previous_errors_string: str = "",
+ replacement_window: Optional[Tuple[int, int]] = None,
+ replacement_n_lines: Optional[int] = None,
+) -> str:
+ """Filter flake8 output for previous errors and print it for a given file.
+
+ Args:
+ input_string: The flake8 output as a string
+ show_line_numbers: Whether to show line numbers in the output
+ previous_errors_string: The previous errors as a string
+ replacement_window: The window of the edit (lines that will be replaced)
+ replacement_n_lines: The number of lines used to replace the text
+
+ Returns:
+ The filtered flake8 output as a string
+ """
+ errors = [Flake8Error.from_line(line.strip()) for line in input_string.split("\n") if line.strip()]
+ lines = []
+ if previous_errors_string:
+ assert replacement_window is not None
+ assert replacement_n_lines is not None
+ previous_errors = [
+ Flake8Error.from_line(line.strip()) for line in previous_errors_string.split("\n") if line.strip()
+ ]
+ previous_errors = _update_previous_errors(previous_errors, replacement_window, replacement_n_lines)
+ errors = [error for error in errors if error not in previous_errors]
+ for error in errors:
+ if not show_line_numbers:
+ lines.append(f"- {error.problem}")
+ else:
+ lines.append(f"- {error.line_number}:{error.col_number} {error.problem}")
+ return "\n".join(lines)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 2:
+ print(format_flake8_output(sys.argv[1]))
+ elif len(sys.argv) == 6:
+ window = (int(sys.argv[3]), int(sys.argv[4]))
+ n_lines = int(sys.argv[5])
+ print(
+ format_flake8_output(
+ sys.argv[1], previous_errors_string=sys.argv[2], replacement_window=window, replacement_n_lines=n_lines
+ )
+ )
+ else:
+ msg = "Invalid number of arguments. Must be 1 or 5."
+ raise ValueError(msg)
diff --git a/tools/edit_replace/bin/edit b/tools/edit_replace/bin/edit
new file mode 100644
index 00000000..9481befc
--- /dev/null
+++ b/tools/edit_replace/bin/edit
@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+
+import argparse
+from pathlib import Path
+
+from default_utils import get_current_file, get_current_file_with_line_range, print_window # type: ignore
+
+current_file = get_current_file()
+
+parser = argparse.ArgumentParser()
+parser.add_argument("search", type=str)
+parser.add_argument("replace", type=str)
+parser.add_argument("-f", "--file", type=Path, default=Path(current_file))
+parser.add_argument("--replace-all", action="store_true")
+args = parser.parse_args()
+
+# Turn \\n into \n etc., i.e., undo the escaping
+args.replace = args.replace.encode("utf8").decode("unicode_escape")
+
+if not args.file:
+ print("No file specified. Either `open` a file first or specify a file with `-f`.")
+ exit(1)
+
+
+text = args.file.read_text()
+lines = text.splitlines()
+_, first_window_line, last_window_line = get_current_file_with_line_range(args.file)
+print(f"first_window_line: {first_window_line}, last_window_line: {last_window_line}")
+
+if not args.replace_all:
+ text_in_window = "\n".join(lines[first_window_line : last_window_line + 1])
+ new_text_in_window = text_in_window.replace(args.search, args.replace, 1)
+ if text_in_window == new_text_in_window:
+ print(
+ "No changes made. Please make sure that your search and replace strings are correct. "
+ "Note: By default, we only replace the first occurrence in the lines that are currently visible in the editor. "
+ "If you want to replace all occurrences, use the `--replace-all` flag."
+ )
+ exit(0)
+ new_text = "\n".join(lines[:first_window_line] + [new_text_in_window] + lines[last_window_line + 1 :])
+else:
+ new_text = text.replace(args.search, args.replace)
+
+args.file.write_text(new_text)
+
+# Recompute the current window, since we might have more/less lines now
+_, first_window_line, last_window_line = get_current_file_with_line_range(args.file)
+print(f"first_window_line: {first_window_line}, last_window_line: {last_window_line}")
+print_window(args.file, first_window_line, last_window_line)
diff --git a/tools/edit_replace/config.yaml b/tools/edit_replace/config.yaml
new file mode 100644
index 00000000..ac2a29e9
--- /dev/null
+++ b/tools/edit_replace/config.yaml
@@ -0,0 +1,15 @@
+tools:
+ edit:
+ signature: |
+ edit <search> <replace>
+ docstring: >
+ asdf asdf
+ arguments:
+ - name: search
+ type: string
+ description: "the text to search for"
+ required: true
+ - name: replace
+ type: string
+ description: "the text to replace the search with"
+ required: true
\ No newline at end of file
diff --git a/tools/edit_replace/install.sh b/tools/edit_replace/install.sh
new file mode 100644
index 00000000..75639deb
--- /dev/null
+++ b/tools/edit_replace/install.sh
@@ -0,0 +1,7 @@
+source /root/tools/defaults/lib/utils.sh
+
+_write_env "CURRENT_FILE" "${CURRENT_FILE:-}"
+_write_env "CURRENT_LINE" "${CURRENT_LINE:-0}"
+_write_env "WINDOW" "$WINDOW"
+
+pip install flake8