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]

Issue #446: Fixed calls to open without ctx manager (#469)

milaiwi47da56d94211
diff --git a/evaluation/aggregate_results.py b/evaluation/aggregate_results.py
index d5b9c1a3..5fc20fb4 100644
--- a/evaluation/aggregate_results.py
+++ b/evaluation/aggregate_results.py
@@ -123,7 +123,8 @@ def convert_experiments_to_rows(folder_name, runs_max):
costs_success = []
costs_failure = []
for x in glob.glob(os.path.join(str(folder), "*.traj")):
- traj_data = json.load(open(x))
+ with open(x) as file:
+ traj_data = json.load(file)
if "model_stats" not in traj_data["info"]:
continue
run_cost = traj_data["info"]["model_stats"]["instance_cost"]
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index d16341ae..cb52d6a5 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -5,6 +5,7 @@ import json
import os
import traceback
from collections import Counter
+from pathlib import Path
from rich import print
from swebench import (
@@ -52,7 +53,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).readlines():
+ for l in Path(pred_path_orig).read_text().splitlines(keepends=True):
pred_total += 1
p = json.loads(l)
# Exclude predictions w/ empty strings
@@ -88,7 +89,7 @@ def main(
os.remove(pred_path_temp)
# Get predictions, define log_dir
- predictions = [json.loads(l) for l in open(pred_path_orig).readlines()]
+ predictions = [json.loads(l) for l in Path(pred_path_orig).read_text().splitlines()]
log_dir = os.path.join(log_dir, directory_name)
print(f"Log directory for evaluation run: {log_dir}")
@@ -100,7 +101,8 @@ 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))
+ with open(traj_path) as f:
+ traj_data = json.load(f)
scorecard["stats"]["traj_num_steps"] = len(traj_data["trajectory"])
scorecard["stats"]["traj_action_dist"] = dict(
Counter(
diff --git a/inspector/server.py b/inspector/server.py
index fc1d1790..28c850b5 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -277,15 +277,18 @@ def main(data_path, directory, port):
data = []
if data_path is not None:
if data_path.endswith(".jsonl"):
- data = [json.loads(x) for x in open(data_path).readlines()]
+ data = [json.loads(x) for x in Path(data_path).read_text().splitlines(keepends=True)]
elif data_path.endswith(".json"):
- data = json.load(open(data_path))
+ with open(data_path) as f:
+ data = json.load(f)
elif "args.yaml" in os.listdir(directory):
- args = yaml.safe_load(open(os.path.join(directory, "args.yaml")))
+ with open(os.path.join(directory, "args.yaml")) as file:
+ args = yaml.safe_load(file)
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))
+ with open(data_path) as f:
+ data = json.load(f)
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 74e3c25f..31734335 100644
--- a/inspector/static.py
+++ b/inspector/static.py
@@ -97,11 +97,12 @@ 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"))
+ args = yaml.safe_load(Path(file_path.parent / "args.yaml").read_text())
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))
+ with open(data_path) as f:
+ data = json.load(f)
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/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.py
index f27f8773..53ed3373 100644
--- a/make_demos/convert_traj_to_demo.py
+++ b/make_demos/convert_traj_to_demo.py
@@ -58,7 +58,9 @@ def save_demo(data, file, traj_path):
def convert_traj_to_action_demo(traj_path: str, output_file: str = None, include_user: bool = False):
- traj = json.load(open(traj_path))
+ with open(traj_path) as file:
+ traj = json.load(file)
+
history = traj["history"]
action_traj = list()
admissible_roles = {"assistant", "user"} if include_user else {"assistant"}
diff --git a/run_replay.py b/run_replay.py
index ebb8c732..6bb8adb2 100644
--- a/run_replay.py
+++ b/run_replay.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
import os
from argparse import ArgumentParser
+from pathlib import Path
from typing import Any
import yaml
@@ -36,7 +37,8 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix
with open(traj_path) as f:
traj_data["history"] = yaml.safe_load(f)
else:
- traj_data = json.load(open(traj_path))
+ with open(traj_path) as file:
+ traj_data = json.load(file)
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:
@@ -45,7 +47,8 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix
# Get data_path from args.yaml
if data_path is None:
args_path = os.path.join(os.path.dirname(traj_path), "args.yaml")
- args = yaml.safe_load(open(args_path))
+ with open(args_path) as f:
+ args = yaml.safe_load(f)
data_path = args["environment"]["data_path"]
# Identify the relevant task instance and create it
@@ -63,10 +66,12 @@ 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).readlines()],
+ [json.loads(x) for x in Path(data_path).read_text().splitlines(keepends=True)],
)
elif data_path.endswith(".json"):
- replay_task_instances_path = create_task_instances_tmp_file(json.load(open(data_path)))
+ with open(data_path) as file:
+ data = json.load(file)
+ replay_task_instances_path = create_task_instances_tmp_file(data)
else:
# Assume data_path is a github url or local url
is_other = True
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 7bb96476..46d28323 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -691,7 +691,8 @@ class Agent:
command_files = list()
for file in self.config.command_files:
datum = dict()
- contents = open(file).read()
+ with open(file) as f:
+ contents = f.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 7446f100..3b47d671 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -77,7 +77,8 @@ class ParseCommand(metaclass=ParseCommandMeta):
class ParseCommandBash(ParseCommand):
def parse_command_file(self, path: str) -> list[Command]:
- contents = open(path).read()
+ with open(path) as file:
+ contents = file.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 61c8637d..b50eec51 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -5,6 +5,7 @@ import logging
import os
from collections import defaultdict
from dataclasses import dataclass, fields
+from pathlib import Path
import together
from anthropic import AI_PROMPT, HUMAN_PROMPT, Anthropic, AnthropicBedrock
@@ -807,7 +808,9 @@ class ReplayModel(BaseModel):
msg = "--replay_path must point to a file that exists to run a replay policy"
raise ValueError(msg)
- self.replays = [list(json.loads(x).values())[0] for x in open(self.args.replay_path).readlines()]
+ self.replays = [
+ list(json.loads(x).values())[0] for x in Path(self.args.replay_path).read_text().splitlines(keepends=True)
+ ]
self.replay_idx = 0
self.action_idx = 0
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 3fc4246e..c634399a 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -741,7 +741,7 @@ class SWEEnv(gym.Env):
if not script_path.is_file():
msg = f"Script not found at {script_path}"
raise FileNotFoundError(msg)
- shell_commands = Path(script_path).read_text().splitlines()
+ shell_commands = Path(script_path).read_text().splitlines(keepends=True)
for i, cmd in enumerate(shell_commands):
self.communicate_with_handling(
cmd,
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 5916a0bc..78b23148 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -701,9 +701,10 @@ def get_instances(
# If file_path is a file, load the file
if file_path.endswith(".json"):
- return postproc_instance_list(json.load(open(file_path)))
+ with open(file_path) as file:
+ return postproc_instance_list(json.load(file))
if file_path.endswith(".jsonl"):
- return postproc_instance_list([json.loads(x) for x in open(file_path).readlines()])
+ return postproc_instance_list([json.loads(x) for x in Path(file_path).read_text().splitlines(keepends=True)])
# Attempt load from HF datasets as a last resort
try: