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 more options to trajectory formatter

Kilian Lieretadd6b9f375ec
diff --git a/config/default_retry_traj1_modes.yaml b/config/default_retry_traj1_modes.yaml
new file mode 100644
index 00000000..dbfd7908
--- /dev/null
+++ b/config/default_retry_traj1_modes.yaml
@@ -0,0 +1,185 @@
+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.
+
+ COMMANDS:
+ {command_docs}
+
+ 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> $
+
+ You need to format your output using two fields; discussion and command.
+ Your output should always include _one_ discussion and _one_ command field EXACTLY as in the following example:
+ DISCUSSION
+ First I'll start by using ls to see what files are in the current directory. Then maybe we can look at some relevant files to see what they look like.
+ ```
+ ls -a
+ ```
+
+ 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:
+ {issue}
+
+ 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 ---
+state_command:
+ name: state
+ code: |
+ state() {
+ local working_dir="$PWD";
+ if [ -z $CURRENT_FILE ]; then
+ echo '{"open_file": "n/a", "working_dir": "'$working_dir'"}';
+ else
+ echo '{"open_file": "'$(realpath $CURRENT_FILE)'", "working_dir": "'$working_dir'"}';
+ fi
+ };
+parse_function: ThoughtActionParser
+env_variables:
+ WINDOW: 100
+ OVERLAP: 2
+ CURRENT_LINE: 0
+ CURRENT_FILE: ''
+ SEARCH_RESULTS: ()
+ SEARCH_FILES: ()
+ SEARCH_INDEX: 0
+command_files:
+- config/commands/defaults.sh
+- config/commands/search.sh
+- config/commands/edit_linting.sh
+- config/commands/_split_string.py
+parse_command: ParseCommandDetailed
+history_processor: Last5Observations
+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
+review_loop_config:
+ review_loop_classname: ReviewLoop
+ reviewer_classname: Reviewer
+ reviewer_config:
+ system_template: |
+ You are an expert at checking pull requests and changes to code.
+
+ You are provided the following:
+
+ INPUT 1. The problem statement.
+ INPUT 2. The history of how someone tried to solve the problem and the final changes.
+ The history is structured as a series of actions, where each action is a description of a
+ motivation ("Step {i}: ") followed by a command in triple-backticks.
+ After the command, there is a description of the output of the command ("Output {i}: ").
+ The most important actions are
+ `open {file}`: This action opens the file {file}. The output of the command shows part of the content of the file.
+ `edit {from}:{to}`, followed by the content to replace lines {from} to {to}. This action always affects the currently
+ opened file. The output of the command is the content of the file after the edit.
+ `python {file}`: This action executes the Python script {file}. The output of the command is the output of the script.
+
+ Analyze the code provided in the pull request and determine if it correctly and efficiently solves the problem as stated in the problem statement.
+ Evaluate the history to assess if the iterative process and decision-making are logically sound and lead to the solution effectively.
+
+ Here is how you should proceed in the evaluation:
+
+ 1. Failed to Reproduce: If the history includes attempts to reproduce the problem statement (by creating `reproduce.py`) but does not
+ manage to reproduce the problem, you should answer "FAIL (failed to reproduce)".
+ 2. Did not attempt to reproduce: If the history does not include attempts to reproduce the problem statement, you should answer "FAIL (did not reproduce)".
+ 3. Failed to understand problem statement: If the problem was reproduced, but the reproduction does not match the problem statement,
+ you should answer "FAIL (did not understand problem)".
+ 4. Failed to fix reproduction script: If the problem was reproduced, but the edits do not fix the problem, you should answer "FAIL (failed to fix)".
+ 5. Overly Specific Implementation: If the problem might be fixed but the changes are likely to introduce other issues, for example by
+ breaking exiting functionality, removing important checks, or similar, you should answer "FAIL (overly specific)".
+ 6. If None of the above applies and you are sure that the code snippet is correct, you should answer "SUCCESS".
+
+ Note: This is a pull request generated by an automated system. The absence of any additional new unit tests,
+ or any testing steps that do not relate to the reproduction script or the original error is **not**
+ a reason to fail the pull request. The focus should be on the code changes and the iterative process that led to them.
+
+ THE LAST LINE OF YOUR REPLY MUST CONTAIN EITHER "SUCCESS" OR "FAIL (failure mode)" TO INDICATE IF THE CODE SNIPPET IS CORRECT OR NOT.
+ You can add multiple failure modes, for example "FAIL (failed to reproduce, overly specific)".
+
+ Demonstration of your reply:
+
+ The history shows a commendable attempt to reproduce the described problem, adjust the code, and validate changes. However, issues arose along the way, and the final execution of the reproduction script still resulted in an error related to imports. The process struggled with circular imports that ultimately were not resolved within the provided environment. Despite applying logic to avoid the `TypeError`, the circular import problem obstructed proper validation of the fix.
+
+ **Final Assessment:**
+
+ While the initial steps and intentions were correct and there was a clear strategy to reproduce the problem and fix it, the issue with the circular imports indicates an unresolved problem with the Python environment setup or test execution methodology which prevents the successful execution of the test script. Such environmental issues could lead to unresolved or undetected issues in real-world applications.
+
+ **Conclusion:**
+ FAIL (failed to fix reproduction script)
+ instance_template: |
+ INPUT 1. The problem statement
+
+ {issue}
+
+ INPUT 2. The history of how the machine learning model tried to solve the problem.
+
+ {traj}
+ traj_output_filter:
+ - goto
+ - find
+ - find_file
+ - search_file
+ - search_dir
+ - rm
+ - scroll_up
+ - scroll_down
+ - open
+ - grep
+ - ls
+ - cat
+ - mv
+ filter_failed_edits: True
+ max_samples: 10
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index 1f3b8357..b86f3e99 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -4,6 +4,7 @@ solving the issue and to select the best solution.
from __future__ import annotations
+import copy
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Literal
@@ -128,8 +129,11 @@ class ReviewerConfig(FrozenSerializable):
reject_exit_cost: bool = True
#: Filter the following actions from the trajectory
traj_filter: list[str] = field(default_factory=list)
+ #: Filter outputs from the following actions from the trajectory
+ traj_output_filter: list[str] = field(default_factory=list)
#: Format of the trajectory item
traj_item_template: str = "Model: {response}\n\nObservation: {observation}"
+ filter_failed_edits: bool = False
@dataclass(frozen=True)
@@ -183,6 +187,8 @@ class Reviewer(AbstractReviewer):
self._traj_formatter = TrajectoryFormatter(
traj_filter=config.traj_filter,
traj_item_template=config.traj_item_template,
+ traj_output_filter=config.traj_output_filter,
+ filter_failed_edits=config.filter_failed_edits,
)
def format_messages(self, instance: INSTANCE_TYPE, submission: ReviewSubmission):
@@ -230,21 +236,38 @@ class Reviewer(AbstractReviewer):
class TrajectoryFormatter:
def __init__(
self,
+ *,
traj_filter: list[str] | None = None,
+ traj_output_filter: list[str] | None = None,
traj_item_template: str = "Model: {response}\n\nObservation: {observation}",
+ filter_failed_edits: bool = False,
):
"""Formats trajectories for the use in prompts"""
self._traj_filter = traj_filter or []
+ self._traj_output_filter = traj_output_filter or []
self._traj_item_template = traj_item_template
+ self._filter_failed_edits = filter_failed_edits
- def _include_trajectory_step(self, item: TrajectoryStep) -> bool:
+ def _include_step(self, item: TrajectoryStep) -> bool:
action = item["action"].strip()
for f in self._traj_filter:
if action.startswith(f):
return False
+ if self._filter_failed_edits and "Your proposed edit has introduced new syntax error(s)" in item["observation"]:
+ return False
+ return True
+
+ def _include_step_output(self, item: TrajectoryStep) -> bool:
+ action = item["action"].strip()
+ for f in self._traj_output_filter:
+ if action.startswith(f):
+ return False
return True
def _format_trajectory_step(self, step: TrajectoryStep, i_step: int, i_traj: int = 1) -> str:
+ step = copy.deepcopy(step)
+ if not self._include_step_output(step):
+ step["observation"] = "[Output omitted]"
return self._traj_item_template.format(
**step,
i_step=i_step,
@@ -252,7 +275,7 @@ class TrajectoryFormatter:
)
def format_trajectory(self, trajectory: Trajectory, i_traj: int = 1) -> str:
- traj_messages = [step for step in trajectory if self._include_trajectory_step(step)]
+ traj_messages = [step for step in trajectory if self._include_step(step)]
return "\n\n".join(
[self._format_trajectory_step(step, i_step, i_traj=i_traj) for i_step, step in enumerate(traj_messages)]
)
diff --git a/tests/test_reviewer.py b/tests/test_reviewer.py
index 30b60ee0..e7a8e833 100644
--- a/tests/test_reviewer.py
+++ b/tests/test_reviewer.py
@@ -157,7 +157,7 @@ def test_loop_comparison_quit_after_max_accepted(dummy_reviewer_config, dummy_bi
def test_loop_comparison_quit_after_accept(dummy_reviewer_config, dummy_binary_reviewer_config):
rmodel = DeterminedModel(["fail", "fail", "success"])
- # Only have one comparison: The two successes
+ # Only have one comparison: The two fails
bmodel = DeterminedModel(["second"])
lconfig = ReviewLoopConfig(
review_loop_classname="ReviewLoop",