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]

Format: Use trailing commas

Kilian Lieret83988093c08a
diff --git a/evaluation/aggregate_results.py b/evaluation/aggregate_results.py
index 6923b326..d5b9c1a3 100644
--- a/evaluation/aggregate_results.py
+++ b/evaluation/aggregate_results.py
@@ -153,7 +153,7 @@ def convert_experiments_to_rows(folder_name, runs_max):
costs_success,
costs_failure,
costs_overall,
- ]
+ ],
)
return rows
@@ -194,7 +194,7 @@ if __name__ == "__main__":
"Costs Success": lambda x: np.mean([item for sublist in x for item in sublist]),
"Costs Failure": lambda x: np.mean([item for sublist in x for item in sublist]),
"Costs Overall": lambda x: np.mean([item for sublist in x for item in sublist]),
- }
+ },
)
.round(2)
.reset_index()
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index dc5354fa..d16341ae 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -62,7 +62,7 @@ def main(
f.write("\n")
pred_will_eval += 1
print(
- f"Found {pred_total} total predictions, will evaluate {pred_will_eval} ({pred_total-pred_will_eval} are empty)"
+ f"Found {pred_total} total predictions, will evaluate {pred_will_eval} ({pred_total-pred_will_eval} are empty)",
)
# Run evaluation
@@ -109,8 +109,8 @@ def main(
if entry["role"] == "assistant" and "action" in entry and len(entry["action"]) > 0
else None
for entry in traj_data["history"]
- ]
- )
+ ],
+ ),
)
scorecard["exit_status"] = traj_data["info"]["exit_status"] if "exit_status" in traj_data["info"] else "n/a"
diff --git a/inspector/server.py b/inspector/server.py
index a83bae3b..4fb55d83 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -29,7 +29,7 @@ def append_exit(content):
{
"role": "model_patch",
"content": submission,
- }
+ },
)
# else submission should be in history already
else:
@@ -50,7 +50,7 @@ def append_patch(instance_id, content, patches, patch_type):
{
"role": f"{patch_type} Patch",
"content": patches[instance_id],
- }
+ },
)
return content
@@ -86,15 +86,15 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_
status.append("**** Statuses ****")
status.append(
f" {'✅' if is_generated else '❌'} Generated (The agent was {'' if is_generated else 'not '}"
- "able to generate a pull request to address this issue)"
+ "able to generate a pull request to address this issue)",
)
status.append(
f" {'✅' if is_applied else '❌'} Applied (The pull request was {'' if is_applied else 'not '}"
- "successfully applied to the repo during eval)"
+ "successfully applied to the repo during eval)",
)
status.append(
f" {'✅' if is_resolved else '❌'} Resolved (The pull request {'' if is_resolved else 'not '}"
- "successfully resolved the issue during eval)"
+ "successfully resolved the issue during eval)",
)
else:
status.append("Results format not recognized")
@@ -122,7 +122,7 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_
else:
status.append("---------------------------")
status.append(
- "Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself."
+ "Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself.",
)
status.append(f"Check {results_file} for the most accurate evaluation results.")
status.append("")
diff --git a/inspector/static.py b/inspector/static.py
index 10132484..74e3c25f 100644
--- a/inspector/static.py
+++ b/inspector/static.py
@@ -111,7 +111,8 @@ def save_static_viewer(file_path):
icons_path = Path(__file__).parent / "icons"
relative_icons_path = find_relative_path(file_path, icons_path)
style_sheet = STYLE_SHEET.replace("url('icons/", f"url('{relative_icons_path.as_posix()}/").replace(
- 'url("icons/', f'url("{relative_icons_path.as_posix()}/'
+ 'url("icons/',
+ f'url("{relative_icons_path.as_posix()}/',
)
data = TEMPLATE.format(file_content=content, style_sheet=style_sheet, file_path_tree=file_path_tree)
output_file = file_path.with_suffix(".html")
diff --git a/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.py
index 41899660..f27f8773 100644
--- a/make_demos/convert_traj_to_demo.py
+++ b/make_demos/convert_traj_to_demo.py
@@ -98,7 +98,11 @@ if __name__ == "__main__":
parser.add_argument("--suffix", type=str, help="Suffix for the output file", default="")
parser.add_argument("--overwrite", type=string2bool, help="Overwrite existing files", default=False, nargs="?")
parser.add_argument(
- "--include_user", type=string2bool, help="Include user responses (computer)", default=False, nargs="?"
+ "--include_user",
+ type=string2bool,
+ help="Include user responses (computer)",
+ default=False,
+ nargs="?",
)
args = parser.parse_args()
main(**vars(args))
diff --git a/pyproject.toml b/pyproject.toml
index f188d547..5e14137c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -157,6 +157,8 @@ select = [
"RET",
# RUF
"RUF019", # unneded key in dict check
+ # other
+ "COM812", # use trailing commas
]
ignore = [
# flake8-return
diff --git a/run.py b/run.py
index a21ae63c..5b0d0953 100644
--- a/run.py
+++ b/run.py
@@ -305,7 +305,7 @@ class OpenPRHook(MainHook):
logger.warning(
"Proceeding with PR creation even though there are already commits "
f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
- "or after verifying that the existing commits do not fix the issue."
+ "or after verifying that the existing commits do not fix the issue.",
)
return True
diff --git a/run_replay.py b/run_replay.py
index 7ac3a717..ebb8c732 100644
--- a/run_replay.py
+++ b/run_replay.py
@@ -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).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 4e4c3113..9513b4c8 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -221,7 +221,14 @@ class AgentHook:
...
def on_query_message_added(
- self, *, role: str, content: str, agent: str, is_demo: bool = False, thought: str = "", action: str = ""
+ self,
+ *,
+ role: str,
+ content: str,
+ agent: str,
+ is_demo: bool = False,
+ thought: str = "",
+ action: str = "",
): ...
@@ -300,7 +307,7 @@ class Agent:
"content": demonstration,
"is_demo": True,
"role": "user",
- }
+ },
)
@property
@@ -401,7 +408,7 @@ class Agent:
"agent": self.name,
"action": match_action,
"cmd_name": first_match.group(1),
- }
+ },
) # submit command is not a subroutine
else:
parsed_action.append(
@@ -410,7 +417,7 @@ class Agent:
"args": first_match.group(2),
"action": match_action,
"cmd_name": first_match.group(1),
- }
+ },
)
else:
parsed_action.append({"agent": self.name, "action": rem_action, "cmd_name": None})
@@ -461,7 +468,7 @@ class Agent:
"thought": thought,
"action": action,
"agent": self.name,
- }
+ },
)
logger.info(f"💭 THOUGHT ({self.name})\n{thought}")
@@ -500,7 +507,7 @@ class Agent:
**self.system_args,
**state_vars,
observation=(observation if observation is not None else ""),
- )
+ ),
)
message = "\n".join(messages)
@@ -781,7 +788,7 @@ class Agent:
"response": output,
"state": state,
"thought": thought,
- }
+ },
)
trajectory.append(trajectory_step)
model_stats: APIStats = self.model.stats
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index 67399566..d8c3ffbb 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -148,7 +148,7 @@ class ParseCommandBash(ParseCommand):
"name": name,
"arguments": arguments,
"signature": signature,
- }
+ },
)
commands.append(command)
docs = []
@@ -189,8 +189,8 @@ class ParseCommandBash(ParseCommand):
"name": name,
"arguments": arguments,
"signature": signature,
- }
- )
+ },
+ ),
]
def generate_command_docs(self, commands: list[Command], subroutine_types, **kwargs) -> str:
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 783db4d2..48820f1b 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -55,7 +55,7 @@ class APIStats(Serializable):
raise TypeError(msg)
return APIStats(
- **{field.name: getattr(self, field.name) + getattr(other, field.name) for field in fields(self)}
+ **{field.name: getattr(self, field.name) + getattr(other, field.name) for field in fields(self)},
)
def replace(self, other):
@@ -146,13 +146,13 @@ class BaseModel:
f"input_tokens={input_tokens:,}, "
f"output_tokens={output_tokens:,}, "
f"instance_cost={self.stats.instance_cost:.2f}, "
- f"cost={cost:.2f}"
+ f"cost={cost:.2f}",
)
logger.info(
f"total_tokens_sent={self.stats.tokens_sent:,}, "
f"total_tokens_received={self.stats.tokens_received:,}, "
f"total_cost={self.stats.total_cost:.2f}, "
- f"total_api_calls={self.stats.api_calls:,}"
+ f"total_api_calls={self.stats.api_calls:,}",
)
# Check whether total cost or instance cost limits have been exceeded
@@ -252,7 +252,9 @@ class OpenAIModel(BaseModel):
self.client = OpenAI(api_key=cfg["OPENAI_API_KEY"], base_url=api_base_url)
def history_to_messages(
- self, history: list[dict[str, str]], is_demonstration: bool = False
+ self,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `messages` by filtering out all keys except for role/content per `history` turn
@@ -344,7 +346,9 @@ class AnthropicModel(BaseModel):
self.api = Anthropic(api_key=cfg["ANTHROPIC_API_KEY"])
def history_to_messages(
- self, history: list[dict[str, str]], is_demonstration: bool = False
+ self,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `prompt` by filtering out all keys except for role/content per `history` turn
@@ -423,7 +427,9 @@ class BedrockModel(BaseModel):
raise ValueError(msg)
def history_to_messages(
- self, history: list[dict[str, str]], is_demonstration: bool = False
+ self,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `prompt` from the history of messages
@@ -452,7 +458,9 @@ class BedrockModel(BaseModel):
def anthropic_history_to_messages(
- model: AnthropicModel | BedrockModel, history: list[dict[str, str]], is_demonstration: bool = False
+ model: AnthropicModel | BedrockModel,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `prompt` by filtering out all keys except for role/content per `history` turn
@@ -560,7 +568,7 @@ class OllamaModel(BaseModel):
"max_context": 128_000,
"cost_per_input_token": 0,
"cost_per_output_token": 0,
- }
+ },
)
def __init__(self, args: ModelArguments, commands: list[Command]):
@@ -570,7 +578,9 @@ class OllamaModel(BaseModel):
self.client = Client(host=args.host_url)
def history_to_messages(
- self, history: list[dict[str, str]], is_demonstration: bool = False
+ self,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `messages` by filtering out all keys except for role/content per `history` turn
@@ -608,7 +618,7 @@ class OllamaModel(BaseModel):
"Prompt eval count not found in response. Using 0. "
"This might be because the prompt has been cached. "
"See https://github.com/princeton-nlp/SWE-agent/issues/44 "
- "and https://github.com/ollama/ollama/issues/3427."
+ "and https://github.com/ollama/ollama/issues/3427.",
)
input_tokens = 0
output_tokens = response["eval_count"]
@@ -718,7 +728,9 @@ class HumanModel(BaseModel):
}
def history_to_messages(
- self, history: list[dict[str, str]], is_demonstration: bool = False
+ self,
+ history: list[dict[str, str]],
+ is_demonstration: bool = False,
) -> str | list[dict[str, str]]:
"""
Create `messages` by filtering out all keys except for role/content per `history` turn
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 10af8b11..b53b789b 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -173,7 +173,9 @@ class SWEEnv(gym.Env):
hook.on_copy_repo_started(repo_type=self.record["repo_type"], repo_path=self.record["repo"])
if self.record["repo_type"] == "local":
copy_anything_to_container(
- self.container_obj, self.record["repo"].removeprefix("local://"), "/" + self._repo_name
+ self.container_obj,
+ self.record["repo"].removeprefix("local://"),
+ "/" + self._repo_name,
)
self.communicate_with_handling(
input=f"chown -R root:root {self._repo_name}",
@@ -327,7 +329,8 @@ class SWEEnv(gym.Env):
shell=True,
)
self.communicate_with_handling(
- input="git apply /root/test.patch", error_msg="Failed to apply test patch correctly"
+ input="git apply /root/test.patch",
+ error_msg="Failed to apply test patch correctly",
)
os.remove(path_to_patch)
@@ -689,7 +692,7 @@ class SWEEnv(gym.Env):
logger.warning(
"install_environment is set to True, but the data path is a GitHub URL "
"without an environment config file (environment_config key/flag). "
- "Skipping conda environment installation."
+ "Skipping conda environment installation.",
)
return
for hook in self.hooks:
@@ -750,7 +753,9 @@ class SWEEnv(gym.Env):
content_env_yml = get_environment_yml(self.record, env_name)
else:
content_env_yml = get_environment_yml(
- self.record, env_name, python_version=install_configs["python"]
+ self.record,
+ env_name,
+ python_version=install_configs["python"],
)
copy_file_to_container(self.container_obj, content_env_yml, PATH_TO_ENV_YML)
if install_configs.get("no_use_env", False):
@@ -804,7 +809,9 @@ class SWEEnv(gym.Env):
if install_configs.get("install", False):
install_cmd = install_configs["install"]
self.communicate_with_handling(
- install_cmd, error_msg="Install command failed to execute successfully", timeout_duration=LONG_TIMEOUT
+ install_cmd,
+ error_msg="Install command failed to execute successfully",
+ timeout_duration=LONG_TIMEOUT,
)
if install_configs.get("post_install", False):
self.logger.info("Running post-install commands...")
@@ -954,5 +961,5 @@ class SWEEnv(gym.Env):
logger.info(
f"🎉 PR created as a draft at {pr_info.html_url}. Please review it carefully, push "
"any required changes onto the branch and then click "
- "'Ready for Review' to bring it to the attention of the maintainers."
+ "'Ready for Review' to bring it to the attention of the maintainers.",
)
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index f35563a5..0292e96e 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -358,7 +358,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =
bash_pid,
1,
],
- )
+ ),
)
@@ -404,7 +404,7 @@ def image_exists(image_name):
"connection aborted" in str(e).lower(),
"connection refused" in str(e).lower(),
"error while fetching server api version" in str(e).lower(),
- )
+ ),
)
if docker_not_running:
msg = (
@@ -425,7 +425,7 @@ def image_exists(image_name):
if attrs is not None:
logger.info(
f"Found image {image_name} with tags: {attrs['RepoTags']}, created: {attrs['Created']} "
- f"for {attrs['Os']} {attrs['Architecture']}."
+ f"for {attrs['Os']} {attrs['Architecture']}.",
)
return True
@@ -505,7 +505,10 @@ class InstanceBuilder:
def set_problem_statement_from_gh_issue(self, issue_url: str):
owner, repo, issue_number = parse_gh_issue_url(issue_url)
self.args["problem_statement"] = get_problem_statement_from_github_issue(
- owner, repo, issue_number, token=self.token
+ owner,
+ repo,
+ issue_number,
+ token=self.token,
)
self.args["instance_id"] = f"{owner}__{repo}-i{issue_number}"
self.args["problem_statement_source"] = "online"
diff --git a/tests/test_env.py b/tests/test_env.py
index bb707bb4..f4920267 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -117,7 +117,9 @@ def test_execute_environment(tmp_path, test_env_args):
@pytest.mark.slow
def test_open_pr(test_env_args):
test_env_args = dataclasses.replace(
- test_env_args, data_path="https://github.com/klieret/swe-agent-test-repo/issues/1", repo_path=""
+ test_env_args,
+ data_path="https://github.com/klieret/swe-agent-test-repo/issues/1",
+ repo_path="",
)
with swe_env_context(test_env_args) as env:
env.reset()
diff --git a/tests/test_env_utils.py b/tests/test_env_utils.py
index 224b3a3b..6fb29805 100644
--- a/tests/test_env_utils.py
+++ b/tests/test_env_utils.py
@@ -80,7 +80,10 @@ def test_is_from_github_url():
def test_get_associated_commit_urls():
assoc = get_associated_commit_urls(
- org="princeton-nlp", repo="SWE-agent", issue_number="41", token=os.environ.get("GITHUB_TOKEN", "")
+ org="princeton-nlp",
+ repo="SWE-agent",
+ issue_number="41",
+ token=os.environ.get("GITHUB_TOKEN", ""),
)
assert len(assoc) > 0
@@ -167,7 +170,9 @@ def test_get_instance_gh_issue_gh_repo(tmp_path):
def test_get_instance_text_issue_gh_repo(tmp_path):
instance = get_instances(
- file_path="text://this is a test", repo_path="https://github.com/princeton-nlp/SWE-agent", **_TOKEN
+ file_path="text://this is a test",
+ repo_path="https://github.com/princeton-nlp/SWE-agent",
+ **_TOKEN,
)[0]
compare_with = {
"repo": "princeton-nlp/SWE-agent",
diff --git a/tests/test_replay.py b/tests/test_replay.py
index a72eea8c..19dc36f8 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -37,7 +37,9 @@ def swe_agent_test_repo_local_problem_stmt(swe_agent_test_repo_clone) -> Path:
@pytest.mark.slow
@pytest.mark.parametrize("problem_statement_source", ["github", "local"])
def test_model_replay_github_repo(
- swe_agent_test_repo_traj, problem_statement_source, swe_agent_test_repo_local_problem_stmt
+ swe_agent_test_repo_traj,
+ problem_statement_source,
+ swe_agent_test_repo_local_problem_stmt,
):
if problem_statement_source == "github":
data_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"