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]

Use ruff and enable some more checks (#174)

Kilian Lieret49d34c5d7831
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 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.5
hooks:
- - 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.py
index 76e507b5..c480e3cc 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -3,7 +3,6 @@ import json
import os
import traceback
-from datasets import load_dataset, load_from_disk
from collections import Counter
from rich import print
from swebench import (
@@ -71,7 +70,6 @@ def main(predictions_path, log_dir, swe_bench_tasks, testbed, skip_existing, tim
print("✅ Finished evaluation")
except Exception as e:
print(f"❌ Evaluation failed: {e}\n{traceback.format_exc()}")
- pass
print("==================================")
os.remove(pred_path_temp)
diff --git a/inspector/server.py b/inspector/server.py
index 79681798..0b0c8027 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -2,7 +2,6 @@ import http.server
import json
import os
import socketserver
-import traceback
import yaml
from pathlib import Path
diff --git a/pyproject.toml b/pyproject.toml
index 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.py
index e15e890d..09a1d659 100644
--- a/run_replay.py
+++ b/run_replay.py
@@ -2,7 +2,6 @@
import json
import os
-import subprocess
import yaml
from argparse import ArgumentParser
diff --git a/sweagent/__init__.py b/sweagent/__init__.py
index 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 file
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 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 += 1
output = 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.py
index 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 response
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 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 found
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 3d679909..b1582a64 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -17,7 +17,7 @@ from ghapi.all import GhApi
from io import BytesIO
from pathlib import Path
from subprocess import PIPE, STDOUT
-from typing import Any, List, Set, Tuple, Dict
+from typing import List, Set, Tuple, Dict
LOGGER_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 archive
with 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.py
index 8ae84a60..bae67771 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -1,6 +1,5 @@
-from tkinter.filedialog import Open
from unittest.mock import MagicMock, Mock, patch
-from sweagent.agent.models import OpenAIModel, ModelArguments, AnthropicModel
+from sweagent.agent.models import OpenAIModel, ModelArguments
import pytest