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 on new entry points

Kilian Lierete19c1697b5c7
diff --git a/pyproject.toml b/pyproject.toml
index 413f4d6a..6e62f07a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -15,7 +15,7 @@ name = "sweagent"
dynamic = ["version", "dependencies"]
description = "The official SWE-agent package - an open source Agent Computer Interface for running language models as software engineers."
readme = "README.md"
-requires-python = ">=3.9"
+requires-python = ">=3.10"
license = {file = "LICENSE"}
keywords = ["nlp", "agents", "code"]
authors = [
@@ -114,7 +114,7 @@ exclude = [
line-length = 120
indent-width = 4
-target-version = "py39"
+target-version = "py310"
[tool.ruff.lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
@@ -227,4 +227,4 @@ ACI = "ACI"
aci = "aci"
[tool.ruff.lint.isort]
-required-imports = ["from __future__ import annotations"]
+# required-imports = ["from __future__ import annotations"]
diff --git a/run.py b/run.py
index e1a3ab5d..bfb8ef28 100644
--- a/run.py
+++ b/run.py
@@ -1,29 +1,23 @@
from __future__ import annotations
+# try:
+# import rich
+# except ModuleNotFoundError as e:
+# msg = (
+# "You probably either forgot to install the dependencies "
+# "or forgot to activate your conda or virtual environment."
+# )
+# raise RuntimeError(msg) from e
+import json
import logging
+import re
+import traceback
from argparse import ArgumentParser
from pprint import pprint
+from sweagent.main.hooks import MainHook
from sweagent.utils.log import add_file_handler, get_logger
-try:
- import rich
-except ModuleNotFoundError as e:
- msg = (
- "You probably either forgot to install the dependencies "
- "or forgot to activate your conda or virtual environment."
- )
- raise RuntimeError(msg) from e
-import json
-import re
-import subprocess
-import traceback
-from typing import Any
-
-import rich.console
-import rich.markdown
-import rich.panel
-
try:
from rich_argparse import RichHelpFormatter
except ImportError:
@@ -42,14 +36,7 @@ from unidiff import PatchSet
from sweagent.agent.agents import Agent, AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import DockerDeploymentConfig, EnvironmentArguments, SWEEnv
-from sweagent.environment.utils import (
- InvalidGithubURL,
- get_associated_commit_urls,
- get_data_path_name,
- get_gh_issue_data,
- parse_gh_issue_url,
-)
+from sweagent.environment.swe_env import DockerDeploymentConfig, EnvironmentConfig, SWEEnv
__doc__: str = """ Run inference. Usage examples:
@@ -91,7 +78,7 @@ class ActionsArguments(BaseModel):
class ScriptArguments(BaseSettings):
"""Configure the control flow of the run.py script"""
- environment: EnvironmentArguments = Field(..., default_factory=EnvironmentArguments)
+ environment: EnvironmentConfig = Field(..., default_factory=EnvironmentConfig)
agent: AgentConfig = Field(..., default_factory=AgentConfig)
actions: ActionsArguments = Field(..., default_factory=ActionsArguments)
# Only run instances that completely match this regex
@@ -116,7 +103,8 @@ class ScriptArguments(BaseSettings):
def _generate_run_name(self) -> str:
"""Generate a unique name for this run based on the arguments."""
model_name = self.agent.model.name.replace(":", "-")
- data_stem = get_data_path_name(self.environment.data_path)
+ # todo: Need to set this properly
+ data_stem = "todo" # get_data_path_name(self.environment.data_path)
# assert self.agent.config_file is not None # mypy
# config_stem = Path(self.agent.config_file).stem
@@ -124,11 +112,11 @@ class ScriptArguments(BaseSettings):
top_p = self.agent.model.top_p
per_instance_cost_limit = self.agent.model.per_instance_cost_limit
- install_env = self.environment.install_environment
+ # install_env = self.environment.install_environment
return (
f"{model_name}__{data_stem}__t-{temp:.2f}__p-{top_p:.2f}"
- + f"__c-{per_instance_cost_limit:.2f}__install-{int(install_env)}"
+ + f"__c-{per_instance_cost_limit:.2f}"
+ (f"__{self.suffix}" if self.suffix else "")
)
@@ -137,177 +125,6 @@ class _ContinueLoop(Exception):
"""Used for internal control flow"""
-class MainHook:
- """Hook structure for the web server or other addons to interface with"""
-
- @staticmethod
- def _is_promising_patch(info: dict[str, Any]) -> bool:
- """Do we actually believe that the patch will solve the issue?
- Or are we just submitting the last patch we generated before hitting an error?
- """
- # 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):
- """Called when hook is initialized"""
-
- def on_start(self):
- """Called at the beginning of `Main.main`"""
-
- def on_end(self):
- """Called at the end of `Main.main`"""
-
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- """Called at the beginning of each instance loop in `Main.run`"""
-
- def on_instance_skipped(
- self,
- ):
- """Called when an instance is skipped in `Main.run`"""
-
- def on_instance_completed(self, *, info, trajectory):
- """Called when an instance is completed in `Main.run`"""
-
-
-class SaveApplyPatchHook(MainHook):
- """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
- self._instance = None
-
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- self._instance = instance
-
- def on_instance_completed(self, *, info, trajectory):
- assert self._instance is not None # mypy
- instance_id = self._instance["instance_id"]
- patch_path = self._save_patch(instance_id, info)
- if patch_path:
- if not self._apply_patch_locally:
- return
- if not self._is_promising_patch(info):
- return
- assert self._instance # mypy
- if self._instance["repo_type"] != "local":
- return
- local_dir = Path(self._instance["repo"])
- self._apply_patch(patch_path, local_dir)
-
- @staticmethod
- def _print_patch_message(patch_output_file: Path):
- console = rich.console.Console()
- msg = [
- "SWE-agent has produced a patch that it believes will solve the issue you submitted!",
- "Use the code snippet below to inspect or apply it!",
- ]
- panel = rich.panel.Panel.fit(
- "\n".join(msg),
- title="πŸŽ‰ Submission successful πŸŽ‰",
- )
- console.print(panel)
- content = [
- "```bash",
- "# The patch has been saved to your local filesystem at:",
- f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
- "# Inspect it:",
- 'cat "${PATCH_FILE_PATH}"',
- "# Apply it to a local repository:",
- "cd <your local repo root>",
- 'git apply "${PATCH_FILE_PATH}"',
- "```",
- ]
- console.print(rich.markdown.Markdown("\n".join(content)))
-
- def _save_patch(self, instance_id: str, info) -> Path | None:
- """Create patch files that can be applied with `git am`.
-
- Returns:
- The path to the patch file, if it was saved. Otherwise, returns None.
- """
- patch_output_dir = self._traj_dir / "patches"
- 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.")
- return None
- model_patch = info["submission"]
- patch_output_file.write_text(model_patch)
- if self._is_promising_patch(info):
- # Only print big congratulations if we actually believe
- # the patch will solve the issue
- self._print_patch_message(patch_output_file)
- return patch_output_file
-
- def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:
- """Apply a patch to a local directory."""
-
- assert local_dir.is_dir()
- assert patch_file.exists()
- # The resolve() is important, because we're gonna run the cmd
- # somewhere else
- cmd = ["git", "apply", str(patch_file.resolve())]
- 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}")
- return
- logger.info(f"Applied patch {patch_file} to {local_dir}")
-
-
-class OpenPRHook(MainHook):
- """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 on_instance_completed(self, *, info, trajectory):
- if self._open_pr and self.should_open_pr(info):
- self._env.open_pr(trajectory=trajectory)
-
- 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.")
- return False
- if info["exit_status"] != "submitted":
- 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.")
- return False
- if issue.state != "open":
- 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 :)")
- return False
- if issue.locked:
- 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.")
- return False
- else:
- 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.",
- )
- return True
-
-
class Main:
def __init__(self, args: ScriptArguments):
self.traj_dir = Path("trajectories") / Path(getuser()) / args.run_name
@@ -324,8 +141,8 @@ class Main:
self.env = SWEEnv(args.environment)
self._save_arguments()
default_hooks = [
- SaveApplyPatchHook(),
- OpenPRHook(),
+ # SaveApplyPatchHook(),
+ # OpenPRHook(),
]
self.hooks: list[MainHook] = []
for hook in default_hooks:
@@ -479,13 +296,13 @@ class Main:
KEY_INSTANCE_ID: instance_id,
KEY_PREDICTION: model_patch,
}
- if challenge is not None:
- challenge_datum = {
- "challenge_name": challenge["name"],
- "challenge_category": challenge["category"],
- "challenge_path": challenge["file_path"],
- }
- datum.update(challenge_datum)
+ # if challenge is not None:
+ # challenge_datum = {
+ # "challenge_name": challenge["name"],
+ # "challenge_category": challenge["category"],
+ # "challenge_path": challenge["file_path"],
+ # }
+ # datum.update(challenge_datum)
with open(output_file, "a+") as fp:
print(json.dumps(datum), file=fp, flush=True)
logger.info(f"Saved predictions to {output_file}")
@@ -501,12 +318,12 @@ def get_args(args=None) -> ScriptArguments:
# Otherwise, the configs from the respective classes will be used
no_config_defaults = ScriptArguments(
suffix="",
- environment=EnvironmentArguments(
+ environment=EnvironmentConfig(
deployment=DockerDeploymentConfig(),
- data_path="princeton-nlp/SWE-bench_Lite",
- split="dev",
- verbose=True,
- install_environment=True,
+ # data_path="princeton-nlp/SWE-bench_Lite",
+ # split="dev",
+ # verbose=True,
+ # install_environment=True,
),
skip_existing=True,
agent=AgentConfig(
@@ -544,22 +361,20 @@ def get_args(args=None) -> ScriptArguments:
print("Config merged")
pprint(config_merged)
args = ScriptArguments.model_validate(config_merged)
- args = CliApp.run(ScriptArguments, remaining_args, **config_merged)
+ return CliApp.run(ScriptArguments, remaining_args, **config_merged)
# args = CliApp.run(ScriptArguments, remaining_args, model_init_data=config_merged)
# todo: Do we need this?
# Nicer yaml dumping of multiline strings
- def multiline_representer(dumper, data):
- """configures yaml for dumping multiline strings
- Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
- """
- if data.count("\n") > 0: # check for multiline string
- return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
- return dumper.represent_scalar("tag:yaml.org,2002:str", data)
-
- yaml.add_representer(str, multiline_representer)
-
- return args
+ # def multiline_representer(dumper, data):
+ # """configures yaml for dumping multiline strings
+ # Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
+ # """
+ # if data.count("\n") > 0: # check for multiline string
+ # return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
+ # return dumper.represent_scalar("tag:yaml.org,2002:str", data)
+
+ # yaml.add_representer(str, multiline_representer)
def main(args: ScriptArguments):
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 20575da8..329b9033 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -302,8 +302,7 @@ class Agent:
The path is reset for every new instance.
"""
if self.traj_dir and self._env is not None:
- assert self._env.record
- return self.traj_dir / (self._env.record["instance_id"] + ".traj")
+ return self.traj_dir / (self._env.args.instance.id + ".traj")
return None
def add_hook(self, hook: AgentHook) -> None:
@@ -635,7 +634,7 @@ class Agent:
**self.instance_args,
**self.system_args,
**state_vars,
- observation=(observation if observation is not None else ""),
+ observation=observation or "",
**self._forwarded_vars,
),
)
@@ -956,7 +955,6 @@ class Agent:
If return_type is "info_trajectory", returns a tuple of
the info dictionary and the trajectory (list of dictionaries).
"""
- assert env.record is not None
# if env.container_obj.id != self.last_container_id:
# self.logger.info(f"Initializing agent settings for container {env.container_obj.id}")
self.init_environment_vars(env)
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index 9b7d6095..200e194c 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -178,7 +178,7 @@ class ParseCommandBash(ParseCommand):
signature += f" [<{param}>]"
code = contents
return [
- Command.from_dict(
+ Command.model_validate(
{
"code": code,
"docstring": docstring,
diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.py
index f069150b..60ab0e43 100644
--- a/sweagent/api/hooks.py
+++ b/sweagent/api/hooks.py
@@ -12,7 +12,7 @@ from sweagent.environment.swe_env import EnvHook
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
-from run import MainHook
+from sweagent.main.hooks import MainHook
class StreamToSocketIO(io.StringIO):
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index cb50ad5d..dc3ae7b5 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -32,7 +32,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 DeploymentConfig, EnvironmentArguments
+from sweagent.environment.swe_env import DeploymentConfig, EnvironmentConfig
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
@@ -154,7 +154,7 @@ def run():
agent_config = OmegaConf.load(CONFIG_DIR / "default_from_url.yaml")
defaults = ScriptArguments(
suffix="",
- environment=EnvironmentArguments(
+ environment=EnvironmentConfig(
deployment=DeploymentConfig(),
data_path=run.environment.data_path,
base_commit=run.environment.base_commit,
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 68970477..119a950a 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import logging
-import random
import re
import shlex
import time
@@ -10,11 +9,10 @@ from pathlib import Path, PurePath
from typing import Any, Literal
import gymnasium as gym
-from ghapi.all import GhApi
from git import Repo
-from pydantic import BaseModel, Field
+from pydantic import BaseModel
from swerex.deployment import get_deployment
-from swerex.runtime.abstract import Action, CreateSessionRequest, UploadRequest, WriteFileRequest
+from swerex.runtime.abstract import BashAction, CreateBashSessionRequest, UploadRequest, WriteFileRequest
from sweagent import REPO_ROOT
@@ -24,13 +22,8 @@ from sweagent import REPO_ROOT
# InteractiveSessionConfig,
# )
from sweagent.environment.utils import (
- InvalidGithubURL,
NoOutputTimeoutError,
PatchFormatter,
- format_trajectory_markdown,
- get_gh_issue_data,
- get_instances,
- parse_gh_issue_url,
)
from sweagent.types import AgentInfo
from sweagent.utils.config import keys_config
@@ -47,40 +40,74 @@ class DockerDeploymentConfig(BaseModel):
image: str = "sweagent/swe-agent:latest"
type: Literal["docker"] = "docker"
+ """Sentinel value. Do not change."""
-class EnvironmentArguments(BaseModel):
- """Configure data sources and setup instructions for the environment in which we solve the tasks."""
+class ModalDeploymentConfig(BaseModel):
+ image: str = "sweagent/swe-agent:latest"
+
+ modal_username: str = "test"
+
+ type: Literal["modal"] = "modal"
+ """Sentinel value. Do not change."""
+
+
+DeploymentConfig = DockerDeploymentConfig | ModalDeploymentConfig
- # Source of issue statement/problem statement. To run over a batch of issues: Path to a data file
- # (`json`, `jsonl`) or directory. To run over single issue: github issue url or path to markdown file
- # with problem statement or problem statement as text prefixed with `text://`.
- data_path: str = ""
- deployment: DockerDeploymentConfig = Field(..., discriminator="type", default_factory=DockerDeploymentConfig)
+class InstanceConfig(BaseModel):
+ content: str = ""
+ id: str = ""
- # When running over SWE-bench issues: Specify the split to use.
- split: str = "dev"
- # Specify a branch name or a commit hash to checkout before running the task.
- # Only used when running over a single problem statement/issue.
+
+class LocalRepoConfig(BaseModel):
+ path: str = ""
base_commit: str | None = None
- # Try to install the environment before running the task.
- install_environment: bool = True
- # Enable environment logger.
- verbose: bool = False
- # Do not use attempt to use a repository mirror from https://github.com/swe-bench.
- no_mirror: bool = False
- # Custom environment setup. Currently only used when data_path points to a single issue.
- # This needs to be either a string pointing to a yaml file (with yaml, yml file extension)
- # or a shell script (with sh extension).
- # See https://princeton-nlp.github.io/SWE-agent/usage/cl_tutorial#environment-setup
- environment_setup: str | None = None
- # Only used when running on single issue. Path to local repository or github repository.
- repo_path: str = ""
- # Interactive command configuration
- # interactive_sessions_config: dict[str, InteractiveSessionConfig] = field(
- # default_factory=lambda: INTERACTIVE_SESSIONS_CONFIG
- # )
+
+ type: Literal["local"] = "local"
+ """Discriminator for serialization. Do not change."""
+
+ @property
+ def repo_name(self) -> str:
+ return Path(self.path).name.replace(" ", "-").replace("'", "")
+
+
+class GithubRepoConfig(BaseModel):
+ url: str = ""
+
+ base_commit: str | None = None
+
+ type: Literal["github"] = "github"
+ """Discriminator for serialization. Do not change."""
+
+ @property
+ def repo_name(self) -> str:
+ # fixme: Need to replace ":" etc.
+ org, repo = self.url.split("/")[-2:]
+ return f"{org}__{repo}"
+
+ def _get_url_with_token(self, token: str) -> str:
+ """Prepend github token to URL"""
+ if "@" in self.url:
+ return self.url
+ return f"https://{token}@{self.url}"
+
+
+RepoConfig = LocalRepoConfig | GithubRepoConfig
+
+
+class EnvironmentConfig(BaseModel):
+ """Configure data sources and setup instructions for the environment in which we solve the tasks."""
+
+ instance: InstanceConfig = InstanceConfig()
+ deployment: DeploymentConfig | None = None
+ repo: RepoConfig | None = None
+ startup_commands: list[str] = []
+
+ def model_post_init(self, __context: Any) -> None:
+ print("In model_post_init")
+ if self.deployment is None:
+ self.deployment = DockerDeploymentConfig()
class EnvHook:
@@ -94,13 +121,8 @@ class EnvHook:
def on_init(self) -> None:
"""Gets called when the hook is added"""
- def on_copy_repo_started(self, *, repo_type: str, repo_path: str) -> None:
- """Gets called when the repository is being cloned to the container
-
- Args:
- repo_type: Type of repository. Either 'local' or 'github'
- repo_path: Path to the repository
- """
+ def on_copy_repo_started(self, repo: RepoConfig) -> None:
+ """Gets called when the repository is being cloned to the container"""
def on_install_env_started(self) -> None:
"""Called when we start installing the environment"""
@@ -114,19 +136,15 @@ class SWEEnv(gym.Env):
name = "swe_main"
- def __init__(self, args: EnvironmentArguments):
+ def __init__(self, args: EnvironmentConfig):
super().__init__()
t0 = time.perf_counter()
self.args = args
self.base_commit: str | None = None
- self.install_environment = args.install_environment
self.logger = get_logger("SWEEnv")
self.returncode: None | int = None
- if not self.args.verbose:
- # fixme: This creates problems if we have multiple instances of this class
- self.logger.disabled = True
- #: The commit hash of the swe-agent repository
+ # : The commit hash of the swe-agent repository
self.commit_sha = None
try:
repo = Repo(REPO_ROOT, search_parent_directories=True)
@@ -138,19 +156,6 @@ class SWEEnv(gym.Env):
self._github_token: str = keys_config.get("GITHUB_TOKEN", "") # type: ignore
- # Load Task Instances
- self.data_path = self.args.data_path
- self.data = get_instances(
- self.data_path,
- self.args.base_commit,
- self.args.split,
- token=self._github_token,
- repo_path=self.args.repo_path,
- )
- #: Instance we're currently processing. Gets set in self.reset.
- self.record: dict[str, Any] | None = None
- self.logger.info(f"πŸ’½ Loaded dataset from {self.data_path}")
-
# Establish connection with execution container
# self.docker_compose: Path | None = None
# self.challenge: dict[str, Any] | None = None
@@ -173,11 +178,10 @@ class SWEEnv(gym.Env):
hook.on_init()
self.hooks.append(hook)
- @property
- def _repo_name(self) -> str:
- """Name of the local copy of the repository"""
- assert self.record is not None
- return self.record["repo"].replace("/", "__").replace(" ", "-").replace("'", "")
+ # @property
+ # def _repo_name(self) -> str:
+ # """Name of the local copy of the repository"""
+ # return self.record["repo"].replace("/", "__").replace(" ", "-").replace("'", "")
def _copy_repo(self) -> str:
"""Clone/copy repository/codebase in container
@@ -186,67 +190,52 @@ class SWEEnv(gym.Env):
folder name of clone
"""
# assert self.container_obj is not None
- assert self.record is not None # mypy
for hook in self.hooks:
- hook.on_copy_repo_started(repo_type=self.record["repo_type"], repo_path=self.record["repo"])
- if self.record["repo_type"] == "local":
- if "challenge" in self.record:
- self.communicate_with_handling(
- input=f"mkdir {self._repo_name}", error_msg=f"Failed to create {self._repo_name} in container"
- )
- for file_name in self.record["challenge"]["files"]:
- self.logger.debug(f"Copying file {file_name} to container")
- source_file_name = Path(self.record["repo"].removeprefix("local://")) / file_name
- target_file_name = Path("/") / self._repo_name / file_name
- asyncio.run(
- self.deployment.runtime.upload(
- UploadRequest(source_path=str(source_file_name), target_path=str(target_file_name))
- )
- )
- else:
- asyncio.run(
- self.deployment.runtime.upload(
- UploadRequest(
- source_path=self.record["repo"].removeprefix("local://"), target_path="/" + self._repo_name
- )
- )
+ if self.args.repo:
+ hook.on_copy_repo_started(self.args.repo)
+ if isinstance(self.args.repo, LocalRepoConfig):
+ # if "challenge" in self.record:
+ # self.communicate_with_handling(
+ # input=f"mkdir {self._repo_name}", error_msg=f"Failed to create {self._repo_name} in container"
+ # )
+ # for file_name in self.record["challenge"]["files"]:
+ # self.logger.debug(f"Copying file {file_name} to container")
+ # source_file_name = Path(self.record["repo"].removeprefix("local://")) / file_name
+ # target_file_name = Path("/") / self._repo_name / file_name
+ # asyncio.run(
+ # self.deployment.runtime.upload(
+ # UploadRequest(source_path=str(source_file_name), target_path=str(target_file_name))
+ # )
+ # )
+ # else:
+ asyncio.run(
+ self.deployment.runtime.upload(
+ UploadRequest(source_path=self.args.repo.path, target_path="/" + self.args.repo.repo_name)
)
+ )
self.communicate_with_handling(
- input=f"chown -R root:root {self._repo_name}",
+ input=f"chown -R root:root {self.args.repo.repo_name}",
error_msg="Failed to change permissions on copied repository",
)
- return self._repo_name
- assert self.record["repo_type"] == "github"
- token_prefix = ""
- if self._github_token:
- token_prefix = f"{self._github_token}@"
- # fixme: This if statement is brittle and should probably be replaced with better logic
- if not self.args.no_mirror and self.record["problem_statement_source"] == "swe-bench":
- self.logger.info(f"{self._repo_name} not found in container, cloning...")
- clone_url = f"https://{token_prefix}github.com/swe-bench/{self._repo_name}.git"
- else:
- self.logger.info("Trying to clone from non-mirror...")
- clone_url = f"https://{token_prefix}github.com/{self.record['repo']}.git"
+ return self.args.repo.repo_name
+ assert isinstance(self.args.repo, GithubRepoConfig)
+ url = self.args.repo._get_url_with_token(self._github_token)
clone_method = keys_config.get("SWE_AGENT_CLONE_METHOD", default="shallow", choices=["shallow", "full"])
- if len(self.data) > 1:
- msg = "Falling back to full cloning method due to multiple instances or persistent container"
- clone_method = "full"
- self.logger.debug(msg)
if clone_method == "full":
self.communicate_with_handling(
- input=f"git clone {clone_url} {self._repo_name}",
+ input=f"git clone {url} {self.args.repo.repo_name}",
error_msg="Failed to clone repository from conservative method",
timeout_duration=LONG_TIMEOUT,
)
else:
- base_commit = self.record["base_commit"]
+ base_commit = self.args.repo.base_commit
self.communicate_with_handling(
input="&&".join(
(
- f"mkdir {self._repo_name}",
- f"cd {self._repo_name}",
+ f"mkdir {self.args.repo.repo_name}",
+ f"cd {self.args.repo.repo_name}",
"git init",
- f"git remote add origin {clone_url}",
+ f"git remote add origin {url}",
f"git fetch --depth 1 origin {base_commit}",
"git checkout FETCH_HEAD",
"cd ..",
@@ -255,9 +244,9 @@ class SWEEnv(gym.Env):
error_msg="Failed to clone repository with fast method",
timeout_duration=LONG_TIMEOUT,
)
- return self._repo_name
+ return self.args.repo.repo_name
- def reset(self, index: int | None = None) -> tuple[str | None, dict]:
+ def reset(self) -> tuple[str | None, dict]:
"""
Function to reset container between each task instance.
@@ -276,17 +265,6 @@ class SWEEnv(gym.Env):
info = {}
info["commit_sha"] = self.commit_sha
- # Get task instance
- self.idx = index if index is not None else self.idx
- self.record = self.data[self.idx]
- self.idx += 1
-
- # Set query, gold command
- self.base_commit = self.record["base_commit"]
- self.query = self.record["problem_statement"]
- # self.challenge = self.record.get("challenge")
- self.reward = None
-
### Reset Container ###
# self._init_docker_compose()
@@ -296,7 +274,7 @@ class SWEEnv(gym.Env):
# Clone repository if not already cloned
self.communicate(input="cd /")
folders = self.communicate(input="ls").split("\n")
- if self._repo_name not in folders:
+ if self.args.repo and self.args.repo.repo_name not in folders:
print("copying repo")
self._copy_repo()
@@ -329,22 +307,23 @@ class SWEEnv(gym.Env):
def _reset_repository(self) -> None:
"""Clean repository of any modifications + Checkout base commit"""
- startup_commands = [
- "echo -n > /root/files_to_edit.txt",
- f"cd /{self._repo_name}",
- "export ROOT=$(pwd -P)",
- ]
- # if self.challenge is None:
- startup_commands += [
- "git status",
- "git restore .",
- f"git reset --hard {self.base_commit}",
- "git clean -fdxq",
- ]
- self.communicate_with_handling(
- input=" && ".join(startup_commands),
- error_msg="Failed to clean repository",
- )
+ if self.args.repo is not None:
+ startup_commands = [
+ "echo -n > /root/files_to_edit.txt",
+ f"cd /{self.args.repo.repo_name}",
+ "export ROOT=$(pwd -P)",
+ ]
+ # if self.challenge is None:
+ startup_commands += [
+ "git status",
+ "git restore .",
+ f"git reset --hard {self.base_commit}",
+ "git clean -fdxq",
+ ]
+ self.communicate_with_handling(
+ input=" && ".join(startup_commands),
+ error_msg="Failed to clean repository",
+ )
def _reset_environment_variables(self) -> None:
"""Reset environment variables (`CURRENT_FILE`) etc. within container"""
@@ -547,15 +526,6 @@ class SWEEnv(gym.Env):
self.logger.warning(f"Failed to execute command: {e}\nRESTARTING PROCESS.")
self.reset_container()
return observation, 0, True, info
- except BrokenPipeError as e:
- observation += "\nBROKEN PIPE ERROR. RESTARTING PROCESS."
- info["exit_status"] = "early_exit"
- self.logger.error(f"Broken pipe error: {e}\nRESTARTING PROCESS.")
- self.reset_container()
- return observation, 0, True, info
- except UnicodeError as e:
- observation += "\nCOMMAND PRODUCED TOO MANY NON-UNICODE CHARACTERS. PLEASE TRY ANOTHER COMMAND.\nIF YOU WANT TO VIEW BINARY FILES, PLEASE USE `xxd` OR `hexdump` INSTEAD.\n"
- self.logger.error(f"Unicode error: {e}")
except Exception:
observation += "\nEXECUTION FAILED OR COMMAND MALFORMED"
self.logger.exception("Unknown exception")
@@ -635,7 +605,7 @@ class SWEEnv(gym.Env):
kwargs = {k: v for k, v in self.args.deployment.model_dump().items() if k != "type"}
self.deployment = get_deployment(self.args.deployment.type, **kwargs) # type: ignore
asyncio.run(self.deployment.start())
- asyncio.run(self.deployment.runtime.create_session(CreateSessionRequest(startup_source=["/root/.bashrc"])))
+ asyncio.run(self.deployment.runtime.create_session(CreateBashSessionRequest(startup_source=["/root/.bashrc"])))
self.logger.info("🌱 Environment Initialized")
def _init_scripts(self):
@@ -669,7 +639,7 @@ class SWEEnv(gym.Env):
no_output_timeout_duration: duration to wait when the process stopped produce any output
"""
self.returncode = None
- r = asyncio.run(self.deployment.runtime.run_in_session(Action(command=input, timeout=timeout_duration)))
+ r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout_duration)))
self.returncode = r.exit_code
return r.output
@@ -823,105 +793,106 @@ class SWEEnv(gym.Env):
msg = f"Invalid command type: {command['type']}"
raise ValueError(msg)
- def open_pr(self, *, trajectory, _dry_run: bool = False) -> None:
- """Create PR to repository
+ # todo: Move this to run.py
+ # def open_pr(self, *, trajectory, _dry_run: bool = False) -> None:
+ # """Create PR to repository
- Args:
- trajectory: Trajectory of actions taken by the agent
- _dry_run: Whether to actually push anything or just simulate it
- """
- self.logger.info("Opening PR")
- # TODO: have better way of handling this
- # Adding random string suffix to avoid name conflicts if we had a previously failed run
- issue_url = self.args.data_path
- try:
- issue = get_gh_issue_data(issue_url, token=self._github_token)
- except InvalidGithubURL as e:
- msg = "Data path must be a github issue URL if --open_pr is set."
- raise ValueError(msg) from e
- branch_name = f"swe-agent-fix-#{issue.number}-" + str(random.random())[2:10]
-
- self.communicate_with_handling(
- input="rm -f model.patch",
- error_msg="Failed to remove model patch",
- timeout_duration=10,
- )
- self.communicate_with_handling(
- input=f"git checkout -b {branch_name}",
- error_msg="Failed to switch to new branch",
- timeout_duration=10,
- )
- self.communicate_with_handling(
- input="git add .",
- error_msg="Failed to add commits",
- timeout_duration=10,
- )
- dry_run_flag = "--allow-empty" if _dry_run else ""
- commit_msg = [
- shlex.quote("Fix: {issue.title}"),
- shlex.quote("Closes #{issue.number}"),
- ]
- self.communicate_with_handling(
- input=f"git commit -m {commit_msg[0]} -m {commit_msg[1]} {dry_run_flag}",
- error_msg="Failed to commit changes",
- timeout_duration=10,
- )
+ # Args:
+ # trajectory: Trajectory of actions taken by the agent
+ # _dry_run: Whether to actually push anything or just simulate it
+ # """
+ # self.logger.info("Opening PR")
+ # # TODO: have better way of handling this
+ # # Adding random string suffix to avoid name conflicts if we had a previously failed run
+ # issue_url = self.args.data_path
+ # try:
+ # issue = get_gh_issue_data(issue_url, token=self._github_token)
+ # except InvalidGithubURL as e:
+ # msg = "Data path must be a github issue URL if --open_pr is set."
+ # raise ValueError(msg) from e
+ # branch_name = f"swe-agent-fix-#{issue.number}-" + str(random.random())[2:10]
+
+ # self.communicate_with_handling(
+ # input="rm -f model.patch",
+ # error_msg="Failed to remove model patch",
+ # timeout_duration=10,
+ # )
+ # self.communicate_with_handling(
+ # input=f"git checkout -b {branch_name}",
+ # error_msg="Failed to switch to new branch",
+ # timeout_duration=10,
+ # )
+ # self.communicate_with_handling(
+ # input="git add .",
+ # error_msg="Failed to add commits",
+ # timeout_duration=10,
+ # )
+ # dry_run_flag = "--allow-empty" if _dry_run else ""
+ # commit_msg = [
+ # shlex.quote("Fix: {issue.title}"),
+ # shlex.quote("Closes #{issue.number}"),
+ # ]
+ # self.communicate_with_handling(
+ # input=f"git commit -m {commit_msg[0]} -m {commit_msg[1]} {dry_run_flag}",
+ # error_msg="Failed to commit changes",
+ # timeout_duration=10,
+ # )
- owner, repo, _ = parse_gh_issue_url(issue_url)
- # If `--repo_path` was specified with a different github URL, then the record will contain
- # the forking user
- assert self.record is not None
- if self.record["repo_type"] != "github":
- # We already validated that `--data_path` is a github issue URL
- # so this is the only case where we can reach here
- msg = "--repo_path must point to a github URL if --open_pr is set"
- raise ValueError(msg)
- forker, _ = self.record["repo"].split("/")
- head = branch_name
- remote = "origin"
- if forker != owner:
- head = f"{forker}:{branch_name}"
- token_prefix = ""
- if self._github_token:
- token_prefix = f"{self._github_token}@"
- fork_url = f"https://{token_prefix}github.com/{forker}/{repo}.git"
- self.logger.debug(f"Using fork: {fork_url}")
- self.communicate_with_handling(
- input=f"git remote add fork {fork_url}",
- error_msg="Failed to create new git remote",
- timeout_duration=10,
- )
- remote = "fork"
- dry_run_prefix = "echo " if _dry_run else ""
- self.communicate_with_handling(
- input=f"{dry_run_prefix} git push {remote} {branch_name}",
- error_msg=(
- "Failed to push branch to remote. Please check your token and permissions. "
- "You might want to push to a fork with the push_gh_repo_url option."
- ),
- timeout_duration=10,
- )
- body = (
- f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "
- f"to close [#{issue.number}]({issue_url}) ({issue.title}).\n\nCloses #{issue.number}."
- )
- body += "\n\n" + format_trajectory_markdown(trajectory)
- api = GhApi(token=self._github_token)
- if not _dry_run:
- pr_info = api.pulls.create( # type: ignore
- owner=owner,
- repo=repo,
- title=f"SWE-agent[bot] PR to fix: {issue.title}",
- head=head,
- base="main",
- body=body,
- draft=True,
- )
- self.logger.info(
- f"πŸŽ‰ PR created as a draft at {pr_info.html_url}. Please review it carefully, push "
- "any required changes onto the branch and then click "
- "'Ready for Review' to bring it to the attention of the maintainers.",
- )
+ # owner, repo, _ = parse_gh_issue_url(issue_url)
+ # # If `--repo_path` was specified with a different github URL, then the record will contain
+ # # the forking user
+ # assert self.record is not None
+ # if self.record["repo_type"] != "github":
+ # # We already validated that `--data_path` is a github issue URL
+ # # so this is the only case where we can reach here
+ # msg = "--repo_path must point to a github URL if --open_pr is set"
+ # raise ValueError(msg)
+ # forker, _ = self.record["repo"].split("/")
+ # head = branch_name
+ # remote = "origin"
+ # if forker != owner:
+ # head = f"{forker}:{branch_name}"
+ # token_prefix = ""
+ # if self._github_token:
+ # token_prefix = f"{self._github_token}@"
+ # fork_url = f"https://{token_prefix}github.com/{forker}/{repo}.git"
+ # self.logger.debug(f"Using fork: {fork_url}")
+ # self.communicate_with_handling(
+ # input=f"git remote add fork {fork_url}",
+ # error_msg="Failed to create new git remote",
+ # timeout_duration=10,
+ # )
+ # remote = "fork"
+ # dry_run_prefix = "echo " if _dry_run else ""
+ # self.communicate_with_handling(
+ # input=f"{dry_run_prefix} git push {remote} {branch_name}",
+ # error_msg=(
+ # "Failed to push branch to remote. Please check your token and permissions. "
+ # "You might want to push to a fork with the push_gh_repo_url option."
+ # ),
+ # timeout_duration=10,
+ # )
+ # body = (
+ # f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "
+ # f"to close [#{issue.number}]({issue_url}) ({issue.title}).\n\nCloses #{issue.number}."
+ # )
+ # body += "\n\n" + format_trajectory_markdown(trajectory)
+ # api = GhApi(token=self._github_token)
+ # if not _dry_run:
+ # pr_info = api.pulls.create( # type: ignore
+ # owner=owner,
+ # repo=repo,
+ # title=f"SWE-agent[bot] PR to fix: {issue.title}",
+ # head=head,
+ # base="main",
+ # body=body,
+ # draft=True,
+ # )
+ # self.logger.info(
+ # f"πŸŽ‰ PR created as a draft at {pr_info.html_url}. Please review it carefully, push "
+ # "any required changes onto the branch and then click "
+ # "'Ready for Review' to bring it to the attention of the maintainers.",
+ # )
def read_file(self, path: str | PurePath) -> str:
"""Read file contents from container
@@ -933,5 +904,5 @@ class SWEEnv(gym.Env):
file_contents: Contents of file as string
"""
# todo: Just use the runtime for this instead
- path_in_container = f"/{self._repo_name}/{path}"
+ path_in_container = f"/{self.args.repo.repo_name}/{path}"
return self.communicate(f"cat {str(path_in_container)}")
diff --git a/sweagent/main/__init__.py b/sweagent/main/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/sweagent/main/common.py b/sweagent/main/common.py
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/sweagent/main/common.py
@@ -0,0 +1 @@
+
diff --git a/sweagent/main/hooks.py b/sweagent/main/hooks.py
new file mode 100644
index 00000000..de595b58
--- /dev/null
+++ b/sweagent/main/hooks.py
@@ -0,0 +1,186 @@
+import subprocess
+from pathlib import Path
+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.environment.utils import (
+ InvalidGithubURL,
+ get_associated_commit_urls,
+ get_gh_issue_data,
+ parse_gh_issue_url,
+)
+
+
+class MainHook:
+ """Hook structure for the web server or other addons to interface with"""
+
+ @staticmethod
+ def _is_promising_patch(info: dict[str, Any]) -> bool:
+ """Do we actually believe that the patch will solve the issue?
+ Or are we just submitting the last patch we generated before hitting an error?
+ """
+ # 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):
+ """Called when hook is initialized"""
+
+ def on_start(self):
+ """Called at the beginning of `Main.main`"""
+
+ def on_end(self):
+ """Called at the end of `Main.main`"""
+
+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):
+ """Called at the beginning of each instance loop in `Main.run`"""
+
+ def on_instance_skipped(
+ self,
+ ):
+ """Called when an instance is skipped in `Main.run`"""
+
+ def on_instance_completed(self, *, info, trajectory):
+ """Called when an instance is completed in `Main.run`"""
+
+
+class SaveApplyPatchHook(MainHook):
+ """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
+ self._instance = None
+
+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):
+ self._instance = instance
+
+ def on_instance_completed(self, *, info, trajectory):
+ assert self._instance is not None # mypy
+ instance_id = self._instance["instance_id"]
+ patch_path = self._save_patch(instance_id, info)
+ if patch_path:
+ if not self._apply_patch_locally:
+ return
+ if not self._is_promising_patch(info):
+ return
+ assert self._instance # mypy
+ if self._instance["repo_type"] != "local":
+ return
+ local_dir = Path(self._instance["repo"])
+ self._apply_patch(patch_path, local_dir)
+
+ @staticmethod
+ def _print_patch_message(patch_output_file: Path):
+ console = rich.console.Console()
+ msg = [
+ "SWE-agent has produced a patch that it believes will solve the issue you submitted!",
+ "Use the code snippet below to inspect or apply it!",
+ ]
+ panel = rich.panel.Panel.fit(
+ "\n".join(msg),
+ title="πŸŽ‰ Submission successful πŸŽ‰",
+ )
+ console.print(panel)
+ content = [
+ "```bash",
+ "# The patch has been saved to your local filesystem at:",
+ f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
+ "# Inspect it:",
+ 'cat "${PATCH_FILE_PATH}"',
+ "# Apply it to a local repository:",
+ "cd <your local repo root>",
+ 'git apply "${PATCH_FILE_PATH}"',
+ "```",
+ ]
+ console.print(rich.markdown.Markdown("\n".join(content)))
+
+ def _save_patch(self, instance_id: str, info) -> Path | None:
+ """Create patch files that can be applied with `git am`.
+
+ Returns:
+ The path to the patch file, if it was saved. Otherwise, returns None.
+ """
+ patch_output_dir = self._traj_dir / "patches"
+ 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.")
+ return None
+ model_patch = info["submission"]
+ patch_output_file.write_text(model_patch)
+ if self._is_promising_patch(info):
+ # Only print big congratulations if we actually believe
+ # the patch will solve the issue
+ self._print_patch_message(patch_output_file)
+ return patch_output_file
+
+ def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:
+ """Apply a patch to a local directory."""
+
+ assert local_dir.is_dir()
+ assert patch_file.exists()
+ # The resolve() is important, because we're gonna run the cmd
+ # somewhere else
+ cmd = ["git", "apply", str(patch_file.resolve())]
+ 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}")
+ return
+ logger.info(f"Applied patch {patch_file} to {local_dir}")
+
+
+class OpenPRHook(MainHook):
+ """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 on_instance_completed(self, *, info, trajectory):
+ if self._open_pr and self.should_open_pr(info):
+ self._env.open_pr(trajectory=trajectory)
+
+ 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.")
+ return False
+ if info["exit_status"] != "submitted":
+ 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.")
+ return False
+ if issue.state != "open":
+ 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 :)")
+ return False
+ if issue.locked:
+ 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.")
+ return False
+ else:
+ 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.",
+ )
+ return True
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
new file mode 100644
index 00000000..226cc4b4
--- /dev/null
+++ b/sweagent/main/run_basic.py
@@ -0,0 +1,109 @@
+"""Run in human mode without any complicated env setup.
+This is mostly for debugging and development.
+"""
+
+from argparse import ArgumentParser
+from pathlib import Path
+
+import yaml
+from pydantic import Field
+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.utils.log import get_logger
+
+
+class BasicRunArguments(BaseSettings):
+ env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
+ agent: AgentConfig = AgentConfig(
+ model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
+ )
+ traj_dir: str = "."
+
+
+# todo: add hooks
+class BasicMain:
+ def __init__(self, args: BasicRunArguments):
+ self.args = args
+ self.logger = get_logger("PlaygroundMain")
+ self.logger.info("Initializing environment")
+ self.env = SWEEnv(args.env)
+ self.logger.info("Initializing agent")
+ self.agent = Agent("main", args.agent)
+
+ def main(self):
+ self.logger.info("Resetting environment")
+ observation, info = self.env.reset()
+ self.logger.info("Running agent")
+ info, trajectory = self.agent.run(
+ setup_args={},
+ env=self.env,
+ observation=observation,
+ traj_dir=Path(self.args.traj_dir),
+ return_type="info_trajectory",
+ )
+ self.logger.info("Done")
+
+
+def main(args: BasicRunArguments):
+ BasicMain(args).main()
+
+
+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
+
+
+if __name__ == "__main__":
+ main(BasicCLI(BasicRunArguments).get_args()) # type: ignore
diff --git a/tests/conftest.py b/tests/conftest.py
index e52e52d5..eb45d2d8 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 EnvironmentArguments, 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
@@ -76,13 +76,13 @@ def test_trajectory(test_trajectory_path):
@pytest.fixture(scope="module")
def test_env_args(
tmpdir_factory,
-) -> Generator[EnvironmentArguments]:
+) -> 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 = EnvironmentArguments(
+ test_env_args = EnvironmentConfig(
data_path=str(data_path),
repo_path=str(local_repo_path),
image_name="sweagent/swe-agent:latest",
diff --git a/tests/test_run.py b/tests/test_run.py
index 692ca34e..4bf405e8 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -11,10 +11,11 @@ from typing import Any
import pytest
import docker
-from run import ActionsArguments, Main, MainHook, OpenPRHook, ScriptArguments
+from run import ActionsArguments, Main, ScriptArguments
from sweagent.agent.agents import Agent, AgentConfig, AgentHook
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentArguments, SWEEnv
+from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
+from sweagent.main.hooks import MainHook, OpenPRHook
@pytest.mark.slow
@@ -104,7 +105,7 @@ class RaisesExceptionHook(MainHook):
def test_script_args():
return ScriptArguments(
suffix="",
- environment=EnvironmentArguments(
+ environment=EnvironmentConfig(
image_name="sweagent/swe-agent:latest",
data_path="https://github.com/swe-agent/test-repo/issues/1",
split="dev",