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]

WIP creating batch script; rename instance config

Kilian Lieret70e5759f9727
diff --git a/run.py b/run.py
index 50b3b0be..c89ae8a7 100644
--- a/run.py
+++ b/run.py
@@ -16,7 +16,8 @@ from argparse import ArgumentParser
from pprint import pprint
from sweagent.environment.config.deployment import DockerDeploymentConfig
-from sweagent.main.hooks.abstract import MainHook
+from sweagent.run.hooks.abstract import RunHook
+from sweagent.run.run_single import RunSingleActionConfig
from sweagent.utils.log import add_file_handler, get_logger
try:
@@ -29,7 +30,7 @@ from getpass import getuser
from pathlib import Path
import yaml
-from pydantic import BaseModel, Field
+from pydantic import Field
from pydantic_settings import BaseSettings, CliApp
from rich.markdown import Markdown
from swebench.harness.constants import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION
@@ -37,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 EnvironmentConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
__doc__: str = """ Run inference. Usage examples:
@@ -56,32 +57,12 @@ logger = get_logger("swe-agent-run")
logging.getLogger("simple_parsing").setLevel(logging.WARNING)
-class ActionsArguments(BaseModel):
- """Run real-life actions (opening PRs, etc.) if we can solve the issue."""
-
- # Open a PR with the patch if we can solve the issue
- open_pr: bool = False
- # When working with local repository: Apply patch
- apply_patch_locally: bool = False
- # Option to be used with open_pr: Skip action if there are already commits claiming
- # to fix the issue. Please only set this to False if you are sure the commits are
- # not fixes or if this is your own repository!
- skip_if_commits_reference_issue: bool = True
- # OBSOLETE. Do not use, will raise error. Please specify --repo_path instead.
- push_gh_repo_url: str = ""
-
- def model_post_init(self, __context):
- if self.push_gh_repo_url:
- msg = "push_gh_repo_url is obsolete. Use repo_path instead"
- raise ValueError(msg)
-
-
class ScriptArguments(BaseSettings):
"""Configure the control flow of the run.py script"""
- environment: EnvironmentConfig = Field(..., default_factory=EnvironmentConfig)
+ environment: EnvironmentInstanceConfig = Field(..., default_factory=EnvironmentInstanceConfig)
agent: AgentConfig = Field(..., default_factory=AgentConfig)
- actions: ActionsArguments = Field(..., default_factory=ActionsArguments)
+ actions: RunSingleActionConfig = Field(..., default_factory=RunSingleActionConfig)
# Only run instances that completely match this regex
instance_filter: str = ".*"
# Skip instances with existing trajectories
@@ -145,11 +126,11 @@ class Main:
# SaveApplyPatchHook(),
# OpenPRHook(),
]
- self.hooks: list[MainHook] = []
+ self.hooks: list[RunHook] = []
for hook in default_hooks:
self.add_hook(hook)
- def add_hook(self, hook: MainHook):
+ def add_hook(self, hook: RunHook):
hook.on_init(args=self.args, agent=self.agent, env=self.env, traj_dir=self.traj_dir)
self.hooks.append(hook)
@@ -319,7 +300,7 @@ def get_args(args=None) -> ScriptArguments:
# Otherwise, the configs from the respective classes will be used
no_config_defaults = ScriptArguments(
suffix="",
- environment=EnvironmentConfig(
+ environment=EnvironmentInstanceConfig(
deployment=DockerDeploymentConfig(),
# data_path="princeton-nlp/SWE-bench_Lite",
# split="dev",
@@ -338,7 +319,7 @@ def get_args(args=None) -> ScriptArguments:
top_p=0.95,
),
),
- actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
+ actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),
ctf=False,
)
diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.py
index 70507109..8ec8cb0f 100644
--- a/sweagent/api/hooks.py
+++ b/sweagent/api/hooks.py
@@ -12,7 +12,7 @@ from sweagent.environment.hooks.abstract import EnvHook
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
-from sweagent.main.hooks.abstract import MainHook
+from sweagent.run.hooks.abstract import RunHook
class StreamToSocketIO(io.StringIO):
@@ -95,7 +95,7 @@ class WebUpdate:
self._emit("finish_run", {})
-class MainUpdateHook(MainHook):
+class MainUpdateHook(RunHook):
def __init__(self, wu: WebUpdate):
"""This hooks into the Main class to update the web interface"""
self._wu = wu
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index ac73f55b..232d8c8b 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from omegaconf import OmegaConf
from sweagent.environment.config.deployment import DeploymentConfig
+from sweagent.run.run_single import RunSingleActionConfig
try:
import flask # noqa
@@ -34,11 +35,11 @@ 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 EnvironmentConfig
+from sweagent.environment.swe_env import EnvironmentInstanceConfig
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
-from run import ActionsArguments, Main, ScriptArguments
+from run import Main, ScriptArguments
app = Flask(__name__, template_folder=Path(__file__).parent)
CORS(app)
@@ -156,7 +157,7 @@ def run():
agent_config = OmegaConf.load(CONFIG_DIR / "default_from_url.yaml")
defaults = ScriptArguments(
suffix="",
- environment=EnvironmentConfig(
+ environment=EnvironmentInstanceConfig(
deployment=DeploymentConfig(),
data_path=run.environment.data_path,
base_commit=run.environment.base_commit,
@@ -168,7 +169,7 @@ def run():
),
agent=AgentConfig(),
skip_existing=False,
- actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
+ actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),
raise_exceptions=True,
)
defaults.agent.model = ModelArguments(
diff --git a/sweagent/environment/config/instance_source.py b/sweagent/environment/config/instance_source.py
new file mode 100644
index 00000000..54d16908
--- /dev/null
+++ b/sweagent/environment/config/instance_source.py
@@ -0,0 +1,29 @@
+from abc import ABC, abstractmethod
+from pathlib import Path
+
+from pydantic import BaseModel
+
+from sweagent.environment.swe_env import EnvironmentInstanceConfig
+
+
+class AbstractInstanceSource(ABC):
+ @abstractmethod
+ def get_instance_configs(self) -> list[EnvironmentInstanceConfig]: ...
+
+
+class JSONInstances(BaseModel, AbstractInstanceSource):
+ path: Path
+ instance_filter: str = ".*"
+
+ def get_instance_configs(self) -> list[EnvironmentInstanceConfig]: ...
+
+
+class HuggingfaceInstances(BaseModel, AbstractInstanceSource):
+ dataset_name: str
+ split: str
+ instance_filter: str = ".*"
+
+ def get_instance_configs(self) -> list[EnvironmentInstanceConfig]: ...
+
+
+InstanceSourceConfig = JSONInstances | HuggingfaceInstances
diff --git a/sweagent/environment/config/instance.py b/sweagent/environment/config/problem_statement.py
similarity index 87%
rename from sweagent/environment/config/instance.py
rename to sweagent/environment/config/problem_statement.py
index 6111d50c..383869b8 100644
--- a/sweagent/environment/config/instance.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -9,7 +9,7 @@ from sweagent.utils._github import get_problem_statement_from_github_issue, pars
from sweagent.utils.config import keys_config
-class EmptyInstanceConfig(BaseModel):
+class EmptyProblemStatement(BaseModel):
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
type: Literal["empty"] = "empty"
"""Discriminator for serialization. Do not change."""
@@ -18,7 +18,7 @@ class EmptyInstanceConfig(BaseModel):
return ""
-class TextInstanceConfig(BaseModel):
+class TextProblemStatement(BaseModel):
problem_statement: str = ""
type: Literal["text"] = "text"
@@ -32,7 +32,7 @@ class TextInstanceConfig(BaseModel):
return self.problem_statement
-class TextFileInstanceConfig(BaseModel):
+class FileProblemStatement(BaseModel):
path: str = ""
type: Literal["text_file"] = "text_file"
@@ -46,7 +46,7 @@ class TextFileInstanceConfig(BaseModel):
return Path(self.path).read_text()
-class GithubInstanceConfig(BaseModel):
+class GithubIssue(BaseModel):
issue_url: str = ""
type: Literal["github"] = "github"
@@ -62,4 +62,4 @@ class GithubInstanceConfig(BaseModel):
return get_problem_statement_from_github_issue(owner, repo, issue_number, token=keys_config.get("GITHUB_TOKEN"))
-InstanceConfig = TextInstanceConfig | GithubInstanceConfig | EmptyInstanceConfig
+ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 348a6a6e..b861ed0c 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -13,7 +13,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.instance import EmptyInstanceConfig, InstanceConfig
+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 (
@@ -29,10 +29,10 @@ 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 EnvironmentConfig(BaseModel):
+class EnvironmentInstanceConfig(BaseModel):
"""Configure data sources and setup instructions for the environment in which we solve the tasks."""
- instance: InstanceConfig = Field(default_factory=EmptyInstanceConfig)
+ problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
deployment: DeploymentConfig | None = None
repo: RepoConfig | None = None
startup_commands: list[str] = []
@@ -54,7 +54,7 @@ class SWEEnv:
deployment: AbstractDeployment,
# todo: Should None be included in RepoConfig?
repo: RepoConfig | None,
- instance: InstanceConfig,
+ instance: ProblemStatementConfig,
startup_commands: list[str],
hooks: list[EnvHook] | None = None,
):
@@ -68,7 +68,9 @@ class SWEEnv:
self.returncode: None | int = None
self.clean_multi_line_functions = lambda x: x
- self._hooks: list[EnvHook] = hooks or []
+ self._hooks: list[EnvHook] = []
+ for hook in hooks or []:
+ self.add_hook(hook)
def start(self) -> None:
"""Start the environment"""
@@ -76,11 +78,14 @@ class SWEEnv:
self._init_scripts()
@classmethod
- def from_config(cls, config: EnvironmentConfig) -> Self:
+ def from_config(cls, config: EnvironmentInstanceConfig) -> Self:
deployment_kwargs = {k: v for k, v in config.deployment.model_dump().items() if k != "type"}
deployment = get_deployment(config.deployment.type, **deployment_kwargs) # type: ignore
return cls(
- deployment=deployment, repo=config.repo, instance=config.instance, startup_commands=config.startup_commands
+ deployment=deployment,
+ repo=config.repo,
+ instance=config.problem_statement,
+ startup_commands=config.startup_commands,
)
@property
diff --git a/sweagent/main/common.py b/sweagent/main/common.py
deleted file mode 100644
index 8b137891..00000000
--- a/sweagent/main/common.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
index dee6d0a6..d0112c12 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 EnvironmentConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
from sweagent.utils.log import get_logger
class BasicRunArguments(BaseSettings):
- env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
+ env: EnvironmentInstanceConfig = Field(default_factory=EnvironmentInstanceConfig)
agent: AgentConfig = AgentConfig(
model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
)
diff --git a/sweagent/main/__init__.py b/sweagent/run/__init__.py
similarity index 100%
rename from sweagent/main/__init__.py
rename to sweagent/run/__init__.py
diff --git a/sweagent/run/_common.py b/sweagent/run/_common.py
new file mode 100644
index 00000000..df68adb8
--- /dev/null
+++ b/sweagent/run/_common.py
@@ -0,0 +1,62 @@
+"""Common functionality for the run scripts."""
+
+from argparse import ArgumentParser
+from pathlib import Path
+
+import yaml
+from pydantic_settings import BaseSettings, CliApp
+
+from sweagent import CONFIG_DIR
+
+
+class BasicCLI:
+ def __init__(self, arg_type: type[BaseSettings]):
+ self.arg_type = arg_type
+
+ def get_args(self, args=None) -> BaseSettings:
+ # The defaults if no config file is provided
+ # Otherwise, the configs from the respective classes will be used
+ parser = ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--config",
+ type=str,
+ action="append",
+ default=[],
+ help="Load additional config files. Use this option multiple times to load multiple files, e.g., --config config1.yaml --config config2.yaml",
+ )
+ parser.add_argument(
+ "--no-config-file",
+ action="store_true",
+ help="Do not load default config file when no config file is provided",
+ )
+ parser.add_argument(
+ "--print-options",
+ action="store_true",
+ help="Print all additional configuration options that can be set via CLI and exit",
+ )
+ parser.add_argument("--print-config", action="store_true", help="Print the final config and exit")
+ cli_args, remaining_args = parser.parse_known_args(args)
+
+ if cli_args.print_options:
+ CliApp.run(self.arg_type, ["--help"])
+ exit(0)
+
+ config_merged = {}
+ if cli_args.config:
+ for _f in cli_args.config:
+ _loaded = yaml.safe_load(Path(_f).read_text())
+ config_merged.update(_loaded)
+ elif not cli_args.no_config_file:
+ config_merged = yaml.safe_load((CONFIG_DIR / "default.yaml").read_text())
+ else:
+ config_merged = self.arg_type().model_dump()
+
+ # args = ScriptArguments.model_validate(config_merged)
+ print("-------")
+ print(remaining_args)
+ print("-------")
+ args = CliApp.run(self.arg_type, remaining_args, **config_merged) # type: ignore
+ if cli_args.print_config: # type: ignore
+ print(yaml.dump(args.model_dump()))
+ exit(0)
+ return args
diff --git a/sweagent/main/hooks/__init__.py b/sweagent/run/hooks/__init__.py
similarity index 100%
rename from sweagent/main/hooks/__init__.py
rename to sweagent/run/hooks/__init__.py
diff --git a/sweagent/main/hooks/abstract.py b/sweagent/run/hooks/abstract.py
similarity index 81%
rename from sweagent/main/hooks/abstract.py
rename to sweagent/run/hooks/abstract.py
index e83976dd..9a55d47a 100644
--- a/sweagent/main/hooks/abstract.py
+++ b/sweagent/run/hooks/abstract.py
@@ -1,12 +1,7 @@
-from pathlib import Path
from typing import Any
-from run import ScriptArguments
-from sweagent.agent.agents import Agent
-from sweagent.environment.swe_env import SWEEnv
-
-class MainHook:
+class RunHook:
"""Hook structure for the web server or other addons to interface with"""
@staticmethod
@@ -17,7 +12,7 @@ class MainHook:
# The exit status can also be `submitted (exit_cost)` etc.
return info["exit_status"] == "submitted" and info.get("submission") is not None
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
+ def on_init(self, *, run):
"""Called when hook is initialized"""
def on_start(self):
diff --git a/sweagent/main/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.py
similarity index 83%
rename from sweagent/main/hooks/apply_patch.py
rename to sweagent/run/hooks/apply_patch.py
index e0217c69..90d0b58c 100644
--- a/sweagent/main/hooks/apply_patch.py
+++ b/sweagent/run/hooks/apply_patch.py
@@ -4,18 +4,20 @@ from typing import Any
import rich
-from run import ScriptArguments, logger
-from sweagent.agent.agents import Agent
-from sweagent.environment.swe_env import SWEEnv
-from sweagent.main.hooks.abstract import MainHook
+from sweagent.run.hooks.abstract import RunHook
+from sweagent.utils.log import get_logger
-class SaveApplyPatchHook(MainHook):
+class SaveApplyPatchHook(RunHook):
"""This hook saves patches to a separate directory and optionally applies them to a local repository."""
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- self._traj_dir = traj_dir
- self._apply_patch_locally = args.actions.apply_patch_locally
+ def __init__(self, apply_patch_locally: bool = False):
+ self.logger = get_logger("⚡️ SaveApplyPatchHook")
+ self._apply_patch_locally = apply_patch_locally
+
+ def on_init(self, *, run):
+ self._traj_dir = run.traj_dir
+ self._apply_patch_locally = run.actions.apply_patch_locally
self._instance = None
def on_instance_start(self, *, index: int, instance: dict[str, Any]):
@@ -71,7 +73,7 @@ class SaveApplyPatchHook(MainHook):
patch_output_dir.mkdir(exist_ok=True, parents=True)
patch_output_file = patch_output_dir / f"{instance_id}.patch"
if info.get("submission") is None:
- logger.info("No patch to save.")
+ self.logger.info("No patch to save.")
return None
model_patch = info["submission"]
patch_output_file.write_text(model_patch)
@@ -92,6 +94,6 @@ class SaveApplyPatchHook(MainHook):
try:
subprocess.run(cmd, cwd=local_dir, check=True)
except subprocess.CalledProcessError as e:
- logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")
+ self.logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")
return
- logger.info(f"Applied patch {patch_file} to {local_dir}")
+ self.logger.info(f"Applied patch {patch_file} to {local_dir}")
diff --git a/sweagent/main/hooks/open_pr.py b/sweagent/run/hooks/open_pr.py
similarity index 81%
rename from sweagent/main/hooks/open_pr.py
rename to sweagent/run/hooks/open_pr.py
index d4ad124d..a90a84b6 100644
--- a/sweagent/main/hooks/open_pr.py
+++ b/sweagent/run/hooks/open_pr.py
@@ -1,12 +1,11 @@
-from pathlib import Path
from typing import Any
-from run import ScriptArguments, logger
-from sweagent.agent.agents import Agent
-from sweagent.environment.swe_env import SWEEnv
+from pydantic import BaseModel
+
from sweagent.environment.utils import InvalidGithubURL
-from sweagent.main.hooks.abstract import MainHook
+from sweagent.run.hooks.abstract import RunHook
from sweagent.utils._github import get_associated_commit_urls, get_gh_issue_data, parse_gh_issue_url
+from sweagent.utils.log import get_logger
# todo: Move this to run.py
# def open_pr(self, *, trajectory, _dry_run: bool = False) -> None:
@@ -110,15 +109,25 @@ from sweagent.utils._github import get_associated_commit_urls, get_gh_issue_data
# )
-class OpenPRHook(MainHook):
+class OpenPRConfig(BaseModel):
+ # Option to be used with open_pr: Skip action if there are already commits claiming
+ # to fix the issue. Please only set this to False if you are sure the commits are
+ # not fixes or if this is your own repository!
+ skip_if_commits_reference_issue: bool = True
+
+
+class OpenPRHook(RunHook):
"""This hook opens a PR if the issue is solved and the user has enabled the option."""
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- self._env = env
- self._token: str = env._github_token
- self._data_path = args.environment.data_path
- self._open_pr = args.actions.open_pr
- self._skip_if_commits_reference_issue = args.actions.skip_if_commits_reference_issue
+ def __init__(self, config: OpenPRConfig):
+ self.logger = get_logger("⚡️ OpenPRHook")
+ self._config = config
+
+ def on_init(self, *, run):
+ self._env = run.env
+ self._token: str = run.env._github_token
+ self._data_path = run.actions.data_path
+ self._open_pr = run.actions.open_pr
def on_instance_completed(self, *, info, trajectory):
if self._open_pr and self.should_open_pr(info):
@@ -127,34 +136,34 @@ class OpenPRHook(MainHook):
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.")
+ self.logger.info("Not opening PR because no submission was made.")
return False
if info["exit_status"] != "submitted":
- logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])
+ self.logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])
return False
try:
issue = get_gh_issue_data(self._data_path, token=self._token)
except InvalidGithubURL:
- logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
+ self.logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
return False
if issue.state != "open":
- logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
+ self.logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
return False
if issue.assignee:
- logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
+ self.logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
return False
if issue.locked:
- logger.info("Issue is locked. Skipping PR creation.")
+ self.logger.info("Issue is locked. Skipping PR creation.")
return False
org, repo, issue_number = parse_gh_issue_url(self._data_path)
associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)
if associated_commits:
commit_url_strs = ", ".join(associated_commits)
- if self._skip_if_commits_reference_issue:
- logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
+ if self._config.skip_if_commits_reference_issue:
+ self.logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
return False
else:
- logger.warning(
+ self.logger.warning(
"Proceeding with PR creation even though there are already commits "
f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
"or after verifying that the existing commits do not fix the issue.",
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
new file mode 100644
index 00000000..42342228
--- /dev/null
+++ b/sweagent/run/run_batch.py
@@ -0,0 +1,91 @@
+"""Run in human mode without any complicated env setup.
+This is mostly for debugging and development.
+"""
+
+from pathlib import Path
+from typing import Self
+
+from pydantic_settings import BaseSettings
+
+from sweagent.agent.agents import Agent, AgentConfig
+from sweagent.agent.models import ModelArguments
+from sweagent.environment.config.instance_source import AbstractInstanceSource, InstanceSourceConfig
+from sweagent.environment.swe_env import SWEEnv
+from sweagent.run._common import BasicCLI
+from sweagent.run.hooks.abstract import RunHook
+from sweagent.utils.log import get_logger
+
+
+class RunBatchConfig(BaseSettings):
+ instances: InstanceSourceConfig
+ agent: AgentConfig = AgentConfig(
+ model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
+ )
+ traj_dir: str = "."
+ raise_exceptions: bool = False
+
+
+class RunBatch:
+ def __init__(
+ self,
+ instance_source: AbstractInstanceSource,
+ agent: Agent,
+ *,
+ traj_dir: str = ".",
+ hooks: list[RunHook] | None = None,
+ ):
+ """Note: When initializing this class, make sure to add the hooks that are required by your actions.
+ See `from_config` for an example.
+ """
+ self.logger = get_logger("PlaygroundMain")
+ self.instance_source = instance_source
+ self.agent = agent
+ self.traj_dir = traj_dir
+ self._hooks = []
+ for hook in hooks or []:
+ self.add_hook(hook)
+
+ @property
+ def hooks(self) -> list[RunHook]:
+ return self._hooks
+
+ @classmethod
+ def from_config(cls, config: RunBatchConfig) -> Self:
+ return cls(instance_source=config.instances, agent=Agent("main", config.agent), traj_dir=config.traj_dir)
+
+ def add_hook(self, hook: RunHook) -> None:
+ hook.on_init(run=self)
+ self._hooks.append(hook)
+
+ def _fire_hooks(self, hook_name: str, *args, **kwargs) -> None:
+ for hook in self.hooks:
+ getattr(hook, hook_name)(*args, **kwargs)
+
+ def main(self):
+ self._fire_hooks("on_start")
+ for instance in self.instance_source.get_instance_configs():
+ self.logger.info("Starting environment")
+ env = SWEEnv.from_config(instance)
+ env.start()
+ self.logger.info("Resetting environment")
+ observation, info = 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()},
+ env=env,
+ observation=observation,
+ traj_dir=Path(self.traj_dir),
+ return_type="info_trajectory",
+ )
+ self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)
+ self.logger.info("Done")
+ self._fire_hooks("on_end")
+
+
+def main(args: RunBatchConfig):
+ RunBatch.from_config(args).main()
+
+
+if __name__ == "__main__":
+ main(BasicCLI(RunBatchConfig).get_args()) # type: ignore
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
new file mode 100644
index 00000000..8dad2ffa
--- /dev/null
+++ b/sweagent/run/run_single.py
@@ -0,0 +1,117 @@
+"""Run in human mode without any complicated env setup.
+This is mostly for debugging and development.
+"""
+
+from pathlib import Path
+from typing import Self
+
+from pydantic import BaseModel, Field
+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.run._common import BasicCLI
+from sweagent.run.hooks.abstract import RunHook
+from sweagent.run.hooks.apply_patch import SaveApplyPatchHook
+from sweagent.run.hooks.open_pr import OpenPRConfig, OpenPRHook
+from sweagent.utils.log import get_logger
+
+
+class RunSingleActionConfig(BaseModel):
+ """Run real-life actions (opening PRs, etc.) if we can solve the issue."""
+
+ # Open a PR with the patch if we can solve the issue
+ open_pr: bool = False
+ pr_config: OpenPRConfig = Field(default_factory=OpenPRConfig)
+ # When working with local repository: Apply patch
+ apply_patch_locally: bool = False
+ # todo: implement this
+ raise_exceptions: bool = False
+ # todo: implement this
+ print_config: bool = True
+
+
+class RunSingleConfig(BaseSettings):
+ env: EnvironmentInstanceConfig = Field(default_factory=EnvironmentInstanceConfig)
+ agent: AgentConfig = AgentConfig(
+ model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
+ )
+ traj_dir: str = "."
+ actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
+
+
+class RunSingle:
+ def __init__(
+ self,
+ env: SWEEnv,
+ agent: Agent,
+ *,
+ traj_dir: str = ".",
+ hooks: list[RunHook] | None = None,
+ actions: RunSingleActionConfig,
+ ):
+ """Note: When initializing this class, make sure to add the hooks that are required by your actions.
+ See `from_config` for an example.
+ """
+ self.logger = get_logger("PlaygroundMain")
+ self.env = env
+ self.agent = agent
+ self.traj_dir = traj_dir
+ self._hooks = []
+ self.actions = actions
+ for hook in hooks or []:
+ self.add_hook(hook)
+
+ @property
+ def hooks(self) -> list[RunHook]:
+ return self._hooks
+
+ @classmethod
+ def from_config(cls, config: RunSingleConfig) -> Self:
+ self = cls(
+ env=SWEEnv.from_config(config.env),
+ agent=Agent("main", config.agent),
+ traj_dir=config.traj_dir,
+ actions=config.actions,
+ )
+ self.add_hook(SaveApplyPatchHook(apply_patch_locally=config.actions.apply_patch_locally))
+ if config.actions.open_pr:
+ self.logger.debug("Adding OpenPRHook")
+ self.add_hook(OpenPRHook(config.actions.pr_config))
+ return self
+
+ def add_hook(self, hook: RunHook) -> None:
+ hook.on_init(run=self)
+ self._hooks.append(hook)
+
+ def _fire_hooks(self, hook_name: str, *args, **kwargs) -> None:
+ for hook in self.hooks:
+ getattr(hook, hook_name)(*args, **kwargs)
+
+ def main(self):
+ self._fire_hooks("on_start")
+ self.logger.info("Starting environment")
+ self.env.start()
+ self.logger.info("Resetting environment")
+ observation, info = self.env.reset()
+ self.logger.info("Running agent")
+ self._fire_hooks("on_instance_start", index=0, instance=self.env.instance.model_dump())
+ info, trajectory = self.agent.run(
+ setup_args={"problem_statement": self.env.instance.get_problem_statement()},
+ env=self.env,
+ observation=observation,
+ traj_dir=Path(self.traj_dir),
+ return_type="info_trajectory",
+ )
+ self._fire_hooks("on_instance_completed", info=info, trajectory=trajectory)
+ self.logger.info("Done")
+ self._fire_hooks("on_end")
+
+
+def main(args: RunSingleConfig):
+ RunSingle.from_config(args).main()
+
+
+if __name__ == "__main__":
+ main(BasicCLI(RunSingleConfig).get_args()) # type: ignore
diff --git a/tests/conftest.py b/tests/conftest.py
index eb45d2d8..bc85570f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -12,7 +12,7 @@ import pytest
import docker
import docker.errors
-from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
# this is a hack and should be removed when we have a better solution
_this_dir = Path(__file__).resolve().parent
@@ -76,13 +76,13 @@ def test_trajectory(test_trajectory_path):
@pytest.fixture(scope="module")
def test_env_args(
tmpdir_factory,
-) -> Generator[EnvironmentConfig]:
+) -> Generator[EnvironmentInstanceConfig]:
"""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 = EnvironmentConfig(
+ test_env_args = EnvironmentInstanceConfig(
data_path=str(data_path),
repo_path=str(local_repo_path),
image_name="sweagent/swe-agent:latest",
diff --git a/tests/test_env_utils.py b/tests/test_env_utils.py
index 53b1fdd1..1e49b1b2 100644
--- a/tests/test_env_utils.py
+++ b/tests/test_env_utils.py
@@ -10,7 +10,7 @@ from sweagent.environment.utils import (
InvalidGithubURL,
get_instances,
)
-from sweagent.main.hooks.open_pr import _remove_triple_backticks, format_trajectory_markdown
+from sweagent.run.hooks.open_pr import _remove_triple_backticks, format_trajectory_markdown
from sweagent.utils._github import (
get_associated_commit_urls,
is_github_issue_url,
diff --git a/tests/test_run.py b/tests/test_run.py
index 1f3f7d77..d9c4021d 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -11,12 +11,13 @@ from typing import Any
import pytest
import docker
-from run import ActionsArguments, Main, ScriptArguments
+from run import Main, ScriptArguments
from sweagent.agent.agents import Agent, AgentConfig, AgentHook
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
-from sweagent.main.hooks.abstract import MainHook
-from sweagent.main.hooks.open_pr import OpenPRHook
+from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.run.hooks.abstract import RunHook
+from sweagent.run.hooks.open_pr import OpenPRHook
+from sweagent.run.run_single import RunSingleActionConfig
@pytest.mark.slow
@@ -96,7 +97,7 @@ def test_should_open_pr_success_has_pr_override(open_pr_hook_init_for_sop, info_
assert hook.should_open_pr(info_dict)
-class RaisesExceptionHook(MainHook):
+class RaisesExceptionHook(RunHook):
def on_instance_start(self, *, index: int, instance: dict[str, Any]):
msg = "test exception"
raise ValueError(msg)
@@ -106,7 +107,7 @@ class RaisesExceptionHook(MainHook):
def test_script_args():
return ScriptArguments(
suffix="",
- environment=EnvironmentConfig(
+ environment=EnvironmentInstanceConfig(
image_name="sweagent/swe-agent:latest",
data_path="https://github.com/swe-agent/test-repo/issues/1",
split="dev",
@@ -119,7 +120,7 @@ def test_script_args():
name="instant_empty_submit",
),
),
- actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
+ actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),
raise_exceptions=True,
print_config=False,
)
@@ -135,7 +136,7 @@ def test_exception_raised(test_script_args: ScriptArguments):
@pytest.mark.slow
-class CreateFakeLogFile(MainHook):
+class CreateFakeLogFile(RunHook):
"""Testing the skip functionality"""
def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
@@ -160,7 +161,7 @@ def test_existing_corrupted_args(test_script_args: ScriptArguments):
@pytest.mark.slow
def test_main_hook(test_script_args: ScriptArguments):
main = Main(test_script_args)
- main.add_hook(MainHook())
+ main.add_hook(RunHook())
main.main()