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]
Use ruff and enable some more checks (#174)
Kilian Lieret49d34c5d7831
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 5baa3794..7236b2c7 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -13,8 +13,11 @@ repos:- id: detect-private-key- id: check-ast- - repo: https://github.com/pycqa/flake8- rev: '7.0.0' # Use the latest flake8 version or the one you prefer+ - repo: https://github.com/astral-sh/ruff-pre-commit+ rev: v0.3.5hooks:- - id: flake8- args: ['--select=F821,F822,F831,E111,E112,E113,E999,E902']+ # Run the linter.+ - id: ruff+ # Run the formatter.+ # - id: ruff-format+diff --git a/evaluation/evaluation.py b/evaluation/evaluation.pyindex 76e507b5..c480e3cc 100644--- a/evaluation/evaluation.py+++ b/evaluation/evaluation.py@@ -3,7 +3,6 @@ import jsonimport osimport traceback-from datasets import load_dataset, load_from_diskfrom collections import Counterfrom rich import printfrom swebench import (@@ -71,7 +70,6 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, timprint("✅ Finished evaluation")except Exception as e:print(f"❌ Evaluation failed: {e}\n{traceback.format_exc()}")- passprint("==================================")os.remove(pred_path_temp)diff --git a/inspector/server.py b/inspector/server.pyindex 79681798..0b0c8027 100644--- a/inspector/server.py+++ b/inspector/server.py@@ -2,7 +2,6 @@ import http.serverimport jsonimport osimport socketserver-import tracebackimport yamlfrom pathlib import Pathdiff --git a/pyproject.toml b/pyproject.tomlindex 172097b5..cb8fccb9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,3 +11,67 @@ testpaths = []xfail_strict = true+[tool.ruff]+# Exclude a variety of commonly ignored directories.+exclude = [+ ".bzr",+ ".direnv",+ ".eggs",+ ".git",+ ".git-rewrite",+ ".hg",+ ".ipynb_checkpoints",+ ".mypy_cache",+ ".nox",+ ".pants.d",+ ".pyenv",+ ".pytest_cache",+ ".pytype",+ ".ruff_cache",+ ".svn",+ ".tox",+ ".venv",+ ".vscode",+ "__pypackages__",+ "_build",+ "buck-out",+ "build",+ "dist",+ "node_modules",+ "site-packages",+ "venv",+]++# Same as Black.+line-length = 88+indent-width = 4++# Assume Python 3.8+target-version = "py38"++[tool.ruff.lint]+# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.+# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or+# McCabe complexity (`C901`) by default.+select = ["F821", "F822", "E999", "E902", "F401", "F841"]+ignore = []++# Allow fix for all enabled rules (when `--fix`) is provided.+fixable = ["ALL"]+unfixable = []++# Allow unused variables when underscore-prefixed.+dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"++[tool.ruff.format]+# Like Black, use double quotes for strings.+quote-style = "double"++# Like Black, indent with spaces, rather than tabs.+indent-style = "space"++# Like Black, respect magic trailing commas.+skip-magic-trailing-comma = false++# Like Black, automatically detect the appropriate line ending.+line-ending = "auto"diff --git a/run_replay.py b/run_replay.pyindex e15e890d..09a1d659 100644--- a/run_replay.py+++ b/run_replay.py@@ -2,7 +2,6 @@import jsonimport os-import subprocessimport yamlfrom argparse import ArgumentParserdiff --git a/sweagent/__init__.py b/sweagent/__init__.pyindex 2f44a3a3..105668cc 100644--- a/sweagent/__init__.py+++ b/sweagent/__init__.py@@ -16,4 +16,14 @@ from sweagent.environment.swe_env import (from sweagent.environment.utils import (get_data_path_name,-)\ No newline at end of file+)+++__all__ = [+ "Agent",+ "AgentArguments",+ "ModelArguments",+ "EnvironmentArguments",+ "SWEEnv",+ "get_data_path_name",+]\ No newline at end of filediff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 9079eada..4ba2ed08 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -580,7 +580,7 @@ class Agent:)except KeyboardInterrupt:raise- except FormatError as e:+ except FormatError:format_fails += 1output = self.retry_after_format_fail(output)continue@@ -606,14 +606,10 @@ class Agent:"exit_error",f"exit due to runtime error: {e}",)- except ContextWindowExceededError as e:+ except ContextWindowExceededError:logger.warning(f"Context window exceeded")- return (- "Exit due to context window",- "exit_context",- "Exit due to context window",- )- except CostLimitExceededError as e:+ return "Exit due to context window", "exit_context", "Exit due to context window"+ except CostLimitExceededError:logger.warning(f"Cost limit exceeded")return "Exit due to cost limit", "exit_cost", "Exit due to cost limit"except RetryError as e:diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 8660741a..511c9cf5 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -266,8 +266,8 @@ class OpenAIModel(BaseModel):temperature=self.args.temperature,top_p=self.args.top_p,)- except BadRequestError as e:- raise CostLimitExceededError(f"Context window ({self.model_metadata['max_context']} tokens) exceeded") from e+ except BadRequestError:+ raise CostLimitExceededError(f"Context window ({self.model_metadata['max_context']} tokens) exceeded")# Calculate + update costs, return responseinput_tokens = response.usage.prompt_tokensoutput_tokens = response.usage.completion_tokensdiff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 4db412a5..4a923d18 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -303,7 +303,7 @@ class SWEEnv(gym.Env):logger.error(f"Broken pipe error: {e}\nRESTARTING PROCESS.")self.reset_container()return observation, 0, True, info- except Exception as e:+ except Exception:observation += "\nEXECUTION FAILED OR COMMAND MALFORMED"# Record submission and end episode if `submit` keyword founddiff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex 3d679909..b1582a64 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -17,7 +17,7 @@ from ghapi.all import GhApifrom io import BytesIOfrom pathlib import Pathfrom subprocess import PIPE, STDOUT-from typing import Any, List, Set, Tuple, Dict+from typing import List, Set, Tuple, DictLOGGER_NAME = "intercode"START_UP_DELAY = 5@@ -65,7 +65,7 @@ def copy_file_to_container(container, contents, container_path):os.fsync(temp_file.fileno())# Create a TAR archive in memory containing the temporary file- with tempfile.NamedTemporaryFile() as temp_tar:+ with tempfile.NamedTemporaryFile():with open(temp_file_name, 'rb') as temp_file:# Prepare the TAR archivewith BytesIO() as tar_stream:@@ -457,4 +457,4 @@ def format_trajectory_markdown(trajectory: List[Dict[str, str]]):"","</details>",]- return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)\ No newline at end of file+ return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)diff --git a/tests/test_models.py b/tests/test_models.pyindex 8ae84a60..bae67771 100644--- a/tests/test_models.py+++ b/tests/test_models.py@@ -1,6 +1,5 @@-from tkinter.filedialog import Openfrom unittest.mock import MagicMock, Mock, patch-from sweagent.agent.models import OpenAIModel, ModelArguments, AnthropicModel+from sweagent.agent.models import OpenAIModel, ModelArgumentsimport pytest