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]
Add --problem_statement flag
Kilian Lieretcc992c01366c
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex ae4fd538..07f78aae 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -53,6 +53,8 @@ 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'data_path: strimage_name: strsplit: str = "dev"@@ -67,6 +69,13 @@ 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())class SWEEnv(gym.Env):@@ -107,7 +116,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)+ self.data = get_instances(self.data_path, self.args.base_commit, self.args.split, token=self._github_token, problem_statement=self.args.problem_statement)#: Instance we're currently processing. Gets set in self.reset.self.record = Noneself.logger.info(f"💽 Loaded dataset from {self.data_path}")diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex ed731654..72b5af89 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -1,3 +1,4 @@+import hashlibimport shleximport dockerimport json@@ -17,30 +18,40 @@ from ghapi.all import GhApifrom io import BytesIOfrom pathlib import Pathfrom subprocess import PIPE, STDOUT-from typing import List, Optional, Set, Tuple, Dict+from typing import Any, List, Optional, Set, Tuple, DictLOGGER_NAME = "intercode"START_UP_DELAY = 5TIMEOUT_DURATION = 25GITHUB_ISSUE_URL_PATTERN = re.compile(r'github\.com\/(.*?)\/(.*?)\/issues\/(\d+)')+GITHUB_REPO_URL_PATTERN = re.compile(r'.*[/@]?github\.com\/([^/]+)\/([^/]+)')logger = logging.getLogger(LOGGER_NAME)def get_data_path_name(data_path: str):- # if data_path is a file, return the file stem- # elif it's a github url, return the owner__repo_name+ """ if data_path is a file, return the file stem+ elif it's a github url, return the owner__repo_name+ """match = GITHUB_ISSUE_URL_PATTERN.search(data_path)if match:- owner, repo, issue_number = match.groups()+ owner, repo, _ = match.groups()return f"{owner}__{repo}"return Path(data_path).stem-def is_github_issue_url(data_path: str):+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+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 copy_file_to_container(container, contents, container_path):"""Copies a given string into a Docker container at a specified path.@@ -329,12 +340,12 @@ def parse_gh_issue_url(issue_url: str) -> Tuple[str, str, str]:def parse_gh_repo_url(repo_url: str) -> Tuple[str, str]:"""Return owner, repo from repo url"""- if not repo_url.startswith('http://') and not repo_url.startswith('https://'):- repo_url = 'https://' + repo_url- parts = repo_url.split('/')- owner = parts[3]- repo = parts[4]- return owner, repo+ match = GITHUB_REPO_URL_PATTERN.search(repo_url)+ if not match:+ raise InvalidGithubURL(f"Invalid GitHub issue URL: {repo_url}")+ res = match.groups()+ assert len(res) == 2+ return tuple(res) # type: ignoredef get_gh_issue_data(issue_url: str, *, token: str = ""):@@ -347,12 +358,63 @@ def get_gh_issue_data(issue_url: str, *, token: str = ""):return api.issues.get(owner, repo, issue_number)-def get_instances(file_path: str, base_commit: Optional[str] = None, split: Optional[str] = None, token: Optional[str] = None):++def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: Optional[str] = "") -> str:+ """Return problem statement from github issue"""+ api = GhApi(token=token)+ issue = api.issues.get(owner, repo, issue_number)+ title = issue.title if issue.title else ""+ body = issue.body if issue.body else ""+ 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."+ 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_instances(+ file_path: str,+ base_commit: Optional[str] = None,+ split: Optional[str] = None,+ token: Optional[str] = None,+ *,+ problem_statement: str = "",+ ):"""Getter function for handling json, jsonl files- Arguments:+ Args: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"""@@ -364,25 +426,11 @@ def get_instances(file_path: str, base_commit: Optional[str] = None, split: Optireturn dataset_or_dict# If file_path is a github issue url, fetch the issue and return a single instance- if is_github_issue_url(file_path):- try:- owner, repo, issue_number = parse_gh_issue_url(file_path)- except InvalidGithubURL:- pass- else:- record = dict()- api = GhApi(token=token)- issue = api.issues.get(owner, repo, issue_number)- title = issue.title if issue.title else ""- body = issue.body if issue.body else ""- text = f"{title}\n{body}\n"- record["repo"] = f"{owner}/{repo}"- record["base_commit"] = base_commit if base_commit else get_commit(api, owner, repo, base_commit).sha- record["version"] = record["base_commit"][:7]- record["problem_statement"] = text- record["instance_id"] = f"{owner}__{repo}-i{issue_number}"- return [record,]- elif base_commit is not None:+ 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,]++ if base_commit is not None:raise ValueError("base_commit must be None if data_path is not a github issue url")# If file_path is a file, load the file@@ -391,6 +439,10 @@ def get_instances(file_path: str, base_commit: Optional[str] = None, split: Optiif 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"+ raise ValueError(msg)+# Attempt load from HF datasets as a last resorttry:return load_dataset(file_path, split=split)diff --git a/tests/test_utils.py b/tests/test_utils.pyindex cbc55c61..de4b3c10 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -1,4 +1,5 @@-from sweagent.environment.utils import format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls+import pytest+from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instance_from_github_url, 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"])@@ -12,11 +13,28 @@ def test_remove_triple_backticks():assert 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")++def test_parse_gh_repo_url():- url = "https://github.com/princeton-nlp/SWE-agent"- owner, repo = parse_gh_repo_url(url)- assert owner == "princeton-nlp"- assert repo == "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")+ with pytest.raises(InvalidGithubURL):+ parse_gh_repo_url("github.com/")+ with pytest.raises(InvalidGithubURL):+ parse_gh_repo_url("github.com//a/")def test_parse_gh_issue_url():@@ -27,6 +45,13 @@ def test_parse_gh_issue_url():assert no == "43"+def test_parse_gh_issue_url_fails():+ with pytest.raises(InvalidGithubURL):+ parse_gh_issue_url("https://github.com/a/b")+ with pytest.raises(InvalidGithubURL):+ 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")@@ -38,4 +63,34 @@ def test_get_associated_commit_urls():repo="SWE-agent",issue_number="41")- assert len(assoc) > 0\ No newline at end of file+ assert len(assoc) > 0+++def test_get_instance_from_github_url_github_issue():+ instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/issues/1")+ compare_with = {+ 'repo': 'klieret/swe-agent-test-repo',+ 'base_commit': '3b37cb20ed4851f9239fe7bef239f9cca1195a1e',+ 'version': '3b37cb2',+ '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"]++++def test_get_instance_from_github_url_github_issue_overrides():+ instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/issues/1", problem_statement="asdf", base_commit="1234")+ assert instance["problem_statement"] == "asdf"+ assert instance["base_commit"] == "1234"+++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_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"