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]
Code quality: Convert to make use of PEP 585 and PEP 604
Kilian Lieret29a4c6dfb6cc
diff --git a/config/commands/_split_string.py b/config/commands/_split_string.pyindex c821be25..ecc363e7 100644--- a/config/commands/_split_string.py+++ b/config/commands/_split_string.py@@ -1,4 +1,6 @@#!/usr/bin/env python3+from __future__ import annotations+import sysdiff --git a/evaluation/aggregate_results.py b/evaluation/aggregate_results.pyindex e282970f..6923b326 100644--- a/evaluation/aggregate_results.py+++ b/evaluation/aggregate_results.py@@ -1,3 +1,5 @@+from __future__ import annotations+import argparseimport globimport json@@ -188,7 +190,7 @@ if __name__ == "__main__":"Generated": "mean","Applied": "mean","Resolved": "mean",- "Resolved IDs": lambda x: len(set([item for sublist in x for item in sublist])),+ "Resolved IDs": lambda x: len({item for sublist in x for item in sublist}),"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]),diff --git a/evaluation/evaluation.py b/evaluation/evaluation.pyindex 2baeca0f..68816539 100644--- a/evaluation/evaluation.py+++ b/evaluation/evaluation.py@@ -1,3 +1,5 @@+from __future__ import annotations+import argparseimport jsonimport os@@ -159,8 +161,8 @@ def main(scorecard["patch_files"] = [x.path for x in diff_obj.modified_files + diff_obj.added_files + diff_obj.removed_files]- scorecard["patch_lines_add"] = sum([f.added for f in diff_obj])- scorecard["patch_lines_del"] = sum([f.removed for f in diff_obj])+ scorecard["patch_lines_add"] = sum(f.added for f in diff_obj)+ scorecard["patch_lines_del"] = sum(f.removed for f in diff_obj)except Exception as e:print(f"[{p[KEY_INSTANCE_ID]}] Error parsing prediction diff: {e}")scorecard["patch_files"] = []diff --git a/inspector/server.py b/inspector/server.pyindex f9b73cd1..92cb177e 100644--- a/inspector/server.py+++ b/inspector/server.py@@ -1,3 +1,5 @@+from __future__ import annotations+import http.serverimport jsonimport os@@ -5,7 +7,7 @@ import socketserverfrom argparse import ArgumentParserfrom functools import partialfrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Anyimport yaml@@ -53,7 +55,7 @@ def append_patch(instance_id, content, patches, patch_type):def append_results(traj_path: Path, instance_id: str, content, results, results_file, scorecards, scorecards_file):- stats: List[str] = []+ stats: list[str] = []model_stats = {}if traj_path.exists():data = json.loads(traj_path.read_text())@@ -135,7 +137,7 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_return content-def load_content(file_name, gold_patches, test_patches) -> Dict[str, Any]:+def load_content(file_name, gold_patches, test_patches) -> dict[str, Any]:with open(file_name) as infile:content = json.load(infile)results_file = Path(file_name).parent / "results.json"@@ -162,7 +164,7 @@ def load_content(file_name, gold_patches, test_patches) -> Dict[str, Any]:return content-def load_results(results_path: Path) -> Optional[Dict[str, Any]]:+def load_results(results_path: Path) -> dict[str, Any] | None:"""Load results from results.json.If file is not found, return None.@@ -248,10 +250,10 @@ class Handler(http.server.SimpleHTTPRequestHandler):self.send_header("Content-type", "application/json")self.end_headers()files = sorted(- [+ (str(file.relative_to(Path(self.traj_dir))) + " " * 4 + get_status(file)for file in Path(self.traj_dir).glob("**/*.traj")- ],+ ),key=lambda x: str(Path(self.traj_dir) / x),reverse=True,)diff --git a/inspector/static.py b/inspector/static.pyindex 508e857c..0f88fee4 100644--- a/inspector/static.py+++ b/inspector/static.py@@ -1,3 +1,5 @@+from __future__ import annotations+import jsonimport loggingfrom argparse import ArgumentParserdiff --git a/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.pyindex 078466f5..61b8ceed 100644--- a/make_demos/convert_traj_to_demo.py+++ b/make_demos/convert_traj_to_demo.py@@ -1,3 +1,5 @@+from __future__ import annotations+import ioimport jsonfrom argparse import ArgumentParserdiff --git a/pyproject.toml b/pyproject.tomlindex 927f1170..4d05973c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -114,8 +114,8 @@ target-version = "py39"# 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.-# I001: Isort-select = ["F821", "F822", "E999", "E902", "F401", "F841", "I001"]+# I001: Isort, I002: required import+select = ["F821", "F822", "E999", "E902", "F401", "F841", "I001", "I002"]ignore = []# Allow fix for all enabled rules (when `--fix`) is provided.@@ -145,3 +145,6 @@ ACI = "ACI"[tool.typos.default.extend-words]# Don't correct the surname "Teh"aci = "aci"++[tool.ruff.lint.isort]+required-imports = ["from __future__ import annotations"]diff --git a/run.py b/run.pyindex 1c1ebd73..05e1f986 100644--- a/run.py+++ b/run.py@@ -1,3 +1,5 @@+from __future__ import annotations+try:import richexcept ModuleNotFoundError as e:@@ -11,7 +13,7 @@ import osimport reimport subprocessimport traceback-from typing import Any, Dict, List, Optional+from typing import Anyimport rich.consoleimport rich.markdown@@ -133,7 +135,7 @@ class MainHook:"""Hook structure for the web server or other addons to interface with"""@staticmethod- def _is_promising_patch(info: Dict[str, Any]) -> bool:+ def _is_promising_patch(info: dict[str, Any]) -> bool:"""Do we actually believe that the patch will solve the issue?Or are we just submitting the last patch we generated before hitting an error?"""@@ -152,7 +154,7 @@ class MainHook:"""Called at the end of `Main.main`"""...- def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):"""Called at the beginning of each instance loop in `Main.run`"""...@@ -175,7 +177,7 @@ class SaveApplyPatchHook(MainHook):self._apply_patch_locally = args.actions.apply_patch_locallyself._instance = None- def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):self._instance = instancedef on_instance_completed(self, *, info, trajectory):@@ -218,7 +220,7 @@ class SaveApplyPatchHook(MainHook):]console.print(rich.markdown.Markdown("\n".join(content)))- def _save_patch(self, instance_id: str, info) -> Optional[Path]:+ def _save_patch(self, instance_id: str, info) -> Path | None:"""Create patch files that can be applied with `git am`.Returns:@@ -268,7 +270,7 @@ class OpenPRHook(MainHook):if self._open_pr and self.should_open_pr(info):self._env.open_pr(trajectory=trajectory)- def should_open_pr(self, info: Dict[str, Any]) -> bool:+ def should_open_pr(self, info: dict[str, Any]) -> bool:"""Does opening a PR make sense?"""if not info.get("submission"):logger.info("Not opening PR because no submission was made.")@@ -319,7 +321,7 @@ class Main:SaveApplyPatchHook(),OpenPRHook(),]- self.hooks: List[MainHook] = []+ self.hooks: list[MainHook] = []for hook in default_hooks:self.add_hook(hook)diff --git a/run_replay.py b/run_replay.pyindex f2b5962f..89463b65 100644--- a/run_replay.py+++ b/run_replay.py@@ -1,16 +1,18 @@"""Replay a trajectory"""+from __future__ import annotations+import jsonimport osfrom argparse import ArgumentParser-from typing import Any, Dict, List+from typing import Anyimport yamlimport run as runscript-def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix: str, *, forward_args: List[str]):+def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix: str, *, forward_args: list[str]):"""Args:@@ -47,7 +49,7 @@ def process_single_traj(traj_path: str, config_file: str, data_path: str, suffixdata_path = args["environment"]["data_path"]# Identify the relevant task instance and create it- def create_task_instances_tmp_file(data: List[Dict[str, Any]]) -> str:+ def create_task_instances_tmp_file(data: list[dict[str, Any]]) -> str:"""Helper function to create a temporary file to write task instances to.Returns path to the temporary file."""@@ -103,7 +105,7 @@ def main(data_path: str,suffix: str,*,- forward_args: List[str],+ forward_args: list[str],):process_single_traj(traj_path, config_file, data_path, suffix, forward_args=forward_args)diff --git a/sweagent/__init__.py b/sweagent/__init__.pyindex 162e662c..0327a96c 100644--- a/sweagent/__init__.py+++ b/sweagent/__init__.py@@ -1,3 +1,5 @@+from __future__ import annotations+__version__ = "0.2.0"from pathlib import Pathdiff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 8d3d993b..d43975fe 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -1,9 +1,11 @@+from __future__ import annotations+import jsonimport loggingimport refrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Dict, List, Optional, Tuple, TypedDict+from typing import Any, TypedDictfrom simple_parsing.helpers.fields import fieldfrom simple_parsing.helpers.flatten import FlattenedAccess@@ -32,22 +34,22 @@ class Subroutine(FrozenSerializable):agent_file: str# one of "action", "observation", "response", "state", "thought"return_type: str = None # type: ignore- init_observation: Optional[str] = None- end_name: Optional[str] = None- signature: Optional[str] = None- docstring: Optional[str] = None- model: Optional[ModelArguments] = None- agent_args: Optional[Any] = None+ init_observation: str | None = None+ end_name: str | None = None+ signature: str | None = None+ docstring: str | None = None+ model: ModelArguments | None = None+ agent_args: Any | None = None@dataclass(frozen=True)class AgentConfig(FrozenSerializable):system_template: strinstance_template: str- next_step_template: Optional[str] = None # defaults to instance_template- next_step_no_output_template: Optional[str] = None # defaults to next_step_template- strategy_template: Optional[str] = None- demonstration_template: Optional[str] = None+ next_step_template: str | None = None # defaults to instance_template+ next_step_no_output_template: str | None = None # defaults to next_step_template+ strategy_template: str | None = None+ demonstration_template: str | None = Nonedemonstrations: list[str] = field(default_factory=list)put_demos_in_history: bool = False # if True, add demonstration to history instead of as a single message# defaults to format_error_template in ParseFunction@@ -62,7 +64,7 @@ class AgentConfig(FrozenSerializable):history_processor_args: dict[str, Any] = field(default_factory=dict)command_docs: str = None # type: ignoreblocklist_error_template: str = "Interactive operation '{name}' is not supported by this environment"- blocklist: Tuple[str, ...] = (+ blocklist: tuple[str, ...] = ("vim","vi","emacs",@@ -70,7 +72,7 @@ class AgentConfig(FrozenSerializable):"nohup","git",)- blocklist_standalone: Tuple[str, ...] = (+ blocklist_standalone: tuple[str, ...] = ("python","python3","ipython",@@ -167,8 +169,8 @@ class AgentArguments(FlattenedAccess, FrozenSerializable):model: ModelArguments = None# Policy can only be set via config yaml file from command line- config_file: Optional[Path] = None- config: Optional[AgentConfig] = field(default=None, cmd=False)+ config_file: Path | None = None+ config: AgentConfig | None = field(default=None, cmd=False)def __post_init__(self):if self.config is None and self.config_file is not None:@@ -190,7 +192,7 @@ class TrajectoryStep(TypedDict):action: strobservation: strresponse: str- state: Optional[str]+ state: str | Nonethought: str@@ -244,7 +246,7 @@ class Agent:hook.on_init()self.hooks.append(hook)- def _append_history(self, item: Dict):+ def _append_history(self, item: dict):for hook in self.hooks:hook.on_query_message_added(**item)self.history.append(item)@@ -258,7 +260,7 @@ class Agent:system_msg = self.config.system_template.format(**self.system_args)logger.info(f"SYSTEM ({self.name})\n{system_msg}")- self.history: List[Dict[str, Any]] = []+ self.history: list[dict[str, Any]] = []self._append_history({"role": "system", "content": system_msg, "agent": self.name})if len(self.config.demonstrations) > 0 and "history_to_messages" in dir(self.model):@@ -311,7 +313,7 @@ class Agent:"""Return the history of the agent since the last reset."""return self.config.history_processor([entry for entry in self.history if entry["agent"] == self.name])- def save_trajectory(self, trajectory, log_path: Path, env_name: str, info: Dict[str, Any]):+ def save_trajectory(self, trajectory, log_path: Path, env_name: str, info: dict[str, Any]):log_dict = {"environment": env_name,"trajectory": trajectory,@@ -321,7 +323,7 @@ class Agent:log_path.write_text(json.dumps(log_dict, indent=2))logger.info(f"Saved trajectory to {log_path}")- def _get_first_match(self, action: str, pattern_type: str) -> Optional[re.Match]:+ def _get_first_match(self, action: str, pattern_type: str) -> re.Match | None:"""Return the first match of a command pattern in the action string."""assert self.config is not None # mypyif pattern_type == "subroutine":@@ -379,7 +381,7 @@ class Agent:rem_action = ""return "\n".join(parsed_action)- def split_actions(self, action: str, pattern_type="subroutine") -> List[Dict[str, Any]]:+ def split_actions(self, action: str, pattern_type="subroutine") -> list[dict[str, Any]]:"""Split an action into a list of actions in a greedy manner, each of which is a subroutine call or a single command."""parsed_action = list()rem_action = action@@ -448,7 +450,7 @@ class Agent:self.subroutine_patterns[self.config.submit_command] = submit_patself.command_patterns[self.config.submit_command] = submit_pat- def forward(self, observation: str, available_actions: list[str], state: str) -> Tuple[str, str, str]:+ def forward(self, observation: str, available_actions: list[str], state: str) -> tuple[str, str, str]:thought, action, output = self.forward_with_error_check(observation, state)self._append_history(@@ -474,7 +476,7 @@ class Agent:state_vars = json.loads(state)- templates: List[str] = []+ templates: list[str] = []# Determine observation template based on what prior observation wasif self.history[-1]["role"] == "system" or self.history[-1].get("is_demo", False):# Show instance template if prev. obs. was initial system message@@ -551,7 +553,7 @@ class Agent:def check_format_and_requery(self,output: str,- ) -> Tuple[str, str, str]:+ ) -> tuple[str, str, str]:"""Query the model with the current state and observation with the appropriate template.Try to parse the output into a thought and action. Retry if the output is malformatted or the action is blocked.@@ -592,7 +594,7 @@ class Agent:logger.warning(f"Malformat limit reached: \n{output}")return "Exit due to format error", "exit_format", output- def forward_with_error_check(self, observation: str, state: str) -> Tuple[str, str, str]:+ def forward_with_error_check(self, observation: str, state: str) -> tuple[str, str, str]:"""Wrapper around `self.forward_model` that handles errors and retriesdue to format errors or blocked actions."""@@ -661,11 +663,9 @@ class Agent:datum["type"] = "utility"else:raise ValueError(- (- f"Non-shell script file {file} does not start with shebang.\n"- "Either add a shebang (#!) or change the file extension to .sh if you want to source it.\n"- "You can override this behavior by adding an underscore to the file name (e.g. _utils.py)."- )+ f"Non-shell script file {file} does not start with shebang.\n"+ "Either add a shebang (#!) or change the file extension to .sh if you want to source it.\n"+ "You can override this behavior by adding an underscore to the file name (e.g. _utils.py).")else:# scripts are made executable@@ -710,12 +710,12 @@ class Agent:def run(self,- setup_args: Dict[str, Any],+ setup_args: dict[str, Any],env: SWEEnv,- observation: Optional[str] = None,- traj_dir: Optional[Path] = None,- return_type: Optional[str] = "info",- init_model_stats: Optional[APIStats] = None,+ observation: str | None = None,+ traj_dir: Path | None = None,+ return_type: str | None = "info",+ init_model_stats: APIStats | None = None,):"""Run the agent on an environment.diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.pyindex c18a84d6..c8e0b2e3 100644--- a/sweagent/agent/commands.py+++ b/sweagent/agent/commands.py@@ -1,8 +1,9 @@+from __future__ import annotations+import refrom abc import abstractmethodfrom dataclasses import dataclassfrom pathlib import Path-from typing import Dict, List, Optionalimport yamlfrom simple_parsing.helpers.serialization.serializable import FrozenSerializable@@ -12,8 +13,8 @@ from simple_parsing.helpers.serialization.serializable import FrozenSerializableclass AssistantMetadata(FrozenSerializable):"""Pass observations to the assistant, and get back a response."""- system_template: Optional[str] = None- instance_template: Optional[str] = None+ system_template: str | None = None+ instance_template: str | None = None# TODO: first can be used for two-stage actions@@ -22,18 +23,18 @@ class AssistantMetadata(FrozenSerializable):class ControlMetadata(FrozenSerializable):"""TODO: should be able to control high-level control flow after calling this command"""- next_step_template: Optional[str] = None- next_step_action_template: Optional[str] = None+ next_step_template: str | None = None+ next_step_action_template: str | None = None@dataclass(frozen=True)class Command(FrozenSerializable):code: strname: str- docstring: Optional[str] = None- end_name: Optional[str] = None # if there is an end_name, then it is a multi-line command- arguments: Optional[Dict] = None- signature: Optional[str] = None+ docstring: str | None = None+ end_name: str | None = None # if there is an end_name, then it is a multi-line command+ arguments: dict | None = None+ signature: str | None = Noneclass ParseCommandMeta(type):@@ -56,14 +57,14 @@ class ParseCommand(metaclass=ParseCommandMeta):raise ValueError(f"Command parser ({name}) not found.")@abstractmethod- def parse_command_file(self, path: str) -> List[Command]:+ def parse_command_file(self, path: str) -> list[Command]:"""Define how to parse a file into a list of commands."""raise NotImplementedError@abstractmethod- def generate_command_docs(self, commands: List[Command], subroutine_types, **kwargs) -> str:+ def generate_command_docs(self, commands: list[Command], subroutine_types, **kwargs) -> str:"""Generate a string of documentation for the given commands and subroutine types."""@@ -74,35 +75,31 @@ class ParseCommand(metaclass=ParseCommandMeta):class ParseCommandBash(ParseCommand):- def parse_command_file(self, path: str) -> List[Command]:+ def parse_command_file(self, path: str) -> list[Command]:contents = open(path, "r").read()if contents.strip().startswith("#!"):commands = self.parse_script(path, contents)else:if not path.endswith(".sh") and not Path(path).name.startswith("_"):raise ValueError(- (- f"Source file {path} does not have a .sh extension.\n"- "Only .sh files are supported for bash function parsing.\n"- "If you want to use a non-shell file as a command (script), "- "it should use a shebang (e.g. #!/usr/bin/env python)."- )+ f"Source file {path} does not have a .sh extension.\n"+ "Only .sh files are supported for bash function parsing.\n"+ "If you want to use a non-shell file as a command (script), "+ "it should use a shebang (e.g. #!/usr/bin/env python).")return self.parse_bash_functions(path, contents)if len(commands) == 0 and not Path(path).name.startswith("_"):raise ValueError(- (- f"Non-shell file {path} does not contain any commands.\n"- "If you want to use a non-shell file as a command (script), "- "it should contain exactly one @yaml docstring. "- "If you want to use a file as a utility script, "- "it should start with an underscore (e.g. _utils.py)."- )+ f"Non-shell file {path} does not contain any commands.\n"+ "If you want to use a non-shell file as a command (script), "+ "it should contain exactly one @yaml docstring. "+ "If you want to use a file as a utility script, "+ "it should start with an underscore (e.g. _utils.py).")else:return commands- def parse_bash_functions(self, path, contents) -> List[Command]:+ def parse_bash_functions(self, path, contents) -> list[Command]:"""Simple logic for parsing a bash file and segmenting it into functions.@@ -154,14 +151,14 @@ class ParseCommandBash(ParseCommand):docs = []return commands- def parse_script(self, path, contents) -> List[Command]:+ def parse_script(self, path, contents) -> list[Command]:pattern = re.compile(r"^#\s*@yaml\s*\n^#.*(?:\n#.*)*", re.MULTILINE)matches = pattern.findall(contents)if len(matches) == 0:return []elif len(matches) > 1:raise ValueError(- ("Non-shell file contains multiple @yaml tags.\n" "Only one @yaml tag is allowed per script.")+ "Non-shell file contains multiple @yaml tags.\n" "Only one @yaml tag is allowed per script.")else:yaml_content = matches[0]@@ -194,7 +191,7 @@ class ParseCommandBash(ParseCommand):)]- def generate_command_docs(self, commands: List[Command], subroutine_types, **kwargs) -> str:+ def generate_command_docs(self, commands: list[Command], subroutine_types, **kwargs) -> str:docs = ""for cmd in commands:if cmd.docstring is not None:@@ -236,7 +233,7 @@ class ParseCommandDetailed(ParseCommandBash):def generate_command_docs(self,- commands: List[Command],+ commands: list[Command],subroutine_types,**kwargs,) -> str:diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.pyindex 4f559b15..21efa2a8 100644--- a/sweagent/agent/history_processors.py+++ b/sweagent/agent/history_processors.py@@ -1,3 +1,5 @@+from __future__ import annotations+import refrom abc import abstractmethodfrom dataclasses import dataclassdiff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 275ff2cd..8c511a3e 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -1,9 +1,10 @@+from __future__ import annotations+import jsonimport loggingimport osfrom collections import defaultdictfrom dataclasses import dataclass, fields-from typing import Optional, Unionimport togetherfrom anthropic import AI_PROMPT, HUMAN_PROMPT, Anthropic, AnthropicBedrock@@ -110,7 +111,7 @@ class BaseModel:f"Unregistered model ({args.model_name}). Add model name to MODELS metadata to {self.__class__}")- def reset_stats(self, other: Optional[APIStats] = None):+ def reset_stats(self, other: APIStats | None = None):if other is None:self.stats = APIStats(total_cost=self.stats.total_cost)logger.info("Resetting model stats")@@ -243,12 +244,12 @@ class OpenAIModel(BaseModel):api_version=cfg.get("AZURE_OPENAI_API_VERSION", "2024-02-01"),)else:- api_base_url: Optional[str] = cfg.get("OPENAI_API_BASE_URL", None)+ api_base_url: str | None = cfg.get("OPENAI_API_BASE_URL", None)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- ) -> Union[str, list[dict[str, str]]]:+ ) -> str | list[dict[str, str]]:"""Create `messages` by filtering out all keys except for role/content per `history` turn"""@@ -339,7 +340,7 @@ class AnthropicModel(BaseModel):def history_to_messages(self, history: list[dict[str, str]], is_demonstration: bool = False- ) -> Union[str, list[dict[str, str]]]:+ ) -> str | list[dict[str, str]]:"""Create `prompt` by filtering out all keys except for role/content per `history` turnReference: https://docs.anthropic.com/claude/reference/complete_post@@ -416,7 +417,7 @@ class BedrockModel(BaseModel):def history_to_messages(self, history: list[dict[str, str]], is_demonstration: bool = False- ) -> Union[str, list[dict[str, str]]]:+ ) -> str | list[dict[str, str]]:"""Create `prompt` from the history of messages"""@@ -442,8 +443,8 @@ class BedrockModel(BaseModel):def anthropic_history_to_messages(- model: Union[AnthropicModel, BedrockModel], history: list[dict[str, str]], is_demonstration: bool = False-) -> Union[str, list[dict[str, str]]]:+ 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` turnReference: https://docs.anthropic.com/claude/reference/complete_post@@ -490,7 +491,7 @@ def anthropic_history_to_messages(return compiled_messages-def anthropic_query(model: Union[AnthropicModel, BedrockModel], history: list[dict[str, str]]) -> str:+def anthropic_query(model: AnthropicModel | BedrockModel, history: list[dict[str, str]]) -> str:"""Query the Anthropic API with the given `history` and return the response."""@@ -562,7 +563,7 @@ class OllamaModel(BaseModel):def history_to_messages(self, history: list[dict[str, str]], is_demonstration: bool = False- ) -> Union[str, list[dict[str, str]]]:+ ) -> str | list[dict[str, str]]:"""Create `messages` by filtering out all keys except for role/content per `history` turn"""@@ -711,7 +712,7 @@ class HumanModel(BaseModel):def history_to_messages(self, history: list[dict[str, str]], is_demonstration: bool = False- ) -> Union[str, list[dict[str, str]]]:+ ) -> str | list[dict[str, str]]:"""Create `messages` by filtering out all keys except for role/content per `history` turn"""@@ -835,7 +836,7 @@ class InstantEmptySubmitTestModel(BaseModel):return action-def get_model(args: ModelArguments, commands: Optional[list[Command]] = None):+def get_model(args: ModelArguments, commands: list[Command] | None = None):"""Returns correct model object given arguments and commands"""diff --git a/sweagent/agent/parsing.py b/sweagent/agent/parsing.pyindex 9c89cc30..2598f510 100644--- a/sweagent/agent/parsing.py+++ b/sweagent/agent/parsing.py@@ -1,3 +1,5 @@+from __future__ import annotations+import jsonimport reimport shlex@@ -5,7 +7,6 @@ import stringimport textwrapfrom abc import abstractmethodfrom dataclasses import dataclass-from typing import Listfrom sweagent.agent.commands import Command@@ -41,7 +42,7 @@ class ParseFunction(metaclass=ParseFunctionMeta):_error_message = None@abstractmethod- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):raise NotImplementedError@property@@ -74,7 +75,7 @@ class ActionParser(ParseFunction):{command_docs}"""- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):if model_response.split():action = model_response.strip().split()[0]if action in {command.name for command in commands}:@@ -103,7 +104,7 @@ class ThoughtActionParser(ParseFunction):```"""- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):"""Parses the action from the output of the API call.We assume that the action is the last code block in the model_response.@@ -152,7 +153,7 @@ class XMLThoughtActionParser(ParseFunction):Please make sure your output precisely matches the following format:"""- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):"""Parses the action from the output of the API call.We assume that the action is the last code block in the model_response.@@ -218,7 +219,7 @@ class Identity(ParseFunction):It seems like something went wrong with your output. Please try again."""- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):"""This doesn't do any parsing. It just returns the model response as the thought and action."""@@ -236,7 +237,7 @@ class JsonParser(ParseFunction):"""- def __call__(self, model_response, commands: List[Command], strict=False):+ def __call__(self, model_response, commands: list[Command], strict=False):"""Parses the action from the output of the API call.We assume that model output is a JSON object with the following fields:diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.pyindex aa2b9db6..f069150b 100644--- a/sweagent/api/hooks.py+++ b/sweagent/api/hooks.py@@ -1,6 +1,7 @@+from __future__ import annotations+import ioimport sys-from typing import Optionalfrom flask_socketio import SocketIO@@ -17,7 +18,7 @@ from run import MainHookclass StreamToSocketIO(io.StringIO):def __init__(self,- wu: "WebUpdate",+ wu: WebUpdate,):super().__init__()self._wu = wu@@ -54,7 +55,7 @@ class WebUpdate:message: str,*,format: str = "markdown",- thought_idx: Optional[int] = None,+ thought_idx: int | None = None,type_: str = "info",):"""Update the agent feed"""@@ -75,7 +76,7 @@ class WebUpdate:*,type_: str,format: str = "markdown",- thought_idx: Optional[int] = None,+ thought_idx: int | None = None,):"""Update the environment feed"""self._emit(diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex 41e73830..30b495c6 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -1,3 +1,5 @@+from __future__ import annotations+try:import flask # noqaexcept ImportError as e:@@ -16,7 +18,7 @@ import timeimport tracebackfrom contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Path-from typing import Any, Dict+from typing import Anyfrom uuid import uuid4import yaml@@ -45,7 +47,7 @@ socketio = SocketIO(app, cors_allowed_origins="*")app.secret_key = "super secret key"app.config["SESSION_TYPE"] = "memcache"-THREADS: Dict[str, "MainThread"] = {}+THREADS: dict[str, MainThread] = {}os.environ["SWE_AGENT_EXPERIMENTAL_COMMUNICATE"] = "1"env_utils.START_UP_DELAY = 1diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pyindex 61325358..5a47a004 100644--- a/sweagent/api/utils.py+++ b/sweagent/api/utils.py@@ -1,3 +1,5 @@+from __future__ import annotations+import ctypesimport inspectimport rediff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex b586a38d..8c71e9ed 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -1,3 +1,5 @@+from __future__ import annotations+import datetimeimport hashlibimport logging@@ -9,7 +11,6 @@ import timeimport tracebackfrom dataclasses import dataclassfrom pathlib import Path-from typing import List, Optional, Tupleimport gymnasium as gymimport yaml@@ -62,8 +63,8 @@ class EnvironmentArguments(FrozenSerializable):split: str = "dev"# Specify a branch name or a commit hash to checkout before running the task.# Only used when running over a single problem statement/issue.- base_commit: Optional[str] = None- container_name: Optional[str] = None+ base_commit: str | None = None+ container_name: str | None = Noneinstall_environment: bool = Truetimeout: int = 35verbose: bool = False@@ -73,7 +74,7 @@ class EnvironmentArguments(FrozenSerializable):# This needs to be either a string pointing to a yaml file (with yaml, yml file extension)# or a shell script (with sh extension).# See https://github.com/princeton-nlp/SWE-agent/pull/153 for more information- environment_setup: Optional[str] = None+ environment_setup: str | None = None# Only used when running on single issue. Path to local repository or github repository.repo_path: str = ""@@ -144,7 +145,7 @@ class SWEEnv(gym.Env):def _get_cached_task_image_name(self) -> str:assert self.record is not None- inputs: List[str] = [+ inputs: list[str] = [self.record["repo"],self.record["base_commit"],self.args.environment_setup or "no_setup",@@ -201,7 +202,7 @@ class SWEEnv(gym.Env):)return self._repo_name- def reset(self, index: Optional[int] = None, apply_test_patch: bool = False) -> Tuple[Optional[str], dict]:+ def reset(self, index: int | None = None, apply_test_patch: bool = False) -> tuple[str | None, dict]:"""Function to reset container between each task instance.* Clones instance's repository@@ -330,7 +331,7 @@ class SWEEnv(gym.Env):)os.remove(path_to_patch)- def step(self, action: str) -> Tuple[Optional[str], int, bool, dict]:+ def step(self, action: str) -> tuple[str | None, int, bool, dict]:"""Runs given action in environment and returns corresponding output@@ -458,7 +459,7 @@ class SWEEnv(gym.Env):self.container_obj = Noneself._reset_container()- def _init_container(self, cached_image: Optional[str] = None) -> None:+ def _init_container(self, cached_image: str | None = None) -> None:"""Handles container initialization. Defines container name and creates it.If cached_image is provided, it will use that image name instead of the default.@@ -679,11 +680,9 @@ class SWEEnv(gym.Env):self.record["problem_statement_source"] != "swe-bench" or self.record["repo_type"] == "local") and self.args.environment_setup is None: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."- )+ "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.")returnfor hook in self.hooks:diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex c4e7c5d8..966e753c 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -1,3 +1,5 @@+from __future__ import annotations+import hashlibimport jsonimport logging@@ -13,7 +15,7 @@ import tracebackfrom io import BytesIOfrom pathlib import Pathfrom subprocess import PIPE, STDOUT-from typing import Any, Dict, List, Optional, Set, Tuple+from typing import Anyfrom datasets import load_dataset, load_from_diskfrom ghapi.all import GhApi@@ -252,7 +254,7 @@ def get_background_pids(container_obj):return bash_pids, other_pids-def _get_non_persistent_container(ctr_name: str, image_name: str) -> Tuple[subprocess.Popen, set]:+def _get_non_persistent_container(ctr_name: str, image_name: str) -> tuple[subprocess.Popen, set]:startup_cmd = ["docker","run",@@ -283,7 +285,7 @@ def _get_non_persistent_container(ctr_name: str, image_name: str) -> Tuple[subpr} # bash PID is always 1 for non-persistent containers-def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool = False) -> Tuple[subprocess.Popen, Set]:+def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool = False) -> tuple[subprocess.Popen, set]:client = docker.from_env()containers = client.containers.list(all=True, filters={"name": ctr_name})if ctr_name in [c.name for c in containers]:@@ -359,7 +361,7 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =)-def get_container(ctr_name: str, image_name: str, persistent: bool = False) -> Tuple[subprocess.Popen, Set]:+def get_container(ctr_name: str, image_name: str, persistent: bool = False) -> tuple[subprocess.Popen, set]:"""Get a container object for a given container name and image name@@ -427,7 +429,7 @@ def image_exists(image_name):return True-def get_commit(api: GhApi, owner: str, repo: str, ref: Optional[str] = None):+def get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):"""Get commit object from github apiArgs:@@ -447,7 +449,7 @@ def get_commit(api: GhApi, owner: str, repo: str, ref: Optional[str] = None):class InvalidGithubURL(ValueError): ...-def parse_gh_issue_url(issue_url: str) -> Tuple[str, str, str]:+def parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:"""Return owner, repo, issue number from issue url"""match = GITHUB_ISSUE_URL_PATTERN.search(issue_url)if not match:@@ -457,7 +459,7 @@ def parse_gh_issue_url(issue_url: str) -> Tuple[str, str, str]:return tuple(res) # type: ignore-def parse_gh_repo_url(repo_url: str) -> Tuple[str, str]:+def parse_gh_repo_url(repo_url: str) -> tuple[str, str]:"""Return owner, repo from repo url"""match = GITHUB_REPO_URL_PATTERN.search(repo_url)if not match:@@ -477,9 +479,7 @@ def get_gh_issue_data(issue_url: str, *, token: str = ""):return api.issues.get(owner, repo, issue_number)-def get_problem_statement_from_github_issue(- owner: str, repo: str, issue_number: str, *, token: Optional[str] = ""-) -> str:+def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: str | None = "") -> str:"""Return problem statement from github issue"""api = GhApi(token=token)issue = api.issues.get(owner, repo, issue_number)@@ -489,7 +489,7 @@ def get_problem_statement_from_github_issue(class InstanceBuilder:- def __init__(self, token: Optional[str] = None):+ def __init__(self, token: str | None = None):"""This helper class is used to build the data for an instance object,retrieving problem statements from github issues or local files and settingrepo paths from github urls or local paths.@@ -528,7 +528,7 @@ class InstanceBuilder:msg = f"Not sure how to get problem statement from {data_path=}."raise ValueError(msg)- def set_repo_info_from_gh_url(self, url: str, base_commit: Optional[str] = None):+ def set_repo_info_from_gh_url(self, url: str, base_commit: str | None = None):owner, repo = parse_gh_repo_url(url)self.args["repo"] = f"{owner}/{repo}"self.args["repo_type"] = "github"@@ -539,7 +539,7 @@ class InstanceBuilder:logger.info(f"Base commit reference {base_commit} resolved to commit hash {self.args['base_commit']}")self.args["version"] = self.args["base_commit"][:7]- def set_repo_info_from_local_path(self, path: str, base_commit: Optional[str] = None):+ def set_repo_info_from_local_path(self, path: str, base_commit: str | None = None):self.args["repo"] = str(Path(path).resolve())self.args["repo_type"] = "local"if base_commit:@@ -556,7 +556,7 @@ class InstanceBuilder:self.args["base_commit"] = repo.head.object.hexshaself.args["version"] = self.args["base_commit"][:7]- def set_repo_info(self, repo: str, base_commit: Optional[str] = None):+ def set_repo_info(self, repo: str, base_commit: str | None = None):if is_github_repo_url(repo):self.set_repo_info_from_gh_url(repo, base_commit=base_commit)elif Path(repo).is_dir():@@ -564,7 +564,7 @@ class InstanceBuilder:else:raise ValueError(f"Could not determine repo path from {repo=}.")- def set_from_dict(self, instance_dict: Dict[str, Any]):+ def set_from_dict(self, instance_dict: dict[str, Any]):self.args |= instance_dictdef set_missing_fields(self):@@ -595,7 +595,7 @@ class InstanceBuilder:if self.args["repo_type"] == "github" and self.args["repo"].count("/") != 1:raise ValueError(f"Invalid repo format for {self.args['repo_type']=}: {self.args['repo']=}")- def build(self) -> Dict[str, Any]:+ def build(self) -> dict[str, Any]:self.set_missing_fields()self.validate()return self.args@@ -603,12 +603,12 @@ class InstanceBuilder:def get_instances(file_path: str,- base_commit: Optional[str] = None,- split: Optional[str] = None,- token: Optional[str] = None,+ base_commit: str | None = None,+ split: str | None = None,+ token: str | None = None,*,repo_path: str = "",-) -> List[Dict[str, Any]]:+) -> list[dict[str, Any]]:"""Getter function for handling json, jsonl files@@ -733,7 +733,7 @@ _MARKDOWN_TRAJECTORY_EMOJI_MAPPING = {}-def format_trajectory_markdown(trajectory: List[Dict[str, str]]):+def format_trajectory_markdown(trajectory: list[dict[str, str]]):"""Format a trajectory as a markdown string for use in gh PR description."""prefix = ["<details>",diff --git a/sweagent/utils/config.py b/sweagent/utils/config.pyindex 323ace99..079dd5e7 100644--- a/sweagent/utils/config.py+++ b/sweagent/utils/config.py@@ -1,3 +1,5 @@+from __future__ import annotations+import loggingimport osfrom typing import Anydiff --git a/tests/conftest.py b/tests/conftest.pyindex 70a792ea..7045cd97 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,3 +1,5 @@+from __future__ import annotations+import jsonimport osimport sysdiff --git a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.pyindex bbc4d4e1..16b2cbee 100644--- a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py+++ b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+from __future__ import annotationsdef division(a: float, b: float) -> float:diff --git a/tests/test_env.py b/tests/test_env.pyindex 0247e7ca..bb707bb4 100644--- a/tests/test_env.py+++ b/tests/test_env.py@@ -1,3 +1,5 @@+from __future__ import annotations+import dataclassesimport osimport subprocessdiff --git a/tests/test_models.py b/tests/test_models.pyindex 49d37204..da58a91d 100644--- a/tests/test_models.py+++ b/tests/test_models.py@@ -1,3 +1,5 @@+from __future__ import annotations+from unittest.mock import MagicMock, Mock, patchimport pytestdiff --git a/tests/test_packaging.py b/tests/test_packaging.pyindex 607d8b9c..13846850 100644--- a/tests/test_packaging.py+++ b/tests/test_packaging.py@@ -1,3 +1,5 @@+from __future__ import annotations+from sweagent import __version__diff --git a/tests/test_parsing.py b/tests/test_parsing.pyindex 70bcc1f6..b320ca55 100644--- a/tests/test_parsing.py+++ b/tests/test_parsing.py@@ -1,3 +1,5 @@+from __future__ import annotations+import pytestfrom sweagent.agent.commands import Commanddiff --git a/tests/test_replay.py b/tests/test_replay.pyindex 30885ef0..da2c5b1b 100644--- a/tests/test_replay.py+++ b/tests/test_replay.py@@ -1,3 +1,5 @@+from __future__ import annotations+import subprocessfrom pathlib import Pathdiff --git a/tests/test_run.py b/tests/test_run.pyindex 9c1bfe8f..1f4bf1dc 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -1,8 +1,10 @@+from __future__ import annotations+import jsonimport osimport subprocessfrom pathlib import Path-from typing import Any, Dict+from typing import Anyimport pytest@@ -89,7 +91,7 @@ def test_should_open_pr_success_has_pr_override(open_pr_hook_init_for_sop, info_class RaisesExceptionHook(MainHook):- def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):raise ValueError("test exception")@@ -135,7 +137,7 @@ class CreateFakeLogFile(MainHook):self._traj_dir = traj_dir(traj_dir / "args.yaml").write_text("asdf")- def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):instance_id = instance["instance_id"]dct = {"info": {"exit_status": "submitted"},diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 57f93232..224b3a3b 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -1,3 +1,5 @@+from __future__ import annotations+import hashlibimport osimport subprocess@@ -136,7 +138,7 @@ def test_get_instance_local_issue_local_repo(tmp_path):compare_with = {"repo": str(tmp_path.resolve() / "swe-agent-test-repo"),"repo_type": "local",- "instance_id": hashlib.sha256("asdf".encode()).hexdigest()[:6],+ "instance_id": hashlib.sha256(b"asdf").hexdigest()[:6],"problem_statement": "asdf",}for key in compare_with: