Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

Add more fixable ruff checks

Kilian Lieretd861a8b1f371
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index 3952121d..fedfac04 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -177,7 +177,7 @@ def main(
print(f"- Wrote per-instance scorecards to {path_scorecards}")
# Get results and write to file
- print(f"Reference Report:")
+ print("Reference Report:")
report = get_model_report(directory_name, pred_path_orig, swe_bench_tasks, log_dir)
for k, v in report.items():
print(f"- {k}: {len(v)}")
diff --git a/inspector/server.py b/inspector/server.py
index 9b5dd3d9..95d4e22e 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -69,7 +69,7 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_
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"
- stats.append(f"**** Run Stats ****")
+ stats.append("**** Run Stats ****")
stats.append(f"Instance Cost: ${instance_cost}")
stats.append(f"Tokens Sent: {tokens_sent}")
stats.append(f"Tokens Received: {tokens_received}")
diff --git a/pyproject.toml b/pyproject.toml
index 1922d829..2a56bb8a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -116,7 +116,23 @@ target-version = "py39"
# McCabe complexity (`C901`) by default.
# I001: Isort, I002: required import
select = [
- "F821", "F822", "E999", "E902", "F401", "F841", "I001", "I002",
+ "E999",
+ "E902",
+ # pycodestyle
+ "E713", # not in
+ "E714", # is not
+ "E711", # comparison with None
+ # pyflakes
+ "F821",
+ "F822",
+ "F401", # unused-import
+ "F841", # unused var
+ "F541", # f-string without args
+ "F901", # raise NotImplemented should be raise NotImplementedError
+ # isort
+ "I001", # isort
+ "I002", # required import
+ # pyupgrade and related
"UP", # pyupgrade
"C401", # flake8-comprehensions: unnecessary-generator-set
"C402", # flake8-comprehensions: unnecessary-generator-dict
@@ -125,6 +141,9 @@ select = [
"C405", # flake8-comprehensions: unnecessary-literal-set
"F632", # pyflakes: is-literal
"W605", # pycodestyle: invalid-escape-sequence
+ # bugbear
+ "B006", # mutable default
+ "B007", # unused loop var
]
ignore = []
diff --git a/run.py b/run.py
index 05e1f986..a2cfddec 100644
--- a/run.py
+++ b/run.py
@@ -209,12 +209,12 @@ class SaveApplyPatchHook(MainHook):
console.print(panel)
content = [
"```bash",
- f"# The patch has been saved to your local filesystem at:",
+ "# The patch has been saved to your local filesystem at:",
f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
"# Inspect it:",
'cat "${PATCH_FILE_PATH}"',
"# Apply it to a local repository:",
- f"cd <your local repo root>",
+ "cd <your local repo root>",
'git apply "${PATCH_FILE_PATH}"',
"```",
]
@@ -385,7 +385,7 @@ class Main:
self.env.close()
break
except SystemExit:
- logger.critical(f"❌ Exiting because SystemExit was called")
+ logger.critical("❌ Exiting because SystemExit was called")
self.env.close()
logger.info("Container closed")
raise
@@ -397,7 +397,7 @@ class Main:
if self.env.record:
logger.warning(f"❌ Failed on {self.env.record['instance_id']}: {e}")
else:
- logger.warning(f"❌ Failed on unknown instance")
+ logger.warning("❌ Failed on unknown instance")
self.env.reset_container()
continue
for hook in self.hooks:
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index bd2026fb..ea31e96f 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -342,7 +342,7 @@ class Agent:
else:
raise ValueError(f"Unknown pattern type: {pattern_type}")
matches = list()
- for name, pat in patterns.items():
+ for _, pat in patterns.items():
match = pat.search(action)
if match:
matches.append(match)
@@ -610,10 +610,10 @@ class Agent:
f"exit due to runtime error: {e}",
)
except ContextWindowExceededError:
- logger.warning(f"Context window exceeded")
+ logger.warning("Context window exceeded")
return "Exit due to context window", "exit_context", "Exit due to context window"
except CostLimitExceededError:
- logger.warning(f"Cost limit exceeded")
+ logger.warning("Cost limit exceeded")
return "Exit due to cost limit", "exit_cost", "Exit due to cost limit"
except RetryError as e:
logger.warning(f"Retry error: {e}")
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 8c71e9ed..44833df1 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -194,7 +194,7 @@ class SWEEnv(gym.Env):
)
return self._repo_name
else:
- logger.info(f"Trying to clone from non-mirror...")
+ logger.info("Trying to clone from non-mirror...")
self.communicate_with_handling(
input=f"git clone https://{token_prefix}github.com/{self.record['repo']}.git {self._repo_name}",
error_msg="Failed to clone repository from non-mirror",
@@ -290,7 +290,7 @@ class SWEEnv(gym.Env):
arch = self.communicate("uname -m").strip().lower()
if system == "linux" and arch == "x86_64":
self.communicate_with_handling(
- f"apt update; apt install build-essential -y",
+ "apt update; apt install build-essential -y",
error_msg="Failed to install build-essential",
timeout_duration=LONG_TIMEOUT,
)
@@ -299,7 +299,7 @@ class SWEEnv(gym.Env):
if 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("pip install flake8", error_msg="Failed to install flake8 (lint library)")
if self.args.cache_task_images:
envs = self.communicate("env")
@@ -865,12 +865,12 @@ class SWEEnv(gym.Env):
try:
issue = get_gh_issue_data(issue_url, token=self._github_token)
except InvalidGithubURL as e:
- msg = f"Data path must be a github issue URL if --open_pr is set."
+ msg = "Data path must be a github issue URL if --open_pr is set."
raise ValueError(msg) from e
branch_name = f"swe-agent-fix-#{issue.number}-" + str(random.random())[2:10]
self.communicate_with_handling(
- input=f"rm -f model.patch",
+ input="rm -f model.patch",
error_msg="Failed to remove model patch",
timeout_duration=10,
)
@@ -880,7 +880,7 @@ class SWEEnv(gym.Env):
timeout_duration=10,
)
self.communicate_with_handling(
- input=f"git add .",
+ input="git add .",
error_msg="Failed to add commits",
timeout_duration=10,
)
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 936a67e7..21ca5859 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -264,7 +264,7 @@ def _get_non_persistent_container(ctr_name: str, image_name: str) -> tuple[subpr
"/bin/bash",
"-l",
]
- logger.debug(f"Starting container with command: %s", shlex.join(startup_cmd))
+ logger.debug("Starting container with command: %s", shlex.join(startup_cmd))
container = subprocess.Popen(
startup_cmd,
stdin=PIPE,
@@ -317,7 +317,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =
"/bin/bash",
"-l",
]
- logger.debug(f"Starting container with command: %s", shlex.join(startup_cmd))
+ logger.debug("Starting container with command: %s", shlex.join(startup_cmd))
container = subprocess.Popen(
startup_cmd,
stdin=PIPE,
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index 079dd5e7..a25e2bb1 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -25,7 +25,7 @@ class Config:
try:
self._keys_cfg = config_file.Config(PACKAGE_DIR / "keys.cfg")
except Exception as e:
- raise RuntimeError(f"Error loading keys.cfg. Please check the file.") from e
+ raise RuntimeError("Error loading keys.cfg. Please check the file.") from e
else:
logger.error(f"keys.cfg not found in {PACKAGE_DIR}")