run.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import json
  2. import logging
  3. import os
  4. import re
  5. import traceback
  6. from typing import Any, Dict
  7. import yaml
  8. from dataclasses import dataclass
  9. from getpass import getuser
  10. from pathlib import Path
  11. from rich.logging import RichHandler
  12. from simple_parsing import parse
  13. from simple_parsing.helpers import FrozenSerializable, FlattenedAccess
  14. from sweagent import (
  15. Agent,
  16. AgentArguments,
  17. EnvironmentArguments,
  18. ModelArguments,
  19. SWEEnv,
  20. get_data_path_name,
  21. )
  22. from swebench import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION
  23. from unidiff import PatchSet
  24. from sweagent.environment.utils import InvalidGithubURL, get_associated_commit_urls, get_gh_issue_data, parse_gh_issue_url
  25. handler = RichHandler(show_time=False, show_path=False)
  26. handler.setLevel(logging.DEBUG)
  27. logger = logging.getLogger("run_dev")
  28. logger.setLevel(logging.DEBUG)
  29. logger.addHandler(handler)
  30. logger.propagate = False
  31. logging.getLogger("simple_parsing").setLevel(logging.WARNING)
  32. @dataclass(frozen=True)
  33. class ActionsArguments(FlattenedAccess, FrozenSerializable):
  34. """Run real-life actions (opening PRs, etc.) if we can solve the issue."""
  35. open_pr: bool = False # Open a PR with the patch if we can solve the issue
  36. # Skip action if there are already commits claiming to fix the issue. Please only
  37. # set this to False if you are sure the commits are not fixes or if this is your
  38. # own repository!
  39. skip_if_commits_reference_issue: bool = True
  40. # For PRs: If you want to push the branch to a fork (e.g., because you lack
  41. # permissions to push to the main repo), set this to the URL of the fork.
  42. push_gh_repo_url: str = ""
  43. def __post_init__(self):
  44. if not self.skip_if_commits_reference_issue and self.push_gh_repo_url:
  45. raise ValueError(
  46. "Overriding `skip_if_commits_reference_issue` when you are "
  47. "pushing to a fork is not supported. You should manually "
  48. "apply the patch to the forked repository."
  49. )
  50. @dataclass(frozen=True)
  51. class ScriptArguments(FlattenedAccess, FrozenSerializable):
  52. environment: EnvironmentArguments
  53. agent: AgentArguments
  54. actions: ActionsArguments
  55. instance_filter: str = ".*" # Only run instances that completely match this regex
  56. skip_existing: bool = True # Skip instances with existing trajectories
  57. suffix: str = ""
  58. @property
  59. def run_name(self):
  60. """Generate a unique name for this run based on the arguments."""
  61. model_name = args.agent.model.model_name.replace(":", "-")
  62. data_stem = get_data_path_name(args.environment.data_path)
  63. config_stem = Path(args.agent.config_file).stem
  64. temp = args.agent.model.temperature
  65. top_p = args.agent.model.top_p
  66. per_instance_cost_limit = args.agent.model.per_instance_cost_limit
  67. install_env = args.environment.install_environment
  68. return (
  69. f"{model_name}__{data_stem}__{config_stem}__t-{temp:.2f}__p-{top_p:.2f}"
  70. + f"__c-{per_instance_cost_limit:.2f}__install-{int(install_env)}"
  71. + (f"__{self.suffix}" if self.suffix else "")
  72. )
  73. def main(args: ScriptArguments):
  74. logger.info(f"📙 Arguments: {args.dumps_yaml()}")
  75. agent = Agent("primary", args.agent)
  76. env = SWEEnv(args.environment)
  77. traj_dir = Path("trajectories") / Path(getuser()) / args.run_name
  78. os.makedirs(traj_dir, exist_ok=True)
  79. save_arguments(traj_dir, args)
  80. for index in range(len(env.data)):
  81. try:
  82. # Reset environment
  83. instance_id = env.data[index]["instance_id"]
  84. if should_skip(args, traj_dir, instance_id):
  85. continue
  86. logger.info("▶️ Beginning task " + str(index))
  87. observation, info = env.reset(index)
  88. if info is None:
  89. continue
  90. # Get info, patch information
  91. issue = getattr(env, "query", None)
  92. files = []
  93. if "patch" in env.record:
  94. files = "\n".join(
  95. [f"- {x.path}" for x in PatchSet(env.record["patch"]).modified_files]
  96. )
  97. # Get test files, F2P tests information
  98. test_files = []
  99. if "test_patch" in env.record:
  100. test_patch_obj = PatchSet(env.record["test_patch"])
  101. test_files = "\n".join(
  102. [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]
  103. )
  104. tests = ""
  105. if "FAIL_TO_PASS" in env.record:
  106. tests = "\n".join([f"- {x}" for x in env.record["FAIL_TO_PASS"]])
  107. setup_args = {
  108. "issue": issue,
  109. "files": files,
  110. "test_files": test_files,
  111. "tests": tests
  112. }
  113. info, trajectory = agent.run(
  114. setup_args=setup_args,
  115. env=env,
  116. observation=observation,
  117. traj_dir=traj_dir,
  118. return_type="info_trajectory",
  119. )
  120. save_predictions(traj_dir, instance_id, info)
  121. if args.actions.open_pr and should_open_pr(args, info, token=env.token):
  122. env.open_pr(args.actions, info, trajectory)
  123. except KeyboardInterrupt:
  124. logger.info("Exiting InterCode environment...")
  125. env.close()
  126. break
  127. except Exception as e:
  128. traceback.print_exc()
  129. logger.warning(f"❌ Failed on {env.record['instance_id']}: {e}")
  130. env.reset_container()
  131. continue
  132. def should_open_pr(args, info: Dict[str, Any], *, token: str="") -> bool:
  133. """Does opening a PR make sense?"""
  134. if not info.get("submission"):
  135. logger.info("Not openening PR because submission was made.")
  136. return False
  137. if info["exit_status"] != "submitted":
  138. logger.info("Not openening PR because exit status was %s and not submitted.", info["exit_status"])
  139. return False
  140. try:
  141. issue = get_gh_issue_data(args.environment.data_path, token=token)
  142. except InvalidGithubURL:
  143. logger.info("Currently only github is supported to open PRs to. Skipping PR creation.")
  144. return False
  145. if issue.state != "open":
  146. logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
  147. return False
  148. if issue.assignee:
  149. logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
  150. return False
  151. if issue.locked:
  152. logger.info("Issue is locked. Skipping PR creation.")
  153. return False
  154. org, repo, issue_number = parse_gh_issue_url(args.environment.data_path)
  155. associated_commits = get_associated_commit_urls(org, repo, issue_number, token=token)
  156. if associated_commits:
  157. commit_url_strs = ", ".join(associated_commits)
  158. if args.actions.skip_if_commits_reference_issue:
  159. logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
  160. return False
  161. else:
  162. logger.warning(
  163. f"Proceeding with PR creation even though there are already commits "
  164. "({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
  165. "or after verifying that the existing commits do not fix the issue."
  166. )
  167. return True
  168. def save_arguments(traj_dir, args):
  169. """Save the arguments to a yaml file to the run's trajectory directory."""
  170. log_path = traj_dir / "args.yaml"
  171. if log_path.exists():
  172. try:
  173. other_args = args.load_yaml(log_path)
  174. if (args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality
  175. logger.warning("**************************************************")
  176. logger.warning("Found existing args.yaml with different arguments!")
  177. logger.warning("**************************************************")
  178. except Exception as e:
  179. logger.warning(f"Failed to load existing args.yaml: {e}")
  180. with log_path.open("w") as f:
  181. args.dump_yaml(f)
  182. def should_skip(args, traj_dir, instance_id):
  183. """Check if we should skip this instance based on the instance filter and skip_existing flag."""
  184. # Skip instances that don't match the instance filter
  185. if re.match(args.instance_filter, instance_id) is None:
  186. logger.info(f"Instance filter not matched. Skipping instance {instance_id}")
  187. return True
  188. # If flag is set to False, don't skip
  189. if not args.skip_existing:
  190. return False
  191. # Check if there's an existing trajectory for this instance
  192. log_path = traj_dir / (instance_id + ".traj")
  193. if log_path.exists():
  194. with log_path.open("r") as f:
  195. data = json.load(f)
  196. # If the trajectory has no exit status, it's incomplete and we will redo it
  197. exit_status = data["info"].get("exit_status", None)
  198. if exit_status == "early_exit" or exit_status is None:
  199. logger.info(f"Found existing trajectory with no exit status: {log_path}")
  200. logger.info("Removing incomplete trajectory...")
  201. os.remove(log_path)
  202. else:
  203. logger.info(f"⏭️ Skipping existing trajectory: {log_path}")
  204. return True
  205. return False
  206. def save_predictions(traj_dir, instance_id, info):
  207. output_file = Path(traj_dir) / "all_preds.jsonl"
  208. model_patch = info["submission"] if "submission" in info else None
  209. datum = {
  210. KEY_MODEL: Path(traj_dir).name,
  211. KEY_INSTANCE_ID: instance_id,
  212. KEY_PREDICTION: model_patch,
  213. }
  214. with open(output_file, "a+") as fp:
  215. print(json.dumps(datum), file=fp, flush=True)
  216. logger.info(f"Saved predictions to {output_file}")
  217. if __name__ == "__main__":
  218. defaults = ScriptArguments(
  219. suffix="",
  220. environment=EnvironmentArguments(
  221. image_name="swe-agent",
  222. data_path="princeton-nlp/SWE-bench_Lite",
  223. split="dev",
  224. verbose=True,
  225. install_environment=True,
  226. ),
  227. skip_existing=True,
  228. agent=AgentArguments(
  229. model=ModelArguments(
  230. model_name="gpt4",
  231. total_cost_limit=0.0,
  232. per_instance_cost_limit=2.0,
  233. temperature=0.2,
  234. top_p=0.95,
  235. ),
  236. config_file="config/default.yaml",
  237. ),
  238. actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
  239. )
  240. # Nicer yaml dumping of multiline strings
  241. def multiline_representer(dumper, data):
  242. """configures yaml for dumping multiline strings
  243. Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
  244. """
  245. if data.count("\n") > 0: # check for multiline string
  246. return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
  247. return dumper.represent_scalar("tag:yaml.org,2002:str", data)
  248. yaml.add_representer(str, multiline_representer)
  249. args = parse(ScriptArguments, default=defaults, add_config_path_arg=False)
  250. main(args)