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]
Strip trailing whitespace & black formatting
Kilian Lieret70ba97190a78
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex d3d6b0fd..0941cca7 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -24,7 +24,7 @@ body:Enclose code/commands/log output in [triple backticks](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#quoting-code).placeholder: |```- Sample code/commands to reproduce the problem.+ Sample code/commands to reproduce the problem.Enclose code in triple backticks.```validations:diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 662ac1e5..30c444cd 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -12,6 +12,7 @@ repos:- id: mixed-line-ending- id: detect-private-key- id: check-ast+ - id: trailing-whitespace- repo: https://github.com/crate-ci/typosrev: v1.21.0@@ -23,12 +24,12 @@ repos:exclude: pyproject.toml- repo: https://github.com/astral-sh/ruff-pre-commit- rev: v0.4.5+ rev: v0.4.4hooks:# Run the linter.- id: ruff# Run the formatter.- # - id: ruff-format+ - id: ruff-format- repo: https://github.com/pre-commit/mirrors-prettierrev: "v4.0.0-alpha.8" # Use the sha or tag you want to point atdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a52158f0..897eacf0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,7 @@ We’re excited to launch the SWE-agent web UI! Specify a bug, press start and w* Add GPT4-turbo model by @zgrannan in https://github.com/princeton-nlp/SWE-agent/pull/252* feat: Amazon Bedrock support (Claude models) by @JGalego in https://github.com/princeton-nlp/SWE-agent/pull/207-### Fixed+### Fixed* Better error handling for --open_pr by @klieret in https://github.com/princeton-nlp/SWE-agent/pull/239* Fixed a potential error by @DanjieTang in https://github.com/princeton-nlp/SWE-agent/pull/242diff --git a/README.md b/README.mdindex 7d3e7fd5..bead9d6f 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@ On [SWE-bench](https://github.com/princeton-nlp/SWE-bench), SWE-agent resolves *We accomplish our results by designing simple LM-centric commands and feedback formats to make it easier for the LM to browse the repository, view, edit and execute code files. We call this an 🤖 **Agent-Computer Interface (ACI)**.Read more about it in our [paper](https://swe-agent.com/paper.pdf)!-SWE-agent is built and maintained by researchers from Princeton University.+SWE-agent is built and maintained by researchers from Princeton University.<p align="center"><img src="assets/results+preview.png" style="width: 80%; height: auto;">@@ -30,7 +30,7 @@ SWE-agent is built and maintained by researchers from Princeton University.If you found this work helpful, please consider using the following citation:```@misc{yang2024sweagent,- title={SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering},+ title={SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering},author={John Yang and Carlos E. Jimenez and Alexander Wettig and Kilian Lieret and Shunyu Yao and Karthik Narasimhan and Ofir Press},year={2024},}diff --git a/config/commands/_split_string.py b/config/commands/_split_string.pyindex 3ceccc15..c821be25 100644--- a/config/commands/_split_string.py+++ b/config/commands/_split_string.py@@ -1,6 +1,7 @@#!/usr/bin/env python3import sys+def print_flake8_output(input_string, show_line_numbers=False):for value in input_string.split("\n"):parts = value.split()@@ -10,6 +11,7 @@ def print_flake8_output(input_string, show_line_numbers=False):line_nums = ":".join(parts[0].split(":")[1:])print(f"- {line_nums} {' '.join(parts[1:])}")+if __name__ == "__main__":lint_output = sys.argv[1]print_flake8_output(lint_output)diff --git a/config/commands/cursors_edit_linting.sh b/config/commands/cursors_edit_linting.shindex 9ec9421c..b4249eb0 100644--- a/config/commands/cursors_edit_linting.sh+++ b/config/commands/cursors_edit_linting.sh@@ -91,7 +91,7 @@ edit() {export CURRENT_LINE=$original_current_lineexport WINDOW=$original_windowexport END_CURSOR=$original_end_cursor-+echo "Your changes have NOT been applied. Please fix your edit command and try again."echo "You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code."echo "DO NOT re-run the same failed edit command. Running it again will lead to the same error."diff --git a/config/commands/edit_linting.sh b/config/commands/edit_linting.shindex dcb0b0c1..e7547611 100644--- a/config/commands/edit_linting.sh+++ b/config/commands/edit_linting.sh@@ -66,7 +66,7 @@ edit() {local new_lines=("${lines[@]:0:$start_line}" "${replacement[@]}" "${lines[@]:$((end_line))}")# Write the new stuff directly back into the original fileprintf "%s\n" "${new_lines[@]}" >| "$CURRENT_FILE"-+# Run linterif [[ $CURRENT_FILE == *.py ]]; thenlint_output=$(flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902 "$CURRENT_FILE" 2>&1)diff --git a/config/commands/search.sh b/config/commands/search.shindex b6a2fc89..c09566bd 100644--- a/config/commands/search.sh+++ b/config/commands/search.sh@@ -42,7 +42,7 @@ search_dir() {echo "More than $num_files files matched for \"$search_term\" in $dir. Please narrow your search."returnfi-+echo "Found $num_matches matches for \"$search_term\" in $dir:"echo "$matches" | awk '{$2=$2; gsub(/^\.+\/+/, "./", $2); print $2 " ("$1" matches)"}'echo "End of matches for \"$search_term\" in $dir"@@ -95,7 +95,7 @@ search_file() {fi# Calculate total number of matcheslocal num_matches=$(echo "$matches" | wc -l | awk '{$1=$1; print $0}')-+# calculate total number of lines matchedlocal num_lines=$(echo "$matches" | cut -d: -f1 | sort | uniq | wc -l | awk '{$1=$1; print $0}')# if num_lines is > 100, print an errordiff --git a/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml b/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yamlindex e8056836..549f4aab 100644--- a/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml+++ b/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml@@ -1,4 +1,4 @@-#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.+#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.system_template: |-SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.@@ -8,7 +8,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -24,7 +24,7 @@ system_template: |-```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.+ 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: |-@@ -33,32 +33,32 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml b/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yamlindex 45a97310..72537d68 100644--- a/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml+++ b/config/configs/default_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml@@ -1,4 +1,4 @@-#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.+#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.system_template: |-SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.@@ -8,7 +8,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -24,7 +24,7 @@ system_template: |-```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.+ 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: |-@@ -33,32 +33,32 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/default_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml b/config/configs/default_sys-env_window100-detailed_cmd_format-full_history-1_demos.yamlindex b87130f1..33a2edc1 100644--- a/config/configs/default_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml+++ b/config/configs/default_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-```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.+ 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: |-@@ -32,32 +32,32 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/default_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml b/config/configs/default_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yamlindex cbba9306..7954b2a1 100644--- a/config/configs/default_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml+++ b/config/configs/default_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-```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.+ 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: |-@@ -32,32 +32,32 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml b/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yamlindex c91aa570..fe094f0c 100644--- a/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml+++ b/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-full_history-1_demos.yaml@@ -1,4 +1,4 @@-#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.+#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.system_template: |-SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.@@ -8,7 +8,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -24,7 +24,7 @@ system_template: |-</command>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.+ 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: |-@@ -33,32 +33,32 @@ instance_template: |-{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.+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml b/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yamlindex 932aa766..9f96e1a7 100644--- a/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml+++ b/config/configs/xml_sys-env_cursors_window100-detailed_cmd_format-last_5_history-1_demos.yaml@@ -1,4 +1,4 @@-#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.+#THIS CONFIG IS EXPERIMENTAL. WE DID NOT USE IT AT ALL FOR THE RESULTS IN THE PAPER. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.system_template: |-SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.@@ -8,7 +8,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -24,7 +24,7 @@ system_template: |-</command>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.+ 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: |-@@ -33,32 +33,32 @@ instance_template: |-{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.+ 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.+ 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.+ 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.-+ 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})diff --git a/config/configs/xml_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml b/config/configs/xml_sys-env_window100-detailed_cmd_format-full_history-1_demos.yamlindex bb76de59..dc4178de 100644--- a/config/configs/xml_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml+++ b/config/configs/xml_sys-env_window100-detailed_cmd_format-full_history-1_demos.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-</command>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.+ 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: |-@@ -32,32 +32,32 @@ instance_template: |-{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.+ 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.+ 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.+ 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.+ 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})diff --git a/config/configs/xml_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml b/config/configs/xml_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yamlindex 64c6416a..2c5d5b48 100644--- a/config/configs/xml_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml+++ b/config/configs/xml_sys-env_window100-detailed_cmd_format-last_5_history-1_demos.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-</command>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.+ 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: |-@@ -32,32 +32,32 @@ instance_template: |-{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.+ 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.+ 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.+ 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.+ 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})diff --git a/config/default.yaml b/config/default.yamlindex 09c71ed6..7954b2a1 100644--- a/config/default.yaml+++ b/config/default.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-```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.+ 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: |-@@ -32,32 +32,32 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.+ 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})diff --git a/config/default_from_url.yaml b/config/default_from_url.yamlindex ba80745e..90e47360 100644--- a/config/default_from_url.yaml+++ b/config/default_from_url.yaml@@ -7,7 +7,7 @@ system_template: |-COMMANDS:{command_docs}- Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ 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:@@ -23,7 +23,7 @@ system_template: |-```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.+ 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: |-@@ -32,26 +32,26 @@ instance_template: |-{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.+ 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!+ 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.+ 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.+ 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.-+ 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.@@ -59,7 +59,7 @@ instance_template: |-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.7. It may be necessary to install the repository from source before you can run code. Please think about how to install the environment from the repository directory if you need to do so.-+(Open file: {open_file})(Current directory: {working_dir})diff --git a/docs/config/commands.md b/docs/config/commands.mdindex bba7a0a7..b57890fe 100644--- a/docs/config/commands.md+++ b/docs/config/commands.md@@ -1,6 +1,6 @@# Command ConfigurationIn this document, we describe how to implement your own commands for the SWE-agent ACI.-To see examples of command implementations, open the `.sh` and `.py` files in the+To see examples of command implementations, open the `.sh` and `.py` files in the[`config/commands`](https://github.com/princeton-nlp/SWE-agent/tree/main/config/commands) folder.## Scaffoldingdiff --git a/docs/config/config.md b/docs/config/config.mdindex f921d9e8..1a02d720 100644--- a/docs/config/config.md+++ b/docs/config/config.md@@ -30,7 +30,7 @@ format_error_template: |-demonstration_template: |Format template for showing a demonstration to the agentdemonstrations:-- `trajectories/<username>/<experiment folder>/*.traj`+- `trajectories/<username>/<experiment folder>/*.traj`- File is a demonstration of how to solve a task. This could an agent generated trajectory.- You can include 1+ demonstrations@@ -82,7 +82,7 @@ Possible variables that can be used in templates are:- `{command_docs}` (an automatically compiled collection of available commands + their docstrings)- any variable given in `env_variables` (same spelling), e.g., `{WINDOW_SIZE}`- any variable extracted as json as part of the `state_command` function-- the last observation `{observation}`+- the last observation `{observation}`- ... this list will grow as we implement more features!## Template Workflowdiff --git a/docs/config/demonstrations.md b/docs/config/demonstrations.mdindex 5a652f88..b054079b 100644--- a/docs/config/demonstrations.md+++ b/docs/config/demonstrations.md@@ -24,7 +24,7 @@ You can also manually generate a trajectory by running the agent with `--model_nTo edit text in `human` mode:1. Run the command `edit edit_start_line:edit_end_line`-2. Write the text you want to insert. Feel free to write the text across multiple lines.+2. Write the text you want to insert. Feel free to write the text across multiple lines.3. Press `return` then write `end_of_edit` and then press `return` again to submit the edit.{% include-markdown "../_footer.md" %}\ No newline at end of filediff --git a/docs/dev/contribute.md b/docs/dev/contribute.mdindex 62442840..d389436d 100644--- a/docs/dev/contribute.md+++ b/docs/dev/contribute.md@@ -23,7 +23,7 @@ Then, make sure to set up [`pre-commit`](https://pre-commit.com):pre-commit install```-`pre-commit` will check for formatting and basic syntax errors before your commits.+`pre-commit` will check for formatting and basic syntax errors before your commits.Some issues can be automatically fixed with [`ruff`](https://github.com/charliermarsh/ruff) (part of the checks):diff --git a/docs/index.md b/docs/index.mdindex c2d1a22e..41f970b1 100644--- a/docs/index.md+++ b/docs/index.md@@ -9,7 +9,7 @@ On [SWE-bench](https://github.com/princeton-nlp/SWE-bench), SWE-agent resolves *We accomplish our results by designing simple LM-centric commands and feedback formats to make it easier for the LM to browse the repository, view, edit and execute code files. We call this an 🤖 **Agent-Computer Interface (ACI)**.Read more about it in our [paper](https://swe-agent.com/paper.pdf)!-SWE-agent is built and maintained by researchers from Princeton University.+SWE-agent is built and maintained by researchers from Princeton University.<p align="center"><img src="assets/readme_assets/results+preview.png" style="width: 80%; height: auto;">@@ -19,7 +19,7 @@ If you found this work helpful, please consider using the following citation:```@misc{yang2024sweagent,- title={SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering},+ title={SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering},author={John Yang and Carlos E. Jimenez and Alexander Wettig and Kilian Lieret and Shunyu Yao and Karthik Narasimhan and Ofir Press},year={2024},}diff --git a/docs/installation/docker.md b/docs/installation/docker.mdindex 5f088c49..e3435334 100644--- a/docs/installation/docker.md+++ b/docs/installation/docker.md@@ -6,7 +6,7 @@in docker.We generally recommend [installing from source](source.md).-Instead of installing SWE-agent from source, you can also run the software directly using Docker.+Instead of installing SWE-agent from source, you can also run the software directly using Docker.1. [Install Docker](https://docs.docker.com/engine/install/), then start Docker locally.2. Run `docker pull sweagent/swe-agent:latest`@@ -53,12 +53,12 @@ To run the web server, make sure to forward port 3000:```bashdocker run -p 3000:3000 -it -v /var/run/docker.sock:/var/run/docker.sock \- -v $(pwd)/keys.cfg:/app/keys.cfg \- sweagent/swe-agent-run:latest bash start_web_ui.sh+ -v $(pwd)/keys.cfg:/app/keys.cfg \+ sweagent/swe-agent-run:latest bash start_web_ui.sh```!!! tip "More tips"See the [installation issues section](tips.md) for more help if you run intotrouble.-+{% include-markdown "../_footer.md" %}\ No newline at end of filediff --git a/docs/installation/index.md b/docs/installation/index.mdindex 60219bb8..89c80368 100644--- a/docs/installation/index.md+++ b/docs/installation/index.md@@ -4,24 +4,24 @@- :material-github:{ .lg .middle } __All in browser__- ---+ ---++ Run SWE-agent using GitHub codespaces. All necessary packages will be pre-installedn in an in-browser VSCode environment.- Run SWE-agent using GitHub codespaces. All necessary packages will be pre-installedn in an in-browser VSCode environment.-[:octicons-arrow-right-24: Get started](codespaces.md)- :material-cog:{ .lg .middle } __Install from source__- ---+ ---++ Install SWE-agent from source using `pip`.- Install SWE-agent from source using `pip`.-[:octicons-arrow-right-24: Get started](source.md)- :material-docker:{ .lg .middle } __Run in docker__- ---+ ---Pull a docker container and directly run SWE-agent. This is our fallback solution if the local installation does not work for you.diff --git a/docs/usage/benchmarking.md b/docs/usage/benchmarking.mdindex 14738f67..a55dbc25 100644--- a/docs/usage/benchmarking.md+++ b/docs/usage/benchmarking.md@@ -1,6 +1,6 @@# Benchmarking-There are two steps to the SWE-agent pipeline. First SWE-agent takes an input GitHub issue and returns a pull request that attempts to fix it. We call that step *inference*. The second step (currently, only available for issues in the SWE-bench benchmark) is to *evaluate* the pull request to verify that it has indeed fixed the issue.+There are two steps to the SWE-agent pipeline. First SWE-agent takes an input GitHub issue and returns a pull request that attempts to fix it. We call that step *inference*. The second step (currently, only available for issues in the SWE-bench benchmark) is to *evaluate* the pull request to verify that it has indeed fixed the issue.!!! warning "Architectures"At this moment, there are known issues with a small number of repositories that don't install properly for `arm64` / `aarch64` architecture computers. We're working on a fix, but if you'd like to run and evaluate on the entirety of SWE-bench, the easiest way is by using an `x86` machine.@@ -32,7 +32,7 @@ You can run evaluations on SWE-bench by passing in the predictions generated by./run_eval.sh <path to predictions>```-The `<predictions_path>` arguments should look like+The `<predictions_path>` arguments should look like```../trajectories/<username>/<model>-<dataset>-<hyperparams>/all_preds.jsonldiff --git a/docs/usage/cl_tutorial.md b/docs/usage/cl_tutorial.mdindex 01893f45..e59ecb0d 100644--- a/docs/usage/cl_tutorial.md+++ b/docs/usage/cl_tutorial.md@@ -15,10 +15,10 @@ python run.py \--model_name gpt4 \--data_path https://github.com/SWE-agent/test-repo/issues/1 \--config_file config/default_from_url.yaml \- --per_instance_cost_limit 2.00+ --per_instance_cost_limit 2.00```-Here,+Here,* `--model_name` sets the language model that is used by SWE-agent (with `gpt4` being the default). More information on the available models in our [FAQ](faq.md)* `--data_path` points to the source of the *problem statement* (for example, the GitHub issue that you want to solve). You can also point it to local files (see [below](#specifying-the-repository))@@ -38,8 +38,8 @@ Here,## Specifying the repository-In the above example, the repository/codebase is inferred from the `--data_path`.-This options is currently only available for GitHub issues.+In the above example, the repository/codebase is inferred from the `--data_path`.+This options is currently only available for GitHub issues.For all other use cases, you can specify `--repo_path`, which accepts either GitHubURLs or paths to local repositories.@@ -82,7 +82,7 @@ SWE-agent will then start from this commit when trying to solve the problem.## Installing dependencies and setting up the environment-Now let's move on to a slightly more complicated issue ([`swe-agent/test-repo #22`](https://github.com/SWE-agent/test-repo/issues/22)).+Now let's move on to a slightly more complicated issue ([`swe-agent/test-repo #22`](https://github.com/SWE-agent/test-repo/issues/22)).What makes it more complicated? This time the problematic code is part of a library `testpkg`, so SWE-agent first has to install the package in order to reproduce the issue before searching for the problematic code.@@ -116,10 +116,10 @@ The config file also provides two more top level directives:## Taking actions* As mentioned [above](#specifying-the-repository), you can use `--apply_patch_locally` to have SWE-agent apply successful solution attempts to local files.-* Alternatively, when running on a GitHub issue, you can have the agent automatically open a PR if the issue has been solved by supplying the `--open_pr` flag.+* Alternatively, when running on a GitHub issue, you can have the agent automatically open a PR if the issue has been solved by supplying the `--open_pr` flag.Please use this feature responsibly (on your own repositories or after careful consideration).-Alternatively, you can always retrieve the patch that was generated by SWE-agent.+Alternatively, you can always retrieve the patch that was generated by SWE-agent.Watch out for the followoing message in the log:diff --git a/docs/usage/faq.md b/docs/usage/faq.mdindex ec256d90..6b29c0f6 100644--- a/docs/usage/faq.md+++ b/docs/usage/faq.md@@ -30,9 +30,9 @@ python run.py --model_name ollama:deepseek-coder:6.7b-instruct \### Models for testingWe also provide models for testing SWE-agent without spending any credits-+* `HumanModel` and `HumandThoughtModel` will prompt for input from the user that stands in for the output of the LM. This can be used to create new [demonstrations](../config/demonstrations.md#manual).* `ReplayModel` takes a trajectory as input and "replays it"-* `InstantEmptySubmitTestModel` will create an empty `reproduce.py` and then submit+* `InstantEmptySubmitTestModel` will create an empty `reproduce.py` and then submit{% include-markdown "../_footer.md" %}\ No newline at end of filediff --git a/docs/usage/index.md b/docs/usage/index.mdindex e76e9d0f..94f26bf3 100644--- a/docs/usage/index.md+++ b/docs/usage/index.md@@ -1,23 +1,23 @@# Usage-We currently provide two interfaces to SWE-agent:+We currently provide two interfaces to SWE-agent:<div class="grid cards" markdown>- :material-keyboard:{ .lg .middle } __Command line interface (CLI)__- ---+ ---The default way of running SWE-agent with maximum options.-+[:octicons-arrow-right-24: Get started](cl_tutorial.md)- :material-mouse:{ .lg .middle } __Graphical user interface__- ---+ ---We provide a browser-based graphical user interface particularly optimized for developers wanting to use SWE-agent as a tool.-+[:octicons-arrow-right-24: Get started](web_ui.md)</div>\ No newline at end of filediff --git a/docs/usage/trajectories.md b/docs/usage/trajectories.mdindex fec235ee..7de64b49 100644--- a/docs/usage/trajectories.md+++ b/docs/usage/trajectories.md@@ -44,7 +44,7 @@ Each call to `run.py` produces a single `trajectories/<user name>/<experiment na* `<instance_id>.traj`: A `.json` formatted file containing the (thought, action, observation) turns generated by SWE-agent towards solving `<instance_id>`.* `<instance_id>.html`: An `.html` single webpage render of the trajectory, which can be directly opened in the browser for easier viewing of the trajectory.-!!! tip+!!! tip* Evaluation is not completed by `run.py`, it is a separate step (see [benchmarking](benchmarking.md))* `all_preds.jsonl` can be referenced directly into `evaluation/run_eval.sh` to run evaluation (see [benchmarking](benchmarking.md))* Trajectories can be turned into custom demonstrations for SWE-agent ([more information](../config/demonstrations.md)).diff --git a/docs/usage/web_ui.md b/docs/usage/web_ui.mdindex a13b7e4d..fcaeacf2 100644--- a/docs/usage/web_ui.md+++ b/docs/usage/web_ui.md@@ -1,6 +1,6 @@# Using the web interface-Our graphical web interface is optimized for using SWE-agent as a developer tool, fixing single GitHub issues or working in local repositories.+Our graphical web interface is optimized for using SWE-agent as a developer tool, fixing single GitHub issues or working in local repositories.However, it is still missing some of the options of the [command line interface](cl_tutorial.md).## Quickstart@@ -14,7 +14,7 @@ To start our web UI, simply runfrom the root of the repository.!!! tip "Opening the webpage"- If the user interface doesn't automatically open in your browser, please open it at `http://localhost:3000`.+ If the user interface doesn't automatically open in your browser, please open it at `http://localhost:3000`.Running from GitHub codespaces? More tips [here](../installation/codespaces.md#running-the-web-ui).!!! note "Running from Docker"@@ -23,7 +23,7 @@ from the root of the repository.## Manually starting frontend and backend-The web UI consists of a frontend written in [react][] (showing the pretty control elements) and a backend written with [flask][].+The web UI consists of a frontend written in [react][] (showing the pretty control elements) and a backend written with [flask][].The `./start_web_ui.sh` starts both of them in the background.However, this might not be best for development and debugging.This section explains how to start both parts separately.@@ -51,9 +51,9 @@ You should see output similar to the following:```!!! tip "Port availability"- If see an error about port 8000 not being available,- please first close any application that occupies it.- The frontend currently expects the `flask` server on port 8000, so choosing+ If see an error about port 8000 not being available,+ please first close any application that occupies it.+ The frontend currently expects the `flask` server on port 8000, so choosinga different port won't work.Now, open a new terminal tab and navigate to the `frontend` directory:@@ -74,8 +74,8 @@ And start the server:npm start```-This should also open the corresponding page in your browser.-If not, check with the tips above.+This should also open the corresponding page in your browser.+If not, check with the tips above.The default port that is being served is port 3000.!!! tip "Possible errors"diff --git a/evaluation/aggregate_results.py b/evaluation/aggregate_results.pyindex dc94d8d3..8776538e 100644--- a/evaluation/aggregate_results.py+++ b/evaluation/aggregate_results.py@@ -5,6 +5,7 @@ import numpy as npimport osimport pandas as pdimport warnings+warnings.filterwarnings("ignore")from pathlib import Path@@ -79,16 +80,16 @@ def convert_experiments_to_rows(folder_name, runs_max):if len(folder_data) != 8:# TODO: This might be too strict?continue- temperature = float(folder_data[3][len("t-"):].strip())- top_p = float(folder_data[4][len("p-"):].strip())- cost = float(folder_data[5][len("c-"):].strip())+ temperature = float(folder_data[3][len("t-") :].strip())+ top_p = float(folder_data[4][len("p-") :].strip())+ cost = float(folder_data[5][len("c-") :].strip())install = "Y" if folder_data[6].strip() == "install-1" else "N"# Parse out run numberrun = folder_data[-1]if "run" not in run:continue-+try:if "run-" in run:run = int(run.split("run-")[-1].split("-")[0].replace("_", "").strip())@@ -97,7 +98,7 @@ def convert_experiments_to_rows(folder_name, runs_max):except Exception as e:print(run)raise e-+if runs_max is not None and run > runs_max:continue@@ -112,7 +113,7 @@ def convert_experiments_to_rows(folder_name, runs_max):resolved_ids = results_data["resolved"]elif "counts" in results_data and isinstance(results_data["counts"]["resolved"], list):resolved_ids = results_data["counts"]["resolved"]-+# Extract instance costs from trajectoriescosts_overall = []costs_success = []@@ -156,10 +157,7 @@ def convert_experiments_to_rows(folder_name, runs_max):def get_results_df(folder_name, runs_max):rows = convert_experiments_to_rows(folder_name, runs_max)- return (- pd.DataFrame(rows, columns=COLUMNS)- .sort_values(by=COLUMNS[:8])- )+ return pd.DataFrame(rows, columns=COLUMNS).sort_values(by=COLUMNS[:8])def get_results_csv(folder_name):@@ -170,9 +168,9 @@ def get_results_csv(folder_name):if __name__ == "__main__":parser = argparse.ArgumentParser(description="Aggregate results from experiments")parser.add_argument("--folder", type=str, help="Folder containing experiment results", default="../trajectories")- parser.add_argument("--model", nargs='+', type=str, help="Model(s) to filter results by.")- parser.add_argument("--dataset", nargs='+', type=str, help="Dataset to filter results by.")- parser.add_argument("--setup", nargs='+', type=str, help="Setup to filter results by.")+ parser.add_argument("--model", nargs="+", type=str, help="Model(s) to filter results by.")+ parser.add_argument("--dataset", nargs="+", type=str, help="Dataset to filter results by.")+ parser.add_argument("--setup", nargs="+", type=str, help="Setup to filter results by.")parser.add_argument("--runs_min", type=int, help="Minimum number of runs that experiment should have been run for.")parser.add_argument("--runs_max", type=int, help="Maximum number of runs taken into account")args = parser.parse_args()@@ -201,19 +199,19 @@ if __name__ == "__main__":# Filteringif args.model:- grouped_data = grouped_data[grouped_data['Model'].isin(args.model)]+ grouped_data = grouped_data[grouped_data["Model"].isin(args.model)]if args.dataset:- grouped_data = grouped_data[grouped_data['Dataset'].isin(args.dataset)]+ grouped_data = grouped_data[grouped_data["Dataset"].isin(args.dataset)]if args.setup:- grouped_data = grouped_data[grouped_data['Setup'].isin(args.setup)]+ grouped_data = grouped_data[grouped_data["Setup"].isin(args.setup)]if args.runs_min:- grouped_data = grouped_data[grouped_data['Run'] >= args.runs_min]+ grouped_data = grouped_data[grouped_data["Run"] >= args.runs_min]print(f"Total experiments run: {grouped_data.shape[0]}")- grouped_data_sorted = grouped_data.sort_values(by=['Dataset', 'Resolved'], ascending=[True, False])+ grouped_data_sorted = grouped_data.sort_values(by=["Dataset", "Resolved"], ascending=[True, False])pd.set_option("display.max_rows", None)- grouped = grouped_data_sorted.groupby('Dataset')+ grouped = grouped_data_sorted.groupby("Dataset")for name, group in grouped:- print(f'\n-----------------\nDataset: {name}\n-----------------')+ print(f"\n-----------------\nDataset: {name}\n-----------------")print(group.to_string(index=False))diff --git a/evaluation/evaluation.py b/evaluation/evaluation.pyindex 049d5801..10037a64 100644--- a/evaluation/evaluation.py+++ b/evaluation/evaluation.py@@ -22,7 +22,18 @@ from swebench.harness.constants import (from unidiff import PatchSet-def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, timeout, verbose, conda_link, log_suffix, num_processes):+def main(+ predictions_path,+ log_dir,+ swe_bench_tasks,+ testbed,+ skip_existing,+ timeout,+ verbose,+ conda_link,+ log_suffix,+ num_processes,+):# Check if paths existif not os.path.exists(predictions_path):raise FileNotFoundError(f"Predictions path {predictions_path} does not exist")@@ -65,7 +76,7 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, timverbose=verbose,conda_link=conda_link,log_suffix=log_suffix,- num_processes=num_processes+ num_processes=num_processes,)print("✅ Finished evaluation")except Exception as e:@@ -98,11 +109,7 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, tim]))- scorecard["exit_status"] = (- traj_data["info"]["exit_status"]- if "exit_status" in traj_data["info"]- else "n/a"- )+ scorecard["exit_status"] = traj_data["info"]["exit_status"] if "exit_status" in traj_data["info"] else "n/a"# Check that a prediction was generatedif p[KEY_PREDICTION] is None or p[KEY_PREDICTION].strip() == "":@@ -112,9 +119,7 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, timscorecard["statuses"].append("generated")# Get log file- log_path = os.path.join(- log_dir, f"{p[KEY_INSTANCE_ID]}.{directory_name}.eval.log"- )+ log_path = os.path.join(log_dir, f"{p[KEY_INSTANCE_ID]}.{directory_name}.eval.log")if not os.path.exists(log_path):scorecard["statuses"].append("build_failure")scorecards.append(scorecard)@@ -144,7 +149,7 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, tim"success": {"FAIL_TO_PASS": report["FAIL_TO_PASS"]["success"],"PASS_TO_PASS": report["PASS_TO_PASS"]["success"],- }+ },}resolution_status = get_resolution_status(report)scorecard["statuses"].append(resolution_status)@@ -152,10 +157,7 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, timtry:diff_obj = PatchSet(p[KEY_PREDICTION])scorecard["patch_files"] = [- x.path- for x in diff_obj.modified_files- + diff_obj.added_files- + diff_obj.removed_files+ x.path for x in diff_obj.modified_files + diff_obj.added_files + diff_obj.removed_files]scorecard["patch_lines_add"] = sum([f.added for f in diff_obj])scorecard["patch_lines_del"] = sum([f.removed for f in diff_obj])@@ -193,38 +195,24 @@ if __name__ == "__main__":help="Path to predictions file (.jsonl)",required=True,)- parser.add_argument(- "--log_dir", type=str, help="Path to log directory", required=True- )+ parser.add_argument("--log_dir", type=str, help="Path to log directory", required=True)parser.add_argument("--swe_bench_tasks",type=str,help="Path to SWE-bench task instances file",required=True,)- parser.add_argument(- "--testbed", type=str, help="Path to testbed directory", required=True- )- parser.add_argument(- "--skip_existing", action="store_true", help="(Optional) Skip existing logs"- )+ parser.add_argument("--testbed", type=str, help="Path to testbed directory", required=True)+ parser.add_argument("--skip_existing", action="store_true", help="(Optional) Skip existing logs")parser.add_argument("--timeout",type=int,help="(Optional) Timeout in seconds (default: 900)",default=900,)- parser.add_argument(- "--verbose", action="store_true", help="(Optional) Verbose mode"- )- parser.add_argument(- "--conda_link", default=None, type=str, help="(Optional) URL to conda installation to use"- )- parser.add_argument(- "--log_suffix", default=None, type=str, help="(Optional) Log suffix"- )- parser.add_argument(- "--num_processes", default=-1, type=int, help="Num processes"- )+ parser.add_argument("--verbose", action="store_true", help="(Optional) Verbose mode")+ parser.add_argument("--conda_link", default=None, type=str, help="(Optional) URL to conda installation to use")+ parser.add_argument("--log_suffix", default=None, type=str, help="(Optional) Log suffix")+ parser.add_argument("--num_processes", default=-1, type=int, help="Num processes")args = parser.parse_args()main(**vars(args))diff --git a/inspector/server.py b/inspector/server.pyindex 6d9c338a..4e9eef7c 100644--- a/inspector/server.py+++ b/inspector/server.py@@ -14,7 +14,7 @@ def append_exit(content):last_entry = content["history"][-1]if last_entry["role"] == "system":return content-+exit_status = content.get("info", {}).get("exit_status", None)if exit_status is None:@@ -23,10 +23,12 @@ def append_exit(content):if exit_status.startswith("submitted"):if "submission" in content["info"]:submission = content["info"]["submission"]- content["history"].append({- "role": "model_patch",- "content": submission,- })+ content["history"].append(+ {+ "role": "model_patch",+ "content": submission,+ }+ )# else submission should be in history alreadyelse:raise ValueError("No submission in history or info")@@ -41,10 +43,12 @@ def append_exit(content):def append_patch(instance_id, content, patches, patch_type):if content.get("info", {}).get("exit_status", None) is not None:if instance_id in patches:- content["history"].append({- "role": f"{patch_type} Patch",- "content": patches[instance_id],- })+ content["history"].append(+ {+ "role": f"{patch_type} Patch",+ "content": patches[instance_id],+ }+ )return content@@ -56,13 +60,13 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_info = data.get("info", {})model_stats = info.get("model_stats", {})instance_cost = model_stats.get("instance_cost", None)- instance_cost = f'{instance_cost:.2f}' if instance_cost is not None else 'N/A'+ instance_cost = f"{instance_cost:.2f}" if instance_cost is not None else "N/A"tokens_sent = model_stats.get("tokens_sent", None)- tokens_sent = f'{tokens_sent:,}' if tokens_sent is not None else 'N/A'+ tokens_sent = f"{tokens_sent:,}" if tokens_sent is not None else "N/A"tokens_received = model_stats.get("tokens_received", None)- tokens_received = f'{tokens_received:,}' if tokens_received is not None else 'N/A'+ tokens_received = f"{tokens_received:,}" if tokens_received is not None else "N/A"api_calls = model_stats.get("api_calls", None)- api_calls = f'{api_calls:,}' if api_calls is not None else 'N/A'+ api_calls = f"{api_calls:,}" if api_calls is not None else "N/A"stats.append(f"**** Run Stats ****")stats.append(f"Instance Cost: ${instance_cost}")stats.append(f"Tokens Sent: {tokens_sent}")@@ -79,25 +83,30 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_status.append("**** Statuses ****")status.append(f" {'✅' if is_generated else '❌'} Generated (The agent was {'' if is_generated else 'not '}"- "able to generate a pull request to address this issue)")+ "able to generate a pull request to address this issue)"+ )status.append(f" {'✅' if is_applied else '❌'} Applied (The pull request was {'' if is_applied else 'not '}"- "successfully applied to the repo during eval)")+ "successfully applied to the repo during eval)"+ )status.append(f" {'✅' if is_resolved else '❌'} Resolved (The pull request {'' if is_resolved else 'not '}"- "successfully resolved the issue during eval)")+ "successfully resolved the issue during eval)"+ )else:status.append("Results format not recognized")if scorecards is not None:scorecard = [x for x in scorecards if x["instance_id"] == instance_id][0]- if "test_results" in scorecard and "failure" in scorecard["test_results"] and (- len(scorecard["test_results"]["failure"]["FAIL_TO_PASS"]) > 0 or- len(scorecard["test_results"]["failure"]["PASS_TO_PASS"]) > 0+ if (+ "test_results" in scorecard+ and "failure" in scorecard["test_results"]+ and (+ len(scorecard["test_results"]["failure"]["FAIL_TO_PASS"]) > 0+ or len(scorecard["test_results"]["failure"]["PASS_TO_PASS"]) > 0+ )):- tests_failing = [- f" - {x}" for x in scorecard["test_results"]["failure"]["FAIL_TO_PASS"]- ] + [+ tests_failing = [f" - {x}" for x in scorecard["test_results"]["failure"]["FAIL_TO_PASS"]] + [f" - {x}" for x in scorecard["test_results"]["failure"]["PASS_TO_PASS"]]status.extend(["", "**** Test Results ****", "🧪 Tests Failed"] + tests_failing[:7])@@ -109,7 +118,9 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_status.append("Instance not found in results")else:status.append("---------------------------")- status.append("Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself.")+ status.append(+ "Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself."+ )status.append(f"Check {results_file} for the most accurate evaluation results.")status.append("")status.append(f"Instance ID: {instance_id}")@@ -196,12 +207,12 @@ class Handler(http.server.SimpleHTTPRequestHandler):self.gold_patches = kwargs.pop("gold_patches")if "test_patches" in kwargs:self.test_patches = kwargs.pop("test_patches")- self.traj_dir = kwargs.pop('directory', '.') # Extract directory+ self.traj_dir = kwargs.pop("directory", ".") # Extract directorysuper().__init__(*args, **kwargs)def serve_directory_info(self):self.send_response(200)- self.send_header('Content-type', 'application/json')+ self.send_header("Content-type", "application/json")self.end_headers()self.wfile.write(json.dumps({"directory": self.traj_dir}).encode())@@ -213,40 +224,41 @@ class Handler(http.server.SimpleHTTPRequestHandler):self.test_patches,)self.send_response(200)- self.send_header('Content-type', 'text/plain')+ self.send_header("Content-type", "text/plain")self.end_headers()self.wfile.write(json.dumps(content).encode())except FileNotFoundError:self.send_error(404, f"File {file_path} not found")def do_GET(self):- if self.path == '/directory_info':+ if self.path == "/directory_info":self.serve_directory_info()- elif self.path.startswith('/files'):+ elif self.path.startswith("/files"):self.handle_files_request()- elif self.path.startswith('/trajectory/'):- file_path = self.path[len('/trajectory/'):]+ elif self.path.startswith("/trajectory/"):+ file_path = self.path[len("/trajectory/") :]self.serve_file_content(file_path)- elif self.path.startswith('/check_update'):+ elif self.path.startswith("/check_update"):self.check_for_updates()else:super().do_GET()def handle_files_request(self):self.send_response(200)- self.send_header('Content-type', 'application/json')+ self.send_header("Content-type", "application/json")self.end_headers()files = sorted([str(file.relative_to(Path(self.traj_dir))) + " " * 4 + get_status(file)- for file in Path(self.traj_dir).glob('**/*.traj')+ for file in Path(self.traj_dir).glob("**/*.traj")],- key=lambda x: str(Path(self.traj_dir) / x), reverse=True+ key=lambda x: str(Path(self.traj_dir) / x),+ reverse=True,)self.wfile.write(json.dumps(files).encode())def check_for_updates(self):- current_mod_times = {str(file): os.path.getmtime(file) for file in Path(self.traj_dir).glob('**/*.traj')}+ current_mod_times = {str(file): os.path.getmtime(file) for file in Path(self.traj_dir).glob("**/*.traj")}if current_mod_times != Handler.file_mod_times:Handler.file_mod_times = current_mod_timesself.send_response(200) # Send response that there's an update@@ -255,7 +267,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):self.end_headers()def end_headers(self):- self.send_header('Access-Control-Allow-Origin', '*')+ self.send_header("Access-Control-Allow-Origin", "*")super().end_headers()@@ -269,21 +281,12 @@ def main(data_path, directory, port):elif "args.yaml" in os.listdir(directory):args = yaml.safe_load(open(os.path.join(directory, "args.yaml")))if "environment" in args and "data_path" in args["environment"]:- data_path = os.path.join(- Path(__file__).parent, "..",- args["environment"]["data_path"]- )+ data_path = os.path.join(Path(__file__).parent, "..", args["environment"]["data_path"])if os.path.exists(data_path):data = json.load(open(data_path, "r"))- gold_patches = {- d["instance_id"]: d["patch"]- if "patch" in d else None for d in data- }- test_patches = {- d["instance_id"]: d["test_patch"]- if "test_patch" in d else None for d in data- }+ gold_patches = {d["instance_id"]: d["patch"] if "patch" in d else None for d in data}+ test_patches = {d["instance_id"]: d["test_patch"] if "test_patch" in d else None for d in data}handler_with_directory = partial(Handler,@@ -305,7 +308,7 @@ def main(data_path, directory, port):if __name__ == "__main__":parser = ArgumentParser()parser.add_argument("--data_path", type=str, help="Path to dataset that was used for the trajectories")- parser.add_argument("--directory", type=str, help="Directory to serve", default="./trajectories", nargs='?')+ parser.add_argument("--directory", type=str, help="Directory to serve", default="./trajectories", nargs="?")parser.add_argument("--port", type=int, help="Port to serve", default=8000)args = parser.parse_args()main(**vars(args))diff --git a/inspector/static.py b/inspector/static.pyindex dab97593..ed36ddfc 100644--- a/inspector/static.py+++ b/inspector/static.py@@ -4,6 +4,7 @@ import yamlfrom pathlib import Pathfrom tqdm.auto import tqdmfrom argparse import ArgumentParser+try:from .server import load_contentexcept ImportError:@@ -33,10 +34,10 @@ TEMPLATE = """"""try:- with open(Path(__file__).parent / 'style.css', 'r') as infile:+ with open(Path(__file__).parent / "style.css", "r") as infile:STYLE_SHEET = infile.read()except Exception as e:- style_file = Path(__file__).parent / 'style.css'+ style_file = Path(__file__).parent / "style.css"logger.error(f"Failed to load style sheet from {style_file}: {e}")raise e@@ -52,41 +53,41 @@ def _load_file(file_name, gold_patches, test_patches):"demo": "Demonstration",}content = load_content(file_name, gold_patches, test_patches)- if 'history' in content and isinstance(content['history'], list):+ if "history" in content and isinstance(content["history"], list):history_content = ""- for index, item in enumerate(content['history']):- item_content = item.get('content', '').replace('<', '<').replace('>', '>')- if item.get('agent') and item['agent'] != "primary":+ for index, item in enumerate(content["history"]):+ item_content = item.get("content", "").replace("<", "<").replace(">", ">")+ if item.get("agent") and item["agent"] != "primary":role_class = "subroutine"else:- role_class = item.get('role', 'default').lower().replace(' ', '-')+ role_class = item.get("role", "default").lower().replace(" ", "-")element_id = f"historyItem{index}"- role_name = role_map.get(item.get('role', ''), item.get('role', ''))+ role_name = role_map.get(item.get("role", ""), item.get("role", ""))history_content += (- f'''<div class="history-item {role_class}" id="{element_id}">'''- f'''<div class="role-bar {role_class}"><strong><span>{role_name}</span></strong></div>'''- f'''<div class="content-container">'''- f'''<pre>{item_content}</pre>'''- f'''</div>'''- f'''<div class="shadow"></div>'''- f'''</div>'''- )+ f"""<div class="history-item {role_class}" id="{element_id}">"""+ f"""<div class="role-bar {role_class}"><strong><span>{role_name}</span></strong></div>"""+ f"""<div class="content-container">"""+ f"""<pre>{item_content}</pre>"""+ f"""</div>"""+ f"""<div class="shadow"></div>"""+ f"""</div>"""+ )return history_contentelse:- return 'No history content found.'+ return "No history content found."except Exception as e:return f"Error loading content. {e}"-+def _make_file_path_tree(file_path):- path_parts = file_path.split('/')+ path_parts = file_path.split("/")relevant_parts = path_parts[-3:]html_string = '<div class="filepath">\n'for part in relevant_parts:html_string += f'<div class="part">{part}</div>\n'- html_string += '</div>'+ html_string += "</div>"return html_string-+def save_static_viewer(file_path):if not isinstance(file_path, Path):@@ -98,32 +99,24 @@ def save_static_viewer(file_path):data_path = Path(__file__).parent.parent / args["environment"]["data_path"]if data_path.exists():data = json.load(open(data_path, "r"))- if (- not isinstance(data, list) or- not data or- 'patch' not in data[0] or- 'test_patch' not in data[0]- ):+ if not isinstance(data, list) or not data or "patch" not in data[0] or "test_patch" not in data[0]:data = []gold_patches = {x["instance_id"]: x["patch"] for x in data}test_patches = {x["instance_id"]: x["test_patch"] for x in data}content = _load_file(file_path, gold_patches, test_patches)file_path_tree = _make_file_path_tree(file_path.absolute().as_posix())- icons_path = Path(__file__).parent / 'icons'+ icons_path = Path(__file__).parent / "icons"relative_icons_path = find_relative_path(file_path, icons_path)- style_sheet = STYLE_SHEET.replace(- "url('icons/",- f"url('{relative_icons_path.as_posix()}/"- ).replace(- 'url("icons/',- f'url("{relative_icons_path.as_posix()}/'- )+ style_sheet = STYLE_SHEET.replace("url('icons/", f"url('{relative_icons_path.as_posix()}/").replace(+ 'url("icons/', f'url("{relative_icons_path.as_posix()}/'+ )data = TEMPLATE.format(file_content=content, style_sheet=style_sheet, file_path_tree=file_path_tree)- output_file = file_path.with_suffix('.html')- with open(output_file, 'w+') as outfile:+ output_file = file_path.with_suffix(".html")+ with open(output_file, "w+") as outfile:print(data, file=outfile)logger.info(f"Saved static viewer to {output_file}")+def find_relative_path(from_path, to_path):# Convert paths to absolute for uniformityfrom_path = from_path.resolve()@@ -141,13 +134,13 @@ def find_relative_path(from_path, to_path):if from_part != to_part:breakcommon_parts += 1-+# Calculate the '../' needed to get back from from_path to the common ancestor- back_to_ancestor = ['..'] * (len(from_path.parts) - common_parts)-+ back_to_ancestor = [".."] * (len(from_path.parts) - common_parts)+# Direct path from common ancestor to to_pathto_target = to_path.parts[common_parts:]-+# Combine to get the relative pathrelative_path = Path(*back_to_ancestor, *to_target)return relative_path@@ -156,7 +149,7 @@ def find_relative_path(from_path, to_path):def save_all_trajectories(directory):if not isinstance(directory, Path):directory = Path(directory)- all_files = list(directory.glob('**/*.traj'))+ all_files = list(directory.glob("**/*.traj"))logger.info(f"Found {len(all_files)} trajectory files in {directory}")for file_path in tqdm(all_files, desc="Saving static viewers"):save_static_viewer(file_path)@@ -167,4 +160,4 @@ if __name__ == "__main__":parser = ArgumentParser()parser.add_argument("directory", type=str, help="Directory containing trajectory files")args = parser.parse_args()- save_all_trajectories(args.directory)\ No newline at end of file+ save_all_trajectories(args.directory)diff --git a/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.pyindex 286cdf2f..708a2ed8 100644--- a/make_demos/convert_traj_to_demo.py+++ b/make_demos/convert_traj_to_demo.py@@ -10,7 +10,7 @@ DEMO_COMMENT = """# This is a demo file generated from trajectory file:# {traj_path}# You can use this demo file to replay the actions in the trajectory with run_replay.py.# You can edit the content of the actions in this file to modify the replay behavior.-# NOTICE:+# NOTICE:# Only the actions of the assistant will be replayed.# You do not need to modify the observation's contents or any other fields.# You can add or remove actions to modify the replay behavior."""@@ -22,18 +22,18 @@ def convert_to_literal_string(d):"""if isinstance(d, dict):for key, value in d.items():- if isinstance(value, str) and '\n' in value:- d[key] = LSS(value.replace('\r\n', '\n').replace('\r', '\n'))+ if isinstance(value, str) and "\n" in value:+ d[key] = LSS(value.replace("\r\n", "\n").replace("\r", "\n"))elif isinstance(value, dict):convert_to_literal_string(value)elif isinstance(d, list):for i, item in enumerate(d):- if isinstance(item, str) and '\n' in item:- d[i] = LSS(item.replace('\r\n', '\n').replace('\r', '\n'))+ if isinstance(item, str) and "\n" in item:+ d[i] = LSS(item.replace("\r\n", "\n").replace("\r", "\n"))elif isinstance(item, dict):convert_to_literal_string(item)- elif isinstance(d, str) and '\n' in d:- d = LSS(d.replace('\r\n', '\n').replace('\r', '\n'))+ elif isinstance(d, str) and "\n" in d:+ d = LSS(d.replace("\r\n", "\n").replace("\r", "\n"))else:raise ValueError(f"Unsupported type: {type(d)}")return d@@ -60,14 +60,16 @@ def convert_traj_to_action_demo(traj_path: str, output_file: str = None, includeaction_traj = list()admissible_roles = {"assistant", "user"} if include_user else {"assistant"}for step in history:- if step['role'] in admissible_roles and step.get('agent', 'primary') == 'primary':- action_traj.append({k: v for k, v in step.items() if k in {'content', 'role'}})+ if step["role"] in admissible_roles and step.get("agent", "primary") == "primary":+ action_traj.append({k: v for k, v in step.items() if k in {"content", "role"}})save_demo(action_traj, output_file, traj_path)print(f"Saved demo to {output_file}")def main(traj_path: str, output_dir: str = None, suffix: str = "", overwrite: bool = False, include_user: bool = False):- filename = '/'.join([Path(traj_path).parent.name + suffix, Path(traj_path).name.rsplit('.traj', 1)[0]]) + ".demo.yaml"+ filename = (+ "/".join([Path(traj_path).parent.name + suffix, Path(traj_path).name.rsplit(".traj", 1)[0]]) + ".demo.yaml"+ )output_file = Path(output_dir) / filenameif output_file.exists() and not overwrite:raise FileExistsError(f"Output file already exists: {output_file}")@@ -82,14 +84,16 @@ def string2bool(s):return Falseelse:raise ValueError(f"Invalid boolean string: {s}")-+if __name__ == "__main__":parser = ArgumentParser()parser.add_argument("traj_path", type=str, help="Path to trajectory file")parser.add_argument("--output_dir", type=str, help="Output directory for action demos", default="./demos")parser.add_argument("--suffix", type=str, help="Suffix for the output file", default="")- parser.add_argument("--overwrite", type=string2bool, help="Overwrite existing files", default=False, nargs='?')- parser.add_argument("--include_user", type=string2bool, help="Include user responses (computer)", default=False, nargs='?')+ parser.add_argument("--overwrite", type=string2bool, help="Overwrite existing files", default=False, nargs="?")+ parser.add_argument(+ "--include_user", type=string2bool, help="Include user responses (computer)", default=False, nargs="?"+ )args = parser.parse_args()main(**vars(args))diff --git a/mkdocs.yml b/mkdocs.ymlindex 27f7ef07..0f3460ec 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -4,7 +4,7 @@ theme:icon:repo: fontawesome/brands/githublogo: assets/swe-agent.svg- palette:+ palette:- media: "(prefers-color-scheme)"toggle:icon: material/brightness-auto@@ -24,7 +24,7 @@ theme:icon: material/weather-sunnyname: Switch to light modefeatures:- - navigation.indexes+ - navigation.indexes- content.action.edit- navigation.footer- content.code.copydiff --git a/pyproject.toml b/pyproject.tomlindex 789f8a77..034ddb33 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -105,12 +105,10 @@ exclude = ["venv",]-# Same as Black.-line-length = 88+line-length = 120indent-width = 4-# Assume Python 3.8-target-version = "py38"+target-version = "py39"[tool.ruff.lint]# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.diff --git a/release_dockerhub.sh b/release_dockerhub.shindex 72c8c0c6..565f892b 100755--- a/release_dockerhub.sh+++ b/release_dockerhub.sh@@ -53,17 +53,17 @@ echo "------------------------------------------"echo "Building swe-agent"echo "------------------------------------------"docker buildx build --platform=linux/amd64,linux/arm64 -t ${USER}/swe-agent:${VERSION_STR} -f docker/swe.Dockerfile --push .-echo "🔥 swe-agent pushed to dockerhub"+echo "🔥 swe-agent pushed to dockerhub"echo "------------------------------------------"echo "Building swe-eval"echo "------------------------------------------"docker buildx build --platform=linux/amd64,linux/arm64 -t ${USER}/swe-eval:${VERSION_STR} -f docker/eval.Dockerfile --push .-echo "🔥 swe-eval pushed to dockerhub"+echo "🔥 swe-eval pushed to dockerhub"echo "------------------------------------------"echo "Building swe-agent-run"echo "------------------------------------------"docker buildx build --platform=linux/amd64,linux/arm64 -t ${USER}/swe-agent-run:${VERSION_STR} --push .-echo "🔥 swe-agent-run pushed to dockerhub"+echo "🔥 swe-agent-run pushed to dockerhub"echo "------------------------------------------"echo "Building of all images done"echo "------------------------------------------"diff --git a/run.py b/run.pyindex 8fad2e6d..118e8ef2 100644--- a/run.py+++ b/run.py@@ -20,9 +20,7 @@ import rich.markdowntry:from rich_argparse import RichHelpFormatterexcept ImportError:- msg = (- "Please install the rich_argparse package with `pip install rich_argparse`."- )+ msg = "Please install the rich_argparse package with `pip install rich_argparse`."raise ImportError(msg)import yamlfrom rich.markdown import Markdown@@ -44,7 +42,12 @@ from sweagent import (from swebench import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTIONfrom unidiff import PatchSet-from sweagent.environment.utils import InvalidGithubURL, get_associated_commit_urls, get_gh_issue_data, parse_gh_issue_url+from sweagent.environment.utils import (+ InvalidGithubURL,+ get_associated_commit_urls,+ get_gh_issue_data,+ parse_gh_issue_url,+)__doc__: str = """ Run inference. Usage examples:@@ -68,14 +71,15 @@ logging.getLogger("simple_parsing").setLevel(logging.WARNING)@dataclass(frozen=True)class ActionsArguments(FlattenedAccess, FrozenSerializable):"""Run real-life actions (opening PRs, etc.) if we can solve the issue."""+# Open a PR with the patch if we can solve the issue- open_pr: bool = False+ open_pr: bool = False# When working with local repository: Apply patchapply_patch_locally: bool = False- # Option to be used with open_pr: Skip action if there are already commits claiming- # to fix the issue. Please only set this to False if you are sure the commits are+ # Option to be used with open_pr: Skip action if there are already commits claiming+ # to fix the issue. Please only set this to False if you are sure the commits are# not fixes or if this is your own repository!- skip_if_commits_reference_issue: bool = True+ skip_if_commits_reference_issue: bool = True# OBSOLETE. Do not use, will raise error. Please specify --repo_path instead.push_gh_repo_url: str = ""@@ -83,9 +87,11 @@ class ActionsArguments(FlattenedAccess, FrozenSerializable):if self.push_gh_repo_url:raise ValueError("push_gh_repo_url is obsolete. Use repo_path instead")+@dataclass(frozen=True)class ScriptArguments(FlattenedAccess, FrozenSerializable):"""Configure the control flow of the run.py script"""+environment: EnvironmentArgumentsagent: AgentArgumentsactions: ActionsArguments@@ -118,12 +124,13 @@ class ScriptArguments(FlattenedAccess, FrozenSerializable):class _ContinueLoop(Exception):"""Used for internal control flow"""+...class MainHook:"""Hook structure for the web server or other addons to interface with"""-+@staticmethoddef _is_promising_patch(info: Dict[str, Any]) -> bool:"""Do we actually believe that the patch will solve the issue?@@ -132,27 +139,28 @@ class MainHook:# The exit status can also be `submitted (exit_cost)` etc.return info["exit_status"] == "submitted" and info.get("submission") is not None-def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):"""Called when hook is initialized"""...def on_start(self):"""Called at the beginning of `Main.main`"""- ...+ ...def on_end(self):"""Called at the end of `Main.main`"""...-+def on_instance_start(self, *, index: int, instance: Dict[str, Any]):"""Called at the beginning of each instance loop in `Main.run`"""...-- def on_instance_skipped(self, ):++ def on_instance_skipped(+ self,+ ):"""Called when an instance is skipped in `Main.run`"""...-+def on_instance_completed(self, *, info, trajectory):"""Called when an instance is completed in `Main.run`"""...@@ -165,12 +173,12 @@ class SaveApplyPatchHook(MainHook):self._traj_dir = traj_dirself._apply_patch_locally = args.actions.apply_patch_locallyself._instance = None-+def on_instance_start(self, *, index: int, instance: Dict[str, Any]):self._instance = instance-+def on_instance_completed(self, *, info, trajectory):- assert self._instance is not None # mypy+ assert self._instance is not None # mypyinstance_id = self._instance["instance_id"]patch_path = self._save_patch(instance_id, info)if patch_path:@@ -189,7 +197,7 @@ class SaveApplyPatchHook(MainHook):console = rich.console.Console()msg = ["SWE-agent has produced a patch that it believes will solve the issue you submitted!",- "Use the code snippet below to inspect or apply it!"+ "Use the code snippet below to inspect or apply it!",]panel = rich.panel.Panel.fit("\n".join(msg),@@ -201,17 +209,17 @@ class SaveApplyPatchHook(MainHook):f"# The patch has been saved to your local filesystem at:",f"PATCH_FILE_PATH='{patch_output_file.resolve()}'","# Inspect it:",- "cat \"${PATCH_FILE_PATH}\"",+ 'cat "${PATCH_FILE_PATH}"',"# Apply it to a local repository:",f"cd <your local repo root>",- "git apply \"${PATCH_FILE_PATH}\"",+ 'git apply "${PATCH_FILE_PATH}"',"```",]console.print(rich.markdown.Markdown("\n".join(content)))def _save_patch(self, instance_id: str, info) -> Optional[Path]:"""Create patch files that can be applied with `git am`.-+Returns:The path to the patch file, if it was saved. Otherwise, returns None."""@@ -224,14 +232,14 @@ class SaveApplyPatchHook(MainHook):model_patch = info["submission"]patch_output_file.write_text(model_patch)if self._is_promising_patch(info):- # Only print big congratulations if we actually believe+ # Only print big congratulations if we actually believe# the patch will solve the issueself._print_patch_message(patch_output_file)return patch_output_filedef _apply_patch(self, patch_file: Path, local_dir: Path) -> None:"""Apply a patch to a local directory."""-+assert local_dir.is_dir()assert patch_file.exists()# The resolve() is important, because we're gonna run the cmd@@ -258,7 +266,7 @@ class OpenPRHook(MainHook):def on_instance_completed(self, *, info, trajectory):if self._open_pr and self.should_open_pr(info):self._env.open_pr(trajectory=trajectory)-+def should_open_pr(self, info: Dict[str, Any]) -> bool:"""Does opening a PR make sense?"""if not info.get("submission"):@@ -282,7 +290,7 @@ class OpenPRHook(MainHook):logger.info("Issue is locked. Skipping PR creation.")return Falseorg, repo, issue_number = parse_gh_issue_url(self._data_path)- associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)+ associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)if associated_commits:commit_url_strs = ", ".join(associated_commits)if self._skip_if_commits_reference_issue:@@ -313,7 +321,7 @@ class Main:self.hooks: List[MainHook] = []for hook in default_hooks:self.add_hook(hook)-+def add_hook(self, hook: MainHook):hook.on_init(args=self.args, agent=self.agent, env=self.env, traj_dir=self.traj_dir)self.hooks.append(hook)@@ -339,26 +347,17 @@ class Main:files = []assert self.env.record is not None # mypyif "patch" in self.env.record:- files = "\n".join(- [f"- {x.path}" for x in PatchSet(self.env.record["patch"]).modified_files]- )+ files = "\n".join([f"- {x.path}" for x in PatchSet(self.env.record["patch"]).modified_files])# Get test files, F2P tests informationtest_files = []if "test_patch" in self.env.record:test_patch_obj = PatchSet(self.env.record["test_patch"])- test_files = "\n".join(- [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]- )+ test_files = "\n".join([f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files])tests = ""if "FAIL_endTO_PASS" in self.env.record:tests = "\n".join([f"- {x}" for x in self.env.record["FAIL_TO_PASS"]])- setup_args = {- "issue": issue,- "files": files,- "test_files": test_files,- "tests": tests- }+ setup_args = {"issue": issue, "files": files, "test_files": test_files, "tests": tests}info, trajectory = self.agent.run(setup_args=setup_args,env=self.env,@@ -369,7 +368,7 @@ class Main:self._save_predictions(instance_id, info)for hook in self.hooks:hook.on_instance_completed(info=info, trajectory=trajectory)-+def main(self):for hook in self.hooks:hook.on_start()@@ -401,7 +400,6 @@ class Main:for hook in self.hooks:hook.on_end()-def _save_arguments(self) -> None:"""Save the arguments to a yaml file to the run's trajectory directory."""log_path = self.traj_dir / "args.yaml"@@ -409,7 +407,7 @@ class Main:if log_path.exists():try:other_args = self.args.load_yaml(log_path)- if (self.args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality+ if self.args.dumps_yaml() != other_args.dumps_yaml(): # check yaml equality instead of object equalitylogger.warning("**************************************************")logger.warning("Found existing args.yaml with different arguments!")logger.warning("**************************************************")@@ -419,7 +417,6 @@ class Main:with log_path.open("w") as f:self.args.dump_yaml(f)-def should_skip(self, instance_id: str) -> bool:"""Check if we should skip this instance based on the instance filter and skip_existing flag."""# Skip instances that don't match the instance filter@@ -447,7 +444,6 @@ class Main:return Truereturn False-def _save_predictions(self, instance_id: str, info):output_file = self.traj_dir / "all_preds.jsonl"model_patch = info["submission"] if "submission" in info else None@@ -463,7 +459,7 @@ class Main:def get_args(args=None) -> ScriptArguments:"""Parse command line arguments and return a ScriptArguments object.-+Args:args: Optional list of arguments to parse. If not provided, uses sys.argv."""@@ -502,8 +498,14 @@ def get_args(args=None) -> ScriptArguments:yaml.add_representer(str, multiline_representer)- return parse(ScriptArguments, default=defaults, add_config_path_arg=False, args=args, formatter_class=RichHelpFormatter, description=Markdown(__doc__))-+ return parse(+ ScriptArguments,+ default=defaults,+ add_config_path_arg=False,+ args=args,+ formatter_class=RichHelpFormatter,+ description=Markdown(__doc__),+ )def main(args: ScriptArguments):diff --git a/run_replay.py b/run_replay.pyindex fb56401a..81573016 100644--- a/run_replay.py+++ b/run_replay.py@@ -37,21 +37,13 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffixactions = [x["content"] for x in traj_data["history"] if x["role"] == "assistant"]instance_id = traj_path.split("/")[-1].split(".")[0]with open(replay_action_trajs_path, "w") as f:- print(- json.dumps({instance_id: actions}),- file=f,- end="\n",- flush=True- )+ print(json.dumps({instance_id: actions}), file=f, end="\n", flush=True)# Get data_path from args.yamlif data_path is None:- args_path = os.path.join(- os.path.dirname(traj_path),- "args.yaml"- )+ args_path = os.path.join(os.path.dirname(traj_path), "args.yaml")args = yaml.safe_load(open(args_path))- data_path = args['environment']['data_path']+ data_path = args["environment"]["data_path"]# Identify the relevant task instance and create itdef create_task_instances_tmp_file(data: List[Dict[str, Any]]) -> str:@@ -67,7 +59,9 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffixis_other = Falseif data_path.endswith(".jsonl"):- replay_task_instances_path = create_task_instances_tmp_file([json.loads(x) for x in open(data_path, "r").readlines()])+ replay_task_instances_path = create_task_instances_tmp_file(+ [json.loads(x) for x in open(data_path, "r").readlines()]+ )elif data_path.endswith(".json"):replay_task_instances_path = create_task_instances_tmp_file(json.load(open(data_path)))else:@@ -77,11 +71,16 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix# Call run.py via subprocessrun_args = [- "--config_file", config_file,- "--data_path", replay_task_instances_path,- "--install_environment", "True",- "--model_name", "replay",- "--replay_path", replay_action_trajs_path,+ "--config_file",+ config_file,+ "--data_path",+ replay_task_instances_path,+ "--install_environment",+ "True",+ "--model_name",+ "replay",+ "--replay_path",+ replay_action_trajs_path,*forward_args,]if is_other:@@ -96,6 +95,7 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffixif not is_other:os.remove(replay_task_instances_path)+def main(traj_path: str,config_file: str,@@ -111,7 +111,11 @@ def get_args(args=None):parser = ArgumentParser(description=__doc__)parser.add_argument("--traj_path", help="Path to trajectory to replay", default=None)parser.add_argument("--config_file", help="Path to template", required=True)- parser.add_argument("--data_path", help="(Optional) Path to data file containing task instances ref'ed by replay trajectories", default=None)+ parser.add_argument(+ "--data_path",+ help="(Optional) Path to data file containing task instances ref'ed by replay trajectories",+ default=None,+ )parser.add_argument("--suffix", help="(Optional) Suffix argument appended to end of traj path", default=None)args, remaining_args = parser.parse_known_args(args=args)return args, remaining_argsdiff --git a/scripts/run_jsonl.sh b/scripts/run_jsonl.shindex f681a28a..776cbfe6 100755--- a/scripts/run_jsonl.sh+++ b/scripts/run_jsonl.sh@@ -21,7 +21,7 @@ while IFS= read -r line; do# into a format suitable for passing to the Python script# xargs -n 2 groups them back into pairs to handle as arguments correctlyARGS=$(echo "$line" | jq -r '. | to_entries | .[] | "--\(.key) \(.value)"' | xargs -n 2 echo)-+# Execute the Python script with the constructed argumentsecho $ARGSpython run.py $ARGSdiff --git a/sweagent/agent/README.md b/sweagent/agent/README.mdindex 7101bbcc..fed45913 100644--- a/sweagent/agent/README.md+++ b/sweagent/agent/README.md@@ -2,7 +2,7 @@The `agent` folder contains the logic for handling model inference and facilitating their interaction with `SWEEnv`.The following documentation describing the purpose and classes of each file.-#### `agents.py`+#### `agents.py`This file defines the `Agent` class, which facilitates the interaction between an agent and the environment. The `AgentConfig` and `AgentArguments` data classes compile all arguments into a single file.- `Agent`: Main class for handling model behavior + interaction with environment- `__init__`: Sets up model, assistant, configurations, and argumentsdiff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex c13e411d..e428ca3e 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -48,9 +48,7 @@ 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- )+ put_demos_in_history: bool = False # if True, add demonstration to history instead of as a single message# defaults to format_error_template in ParseFunctionformat_error_template: str = None # type: ignorecommand_files: list[str] = field(default_factory=list)@@ -62,9 +60,7 @@ class AgentConfig(FrozenSerializable):history_processor: str = "DefaultHistoryProcessor"history_processor_args: dict[str, Any] = field(default_factory=dict)command_docs: str = None # type: ignore- 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",@@ -103,24 +99,16 @@ class AgentConfig(FrozenSerializable):if self.next_step_template is None:object.__setattr__(self, "next_step_template", self.instance_template)if self.next_step_no_output_template is None:- object.__setattr__(- self, "next_step_no_output_template", self.next_step_template- )+ object.__setattr__(self, "next_step_no_output_template", self.next_step_template)object.__setattr__(self, "parse_command", ParseCommand.get(self.parse_command))for file in self.command_files:commands = self.parse_command.parse_command_file(file)- util_functions = [- command for command in commands if command.name.startswith("_")- ]- commands = [- command for command in commands if not command.name.startswith("_")- ]+ util_functions = [command for command in commands if command.name.startswith("_")]+ commands = [command for command in commands if not command.name.startswith("_")]- object.__setattr__(- self, "util_functions", self.util_functions + util_functions- )+ object.__setattr__(self, "util_functions", self.util_functions + util_functions)object.__setattr__(self, "_commands", self._commands + commands)for subroutine in self.subroutine_types:@@ -131,18 +119,14 @@ class AgentConfig(FrozenSerializable):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",@@ -152,9 +136,7 @@ class AgentConfig(FrozenSerializable):**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,@@ -180,6 +162,7 @@ class AgentConfig(FrozenSerializable):@dataclass(frozen=True)class AgentArguments(FlattenedAccess, FrozenSerializable):"""Configure the agent's behaviour (templates, parse functions, blocklists, ...)."""+model: ModelArguments = None# Policy can only be set via config yaml file from command line@@ -199,9 +182,7 @@ class AgentArguments(FlattenedAccess, FrozenSerializable):"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, "total_cost_limit", self.model.total_cost_limit)class TrajectoryStep(TypedDict):@@ -213,36 +194,31 @@ class TrajectoryStep(TypedDict):class AgentHook:- def on_init(self):- ...+ def on_init(self): ...- def on_run_start(self, ):- ...+ def on_run_start(+ self,+ ): ...- def on_step_start(self):- ...+ def on_step_start(self): ...- def on_actions_generated(self, *, thought: str, action: str, output: str):- ...-- def on_sub_action_started(self, *, sub_action: str):- ...+ def on_actions_generated(self, *, thought: str, action: str, output: str): ...- def on_sub_action_executed(self, *, obs: str, done: bool):- ...+ def on_sub_action_started(self, *, sub_action: str): ...- def on_step_done(self, *, trajectory_step: TrajectoryStep, model_stats: APIStats):- ...+ def on_sub_action_executed(self, *, obs: str, done: bool): ...++ def on_step_done(self, *, trajectory_step: TrajectoryStep, model_stats: APIStats): ...++ def on_run_done(self): ...- def on_run_done(self):- ...-def on_model_query(self, *, query: str, agent: str):"""Actually query the model with the complete history."""...-- def on_query_message_added(self, *, role: str, content: str, agent: str, is_demo: bool = False, thought: str = "", action: str = ""):- ...++ def on_query_message_added(+ self, *, role: str, content: str, agent: str, is_demo: bool = False, thought: str = "", action: str = ""+ ): ...class Agent:@@ -250,9 +226,7 @@ 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.configassert self.config is not None # mypyself.system_args = {@@ -268,7 +242,7 @@ class Agent:def add_hook(self, hook: AgentHook):hook.on_init()self.hooks.append(hook)-+def _append_history(self, item: Dict):for hook in self.hooks:hook.on_query_message_added(**item)@@ -286,14 +260,9 @@ class Agent:self.history: List[Dict[str, Any]] = []self._append_history({"role": "system", "content": system_msg, "agent": self.name})- if len(self.config.demonstrations) > 0 and "history_to_messages" in dir(- self.model- ):+ if len(self.config.demonstrations) > 0 and "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- ):+ 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")@@ -304,15 +273,12 @@ class Agent:demo_history = [entryfor entry in demo_history- if ("agent" not in entry)- or ("agent" in entry and entry["agent"] == self.name)+ 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":@@ -324,9 +290,7 @@ class Agent:demo_history,is_demonstration=True,)- demonstration = self.config.demonstration_template.format(- **{"demonstration": demo_message}- )+ demonstration = self.config.demonstration_template.format(**{"demonstration": demo_message})self._append_history({"agent": self.name,@@ -336,7 +300,6 @@ class Agent:})-@propertydef state_command(self) -> str:"""Return the bash command that will be used to extract the environment state."""@@ -345,10 +308,8 @@ class Agent:@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, log_path: Path, env_name: str, info: Dict[str, Any]):log_dict = {"environment": env_name,@@ -368,20 +329,13 @@ class Agent:patterns = {k: vfor k, v in self.command_patterns.items()- if k in self.config.multi_line_command_endings- or k == self.config.submit_command+ 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+ 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()@@ -415,9 +369,7 @@ class Agent: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- )+ guarded_command = guarded_command.replace(first_line, first_line + f" << '{eof}'", 1)parsed_action.append(guarded_command)else:parsed_action.append(match_action)@@ -437,9 +389,7 @@ class Agent: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(@@ -459,9 +409,7 @@ class Agent:})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@@ -495,15 +443,11 @@ class Agent: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._append_history(@@ -531,9 +475,7 @@ class Agent:templates: List[str] = []# 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:@@ -560,9 +502,7 @@ class Agent:message = "\n".join(messages)logger.info(f"🤖 MODEL INPUT\n{message}")- self._append_history(- {"role": "user", "content": message, "agent": self.name}- )+ self._append_history({"role": "user", "content": message, "agent": self.name})for hook in self.hooks:hook.on_model_query(query=self.local_history, agent=self.name)@@ -651,11 +591,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]:"""Wrapper around `self.forward_model` that handles errors and retries- due to format errors or blocked actions.+ due to format errors or blocked actions."""try:output = self.forward_model(observation, state)@@ -699,9 +637,7 @@ class Agent: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:raiseexcept Exception as e:@@ -755,9 +691,7 @@ class Agent:obs = Noneif env.returncode != 0:self._append_history({"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(@@ -793,9 +727,7 @@ class Agent:assert self.config is not Noneif 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@@ -807,24 +739,19 @@ class Agent:# Run action/observation looptrajectory = []info = {}- traj_log_path = traj_dir / (env.record["instance_id"] + ".traj")+ traj_log_path = traj_dir / (env.record["instance_id"] + ".traj")logger.info("Trajectory will be saved to %s", traj_log_path)while 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- )+ 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- ):+ 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"])@@ -858,10 +785,10 @@ class Agent: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)-+for hook in self.hooks:hook.on_run_done()-+logger.info("Trajectory saved to %s", traj_log_path)if return_type == "info":diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.pyindex 73d735a6..312d2305 100644--- a/sweagent/agent/commands.py+++ b/sweagent/agent/commands.py@@ -11,6 +11,7 @@ from simple_parsing.helpers.serialization.serializable import FrozenSerializable@dataclass(frozen=True)class AssistantMetadata(FrozenSerializable):"""Pass observations to the assistant, and get back a response."""+system_template: Optional[str] = Noneinstance_template: Optional[str] = None@@ -20,9 +21,10 @@ class AssistantMetadata(FrozenSerializable):@dataclass(frozen=True)class ControlMetadata(FrozenSerializable):"""TODO: should be able to control high-level control flow after calling this command"""+next_step_template: Optional[str] = Nonenext_step_action_template: Optional[str] = None-+@dataclass(frozen=True)class Command(FrozenSerializable):@@ -59,7 +61,7 @@ class ParseCommand(metaclass=ParseCommandMeta):Define how to parse a file into a list of commands."""raise NotImplementedError-+@abstractmethoddef generate_command_docs(self, commands: List[Command], subroutine_types, **kwargs) -> str:"""@@ -70,6 +72,7 @@ class ParseCommand(metaclass=ParseCommandMeta):# DEFINE NEW COMMAND PARSER FUNCTIONS BELOW THIS LINE+class ParseCommandBash(ParseCommand):def parse_command_file(self, path: str) -> List[Command]:contents = open(path, "r").read()@@ -77,24 +80,28 @@ class ParseCommandBash(ParseCommand):commands = self.parse_script(path, contents)else:if not path.endswith(".sh") and not Path(path).name.startswith("_"):- raise ValueError((- f"Source file {path} does not have a .sh extension.\n"- "Only .sh files are supported for bash function parsing.\n"- "If you want to use a non-shell file as a command (script), "- "it should use a shebang (e.g. #!/usr/bin/env python)."- ))+ raise ValueError(+ (+ f"Source file {path} does not have a .sh extension.\n"+ "Only .sh files are supported for bash function parsing.\n"+ "If you want to use a non-shell file as a command (script), "+ "it should use a shebang (e.g. #!/usr/bin/env python)."+ )+ )return self.parse_bash_functions(path, contents)if len(commands) == 0 and not Path(path).name.startswith("_"):- raise ValueError((- f"Non-shell file {path} does not contain any commands.\n"- "If you want to use a non-shell file as a command (script), "- "it should contain exactly one @yaml docstring. "- "If you want to use a file as a utility script, "- "it should start with an underscore (e.g. _utils.py)."- ))+ raise ValueError(+ (+ f"Non-shell file {path} does not contain any commands.\n"+ "If you want to use a non-shell file as a command (script), "+ "it should contain exactly one @yaml docstring. "+ "If you want to use a file as a utility script, "+ "it should start with an underscore (e.g. _utils.py)."+ )+ )else:return commands-+def parse_bash_functions(self, path, contents) -> List[Command]:"""Simple logic for parsing a bash file and segmenting it into functions.@@ -119,7 +126,7 @@ class ParseCommandBash(ParseCommand):idx += 1code += lines[idx]docstring, end_name, arguments, signature = None, None, None, name- docs_dict = yaml.safe_load("\n".join(docs).replace('@yaml', ''))+ docs_dict = yaml.safe_load("\n".join(docs).replace("@yaml", ""))if docs_dict is not None:docstring = docs_dict["docstring"]end_name = docs_dict.get("end_name", None)@@ -133,32 +140,33 @@ class ParseCommandBash(ParseCommand):signature += f" <{param}>"else:signature += f" [<{param}>]"- command = Command.from_dict({- "code": code,- "docstring": docstring,- "end_name": end_name,- "name": name,- "arguments": arguments,- "signature": signature- })+ command = Command.from_dict(+ {+ "code": code,+ "docstring": docstring,+ "end_name": end_name,+ "name": name,+ "arguments": arguments,+ "signature": signature,+ }+ )commands.append(command)docs = []return commands-+def parse_script(self, path, contents) -> List[Command]:- pattern = re.compile(r'^#\s*@yaml\s*\n^#.*(?:\n#.*)*', re.MULTILINE)+ pattern = re.compile(r"^#\s*@yaml\s*\n^#.*(?:\n#.*)*", re.MULTILINE)matches = pattern.findall(contents)if len(matches) == 0:return []elif len(matches) > 1:- raise ValueError((- "Non-shell file contains multiple @yaml tags.\n"- "Only one @yaml tag is allowed per script."- ))+ raise ValueError(+ ("Non-shell file contains multiple @yaml tags.\n" "Only one @yaml tag is allowed per script.")+ )else:yaml_content = matches[0]- yaml_content = re.sub(r'^#', '', yaml_content, flags=re.MULTILINE)- docs_dict = yaml.safe_load(yaml_content.replace('@yaml', ''))+ yaml_content = re.sub(r"^#", "", yaml_content, flags=re.MULTILINE)+ docs_dict = yaml.safe_load(yaml_content.replace("@yaml", ""))assert docs_dict is not Nonedocstring = docs_dict["docstring"]end_name = docs_dict.get("end_name", None)@@ -173,15 +181,18 @@ class ParseCommandBash(ParseCommand):else:signature += f" [<{param}>]"code = contents- return [Command.from_dict({- "code": code,- "docstring": docstring,- "end_name": end_name,- "name": name,- "arguments": arguments,- "signature": signature- })]-+ return [+ Command.from_dict(+ {+ "code": code,+ "docstring": docstring,+ "end_name": end_name,+ "name": name,+ "arguments": arguments,+ "signature": signature,+ }+ )+ ]def generate_command_docs(self, commands: List[Command], subroutine_types, **kwargs) -> str:docs = ""@@ -203,31 +214,32 @@ class ParseCommandDetailed(ParseCommandBash):# arg1 (type) [required]: "description"# arg2 (type) [optional]: "description""""+@staticmethoddef get_signature(cmd):signature = cmd.nameif "arguments" in cmd.__dict__ and cmd.arguments is not None:- if cmd.end_name is None:- for param, settings in cmd.arguments.items():- if settings["required"]:- signature += f" <{param}>"- else:- signature += f" [<{param}>]"- else:- for param, settings in list(cmd.arguments.items())[:-1]:- if settings["required"]:- signature += f" <{param}>"- else:- signature += f" [<{param}>]"- signature += f"\n{list(cmd.arguments[-1].keys())[0]}\n{cmd.end_name}"+ if cmd.end_name is None:+ for param, settings in cmd.arguments.items():+ if settings["required"]:+ signature += f" <{param}>"+ else:+ signature += f" [<{param}>]"+ else:+ for param, settings in list(cmd.arguments.items())[:-1]:+ if settings["required"]:+ signature += f" <{param}>"+ else:+ signature += f" [<{param}>]"+ signature += f"\n{list(cmd.arguments[-1].keys())[0]}\n{cmd.end_name}"return signaturedef generate_command_docs(- self,- commands: List[Command],- subroutine_types,- **kwargs,- ) -> str:+ self,+ commands: List[Command],+ subroutine_types,+ **kwargs,+ ) -> str:docs = ""for cmd in commands + subroutine_types:docs += f"{cmd.name}:\n"diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.pyindex 08215053..978862ac 100644--- a/sweagent/agent/history_processors.py+++ b/sweagent/agent/history_processors.py@@ -7,8 +7,10 @@ from dataclasses import dataclassclass FormatError(Exception):pass+# ABSTRACT BASE CLASSES+class HistoryProcessorMeta(type):_registry = {}@@ -27,7 +29,7 @@ class HistoryProcessor(metaclass=HistoryProcessorMeta):@abstractmethoddef __call__(self, history: list[str]) -> list[str]:raise NotImplementedError-+@classmethoddef get(cls, name, *args, **kwargs):try:@@ -44,16 +46,16 @@ class DefaultHistoryProcessor(HistoryProcessor):def last_n_history(history, n):if n <= 0:- raise ValueError('n must be a positive integer')+ raise ValueError("n must be a positive integer")new_history = list()- user_messages = len([entry for entry in history if (entry['role'] == 'user' and not entry.get('is_demo', False))])+ user_messages = len([entry for entry in history if (entry["role"] == "user" and not entry.get("is_demo", False))])user_msg_idx = 0for entry in history:data = entry.copy()- if data['role'] != 'user':+ if data["role"] != "user":new_history.append(entry)continue- if data.get('is_demo', False):+ if data.get("is_demo", False):new_history.append(entry)continueelse:@@ -61,7 +63,7 @@ def last_n_history(history, n):if user_msg_idx == 1 or user_msg_idx in range(user_messages - n + 1, user_messages + 1):new_history.append(entry)else:- data['content'] = f'Old output omitted ({len(entry["content"].splitlines())} lines)'+ data["content"] = f'Old output omitted ({len(entry["content"].splitlines())} lines)'new_history.append(data)return new_history@@ -69,7 +71,7 @@ def last_n_history(history, n):class LastNObservations(HistoryProcessor):def __init__(self, n):self.n = n-+def __call__(self, history):return last_n_history(history, self.n)@@ -85,8 +87,8 @@ class Last5Observations(HistoryProcessor):class ClosedWindowHistoryProcessor(HistoryProcessor):- pattern = re.compile(r'^(\d+)\:.*?(\n|$)', re.MULTILINE)- file_pattern = re.compile(r'\[File:\s+(.*)\s+\(\d+\s+lines\ total\)\]')+ pattern = re.compile(r"^(\d+)\:.*?(\n|$)", re.MULTILINE)+ file_pattern = re.compile(r"\[File:\s+(.*)\s+\(\d+\s+lines\ total\)\]")def __call__(self, history):new_history = list()@@ -96,15 +98,15 @@ class ClosedWindowHistoryProcessor(HistoryProcessor):windows = set()for entry in reversed(history):data = entry.copy()- if data['role'] != 'user':+ if data["role"] != "user":new_history.append(entry)continue- if data.get('is_demo', False):+ if data.get("is_demo", False):new_history.append(entry)continue- matches = list(self.pattern.finditer(entry['content']))+ matches = list(self.pattern.finditer(entry["content"]))if len(matches) >= 1:- file_match = self.file_pattern.search(entry['content'])+ file_match = self.file_pattern.search(entry["content"])if file_match:file = file_match.group(1)else:@@ -112,10 +114,10 @@ class ClosedWindowHistoryProcessor(HistoryProcessor):if file in windows:start = matches[0].start()end = matches[-1].end()- data['content'] = (- entry['content'][:start] +\- f'Outdated window with {len(matches)} lines omitted...\n' +\- entry['content'][end:]+ data["content"] = (+ entry["content"][:start]+ + f"Outdated window with {len(matches)} lines omitted...\n"+ + entry["content"][end:])windows.add(file)new_history.append(data)diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex add98336..255320e5 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -29,6 +29,7 @@ logger.propagate = False@dataclass(frozen=True)class ModelArguments(FrozenSerializable):"""Arguments configuring the model and its behavior."""+model_name: strper_instance_cost_limit: float = 0.0total_cost_limit: float = 0.0@@ -50,18 +51,15 @@ class APIStats(Serializable):if not isinstance(other, APIStats):raise TypeError("Can only add APIStats with APIStats")- return APIStats(**{- field.name: getattr(self, field.name) + getattr(other, field.name)- for field in fields(self)- })+ return APIStats(+ **{field.name: getattr(self, field.name) + getattr(other, field.name) for field in fields(self)}+ )+def replace(self, other):if not isinstance(other, APIStats):raise TypeError("Can only replace APIStats with APIStats")- return APIStats(**{- field.name: getattr(other, field.name)- for field in fields(self)- })+ return APIStats(**{field.name: getattr(other, field.name) for field in fields(self)})class ContextWindowExceededError(Exception):@@ -84,9 +82,7 @@ class BaseModel:# Map `model_name` to API-compatible name `api_model`self.api_model = (- self.SHORTCUTS[self.args.model_name]- if self.args.model_name in self.SHORTCUTS- else self.args.model_name+ self.SHORTCUTS[self.args.model_name] if self.args.model_name in self.SHORTCUTS else self.args.model_name)# Map model name to metadata (cost, context info)@@ -100,7 +96,7 @@ class BaseModel:ft_model = args.model_name.split(":")[1]self.model_metadata = MODELS[ft_model]elif args.model_name.startswith("ollama:"):- self.api_model = args.model_name.split('ollama:', 1)[1]+ self.api_model = args.model_name.split("ollama:", 1)[1]self.model_metadata = self.MODELS[self.api_model]elif args.model_name.startswith("azure:"):azure_model = args.model_name.split("azure:", 1)[1]@@ -109,7 +105,9 @@ class BaseModel:self.api_model = args.model_name.split("bedrock:", 1)[1]self.model_metadata = MODELS[self.api_model]else:- raise ValueError(f"Unregistered model ({args.model_name}). Add model name to MODELS metadata to {self.__class__}")+ raise ValueError(+ f"Unregistered model ({args.model_name}). Add model name to MODELS metadata to {self.__class__}"+ )def reset_stats(self, other: Optional[APIStats] = None):if other is None:@@ -156,15 +154,11 @@ class BaseModel:# Check whether total cost or instance cost limits have been exceededif 0 < self.args.total_cost_limit <= self.stats.total_cost:- logger.warning(- f"Cost {self.stats.total_cost:.2f} exceeds limit {self.args.total_cost_limit:.2f}"- )+ logger.warning(f"Cost {self.stats.total_cost:.2f} exceeds limit {self.args.total_cost_limit:.2f}")raise CostLimitExceededError("Total cost limit exceeded")if 0 < self.args.per_instance_cost_limit <= self.stats.instance_cost:- logger.warning(- f"Cost {self.stats.instance_cost:.2f} exceeds limit {self.args.per_instance_cost_limit:.2f}"- )+ logger.warning(f"Cost {self.stats.instance_cost:.2f} exceeds limit {self.args.per_instance_cost_limit:.2f}")raise CostLimitExceededError("Instance cost limit exceeded")return cost@@ -242,7 +236,11 @@ class OpenAIModel(BaseModel):cfg = Config()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"))+ 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"),+ )else:api_base_url: Optional[str] = cfg.get("OPENAI_API_BASE_URL", None)self.client = OpenAI(api_key=cfg["OPENAI_API_KEY"], base_url=api_base_url)@@ -256,12 +254,9 @@ class OpenAIModel(BaseModel):# Remove system messages if it is a demonstrationif is_demonstration:history = [entry for entry in history if entry["role"] != "system"]- return '\n'.join([entry["content"] for entry in history])+ return "\n".join([entry["content"] for entry in history])# Return history components with just role, content fields- return [- {k: v for k, v in entry.items() if k in ["role", "content"]}- for entry in history- ]+ return [{k: v for k, v in entry.items() if k in ["role", "content"]} for entry in history]@retry(wait=wait_random_exponential(min=1, max=15),@@ -408,7 +403,7 @@ class BedrockModel(BaseModel):# Extract provider from model ID# https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html- self.model_provider = self.api_model.split('.')[0]+ self.model_provider = self.api_model.split(".")[0]if self.model_provider == "anthropic":# Note: this assumes AWS credentials are already configured.# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html@@ -446,15 +441,16 @@ class BedrockModel(BaseModel):def anthropic_history_to_messages(- model: Union[AnthropicModel, BedrockModel], history: list[dict[str, str]], is_demonstration: bool = False- ) -> Union[str, list[dict[str, str]]]:+ model: Union[AnthropicModel, BedrockModel], history: list[dict[str, str]], is_demonstration: bool = False+) -> Union[str, list[dict[str, str]]]:"""Create `prompt` by filtering out all keys except for role/content per `history` turnReference: https://docs.anthropic.com/claude/reference/complete_post"""# Preserve behavior for older models- if model.api_model in ["claude-instant", "claude-2.0"] or \- (isinstance(model, BedrockModel) and model.api_model in ["anthropic.claude-instant-v1", "anthropic.claude-v2"]):+ if model.api_model in ["claude-instant", "claude-2.0"] or (+ isinstance(model, BedrockModel) and model.api_model in ["anthropic.claude-instant-v1", "anthropic.claude-v2"]+ ):# Remove system messages if it is a demonstrationif is_demonstration:history = [entry for entry in history if entry["role"] != "system"]@@ -471,15 +467,11 @@ def anthropic_history_to_messages(# Remove system messages if it is a demonstrationif is_demonstration:history = [entry for entry in history if entry["role"] != "system"]- return '\n'.join([entry["content"] for entry in history])+ return "\n".join([entry["content"] for entry in history])# Return history components with just role, content fields (no system message)messages = [- {- k: v for k, v in entry.items()- if k in ["role", "content"]- }- for entry in history if entry["role"] != "system"+ {k: v for k, v in entry.items() if k in ["role", "content"]} for entry in history if entry["role"] != "system"]compiled_messages = [] # Combine messages from the same rolelast_role = None@@ -502,8 +494,9 @@ def anthropic_query(model: Union[AnthropicModel, BedrockModel], history: list[diQuery the Anthropic API with the given `history` and return the response."""# Preserve behavior for older models- if model.api_model in ["claude-instant", "claude-2.0", "claude-2.1"] or \- (isinstance(model, BedrockModel) and model.api_model in ["anthropic.claude-instant-v1", "anthropic.claude-v2"]):+ if model.api_model in ["claude-instant", "claude-2.0", "claude-2.1"] or (+ isinstance(model, BedrockModel) and model.api_model in ["anthropic.claude-instant-v1", "anthropic.claude-v2"]+ ):# Perform Anthropic API callprompt = anthropic_history_to_messages(model, history)if isinstance(model, BedrockModel):@@ -516,7 +509,9 @@ def anthropic_query(model: Union[AnthropicModel, BedrockModel], history: list[dicompletion = model.api.completions.create(model=model.api_model,prompt=prompt,- max_tokens_to_sample=model.model_metadata["max_context"] - input_tokens if isinstance(model, Anthropic) else model.model_metadata["max_tokens_to_sample"],+ max_tokens_to_sample=model.model_metadata["max_context"] - input_tokens+ if isinstance(model, Anthropic)+ else model.model_metadata["max_tokens_to_sample"],temperature=model.args.temperature,top_p=model.args.top_p,)@@ -530,9 +525,7 @@ def anthropic_query(model: Union[AnthropicModel, BedrockModel], history: list[direturn response# Get system message(s)- system_message = "\n".join([- entry["content"] for entry in history if entry["role"] == "system"- ])+ system_message = "\n".join([entry["content"] for entry in history if entry["role"] == "system"])messages = anthropic_history_to_messages(model, history)# Perform Anthropic API call@@ -546,24 +539,24 @@ def anthropic_query(model: Union[AnthropicModel, BedrockModel], history: list[di)# Calculate + update costs, return response- model.update_stats(- response.usage.input_tokens,- response.usage.output_tokens- )+ model.update_stats(response.usage.input_tokens, response.usage.output_tokens)response = "\n".join([x.text for x in response.content])return responseclass OllamaModel(BaseModel):- MODELS = defaultdict(lambda: {- "max_context": 128_000,- "cost_per_input_token": 0,- "cost_per_output_token": 0,- })+ MODELS = defaultdict(+ lambda: {+ "max_context": 128_000,+ "cost_per_input_token": 0,+ "cost_per_output_token": 0,+ }+ )def __init__(self, args: ModelArguments, commands: list[Command]):super().__init__(args, commands)from ollama import Client+self.client = Client(host=args.host_url)def history_to_messages(@@ -575,12 +568,9 @@ class OllamaModel(BaseModel):# Remove system messages if it is a demonstrationif is_demonstration:history = [entry for entry in history if entry["role"] != "system"]- return '\n'.join([entry["content"] for entry in history])+ return "\n".join([entry["content"] for entry in history])# Return history components with just role, content fields- return [- {k: v for k, v in entry.items() if k in ["role", "content"]}- for entry in history- ]+ return [{k: v for k, v in entry.items() if k in ["role", "content"]} for entry in history]@retry(wait=wait_random_exponential(min=1, max=15),@@ -598,7 +588,7 @@ class OllamaModel(BaseModel):options={"temperature": self.args.temperature,"top_p": self.args.top_p,- }+ },)# Calculate + update costs, return responseif "prompt_eval_count" in response:@@ -657,15 +647,13 @@ class TogetherModel(BaseModel):def __init__(self, args: ModelArguments, commands: list[Command]):super().__init__(args, commands)- assert together.version >= '1.1.0', "Please upgrade to Together SDK v1.1.0 or later."+ assert together.version >= "1.1.0", "Please upgrade to Together SDK v1.1.0 or later."# Set Together keycfg = Config()together.api_key = cfg.TOGETHER_API_KEY- def history_to_messages(- self, history: list[dict[str, str]], is_demonstration: bool = False- ) -> str:+ def history_to_messages(self, history: list[dict[str, str]], is_demonstration: bool = False) -> str:"""Create `prompt` by filtering out all keys except for role/content per `history` turn"""@@ -717,9 +705,7 @@ class HumanModel(BaseModel):# Determine which commands require multi-line inputself.multi_line_command_endings = {- command.name: command.end_name- for command in commands- if command.end_name is not None+ command.name: command.end_name for command in commands if command.end_name is not None}def history_to_messages(@@ -731,12 +717,9 @@ class HumanModel(BaseModel):# Remove system messages if it is a demonstrationif is_demonstration:history = [entry for entry in history if entry["role"] != "system"]- return '\n'.join([entry["content"] for entry in history])+ return "\n".join([entry["content"] for entry in history])# Return history components with just role, content fields- return [- {k: v for k, v in entry.items() if k in ["role", "content"]}- for entry in history- ]+ return [{k: v for k, v in entry.items() if k in ["role", "content"]} for entry in history]def query(self, history: list[dict[str, str]], action_prompt: str = "> ") -> str:"""@@ -796,14 +779,9 @@ class ReplayModel(BaseModel):super().__init__(args, commands)if self.args.replay_path is None or not os.path.exists(self.args.replay_path):- raise ValueError(- "--replay_path must point to a file that exists to run a replay policy"- )+ raise ValueError("--replay_path must point to a file that exists to run a replay policy")- self.replays = [- list(json.loads(x).values())[0]- for x in open(self.args.replay_path, "r").readlines()- ]+ self.replays = [list(json.loads(x).values())[0] for x in open(self.args.replay_path, "r").readlines()]self.replay_idx = 0self.action_idx = 0@@ -856,7 +834,6 @@ class InstantEmptySubmitTestModel(BaseModel):return action-def get_model(args: ModelArguments, commands: Optional[list[Command]] = None):"""Returns correct model object given arguments and commands@@ -871,7 +848,11 @@ def get_model(args: ModelArguments, commands: Optional[list[Command]] = None):return HumanThoughtModel(args, commands)if args.model_name == "replay":return ReplayModel(args, commands)- elif args.model_name.startswith("gpt") or args.model_name.startswith("ft:gpt") or args.model_name.startswith("azure:gpt"):+ elif (+ args.model_name.startswith("gpt")+ or args.model_name.startswith("ft:gpt")+ or args.model_name.startswith("azure:gpt")+ ):return OpenAIModel(args, commands)elif args.model_name.startswith("claude"):return AnthropicModel(args, commands)diff --git a/sweagent/agent/parsing.py b/sweagent/agent/parsing.pyindex 019ca4c5..e5d2bfe3 100644--- a/sweagent/agent/parsing.py+++ b/sweagent/agent/parsing.py@@ -13,12 +13,15 @@ from typing import Listclass FormatError(Exception):pass+# ABSTRACT BASE CLASSES+class ParseFunctionMeta(type):"""Registry maps all inherited classes to their names."""+_registry = {}def __new__(cls, name, bases, attrs):@@ -26,7 +29,7 @@ class ParseFunctionMeta(type):if name != "ParseFunction":cls._registry[name] = new_clsreturn new_cls-+@dataclassclass ParseFunction(metaclass=ParseFunctionMeta):@@ -34,18 +37,19 @@ class ParseFunction(metaclass=ParseFunctionMeta):Abstract class for parsing functions.We use get to generate the right parser based on the name of the parser."""+_error_message = None@abstractmethoddef __call__(self, model_response, commands: List[Command], strict=False):raise NotImplementedError-+@propertydef format_error_template(self):if self._error_message is None:raise NotImplementedError("You must define an error message for your parser.")return textwrap.dedent(self._error_message)-+@classmethoddef get(cls, name):try:@@ -56,25 +60,27 @@ class ParseFunction(metaclass=ParseFunctionMeta):# DEFINE NEW PARSING FUNCTIONS BELOW THIS LINE+class ActionParser(ParseFunction):"""Expects the model response to be a single command.Example: "ls -l""""+_error_message = """\The command you provided was not recognized. Please specify one of the commands (+ any necessary arguments) from the following list in your response. Do not include any other text.-+COMMANDS:{command_docs}"""-+def __call__(self, model_response, commands: List[Command], strict=False):if model_response.split():action = model_response.strip().split()[0]if action in {command.name for command in commands}:return model_response, model_responseraise FormatError("First word in model response is not a valid command.")-+class ThoughtActionParser(ParseFunction):"""@@ -85,12 +91,13 @@ class ThoughtActionParser(ParseFunction):ls -l```"""+_error_message = """\Your output was not formatted correctly. You must always include one discussion and one command as part of your response. Make sure you do not have multiple discussion/command tags.Please make sure your output precisely matches the following format:DISCUSSIONDiscuss here with yourself about what your planning and what you're going to do in this step.-+```command(s) that you're going to run```@@ -109,10 +116,10 @@ class ThoughtActionParser(ParseFunction):```This is another code block.```-+In this case, only the second code block will be parsed as the action."""- code_block_pat = re.compile(r'^```(\S*)\s*\n|^```\s*$', re.MULTILINE)+ code_block_pat = re.compile(r"^```(\S*)\s*\n|^```\s*$", re.MULTILINE)stack = []last_valid_block = Nonefor match in code_block_pat.finditer(model_response):@@ -125,8 +132,8 @@ class ThoughtActionParser(ParseFunction):stack.append(match)if last_valid_block:start, end = last_valid_block- thought = model_response[:start.start()] + model_response[end.end():]- return thought, model_response[start.end():end.start()]+ thought = model_response[: start.start()] + model_response[end.end() :]+ return thought, model_response[start.end() : end.start()]raise FormatError("No action found in model response.")@@ -139,6 +146,7 @@ class XMLThoughtActionParser(ParseFunction):ls -l</command>"""+_error_message = """\Your output was not formatted correctly. You must always include one discussion and one command as part of your response. Make sure you do not have multiple discussion/command tags.Please make sure your output precisely matches the following format:@@ -163,16 +171,16 @@ class XMLThoughtActionParser(ParseFunction):if "<command>" not in model_response or "</command>" not in model_response:raise FormatError("No action found in model response.")# `action` is everything between the last <command> and </command> tags- start_action = model_response.rfind('<command>') + len('<command>') # start after the last <command> tag- end_thought = model_response.rfind('<command>') # end before the last <command> tag- end_action = model_response.rfind('</command>') # end before the last </command> tag- restart_thought = model_response.rfind('</command>') + len('</command>') # start after the last </command> tag+ start_action = model_response.rfind("<command>") + len("<command>") # start after the last <command> tag+ end_thought = model_response.rfind("<command>") # end before the last <command> tag+ end_action = model_response.rfind("</command>") # end before the last </command> tag+ restart_thought = model_response.rfind("</command>") + len("</command>") # start after the last </command> tag# `thought` is everything not in between <command> and </command> tags (includes after the last </command> tag)action = model_response[start_action:end_action]thought = model_response[:end_thought] + model_response[restart_thought:]return thought.strip(), action.strip()-+class EditFormat(ThoughtActionParser):"""@@ -184,14 +192,15 @@ class EditFormat(ThoughtActionParser):os.listdir()```"""+_error_message = """\Your output was not formatted correctly. You must wrap the replacement text in backticks (```).Please make sure your output precisely matches the following format:COMMENTSYou can write comments here about what you're going to do if you want.-+```- New window contents.+ New window contents.Make sure you copy the entire contents of the window here, with the required indentation.Make the changes to the window above directly in this window.Remember that all of the window's contents will be replaced with the contents of this window.@@ -204,10 +213,11 @@ class Identity(ParseFunction):"""This parser does not do any parsing. It just returns the model response as both the thought and action."""+_error_message = """\It seems like something went wrong with your output. Please try again."""-+def __call__(self, model_response, commands: List[Command], strict=False):"""This doesn't do any parsing. It just returns the model response as the thought and action.@@ -219,12 +229,13 @@ class JsonParser(ParseFunction):"""Expects the model response to be a JSON object."""+_error_message = """\Your output could not be parsed as JSON. Please make sure your output 1) is valid JSON and2) Includes the "thought" and "command" fields."""-+def __call__(self, model_response, commands: List[Command], strict=False):"""Parses the action from the output of the API call.@@ -245,40 +256,39 @@ class JsonParser(ParseFunction):data = json.loads(model_response)if not isinstance(data, dict):raise FormatError("Model output is not a JSON object.")-+# Check if required keys are presentrequired_keys = ["thought", "command"]for key in required_keys:if key not in data:raise FormatError(f"Key '{key}' is missing from model output.")-+# Check structure of 'command' keydata_command = data["command"]if not isinstance(data_command, dict):raise FormatError("Value of 'command' key is not a JSON object.")-+# Check if required keys are present in 'command' objectcommand_keys = ["name"]for key in command_keys:if key not in data_command:raise FormatError(f"Key '{key}' is missing from 'command' object.")-+thought = data["thought"]# Generate actioncommands_dict = {c.name: c for c in commands}command = commands_dict.get(data_command["name"])if command is None:- action = data_command['name']+ action = data_command["name"]if "arguments" in data_command:- action += " " + ' '.join(data_command["arguments"].values())+ action += " " + " ".join(data_command["arguments"].values())else:signature = command.signature- signature = signature.replace("[", "").replace("]", "")\- .replace("<", "{").replace(">", "}")+ signature = signature.replace("[", "").replace("]", "").replace("<", "{").replace(">", "}")signature_args = extract_keys(signature)command_args = {k: "" for k in signature_args}-+if "arguments" in data_command:for arg in signature_args:if arg in data_command["arguments"]:@@ -309,4 +319,4 @@ def should_quote(value, command):"""Returns True if the value should be quoted, False otherwise."""- return (isinstance(value, str) and command.end_name is None)\ No newline at end of file+ return isinstance(value, str) and command.end_name is Nonediff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.pyindex 78ce246e..fcc7b58c 100644--- a/sweagent/api/hooks.py+++ b/sweagent/api/hooks.py@@ -44,7 +44,7 @@ class WebUpdate:def up_log(self, message: str):"""Update the log"""self._emit("log_message", {"message": message})-+def up_banner(self, message: str):"""Update the banner"""self._emit("update_banner", {"message": message})@@ -100,9 +100,7 @@ class MainUpdateHook(MainHook):self._wu = wudef on_start(self):- self._wu.up_env(- message="Environment container initialized", format="text", type_="info"- )+ self._wu.up_env(message="Environment container initialized", format="text", type_="info")def on_end(self):self._wu.up_agent(message="The run has ended", format="text")diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex cdc46b94..59554e65 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -140,7 +140,7 @@ def run():print(run.environment.base_commit)model_name: str = run.agent.model.model_nameenvironment_setup = ""- environment_input_type = run.environment.environment_setup.input_type+ environment_input_type = run.environment.environment_setup.input_typeif environment_input_type == "manual":environment_setup = str(write_env_yaml(run.environment.environment_setup.manual))elif environment_input_type == "script_path":diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pyindex 3dc76c84..61325358 100644--- a/sweagent/api/utils.py+++ b/sweagent/api/utils.py@@ -14,9 +14,7 @@ def _async_raise(tid, exctype):"""if not inspect.isclass(exctype):raise TypeError("Only types can be raised (not instances)")- res = ctypes.pythonapi.PyThreadState_SetAsyncExc(- ctypes.c_long(tid), ctypes.py_object(exctype)- )+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))if res == 0:raise ValueError("invalid thread id")elif res != 1:@@ -107,7 +105,7 @@ def strip_ansi_sequences(string: str) -> str:class AttrDict(dict):- """ Dictionary subclass whose entries can be accessed by attributes (as well+ """Dictionary subclass whose entries can be accessed by attributes (as wellas normally).Author: https://stackoverflow.com/users/355230/martineau@@ -128,15 +126,15 @@ class AttrDict(dict):>>> print len(obj)0"""+def __init__(self, *args, **kwargs):super(AttrDict, self).__init__(*args, **kwargs)self.__dict__ = self@classmethoddef from_nested_dicts(cls, data):- """ Construct nested AttrDicts from nested dictionaries. """+ """Construct nested AttrDicts from nested dictionaries."""if not isinstance(data, dict):return dataelse:return cls({key: cls.from_nested_dicts(data[key]) for key in data})-diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 140dd28a..49384d32 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -33,11 +33,7 @@ from sweagent.environment.utils import (LOGGER_NAME,read_with_timeout_experimental,)-from swebench import (- get_environment_yml,- get_requirements,- MAP_VERSION_TO_INSTALL-)+from swebench import get_environment_yml, get_requirements, MAP_VERSION_TO_INSTALLfrom typing import List, Optional, Tuplefrom sweagent.utils.config import Config@@ -56,8 +52,8 @@ logger.propagate = False@dataclass(frozen=True)class EnvironmentArguments(FrozenSerializable):- """Configure data sources and setup instructions for the environment in which we solve the tasks.- """+ """Configure data sources and setup instructions for the environment in which we solve the tasks."""+# Source of issue statement/problem statement. To run over a batch of issues: Path to a data file# (`json`, `jsonl`) or directory. To run over single issue: github issue url or path to markdown file# with problem statement or problem statement as text prefixed with `text://`.@@ -66,7 +62,7 @@ class EnvironmentArguments(FrozenSerializable):split: str = "dev"# Specify a branch name or a commit hash to checkout before running the task.# Only used when running over a single problem statement/issue.- base_commit: Optional[str] = None+ base_commit: Optional[str] = Nonecontainer_name: Optional[str] = Noneinstall_environment: bool = Truetimeout: int = 35@@ -82,20 +78,15 @@ class EnvironmentArguments(FrozenSerializable):repo_path: str = ""-class EnvHook:- def on_init(self):- ...+ def on_init(self): ...++ def on_copy_repo_started(self, *, repo_type: str, repo_path: str): ...- def on_copy_repo_started(self, *, repo_type: str, repo_path: str):- ...+ def on_install_env_started(self): ...++ def on_close(self): ...- def on_install_env_started(self):- ...-- def on_close(self):- ...-class SWEEnv(gym.Env):"""Gym environment for SWE-bench. This class should handle all communication with the docker container."""@@ -130,7 +121,13 @@ class SWEEnv(gym.Env):# Load Task Instancesself.data_path = self.args.data_path- self.data = get_instances(self.data_path, self.args.base_commit, self.args.split, token=self._github_token, repo_path=self.args.repo_path)+ self.data = get_instances(+ self.data_path,+ self.args.base_commit,+ self.args.split,+ token=self._github_token,+ repo_path=self.args.repo_path,+ )#: Instance we're currently processing. Gets set in self.reset.self.record = Noneself.logger.info(f"💽 Loaded dataset from {self.data_path}")@@ -174,7 +171,9 @@ class SWEEnv(gym.Env):for hook in self.hooks:hook.on_copy_repo_started(repo_type=self.record["repo_type"], repo_path=self.record["repo"])if self.record["repo_type"] == "local":- copy_anything_to_container(self.container_obj, self.record["repo"].removeprefix("local://"), "/"+self._repo_name)+ copy_anything_to_container(+ self.container_obj, self.record["repo"].removeprefix("local://"), "/" + self._repo_name+ )self.communicate_with_handling(input=f"chown -R root:root {self._repo_name}",error_msg="Failed to change permissions on copied repository",@@ -235,7 +234,7 @@ class SWEEnv(gym.Env):cached_image = self._get_cached_task_image_name()if image_exists(cached_image):logger.info(f"Restore environment from cached image {cached_image}")- self.close() # stop current container+ self.close() # stop current containerself._init_container(cached_image=cached_image)self.communicate("export $(xargs </.env)")envs = self.communicate("env")@@ -288,21 +287,18 @@ class SWEEnv(gym.Env):system = self.communicate("uname -s").strip().lower()arch = self.communicate("uname -m").strip().lower()- if system == 'linux' and arch == 'x86_64':+ if system == "linux" and arch == "x86_64":self.communicate_with_handling(f"apt update; apt install build-essential -y",error_msg="Failed to install build-essential",timeout_duration=LONG_TIMEOUT,- )+ )# Call install environment helper function if specifiedif self.install_environment:self.install_env()# Install mypy for linting purposes- self.communicate_with_handling(- f"pip install flake8",- error_msg="Failed to install flake8 (lint library)"- )+ self.communicate_with_handling(f"pip install flake8", error_msg="Failed to install flake8 (lint library)")if self.args.cache_task_images:envs = self.communicate("env")@@ -326,13 +322,12 @@ class SWEEnv(gym.Env):with open(path_to_patch, "w") as f:f.write(self.record["test_patch"])subprocess.run(- f"docker cp {path_to_patch} {self.container_name}:/root/test.patch",- shell=True,- )+ f"docker cp {path_to_patch} {self.container_name}:/root/test.patch",+ shell=True,+ )self.communicate_with_handling(- input="git apply /root/test.patch",- error_msg="Failed to apply test patch correctly"- )+ input="git apply /root/test.patch", error_msg="Failed to apply test patch correctly"+ )os.remove(path_to_patch)def step(self, action: str) -> Tuple[Optional[str], int, bool, dict]:@@ -360,7 +355,7 @@ class SWEEnv(gym.Env):try:observation = self.communicate(input="submit")submission = self.get_submission(observation)- assert submission is not None and submission.strip() != "", AssertionError('No submission found.')+ assert submission is not None and submission.strip() != "", AssertionError("No submission found.")self.logger.info(f"Found submission: {submission}")info["exit_status"] = f"submitted ({action})"info["submission"] = submission@@ -482,16 +477,12 @@ class SWEEnv(gym.Env):image_name_sanitized = image_name.replace("/", "-")image_name_sanitized = image_name_sanitized.replace(":", "-")self.container_name = f"{image_name_sanitized}-{hash_object.hexdigest()[:10]}"- self.container, self.parent_pids = get_container(- self.container_name, image_name, persistent=self.persistent- )+ self.container, self.parent_pids = get_container(self.container_name, image_name, persistent=self.persistent)try:client = docker.from_env(timeout=600)except docker.errors.DockerException as e:if "Error while fetching server API version" in str(e):- raise RuntimeError(- "Docker is not running. Please start Docker and try again."- ) from e+ raise RuntimeError("Docker is not running. Please start Docker and try again.") from etry:self.container_obj = client.containers.get(self.container_name)except docker.errors.NotFound:@@ -538,9 +529,7 @@ class SWEEnv(gym.Env):self.container.stdin.flush()except BrokenPipeError:traceback.print_exc()- self.logger.error(- "Failed to communicate with container. Check docker logs for more information."- )+ self.logger.error("Failed to communicate with container. Check docker logs for more information.")raise RuntimeError("Failed to communicate with container")buffer, exit_code = read_with_timeout_experimental(self.container, timeout_duration)@@ -562,9 +551,7 @@ class SWEEnv(gym.Env):self.container.stdin.flush()except BrokenPipeError:traceback.print_exc()- self.logger.error(- "Failed to communicate with container. Check docker logs for more information."- )+ self.logger.error("Failed to communicate with container. Check docker logs for more information.")raise RuntimeError("Failed to communicate with container")try:buffer = read_with_timeout(self.container, self.get_pids, timeout_duration)@@ -606,7 +593,8 @@ class SWEEnv(gym.Env):if not valid:return output # shows syntax errorsoutput = self._communicate(- input, timeout_duration=timeout_duration,+ input,+ timeout_duration=timeout_duration,)self.communicate_output = outputreturn output@@ -616,9 +604,7 @@ class SWEEnv(gym.Env):self.communicate_output = ""return ""- def communicate_with_handling(- self, input: str, error_msg: str, timeout_duration=25- ) -> str:+ def communicate_with_handling(self, input: str, error_msg: str, timeout_duration=25) -> str:"""Wrapper for communicate function that raises error if return code is non-zero"""@@ -639,11 +625,7 @@ class SWEEnv(gym.Env):"""Gets list of processes running inside docker container"""- pids = (- self.container_obj.exec_run("ps -eo pid,comm --no-headers")- .output.decode()- .split("\n")- )+ pids = self.container_obj.exec_run("ps -eo pid,comm --no-headers").output.decode().split("\n")pids = [x.split() for x in pids if x]if not all_pids:pids = [x for x in pids if x[1] != "ps" and x[0] not in self.parent_pids]@@ -693,13 +675,16 @@ class SWEEnv(gym.Env):Creates conda environment and installs third party dependencies to allow code execution"""assert self.record is not None # mypy- if (self.record["problem_statement_source"] != "swe-bench" or \- self.record["repo_type"] == "local") and self.args.environment_setup is None:- logger.warning((- "install_environment is set to True, but the data path is a GitHub URL "- "without an environment config file (environment_config key/flag). "- "Skipping conda environment installation."- ))+ if (+ self.record["problem_statement_source"] != "swe-bench" or self.record["repo_type"] == "local"+ ) and self.args.environment_setup is None:+ logger.warning(+ (+ "install_environment is set to True, but the data path is a GitHub URL "+ "without an environment config file (environment_config key/flag). "+ "Skipping conda environment installation."+ )+ )returnfor hook in self.hooks:hook.on_install_env_started()@@ -718,9 +703,7 @@ class SWEEnv(gym.Env):raise ValueError("Environment config file needs to be a yaml file or shell script")else:try:- install_configs = MAP_VERSION_TO_INSTALL[self.record["repo"]][- str(self.record["version"])- ]+ install_configs = MAP_VERSION_TO_INSTALL[self.record["repo"]][str(self.record["version"])]except KeyError as e:msg = ("Tried to look up install configs in swe-bench, but failed. "@@ -729,14 +712,10 @@ class SWEEnv(gym.Env):raise ValueError(msg) from e# Create environment if does not exist yetenv_name = f"{self._repo_name}__{self.record['version']}"- env_check = self.communicate(- f"conda env list | grep {env_name}", timeout_duration=LONG_TIMEOUT- )+ env_check = self.communicate(f"conda env list | grep {env_name}", timeout_duration=LONG_TIMEOUT)if env_check.strip() == "":self.logger.info(f"{env_name} conda env not found, creating...")- packages = (- install_configs.get("packages", "")- )+ packages = install_configs.get("packages", "")if packages == "requirements.txt":# Create conda environmentself.communicate_with_handling(@@ -778,7 +757,7 @@ class SWEEnv(gym.Env):self.communicate_with_handling(f"conda env update -f {PATH_TO_ENV_YML}",error_msg="Failed to install environment.yml",- timeout_duration=LONG_TIMEOUT+ timeout_duration=LONG_TIMEOUT,)else:# Create environment + install packages@@ -800,14 +779,11 @@ class SWEEnv(gym.Env):self.communicate_with_handling(f"source activate {env_name} && pip install {' '.join(install_configs['pip_packages'])}",error_msg="Failed to install pip packages",- timeout_duration=LONG_TIMEOUT+ timeout_duration=LONG_TIMEOUT,)# Activate environment- self.communicate_with_handling(- f"conda activate {env_name}",- error_msg="Failed to activate conda environment"- )+ self.communicate_with_handling(f"conda activate {env_name}", error_msg="Failed to activate conda environment")# Install repo at base commitif install_configs.get("pre_install", False):@@ -821,9 +797,7 @@ class SWEEnv(gym.Env):if install_configs.get("install", False):install_cmd = install_configs["install"]self.communicate_with_handling(- install_cmd,- error_msg="Install command failed to execute successfully",- timeout_duration=LONG_TIMEOUT+ install_cmd, error_msg="Install command failed to execute successfully", timeout_duration=LONG_TIMEOUT)if install_configs.get("post_install", False):self.logger.info("Running post-install commands...")@@ -841,20 +815,20 @@ class SWEEnv(gym.Env):name = command["name"]contents = command["contents"]copy_file_to_container(self.container_obj, contents, f"/root/commands/{name}")- if command['type'] == "source_file":+ if command["type"] == "source_file":self.communicate_with_handling(f"source /root/commands/{name}",error_msg=(f"Failed to source {name}. If you meant to make a script,"" start the file with a shebang (e.g. #!/usr/bin/env python)."- )+ ),)- elif command['type'] == "script":+ elif command["type"] == "script":self.communicate_with_handling(f"chmod +x /root/commands/{name}",error_msg=f"Failed to chmod {name}",)- elif command['type'] == "utility":+ elif command["type"] == "utility":# nothing to do for utility scriptspasselse:@@ -878,8 +852,7 @@ class SWEEnv(gym.Env):except TimeoutError:raise RuntimeError("Failed to interrupt container")-- def open_pr(self, *, trajectory, _dry_run: bool=False):+ def open_pr(self, *, trajectory, _dry_run: bool = False):"""Create PR to repositoryArgs:@@ -953,7 +926,7 @@ class SWEEnv(gym.Env):),timeout_duration=10,)- body = (+ body = (f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "f"to close [#{issue.number}]({issue_url}) ({issue.title}).\n\nCloses #{issue.number}.")diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex 1c53461e..d62f3c99 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -24,14 +24,14 @@ from git import InvalidGitRepositoryError, RepoLOGGER_NAME = "intercode"START_UP_DELAY = 5TIMEOUT_DURATION = 25-GITHUB_ISSUE_URL_PATTERN = re.compile(r'github\.com\/(.*?)\/(.*?)\/issues\/(\d+)')-GITHUB_REPO_URL_PATTERN = re.compile(r'.*[/@]?github\.com\/([^/]+)\/([^/]+)')+GITHUB_ISSUE_URL_PATTERN = re.compile(r"github\.com\/(.*?)\/(.*?)\/issues\/(\d+)")+GITHUB_REPO_URL_PATTERN = re.compile(r".*[/@]?github\.com\/([^/]+)\/([^/]+)")logger = logging.getLogger(LOGGER_NAME)def get_data_path_name(data_path: str) -> str:- """ if data_path is a file, return the file stem+ """if data_path is a file, return the file stemelif it's a github url, return the owner__repo_name"""if data_path.startswith("text://"):@@ -75,16 +75,16 @@ def copy_file_to_container(container, contents, container_path):with tempfile.NamedTemporaryFile(delete=False) as temp_file:temp_file_name = temp_file.name# Write the string to the temporary file and ensure it's written to disk- temp_file.write(contents.encode('utf-8'))+ temp_file.write(contents.encode("utf-8"))temp_file.flush()os.fsync(temp_file.fileno())# Create a TAR archive in memory containing the temporary filewith tempfile.NamedTemporaryFile():- with open(temp_file_name, 'rb') as temp_file:+ with open(temp_file_name, "rb") as temp_file:# Prepare the TAR archivewith BytesIO() as tar_stream:- with tarfile.open(fileobj=tar_stream, mode='w') as tar:+ with tarfile.open(fileobj=tar_stream, mode="w") as tar:tar_info = tarfile.TarInfo(name=os.path.basename(container_path))tar_info.size = os.path.getsize(temp_file_name)tar.addfile(tarinfo=tar_info, fileobj=temp_file)@@ -169,12 +169,16 @@ def read_with_timeout(container, pid_func, timeout_duration):if container.poll() is not None:raise RuntimeError("Subprocess exited unexpectedly.\nCurrent buffer: {}".format(buffer.decode()))if time.time() >= end_time:- raise TimeoutError("Timeout reached while reading from subprocess.\nCurrent buffer: {}\nRunning PIDs: {}".format(buffer.decode(), pids))+ raise TimeoutError(+ "Timeout reached while reading from subprocess.\nCurrent buffer: {}\nRunning PIDs: {}".format(+ buffer.decode(), pids+ )+ )return buffer.decode()PROCESS_DONE_MARKER_START = "///PROCESS-DONE:"-PROCESS_DONE_MARKER_END= ":PROCESS-DONE///"+PROCESS_DONE_MARKER_END = ":PROCESS-DONE///"PROCESS_DONE_REGEX = re.compile(rf"{PROCESS_DONE_MARKER_START}(.+?){PROCESS_DONE_MARKER_END}")@@ -240,11 +244,7 @@ def read_with_timeout_experimental(container, timeout_duration):def get_background_pids(container_obj):- pids = (- container_obj.exec_run("ps -eo pid,comm --no-headers")- .output.decode()- .split("\n")- )+ pids = container_obj.exec_run("ps -eo pid,comm --no-headers").output.decode().split("\n")pids = [x.split() for x in pids if x]pids = [x for x in pids if x[1] not in {"ps"} and x[0] != "1"]bash_pids = [x for x in pids if x[1] == "bash"]@@ -271,14 +271,16 @@ def _get_non_persistent_container(ctr_name: str, image_name: str) -> Tuple[subprstdout=PIPE,stderr=STDOUT,text=True,- bufsize=1, # line buffered+ bufsize=1, # line buffered)time.sleep(START_UP_DELAY)# try to read output from container setup (usually an error), timeout if no outputoutput = read_with_timeout(container, lambda: list(), timeout_duration=2)if output:logger.error(f"Unexpected container setup output: {output}")- return container, {"1", } # bash PID is always 1 for non-persistent containers+ return container, {+ "1",+ } # bash PID is always 1 for non-persistent containersdef _get_persistent_container(ctr_name: str, image_name: str, persistent: bool = False) -> Tuple[subprocess.Popen, Set]:@@ -299,7 +301,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =else:container_obj = client.containers.run(image_name,- command='/bin/bash -l -m',+ command="/bin/bash -l -m",name=ctr_name,stdin_open=True,tty=True,@@ -307,7 +309,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =auto_remove=not persistent,)container_obj.start()- startup_cmd = [+ startup_cmd = ["docker","exec","-i",@@ -322,7 +324,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =stdout=PIPE,stderr=STDOUT,text=True,- bufsize=1, # line buffered+ bufsize=1, # line buffered)time.sleep(START_UP_DELAY)# try to read output from container setup (usually an error), timeout if no output@@ -337,14 +339,24 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =time.sleep(1)total_time_slept += 1bash_pids, other_pids = get_background_pids(container_obj)- if total_time_slept > 5*START_UP_DELAY:+ if total_time_slept > 5 * START_UP_DELAY:breakbash_pid = 1if len(bash_pids) == 1:bash_pid = bash_pids[0][0]elif len(bash_pids) > 1 or len(other_pids) > 0:- raise RuntimeError(f"Detected alien processes attached or running. Please ensure that no other agents are running on this container. PIDs: {bash_pids}, {other_pids}")- return container, set(map(str, [bash_pid, 1, ]))+ raise RuntimeError(+ f"Detected alien processes attached or running. Please ensure that no other agents are running on this container. PIDs: {bash_pids}, {other_pids}"+ )+ return container, set(+ map(+ str,+ [+ bash_pid,+ 1,+ ],+ )+ )def get_container(ctr_name: str, image_name: str, persistent: bool = False) -> Tuple[subprocess.Popen, Set]:@@ -384,11 +396,13 @@ def image_exists(image_name):try:client = docker.from_env()except docker.errors.DockerException as e:- docker_not_running = any((- "connection aborted" in str(e).lower(),- "connection refused" in str(e).lower(),- "error while fetching server api version" in str(e).lower(),- ))+ docker_not_running = any(+ (+ "connection aborted" in str(e).lower(),+ "connection refused" in str(e).lower(),+ "error while fetching server api version" in str(e).lower(),+ )+ )if docker_not_running:msg = ("Probably the Docker daemon is not running. Please start the Docker daemon and try again. "@@ -399,7 +413,7 @@ def image_exists(image_name):)raise RuntimeError(msg) from eraise- filterred_images = client.images.list(filters={'reference': image_name})+ filterred_images = client.images.list(filters={"reference": image_name})if len(filterred_images) == 0:return Falseelif len(filterred_images) > 1:@@ -417,7 +431,7 @@ def get_commit(api: GhApi, owner: str, repo: str, ref: Optional[str] = None):"""Get commit object from github apiArgs:- api (GhApi):+ api (GhApi):owner (str): Repo owner, e.g., "princeton-nlp"repo (str): Repo, e.g., "SWE-agent"ref (str, optional): Branch, tag or commit hash@@ -430,9 +444,7 @@ def get_commit(api: GhApi, owner: str, repo: str, ref: Optional[str] = None):return api.repos.list_commits(owner, repo)[0]--class InvalidGithubURL(ValueError):- ...+class InvalidGithubURL(ValueError): ...def parse_gh_issue_url(issue_url: str) -> Tuple[str, str, str]:@@ -465,8 +477,9 @@ def get_gh_issue_data(issue_url: str, *, token: str = ""):return api.issues.get(owner, repo, issue_number)--def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: Optional[str] = "") -> str:+def get_problem_statement_from_github_issue(+ owner: str, repo: str, issue_number: str, *, token: Optional[str] = ""+) -> str:"""Return problem statement from github issue"""api = GhApi(token=token)issue = api.issues.get(owner, repo, issue_number)@@ -488,7 +501,9 @@ class InstanceBuilder:def set_problem_statement_from_gh_issue(self, issue_url: str):owner, repo, issue_number = parse_gh_issue_url(issue_url)- self.args["problem_statement"] = get_problem_statement_from_github_issue(owner, repo, issue_number, token=self.token)+ self.args["problem_statement"] = get_problem_statement_from_github_issue(+ owner, repo, issue_number, token=self.token+ )self.args["instance_id"] = f"{owner}__{repo}-i{issue_number}"self.args["problem_statement_source"] = "online"@@ -500,7 +515,7 @@ class InstanceBuilder:self.args["instance_id"] = hashlib.sha256(self.args["problem_statement"].encode()).hexdigest()[:6]self.args["problem_statement_source"] = "local"- def set_problem_statement(self, data_path: str ):+ def set_problem_statement(self, data_path: str):"""Get problem statement for a single instance from a github issue url or apath to a markdown or text file."""@@ -521,9 +536,7 @@ class InstanceBuilder:api = GhApi(token=self.token)self.args["base_commit"] = get_commit(api, owner, repo, ref=base_commit).shaif base_commit != self.args["base_commit"]:- logger.info(- f"Base commit reference {base_commit} resolved to commit hash {self.args['base_commit']}"- )+ logger.info(f"Base commit reference {base_commit} resolved to commit hash {self.args['base_commit']}")self.args["version"] = self.args["base_commit"][:7]def set_repo_info_from_local_path(self, path: str, base_commit: Optional[str] = None):@@ -589,13 +602,13 @@ class InstanceBuilder:def get_instances(- file_path: str,- base_commit: Optional[str] = None,- split: Optional[str] = None,- token: Optional[str] = None,- *,- repo_path: str = "",- ) -> List[Dict[str, Any]]:+ file_path: str,+ base_commit: Optional[str] = None,+ split: Optional[str] = None,+ token: Optional[str] = None,+ *,+ repo_path: str = "",+) -> List[Dict[str, Any]]:"""Getter function for handling json, jsonl files@@ -605,6 +618,7 @@ def get_instances(Returns:List of instances as dictionaries"""+def instance_from_dict(instances):ib = InstanceBuilder(token=token)ib.set_from_dict(instances)@@ -617,7 +631,11 @@ def get_instances(return [instance_from_dict(x) for x in instances]# The next if statement is very brittle logic to determine if we're processing a single instance- if file_path.startswith("text://") or (Path(file_path).is_file() and Path(file_path).suffix in ['.md', '.txt']) or is_github_issue_url(file_path):+ if (+ file_path.startswith("text://")+ or (Path(file_path).is_file() and Path(file_path).suffix in [".md", ".txt"])+ or is_github_issue_url(file_path)+ ):ib = InstanceBuilder(token=token)ib.set_problem_statement(file_path)if repo_path:@@ -628,11 +646,11 @@ def get_instances(raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")return [ib.build()]-+if base_commit:msg = "base_commit must be empty if running over multiple problem statements"raise ValueError(msg)-+if repo_path:msg = "repo_path must be empty if running over multiple problem statements"raise ValueError(msg)@@ -649,7 +667,11 @@ def get_instances(pass# The next if statement is very brittle logic to determine if we're processing a single instance- if (Path(file_path).is_file() and Path(file_path).suffix in ['.md', '.txt']) or is_github_issue_url(file_path) or file_path.startswith("text://"):+ if (+ (Path(file_path).is_file() and Path(file_path).suffix in [".md", ".txt"])+ or is_github_issue_url(file_path)+ or file_path.startswith("text://")+ ):ib = InstanceBuilder(token=token)ib.set_problem_statement(file_path)if repo_path:@@ -668,7 +690,7 @@ def get_instances(if file_path.endswith(".json"):return postproc_instance_list(json.load(open(file_path)))if file_path.endswith(".jsonl"):- return postproc_instance_list([json.loads(x) for x in open(file_path, 'r').readlines()])+ return postproc_instance_list([json.loads(x) for x in open(file_path, "r").readlines()])# Attempt load from HF datasets as a last resorttry:@@ -702,13 +724,15 @@ def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token:def remove_triple_backticks(text: str) -> str:return "\n".join(line.removeprefix("```") for line in text.splitlines())+_MARKDOWN_TRAJECTORY_EMOJI_MAPPING = {"observation": "👀","response": "️🧑🚒","state": "🧠","thought": "💡",-}++def format_trajectory_markdown(trajectory: List[Dict[str, str]]):"""Format a trajectory as a markdown string for use in gh PR description."""prefix = [@@ -737,4 +761,3 @@ def format_trajectory_markdown(trajectory: List[Dict[str, str]]):"</details>",]return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)-diff --git a/sweagent/utils/config.py b/sweagent/utils/config.pyindex 095bca1a..d10ae0bc 100644--- a/sweagent/utils/config.py+++ b/sweagent/utils/config.py@@ -8,12 +8,15 @@ logger = logging.getLogger("config")class Config:- def __init__(self, ):+ def __init__(+ self,+ ):"""This wrapper class is used to load keys from environment variables or keys.cfg file.Whenever both are presents, the environment variable is used."""# Defer import to avoid circular importfrom sweagent import PACKAGE_DIR+self._keys_cfg = Nonekeys_cfg_path = PACKAGE_DIR / "keys.cfg"if keys_cfg_path.exists():@@ -23,20 +26,20 @@ class Config:raise RuntimeError(f"Error loading keys.cfg. Please check the file.") from eelse:logger.error(f"keys.cfg not found in {PACKAGE_DIR}")-+def get(self, key: str, default=None) -> Any:if key in os.environ:return os.environ[key]if self._keys_cfg is not None and key in self._keys_cfg:return self._keys_cfg[key]return default-+def __getitem__(self, key: str) -> Any:if key in os.environ:return os.environ[key]if self._keys_cfg is not None and key in self._keys_cfg:return self._keys_cfg[key]raise KeyError(f"Key {key} not found in environment or keys.cfg")-+def __contains__(self, key: str) -> bool:- return key in os.environ or (self._keys_cfg is not None and key in self._keys_cfg)\ No newline at end of file+ return key in os.environ or (self._keys_cfg is not None and key in self._keys_cfg)diff --git a/tests/conftest.py b/tests/conftest.pyindex 77113a30..c0fe47ba 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -8,7 +8,7 @@ import sweagent.environment.utils as env_utils# this is a hack and should be removed when we have a better solution_this_dir = Path(__file__).resolve().parent-root_dir = _this_dir.parent+root_dir = _this_dir.parentpackage_dir = root_dir / "sweagent"sys.path.insert(0, str(root_dir))sys.path.insert(1, str(package_dir))@@ -22,6 +22,7 @@ def test_data_path() -> Path:assert p.is_dir()return p+@fixturedef test_trajectories_path(test_data_path) -> Path:p = test_data_path / "trajectories"@@ -35,12 +36,18 @@ def test_data_sources_path(test_data_path) -> Path:assert p.is_dir()return p+@fixturedef test_trajectory_path(test_trajectories_path) -> Path:- traj = test_trajectories_path / "gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "klieret__swe-agent-test-repo-i1.traj"+ traj = (+ test_trajectories_path+ / "gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1"+ / "klieret__swe-agent-test-repo-i1.traj"+ )assert traj.exists()return traj+@fixturedef test_trajectory(test_trajectory_path):return json.loads(test_trajectory_path.read_text())diff --git a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.pyindex ec220afd..bbc4d4e1 100644--- a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py+++ b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py@@ -12,4 +12,3 @@ if __name__ == "__main__":print(division(23, 0))except ValueError as e:print(e)-diff --git a/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/patches/pydicom__pydicom-1458.patch b/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/patches/pydicom__pydicom-1458.patchindex 3c70387c..af3cae4f 100644--- a/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/patches/pydicom__pydicom-1458.patch+++ b/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/patches/pydicom__pydicom-1458.patch@@ -5,7 +5,7 @@ index 8e8d319ae..6a1221b72 100644+++ b/pydicom/pixel_data_handlers/numpy_handler.py@@ -285,9 +285,10 @@ def get_pixeldata(ds: "Dataset", read_only: bool = False) -> "np.ndarray":)-+required_elements = [- 'BitsAllocated', 'Rows', 'Columns', 'PixelRepresentation',- 'SamplesPerPixel', 'PhotometricInterpretation'diff --git a/tests/test_env.py b/tests/test_env.pyindex 0be45862..e2d35341 100644--- a/tests/test_env.py+++ b/tests/test_env.py@@ -11,7 +11,9 @@ import docker@pytest.fixture(scope="module")-def test_env_args(tmpdir_factory, ):+def test_env_args(+ tmpdir_factory,+):"""This will use a persistent container"""local_repo_path = tmpdir_factory.getbasetemp() / "swe-agent-test-repo"clone_cmd = ["git", "clone", "https://github.com/klieret/swe-agent-test-repo", local_repo_path]@@ -62,7 +64,7 @@ def test_init_swe_env_cached_task_image(test_env_args):start = time.perf_counter()with swe_env_context(test_env_args) as env:env.reset()- duration_no_cache = time.perf_counter() - start+ duration_no_cache = time.perf_counter() - startstart = time.perf_counter()# now it should be cached, so let's run againimage_prefix = None@@ -110,7 +112,9 @@ def test_execute_environment(tmp_path, test_env_args):@pytest.mark.slowdef test_open_pr(test_env_args):- test_env_args = dataclasses.replace(test_env_args, data_path="https://github.com/klieret/swe-agent-test-repo/issues/1", repo_path="")+ test_env_args = dataclasses.replace(+ test_env_args, data_path="https://github.com/klieret/swe-agent-test-repo/issues/1", repo_path=""+ )with swe_env_context(test_env_args) as env:env.reset()env.open_pr(_dry_run=True, trajectory=[])@@ -139,4 +143,4 @@ def test_communicate_old(test_env_args):def test_env_with_hook(test_env_args):with swe_env_context(test_env_args) as env:env.add_hook(EnvHook())- env.reset()\ No newline at end of file+ env.reset()diff --git a/tests/test_models.py b/tests/test_models.pyindex 4c78b061..2139dd92 100644--- a/tests/test_models.py+++ b/tests/test_models.py@@ -16,6 +16,7 @@ def openai_mock_client():return model+@pytest.fixturedef mock_together_response():return {@@ -24,12 +25,7 @@ def mock_together_response():}-TEST_HISTORY = [- {- "role": "system",- "content": "Hello, how are you?"- }-]+TEST_HISTORY = [{"role": "system", "content": "Hello, how are you?"}]def test_openai_model(openai_mock_client):@@ -43,9 +39,8 @@ def test_openai_model(openai_mock_client):@pytest.mark.parametrize("model_name", list(TogetherModel.MODELS) + list(TogetherModel.SHORTCUTS))def test_together_model(mock_together_response, model_name):- with patch("sweagent.agent.models.Config"), \- patch("sweagent.agent.models.together") as mock_together:- mock_together.version = '1.1.0'+ with patch("sweagent.agent.models.Config"), patch("sweagent.agent.models.together") as mock_together:+ mock_together.version = "1.1.0"mock_together.Complete.create.return_value = mock_together_responsemodel_args = ModelArguments(model_name)diff --git a/tests/test_packaging.py b/tests/test_packaging.pyindex d373fad8..607d8b9c 100644--- a/tests/test_packaging.py+++ b/tests/test_packaging.py@@ -2,4 +2,4 @@ from sweagent import __version__def test_version():- assert __version__.count(".") == 2\ No newline at end of file+ assert __version__.count(".") == 2diff --git a/tests/test_parsing.py b/tests/test_parsing.pyindex be690bb2..e9411c3f 100644--- a/tests/test_parsing.py+++ b/tests/test_parsing.py@@ -1,8 +1,14 @@import pytestfrom sweagent.agent.commands import Commandfrom sweagent.agent.parsing import (- FormatError, ParseFunction, ActionParser, ThoughtActionParser,- XMLThoughtActionParser, EditFormat, Identity, JsonParser+ FormatError,+ ParseFunction,+ ActionParser,+ ThoughtActionParser,+ XMLThoughtActionParser,+ EditFormat,+ Identity,+ JsonParser,)@@ -19,7 +25,7 @@ def test_parse_function_registry():def test_action_parser():parser = ActionParser()- command = Command(code='ls', name='ls')+ command = Command(code="ls", name="ls")thought, action = parser("ls -l", [command])assert thought == "ls -l"assert action == "ls -l"diff --git a/tests/test_replay.py b/tests/test_replay.pyindex 4db58088..74bea1a7 100644--- a/tests/test_replay.py+++ b/tests/test_replay.py@@ -14,7 +14,11 @@ def swe_agent_test_repo_clone(tmp_path):@pytest.fixturedef swe_agent_test_repo_traj(test_trajectories_path) -> Path:- p = test_trajectories_path / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "6e44b9__sweagenttestrepo-1c2844.traj"+ p = (+ test_trajectories_path+ / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1"+ / "6e44b9__sweagenttestrepo-1c2844.traj"+ )assert p.is_file()return p@@ -28,9 +32,11 @@ def swe_agent_test_repo_local_problem_stmt(swe_agent_test_repo_clone) -> Path:@pytest.mark.slow@pytest.mark.parametrize("problem_statement_source", ["github", "local"])-def test_model_replay_github_repo(swe_agent_test_repo_traj, problem_statement_source, swe_agent_test_repo_local_problem_stmt):+def test_model_replay_github_repo(+ swe_agent_test_repo_traj, problem_statement_source, swe_agent_test_repo_local_problem_stmt+):if problem_statement_source == "github":- data_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"+ data_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"elif problem_statement_source == "local":data_path = str(swe_agent_test_repo_local_problem_stmt)args = [@@ -50,7 +56,11 @@ def test_model_replay_github_repo(swe_agent_test_repo_traj, problem_statement_so@pytest.mark.slowdef test_model_replay_from_json(test_trajectories_path, test_data_sources_path):- traj_path = test_trajectories_path / "gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1" / "pydicom__pydicom-1458.traj"+ traj_path = (+ test_trajectories_path+ / "gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1"+ / "pydicom__pydicom-1458.traj"+ )assert traj_path.is_file()data_path = test_data_sources_path / "swe-bench-dev-easy_first_only.json"assert data_path.is_file()@@ -67,8 +77,6 @@ def test_model_replay_from_json(test_trajectories_path, test_data_sources_path):main(**vars(args), forward_args=remaining_args)--def test_run_cli_help():args = ["python",@@ -95,7 +103,7 @@ def test_model_replay_local_repo(swe_agent_test_repo_clone, swe_agent_test_repo_"--repo_path",str(local_repo_path),"--config_file",- "config/default_from_url.yaml",+ "config/default_from_url.yaml","--data_path",str(problem_statement_path),"--apply_patch",@@ -121,7 +129,7 @@ def test_exception_replay_local_dirty(swe_agent_test_repo_clone, swe_agent_test_"--repo_path",str(swe_agent_test_repo_clone),"--config_file",- "config/default_from_url.yaml",+ "config/default_from_url.yaml","--data_path",str(problem_statement_path),"--apply_patch",@@ -129,4 +137,4 @@ def test_exception_replay_local_dirty(swe_agent_test_repo_clone, swe_agent_test_]args, remaining_args = get_args(run_cmd)with pytest.raises(ValueError, match=".*dirty.*"):- main(**vars(args), forward_args=remaining_args)\ No newline at end of file+ main(**vars(args), forward_args=remaining_args)diff --git a/tests/test_run.py b/tests/test_run.pyindex 9b663ae0..53f21bd5 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -10,6 +10,7 @@ from sweagent.agent.agents import Agent, AgentArguments, AgentHookfrom sweagent.agent.models import ModelArgumentsfrom sweagent.environment.swe_env import EnvironmentArguments, SWEEnv+def test_run_cli_help():args = ["python",@@ -19,7 +20,6 @@ def test_run_cli_help():subprocess.run(args, check=True)-@pytest.fixturedef open_pr_hook_init_for_sop():hook = OpenPRHook()@@ -73,6 +73,7 @@ def test_should_open_pr_fail_locked(open_pr_hook_init_for_sop, info_dict):hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/18"assert not hook.should_open_pr(info_dict)+def test_should_open_pr_fail_has_pr(open_pr_hook_init_for_sop, info_dict):hook = open_pr_hook_init_for_sophook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/19"@@ -90,6 +91,7 @@ class RaisesExceptionHook(MainHook):def on_instance_start(self, *, index: int, instance: Dict[str, Any]):raise ValueError("test exception")+@pytest.fixturedef test_script_args():return ScriptArguments(@@ -127,17 +129,17 @@ def test_exception_raised(test_script_args):class CreateFakeLogFile(MainHook):"""Testing the skip functionality"""+def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):self._traj_dir = traj_dir(traj_dir / "args.yaml").write_text("asdf")-+def on_instance_start(self, *, index: int, instance: Dict[str, Any]):instance_id = instance["instance_id"]dct = {"info": {"exit_status": "submitted"},}(self._traj_dir / f"{instance_id}.traj").write_text(json.dumps(dct))-def test_existing_corrupted_args(test_script_args):@@ -146,7 +148,6 @@ def test_existing_corrupted_args(test_script_args):main.main()-def test_main_hook(test_script_args):main = Main(test_script_args)main.add_hook(MainHook())@@ -156,4 +157,4 @@ def test_main_hook(test_script_args):def test_agent_with_hook(test_script_args):main = Main(test_script_args)main.agent.add_hook(AgentHook())- main.main()\ No newline at end of file+ main.main()diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 8c5edb4f..bfe1aa1a 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -2,11 +2,23 @@ import hashlibimport osimport subprocessimport pytest-from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls+from sweagent.environment.utils import (+ InvalidGithubURL,+ format_trajectory_markdown,+ _MARKDOWN_TRAJECTORY_EMOJI_MAPPING,+ get_instances,+ is_github_repo_url,+ remove_triple_backticks,+ parse_gh_repo_url,+ parse_gh_issue_url,+ is_github_issue_url,+ get_associated_commit_urls,+)_TOKEN = {"token": os.environ.get("GITHUB_TOKEN", "")}+def test_format_trajectory_markdown(test_trajectory):formatted = format_trajectory_markdown(test_trajectory["trajectory"])assert formatted.startswith("<details>")@@ -65,10 +77,7 @@ def test_is_from_github_url():def test_get_associated_commit_urls():assoc = get_associated_commit_urls(- org="princeton-nlp",- repo="SWE-agent",- issue_number="41",- token=os.environ.get("GITHUB_TOKEN", "")+ org="princeton-nlp", repo="SWE-agent", issue_number="41", token=os.environ.get("GITHUB_TOKEN", ""))assert len(assoc) > 0@@ -76,8 +85,8 @@ def test_get_associated_commit_urls():def test_get_instance_gh_issue():instance = get_instances("https://github.com/klieret/swe-agent-test-repo/issues/1", **_TOKEN)[0]compare_with = {- 'repo': 'klieret/swe-agent-test-repo',- 'instance_id': 'klieret__swe-agent-test-repo-i1',+ "repo": "klieret/swe-agent-test-repo",+ "instance_id": "klieret__swe-agent-test-repo-i1","repo_type": "github",}for key in compare_with:@@ -88,7 +97,11 @@ def test_get_instance_gh_issue():def clone_repo(tmp_path, repo_url):- cmd = ["git", "clone", repo_url, ]+ cmd = [+ "git",+ "clone",+ repo_url,+ ]subprocess.run(cmd, check=True, cwd=tmp_path)@@ -97,12 +110,12 @@ def test_get_instance_gh_issue_local_repo(tmp_path):instance = get_instances(file_path="https://github.com/klieret/swe-agent-test-repo/issues/1",repo_path=str(tmp_path / "swe-agent-test-repo"),- **_TOKEN+ **_TOKEN,)[0]compare_with = {- 'repo': str(tmp_path.resolve() / "swe-agent-test-repo"),+ "repo": str(tmp_path.resolve() / "swe-agent-test-repo"),"repo_type": "local",- 'instance_id': 'klieret__swe-agent-test-repo-i1'+ "instance_id": "klieret__swe-agent-test-repo-i1",}for key in compare_with:assert instance[key] == compare_with[key]@@ -120,9 +133,9 @@ def test_get_instance_local_issue_local_repo(tmp_path):repo_path=str(tmp_path / "swe-agent-test-repo"),)[0]compare_with = {- 'repo': str(tmp_path.resolve() / "swe-agent-test-repo"),+ "repo": str(tmp_path.resolve() / "swe-agent-test-repo"),"repo_type": "local",- 'instance_id': hashlib.sha256("asdf".encode()).hexdigest()[:6],+ "instance_id": hashlib.sha256("asdf".encode()).hexdigest()[:6],"problem_statement": "asdf",}for key in compare_with:@@ -135,12 +148,12 @@ def test_get_instance_gh_issue_gh_repo(tmp_path):instance = get_instances(file_path="https://github.com/klieret/swe-agent-test-repo/issues/1",repo_path="https://github.com/princeton-nlp/SWE-agent",- **_TOKEN+ **_TOKEN,)[0]compare_with = {- 'repo': "princeton-nlp/SWE-agent",+ "repo": "princeton-nlp/SWE-agent","repo_type": "github",- 'instance_id': "klieret__swe-agent-test-repo-i1",+ "instance_id": "klieret__swe-agent-test-repo-i1",}for key in compare_with:assert instance[key] == compare_with[key]@@ -151,12 +164,10 @@ def test_get_instance_gh_issue_gh_repo(tmp_path):def test_get_instance_text_issue_gh_repo(tmp_path):instance = get_instances(- file_path="text://this is a test",- repo_path="https://github.com/princeton-nlp/SWE-agent",- **_TOKEN+ file_path="text://this is a test", repo_path="https://github.com/princeton-nlp/SWE-agent", **_TOKEN)[0]compare_with = {- 'repo': "princeton-nlp/SWE-agent",+ "repo": "princeton-nlp/SWE-agent","repo_type": "github","problem_statement": "this is a test",}@@ -170,4 +181,4 @@ def test_load_instances(test_data_path, caplog):test_data_sources = test_data_path / "data_sources"examples = list(test_data_sources.iterdir())for example in examples:- get_instances(file_path=str(example), **_TOKEN)\ No newline at end of file+ get_instances(file_path=str(example), **_TOKEN)