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]
SWE-bench batch instances need to set repo name
Kilian Lieret5d429d997fec
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 0fcb8dd7..ca32c821 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -304,17 +304,24 @@ class Agent:# Populate selected template(s) with information (e.g., issue, arguments, state)messages = []assert self._problem_statement is not None++ format_dict = dict(+ command_docs=self.tools.config.command_docs,+ **self.tools.config.env_variables,+ **state,+ observation=observation or "",+ **self._forwarded_vars,+ problem_statement=self._problem_statement.get_problem_statement(),+ )+for template in templates:- messages.append(- template.format(- command_docs=self.tools.config.command_docs,- **self.tools.config.env_variables,- **state,- observation=observation or "",- **self._forwarded_vars,- problem_statement=self._problem_statement.get_problem_statement(),- ),- )+ try:+ messages.append(+ template.format(**format_dict),+ )+ except KeyError:+ self.logger.debug("The following keys are available: %s", format_dict.keys())+ raisemessage = "\n".join(messages)diff --git a/sweagent/environment/config/deployment.py b/sweagent/environment/config/deployment.pyindex 01fdff02..ac95a09a 100644--- a/sweagent/environment/config/deployment.py+++ b/sweagent/environment/config/deployment.py@@ -35,6 +35,11 @@ class DockerDeploymentConfig(BaseModel):image: str = "sweagent/swe-agent:latest"+ startup_timeout: float = 60.0+ """Timeout for the startup of the docker container.+ This can take a while especially if swe-rex isn't installed yet.+ """+type: Literal["docker"] = "docker""""Discriminator for (de)serialization/CLI. Do not change."""@@ -45,6 +50,11 @@ class DockerDeploymentConfig(BaseModel):class ModalDeploymentConfig(BaseModel):image: str = "sweagent/swe-agent:latest"+ startup_timeout: float = 60.0+ """Timeout for the startup of the modal app.+ This can take a while especially if swe-rex isn't installed yet.+ """+type: Literal["modal"] = "modal""""Discriminator for (de)serialization/CLI. Do not change."""diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.pyindex cec2830b..f918bdf0 100644--- a/sweagent/environment/config/problem_statement.py+++ b/sweagent/environment/config/problem_statement.py@@ -49,6 +49,9 @@ class TextProblemStatement(BaseModel):def get_problem_statement(self) -> str:return self.text+ def __repr__(self) -> str:+ return f"TextProblemStatement(id={self.id}, text={self.text[:30]}...)"+class FileProblemStatement(BaseModel):path: Pathdiff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.pyindex 4f203474..0865b475 100644--- a/sweagent/environment/config/repo.py+++ b/sweagent/environment/config/repo.py@@ -24,6 +24,25 @@ class Repo(Protocol):def copy(self, deployment: AbstractDeployment): ...+class PreExistingRepo(BaseModel):+ """Use this to specify a repository that already exists on the deployment.+ This is important because we need to cd to the repo before running the agent.++ Note: The repository must be at the root of the deployment.+ """++ repo_name: str+ """The repo name (the repository must be located at the root of the deployment)."""+ base_commit: str = "HEAD"+ """Used to reset repo."""++ type: Literal["preexisting"] = "preexisting"+ """Discriminator for (de)serialization/CLI. Do not change."""++ def copy(self, deployment: AbstractDeployment):+ pass++class LocalRepoConfig(BaseModel):path: str = ""base_commit: str = "HEAD"@@ -108,22 +127,25 @@ class GithubRepoConfig(BaseModel):)-RepoConfig = LocalRepoConfig | GithubRepoConfig+RepoConfig = LocalRepoConfig | GithubRepoConfig | PreExistingRepodef repo_from_simplified_input(- *, input: str, base_commit: str = "HEAD", type: Literal["local", "github", "auto"] = "auto"+ *, input: str, base_commit: str = "HEAD", type: Literal["local", "github", "preexisting", "auto"] = "auto") -> RepoConfig:"""Get repo config from a simplified input.Args:input: Local path or GitHub URL- type: The type of repo. Set to "auto" to automatically detect the type.+ type: The type of repo. Set to "auto" to automatically detect the type+ (does not work for preexisting repos)."""if type == "local":return LocalRepoConfig(path=input, base_commit=base_commit)if type == "github":return GithubRepoConfig(url=input, base_commit=base_commit)+ if type == "preexisting":+ return PreExistingRepo(repo_name=input, base_commit=base_commit)if type == "auto":if input.startswith("https://github.com/"):return GithubRepoConfig(url=input, base_commit=base_commit)diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex e0e3ca0a..9464e521 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -9,6 +9,7 @@ from pydantic import BaseModel, Fieldfrom sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfigfrom sweagent.environment.config.problem_statement import ProblemStatementConfig, TextProblemStatement+from sweagent.environment.config.repo import PreExistingRepofrom sweagent.environment.swe_env import EnvironmentConfigfrom sweagent.utils.log import get_logger@@ -84,43 +85,55 @@ def _filter_batch_items(instances: list[BatchInstance], *, filter: str, slice: sclass SimpleBatchInstance(BaseModel):"""A simple way to configure a single instance in a batch of instances that alluse similar deployment configurations.++ Predominantly used for benchmarking purposes. Assumes that the repository is already+ present in the docker container."""image_name: strproblem_statement: strid: str+ repo_name: str+ """The repo name or path within the docker container/environment."""+ base_commit: str = "HEAD"+ """Used to reset repo."""def to_full_batch_instance(self, deployment: DeploymentConfig) -> BatchInstance:"""Merge the deployment options into the `SimpleBatchInstance` object to get a full `BatchInstance`."""# 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.+ problem_statement = TextProblemStatement(text=self.problem_statement, id=self.id)+ repo = PreExistingRepo(repo_name=self.repo_name, base_commit=self.base_commit)if deployment.type == "local":if self.image_name:msg = "Local deployment does not support image name"raise ValueError(msg)return BatchInstance(- env=EnvironmentConfig(deployment=deployment, repo=None),- problem_statement=TextProblemStatement(text=self.problem_statement, id=self.id),+ env=EnvironmentConfig(deployment=deployment, repo=repo), problem_statement=problem_statement)if deployment.type == "dummy":return BatchInstance(- env=EnvironmentConfig(deployment=deployment, repo=None),- problem_statement=TextProblemStatement(text=self.problem_statement, id=self.id),+ env=EnvironmentConfig(deployment=deployment, repo=repo), problem_statement=problem_statement)deployment.image = self.image_name- problem_statement = TextProblemStatement(text=self.problem_statement, id=self.id)return BatchInstance(- env=EnvironmentConfig(deployment=deployment, repo=None), problem_statement=problem_statement+ env=EnvironmentConfig(deployment=deployment, repo=repo), problem_statement=problem_statement)@classmethoddef from_swe_bench(cls, instance: dict[str, Any]) -> Self:"""Convert instances from the classical SWE-bench dataset to the `SimpleBatchInstance` format."""- id_ = instance["instance_id"]+ iid = instance["instance_id"]# Docker doesn't allow double underscore, so we replace them with a magic token- id_docker_compatible = id_.replace("__", "_1776_")+ id_docker_compatible = iid.replace("__", "_1776_")image_name = f"swebench/sweb.eval.x86_64.{id_docker_compatible}:v1"- return cls(image_name=image_name, problem_statement=instance["problem_statement"], id=id_)+ return cls(+ image_name=image_name,+ problem_statement=instance["problem_statement"],+ id=iid,+ repo_name="testbed",+ base_commit=instance["base_commit"],+ )class InstancesFromFile(BaseModel, AbstractInstanceSource):diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.pyindex 754b27b3..f22eae76 100644--- a/sweagent/run/run_batch.py+++ b/sweagent/run/run_batch.py@@ -128,12 +128,14 @@ class RunBatch:except KeyboardInterrupt:raise _BreakLoopexcept SystemExit:+ if self._raise_exceptions:+ raiseself.logger.critical("❌ Exiting because SystemExit was called")raise _BreakLoopexcept Exception as e:self.logger.error(traceback.format_exc())if self._raise_exceptions:- raise _BreakLoop+ raiseself.logger.warning(f"❌ Failed on {instance.problem_statement.id}: {e}")def _run_instance(self, instance: BatchInstance):diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.pyindex e8f2d5cc..f2c32d81 100644--- a/sweagent/tools/tools.py+++ b/sweagent/tools/tools.py@@ -225,6 +225,7 @@ class ToolHandler:return {}output = env.communicate(self.config.state_command.name, check=True).strip()if not output:+ self.logger.warning("State command %s returned empty output", self.config.state_command.name)return {}try:state = json.loads(output)diff --git a/tests/test_batch_instance.py b/tests/test_batch_instance.pynew file mode 100644index 00000000..6236b1ce--- /dev/null+++ b/tests/test_batch_instance.py@@ -0,0 +1,41 @@+import json++import pytest++from sweagent.environment.config.deployment import DockerDeploymentConfig+from sweagent.environment.config.problem_statement import TextProblemStatement+from sweagent.environment.config.repo import PreExistingRepo+from sweagent.run.batch_instances import BatchInstance, SimpleBatchInstance, SWEBenchInstances, _slice_spec_to_slice+++def test_simple_batch_from_swe_bench_to_full_batch_instance(test_data_sources_path):+ sb_instance = json.loads((test_data_sources_path / "swe-bench-dev-easy.json").read_text())[0]+ instance = SimpleBatchInstance.from_swe_bench(sb_instance).to_full_batch_instance(DockerDeploymentConfig())+ assert isinstance(instance.env.repo, PreExistingRepo)+ assert instance.env.repo.repo_name == "testbed"+ assert isinstance(instance.env.deployment, DockerDeploymentConfig)+ assert instance.env.deployment.image == "swebench/sweb.eval.x86_64.pydicom_1776_pydicom-1458:v1"+ assert isinstance(instance.problem_statement, TextProblemStatement)+ assert instance.problem_statement.text == sb_instance["problem_statement"]+ assert instance.problem_statement.id == "pydicom__pydicom-1458"+++def test_slice_spec_to_slice():+ assert _slice_spec_to_slice("10") == slice(10)+ assert _slice_spec_to_slice("10:20") == slice(10, 20)+ assert _slice_spec_to_slice("10:20:3") == slice(10, 20, 3)+ with pytest.raises(ValueError):+ _slice_spec_to_slice("10:20:3:4")+++def test_get_swe_bench_instances():+ for flavor in ["lite", "verified", "full"]:+ for split in ["dev", "test"]:+ if flavor == "verified" and split == "dev":+ continue+ print(flavor, split)+ instance_config = SWEBenchInstances(flavor=flavor, split=split) # type: ignore+ instances = instance_config.get_instance_configs()+ assert len(instances) > 0+ assert all(isinstance(instance, BatchInstance) for instance in instances)diff --git a/tests/test_run_batch.py b/tests/test_run_batch.pyindex 9838fe0e..afcd7358 100644--- a/tests/test_run_batch.py+++ b/tests/test_run_batch.py@@ -82,3 +82,25 @@ def test_empty_instances_expert(test_data_sources_path: Path, tmp_path: Path):]with pytest.raises(ValueError, match="No instances to run"):main(cmd)+++# This doesn't work because we need to retrieve environment variables from the environment+# in order to format our templates.+# def test_run_batch_swe_bench_instances(tmp_path: Path):+# cmd = [+# "run-batch",+# "--agent.model.name",+# "instant_empty_submit",+# "--instances.flavor",+# "lite",+# "--instances.split",+# "test",+# "--instances.slice",+# "0:1",+# "--output_dir",+# str(tmp_path),+# "--raise_exceptions",+# "--instances.deployment.type",+# "dummy",+# ]+# main(cmd)