run.py 20 KB

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