resolve_issue.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. # flake8: noqa: E501
  2. import asyncio
  3. import dataclasses
  4. import json
  5. import os
  6. import pathlib
  7. import shutil
  8. import subprocess
  9. from typing import Any
  10. from uuid import uuid4
  11. from termcolor import colored
  12. import openhands
  13. from openhands.controller.state.state import State
  14. from openhands.core.config import (
  15. AgentConfig,
  16. AppConfig,
  17. LLMConfig,
  18. SandboxConfig,
  19. )
  20. from openhands.core.logger import openhands_logger as logger
  21. from openhands.core.main import create_runtime, run_controller
  22. from openhands.events.action import CmdRunAction, MessageAction
  23. from openhands.events.observation import (
  24. CmdOutputObservation,
  25. ErrorObservation,
  26. Observation,
  27. )
  28. from openhands.events.stream import EventStreamSubscriber
  29. from openhands.resolver.github_issue import GithubIssue
  30. from openhands.resolver.issue_definitions import (
  31. IssueHandler,
  32. IssueHandlerInterface,
  33. PRHandler,
  34. )
  35. from openhands.resolver.resolver_output import ResolverOutput
  36. from openhands.resolver.utils import (
  37. codeact_user_response,
  38. reset_logger_for_multiprocessing,
  39. )
  40. from openhands.runtime.base import Runtime
  41. # Don't make this confgurable for now, unless we have other competitive agents
  42. AGENT_CLASS = 'CodeActAgent'
  43. def initialize_runtime(
  44. runtime: Runtime,
  45. ):
  46. """Initialize the runtime for the agent.
  47. This function is called before the runtime is used to run the agent.
  48. Currently it does nothing.
  49. """
  50. logger.info('-' * 30)
  51. logger.info('BEGIN Runtime Completion Fn')
  52. logger.info('-' * 30)
  53. obs: Observation
  54. action = CmdRunAction(command='cd /workspace')
  55. logger.info(action, extra={'msg_type': 'ACTION'})
  56. obs = runtime.run_action(action)
  57. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  58. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  59. raise RuntimeError(f'Failed to change directory to /workspace.\n{obs}')
  60. action = CmdRunAction(command='git config --global core.pager ""')
  61. logger.info(action, extra={'msg_type': 'ACTION'})
  62. obs = runtime.run_action(action)
  63. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  64. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  65. raise RuntimeError(f'Failed to set git config.\n{obs}')
  66. async def complete_runtime(
  67. runtime: Runtime,
  68. base_commit: str,
  69. ) -> dict[str, Any]:
  70. """Complete the runtime for the agent.
  71. This function is called before the runtime is used to run the agent.
  72. If you need to do something in the sandbox to get the correctness metric after
  73. the agent has run, modify this function.
  74. """
  75. logger.info('-' * 30)
  76. logger.info('BEGIN Runtime Completion Fn')
  77. logger.info('-' * 30)
  78. obs: Observation
  79. action = CmdRunAction(command='cd /workspace')
  80. logger.info(action, extra={'msg_type': 'ACTION'})
  81. obs = runtime.run_action(action)
  82. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  83. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  84. raise RuntimeError(
  85. f'Failed to change directory to /workspace. Observation: {obs}'
  86. )
  87. action = CmdRunAction(command='git config --global core.pager ""')
  88. logger.info(action, extra={'msg_type': 'ACTION'})
  89. obs = runtime.run_action(action)
  90. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  91. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  92. raise RuntimeError(f'Failed to set git config. Observation: {obs}')
  93. action = CmdRunAction(command='git config --global --add safe.directory /workspace')
  94. logger.info(action, extra={'msg_type': 'ACTION'})
  95. obs = runtime.run_action(action)
  96. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  97. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  98. raise RuntimeError(f'Failed to set git config. Observation: {obs}')
  99. action = CmdRunAction(command='git add -A')
  100. logger.info(action, extra={'msg_type': 'ACTION'})
  101. obs = runtime.run_action(action)
  102. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  103. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  104. raise RuntimeError(f'Failed to git add. Observation: {obs}')
  105. n_retries = 0
  106. git_patch = None
  107. while n_retries < 5:
  108. action = CmdRunAction(
  109. command=f'git diff --no-color --cached {base_commit}',
  110. keep_prompt=False,
  111. )
  112. action.timeout = 600 + 100 * n_retries
  113. logger.info(action, extra={'msg_type': 'ACTION'})
  114. obs = runtime.run_action(action)
  115. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  116. n_retries += 1
  117. if isinstance(obs, CmdOutputObservation):
  118. if obs.exit_code == 0:
  119. git_patch = obs.content.strip()
  120. break
  121. else:
  122. logger.info('Failed to get git diff, retrying...')
  123. await asyncio.sleep(10)
  124. elif isinstance(obs, ErrorObservation):
  125. logger.error(f'Error occurred: {obs.content}. Retrying...')
  126. await asyncio.sleep(10)
  127. else:
  128. raise ValueError(f'Unexpected observation type: {type(obs)}')
  129. logger.info('-' * 30)
  130. logger.info('END Runtime Completion Fn')
  131. logger.info('-' * 30)
  132. return {'git_patch': git_patch}
  133. async def process_issue(
  134. issue: GithubIssue,
  135. base_commit: str,
  136. max_iterations: int,
  137. llm_config: LLMConfig,
  138. output_dir: str,
  139. runtime_container_image: str,
  140. prompt_template: str,
  141. issue_handler: IssueHandlerInterface,
  142. repo_instruction: str | None = None,
  143. reset_logger: bool = False,
  144. ) -> ResolverOutput:
  145. # Setup the logger properly, so you can run multi-processing to parallelize processing
  146. if reset_logger:
  147. log_dir = os.path.join(output_dir, 'infer_logs')
  148. reset_logger_for_multiprocessing(logger, str(issue.number), log_dir)
  149. else:
  150. logger.info(f'Starting fixing issue {issue.number}.')
  151. workspace_base = os.path.join(
  152. output_dir, 'workspace', f'{issue_handler.issue_type}_{issue.number}'
  153. )
  154. # Get the absolute path of the workspace base
  155. workspace_base = os.path.abspath(workspace_base)
  156. # write the repo to the workspace
  157. if os.path.exists(workspace_base):
  158. shutil.rmtree(workspace_base)
  159. shutil.copytree(os.path.join(output_dir, 'repo'), workspace_base)
  160. config = AppConfig(
  161. default_agent='CodeActAgent',
  162. runtime='eventstream',
  163. max_budget_per_task=4,
  164. max_iterations=max_iterations,
  165. sandbox=SandboxConfig(
  166. runtime_container_image=runtime_container_image,
  167. enable_auto_lint=False,
  168. use_host_network=False,
  169. # large enough timeout, since some testcases take very long to run
  170. timeout=300,
  171. ),
  172. # do not mount workspace
  173. workspace_base=workspace_base,
  174. workspace_mount_path=workspace_base,
  175. agents={'CodeActAgent': AgentConfig(disabled_microagents=['github'])},
  176. )
  177. config.set_llm_config(llm_config)
  178. runtime = create_runtime(config)
  179. await runtime.connect()
  180. async def on_event(evt):
  181. logger.info(evt)
  182. runtime.event_stream.subscribe(EventStreamSubscriber.MAIN, on_event, str(uuid4()))
  183. initialize_runtime(runtime)
  184. instruction, images_urls = issue_handler.get_instruction(
  185. issue, prompt_template, repo_instruction
  186. )
  187. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  188. action = MessageAction(content=instruction, image_urls=images_urls)
  189. try:
  190. state: State | None = await run_controller(
  191. config=config,
  192. initial_user_action=action,
  193. runtime=runtime,
  194. fake_user_response_fn=codeact_user_response,
  195. )
  196. if state is None:
  197. raise RuntimeError('Failed to run the agent.')
  198. except (ValueError, RuntimeError) as e:
  199. error_msg = f'Agent failed with error: {str(e)}'
  200. logger.error(error_msg)
  201. state = None
  202. last_error: str | None = error_msg
  203. # Get git patch
  204. return_val = await complete_runtime(runtime, base_commit)
  205. git_patch = return_val['git_patch']
  206. logger.info(
  207. f'Got git diff for instance {issue.number}:\n--------\n{git_patch}\n--------'
  208. )
  209. # Serialize histories and set defaults for failed state
  210. if state is None:
  211. histories = []
  212. metrics = None
  213. success = False
  214. comment_success = None
  215. success_explanation = 'Agent failed to run'
  216. last_error = 'Agent failed to run or crashed'
  217. else:
  218. histories = [dataclasses.asdict(event) for event in state.history]
  219. metrics = state.metrics.get() if state.metrics else None
  220. # determine success based on the history and the issue description
  221. success, comment_success, success_explanation = issue_handler.guess_success(
  222. issue, state.history
  223. )
  224. if issue_handler.issue_type == 'pr' and comment_success:
  225. success_log = 'I have updated the PR and resolved some of the issues that were cited in the pull request review. Specifically, I identified the following revision requests, and all the ones that I think I successfully resolved are checked off. All the unchecked ones I was not able to resolve, so manual intervention may be required:\n'
  226. try:
  227. explanations = json.loads(success_explanation)
  228. except json.JSONDecodeError:
  229. logger.error(
  230. f'Failed to parse success_explanation as JSON: {success_explanation}'
  231. )
  232. explanations = [str(success_explanation)] # Use raw string as fallback
  233. for success_indicator, explanation in zip(comment_success, explanations):
  234. status = (
  235. colored('[X]', 'red')
  236. if success_indicator
  237. else colored('[ ]', 'red')
  238. )
  239. bullet_point = colored('-', 'yellow')
  240. success_log += f'\n{bullet_point} {status}: {explanation}'
  241. logger.info(success_log)
  242. last_error = state.last_error if state.last_error else None
  243. # Save the output
  244. output = ResolverOutput(
  245. issue=issue,
  246. issue_type=issue_handler.issue_type,
  247. instruction=instruction,
  248. base_commit=base_commit,
  249. git_patch=git_patch,
  250. history=histories,
  251. metrics=metrics,
  252. success=success,
  253. comment_success=comment_success,
  254. success_explanation=success_explanation,
  255. error=last_error,
  256. )
  257. return output
  258. def issue_handler_factory(
  259. issue_type: str, owner: str, repo: str, token: str, llm_config: LLMConfig
  260. ) -> IssueHandlerInterface:
  261. if issue_type == 'issue':
  262. return IssueHandler(owner, repo, token, llm_config)
  263. elif issue_type == 'pr':
  264. return PRHandler(owner, repo, token, llm_config)
  265. else:
  266. raise ValueError(f'Invalid issue type: {issue_type}')
  267. async def resolve_issue(
  268. owner: str,
  269. repo: str,
  270. token: str,
  271. username: str,
  272. max_iterations: int,
  273. output_dir: str,
  274. llm_config: LLMConfig,
  275. runtime_container_image: str,
  276. prompt_template: str,
  277. issue_type: str,
  278. repo_instruction: str | None,
  279. issue_number: int,
  280. comment_id: int | None,
  281. target_branch: str | None = None,
  282. reset_logger: bool = False,
  283. ) -> None:
  284. """Resolve a single github issue.
  285. Args:
  286. owner: Github owner of the repo.
  287. repo: Github repository to resolve issues in form of `owner/repo`.
  288. token: Github token to access the repository.
  289. username: Github username to access the repository.
  290. max_iterations: Maximum number of iterations to run.
  291. output_dir: Output directory to write the results.
  292. llm_config: Configuration for the language model.
  293. runtime_container_image: Container image to use.
  294. prompt_template: Prompt template to use.
  295. issue_type: Type of issue to resolve (issue or pr).
  296. repo_instruction: Repository instruction to use.
  297. issue_number: Issue number to resolve.
  298. comment_id: Optional ID of a specific comment to focus on.
  299. target_branch: Optional target branch to create PR against (for PRs).
  300. reset_logger: Whether to reset the logger for multiprocessing.
  301. """
  302. issue_handler = issue_handler_factory(issue_type, owner, repo, token, llm_config)
  303. # Load dataset
  304. issues: list[GithubIssue] = issue_handler.get_converted_issues(
  305. issue_numbers=[issue_number], comment_id=comment_id
  306. )
  307. if not issues:
  308. raise ValueError(
  309. f'No issues found for issue number {issue_number}. Please verify that:\n'
  310. f'1. The issue/PR #{issue_number} exists in the repository {owner}/{repo}\n'
  311. f'2. You have the correct permissions to access it\n'
  312. f'3. The repository name is spelled correctly'
  313. )
  314. issue = issues[0]
  315. if comment_id is not None:
  316. if (
  317. issue_type == 'pr'
  318. and not issue.review_comments
  319. and not issue.review_threads
  320. and not issue.thread_comments
  321. ):
  322. raise ValueError(
  323. f'Comment ID {comment_id} did not have a match for issue {issue.number}'
  324. )
  325. if issue_type == 'issue' and not issue.thread_comments:
  326. raise ValueError(
  327. f'Comment ID {comment_id} did not have a match for issue {issue.number}'
  328. )
  329. # TEST METADATA
  330. model_name = llm_config.model.split('/')[-1]
  331. pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)
  332. pathlib.Path(os.path.join(output_dir, 'infer_logs')).mkdir(
  333. parents=True, exist_ok=True
  334. )
  335. logger.info(f'Using output directory: {output_dir}')
  336. # checkout the repo
  337. repo_dir = os.path.join(output_dir, 'repo')
  338. if not os.path.exists(repo_dir):
  339. checkout_output = subprocess.check_output(
  340. [
  341. 'git',
  342. 'clone',
  343. f'https://{username}:{token}@github.com/{owner}/{repo}',
  344. f'{output_dir}/repo',
  345. ]
  346. ).decode('utf-8')
  347. if 'fatal' in checkout_output:
  348. raise RuntimeError(f'Failed to clone repository: {checkout_output}')
  349. # get the commit id of current repo for reproducibility
  350. base_commit = (
  351. subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)
  352. .decode('utf-8')
  353. .strip()
  354. )
  355. logger.info(f'Base commit: {base_commit}')
  356. if repo_instruction is None:
  357. # Check for .openhands_instructions file in the workspace directory
  358. openhands_instructions_path = os.path.join(repo_dir, '.openhands_instructions')
  359. if os.path.exists(openhands_instructions_path):
  360. with open(openhands_instructions_path, 'r') as f:
  361. repo_instruction = f.read()
  362. # OUTPUT FILE
  363. output_file = os.path.join(output_dir, 'output.jsonl')
  364. logger.info(f'Writing output to {output_file}')
  365. # Check if this issue was already processed
  366. if os.path.exists(output_file):
  367. with open(output_file, 'r') as f:
  368. for line in f:
  369. data = ResolverOutput.model_validate_json(line)
  370. if data.issue.number == issue_number:
  371. logger.warning(
  372. f'Issue {issue_number} was already processed. Skipping.'
  373. )
  374. return
  375. output_fp = open(output_file, 'a')
  376. logger.info(
  377. f'Resolving issue {issue_number} with Agent {AGENT_CLASS}, model {model_name}, max iterations {max_iterations}.'
  378. )
  379. try:
  380. # checkout to pr branch if needed
  381. if issue_type == 'pr':
  382. branch_to_use = target_branch if target_branch else issue.head_branch
  383. logger.info(
  384. f'Checking out to PR branch {target_branch} for issue {issue.number}'
  385. )
  386. if not branch_to_use:
  387. raise ValueError('Branch name cannot be None')
  388. # Fetch the branch first to ensure it exists locally
  389. fetch_cmd = ['git', 'fetch', 'origin', branch_to_use]
  390. subprocess.check_output(
  391. fetch_cmd,
  392. cwd=repo_dir,
  393. )
  394. # Checkout the branch
  395. checkout_cmd = ['git', 'checkout', branch_to_use]
  396. subprocess.check_output(
  397. checkout_cmd,
  398. cwd=repo_dir,
  399. )
  400. # Update issue's base_branch if using custom target branch
  401. if target_branch:
  402. issue.base_branch = target_branch
  403. base_commit = (
  404. subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)
  405. .decode('utf-8')
  406. .strip()
  407. )
  408. output = await process_issue(
  409. issue,
  410. base_commit,
  411. max_iterations,
  412. llm_config,
  413. output_dir,
  414. runtime_container_image,
  415. prompt_template,
  416. issue_handler,
  417. repo_instruction,
  418. reset_logger,
  419. )
  420. output_fp.write(output.model_dump_json() + '\n')
  421. output_fp.flush()
  422. finally:
  423. output_fp.close()
  424. logger.info('Finished.')
  425. def main():
  426. import argparse
  427. def int_or_none(value):
  428. if value.lower() == 'none':
  429. return None
  430. else:
  431. return int(value)
  432. parser = argparse.ArgumentParser(description='Resolve a single issue from Github.')
  433. parser.add_argument(
  434. '--repo',
  435. type=str,
  436. required=True,
  437. help='Github repository to resolve issues in form of `owner/repo`.',
  438. )
  439. parser.add_argument(
  440. '--token',
  441. type=str,
  442. default=None,
  443. help='Github token to access the repository.',
  444. )
  445. parser.add_argument(
  446. '--username',
  447. type=str,
  448. default=None,
  449. help='Github username to access the repository.',
  450. )
  451. parser.add_argument(
  452. '--runtime-container-image',
  453. type=str,
  454. default=None,
  455. help='Container image to use.',
  456. )
  457. parser.add_argument(
  458. '--max-iterations',
  459. type=int,
  460. default=50,
  461. help='Maximum number of iterations to run.',
  462. )
  463. parser.add_argument(
  464. '--issue-number',
  465. type=int,
  466. required=True,
  467. help='Issue number to resolve.',
  468. )
  469. parser.add_argument(
  470. '--comment-id',
  471. type=int_or_none,
  472. required=False,
  473. default=None,
  474. help='Resolve a specific comment',
  475. )
  476. parser.add_argument(
  477. '--output-dir',
  478. type=str,
  479. default='output',
  480. help='Output directory to write the results.',
  481. )
  482. parser.add_argument(
  483. '--llm-model',
  484. type=str,
  485. default=None,
  486. help='LLM model to use.',
  487. )
  488. parser.add_argument(
  489. '--llm-api-key',
  490. type=str,
  491. default=None,
  492. help='LLM API key to use.',
  493. )
  494. parser.add_argument(
  495. '--llm-base-url',
  496. type=str,
  497. default=None,
  498. help='LLM base URL to use.',
  499. )
  500. parser.add_argument(
  501. '--prompt-file',
  502. type=str,
  503. default=None,
  504. help='Path to the prompt template file in Jinja format.',
  505. )
  506. parser.add_argument(
  507. '--repo-instruction-file',
  508. type=str,
  509. default=None,
  510. help='Path to the repository instruction file in text format.',
  511. )
  512. parser.add_argument(
  513. '--issue-type',
  514. type=str,
  515. default='issue',
  516. choices=['issue', 'pr'],
  517. help='Type of issue to resolve, either open issue or pr comments.',
  518. )
  519. parser.add_argument(
  520. '--target-branch',
  521. type=str,
  522. default=None,
  523. help="Target branch to pull and create PR against (for PRs). If not specified, uses the PR's base branch.",
  524. )
  525. my_args = parser.parse_args()
  526. runtime_container_image = my_args.runtime_container_image
  527. if runtime_container_image is None:
  528. runtime_container_image = (
  529. f'ghcr.io/all-hands-ai/runtime:{openhands.__version__}-nikolaik'
  530. )
  531. owner, repo = my_args.repo.split('/')
  532. token = my_args.token if my_args.token else os.getenv('GITHUB_TOKEN')
  533. username = my_args.username if my_args.username else os.getenv('GITHUB_USERNAME')
  534. if not username:
  535. raise ValueError('Github username is required.')
  536. if not token:
  537. raise ValueError('Github token is required.')
  538. llm_config = LLMConfig(
  539. model=my_args.llm_model or os.environ['LLM_MODEL'],
  540. api_key=my_args.llm_api_key or os.environ['LLM_API_KEY'],
  541. base_url=my_args.llm_base_url or os.environ.get('LLM_BASE_URL', None),
  542. )
  543. repo_instruction = None
  544. if my_args.repo_instruction_file:
  545. with open(my_args.repo_instruction_file, 'r') as f:
  546. repo_instruction = f.read()
  547. issue_type = my_args.issue_type
  548. # Read the prompt template
  549. prompt_file = my_args.prompt_file
  550. if prompt_file is None:
  551. if issue_type == 'issue':
  552. prompt_file = os.path.join(
  553. os.path.dirname(__file__), 'prompts/resolve/basic-with-tests.jinja'
  554. )
  555. else:
  556. prompt_file = os.path.join(
  557. os.path.dirname(__file__), 'prompts/resolve/basic-followup.jinja'
  558. )
  559. with open(prompt_file, 'r') as f:
  560. prompt_template = f.read()
  561. asyncio.run(
  562. resolve_issue(
  563. owner=owner,
  564. repo=repo,
  565. token=token,
  566. username=username,
  567. runtime_container_image=runtime_container_image,
  568. max_iterations=my_args.max_iterations,
  569. output_dir=my_args.output_dir,
  570. llm_config=llm_config,
  571. prompt_template=prompt_template,
  572. issue_type=issue_type,
  573. repo_instruction=repo_instruction,
  574. issue_number=my_args.issue_number,
  575. comment_id=my_args.comment_id,
  576. target_branch=my_args.target_branch,
  577. )
  578. )
  579. if __name__ == '__main__':
  580. main()