run.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import json
  2. import logging
  3. import os
  4. import re
  5. import traceback
  6. from typing import Any, Dict, Optional
  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. # Raise unhandled exceptions during the run (useful for debugging)
  59. raise_exceptions: bool = False
  60. @property
  61. def run_name(self):
  62. """Generate a unique name for this run based on the arguments."""
  63. model_name = self.agent.model.model_name.replace(":", "-")
  64. data_stem = get_data_path_name(self.environment.data_path)
  65. config_stem = Path(self.agent.config_file).stem
  66. temp = self.agent.model.temperature
  67. top_p = self.agent.model.top_p
  68. per_instance_cost_limit = self.agent.model.per_instance_cost_limit
  69. install_env = self.environment.install_environment
  70. return (
  71. f"{model_name}__{data_stem}__{config_stem}__t-{temp:.2f}__p-{top_p:.2f}"
  72. + f"__c-{per_instance_cost_limit:.2f}__install-{int(install_env)}"
  73. + (f"__{self.suffix}" if self.suffix else "")
  74. )
  75. def main(args: ScriptArguments):
  76. logger.info(f"📙 Arguments: {args.dumps_yaml()}")
  77. agent = Agent("primary", args.agent)
  78. env = SWEEnv(args.environment)
  79. traj_dir = Path("trajectories") / Path(getuser()) / args.run_name
  80. traj_dir.mkdir(parents=True, exist_ok=True)
  81. save_arguments(traj_dir, args)
  82. for index in range(len(env.data)):
  83. try:
  84. # Reset environment
  85. instance_id = env.data[index]["instance_id"]
  86. assert isinstance(instance_id, str) # mypy
  87. if should_skip(args, traj_dir, instance_id):
  88. continue
  89. logger.info("▶️ Beginning task " + str(index))
  90. observation, info = env.reset(index)
  91. if info is None:
  92. continue
  93. # Get info, patch information
  94. issue = getattr(env, "query", None)
  95. files = []
  96. if "patch" in env.record:
  97. files = "\n".join(
  98. [f"- {x.path}" for x in PatchSet(env.record["patch"]).modified_files]
  99. )
  100. # Get test files, F2P tests information
  101. test_files = []
  102. if "test_patch" in env.record:
  103. test_patch_obj = PatchSet(env.record["test_patch"])
  104. test_files = "\n".join(
  105. [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]
  106. )
  107. tests = ""
  108. if "FAIL_TO_PASS" in env.record:
  109. tests = "\n".join([f"- {x}" for x in env.record["FAIL_TO_PASS"]])
  110. setup_args = {
  111. "issue": issue,
  112. "files": files,
  113. "test_files": test_files,
  114. "tests": tests
  115. }
  116. info, trajectory = agent.run(
  117. setup_args=setup_args,
  118. env=env,
  119. observation=observation,
  120. traj_dir=traj_dir,
  121. return_type="info_trajectory",
  122. )
  123. save_predictions(traj_dir, instance_id, info)
  124. save_patch(traj_dir, instance_id, info)
  125. if args.actions.open_pr and should_open_pr(args, info, token=env.token):
  126. env.open_pr(trajectory=trajectory, push_gh_repo_url=args.actions.push_gh_repo_url)
  127. except KeyboardInterrupt:
  128. logger.info("Exiting InterCode environment...")
  129. env.close()
  130. break
  131. except Exception as e:
  132. traceback.print_exc()
  133. logger.warning(f"❌ Failed on {env.record['instance_id']}: {e}")
  134. if args.raise_exceptions:
  135. raise e
  136. env.reset_container()
  137. continue
  138. def should_open_pr(args: ScriptArguments, info: Dict[str, Any], *, token: str="") -> bool:
  139. """Does opening a PR make sense?"""
  140. if not info.get("submission"):
  141. logger.info("Not openening PR because submission was made.")
  142. return False
  143. if info["exit_status"] != "submitted":
  144. logger.info("Not openening PR because exit status was %s and not submitted.", info["exit_status"])
  145. return False
  146. try:
  147. issue = get_gh_issue_data(args.environment.data_path, token=token)
  148. except InvalidGithubURL:
  149. logger.info("Currently only github is supported to open PRs to. Skipping PR creation.")
  150. return False
  151. if issue.state != "open":
  152. logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
  153. return False
  154. if issue.assignee:
  155. logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
  156. return False
  157. if issue.locked:
  158. logger.info("Issue is locked. Skipping PR creation.")
  159. return False
  160. org, repo, issue_number = parse_gh_issue_url(args.environment.data_path)
  161. associated_commits = get_associated_commit_urls(org, repo, issue_number, token=token)
  162. if associated_commits:
  163. commit_url_strs = ", ".join(associated_commits)
  164. if args.actions.skip_if_commits_reference_issue:
  165. logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
  166. return False
  167. else:
  168. logger.warning(
  169. f"Proceeding with PR creation even though there are already commits "
  170. "({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
  171. "or after verifying that the existing commits do not fix the issue."
  172. )
  173. return True
  174. def save_arguments(traj_dir: Path, args: ScriptArguments) -> None:
  175. """Save the arguments to a yaml file to the run's trajectory directory."""
  176. log_path = traj_dir / "args.yaml"
  177. if log_path.exists():
  178. try:
  179. other_args = args.load_yaml(log_path)
  180. if (args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality
  181. logger.warning("**************************************************")
  182. logger.warning("Found existing args.yaml with different arguments!")
  183. logger.warning("**************************************************")
  184. except Exception as e:
  185. logger.warning(f"Failed to load existing args.yaml: {e}")
  186. with log_path.open("w") as f:
  187. args.dump_yaml(f)
  188. def should_skip(args: ScriptArguments, traj_dir: Path, instance_id: str) -> bool:
  189. """Check if we should skip this instance based on the instance filter and skip_existing flag."""
  190. # Skip instances that don't match the instance filter
  191. if re.match(args.instance_filter, instance_id) is None:
  192. logger.info(f"Instance filter not matched. Skipping instance {instance_id}")
  193. return True
  194. # If flag is set to False, don't skip
  195. if not args.skip_existing:
  196. return False
  197. # Check if there's an existing trajectory for this instance
  198. log_path = traj_dir / (instance_id + ".traj")
  199. if log_path.exists():
  200. with log_path.open("r") as f:
  201. data = json.load(f)
  202. # If the trajectory has no exit status, it's incomplete and we will redo it
  203. exit_status = data["info"].get("exit_status", None)
  204. if exit_status == "early_exit" or exit_status is None:
  205. logger.info(f"Found existing trajectory with no exit status: {log_path}")
  206. logger.info("Removing incomplete trajectory...")
  207. os.remove(log_path)
  208. else:
  209. logger.info(f"⏭️ Skipping existing trajectory: {log_path}")
  210. return True
  211. return False
  212. def save_predictions(traj_dir: Path, instance_id: str, info):
  213. output_file = traj_dir / "all_preds.jsonl"
  214. model_patch = info["submission"] if "submission" in info else None
  215. datum = {
  216. KEY_MODEL: Path(traj_dir).name,
  217. KEY_INSTANCE_ID: instance_id,
  218. KEY_PREDICTION: model_patch,
  219. }
  220. with open(output_file, "a+") as fp:
  221. print(json.dumps(datum), file=fp, flush=True)
  222. logger.info(f"Saved predictions to {output_file}")
  223. def save_patch(traj_dir: Path, instance_id: str, info) -> Optional[Path]:
  224. """Create patch files that can be applied with `git am`.
  225. Returns:
  226. The path to the patch file, if it was saved. Otherwise, returns None.
  227. """
  228. patch_output_dir = traj_dir / "patches"
  229. patch_output_dir.mkdir(exist_ok=True, parents=True)
  230. patch_output_file = patch_output_dir / f"{instance_id}.patch"
  231. if not "submission" in info:
  232. logger.info("No patch to save.")
  233. return
  234. model_patch = info["submission"]
  235. patch_output_file.write_text(model_patch)
  236. logger.info(f"Saved patch to {patch_output_file}")
  237. return patch_output_file
  238. def get_args(args=None) -> ScriptArguments:
  239. """Parse command line arguments and return a ScriptArguments object.
  240. Args:
  241. args: Optional list of arguments to parse. If not provided, uses sys.argv.
  242. """
  243. defaults = ScriptArguments(
  244. suffix="",
  245. environment=EnvironmentArguments(
  246. image_name="sweagent/swe-agent:latest",
  247. data_path="princeton-nlp/SWE-bench_Lite",
  248. split="dev",
  249. verbose=True,
  250. install_environment=True,
  251. ),
  252. skip_existing=True,
  253. agent=AgentArguments(
  254. model=ModelArguments(
  255. model_name="gpt4",
  256. total_cost_limit=0.0,
  257. per_instance_cost_limit=3.0,
  258. temperature=0.0,
  259. top_p=0.95,
  260. ),
  261. config_file="config/default.yaml",
  262. ),
  263. actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
  264. )
  265. # Nicer yaml dumping of multiline strings
  266. def multiline_representer(dumper, data):
  267. """configures yaml for dumping multiline strings
  268. Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
  269. """
  270. if data.count("\n") > 0: # check for multiline string
  271. return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
  272. return dumper.represent_scalar("tag:yaml.org,2002:str", data)
  273. yaml.add_representer(str, multiline_representer)
  274. return parse(ScriptArguments, default=defaults, add_config_path_arg=False, args=args)
  275. if __name__ == "__main__":
  276. args = get_args()
  277. main(args)