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]

Rename _github -> github and fixes

Kilian Lieret1a2916bf9dc7
diff --git a/run.py b/run.py
index c89ae8a7..620a58b0 100644
--- a/run.py
+++ b/run.py
@@ -182,7 +182,6 @@ class Main:
env=self.env,
observation=observation,
traj_dir=self.traj_dir,
- return_type="info_trajectory",
)
challenge = None
self._save_predictions(instance_id, info, challenge)
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 96580983..34796044 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -936,9 +936,8 @@ class Agent:
env: SWEEnv,
observation: str | None = None,
traj_dir: Path | None = None,
- return_type: str = "info_trajectory",
init_model_stats: APIStats | None = None,
- ):
+ ) -> tuple[AgentInfo, Trajectory]:
"""
Run the agent on an environment.
Return the final value of the specified return type.
@@ -948,22 +947,14 @@ class Agent:
env: The environment to run the agent on.
observation: Output from environment setup
traj_dir: Directory to save the trajectory to
- return_type: Controls what to return.
- This should be left at `info_trajectory`, the
- other values are for internal usage with subroutines.
init_model_stats: Initial model stats to use for the run.
Returns:
If return_type is "info_trajectory", returns a tuple of
the info dictionary and the trajectory (list of dictionaries).
"""
- # 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)
- # Re-initialize primary
self.setup(setup_args, init_model_stats)
- # self._summarizer =
- # self.config.summarizer_config.function.setup(setup_args, self.config)
# Save/reset some attributes
self.trajectory = Trajectory()
@@ -981,14 +972,8 @@ class Agent:
while not done:
observation, done = self._run_step(observation)
self.save_trajectory()
- if done:
- done = True
self._fire_hooks("on_run_done", trajectory=self.trajectory, info=self.info)
self.logger.info("Trajectory saved to %s", self.traj_path)
- if return_type == "info":
- return self.info
- if return_type == "info_trajectory":
- return self.info, self.trajectory
- return self.trajectory[-1][return_type]
+ return self.info, self.trajectory
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.py
index 79516ba4..ecdcaccb 100644
--- a/sweagent/environment/config/problem_statement.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -5,8 +5,8 @@ from typing import Literal
from pydantic import BaseModel, Field
-from sweagent.utils._github import get_problem_statement_from_github_issue, parse_gh_issue_url
from sweagent.utils.config import keys_config
+from sweagent.utils.github import _get_problem_statement_from_github_issue, _parse_gh_issue_url
class EmptyProblemStatement(BaseModel):
@@ -58,8 +58,10 @@ class GithubIssue(BaseModel):
return f"{org}__{repo}-i{issue}"
def get_problem_statement(self) -> str:
- owner, repo, issue_number = parse_gh_issue_url(self.issue_url)
- return get_problem_statement_from_github_issue(owner, repo, issue_number, token=keys_config.get("GITHUB_TOKEN"))
+ owner, repo, issue_number = _parse_gh_issue_url(self.issue_url)
+ return _get_problem_statement_from_github_issue(
+ owner, repo, issue_number, token=keys_config.get("GITHUB_TOKEN")
+ )
-ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement
+ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
index d0112c12..a65dd867 100644
--- a/sweagent/main/run_basic.py
+++ b/sweagent/main/run_basic.py
@@ -48,7 +48,6 @@ class BasicMain:
env=self.env,
observation=observation,
traj_dir=Path(self.traj_dir),
- return_type="info_trajectory",
)
self.logger.info("Done")
diff --git a/sweagent/run/hooks/open_pr.py b/sweagent/run/hooks/open_pr.py
index a90a84b6..dc9f0a39 100644
--- a/sweagent/run/hooks/open_pr.py
+++ b/sweagent/run/hooks/open_pr.py
@@ -4,7 +4,7 @@ from pydantic import BaseModel
from sweagent.environment.utils import InvalidGithubURL
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.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
@@ -142,7 +142,7 @@ class OpenPRHook(RunHook):
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)
+ issue = _get_gh_issue_data(self._data_path, token=self._token)
except InvalidGithubURL:
self.logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
return False
@@ -155,8 +155,8 @@ class OpenPRHook(RunHook):
if issue.locked:
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)
+ 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._config.skip_if_commits_reference_issue:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index f2696a18..9192eaa2 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -80,7 +80,6 @@ class RunBatch:
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")
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index a6fe85a9..f54fa33e 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -100,7 +100,6 @@ class RunSingle:
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")
diff --git a/sweagent/utils/_github.py b/sweagent/utils/github.py
similarity index 75%
rename from sweagent/utils/_github.py
rename to sweagent/utils/github.py
index b234acaf..31247d28 100644
--- a/sweagent/utils/_github.py
+++ b/sweagent/utils/github.py
@@ -2,27 +2,24 @@ import re
from ghapi.all import GhApi
-from sweagent.environment.utils import InvalidGithubURL
-
GITHUB_ISSUE_URL_PATTERN = re.compile(r"github\.com\/(.*?)\/(.*?)\/issues\/(\d+)")
-def is_github_issue_url(data_path: str) -> bool:
- """Check if data_path is an URL pointing to a github issue"""
- return GITHUB_ISSUE_URL_PATTERN.search(data_path) is not None
+class InvalidGithubURL(Exception):
+ """Raised when a github URL is invalid"""
GITHUB_REPO_URL_PATTERN = re.compile(r".*[/@]?github\.com\/([^/]+)\/([^/]+)")
-def is_github_repo_url(data_path: str) -> bool:
+def _is_github_repo_url(data_path: str) -> bool:
"""Check if data_path is an URL pointing to a github repository.
Paths to issues or PRs will also match this pattern.
"""
return GITHUB_REPO_URL_PATTERN.search(data_path) is not None
-def get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
+def _get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
"""Get commit object from github api
Args:
@@ -39,7 +36,7 @@ def get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
return api.repos.list_commits(owner, repo)[0] # type: ignore
-def parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:
+def _parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:
"""
Returns:
owner: Repo owner
@@ -58,7 +55,7 @@ def parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:
return tuple(res) # type: ignore
-def parse_gh_repo_url(repo_url: str) -> tuple[str, str]:
+def _parse_gh_repo_url(repo_url: str) -> tuple[str, str]:
"""
Returns:
owner: Repo owner/org
@@ -76,17 +73,19 @@ def parse_gh_repo_url(repo_url: str) -> tuple[str, str]:
return tuple(res) # type: ignore
-def get_gh_issue_data(issue_url: str, *, token: str = ""):
+def _get_gh_issue_data(issue_url: str, *, token: str = ""):
"""Returns github issue data in the form of a dictionary.
See https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
for return format
"""
- owner, repo, issue_number = parse_gh_issue_url(issue_url)
+ owner, repo, issue_number = _parse_gh_issue_url(issue_url)
api = GhApi(token=token)
- return api.issues.get(owner, repo, issue_number)
+ return api.issues.get(owner, repo, issue_number) # type: ignore
-def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: str | None = "") -> str:
+def _get_problem_statement_from_github_issue(
+ owner: str, repo: str, issue_number: str, *, token: str | None = ""
+) -> str:
"""Return problem statement from github issue"""
api = GhApi(token=token)
issue = api.issues.get(owner, repo, issue_number) # type: ignore
@@ -95,19 +94,19 @@ def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number:
return f"{title}\n{body}\n"
-def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token: str = "") -> list[str]:
+def _get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token: str = "") -> list[str]:
"""Return the URLs of commits that would close an issue."""
api = GhApi(token=token)
# Strangely the "pull_request" field of api.issues.get is often not set
# so we have to go through the events to check if there's a commit
- events = api.issues.list_events(org, repo, issue_number)
+ events = api.issues.list_events(org, repo, issue_number) # type: ignore
commit_urls = []
for event in events:
if event.event != "referenced":
continue
if not event.commit_id:
continue
- commit = api.repos.get_commit(org, repo, event.commit_id)
+ commit = api.repos.get_commit(org, repo, event.commit_id) # type: ignore
message = commit.commit.message
if f"fixes #{issue_number}" in message.lower() or f"closes #{issue_number}" in message.lower():
commit_urls.append(commit.html_url)
diff --git a/tests/conftest.py b/tests/conftest.py
index bc85570f..1b633759 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -10,8 +10,9 @@ from pathlib import Path
import pytest
-import docker
-import docker.errors
+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
# this is a hack and should be removed when we have a better solution
@@ -83,24 +84,11 @@ def test_env_args(
subprocess.run(clone_cmd, check=True)
data_path = local_repo_path / "problem_statements" / "1.md"
test_env_args = EnvironmentInstanceConfig(
- data_path=str(data_path),
- repo_path=str(local_repo_path),
- image_name="sweagent/swe-agent:latest",
- container_name="test-container-this-is-a-random-string",
- verbose=True,
+ problem_statement=FileProblemStatement(path=str(data_path)),
+ deployment=DockerDeploymentConfig(image="sweagent/swe-agent:latest"),
+ repo=LocalRepoConfig(path=str(local_repo_path)),
)
yield test_env_args
- # Cleanup (after session ends)
- client = docker.from_env()
- # fixme (?): What happens if user changed container_name?
- try:
- assert test_env_args.container_name is not None # mypy
- container = client.containers.get(test_env_args.container_name)
- container.remove(force=True)
- except docker.errors.NotFound:
- # Can happen if this fixture never runs because we only do a partial
- # test run
- pass
shutil.rmtree(local_repo_path)
@@ -110,7 +98,8 @@ def swe_env_context(env_args):
so that we can reuse it.
"""
- env = SWEEnv(env_args)
+ env = SWEEnv.from_config(env_args)
+ env.start()
try:
yield env
finally:
diff --git a/tests/test_env.py b/tests/test_env.py
index e91c1462..d4d3a973 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -1,13 +1,10 @@
from __future__ import annotations
-import dataclasses
from pathlib import Path
from unittest import mock
import pytest
-import yaml
-from sweagent import CONFIG_DIR
from sweagent.environment.hooks.abstract import EnvHook
from .conftest import swe_env_context
@@ -27,18 +24,9 @@ def test_init_swe_env_conservative_clone(test_env_args):
@pytest.mark.slow
-def test_init_swe_env_non_persistent(test_env_args):
- test_env_args = dataclasses.replace(test_env_args, container_name=None)
- with swe_env_context(test_env_args) as env:
- env.reset()
-
-
-def test_execute_setup_script(tmp_path, test_env_args):
+def test_startup_commands(test_env_args):
test_script = "echo 'hello world'"
- script_path = Path(tmp_path / "test_script.sh")
- script_path.write_text(test_script)
- test_env_args = dataclasses.replace(test_env_args, environment_setup=script_path)
+ test_env_args.startup_commands = [test_script]
with swe_env_context(test_env_args) as env:
env.reset()
@@ -51,74 +39,6 @@ def test_read_file(tmp_path, test_env_args):
assert content.splitlines()[-1].strip() == "SWEEnv.read_file"
-def test_execute_environment(tmp_path, test_env_args, capsys):
- test_env = {
- "python": "3.11",
- "packages": "pytest",
- "pip_packages": ["tox"],
- "install": "python -m pip install --upgrade pip && python -m pip install -e .",
- }
- env_config_path = Path(tmp_path / "env_config.yml")
- env_config_path.write_text(yaml.dump(test_env))
- # Make sure we don't use persistent container, else we might have already installed the conda environment
- test_env_args = dataclasses.replace(test_env_args, environment_setup=env_config_path, container_name=None)
- with swe_env_context(test_env_args) as env:
- env.reset()
- out = capsys.readouterr().out
- print(out)
- assert "Cloned python conda environment" not in out
-
-
-def test_execute_environment_default(test_env_args):
- env_config_paths = (CONFIG_DIR / "environment_setup").iterdir()
- assert env_config_paths
- # Make sure we don't use persistent container, else we might have already installed the conda environment
- test_env_args = dataclasses.replace(test_env_args, container_name=None)
- for env_config_path in env_config_paths:
- if env_config_path.name == "django.yaml":
- continue
- if env_config_path.suffix not in [".yaml", ".yml", ".sh"]:
- continue
- print(env_config_path)
- test_env_args = dataclasses.replace(test_env_args, environment_setup=env_config_path)
- with swe_env_context(test_env_args) as env:
- env.reset()
-
-
-def test_execute_environment_clone_python(tmp_path, test_env_args, capsys):
- """This should clone the existing python 3.10 conda environment for speedup"""
- test_env = {
- "python": "3.10",
- "packages": "pytest",
- "pip_packages": ["tox"],
- "install": "python -m pip install --upgrade pip && python -m pip install -e .",
- }
- env_config_path = Path(tmp_path / "env_config.yml")
- env_config_path.write_text(yaml.dump(test_env))
- # Make sure we don't use persistent container, else we might have already installed the conda environment
- test_env_args = dataclasses.replace(test_env_args, environment_setup=env_config_path, container_name=None)
- with swe_env_context(test_env_args) as env:
- env.reset()
- out = capsys.readouterr().out
- print(out)
- assert "Cloned python conda environment" in out
-
-
-def test_open_pr(test_env_args):
- test_env_args = dataclasses.replace(
- test_env_args,
- data_path="https://github.com/swe-agent/test-repo/issues/1",
- repo_path="",
- )
- with swe_env_context(test_env_args) as env:
- env.reset()
- env.open_pr(_dry_run=True, trajectory=[])
-
-
@pytest.mark.slow
def test_env_with_hook(test_env_args):
with swe_env_context(test_env_args) as env:
diff --git a/tests/test_env_utils.py b/tests/test_env_utils.py
index 1e49b1b2..6308903f 100644
--- a/tests/test_env_utils.py
+++ b/tests/test_env_utils.py
@@ -11,14 +11,14 @@ from sweagent.environment.utils import (
get_instances,
)
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,
- is_github_repo_url,
- parse_gh_issue_url,
- parse_gh_repo_url,
-)
from sweagent.utils.config import keys_config
+from sweagent.utils.github import (
+ _get_associated_commit_urls,
+ _is_github_issue_url,
+ _is_github_repo_url,
+ _parse_gh_issue_url,
+ _parse_gh_repo_url,
+)
_TOKEN = {"token": keys_config["GITHUB_TOKEN"]}
@@ -34,32 +34,32 @@ def test_remove_triple_backticks():
def test_is_github_repo_url():
- assert is_github_repo_url("https://github.com/princeton-nlp/SWE-agent")
- assert is_github_repo_url("https://github.com/princeton-nlp/SWE-agent/anything")
- assert is_github_repo_url("github.com/princeton-nlp/SWE-agent/anything")
- assert not is_github_repo_url("")
- assert not is_github_repo_url("/path/to/file")
+ assert _is_github_repo_url("https://github.com/princeton-nlp/SWE-agent")
+ assert _is_github_repo_url("https://github.com/princeton-nlp/SWE-agent/anything")
+ assert _is_github_repo_url("github.com/princeton-nlp/SWE-agent/anything")
+ assert not _is_github_repo_url("")
+ assert not _is_github_repo_url("/path/to/file")
def test_parse_gh_repo_url():
- assert parse_gh_repo_url("https://github.com/princeton-nlp/SWE-agent") == ("princeton-nlp", "SWE-agent")
- assert parse_gh_repo_url("github.com/princeton-nlp/SWE-agent") == ("princeton-nlp", "SWE-agent")
- assert parse_gh_repo_url("github.com/princeton-nlp/SWE-agent/asdfjsdfg") == ("princeton-nlp", "SWE-agent")
- assert parse_gh_repo_url("[email protected]/princeton-nlp/SWE-agent/asdfjsdfg") == ("princeton-nlp", "SWE-agent")
+ assert _parse_gh_repo_url("https://github.com/princeton-nlp/SWE-agent") == ("princeton-nlp", "SWE-agent")
+ assert _parse_gh_repo_url("github.com/princeton-nlp/SWE-agent") == ("princeton-nlp", "SWE-agent")
+ assert _parse_gh_repo_url("github.com/princeton-nlp/SWE-agent/asdfjsdfg") == ("princeton-nlp", "SWE-agent")
+ assert _parse_gh_repo_url("[email protected]/princeton-nlp/SWE-agent/asdfjsdfg") == ("princeton-nlp", "SWE-agent")
def test_parse_gh_repo_url_fails():
with pytest.raises(InvalidGithubURL):
- parse_gh_repo_url("adfkj;lasdfl;kj")
+ _parse_gh_repo_url("adfkj;lasdfl;kj")
with pytest.raises(InvalidGithubURL):
- parse_gh_repo_url("github.com/")
+ _parse_gh_repo_url("github.com/")
with pytest.raises(InvalidGithubURL):
- parse_gh_repo_url("github.com//a/")
+ _parse_gh_repo_url("github.com//a/")
def test_parse_gh_issue_url():
url = "https://github.com/princeton-nlp/SWE-agent/issues/43"
- owner, repo, no = parse_gh_issue_url(url)
+ owner, repo, no = _parse_gh_issue_url(url)
assert owner == "princeton-nlp"
assert repo == "SWE-agent"
assert no == "43"
@@ -67,18 +67,18 @@ def test_parse_gh_issue_url():
def test_parse_gh_issue_url_fails():
with pytest.raises(InvalidGithubURL):
- parse_gh_issue_url("https://github.com/a/b")
+ _parse_gh_issue_url("https://github.com/a/b")
with pytest.raises(InvalidGithubURL):
- parse_gh_issue_url("https://github.com/a/b////")
+ _parse_gh_issue_url("https://github.com/a/b////")
def test_is_from_github_url():
- assert not is_github_issue_url("")
- assert is_github_issue_url("https://github.com/princeton-nlp/SWE-agent/issues/43")
+ assert not _is_github_issue_url("")
+ assert _is_github_issue_url("https://github.com/princeton-nlp/SWE-agent/issues/43")
def test_get_associated_commit_urls():
- assoc = get_associated_commit_urls(
+ assoc = _get_associated_commit_urls(
org="princeton-nlp",
repo="SWE-agent",
issue_number="41",