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 SWE-bench instances; remove utils.py

Kilian Lieret4661ebfc3c27
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index b861ed0c..003ae11a 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -16,9 +16,6 @@ from sweagent.environment.config.deployment import DeploymentConfig, DockerDeplo
from sweagent.environment.config.problem_statement import EmptyProblemStatement, ProblemStatementConfig
from sweagent.environment.config.repo import RepoConfig
from sweagent.environment.hooks.abstract import EnvHook
-from sweagent.environment.utils import (
- NoOutputTimeoutError,
-)
from sweagent.types import AgentInfo
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
@@ -262,6 +259,7 @@ class SWEEnv:
observation = "Exited"
info["exit_status"] = action
return observation, 0, True, info
+ # todo: pull out a handle_exit_action function
if action in {"exit_context", "exit_cost", "exit_error", "exit_format", "exit_api"}:
try:
observation = self.communicate(input="submit")
@@ -290,23 +288,6 @@ class SWEEnv:
no_output_timeout_duration=AGENT_ACTION_NO_OUTPUT_TIMEOUT,
set_last_action=True,
)
- except TimeoutError as e:
- try:
- observation += e.args[1] if len(e.args) > 1 else ""
- # observation += self.interrupt()
- observation += "\nEXECUTION TIMED OUT"
- observation += (
- f" BECAUSE NO OUTPUT WAS PRODUCED FOR MORE THAN {AGENT_ACTION_NO_OUTPUT_TIMEOUT} SECONDS.\nPLEASE REFINE YOUR RUNNING COMMAND SO IT WILL PRODUCE OUTPUT IN THE SPECIFIED TIME FRAME."
- if isinstance(e, NoOutputTimeoutError)
- else f" BECAUSE THE COMMAND WAS RUNNING FOR MORE THAN {AGENT_ACTION_TIMEOUT} SECONDS."
- )
- except RuntimeError as e:
- observation += e.args[1] if len(e.args) > 1 else ""
- observation += "\nEXECUTION TIMED OUT AND INTERRUPT FAILED. RESTARTING PROCESS."
- info["exit_status"] = "early_exit"
- self.logger.warning(f"Failed to interrupt container: {e}\nRESTARTING PROCESS.")
- self.reset_container()
- return observation, 0, True, info
except RuntimeError as e:
observation += e.args[1] if len(e.args) > 1 else ""
observation += "\nCOMMAND FAILED TO EXECUTE. RESTARTING PROCESS."
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
deleted file mode 100644
index 375fd582..00000000
--- a/sweagent/environment/utils.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from __future__ import annotations
-
-import hashlib
-import json
-from pathlib import Path
-from typing import Any
-
-from datasets import load_dataset, load_from_disk
-
-from sweagent.utils._github import GITHUB_ISSUE_URL_PATTERN
-from sweagent.utils.log import get_logger
-
-logger = get_logger("env_utils")
-
-
-def get_data_path_name(data_path: str) -> str:
- """if data_path is a file, return the file stem
- elif it's a github url, return the owner__repo_name
- """
- if data_path.startswith("text://"):
- return hashlib.sha256(data_path.removeprefix("text://").encode()).hexdigest()[:6]
- match = GITHUB_ISSUE_URL_PATTERN.search(data_path)
- if match:
- owner, repo, _ = match.groups()
- return f"{owner}__{repo}"
- return Path(data_path).stem
-
-
-class InvalidGithubURL(ValueError): ...
-
-
-def get_instances(
- file_path: str,
- base_commit: str | None = None,
- split: str | None = None,
- token: str | None = None,
- *,
- repo_path: str = "",
-) -> list[dict[str, Any]]:
- """
- Getter function for handling json, jsonl files
-
- Args:
- file_path (str): Path to file
-
- Returns:
- List of instances as dictionaries
- """
-
- def instance_from_dict(instances):
- raise NotImplementedError
- # ib = InstanceBuilder(token=token)
- # ib.set_from_dict(instances)
- # return ib.build()
-
- def postproc_instance_list(instances):
- if isinstance(instances, dict):
- msg = "Expected a list of instances, got a dictionary."
- raise ValueError(msg)
- return [instance_from_dict(x) for x in instances]
-
- # The next if statement is very brittle logic to determine if we're processing a single instance
- if base_commit:
- msg = "base_commit must be empty if running over multiple problem statements"
- raise ValueError(msg)
-
- if repo_path:
- if not Path(repo_path).exists():
- msg = f"Specified repository path {repo_path} does not exist"
- raise FileNotFoundError(msg)
- msg = "repo_path must be empty if running over multiple problem statements"
- raise ValueError(msg)
-
- # If file_path is a directory, attempt load from disk
- if Path(file_path).is_dir():
- try:
- dataset_or_dict = load_from_disk(file_path)
- if isinstance(dataset_or_dict, dict):
- return postproc_instance_list(dataset_or_dict[split])
- return postproc_instance_list(dataset_or_dict)
- except FileNotFoundError:
- # Raised by load_from_disk if the directory is not a dataset directory
- pass
-
- if base_commit is not None:
- 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"):
- with open(file_path) as file:
- return postproc_instance_list(json.load(file))
- if file_path.endswith(".jsonl"):
- return postproc_instance_list([json.loads(x) for x in Path(file_path).read_text().splitlines(keepends=True)])
-
- # Attempt load from HF datasets as a last resort
- try:
- return postproc_instance_list(load_dataset(file_path, split=split))
- except Exception as e:
- 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) from e
diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.py
index f2eee9c5..49a73f3c 100644
--- a/sweagent/run/batch_instances.py
+++ b/sweagent/run/batch_instances.py
@@ -47,6 +47,8 @@ class BatchInstance(BaseModel):
def _to_env_config(self, deployment_kwargs: dict[str, Any]) -> EnvironmentInstanceConfig:
"""Merge the deployment options into the BatchInstance object to get a full `EnvironmentInstanceConfig`."""
+ # Combine image name and deployment options into a DeploymentConfig object. Because this can be one of many
+ # subclasses, we use a TypeAdapter to validate/instantiate the object.
deployment = TypeAdapter(DeploymentConfig).validate_python(dict(image=self.image_name, **deployment_kwargs))
problem_statement = TextProblemStatement(problem_statement=self.problem_statement)
return EnvironmentInstanceConfig(deployment=deployment, problem_statement=problem_statement, repo=None)
@@ -93,6 +95,21 @@ class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):
return [instance._to_env_config(self.deployment) for instance in simple_instances]
+class SWEBenchInstances(BaseModel, AbstractInstanceSource):
+ """Load instances from SWE-bench."""
+
+ flavor: Literal["lite", "verified", "full"] = "lite"
+
+ deployment: dict[str, Any]
+ """Any options for one of the `DeploymentConfig` subclasses."""
+
+ type: Literal["swe_bench"]
+ """Discriminator for (de)serialization/CLI. Do not change."""
+
+ def get_instance_configs(self) -> list[EnvironmentInstanceConfig]:
+ raise NotImplementedError
+
+
class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
"""Load instances from a file. The difference to `InstancesFromFile` is that the instances are configured as full
`EnvironmentInstanceConfig` objects, i.e., we could specify separate deployment configurations etc.
@@ -110,4 +127,4 @@ class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
return _filter_instances(instances, self.instance_filter)
-InstanceSourceConfig = ExpertInstancesFromFile | InstancesFromHuggingFace | InstancesFromFile
+InstanceSourceConfig = ExpertInstancesFromFile | InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index dfa130d6..f2696a18 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -1,5 +1,5 @@
-"""Run in human mode without any complicated env setup.
-This is mostly for debugging and development.
+"""
+Run on a batch of instances/issues. For example run on all of SWE-bench.
"""
from pathlib import Path
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index 8dad2ffa..a6fe85a9 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -1,6 +1,4 @@
-"""Run in human mode without any complicated env setup.
-This is mostly for debugging and development.
-"""
+"""Run on a single instance taken from github or similar."""
from pathlib import Path
from typing import Self