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]

Add flake8-errmsg to tests

Kilian Lieretc33615a13aec
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index fedfac04..dc5354fa 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -38,7 +38,8 @@ def main(
):
# Check if paths exist
if not os.path.exists(predictions_path):
- raise FileNotFoundError(f"Predictions path {predictions_path} does not exist")
+ msg = f"Predictions path {predictions_path} does not exist"
+ raise FileNotFoundError(msg)
eval_refs = get_eval_refs(swe_bench_tasks)
for k, v in eval_refs.items():
eval_refs[k] = {key: v[key] for key in [KEY_INSTANCE_ID, "FAIL_TO_PASS", "PASS_TO_PASS"]}
diff --git a/inspector/server.py b/inspector/server.py
index 95d4e22e..d59b1e53 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -33,7 +33,8 @@ def append_exit(content):
)
# else submission should be in history already
else:
- raise ValueError("No submission in history or info")
+ msg = "No submission in history or info"
+ raise ValueError(msg)
# elif content.get("info", {}).get("exit_status", None) is not None:
# content["history"].append({
# "role": "system",
diff --git a/inspector/static.py b/inspector/static.py
index 7ca57aaf..236a6ecb 100644
--- a/inspector/static.py
+++ b/inspector/static.py
@@ -129,7 +129,8 @@ def find_relative_path(from_path, to_path):
if to_path.is_file():
to_path = to_path.parent
if not from_path.is_dir() or not to_path.is_dir():
- raise ValueError(f"Both from_path and to_path must be directories, but got {from_path} and {to_path}")
+ msg = f"Both from_path and to_path must be directories, but got {from_path} and {to_path}"
+ raise ValueError(msg)
# Identify the common ancestor and the parts of each path beyond it
common_parts = 0
diff --git a/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.py
index 61b8ceed..41899660 100644
--- a/make_demos/convert_traj_to_demo.py
+++ b/make_demos/convert_traj_to_demo.py
@@ -37,7 +37,8 @@ def convert_to_literal_string(d):
elif isinstance(d, str) and "\n" in d:
d = LSS(d.replace("\r\n", "\n").replace("\r", "\n"))
else:
- raise ValueError(f"Unsupported type: {type(d)}")
+ msg = f"Unsupported type: {type(d)}"
+ raise ValueError(msg)
return d
@@ -74,7 +75,8 @@ def main(traj_path: str, output_dir: str = None, suffix: str = "", overwrite: bo
)
output_file = Path(output_dir) / filename
if output_file.exists() and not overwrite:
- raise FileExistsError(f"Output file already exists: {output_file}")
+ msg = f"Output file already exists: {output_file}"
+ raise FileExistsError(msg)
output_file.parent.mkdir(parents=True, exist_ok=True)
convert_traj_to_action_demo(traj_path, output_file, include_user)
@@ -85,7 +87,8 @@ def string2bool(s):
elif s.lower() in {"false", "0"}:
return False
else:
- raise ValueError(f"Invalid boolean string: {s}")
+ msg = f"Invalid boolean string: {s}"
+ raise ValueError(msg)
if __name__ == "__main__":
diff --git a/pyproject.toml b/pyproject.toml
index 701f742b..69d44063 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -145,6 +145,8 @@ select = [
# bugbear
"B006", # mutable default
"B007", # unused loop var
+ # flake8-errmsg
+ "EM",
]
ignore = []
diff --git a/run.py b/run.py
index a2cfddec..f66d2f20 100644
--- a/run.py
+++ b/run.py
@@ -3,10 +3,11 @@ from __future__ import annotations
try:
import rich
except ModuleNotFoundError as e:
- raise RuntimeError(
+ msg = (
"You probably either forgot to install the dependencies "
"or forgot to activate your conda or virtual environment."
- ) from e
+ )
+ raise RuntimeError(msg) from e
import json
import logging
import os
@@ -88,7 +89,8 @@ class ActionsArguments(FlattenedAccess, FrozenSerializable):
def __post_init__(self):
if self.push_gh_repo_url:
- raise ValueError("push_gh_repo_url is obsolete. Use repo_path instead")
+ msg = "push_gh_repo_url is obsolete. Use repo_path instead"
+ raise ValueError(msg)
@dataclass(frozen=True)
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index ea31e96f..4e4c3113 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -116,7 +116,8 @@ class AgentConfig(FrozenSerializable):
for subroutine in self.subroutine_types:
if subroutine.name == "submit":
- raise ValueError("Cannot use 'submit' as a subroutine name")
+ msg = "Cannot use 'submit' as a subroutine name"
+ raise ValueError(msg)
agent_args = AgentArguments(
model=subroutine.model,
config_file=subroutine.agent_file,
@@ -266,9 +267,8 @@ class Agent:
if len(self.config.demonstrations) > 0 and "history_to_messages" in dir(self.model):
for demonstration_path in self.config.demonstrations:
if self.config.demonstration_template is None and not self.config.put_demos_in_history:
- raise ValueError(
- "Cannot use demonstrations without a demonstration template or put_demos_in_history=True"
- )
+ msg = "Cannot use demonstrations without a demonstration template or put_demos_in_history=True"
+ raise ValueError(msg)
# Load history
logger.info(f"DEMONSTRATION: {demonstration_path}")
@@ -340,7 +340,8 @@ class Agent:
elif pattern_type == "multi_line_no_subroutines":
patterns = {k: v for k, v in self.command_patterns.items() if k in self.config.multi_line_command_endings}
else:
- raise ValueError(f"Unknown pattern type: {pattern_type}")
+ msg = f"Unknown pattern type: {pattern_type}"
+ raise ValueError(msg)
matches = list()
for _, pat in patterns.items():
match = pat.search(action)
@@ -640,7 +641,8 @@ class Agent:
try:
output = env.communicate(commands)
if env.returncode != 0:
- raise RuntimeError(f"Nonzero return code: {env.returncode}\nOutput: {output}")
+ msg = f"Nonzero return code: {env.returncode}\nOutput: {output}"
+ raise RuntimeError(msg)
except KeyboardInterrupt:
raise
except Exception as e:
@@ -662,11 +664,12 @@ class Agent:
datum["name"] = Path(file).name
datum["type"] = "utility"
else:
- raise ValueError(
+ msg = (
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)."
)
+ raise ValueError(msg)
else:
# scripts are made executable
datum["name"] = Path(file).name.rsplit(".", 1)[0]
@@ -692,7 +695,8 @@ class Agent:
obs = None
if env.returncode != 0:
self._append_history({"role": "user", "content": obs, "agent": agent_name})
- raise RuntimeError(f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}")
+ msg = f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}"
+ raise RuntimeError(msg)
return_type = self.config._subroutines[agent_name].return_type
sub_agent = Agent(agent_name, self.config._subroutines[agent_name].agent_args)
sub_agent_output = sub_agent.run(
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index bc6c2f86..244d2c6a 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -54,7 +54,8 @@ class ParseCommand(metaclass=ParseCommandMeta):
try:
return cls._registry[name]()
except KeyError:
- raise ValueError(f"Command parser ({name}) not found.")
+ msg = f"Command parser ({name}) not found."
+ raise ValueError(msg)
@abstractmethod
def parse_command_file(self, path: str) -> list[Command]:
@@ -81,21 +82,23 @@ class ParseCommandBash(ParseCommand):
commands = self.parse_script(path, contents)
else:
if not path.endswith(".sh") and not Path(path).name.startswith("_"):
- raise ValueError(
+ msg = (
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)."
)
+ raise ValueError(msg)
return self.parse_bash_functions(path, contents)
if len(commands) == 0 and not Path(path).name.startswith("_"):
- raise ValueError(
+ msg = (
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)."
)
+ raise ValueError(msg)
else:
return commands
@@ -157,9 +160,8 @@ class ParseCommandBash(ParseCommand):
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."
- )
+ msg = "Non-shell file contains multiple @yaml tags.\n" "Only one @yaml tag is allowed per script."
+ raise ValueError(msg)
else:
yaml_content = matches[0]
yaml_content = re.sub(r"^#", "", yaml_content, flags=re.MULTILINE)
diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.py
index 21efa2a8..e5c935ba 100644
--- a/sweagent/agent/history_processors.py
+++ b/sweagent/agent/history_processors.py
@@ -36,7 +36,8 @@ class HistoryProcessor(metaclass=HistoryProcessorMeta):
try:
return cls._registry[name](*args, **kwargs)
except KeyError:
- raise ValueError(f"Model output parser ({name}) not found.")
+ msg = f"Model output parser ({name}) not found."
+ raise ValueError(msg)
# DEFINE NEW PARSING FUNCTIONS BELOW THIS LINE
@@ -47,7 +48,8 @@ class DefaultHistoryProcessor(HistoryProcessor):
def last_n_history(history, n):
if n <= 0:
- raise ValueError("n must be a positive integer")
+ msg = "n must be a positive integer"
+ raise ValueError(msg)
new_history = list()
user_messages = len([entry for entry in history if (entry["role"] == "user" and not entry.get("is_demo", False))])
user_msg_idx = 0
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index d43f9082..b022d871 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -51,7 +51,8 @@ class APIStats(Serializable):
def __add__(self, other):
if not isinstance(other, APIStats):
- raise TypeError("Can only add APIStats with APIStats")
+ msg = "Can only add APIStats with APIStats"
+ raise TypeError(msg)
return APIStats(
**{field.name: getattr(self, field.name) + getattr(other, field.name) for field in fields(self)}
@@ -59,7 +60,8 @@ class APIStats(Serializable):
def replace(self, other):
if not isinstance(other, APIStats):
- raise TypeError("Can only replace APIStats with APIStats")
+ msg = "Can only replace APIStats with APIStats"
+ raise TypeError(msg)
return APIStats(**{field.name: getattr(other, field.name) for field in fields(self)})
@@ -107,9 +109,8 @@ class BaseModel:
self.api_model = args.model_name.split("bedrock:", 1)[1]
self.model_metadata = MODELS[self.api_model]
else:
- raise ValueError(
- f"Unregistered model ({args.model_name}). Add model name to MODELS metadata to {self.__class__}"
- )
+ msg = f"Unregistered model ({args.model_name}). Add model name to MODELS metadata to {self.__class__}"
+ raise ValueError(msg)
def reset_stats(self, other: APIStats | None = None):
if other is None:
@@ -157,15 +158,18 @@ class BaseModel:
# Check whether total cost or instance cost limits have been exceeded
if 0 < self.args.total_cost_limit <= self.stats.total_cost:
logger.warning(f"Cost {self.stats.total_cost:.2f} exceeds limit {self.args.total_cost_limit:.2f}")
- raise CostLimitExceededError("Total cost limit exceeded")
+ msg = "Total cost limit exceeded"
+ raise CostLimitExceededError(msg)
if 0 < self.args.per_instance_cost_limit <= self.stats.instance_cost:
logger.warning(f"Cost {self.stats.instance_cost:.2f} exceeds limit {self.args.per_instance_cost_limit:.2f}")
- raise CostLimitExceededError("Instance cost limit exceeded")
+ msg = "Instance cost limit exceeded"
+ raise CostLimitExceededError(msg)
return cost
def query(self, history: list[dict[str, str]]) -> str:
- raise NotImplementedError("Use a subclass of BaseModel")
+ msg = "Use a subclass of BaseModel"
+ raise NotImplementedError(msg)
class OpenAIModel(BaseModel):
@@ -279,7 +283,8 @@ class OpenAIModel(BaseModel):
top_p=self.args.top_p,
)
except BadRequestError:
- raise CostLimitExceededError(f"Context window ({self.model_metadata['max_context']} tokens) exceeded")
+ msg = f"Context window ({self.model_metadata['max_context']} tokens) exceeded"
+ raise CostLimitExceededError(msg)
# Calculate + update costs, return response
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
@@ -411,9 +416,11 @@ class BedrockModel(BaseModel):
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
self.api = AnthropicBedrock()
elif self.model_provider in ["ai21", "amazon", "cohere", "meta", "mistral"]:
- raise NotImplementedError(f"{self.api_model} is not supported!")
+ msg = f"{self.api_model} is not supported!"
+ raise NotImplementedError(msg)
else:
- raise ValueError(f"Provider {self.model_provider} is not supported by Amazon Bedrock!")
+ msg = f"Provider {self.model_provider} is not supported by Amazon Bedrock!"
+ raise ValueError(msg)
def history_to_messages(
self, history: list[dict[str, str]], is_demonstration: bool = False
@@ -424,7 +431,8 @@ class BedrockModel(BaseModel):
if self.model_provider == "anthropic":
return anthropic_history_to_messages(self, history, is_demonstration)
else:
- raise NotImplementedError(f"{self.api_model} is not supported!")
+ msg = f"{self.api_model} is not supported!"
+ raise NotImplementedError(msg)
@retry(
wait=wait_random_exponential(min=1, max=15),
@@ -439,7 +447,8 @@ class BedrockModel(BaseModel):
if self.model_provider == "anthropic":
return anthropic_query(self, history)
else:
- raise NotImplementedError(f"{self.api_model} is not supported!")
+ msg = f"{self.api_model} is not supported!"
+ raise NotImplementedError(msg)
def anthropic_history_to_messages(
@@ -781,7 +790,8 @@ class ReplayModel(BaseModel):
super().__init__(args, commands)
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")
+ 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.replay_idx = 0
@@ -867,4 +877,5 @@ def get_model(args: ModelArguments, commands: list[Command] | None = None):
elif args.model_name == "instant_empty_submit":
return InstantEmptySubmitTestModel(args, commands)
else:
- raise ValueError(f"Invalid model name: {args.model_name}")
+ msg = f"Invalid model name: {args.model_name}"
+ raise ValueError(msg)
diff --git a/sweagent/agent/parsing.py b/sweagent/agent/parsing.py
index 2598f510..beb627f6 100644
--- a/sweagent/agent/parsing.py
+++ b/sweagent/agent/parsing.py
@@ -48,7 +48,8 @@ class ParseFunction(metaclass=ParseFunctionMeta):
@property
def format_error_template(self):
if self._error_message is None:
- raise NotImplementedError("You must define an error message for your parser.")
+ msg = "You must define an error message for your parser."
+ raise NotImplementedError(msg)
return textwrap.dedent(self._error_message)
@classmethod
@@ -56,7 +57,8 @@ class ParseFunction(metaclass=ParseFunctionMeta):
try:
return cls._registry[name]()
except KeyError:
- raise ValueError(f"Model output parser ({name}) not found.")
+ msg = f"Model output parser ({name}) not found."
+ raise ValueError(msg)
# DEFINE NEW PARSING FUNCTIONS BELOW THIS LINE
@@ -80,7 +82,8 @@ class ActionParser(ParseFunction):
action = model_response.strip().split()[0]
if action in {command.name for command in commands}:
return model_response, model_response
- raise FormatError("First word in model response is not a valid command.")
+ msg = "First word in model response is not a valid command."
+ raise FormatError(msg)
class ThoughtActionParser(ParseFunction):
@@ -135,7 +138,8 @@ class ThoughtActionParser(ParseFunction):
start, end = last_valid_block
thought = model_response[: start.start()] + model_response[end.end() :]
return thought, model_response[start.end() : end.start()]
- raise FormatError("No action found in model response.")
+ msg = "No action found in model response."
+ raise FormatError(msg)
class XMLThoughtActionParser(ParseFunction):
@@ -170,7 +174,8 @@ class XMLThoughtActionParser(ParseFunction):
In this case, only the second code block will be parsed as the action.
"""
if "<command>" not in model_response or "</command>" not in model_response:
- raise FormatError("No action found in model response.")
+ msg = "No action found in model response."
+ raise FormatError(msg)
# `action` is everything between the last <command> and </command> tags
start_action = model_response.rfind("<command>") + len("<command>") # start after the last <command> tag
end_thought = model_response.rfind("<command>") # end before the last <command> tag
@@ -256,24 +261,28 @@ class JsonParser(ParseFunction):
try:
data = json.loads(model_response)
if not isinstance(data, dict):
- raise FormatError("Model output is not a JSON object.")
+ msg = "Model output is not a JSON object."
+ raise FormatError(msg)
# Check if required keys are present
required_keys = ["thought", "command"]
for key in required_keys:
if key not in data:
- raise FormatError(f"Key '{key}' is missing from model output.")
+ msg = f"Key '{key}' is missing from model output."
+ raise FormatError(msg)
# Check structure of 'command' key
data_command = data["command"]
if not isinstance(data_command, dict):
- raise FormatError("Value of 'command' key is not a JSON object.")
+ msg = "Value of 'command' key is not a JSON object."
+ raise FormatError(msg)
# Check if required keys are present in 'command' object
command_keys = ["name"]
for key in command_keys:
if key not in data_command:
- raise FormatError(f"Key '{key}' is missing from 'command' object.")
+ msg = f"Key '{key}' is missing from 'command' object."
+ raise FormatError(msg)
thought = data["thought"]
@@ -301,7 +310,8 @@ class JsonParser(ParseFunction):
action = action.strip()
return thought, action
except json.JSONDecodeError:
- raise FormatError("Model output is not valid JSON.")
+ msg = "Model output is not valid JSON."
+ raise FormatError(msg)
def extract_keys(format_string):
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index 30b495c6..93c47497 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -147,7 +147,8 @@ def run():
elif environment_input_type == "script_path":
environment_setup = run.environment.environment_setup.script_path["script_path"]
else:
- raise ValueError(f"Unknown input type: {environment_input_type}")
+ msg = f"Unknown input type: {environment_input_type}"
+ raise ValueError(msg)
if not environment_setup.strip():
environment_setup = None
test_run: bool = run.extra.test_run
diff --git a/sweagent/api/utils.py b/sweagent/api/utils.py
index cdc7f94b..3286de7e 100644
--- a/sweagent/api/utils.py
+++ b/sweagent/api/utils.py
@@ -15,15 +15,18 @@ def _async_raise(tid, exctype):
URL: https://stackoverflow.com/a/325528/
"""
if not inspect.isclass(exctype):
- raise TypeError("Only types can be raised (not instances)")
+ msg = "Only types can be raised (not instances)"
+ raise TypeError(msg)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
if res == 0:
- raise ValueError("invalid thread id")
+ msg = "invalid thread id"
+ raise ValueError(msg)
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
- raise SystemError("PyThreadState_SetAsyncExc failed")
+ msg = "PyThreadState_SetAsyncExc failed"
+ raise SystemError(msg)
class ThreadWithExc(threading.Thread):
@@ -44,7 +47,8 @@ class ThreadWithExc(threading.Thread):
instance.
"""
if not self.is_alive():
- raise threading.ThreadError("the thread is not active")
+ msg = "the thread is not active"
+ raise threading.ThreadError(msg)
# do we have it cached?
if hasattr(self, "_thread_id"):
@@ -56,7 +60,8 @@ class ThreadWithExc(threading.Thread):
self._thread_id = tid
return tid
- raise RuntimeError("could not determine the thread's id")
+ msg = "could not determine the thread's id"
+ raise RuntimeError(msg)
def raise_exc(self, exctype):
"""Raises the given exception type in the context of this thread.
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 44833df1..10af8b11 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -483,7 +483,8 @@ class SWEEnv(gym.Env):
client = docker.from_env(timeout=600)
except docker.errors.DockerException as e:
if "Error while fetching server API version" in str(e):
- raise RuntimeError("Docker is not running. Please start Docker and try again.") from e
+ msg = "Docker is not running. Please start Docker and try again."
+ raise RuntimeError(msg) from e
try:
self.container_obj = client.containers.get(self.container_name)
except docker.errors.NotFound:
@@ -531,7 +532,8 @@ class SWEEnv(gym.Env):
except BrokenPipeError:
traceback.print_exc()
self.logger.error("Failed to communicate with container. Check docker logs for more information.")
- raise RuntimeError("Failed to communicate with container")
+ msg = "Failed to communicate with container"
+ raise RuntimeError(msg)
buffer, exit_code = read_with_timeout_experimental(self.container, timeout_duration)
self.returncode = int(exit_code)
@@ -553,7 +555,8 @@ class SWEEnv(gym.Env):
except BrokenPipeError:
traceback.print_exc()
self.logger.error("Failed to communicate with container. Check docker logs for more information.")
- raise RuntimeError("Failed to communicate with container")
+ msg = "Failed to communicate with container"
+ raise RuntimeError(msg)
try:
buffer = read_with_timeout(self.container, self.get_pids, timeout_duration)
self.container.stdin.write("echo $?\n")
@@ -564,7 +567,8 @@ class SWEEnv(gym.Env):
self.logger.error(f"Read with timeout failed on input:\n---\n{input}\n---")
raise e
if not exit_code.isdigit():
- raise RuntimeError(f"Container crashed. Failed to get exit code. Output:\n---\n{buffer}\n---")
+ msg = f"Container crashed. Failed to get exit code. Output:\n---\n{buffer}\n---"
+ raise RuntimeError(msg)
self.returncode = int(exit_code)
return buffer
@@ -613,7 +617,8 @@ class SWEEnv(gym.Env):
if self.returncode != 0:
self.logger.error(f"{error_msg}: {logs}")
self.close()
- raise RuntimeError(f"{error_msg}: {logs}")
+ msg = f"{error_msg}: {logs}"
+ raise RuntimeError(msg)
return logs
def get_available_actions(self) -> list[str]:
@@ -657,12 +662,14 @@ class SWEEnv(gym.Env):
return self._run_shell_script_host(script_path)
elif location == "container":
raise NotImplementedError
- raise ValueError(f"Invalid 'location': {location}")
+ msg = f"Invalid 'location': {location}"
+ raise ValueError(msg)
def _run_shell_script_host(self, script_path: Path) -> None:
"""Run shell script file (located on host) in container"""
if not script_path.is_file():
- raise FileNotFoundError(f"Script not found at {script_path}")
+ msg = f"Script not found at {script_path}"
+ raise FileNotFoundError(msg)
shell_commands = Path(script_path).read_text().splitlines()
for i, cmd in enumerate(shell_commands):
self.communicate_with_handling(
@@ -699,7 +706,8 @@ class SWEEnv(gym.Env):
self.run_shell_script(Path(self.args.environment_setup), location="host")
return
else:
- raise ValueError("Environment config file needs to be a yaml file or shell script")
+ msg = "Environment config file needs to be a yaml file or shell script"
+ raise ValueError(msg)
else:
try:
install_configs = MAP_VERSION_TO_INSTALL[self.record["repo"]][str(self.record["version"])]
@@ -831,7 +839,8 @@ class SWEEnv(gym.Env):
# nothing to do for utility scripts
pass
else:
- raise ValueError(f"Invalid command type: {command['type']}")
+ msg = f"Invalid command type: {command['type']}"
+ raise ValueError(msg)
def interrupt(self):
"""
@@ -849,7 +858,8 @@ class SWEEnv(gym.Env):
output = self.communicate(input="echo 'interrupted'", timeout_duration=5)
assert output.strip().endswith("interrupted"), "container health check failed"
except TimeoutError:
- raise RuntimeError("Failed to interrupt container")
+ msg = "Failed to interrupt container"
+ raise RuntimeError(msg)
def open_pr(self, *, trajectory, _dry_run: bool = False):
"""Create PR to repository
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 21ca5859..f35563a5 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -169,11 +169,11 @@ def read_with_timeout(container, pid_func, timeout_duration):
time.sleep(0.05) # Prevents CPU hogging
if container.poll() is not None:
- raise RuntimeError(f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}")
+ msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"
+ raise RuntimeError(msg)
if time.time() >= end_time:
- raise TimeoutError(
- f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}\nRunning PIDs: {pids}"
- )
+ msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}\nRunning PIDs: {pids}"
+ raise TimeoutError(msg)
return buffer.decode()
@@ -230,15 +230,18 @@ def read_with_timeout_experimental(container, timeout_duration):
time.sleep(0.01) # Prevents CPU hogging
if container.poll() is not None:
- raise RuntimeError(f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}")
+ msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"
+ raise RuntimeError(msg)
if time.time() >= end_time:
- raise TimeoutError(f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}")
+ msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}"
+ raise TimeoutError(msg)
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]
_results = PROCESS_DONE_REGEX.search(last_line)
if _results is None:
- raise ValueError(f"Could not find process done marker in last line: {last_line=}, {body=}")
+ msg = f"Could not find process done marker in last line: {last_line=}, {body=}"
+ raise ValueError(msg)
exit_code = _results.group(1)
return body, exit_code
@@ -297,7 +300,8 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =
elif container_obj.status in {"paused"}:
container_obj.unpause()
else:
- raise RuntimeError(f"Unexpected container status: {container_obj.status}")
+ msg = f"Unexpected container status: {container_obj.status}"
+ raise RuntimeError(msg)
else:
container_obj = client.containers.run(
image_name,
@@ -345,9 +349,8 @@ def _get_persistent_container(ctr_name: str, image_name: str, persistent: bool =
if len(bash_pids) == 1:
bash_pid = bash_pids[0][0]
elif len(bash_pids) > 1 or len(other_pids) > 0:
- raise RuntimeError(
- f"Detected alien processes attached or running. Please ensure that no other agents are running on this container. PIDs: {bash_pids}, {other_pids}"
- )
+ msg = f"Detected alien processes attached or running. Please ensure that no other agents are running on this container. PIDs: {bash_pids}, {other_pids}"
+ raise RuntimeError(msg)
return container, set(
map(
str,
@@ -451,7 +454,8 @@ 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:
- raise InvalidGithubURL(f"Invalid GitHub issue URL: {issue_url}")
+ msg = f"Invalid GitHub issue URL: {issue_url}"
+ raise InvalidGithubURL(msg)
res = match.groups()
assert len(res) == 3
return tuple(res) # type: ignore
@@ -461,7 +465,8 @@ 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:
- raise InvalidGithubURL(f"Invalid GitHub issue URL: {repo_url}")
+ msg = f"Invalid GitHub issue URL: {repo_url}"
+ raise InvalidGithubURL(msg)
res = match.groups()
assert len(res) == 2
return tuple(res) # type: ignore
@@ -560,7 +565,8 @@ class InstanceBuilder:
elif Path(repo).is_dir():
self.set_repo_info_from_local_path(repo, base_commit=base_commit)
else:
- raise ValueError(f"Could not determine repo path from {repo=}.")
+ msg = f"Could not determine repo path from {repo=}."
+ raise ValueError(msg)
def set_from_dict(self, instance_dict: dict[str, Any]):
self.args |= instance_dict
@@ -587,11 +593,14 @@ class InstanceBuilder:
]
if not all(x in self.args for x in required_fields):
missing = set(required_fields) - set(self.args.keys())
- raise ValueError(f"Missing required fields: {missing=}")
+ msg = f"Missing required fields: {missing=}"
+ raise ValueError(msg)
if self.args["repo_type"] not in {"github", "local"}:
- raise ValueError(f"Invalid repo type: {self.args['repo_type']=}")
+ msg = f"Invalid repo type: {self.args['repo_type']=}"
+ raise ValueError(msg)
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']=}")
+ msg = f"Invalid repo format for {self.args['repo_type']=}: {self.args['repo']=}"
+ raise ValueError(msg)
def build(self) -> dict[str, Any]:
self.set_missing_fields()
@@ -641,7 +650,8 @@ def get_instances(
elif is_github_repo_url(file_path):
ib.set_repo_info_from_gh_url(file_path, base_commit=base_commit)
else:
- raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")
+ msg = f"Could not determine repo path from {file_path=}, {repo_path=}"
+ raise ValueError(msg)
return [ib.build()]
@@ -677,12 +687,14 @@ def get_instances(
elif is_github_repo_url(file_path):
ib.set_repo_info_from_gh_url(file_path)
else:
- raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")
+ msg = f"Could not determine repo path from {file_path=}, {repo_path=}"
+ raise ValueError(msg)
return [ib.build()]
if base_commit is not None:
- raise ValueError("base_commit must be None if data_path is not a github issue url")
+ msg = "base_commit must be None if data_path is not a github issue url"
+ raise ValueError(msg)
# If file_path is a file, load the file
if file_path.endswith(".json"):
@@ -694,10 +706,11 @@ def get_instances(
try:
return postproc_instance_list(load_dataset(file_path, split=split))
except:
- raise ValueError(
+ msg = (
f"Could not load instances from {file_path}. "
"Please ensure --data_path is a GitHub URL, a SWE-bench HuggingFace dataset, or a JSON/JSONL file."
)
+ raise ValueError(msg)
def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token: str = "") -> list[str]:
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index 02e4daca..de321937 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -42,7 +42,8 @@ class Config:
return os.environ[key]
if self._keys_cfg is not None and key in self._keys_cfg:
return self._keys_cfg[key]
- raise KeyError(f"Key {key} not found in environment or keys.cfg")
+ msg = f"Key {key} not found in environment or keys.cfg"
+ raise KeyError(msg)
def __contains__(self, key: str) -> bool:
return key in os.environ or (self._keys_cfg is not None and key in self._keys_cfg)
diff --git a/tests/test_run.py b/tests/test_run.py
index 4c1efae9..97ecddb3 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -93,7 +93,8 @@ 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]):
- raise ValueError("test exception")
+ msg = "test exception"
+ raise ValueError(msg)
@pytest.fixture