resolve_all_issues.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. # flake8: noqa: E501
  2. import argparse
  3. import asyncio
  4. import multiprocessing as mp
  5. import os
  6. import pathlib
  7. import subprocess
  8. from typing import Awaitable, TextIO
  9. from tqdm import tqdm
  10. import openhands
  11. from openhands.core.config import LLMConfig
  12. from openhands.core.logger import openhands_logger as logger
  13. from openhands.resolver.github_issue import GithubIssue
  14. from openhands.resolver.resolve_issue import (
  15. issue_handler_factory,
  16. process_issue,
  17. )
  18. from openhands.resolver.resolver_output import ResolverOutput
  19. def cleanup():
  20. print('Cleaning up child processes...')
  21. for process in mp.active_children():
  22. print(f'Terminating child process: {process.name}')
  23. process.terminate()
  24. process.join()
  25. # This function tracks the progress AND write the output to a JSONL file
  26. async def update_progress(
  27. output: Awaitable[ResolverOutput], output_fp: TextIO, pbar: tqdm
  28. ) -> None:
  29. resolved_output = await output
  30. pbar.update(1)
  31. pbar.set_description(f'issue {resolved_output.issue.number}')
  32. pbar.set_postfix_str(
  33. f'Test Result: {resolved_output.metrics.get("test_result", "N/A") if resolved_output.metrics else "N/A"}'
  34. )
  35. logger.info(
  36. f'Finished issue {resolved_output.issue.number}: {resolved_output.metrics.get("test_result", "N/A") if resolved_output.metrics else "N/A"}'
  37. )
  38. output_fp.write(resolved_output.model_dump_json() + '\n')
  39. output_fp.flush()
  40. async def resolve_issues(
  41. owner: str,
  42. repo: str,
  43. token: str,
  44. username: str,
  45. max_iterations: int,
  46. limit_issues: int | None,
  47. num_workers: int,
  48. output_dir: str,
  49. llm_config: LLMConfig,
  50. runtime_container_image: str,
  51. prompt_template: str,
  52. issue_type: str,
  53. repo_instruction: str | None,
  54. issue_numbers: list[int] | None,
  55. ) -> None:
  56. """Resolve multiple github issues.
  57. Args:
  58. owner: Github owner of the repo.
  59. repo: Github repository to resolve issues in form of `owner/repo`.
  60. token: Github token to access the repository.
  61. username: Github username to access the repository.
  62. max_iterations: Maximum number of iterations to run.
  63. limit_issues: Limit the number of issues to resolve.
  64. num_workers: Number of workers to use for parallel processing.
  65. output_dir: Output directory to write the results.
  66. llm_config: Configuration for the language model.
  67. runtime_container_image: Container image to use.
  68. prompt_template: Prompt template to use.
  69. issue_type: Type of issue to resolve (issue or pr).
  70. repo_instruction: Repository instruction to use.
  71. issue_numbers: List of issue numbers to resolve.
  72. """
  73. issue_handler = issue_handler_factory(issue_type, owner, repo, token, llm_config)
  74. # Load dataset
  75. issues: list[GithubIssue] = issue_handler.get_converted_issues(
  76. issue_numbers=issue_numbers
  77. )
  78. if limit_issues is not None:
  79. issues = issues[:limit_issues]
  80. logger.info(f'Limiting resolving to first {limit_issues} issues.')
  81. # TEST METADATA
  82. model_name = llm_config.model.split('/')[-1]
  83. pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)
  84. pathlib.Path(os.path.join(output_dir, 'infer_logs')).mkdir(
  85. parents=True, exist_ok=True
  86. )
  87. logger.info(f'Using output directory: {output_dir}')
  88. # checkout the repo
  89. repo_dir = os.path.join(output_dir, 'repo')
  90. if not os.path.exists(repo_dir):
  91. checkout_output = subprocess.check_output(
  92. [
  93. 'git',
  94. 'clone',
  95. f'https://{username}:{token}@github.com/{owner}/{repo}',
  96. f'{output_dir}/repo',
  97. ]
  98. ).decode('utf-8')
  99. if 'fatal' in checkout_output:
  100. raise RuntimeError(f'Failed to clone repository: {checkout_output}')
  101. # get the commit id of current repo for reproducibility
  102. base_commit = (
  103. subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)
  104. .decode('utf-8')
  105. .strip()
  106. )
  107. logger.info(f'Base commit: {base_commit}')
  108. if repo_instruction is None:
  109. # Check for .openhands_instructions file in the workspace directory
  110. openhands_instructions_path = os.path.join(repo_dir, '.openhands_instructions')
  111. if os.path.exists(openhands_instructions_path):
  112. with open(openhands_instructions_path, 'r') as f:
  113. repo_instruction = f.read()
  114. # OUTPUT FILE
  115. output_file = os.path.join(output_dir, 'output.jsonl')
  116. logger.info(f'Writing output to {output_file}')
  117. finished_numbers = set()
  118. if os.path.exists(output_file):
  119. with open(output_file, 'r') as f:
  120. for line in f:
  121. data = ResolverOutput.model_validate_json(line)
  122. finished_numbers.add(data.issue.number)
  123. logger.warning(
  124. f'Output file {output_file} already exists. Loaded {len(finished_numbers)} finished issues.'
  125. )
  126. output_fp = open(output_file, 'a')
  127. logger.info(
  128. f'Resolving issues with model {model_name}, max iterations {max_iterations}.'
  129. )
  130. # =============================================
  131. # filter out finished issues
  132. new_issues = []
  133. for issue in issues:
  134. if issue.number in finished_numbers:
  135. logger.info(f'Skipping issue {issue.number} as it is already finished.')
  136. continue
  137. new_issues.append(issue)
  138. logger.info(
  139. f'Finished issues: {len(finished_numbers)}, Remaining issues: {len(issues)}'
  140. )
  141. # =============================================
  142. pbar = tqdm(total=len(issues))
  143. # This sets the multi-processing
  144. logger.info(f'Using {num_workers} workers.')
  145. try:
  146. tasks = []
  147. for issue in issues:
  148. # checkout to pr branch
  149. if issue_type == 'pr':
  150. logger.info(
  151. f'Checking out to PR branch {issue.head_branch} for issue {issue.number}'
  152. )
  153. subprocess.check_output(
  154. ['git', 'checkout', f'{issue.head_branch}'],
  155. cwd=repo_dir,
  156. )
  157. base_commit = (
  158. subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)
  159. .decode('utf-8')
  160. .strip()
  161. )
  162. task = update_progress(
  163. process_issue(
  164. issue,
  165. base_commit,
  166. max_iterations,
  167. llm_config,
  168. output_dir,
  169. runtime_container_image,
  170. prompt_template,
  171. issue_handler,
  172. repo_instruction,
  173. bool(num_workers > 1),
  174. ),
  175. output_fp,
  176. pbar,
  177. )
  178. tasks.append(task)
  179. # Use asyncio.gather with a semaphore to limit concurrency
  180. sem = asyncio.Semaphore(num_workers)
  181. async def run_with_semaphore(task):
  182. async with sem:
  183. return await task
  184. await asyncio.gather(*[run_with_semaphore(task) for task in tasks])
  185. except KeyboardInterrupt:
  186. print('KeyboardInterrupt received. Cleaning up...')
  187. cleanup()
  188. output_fp.close()
  189. logger.info('Finished.')
  190. def main():
  191. parser = argparse.ArgumentParser(description='Resolve multiple issues from Github.')
  192. parser.add_argument(
  193. '--repo',
  194. type=str,
  195. required=True,
  196. help='Github repository to resolve issues in form of `owner/repo`.',
  197. )
  198. parser.add_argument(
  199. '--token',
  200. type=str,
  201. default=None,
  202. help='Github token to access the repository.',
  203. )
  204. parser.add_argument(
  205. '--username',
  206. type=str,
  207. default=None,
  208. help='Github username to access the repository.',
  209. )
  210. parser.add_argument(
  211. '--runtime-container-image',
  212. type=str,
  213. default=None,
  214. help='Container image to use.',
  215. )
  216. parser.add_argument(
  217. '--max-iterations',
  218. type=int,
  219. default=50,
  220. help='Maximum number of iterations to run.',
  221. )
  222. parser.add_argument(
  223. '--limit-issues',
  224. type=int,
  225. default=None,
  226. help='Limit the number of issues to resolve.',
  227. )
  228. parser.add_argument(
  229. '--issue-numbers',
  230. type=str,
  231. default=None,
  232. help='Comma separated list of issue numbers to resolve.',
  233. )
  234. parser.add_argument(
  235. '--num-workers',
  236. type=int,
  237. default=1,
  238. help='Number of workers to use for parallel processing.',
  239. )
  240. parser.add_argument(
  241. '--output-dir',
  242. type=str,
  243. default='output',
  244. help='Output directory to write the results.',
  245. )
  246. parser.add_argument(
  247. '--llm-model',
  248. type=str,
  249. default=None,
  250. help='LLM model to use.',
  251. )
  252. parser.add_argument(
  253. '--llm-api-key',
  254. type=str,
  255. default=None,
  256. help='LLM API key to use.',
  257. )
  258. parser.add_argument(
  259. '--llm-base-url',
  260. type=str,
  261. default=None,
  262. help='LLM base URL to use.',
  263. )
  264. parser.add_argument(
  265. '--prompt-file',
  266. type=str,
  267. default=None,
  268. help='Path to the prompt template file in Jinja format.',
  269. )
  270. parser.add_argument(
  271. '--repo-instruction-file',
  272. type=str,
  273. default=None,
  274. help='Path to the repository instruction file in text format.',
  275. )
  276. parser.add_argument(
  277. '--issue-type',
  278. type=str,
  279. default='issue',
  280. choices=['issue', 'pr'],
  281. help='Type of issue to resolve, either open issue or pr comments.',
  282. )
  283. my_args = parser.parse_args()
  284. runtime_container_image = my_args.runtime_container_image
  285. if runtime_container_image is None:
  286. runtime_container_image = (
  287. f'ghcr.io/all-hands-ai/runtime:{openhands.__version__}-nikolaik'
  288. )
  289. owner, repo = my_args.repo.split('/')
  290. token = my_args.token if my_args.token else os.getenv('GITHUB_TOKEN')
  291. username = my_args.username if my_args.username else os.getenv('GITHUB_USERNAME')
  292. if not username:
  293. raise ValueError('Github username is required.')
  294. if not token:
  295. raise ValueError('Github token is required.')
  296. llm_config = LLMConfig(
  297. model=my_args.llm_model or os.environ['LLM_MODEL'],
  298. api_key=my_args.llm_api_key or os.environ['LLM_API_KEY'],
  299. base_url=my_args.llm_base_url or os.environ.get('LLM_BASE_URL', None),
  300. )
  301. repo_instruction = None
  302. if my_args.repo_instruction_file:
  303. with open(my_args.repo_instruction_file, 'r') as f:
  304. repo_instruction = f.read()
  305. issue_numbers = None
  306. if my_args.issue_numbers:
  307. issue_numbers = [int(number) for number in my_args.issue_numbers.split(',')]
  308. issue_type = my_args.issue_type
  309. # Read the prompt template
  310. prompt_file = my_args.prompt_file
  311. if prompt_file is None:
  312. if issue_type == 'issue':
  313. prompt_file = os.path.join(
  314. os.path.dirname(__file__), 'prompts/resolve/basic-with-tests.jinja'
  315. )
  316. else:
  317. prompt_file = os.path.join(
  318. os.path.dirname(__file__), 'prompts/resolve/basic-followup.jinja'
  319. )
  320. with open(prompt_file, 'r') as f:
  321. prompt_template = f.read()
  322. asyncio.run(
  323. resolve_issues(
  324. owner=owner,
  325. repo=repo,
  326. token=token,
  327. username=username,
  328. runtime_container_image=runtime_container_image,
  329. max_iterations=my_args.max_iterations,
  330. limit_issues=my_args.limit_issues,
  331. num_workers=my_args.num_workers,
  332. output_dir=my_args.output_dir,
  333. llm_config=llm_config,
  334. prompt_template=prompt_template,
  335. issue_type=issue_type,
  336. repo_instruction=repo_instruction,
  337. issue_numbers=issue_numbers,
  338. )
  339. )
  340. if __name__ == '__main__':
  341. main()