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]
Use --data_path for local problem stmts and --repo_path for local repos
Kilian Lieret9186e535bf38
diff --git a/run.py b/run.pyindex b66977fd..f5bb6844 100644--- a/run.py+++ b/run.py@@ -39,7 +39,10 @@ logging.getLogger("simple_parsing").setLevel(logging.WARNING)@dataclass(frozen=True)class ActionsArguments(FlattenedAccess, FrozenSerializable):"""Run real-life actions (opening PRs, etc.) if we can solve the issue."""- open_pr: bool = False # Open a PR with the patch 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!@@ -47,8 +50,6 @@ class ActionsArguments(FlattenedAccess, FrozenSerializable):# For PRs: If you want to push the branch to a fork (e.g., because you lack# permissions to push to the main repo), set this to the URL of the fork.push_gh_repo_url: str = ""- # When working with local repository- apply_patch_locally: bool = Truedef __post_init__(self):if not self.skip_if_commits_reference_issue and self.push_gh_repo_url:diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 7bb32768..0b31658d 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -54,8 +54,9 @@ logger.propagate = Falseclass EnvironmentArguments(FrozenSerializable):"""Configure data sources and setup instructions for th environment in which we solve the tasks."""- # Path to a data file or directory, or github issue url, or github repo url- # with specified 'problem_statement'+ # 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.data_path: strimage_name: strsplit: str = "dev"@@ -70,13 +71,8 @@ class EnvironmentArguments(FrozenSerializable):# or a shell script (with sh extension).# See https://github.com/princeton-nlp/SWE-agent/pull/153 for more informationenvironment_setup: Optional[str] = None- # Problem statement (takes the place of an issue text). Only used when data_path is a GitHub URL.- # Can be path to file.- problem_statement: str = ""-- def __post_init__(self):- if self.problem_statement and len(self.problem_statement) < 200 and Path(self.problem_statement).is_file():- object.__setattr__(self, "problem_statement", Path(self.problem_statement).read_text())+ # Only used when running on single issue. Path to local repository or github repository.+ repo_path: str = ""class SWEEnv(gym.Env):@@ -94,7 +90,7 @@ class SWEEnv(gym.Env):self.logger = loggerself.persistent = args.container_name is not Noneself.returncode = None- self.is_from_github_url = is_github_issue_url(args.data_path)+ self.problem_statement_from_github_issue = is_github_issue_url(args.data_path)if not self.args.verbose:self.logger.disabled = True@@ -117,7 +113,7 @@ class SWEEnv(gym.Env):# Load Task Instancesself.data_path = self.args.data_path- self.data = get_instances(self.data_path, self.args.base_commit, self.args.split, token=self._github_token, problem_statement=self.args.problem_statement)+ 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 = Noneself.logger.info(f"💽 Loaded dataset from {self.data_path}")@@ -135,10 +131,7 @@ class SWEEnv(gym.Env):def _repo_name(self) -> str:"""Name of the local copy of the repository"""assert self.record is not None- if not self.record["repo"].startswith("local://"):- return self.record["repo"].replace("/", "__")- else:- return self.record["repo"].removeprefix("local://").replace("/", "__")+ return self.record["repo"].replace("/", "__")def _copy_repo(self) -> str:"""Clone/copy repository/codebase in container@@ -146,17 +139,18 @@ class SWEEnv(gym.Env):folder name of clone"""assert self.record is not None # mypy- if self.record["repo"].startswith("local://"):+ if self.record["repo_type"] == "local":copy_anything_to_container(self.container_obj, self.record["repo"].removeprefix("local://"), "/"+self._repo_name)self.communicate_with_handling(input=f"chown -R root:root {self._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}@"- if not self.args.no_mirror and not self.is_from_github_url:+ if not self.args.no_mirror and not self.problem_statement_from_github_issue:self.logger.info(f"{self._repo_name} not found in container, cloning...")self.communicate_with_handling(input=f"git clone https://{token_prefix}github.com/swe-bench/{self._repo_name}.git",@@ -597,7 +591,7 @@ class SWEEnv(gym.Env):Creates conda environment and installs third party dependencies to allow code execution"""assert self.record is not None # mypy- if (self.is_from_github_url or self.record["repo"].startswith("local://")) and self.args.environment_setup is None:+ if (self.problem_statement_from_github_issue or self.record["repo_type"] == "local") and self.args.environment_setup is None:logger.warning(("install_environment is set to True, but the data path is a GitHub URL ""without an environment config file (environment_config key/flag). "diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex 3c1c0af2..60f11447 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -12,16 +12,18 @@ import tarfileimport tempfileimport timeimport traceback+import dataclassesfrom datasets import load_dataset, load_from_diskfrom ghapi.all import GhApifrom io import BytesIOfrom pathlib import Pathfrom subprocess import PIPE, STDOUT-from typing import Any, List, Optional, Set, Tuple, Dict, Union+from typing import Any, List, Optional, Set, Tuple, Dictfrom git import InvalidGitRepositoryError, Repo+LOGGER_NAME = "intercode"START_UP_DELAY = 5TIMEOUT_DURATION = 25@@ -388,65 +390,92 @@ def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number:return f"{title}\n{body}\n"-def get_instance_from_github_url(url: str, *, base_commit: Optional[str]=None, problem_statement: str="", token: Optional[str] = None) -> dict[str, Any]:- """Get instance from a github URL (either issue or repo)"""- try:- owner, repo, issue_number = parse_gh_issue_url(url)- except InvalidGithubURL:- owner, repo = parse_gh_repo_url(url)- issue_number = None- record = dict()- record["repo"] = f"{owner}/{repo}"- if base_commit:- record["base_commit"] = base_commit- else:- api = GhApi(token=token)- record["base_commit"] = get_commit(api, owner, repo, base_commit).sha- record["version"] = record["base_commit"][:7]- if not problem_statement:- if not issue_number:- msg = "Problem statement must be provided if data_path is a github repo url without an issue number."+class Instance:+ repo: str+ base_commit: str+ version: str+ problem_statement: str+ instance_id: str+ repo_type: str = "github"++ def _validate(self):+ if self.repo_type not in {"github", "local"}:+ raise ValueError(f"Invalid repo type: {self.repo_type=}")+ if self.repo_type == "github" and self.repo.count("/") != 1:+ raise ValueError(f"Invalid repo format for {self.repo_type=}: {self.repo=}")++ def __post_init__(self):+ self._validate()+++class InstanceBuilder:+ def __init__(self, token: Optional[str] = None):+ """This helper class is used to build the data for an instance object,+ retrieving problem statements from github issues or local files and setting+ repo paths from github urls or local paths.+ """+ # Args that will be passed to the Instance constructor+ self.args = {}+ self.token = token+ self._instance_id_problem_suffix = ""++ def set_problem_statement_from_gh_issue(self, issue_url: str):+ owner, repo, issue_number = parse_gh_issue_url(issue_url)+ self.args["problem_statement"] = get_problem_statement_from_github_issue(owner, repo, issue_number, token=self.token)+ self.args["instance_id"] = f"{owner}__{repo}-i{issue_number}"++ def set_problem_statement_from_file(self, file_path: str):+ self.args["problem_statement"] = Path(file_path).read_text()+ self.args["instance_id"] = hashlib.sha256(self.args["problem_statement"].encode()).hexdigest()[:6]++ def set_problem_statement(self, data_path: str ):+ """Get problem statement for a single instance from a github issue url or a+ path to a markdown or text file.+ """+ if is_github_issue_url(data_path):+ self.set_problem_statement_from_gh_issue(data_path)+ elif Path(data_path).is_file():+ self.set_problem_statement_from_file(data_path)+ else:+ msg = f"Not sure how to get problem statement from {data_path=}."raise ValueError(msg)- record["problem_statement"] = get_problem_statement_from_github_issue(owner, repo, issue_number, token=token)- else:- record["problem_statement"] = problem_statement- if issue_number is not None:- record["instance_id"] = f"{owner}__{repo}-i{issue_number}"- else:- # Get a unique ID by hashing the problem statement- ps_hash = hashlib.sha256(problem_statement.encode()).hexdigest()[:6]- record["instance_id"] = f"{owner}__{repo}-{ps_hash}"- return record---def get_instance_from_local_dir(data_path: Union[str, os.PathLike], *, problem_statement: str) -> Dict[str, Any]:- """Get task instance from a local directory"""- if not problem_statement:- msg = "Problem statement must be provided if data_path is a local directory."- raise ValueError(msg)- data_path = Path(data_path).resolve()- if not data_path.is_dir():- msg = "data_path must be a directory"- raise ValueError(msg)- try:- repo = Repo(data_path, search_parent_directories=True)- except InvalidGitRepositoryError as e:- msg = "data_path must be a git repository"- raise ValueError(msg) from e- # The instance id is made up of the hash of the parent directory, the sanitized directory name- # and the hash of the problem statement- iid = hashlib.sha256(str(data_path.parent).encode()).hexdigest()[:6]- iid += "__"+ "".join(x for x in data_path.stem if x.isalnum())- iid += "-" + hashlib.sha256(problem_statement.encode()).hexdigest()[:6]- base_commit = repo.head.object.hexsha- return {- "repo": f"local://{data_path}",- "base_commit": base_commit,- "version": base_commit[:7],- "problem_statement": problem_statement,- "instance_id": iid,- }-++ def set_repo_info_from_gh_url(self, url: str, base_commit: Optional[str] = None):+ owner, repo = parse_gh_repo_url(url)+ self.args["repo"] = f"{owner}/{repo}"+ self.args["repo_type"] = "github"+ if base_commit:+ self.args["base_commit"] = base_commit+ else:+ api = GhApi(token=self.token)+ self.args["base_commit"] = get_commit(api, owner, repo, base_commit).sha+ self.args["version"] = self.args["base_commit"][:7]++ def set_repo_info_from_local_path(self, path: str, base_commit: Optional[str] = None):+ self.args["repo"] = str(Path(path).resolve())+ self.args["repo_type"] = "local"+ if base_commit:+ self.args["base_commit"] = base_commit+ else:+ try:+ repo = Repo(path, search_parent_directories=True)+ except InvalidGitRepositoryError as e:+ msg = f"Could not find git repository at {path=}."+ raise ValueError(msg) from e+ self.args["base_commit"] = repo.head.object.hexsha+ self.args["version"] = self.args["base_commit"][:7]++ def set_repo_info(self, repo: str, base_commit: Optional[str] = None):+ if is_github_repo_url(repo):+ self.set_repo_info_from_gh_url(repo, base_commit=base_commit)+ elif Path(repo).is_dir():+ self.set_repo_info_from_local_path(repo, base_commit=base_commit)+ else:+ raise ValueError(f"Could not determine repo path from {repo=}.")++ def build(self) -> Instance: return Instance(**self.args)+def get_instances(file_path: str,@@ -454,18 +483,16 @@ def get_instances(split: Optional[str] = None,token: Optional[str] = None,*,- problem_statement: str = "",+ repo_path: str = "",) -> List[Dict[str, Any]]:"""Getter function for handling json, jsonl filesArgs:file_path (str): Path to file- problem_statement: Problem statement when running on github repository URL- or local path. If running on github issue, will replace issue content.Returns:- List of instances+ List of instances as dictionaries"""# If file_path is a directory, attempt load from disk@@ -478,17 +505,19 @@ def get_instances(except FileNotFoundError:# Raised by load_from_disk if the directory is not a dataset directorypass-- if Path(file_path).is_dir():- if base_commit is not None:- msg = "base_commit must be None if data_path is a local directory"- raise ValueError(msg)- return [get_instance_from_local_dir(file_path, problem_statement=problem_statement)]- # If file_path is a github issue url, fetch the issue and return a single instance- if is_github_repo_url(file_path):- record = get_instance_from_github_url(file_path, base_commit=base_commit, problem_statement=problem_statement, token=token)- return [record,]+ # The next if statement is very brittle logic to determine if we're processing a single instance+ if (Path(file_path).is_file() and Path(file_path).suffix in ['.md', '.txt']) or is_github_issue_url(file_path):+ ib = InstanceBuilder(token=token)+ ib.set_problem_statement(file_path)+ if repo_path:+ ib.set_repo_info(repo_path, base_commit=base_commit)+ elif is_github_repo_url(file_path):+ ib.set_repo_info_from_gh_url(file_path)+ else:+ raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")++ return [dataclasses.asdict(ib.build())]if base_commit is not None:raise ValueError("base_commit must be None if data_path is not a github issue url")@@ -499,8 +528,8 @@ def get_instances(if file_path.endswith(".jsonl"):return [json.loads(x) for x in open(file_path, 'r').readlines()]- if problem_statement:- msg = "problem_statement must be empty if data_path is not a github url or local repo url"+ if repo_path:+ msg = "repo_path must be empty if data_path is not a github url or local repo url"raise ValueError(msg)# Attempt load from HF datasets as a last resortdiff --git a/tests/test_replay.py b/tests/test_replay.pyindex 0f231c13..0db63c22 100644--- a/tests/test_replay.py+++ b/tests/test_replay.py@@ -39,11 +39,11 @@ def test_model_replay_local_repo(tmp_path):run_cmd = ["--traj_path","tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj",- "--data_path",+ "--repo_path",str(local_repo_path),"--config_file","config/default_from_url.yaml",- "--problem_statement",+ "--data_path",str(problem_statement_path),]args, remaing_args = get_args(run_cmd)diff --git a/tests/test_utils.py b/tests/test_utils.pyindex cd282c5d..8b59880e 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -1,5 +1,7 @@+import hashlib+import subprocessimport pytest-from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instance_from_github_url, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls+from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urlsdef test_format_trajectory_markdown(test_trajectory):formatted = format_trajectory_markdown(test_trajectory["trajectory"])@@ -66,11 +68,12 @@ def test_get_associated_commit_urls():assert len(assoc) > 0-def test_get_instance_from_github_url_github_issue():+def test_get_instance_gh_issue():instance = get_instances("https://github.com/klieret/swe-agent-test-repo/issues/1")[0]compare_with = {'repo': 'klieret/swe-agent-test-repo',- 'instance_id': 'klieret__swe-agent-test-repo-i1'+ 'instance_id': 'klieret__swe-agent-test-repo-i1',+ "repo_type": "github",}for key in compare_with:assert instance[key] == compare_with[key]@@ -79,18 +82,61 @@ def test_get_instance_from_github_url_github_issue():assert instance["version"]+def clone_repo(tmp_path, repo_url):+ cmd = ["git", "clone", repo_url, ]+ subprocess.run(cmd, check=True, cwd=tmp_path)-def test_get_instance_from_github_url_github_issue_overrides():- instance = get_instances("https://github.com/klieret/swe-agent-test-repo/issues/1", problem_statement="asdf", base_commit="1234")[0]- assert instance["problem_statement"] == "asdf"- assert instance["base_commit"] == "1234"+def test_get_instance_gh_issue_local_repo(tmp_path):+ clone_repo(tmp_path, "https://github.com/klieret/swe-agent-test-repo/")+ instance = get_instances(+ file_path="https://github.com/klieret/swe-agent-test-repo/issues/1",+ repo_path=str(tmp_path / "swe-agent-test-repo"),+ )[0]+ compare_with = {+ 'repo': str(tmp_path.resolve() / "swe-agent-test-repo"),+ "repo_type": "local",+ 'instance_id': 'klieret__swe-agent-test-repo-i1'+ }+ for key in compare_with:+ assert instance[key] == compare_with[key]+ assert "SyntaxError" in instance["problem_statement"]+ assert len(instance["base_commit"]) > 10+ assert instance["version"]-def test_get_instance_from_github_url_github_repo_missing_problem():- with pytest.raises(ValueError, match=".*Problem statement.*"):- get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/")+def test_get_instance_local_issue_local_repo(tmp_path):+ clone_repo(tmp_path, "https://github.com/klieret/swe-agent-test-repo/")+ issue_path = tmp_path / "issue.txt"+ issue_path.write_text("asdf")+ instance = get_instances(+ file_path=str(issue_path),+ repo_path=str(tmp_path / "swe-agent-test-repo"),+ )[0]+ compare_with = {+ 'repo': str(tmp_path.resolve() / "swe-agent-test-repo"),+ "repo_type": "local",+ 'instance_id': hashlib.sha256("asdf".encode()).hexdigest()[:6],+ "problem_statement": "asdf",+ }+ for key in compare_with:+ assert instance[key] == compare_with[key]+ assert len(instance["base_commit"]) > 10+ assert instance["version"]-def test_get_instance_from_github_url_github_repo():- instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/", problem_statement="asdf")- assert instance["problem_statement"] == "asdf"++def test_get_instance_gh_issue_gh_repo(tmp_path):+ instance = get_instances(+ file_path="https://github.com/klieret/swe-agent-test-repo/issues/1",+ repo_path="https://github.com/princeton-nlp/SWE-agent",+ )[0]+ compare_with = {+ 'repo': "princeton-nlp/SWE-agent",+ "repo_type": "github",+ 'instance_id': "klieret__swe-agent-test-repo-i1",+ }+ for key in compare_with:+ assert instance[key] == compare_with[key]+ assert "SyntaxError" in instance["problem_statement"]+ assert len(instance["base_commit"]) > 10+ assert instance["version"]