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]

CI: Add pyupgrade via ruff

Kilian Lieret3809c51ac371
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index 68816539..3952121d 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -51,7 +51,7 @@ def main(
pred_total, pred_will_eval = 0, 0
with open(pred_path_temp, "w") as f:
- for l in open(pred_path_orig, "r").readlines():
+ for l in open(pred_path_orig).readlines():
pred_total += 1
p = json.loads(l)
# Exclude predictions w/ empty strings
@@ -87,7 +87,7 @@ def main(
os.remove(pred_path_temp)
# Get predictions, define log_dir
- predictions = [json.loads(l) for l in open(pred_path_orig, "r").readlines()]
+ predictions = [json.loads(l) for l in open(pred_path_orig).readlines()]
log_dir = os.path.join(log_dir, directory_name)
print(f"Log directory for evaluation run: {log_dir}")
@@ -99,7 +99,7 @@ def main(
# Add trajectory statistics if traj_path exists
traj_path = os.path.join(directory, f"{p[KEY_INSTANCE_ID]}.traj")
if os.path.exists(traj_path):
- traj_data = json.load(open(traj_path, "r"))
+ traj_data = json.load(open(traj_path))
scorecard["stats"]["traj_num_steps"] = len(traj_data["trajectory"])
scorecard["stats"]["traj_action_dist"] = dict(
Counter(
@@ -136,7 +136,7 @@ def main(
continue
scorecard["statuses"].append("applied")
- with open(log_path, "r") as f:
+ with open(log_path) as f:
log_contents = f.read()
if INSTALL_FAIL in log_contents:
scorecard["statuses"].append("install_fail")
diff --git a/inspector/server.py b/inspector/server.py
index 92cb177e..9b5dd3d9 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -285,7 +285,7 @@ def main(data_path, directory, port):
if "environment" in args and "data_path" in args["environment"]:
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"))
+ data = json.load(open(data_path))
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}
diff --git a/inspector/static.py b/inspector/static.py
index 0f88fee4..7ca57aaf 100644
--- a/inspector/static.py
+++ b/inspector/static.py
@@ -37,7 +37,7 @@ TEMPLATE = """
"""
try:
- with open(Path(__file__).parent / "style.css", "r") as infile:
+ with open(Path(__file__).parent / "style.css") as infile:
STYLE_SHEET = infile.read()
except Exception as e:
style_file = Path(__file__).parent / "style.css"
@@ -97,11 +97,11 @@ def save_static_viewer(file_path):
file_path = Path(file_path)
data = []
if "args.yaml" in list(map(lambda x: x.name, file_path.parent.iterdir())):
- args = yaml.safe_load(open(file_path.parent / "args.yaml", "r"))
+ args = yaml.safe_load(open(file_path.parent / "args.yaml"))
if "environment" in args and "data_path" in args["environment"]:
data_path = Path(__file__).parent.parent / args["environment"]["data_path"]
if data_path.exists():
- data = json.load(open(data_path, "r"))
+ data = json.load(open(data_path))
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}
diff --git a/pyproject.toml b/pyproject.toml
index 4d05973c..1922d829 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -115,7 +115,17 @@ target-version = "py39"
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
# I001: Isort, I002: required import
-select = ["F821", "F822", "E999", "E902", "F401", "F841", "I001", "I002"]
+select = [
+ "F821", "F822", "E999", "E902", "F401", "F841", "I001", "I002",
+ "UP", # pyupgrade
+ "C401", # flake8-comprehensions: unnecessary-generator-set
+ "C402", # flake8-comprehensions: unnecessary-generator-dict
+ "C403", # flake8-comprehensions: unnecessary-list-comprehension-set
+ "C404", # flake8-comprehensions: unnecessary-list-comprehension-dict
+ "C405", # flake8-comprehensions: unnecessary-literal-set
+ "F632", # pyflakes: is-literal
+ "W605", # pycodestyle: invalid-escape-sequence
+]
ignore = []
# Allow fix for all enabled rules (when `--fix`) is provided.
diff --git a/run_replay.py b/run_replay.py
index 89463b65..7ac3a717 100644
--- a/run_replay.py
+++ b/run_replay.py
@@ -33,10 +33,10 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix
# Open trajectory file, extract responses as actions
if traj_path.endswith(".yaml"):
traj_data = dict()
- with open(traj_path, "r") as f:
+ with open(traj_path) as f:
traj_data["history"] = yaml.safe_load(f)
else:
- traj_data = json.load(open(traj_path, "r"))
+ traj_data = json.load(open(traj_path))
actions = [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:
@@ -63,7 +63,7 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix
is_other = False
if data_path.endswith(".jsonl"):
replay_task_instances_path = create_task_instances_tmp_file(
- [json.loads(x) for x in open(data_path, "r").readlines()]
+ [json.loads(x) for x in open(data_path).readlines()]
)
elif data_path.endswith(".json"):
replay_task_instances_path = create_task_instances_tmp_file(json.load(open(data_path)))
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index d43975fe..bd2026fb 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -272,7 +272,7 @@ class Agent:
# Load history
logger.info(f"DEMONSTRATION: {demonstration_path}")
- demo_history = json.load(open(demonstration_path, "r"))["history"]
+ demo_history = json.load(open(demonstration_path))["history"]
demo_history = [
entry
for entry in demo_history
@@ -649,7 +649,7 @@ class Agent:
command_files = list()
for file in self.config.command_files:
datum = dict()
- contents = open(file, "r").read()
+ contents = open(file).read()
datum["contents"] = contents
filename = Path(file).name
if not contents.strip().startswith("#!"):
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index c8e0b2e3..bc6c2f86 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -76,7 +76,7 @@ class ParseCommand(metaclass=ParseCommandMeta):
class ParseCommandBash(ParseCommand):
def parse_command_file(self, path: str) -> list[Command]:
- contents = open(path, "r").read()
+ contents = open(path).read()
if contents.strip().startswith("#!"):
commands = self.parse_script(path, contents)
else:
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 8c511a3e..d43f9082 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -783,7 +783,7 @@ class ReplayModel(BaseModel):
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")
- 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).readlines()]
self.replay_idx = 0
self.action_idx = 0
diff --git a/sweagent/api/utils.py b/sweagent/api/utils.py
index 5a47a004..cdc7f94b 100644
--- a/sweagent/api/utils.py
+++ b/sweagent/api/utils.py
@@ -130,7 +130,7 @@ class AttrDict(dict):
"""
def __init__(self, *args, **kwargs):
- super(AttrDict, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self.__dict__ = self
@classmethod
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 966e753c..936a67e7 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -169,12 +169,10 @@ def read_with_timeout(container, pid_func, timeout_duration):
time.sleep(0.05) # Prevents CPU hogging
if container.poll() is not None:
- raise RuntimeError("Subprocess exited unexpectedly.\nCurrent buffer: {}".format(buffer.decode()))
+ raise RuntimeError(f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}")
if time.time() >= end_time:
raise TimeoutError(
- "Timeout reached while reading from subprocess.\nCurrent buffer: {}\nRunning PIDs: {}".format(
- buffer.decode(), pids
- )
+ f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}\nRunning PIDs: {pids}"
)
return buffer.decode()
@@ -232,9 +230,9 @@ def read_with_timeout_experimental(container, timeout_duration):
time.sleep(0.01) # Prevents CPU hogging
if container.poll() is not None:
- raise RuntimeError("Subprocess exited unexpectedly.\nCurrent buffer: {}".format(buffer.decode()))
+ raise RuntimeError(f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}")
if time.time() >= end_time:
- raise TimeoutError("Timeout reached while reading from subprocess.\nCurrent buffer: {}".format(buffer.decode()))
+ raise TimeoutError(f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}")
decoded = buffer.decode()
body = "\n".join(line for line in decoded.splitlines() if not line.startswith(PROCESS_DONE_MARKER_START))
last_line = decoded.splitlines()[-1]
@@ -690,7 +688,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).readlines()])
# Attempt load from HF datasets as a last resort
try:
diff --git a/tests/test_replay.py b/tests/test_replay.py
index da2c5b1b..a72eea8c 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -53,7 +53,7 @@ def test_model_replay_github_repo(
"--raise_exceptions",
]
if problem_statement_source == "local":
- args.extend(["--repo_path", str("https://github.com/klieret/swe-agent-test-repo/")])
+ args.extend(["--repo_path", "https://github.com/klieret/swe-agent-test-repo/"])
args, remaining_args = get_args(args)
main(**vars(args), forward_args=remaining_args)