resolve_all_issues.py 12 KB

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