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]

problem_statement is passed to Agent.run instead of env

Kilian Lieret8dc92f715d16
diff --git a/run.py b/run.py
index 620a58b0..da10854f 100644
--- a/run.py
+++ b/run.py
@@ -38,7 +38,7 @@ from unidiff import PatchSet
from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
__doc__: str = """ Run inference. Usage examples:
@@ -60,7 +60,7 @@ logging.getLogger("simple_parsing").setLevel(logging.WARNING)
class ScriptArguments(BaseSettings):
"""Configure the control flow of the run.py script"""
- environment: EnvironmentInstanceConfig = Field(..., default_factory=EnvironmentInstanceConfig)
+ environment: EnvironmentConfig = Field(..., default_factory=EnvironmentConfig)
agent: AgentConfig = Field(..., default_factory=AgentConfig)
actions: RunSingleActionConfig = Field(..., default_factory=RunSingleActionConfig)
# Only run instances that completely match this regex
@@ -178,7 +178,7 @@ class Main:
# setup_args["port"] = challenge.get("port")
# setup_args["server_description"] = challenge.get("server_description")
info, trajectory = self.agent.run(
- setup_args=setup_args,
+ problem_statement=setup_args,
env=self.env,
observation=observation,
traj_dir=self.traj_dir,
@@ -299,7 +299,7 @@ def get_args(args=None) -> ScriptArguments:
# Otherwise, the configs from the respective classes will be used
no_config_defaults = ScriptArguments(
suffix="",
- environment=EnvironmentInstanceConfig(
+ environment=EnvironmentConfig(
deployment=DockerDeploymentConfig(),
# data_path="princeton-nlp/SWE-bench_Lite",
# split="dev",
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 2b616959..416728f1 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -28,6 +28,7 @@ from sweagent.agent.parsing import FormatError, ParseFunction
# from sweagent.agent.summarizer import SummarizerConfig
from sweagent.agent.utils import _guard_multiline_input
+from sweagent.environment.config.problem_statement import ProblemStatement
from sweagent.environment.swe_env import SWEEnv
from sweagent.types import AgentInfo, History, HistoryItem, Trajectory, TrajectoryStep
from sweagent.utils.config import _convert_paths_to_abspath
@@ -198,7 +199,6 @@ class Agent:
"command_docs": self.config.command_docs,
**self.config.env_variables,
}
- self.instance_args = {}
self._parse_command_patterns()
self.last_container_id = None
self.logger = get_logger("agent", emoji="🤠")
@@ -207,7 +207,8 @@ class Agent:
# Set in run method
self._env: SWEEnv | None = None
- self.traj_dir: None | Path = None
+ self._problem_statement: ProblemStatement | None = None
+ self.traj_path: Path | None = None
#: Number of attempts to solve the issue when using a review loop
self._i_attempt: int = 0
@@ -261,15 +262,6 @@ class Agent:
def info(self, value: AgentInfo):
self._info_by_attempt[self._i_attempt] = value
- @property
- def traj_path(self) -> Path | None:
- """Returns path to the trajectory.
- The path is reset for every new instance.
- """
- if self.traj_dir and self._env is not None:
- return self.traj_dir / (self._env.problem_statement.id + ".traj")
- return None
-
def add_hook(self, hook: AbstractAgentHook) -> None:
"""Add hook to agent"""
hook.on_init(agent=self)
@@ -281,7 +273,7 @@ class Agent:
self.history.append(item)
# todo: klieret: Long term: Might make more sense to reinitialize the agent class for every instance instead of this
- def setup(self, instance_args: dict[str, Any], init_model_stats: APIStats | None = None) -> None:
+ def setup(self, init_model_stats: APIStats | None = None) -> None:
"""Setup the agent for a new instance. This includes
formatting the system message and adding demonstrations to the history.
@@ -289,8 +281,6 @@ class Agent:
instance_args: Arguments for the instance
"""
- self.instance_args = instance_args
-
self._i_attempt = 0
self._history_by_attempt = defaultdict(list)
self._trajectory_by_attempt = defaultdict(list)
@@ -318,7 +308,10 @@ class Agent:
self.model.reset_stats(init_model_stats)
# self.model = get_model(self._args.model, self.config._commands + self.config.subroutine_types)
# fixme: This doesn't reset total cost
- system_msg = self.config.system_template.format(**self.system_args, **self.instance_args)
+ assert self._problem_statement is not None
+ system_msg = self.config.system_template.format(
+ **self.system_args, problem_statement=self._problem_statement.get_problem_statement()
+ )
self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
self._append_history(HistoryItem({"role": "system", "content": system_msg, "agent": self.name}))
# todo: This should be moved somewhere
@@ -513,14 +506,15 @@ class Agent:
# Populate selected template(s) with information (e.g., issue, arguments, state)
messages = []
+ assert self._problem_statement is not None
for template in templates:
messages.append(
template.format(
- **self.instance_args,
**self.system_args,
**state,
observation=observation or "",
**self._forwarded_vars,
+ problem_statement=self._problem_statement.get_problem_statement(),
),
)
@@ -655,10 +649,10 @@ class Agent:
f"exit due to retry error: {e}",
)
- def init_environment_vars(self, env: SWEEnv):
- self.set_environment_vars(env, self.config.env_variables)
+ def init_environment_vars(self):
+ self.set_environment_vars(self.config.env_variables)
- def set_environment_vars(self, env: SWEEnv, env_variables: dict[str, Any]) -> None:
+ def set_environment_vars(self, env_variables: dict[str, Any]) -> None:
"""Sets environment variables in the container and for example makes sure
that all the commands are available in the PATH on the container.
"""
@@ -671,8 +665,9 @@ class Agent:
[f"{k}={v}" for k, v in env_variables.items()]
)
commands = "\n".join(commands_to_execute)
+ assert self._env is not None
try:
- env.communicate(commands, require_zero=True)
+ self._env.communicate(commands, require_zero=True)
except KeyboardInterrupt:
raise
except Exception as e:
@@ -706,8 +701,9 @@ class Agent:
datum["name"] = Path(file).name.rsplit(".", 1)[0]
datum["type"] = "script"
command_files.append(datum)
- env.add_commands(command_files)
+ self._env.add_commands(command_files)
+ # todo: Move to SWEEnv?
def get_environment_vars(self, env: SWEEnv) -> dict[str, Any]:
"""Get environment variables inside of the container"""
env_vars = dict()
@@ -772,13 +768,13 @@ class Agent:
self._chook.on_step_done(trajectory_step=trajectory_step, model_stats=model_stats)
return observation, done
- # todo: Get rid of setup_arts in this unspecified form
+ # todo: Set env already in setup?
def run(
self,
- setup_args: dict[str, Any],
+ problem_statement: ProblemStatement,
env: SWEEnv,
observation: str = "",
- traj_dir: Path | None = None,
+ traj_dir: Path = Path("."),
init_model_stats: APIStats | None = None,
) -> tuple[AgentInfo, Trajectory]:
"""Run the agent on a problem instance. This method contains the
@@ -795,16 +791,18 @@ class Agent:
If return_type is "info_trajectory", returns a tuple of
the info dictionary and the trajectory (list of dictionaries).
"""
- self.init_environment_vars(env)
- self.setup(setup_args, init_model_stats)
+ self._problem_statement = problem_statement
+ self._env = env
+ # todo: Shouldn't this be moved to setup?
+ self.init_environment_vars()
+ self.setup(init_model_stats)
# Save/reset some attributes
self.trajectory = Trajectory()
- self._env = env
self.info = AgentInfo()
self.info["swe_agent_hash"] = get_agent_commit_hash()
self.info["swe_agent_version"] = __version__
- self.traj_dir = traj_dir
+ self.traj_path = traj_dir / (self._problem_statement.id + ".traj")
self.logger.info("Trajectory will be saved to %s", self.traj_path)
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index 232d8c8b..0f7ce5b0 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -35,7 +35,7 @@ from sweagent.agent.agents import AgentConfig
from sweagent.agent.models import ModelArguments
from sweagent.api.hooks import AgentUpdateHook, EnvUpdateHook, MainUpdateHook, WebUpdate
from sweagent.api.utils import AttrDict, ThreadWithExc
-from sweagent.environment.swe_env import EnvironmentInstanceConfig
+from sweagent.environment.swe_env import EnvironmentConfig
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
@@ -157,7 +157,7 @@ def run():
agent_config = OmegaConf.load(CONFIG_DIR / "default_from_url.yaml")
defaults = ScriptArguments(
suffix="",
- environment=EnvironmentInstanceConfig(
+ environment=EnvironmentConfig(
deployment=DeploymentConfig(),
data_path=run.environment.data_path,
base_commit=run.environment.base_commit,
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.py
index 3eb6b8b5..3e8eb396 100644
--- a/sweagent/environment/config/problem_statement.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -1,7 +1,7 @@
import hashlib
import uuid
from pathlib import Path
-from typing import Literal
+from typing import Literal, Protocol
from pydantic import BaseModel, Field
@@ -9,6 +9,14 @@ from sweagent.utils.config import keys_config
from sweagent.utils.github import _get_problem_statement_from_github_issue, _parse_gh_issue_url
+class ProblemStatement(Protocol):
+ """A problem statement for a task."""
+
+ id: str
+
+ def get_problem_statement(self) -> str: ...
+
+
class EmptyProblemStatement(BaseModel):
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
type: Literal["empty"] = "empty"
@@ -18,6 +26,7 @@ class EmptyProblemStatement(BaseModel):
return ""
+# todo: Make id overridable
class TextProblemStatement(BaseModel):
text: str = ""
@@ -32,6 +41,7 @@ class TextProblemStatement(BaseModel):
return self.text
+# todo: Make id overridable
class FileProblemStatement(BaseModel):
path: str = ""
diff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.py
index b9fae72c..4d6fd8bd 100644
--- a/sweagent/environment/config/repo.py
+++ b/sweagent/environment/config/repo.py
@@ -1,11 +1,11 @@
import asyncio
import os
-from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Literal, Self
+from typing import Literal, Protocol, Self
import pydantic
-from git import InvalidGitRepositoryError, Repo
+from git import InvalidGitRepositoryError
+from git import Repo as GitRepo
from pydantic import BaseModel
from swerex.deployment.abstract import AbstractDeployment
from swerex.runtime.abstract import Command, UploadRequest
@@ -13,14 +13,15 @@ from swerex.runtime.abstract import Command, UploadRequest
from sweagent.utils.config import keys_config
-class AbstractRepoConfig(ABC):
- """Abstract base class for repository configurations."""
+class Repo(Protocol):
+ """Protocol for repository configurations."""
+
+ base_commit: str
- @abstractmethod
def copy(self, deployment: AbstractDeployment): ...
-class LocalRepoConfig(BaseModel, AbstractRepoConfig):
+class LocalRepoConfig(BaseModel):
path: str = ""
base_commit: str = "HEAD"
@@ -34,7 +35,7 @@ class LocalRepoConfig(BaseModel, AbstractRepoConfig):
@pydantic.model_validator(mode="after")
def check_valid_repo(self) -> Self:
try:
- repo = Repo(self.path, search_parent_directories=True)
+ repo = GitRepo(self.path, search_parent_directories=True)
except InvalidGitRepositoryError as e:
msg = f"Could not find git repository at {self.path=}."
raise ValueError(msg) from e
@@ -51,7 +52,7 @@ class LocalRepoConfig(BaseModel, AbstractRepoConfig):
raise RuntimeError(msg)
-class GithubRepoConfig(BaseModel, AbstractRepoConfig):
+class GithubRepoConfig(BaseModel):
url: str = ""
base_commit: str = "HEAD"
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 7f2ffb9e..c94a388d 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -12,8 +12,7 @@ from swerex.deployment.abstract import AbstractDeployment
from swerex.runtime.abstract import BashAction, CreateBashSessionRequest, WriteFileRequest
from sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfig
-from sweagent.environment.config.problem_statement import EmptyProblemStatement, ProblemStatementConfig
-from sweagent.environment.config.repo import AbstractRepoConfig, RepoConfig
+from sweagent.environment.config.repo import Repo, RepoConfig
from sweagent.environment.hooks.abstract import EnvHook
from sweagent.types import AgentInfo
from sweagent.utils.config import keys_config
@@ -25,10 +24,9 @@ AGENT_ACTION_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_TIMEOUT", 25))
AGENT_ACTION_NO_OUTPUT_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_NO_OUTPUT_TIMEOUT", AGENT_ACTION_TIMEOUT))
-class EnvironmentInstanceConfig(BaseModel):
+class EnvironmentConfig(BaseModel):
"""Configure data sources and setup instructions for the environment in which we solve the tasks."""
- problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
deployment: DeploymentConfig = Field(default_factory=DockerDeploymentConfig)
repo: RepoConfig | None = None
startup_commands: list[str] = []
@@ -41,9 +39,7 @@ class SWEEnv:
self,
*,
deployment: AbstractDeployment,
- # todo: Should None be included in RepoConfig?
- repo: AbstractRepoConfig | None,
- problem_statement: ProblemStatementConfig,
+ repo: Repo | None,
startup_commands: list[str],
hooks: list[EnvHook] | None = None,
_catch_errors: bool = False,
@@ -55,7 +51,6 @@ class SWEEnv:
self._require_zero_exit_code = _always_require_zero_exit_code
self.deployment = deployment
self.repo = repo
- self.problem_statement = problem_statement
self._startup_commands = startup_commands
self.logger = get_logger("swe_env", emoji="🌱")
@@ -70,11 +65,10 @@ class SWEEnv:
self._init_scripts()
@classmethod
- def from_config(cls, config: EnvironmentInstanceConfig) -> Self:
+ def from_config(cls, config: EnvironmentConfig) -> Self:
return cls(
deployment=config.deployment.get_deployment(),
repo=config.repo,
- problem_statement=config.problem_statement,
startup_commands=config.startup_commands,
)
@@ -113,6 +107,7 @@ class SWEEnv:
self._fire_hooks("on_copy_repo_started", self.repo)
self.repo.copy(self.deployment)
+ # todo: have named return type here
def reset(self) -> tuple[str | None, dict]:
"""Reset the container between each task instance.
@@ -464,6 +459,5 @@ class SWEEnv:
msg = "Repository not set, cannot read file"
raise ValueError(msg)
- # todo: Just use the runtime for this instead
path_in_container = f"/{self.repo.repo_name}/{path}"
return self.communicate(f"cat {str(path_in_container)}")
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
index 7601c6e5..412d5287 100644
--- a/sweagent/main/run_basic.py
+++ b/sweagent/main/run_basic.py
@@ -13,12 +13,12 @@ from pydantic_settings import BaseSettings, CliApp
from sweagent import CONFIG_DIR
from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
from sweagent.utils.log import get_logger
class BasicRunArguments(BaseSettings):
- env: EnvironmentInstanceConfig = Field(default_factory=EnvironmentInstanceConfig)
+ env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
agent: AgentConfig = AgentConfig(
model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
)
@@ -44,7 +44,7 @@ class BasicMain:
observation, info = self.env.reset()
self.logger.info("Running agent")
info, trajectory = self.agent.run(
- setup_args={"problem_statement": self.env.problem_statement.get_problem_statement()},
+ problem_statement={"problem_statement": self.env.problem_statement.get_problem_statement()},
env=self.env,
observation=observation,
traj_dir=Path(self.traj_dir),
diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.py
index 4fb6e8fe..c754e439 100644
--- a/sweagent/run/batch_instances.py
+++ b/sweagent/run/batch_instances.py
@@ -6,16 +6,16 @@ from typing import Any, Literal
from pydantic import BaseModel, TypeAdapter
-from sweagent.environment.config.deployment import DeploymentConfig
-from sweagent.environment.config.problem_statement import TextProblemStatement
-from sweagent.environment.swe_env import EnvironmentInstanceConfig
+from sweagent.environment.config.deployment import DeploymentConfig, LocalDeploymentConfig
+from sweagent.environment.config.problem_statement import ProblemStatement, TextProblemStatement
+from sweagent.environment.swe_env import EnvironmentConfig
class AbstractInstanceSource(ABC):
"""Anything that adheres to this standard can be used to load instances."""
@abstractmethod
- def get_instance_configs(self) -> list[EnvironmentInstanceConfig]: ...
+ def get_instance_configs(self) -> list[EnvironmentConfig]: ...
def _load_file(path: Path) -> Any:
@@ -34,24 +34,43 @@ def _load_file(path: Path) -> Any:
raise NotImplementedError
-def _filter_instances(instances: list[EnvironmentInstanceConfig], filter: str) -> list[EnvironmentInstanceConfig]:
+class BatchInstance(BaseModel):
+ """A single instance in a batch of instances.
+ This specifies both the environment configuration and the problem statement.
+ """
+
+ env: EnvironmentConfig
+ problem_statement: ProblemStatement
+
+
+def _filter_batch_items(instances: list[BatchInstance], filter: str) -> list[BatchInstance]:
return [instance for instance in instances if re.match(filter, instance.problem_statement.id)]
-class BatchInstance(BaseModel):
- """A single instance in a batch of instances."""
+class SimpleBatchInstance(BaseModel):
+ """A simple way to configure a single instance in a batch of instances that all
+ use similar deployment configurations.
+ """
image_name: str
problem_statement: str
id: str
- def _to_env_config(self, deployment_kwargs: dict[str, Any]) -> EnvironmentInstanceConfig:
- """Merge the deployment options into the BatchInstance object to get a full `EnvironmentInstanceConfig`."""
+ def to_full_batch_instance(self, deployment_kwargs: dict[str, Any]) -> 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.
- deployment = TypeAdapter(DeploymentConfig).validate_python(dict(image=self.image_name, **deployment_kwargs))
+ if deployment_kwargs.get("type") == "local":
+ if self.image_name:
+ msg = "Local deployment does not support image name"
+ raise ValueError(msg)
+ deployment = LocalDeploymentConfig(**deployment_kwargs)
+ else:
+ deployment = TypeAdapter(DeploymentConfig).validate_python(dict(image=self.image_name, **deployment_kwargs))
problem_statement = TextProblemStatement(text=self.problem_statement)
- return EnvironmentInstanceConfig(deployment=deployment, problem_statement=problem_statement, repo=None)
+ return BatchInstance(
+ env=EnvironmentConfig(deployment=deployment, repo=None), problem_statement=problem_statement
+ )
class InstancesFromFile(BaseModel, AbstractInstanceSource):
@@ -69,10 +88,10 @@ class InstancesFromFile(BaseModel, AbstractInstanceSource):
type: Literal["simple_file"]
"""Discriminator for (de)serialization/CLI. Do not change."""
- def get_instance_configs(self) -> list[EnvironmentInstanceConfig]:
+ def get_instance_configs(self) -> list[BatchInstance]:
instance_dicts = _load_file(self.path)
- simple_instances = [BatchInstance(**instance_dict) for instance_dict in instance_dicts]
- return [instance._to_env_config(self.deployment) for instance in simple_instances]
+ simple_instances = [SimpleBatchInstance(**instance_dict) for instance_dict in instance_dicts]
+ return [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]
class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):
@@ -87,12 +106,12 @@ class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):
type: Literal["simple_huggingface"]
"""Discriminator for (de)serialization/CLI. Do not change."""
- def get_instance_configs(self) -> list[EnvironmentInstanceConfig]:
+ def get_instance_configs(self) -> list[BatchInstance]:
from datasets import load_dataset
ds: list[dict[str, Any]] = load_dataset(self.dataset_name, split=self.split) # type: ignore
- simple_instances: list[BatchInstance] = [BatchInstance(**instance) for instance in ds]
- return [instance._to_env_config(self.deployment) for instance in simple_instances]
+ simple_instances: list[SimpleBatchInstance] = [SimpleBatchInstance(**instance) for instance in ds]
+ return [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]
class SWEBenchInstances(BaseModel, AbstractInstanceSource):
@@ -106,7 +125,7 @@ class SWEBenchInstances(BaseModel, AbstractInstanceSource):
type: Literal["swe_bench"]
"""Discriminator for (de)serialization/CLI. Do not change."""
- def get_instance_configs(self) -> list[EnvironmentInstanceConfig]:
+ def get_instance_configs(self) -> list[BatchInstance]:
raise NotImplementedError
@@ -121,10 +140,13 @@ class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
type: Literal["expert_file"]
"""Discriminator for (de)serialization/CLI. Do not change."""
- def get_instance_configs(self) -> list[EnvironmentInstanceConfig]:
+ def get_instance_configs(self) -> list[BatchInstance]:
instance_dicts = _load_file(self.path)
- instances = [EnvironmentInstanceConfig(**instance_dict) for instance_dict in instance_dicts]
- return _filter_instances(instances, self.instance_filter)
+ instances = [
+ BatchInstance(env=EnvironmentConfig(**instance_dict), problem_statement=TextProblemStatement(text=""))
+ for instance_dict in instance_dicts
+ ]
+ return _filter_batch_items(instances, self.instance_filter)
-InstanceSourceConfig = ExpertInstancesFromFile | InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances
+BatchInstanceSourceConfig = ExpertInstancesFromFile | InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances
diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.py
index d6f3d843..88bd0bfc 100644
--- a/sweagent/run/hooks/apply_patch.py
+++ b/sweagent/run/hooks/apply_patch.py
@@ -21,14 +21,14 @@ class SaveApplyPatchHook(RunHook):
def on_init(self, *, run):
self._traj_dir = Path(run.traj_dir)
self._apply_patch_locally = run.actions.apply_patch_locally
- self._env: SWEEnv | None = None
+ self._env = run.env
+ self._problem_statement = run.problem_statement
def on_instance_start(self, *, index: int, env: SWEEnv):
self._env = env
def on_instance_completed(self, *, info, trajectory):
- assert self._env is not None # mypy
- instance_id = self._env.problem_statement.id
+ instance_id = self._problem_statement.id
patch_path = self._save_patch(instance_id, info)
if patch_path:
if not self._apply_patch_locally:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 9192eaa2..93e46350 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -9,15 +9,15 @@ from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
from sweagent.run._common import BasicCLI
-from sweagent.run.batch_instances import InstanceSourceConfig
+from sweagent.run.batch_instances import BatchInstanceSourceConfig
from sweagent.run.hooks.abstract import RunHook
from sweagent.utils.log import get_logger
class RunBatchConfig(BaseSettings):
- instances: InstanceSourceConfig
+ instances: BatchInstanceSourceConfig
agent: AgentConfig = AgentConfig(
model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
)
@@ -28,7 +28,7 @@ class RunBatchConfig(BaseSettings):
class RunBatch:
def __init__(
self,
- instances: list[EnvironmentInstanceConfig],
+ instances: list[EnvironmentConfig],
agent: Agent,
*,
traj_dir: str = ".",
@@ -72,16 +72,15 @@ class RunBatch:
env = SWEEnv.from_config(instance)
env.start()
self.logger.info("Resetting environment")
- observation, info = env.reset()
+ env.reset()
self.logger.info("Running agent")
self._fire_hooks("on_instance_start", index=0, instance=instance.model_dump())
info, trajectory = self.agent.run(
- setup_args={"problem_statement": instance.problem_statement.get_problem_statement()},
+ problem_statement=instance.problem_statement,
env=env,
- observation=observation,
traj_dir=Path(self.traj_dir),
)
- self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)
+ self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)
self.logger.info("Done")
self._fire_hooks("on_end")
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index cb972c81..60412b88 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -77,7 +77,6 @@ class RunReplay:
return SWEEnv(
deployment=self.deployment,
repo=self.repo,
- problem_statement=EmptyProblemStatement(),
startup_commands=[],
_catch_errors=self._catch_errors,
_always_require_zero_exit_code=self._require_zero_exit_code,
@@ -90,7 +89,7 @@ class RunReplay:
return Agent("replay", agent_config)
def _get_run_single(self) -> RunSingle:
- return RunSingle(self._get_env(), self._get_agent())
+ return RunSingle(self._get_env(), self._get_agent(), problem_statement=EmptyProblemStatement())
def main(self):
self._create_actions_file()
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index a28129fa..5b11e632 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -8,7 +8,12 @@ from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.config.problem_statement import (
+ EmptyProblemStatement,
+ ProblemStatement,
+ ProblemStatementConfig,
+)
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
from sweagent.run._common import BasicCLI
from sweagent.run.hooks.abstract import CombinedRunHooks, RunHook
from sweagent.run.hooks.apply_patch import SaveApplyPatchHook
@@ -27,10 +32,11 @@ class RunSingleActionConfig(BaseModel):
class RunSingleConfig(BaseSettings):
- env: EnvironmentInstanceConfig = Field(default_factory=EnvironmentInstanceConfig)
+ env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
agent: AgentConfig = AgentConfig(
model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
)
+ problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
traj_dir: str = "."
actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
# todo: implement this
@@ -44,6 +50,7 @@ class RunSingle:
self,
env: SWEEnv,
agent: Agent,
+ problem_statement: ProblemStatement,
*,
traj_dir: str = ".",
hooks: list[RunHook] | None = None,
@@ -61,6 +68,7 @@ class RunSingle:
actions = RunSingleActionConfig()
self.actions = actions
self._chooks = CombinedRunHooks()
+ self.problem_statement = problem_statement
for hook in hooks or []:
self.add_hook(hook)
@@ -73,6 +81,7 @@ class RunSingle:
self = cls(
env=SWEEnv.from_config(config.env),
agent=Agent("main", config.agent),
+ problem_statement=config.problem_statement,
traj_dir=config.traj_dir,
actions=config.actions,
)
@@ -91,13 +100,12 @@ class RunSingle:
self.logger.info("Starting environment")
self.env.start()
self.logger.info("Resetting environment")
- observation, info = self.env.reset()
+ self.env.reset()
self.logger.info("Running agent")
self._chooks.on_instance_start(index=0, env=self.env)
info, trajectory = self.agent.run(
- setup_args={"problem_statement": self.env.problem_statement.get_problem_statement()},
+ problem_statement=self.problem_statement,
env=self.env,
- observation=observation,
traj_dir=Path(self.traj_dir),
)
self._chooks.on_instance_completed(info=info, trajectory=trajectory)
diff --git a/tests/conftest.py b/tests/conftest.py
index b357fd7e..04758198 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -11,9 +11,8 @@ from pathlib import Path
import pytest
from sweagent.environment.config.deployment import DockerDeploymentConfig
-from sweagent.environment.config.problem_statement import FileProblemStatement
from sweagent.environment.config.repo import LocalRepoConfig
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
# this is a hack and should be removed when we have a better solution
_this_dir = Path(__file__).resolve().parent
@@ -77,14 +76,12 @@ def test_trajectory(test_trajectory_path):
@pytest.fixture(scope="module")
def test_env_args(
tmpdir_factory,
-) -> Generator[EnvironmentInstanceConfig]:
+) -> Generator[EnvironmentConfig]:
"""This will use a persistent container"""
local_repo_path = tmpdir_factory.getbasetemp() / "test-repo"
clone_cmd = ["git", "clone", "https://github.com/swe-agent/test-repo", str(local_repo_path)]
subprocess.run(clone_cmd, check=True)
- data_path = local_repo_path / "problem_statements" / "1.md"
- test_env_args = EnvironmentInstanceConfig(
- problem_statement=FileProblemStatement(path=str(data_path)),
+ test_env_args = EnvironmentConfig(
deployment=DockerDeploymentConfig(image="sweagent/swe-agent:latest"),
repo=LocalRepoConfig(path=str(local_repo_path)),
)
diff --git a/tests/test_run.py b/tests/test_run.py
index 4fe2a73b..59b483c5 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -5,7 +5,7 @@ import subprocess
import pytest
from sweagent.agent.agents import AgentConfig
-from sweagent.environment.swe_env import EnvironmentInstanceConfig
+from sweagent.environment.swe_env import EnvironmentConfig
from sweagent.run._common import BasicCLI
from sweagent.run.hooks.abstract import RunHook
from sweagent.run.run_single import RunSingle, RunSingleConfig
@@ -51,7 +51,7 @@ def test_run_ies(agent_config_with_commands):
ac = agent_config_with_commands
ac.model.name = "instant_empty_submit"
rsc = RunSingleConfig(
- env=EnvironmentInstanceConfig(),
+ env=EnvironmentConfig(),
agent=ac,
)
rs = RunSingle.from_config(rsc)
@@ -68,11 +68,11 @@ def test_run_ies_repo_ps_matrix(
problem_statement_source,
):
if problem_statement_source == "github":
- ps_args = ["--env.problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]
+ ps_args = ["--problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]
elif problem_statement_source == "local":
- ps_args = ["--env.problem_statement.path", str(swe_agent_test_repo_clone / "problem_statements" / "1.md")]
+ ps_args = ["--problem_statement.path", str(swe_agent_test_repo_clone / "problem_statements" / "1.md")]
elif problem_statement_source == "text":
- ps_args = ["--env.problem_statement.text='this is a test'"]
+ ps_args = ["--problem_statement.text='this is a test'"]
else:
raise ValueError(problem_statement_source)
if repo == "local":