run.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. try:
  2. import rich
  3. except ModuleNotFoundError as e:
  4. raise RuntimeError(
  5. "You probably either forgot to install the dependencies "
  6. "or forgot to activate your conda or virtual environment."
  7. ) from e
  8. import json
  9. import logging
  10. import os
  11. import re
  12. import subprocess
  13. import traceback
  14. from typing import Any, Dict, List, Optional
  15. import rich.console
  16. import rich.markdown
  17. import rich.panel
  18. import rich.markdown
  19. try:
  20. from rich_argparse import RichHelpFormatter
  21. except ImportError:
  22. msg = (
  23. "Please install the rich_argparse package with `pip install rich_argparse`."
  24. )
  25. raise ImportError(msg)
  26. import yaml
  27. from rich.markdown import Markdown
  28. from dataclasses import dataclass
  29. from getpass import getuser
  30. from pathlib import Path
  31. from rich.logging import RichHandler
  32. from simple_parsing import parse
  33. from simple_parsing.helpers.serialization.serializable import FrozenSerializable
  34. from simple_parsing.helpers.flatten import FlattenedAccess
  35. from sweagent import (
  36. Agent,
  37. AgentArguments,
  38. EnvironmentArguments,
  39. ModelArguments,
  40. SWEEnv,
  41. get_data_path_name,
  42. )
  43. from swebench import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION
  44. from unidiff import PatchSet
  45. from sweagent.environment.utils import InvalidGithubURL, get_associated_commit_urls, get_gh_issue_data, parse_gh_issue_url
  46. __doc__: str = """ Run inference. Usage examples:
  47. ```bash
  48. # Run over a github issue:
  49. python run.py --model_name "gpt4" --data_path "https://github.com/pvlib/pvlib-python/issues/1603" --config_file "config/default_from_url.yaml"
  50. # Apply a patch in a local repository to an issue specified as Markdown file and run a custom installer script in the container
  51. python run.py --model_name "gpt4" --data_path "/path/to/my_issue.md" --repo_path "/path/to/my/local/repo" --environment_setup "/path/to/setup.sh" --config_file "config/default_from_url.yaml" --apply_patch_locally
  52. ```
  53. """
  54. handler = RichHandler(show_time=False, show_path=False)
  55. handler.setLevel(logging.DEBUG)
  56. logger = logging.getLogger("run_dev")
  57. logger.setLevel(logging.DEBUG)
  58. logger.addHandler(handler)
  59. logger.propagate = False
  60. logging.getLogger("simple_parsing").setLevel(logging.WARNING)
  61. @dataclass(frozen=True)
  62. class ActionsArguments(FlattenedAccess, FrozenSerializable):
  63. """Run real-life actions (opening PRs, etc.) if we can solve the issue."""
  64. # Open a PR with the patch if we can solve the issue
  65. open_pr: bool = False
  66. # When working with local repository: Apply patch
  67. apply_patch_locally: bool = False
  68. # Option to be used with open_pr: Skip action if there are already commits claiming
  69. # to fix the issue. Please only set this to False if you are sure the commits are
  70. # not fixes or if this is your own repository!
  71. skip_if_commits_reference_issue: bool = True
  72. # OBSOLETE. Do not use, will raise error. Please specify --repo_path instead.
  73. push_gh_repo_url: str = ""
  74. def __post_init__(self):
  75. if self.push_gh_repo_url:
  76. raise ValueError("push_gh_repo_url is obsolete. Use repo_path instead")
  77. @dataclass(frozen=True)
  78. class ScriptArguments(FlattenedAccess, FrozenSerializable):
  79. """Configure the control flow of the run.py script"""
  80. environment: EnvironmentArguments
  81. agent: AgentArguments
  82. actions: ActionsArguments
  83. instance_filter: str = ".*" # Only run instances that completely match this regex
  84. skip_existing: bool = True # Skip instances with existing trajectories
  85. suffix: str = ""
  86. # Raise unhandled exceptions during the run (useful for debugging)
  87. raise_exceptions: bool = False
  88. @property
  89. def run_name(self):
  90. """Generate a unique name for this run based on the arguments."""
  91. model_name = self.agent.model.model_name.replace(":", "-")
  92. data_stem = get_data_path_name(self.environment.data_path)
  93. assert self.agent.config_file is not None # mypy
  94. config_stem = Path(self.agent.config_file).stem
  95. temp = self.agent.model.temperature
  96. top_p = self.agent.model.top_p
  97. per_instance_cost_limit = self.agent.model.per_instance_cost_limit
  98. install_env = self.environment.install_environment
  99. return (
  100. f"{model_name}__{data_stem}__{config_stem}__t-{temp:.2f}__p-{top_p:.2f}"
  101. + f"__c-{per_instance_cost_limit:.2f}__install-{int(install_env)}"
  102. + (f"__{self.suffix}" if self.suffix else "")
  103. )
  104. class _ContinueLoop(Exception):
  105. """Used for internal control flow"""
  106. ...
  107. class MainHook:
  108. """Hook structure for the web server or other addons to interface with"""
  109. @staticmethod
  110. def _is_promising_patch(info: Dict[str, Any]) -> bool:
  111. """Do we actually believe that the patch will solve the issue?
  112. Or are we just submitting the last patch we generated before hitting an error?
  113. """
  114. # The exit status can also be `submitted (exit_cost)` etc.
  115. return info["exit_status"] == "submitted" and info.get("submission") is not None
  116. def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
  117. """Called when hook is initialized"""
  118. ...
  119. def on_start(self):
  120. """Called at the beginning of `Main.main`"""
  121. ...
  122. def on_end(self):
  123. """Called at the end of `Main.main`"""
  124. ...
  125. def on_instance_start(self, *, index: int, instance: Dict[str, Any]):
  126. """Called at the beginning of each instance loop in `Main.run`"""
  127. ...
  128. def on_instance_skipped(self, ):
  129. """Called when an instance is skipped in `Main.run`"""
  130. ...
  131. def on_instance_completed(self, *, info, trajectory):
  132. """Called when an instance is completed in `Main.run`"""
  133. ...
  134. class SaveApplyPatchHook(MainHook):
  135. """This hook saves patches to a separate directory and optionally applies them to a local repository."""
  136. def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
  137. self._traj_dir = traj_dir
  138. self._apply_patch_locally = args.actions.apply_patch_locally
  139. self._instance = None
  140. def on_instance_start(self, *, index: int, instance: Dict[str, Any]):
  141. self._instance = instance
  142. def on_instance_completed(self, *, info, trajectory):
  143. assert self._instance is not None # mypy
  144. instance_id = self._instance["instance_id"]
  145. patch_path = self._save_patch(instance_id, info)
  146. if patch_path:
  147. if not self._apply_patch_locally:
  148. return
  149. if not self._is_promising_patch(info):
  150. return
  151. assert self._instance # mypy
  152. if not self._instance["repo_type"] == "local":
  153. return
  154. local_dir = Path(self._instance["repo"])
  155. self._apply_patch(patch_path, local_dir)
  156. @staticmethod
  157. def _print_patch_message(patch_output_file: Path):
  158. console = rich.console.Console()
  159. msg = [
  160. "SWE-agent has produced a patch that it believes will solve the issue you submitted!",
  161. "Use the code snippet below to inspect or apply it!"
  162. ]
  163. panel = rich.panel.Panel.fit(
  164. "\n".join(msg),
  165. title="🎉 Submission successful 🎉",
  166. )
  167. console.print(panel)
  168. content = [
  169. "```bash",
  170. f"# The patch has been saved to your local filesystem at:",
  171. f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
  172. "# Inspect it:",
  173. "cat \"${PATCH_FILE_PATH}\"",
  174. "# Apply it to a local repository:",
  175. f"cd <your local repo root>",
  176. "git apply \"${PATCH_FILE_PATH}\"",
  177. "```",
  178. ]
  179. console.print(rich.markdown.Markdown("\n".join(content)))
  180. def _save_patch(self, instance_id: str, info) -> Optional[Path]:
  181. """Create patch files that can be applied with `git am`.
  182. Returns:
  183. The path to the patch file, if it was saved. Otherwise, returns None.
  184. """
  185. patch_output_dir = self._traj_dir / "patches"
  186. patch_output_dir.mkdir(exist_ok=True, parents=True)
  187. patch_output_file = patch_output_dir / f"{instance_id}.patch"
  188. if not info.get("submission"):
  189. logger.info("No patch to save.")
  190. return
  191. model_patch = info["submission"]
  192. patch_output_file.write_text(model_patch)
  193. if self._is_promising_patch(info):
  194. # Only print big congratulations if we actually believe
  195. # the patch will solve the issue
  196. self._print_patch_message(patch_output_file)
  197. return patch_output_file
  198. def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:
  199. """Apply a patch to a local directory."""
  200. assert local_dir.is_dir()
  201. assert patch_file.exists()
  202. # The resolve() is important, because we're gonna run the cmd
  203. # somewhere else
  204. cmd = ["git", "apply", str(patch_file.resolve())]
  205. try:
  206. subprocess.run(cmd, cwd=local_dir, check=True)
  207. except subprocess.CalledProcessError as e:
  208. logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")
  209. return
  210. logger.info(f"Applied patch {patch_file} to {local_dir}")
  211. class OpenPRHook(MainHook):
  212. """This hook opens a PR if the issue is solved and the user has enabled the option."""
  213. def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
  214. self._env = env
  215. self._token: str = env._github_token
  216. self._data_path = args.environment.data_path
  217. self._open_pr = args.actions.open_pr
  218. self._skip_if_commits_reference_issue = args.actions.skip_if_commits_reference_issue
  219. def on_instance_completed(self, *, info, trajectory):
  220. if self._open_pr and self.should_open_pr(info):
  221. self._env.open_pr(trajectory=trajectory)
  222. def should_open_pr(self, info: Dict[str, Any]) -> bool:
  223. """Does opening a PR make sense?"""
  224. if not info.get("submission"):
  225. logger.info("Not opening PR because no submission was made.")
  226. return False
  227. if info["exit_status"] != "submitted":
  228. logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])
  229. return False
  230. try:
  231. issue = get_gh_issue_data(self._data_path, token=self._token)
  232. except InvalidGithubURL:
  233. logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
  234. return False
  235. if issue.state != "open":
  236. logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
  237. return False
  238. if issue.assignee:
  239. logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
  240. return False
  241. if issue.locked:
  242. logger.info("Issue is locked. Skipping PR creation.")
  243. return False
  244. org, repo, issue_number = parse_gh_issue_url(self._data_path)
  245. associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)
  246. if associated_commits:
  247. commit_url_strs = ", ".join(associated_commits)
  248. if self._skip_if_commits_reference_issue:
  249. logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
  250. return False
  251. else:
  252. logger.warning(
  253. "Proceeding with PR creation even though there are already commits "
  254. f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
  255. "or after verifying that the existing commits do not fix the issue."
  256. )
  257. return True
  258. class Main:
  259. def __init__(self, args: ScriptArguments):
  260. logger.info(f"📙 Arguments: {args.dumps_yaml()}")
  261. self.args = args
  262. self.agent = Agent("primary", args.agent)
  263. self.env = SWEEnv(args.environment)
  264. self.traj_dir = Path("trajectories") / Path(getuser()) / args.run_name
  265. self.traj_dir.mkdir(parents=True, exist_ok=True)
  266. self._save_arguments()
  267. default_hooks = [
  268. SaveApplyPatchHook(),
  269. OpenPRHook(),
  270. ]
  271. self.hooks: List[MainHook] = []
  272. for hook in default_hooks:
  273. self.add_hook(hook)
  274. def add_hook(self, hook: MainHook):
  275. hook.on_init(args=self.args, agent=self.agent, env=self.env, traj_dir=self.traj_dir)
  276. self.hooks.append(hook)
  277. def run(self, index):
  278. # Reset environment
  279. instance_id = self.env.data[index]["instance_id"]
  280. for hook in self.hooks:
  281. hook.on_instance_start(index=index, instance=self.env.data[index])
  282. assert isinstance(instance_id, str) # mypy
  283. if self.should_skip(instance_id):
  284. for hook in self.hooks:
  285. hook.on_instance_skipped()
  286. raise _ContinueLoop
  287. logger.info("▶️ Beginning task " + str(index))
  288. observation, info = self.env.reset(index)
  289. if info is None:
  290. raise _ContinueLoop
  291. # Get info, patch information
  292. issue = getattr(self.env, "query", None)
  293. files = []
  294. assert self.env.record is not None # mypy
  295. if "patch" in self.env.record:
  296. files = "\n".join(
  297. [f"- {x.path}" for x in PatchSet(self.env.record["patch"]).modified_files]
  298. )
  299. # Get test files, F2P tests information
  300. test_files = []
  301. if "test_patch" in self.env.record:
  302. test_patch_obj = PatchSet(self.env.record["test_patch"])
  303. test_files = "\n".join(
  304. [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]
  305. )
  306. tests = ""
  307. if "FAIL_endTO_PASS" in self.env.record:
  308. tests = "\n".join([f"- {x}" for x in self.env.record["FAIL_TO_PASS"]])
  309. setup_args = {
  310. "issue": issue,
  311. "files": files,
  312. "test_files": test_files,
  313. "tests": tests
  314. }
  315. info, trajectory = self.agent.run(
  316. setup_args=setup_args,
  317. env=self.env,
  318. observation=observation,
  319. traj_dir=self.traj_dir,
  320. return_type="info_trajectory",
  321. )
  322. self._save_predictions(instance_id, info)
  323. for hook in self.hooks:
  324. hook.on_instance_completed(info=info, trajectory=trajectory)
  325. def main(self):
  326. for hook in self.hooks:
  327. hook.on_start()
  328. for index in range(len(self.env.data)):
  329. try:
  330. self.run(index)
  331. except _ContinueLoop:
  332. continue
  333. except KeyboardInterrupt:
  334. logger.info("Exiting InterCode environment...")
  335. self.env.close()
  336. break
  337. except SystemExit:
  338. logger.critical(f"❌ Exiting because SystemExit was called")
  339. self.env.close()
  340. logger.info("Container closed")
  341. raise
  342. except Exception as e:
  343. traceback.print_exc()
  344. if self.args.raise_exceptions:
  345. self.env.close()
  346. raise e
  347. if self.env.record:
  348. logger.warning(f"❌ Failed on {self.env.record['instance_id']}: {e}")
  349. else:
  350. logger.warning(f"❌ Failed on unknown instance")
  351. self.env.reset_container()
  352. continue
  353. for hook in self.hooks:
  354. hook.on_end()
  355. def _save_arguments(self) -> None:
  356. """Save the arguments to a yaml file to the run's trajectory directory."""
  357. log_path = self.traj_dir / "args.yaml"
  358. if log_path.exists():
  359. try:
  360. other_args = self.args.load_yaml(log_path)
  361. if (self.args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality
  362. logger.warning("**************************************************")
  363. logger.warning("Found existing args.yaml with different arguments!")
  364. logger.warning("**************************************************")
  365. except Exception as e:
  366. logger.warning(f"Failed to load existing args.yaml: {e}")
  367. with log_path.open("w") as f:
  368. self.args.dump_yaml(f)
  369. def should_skip(self, instance_id: str) -> bool:
  370. """Check if we should skip this instance based on the instance filter and skip_existing flag."""
  371. # Skip instances that don't match the instance filter
  372. if re.match(self.args.instance_filter, instance_id) is None:
  373. logger.info(f"Instance filter not matched. Skipping instance {instance_id}")
  374. return True
  375. # If flag is set to False, don't skip
  376. if not self.args.skip_existing:
  377. return False
  378. # Check if there's an existing trajectory for this instance
  379. log_path = self.traj_dir / (instance_id + ".traj")
  380. if log_path.exists():
  381. with log_path.open("r") as f:
  382. data = json.load(f)
  383. # If the trajectory has no exit status, it's incomplete and we will redo it
  384. exit_status = data["info"].get("exit_status", None)
  385. if exit_status == "early_exit" or exit_status is None:
  386. logger.info(f"Found existing trajectory with no exit status: {log_path}")
  387. logger.info("Removing incomplete trajectory...")
  388. os.remove(log_path)
  389. else:
  390. logger.info(f"⏭️ Skipping existing trajectory: {log_path}")
  391. return True
  392. return False
  393. def _save_predictions(self, instance_id: str, info):
  394. output_file = self.traj_dir / "all_preds.jsonl"
  395. model_patch = info["submission"] if "submission" in info else None
  396. datum = {
  397. KEY_MODEL: Path(self.traj_dir).name,
  398. KEY_INSTANCE_ID: instance_id,
  399. KEY_PREDICTION: model_patch,
  400. }
  401. with open(output_file, "a+") as fp:
  402. print(json.dumps(datum), file=fp, flush=True)
  403. logger.info(f"Saved predictions to {output_file}")
  404. def get_args(args=None) -> ScriptArguments:
  405. """Parse command line arguments and return a ScriptArguments object.
  406. Args:
  407. args: Optional list of arguments to parse. If not provided, uses sys.argv.
  408. """
  409. defaults = ScriptArguments(
  410. suffix="",
  411. environment=EnvironmentArguments(
  412. image_name="sweagent/swe-agent:latest",
  413. data_path="princeton-nlp/SWE-bench_Lite",
  414. split="dev",
  415. verbose=True,
  416. install_environment=True,
  417. ),
  418. skip_existing=True,
  419. agent=AgentArguments(
  420. model=ModelArguments(
  421. model_name="gpt4",
  422. total_cost_limit=0.0,
  423. per_instance_cost_limit=3.0,
  424. temperature=0.0,
  425. top_p=0.95,
  426. ),
  427. config_file=Path("config/default.yaml"),
  428. ),
  429. actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
  430. )
  431. # Nicer yaml dumping of multiline strings
  432. def multiline_representer(dumper, data):
  433. """configures yaml for dumping multiline strings
  434. Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
  435. """
  436. if data.count("\n") > 0: # check for multiline string
  437. return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
  438. return dumper.represent_scalar("tag:yaml.org,2002:str", data)
  439. yaml.add_representer(str, multiline_representer)
  440. return parse(ScriptArguments, default=defaults, add_config_path_arg=False, args=args, formatter_class=RichHelpFormatter, description=Markdown(__doc__))
  441. def main(args: ScriptArguments):
  442. Main(args).main()
  443. if __name__ == "__main__":
  444. main(get_args())