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]
More conditions to open PR; better commit msg; refactor
Kilian Lieret5fa2d6bd7613
diff --git a/run.py b/run.pyindex 930a9e4f..9ab562f8 100644--- a/run.py+++ b/run.py@@ -4,7 +4,7 @@ import osimport randomimport reimport traceback-from typing import Any, Dict, Tuple+from typing import Any, Dict, Optional, Tupleimport requestsimport yaml@@ -120,7 +120,7 @@ def main(args: ScriptArguments):return_type="info",)save_predictions(traj_dir, instance_id, info)- if should_open_pr(args, info):+ if should_open_pr(args, info, token=env.token):open_pr(env)except KeyboardInterrupt:@@ -134,7 +134,7 @@ def main(args: ScriptArguments):continue-def should_open_pr(args, info: Dict[str, Any]) -> bool:+def should_open_pr(args, info: Dict[str, Any], *, token: str="") -> bool:"""Does opening a PR make sense?"""if not info.get("submission"):logger.info("Not openening PR because submission was made.")@@ -145,28 +145,54 @@ def should_open_pr(args, info: Dict[str, Any]) -> bool:if not is_from_github_url(args.environment.data_path):logger.info("Currently only github is supported to open githubs to. Skipping PR creation.")return False+ issue_info = IssueInfo.from_issue_url(args.environment.data_path, token=token)+ if issue_info.is_closed:+ logger.info("Issue is already closed. Skipping PR creation.")+ return False+ if issue_info.is_assigned:+ logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")+ return Falsereturn Trueclass GitHubApiException(RuntimeError):pass-def get_org_repo_from_gh_url(url: str) -> Tuple[str, str]:- parse_url = url.removeprefix("https://")- assert parse_url.startswith("github.com/")- return tuple(parse_url.split("/")[1:3]) # type: ignore--def get_issue_number_from_gh_url(url: str) -> str:- return url.split("/")[-1]+@dataclass+class IssueInfo:+ title: str+ number: int+ is_closed: bool+ is_assigned: bool+ org: str+ repo: str++ @classmethod+ def from_issue_url(cls, issue_url: str, *, token: str = "") -> "IssueInfo":+ parse_url = issue_url.removeprefix("https://")+ assert parse_url.startswith("github.com/")+ org, repo = parse_url.split("/")[1:3]+ issue_number = issue_url.split("/")[-1]+ issue_data = retrieve_issue_data(org, repo, issue_number, token=token)+ if issue_data is None:+ raise GitHubApiException(f"Failed to retrieve issue data from {issue_url}")+ return cls(+ title=issue_data["title"],+ number=issue_data["number"],+ is_closed=bool(issue_data["closed_at"]),+ is_assigned=bool(issue_data["assignee"]) or bool(issue_data["assignees"]),+ org=org,+ repo=repo,+ )-def retrieve_issue_title(org: str, repo: str, issue_num: str, token: str) -> str:+def retrieve_issue_data(org: str, repo: str, issue_num: str, *, token: str="") -> Optional[Dict[str, Any]]:+ # fixme: Authenticationapi_url = f"https://api.github.com/repos/{org}/{repo}/issues/{issue_num}"response = requests.get(api_url)if not response.ok:- return ""- issue_data = response.json()- return issue_data.get('title', '')-+ logger.warning(f"Failed to retrieve issue data from {api_url}: {response.text}")+ return None+ return response.json()def open_pr(env: SWEEnv) -> None:@@ -175,47 +201,44 @@ def open_pr(env: SWEEnv) -> None:# todo: have better way of handling this# Adding random string suffix to avoid name conflicts if we had a previously failed runbranch_name = "swe-agent-patch-branch-" + str(random.random())[2:10]- print(env.communicate_with_handling(+ issue_url = env.args.data_path+ issue_info = IssueInfo.from_issue_url(issue_url, token=env.token)+ logger.debug(env.communicate_with_handling(input=f"rm model.patch",- error_msg="Failed to clone repository from mirror",+ error_msg="Failed to remove model patch",timeout_duration=10,))- print(env.communicate_with_handling(+ logger.debug(env.communicate_with_handling(input=f"git checkout -b {branch_name}",- error_msg="Failed to clone repository from mirror",+ error_msg="Failed to switch to new branch",timeout_duration=10,))- print(env.communicate_with_handling(+ logger.debug(env.communicate_with_handling(input=f"git add .",- error_msg="Failed to clone repository from mirror",+ error_msg="Failed to add commits",timeout_duration=10,))- print(env.communicate_with_handling(- input=f"git commit -m 'Solved issue'",- error_msg="Failed to clone repository from mirror",+ logger.debug(env.communicate_with_handling(+ input=f"git commit -m 'Fix: {issue_info.title}' -m 'Closes #{issue_info.number}' ",+ error_msg="Failed to commit changes",timeout_duration=10,))- print(env.communicate_with_handling(+ logger.debug(env.communicate_with_handling(input=f"git push origin {branch_name}",error_msg="Failed to clone repository from mirror",timeout_duration=10,))- issue_url = env.args.data_path- issue_number = get_issue_number_from_gh_url(issue_url)- org, repo = get_org_repo_from_gh_url(env.args.data_path)- issue_title = retrieve_issue_title(org, repo, issue_number, env.token)- api_url = f"https://api.github.com/repos/{org}/{repo}/pulls"+ api_url = f"https://api.github.com/repos/{issue_info.org}/{issue_info.repo}/pulls"headers = {'Accept': 'application/vnd.github+json','Authorization': f'Bearer {env.token}','X-GitHub-Api-Version': '2022-11-28'}- # todo: retrieve issue name and add to PR title# todo: add representation of trajectory to PR bodydata = {- 'title': f'AI tool PR to fix: {issue_title}',- 'body': f'This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) to close [#{issue_number}]({issue_url}) ({issue_title}).\n\nCloses #{issue_number}.',+ 'title': f'AI tool PR to fix: {issue_info.title}',+ 'body': f'This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) to close [#{issue_info.number}]({issue_url}) ({issue_info.title}).\n\nCloses #{issue_info.number}.','head': branch_name,'base': 'main'}@@ -225,7 +248,6 @@ def open_pr(env: SWEEnv) -> None:print(api_url)response = requests.post(api_url, headers=headers, json=data)- # Raise exception if the response was not successfulif not response.ok:error_message = f"Error {response.status_code}: {response.text}"if response.status_code == 403: