run_infer.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import asyncio
  2. import json
  3. import os
  4. import tempfile
  5. from typing import Any
  6. import pandas as pd
  7. import toml
  8. from datasets import load_dataset
  9. import openhands.agenthub
  10. from evaluation.utils.shared import (
  11. EvalException,
  12. EvalMetadata,
  13. EvalOutput,
  14. assert_and_raise,
  15. codeact_user_response,
  16. make_metadata,
  17. prepare_dataset,
  18. reset_logger_for_multiprocessing,
  19. run_evaluation,
  20. update_llm_config_for_completions_logging,
  21. )
  22. from openhands.controller.state.state import State
  23. from openhands.core.config import (
  24. AgentConfig,
  25. AppConfig,
  26. SandboxConfig,
  27. get_llm_config_arg,
  28. get_parser,
  29. )
  30. from openhands.core.logger import openhands_logger as logger
  31. from openhands.core.main import create_runtime, run_controller
  32. from openhands.events.action import CmdRunAction, MessageAction
  33. from openhands.events.observation import CmdOutputObservation, ErrorObservation
  34. from openhands.events.serialization.event import event_to_dict
  35. from openhands.runtime.base import Runtime
  36. from openhands.utils.async_utils import call_async_from_sync
  37. from openhands.utils.shutdown_listener import sleep_if_should_continue
  38. USE_HINT_TEXT = os.environ.get('USE_HINT_TEXT', 'false').lower() == 'true'
  39. USE_INSTANCE_IMAGE = os.environ.get('USE_INSTANCE_IMAGE', 'false').lower() == 'true'
  40. RUN_WITH_BROWSING = os.environ.get('RUN_WITH_BROWSING', 'false').lower() == 'true'
  41. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  42. 'CodeActAgent': codeact_user_response,
  43. }
  44. def _get_swebench_workspace_dir_name(instance: pd.Series) -> str:
  45. return f'{instance.repo}__{instance.version}'.replace('/', '__')
  46. def get_instruction(instance: pd.Series, metadata: EvalMetadata):
  47. workspace_dir_name = _get_swebench_workspace_dir_name(instance)
  48. # Prepare instruction
  49. # Instruction based on Anthropic's official trajectory
  50. # https://github.com/eschluntz/swe-bench-experiments/tree/main/evaluation/verified/20241022_tools_claude-3-5-sonnet-updated/trajs
  51. instruction = (
  52. '<uploaded_files>\n'
  53. f'/workspace/{workspace_dir_name}\n'
  54. '</uploaded_files>\n'
  55. f"I've uploaded a python code repository in the directory {workspace_dir_name}. Consider the following PR description:\n\n"
  56. f'<pr_description>\n'
  57. f'{instance.problem_statement}\n'
  58. '</pr_description>\n\n'
  59. 'Can you help me implement the necessary changes to the repository so that the requirements specified in the <pr_description> are met?\n'
  60. "I've already taken care of all changes to any of the test files described in the <pr_description>. This means you DON'T have to modify the testing logic or any of the tests in any way!\n"
  61. 'Your task is to make the minimal changes to non-tests files in the /workspace directory to ensure the <pr_description> is satisfied.\n'
  62. 'Follow these steps to resolve the issue:\n'
  63. '1. As a first step, it might be a good idea to explore the repo to familiarize yourself with its structure.\n'
  64. '2. Create a script to reproduce the error and execute it with `python <filename.py>` using the BashTool, to confirm the error\n'
  65. '3. Edit the sourcecode of the repo to resolve the issue\n'
  66. '4. Rerun your reproduce script and confirm that the error is fixed!\n'
  67. '5. Think about edgecases and make sure your fix handles them as well\n'
  68. "Your thinking should be thorough and so it's fine if it's very long.\n"
  69. )
  70. if RUN_WITH_BROWSING:
  71. instruction += (
  72. '<IMPORTANT!>\n'
  73. 'You SHOULD NEVER attempt to browse the web. '
  74. '</IMPORTANT!>\n'
  75. )
  76. return instruction
  77. # TODO: migrate all swe-bench docker to ghcr.io/openhands
  78. DOCKER_IMAGE_PREFIX = os.environ.get('EVAL_DOCKER_IMAGE_PREFIX', 'docker.io/xingyaoww/')
  79. logger.info(f'Using docker image prefix: {DOCKER_IMAGE_PREFIX}')
  80. def get_instance_docker_image(instance_id: str) -> str:
  81. image_name = 'sweb.eval.x86_64.' + instance_id
  82. image_name = image_name.replace(
  83. '__', '_s_'
  84. ) # to comply with docker image naming convention
  85. return (DOCKER_IMAGE_PREFIX.rstrip('/') + '/' + image_name).lower()
  86. def get_config(
  87. instance: pd.Series,
  88. metadata: EvalMetadata,
  89. ) -> AppConfig:
  90. SWE_BENCH_CONTAINER_IMAGE = 'ghcr.io/opendevin/eval-swe-bench:full-v1.2.1'
  91. if USE_INSTANCE_IMAGE:
  92. # We use a different instance image for the each instance of swe-bench eval
  93. base_container_image = get_instance_docker_image(instance['instance_id'])
  94. logger.info(
  95. f'Using instance container image: {base_container_image}. '
  96. f'Please make sure this image exists. '
  97. f'Submit an issue on https://github.com/All-Hands-AI/OpenHands if you run into any issues.'
  98. )
  99. else:
  100. base_container_image = SWE_BENCH_CONTAINER_IMAGE
  101. logger.info(f'Using swe-bench container image: {base_container_image}')
  102. config = AppConfig(
  103. default_agent=metadata.agent_class,
  104. run_as_openhands=False,
  105. max_iterations=metadata.max_iterations,
  106. runtime=os.environ.get('RUNTIME', 'eventstream'),
  107. sandbox=SandboxConfig(
  108. base_container_image=base_container_image,
  109. enable_auto_lint=True,
  110. use_host_network=False,
  111. # large enough timeout, since some testcases take very long to run
  112. timeout=300,
  113. # Add platform to the sandbox config to solve issue 4401
  114. platform='linux/amd64',
  115. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  116. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  117. keep_runtime_alive=False,
  118. remote_runtime_init_timeout=3600,
  119. ),
  120. # do not mount workspace
  121. workspace_base=None,
  122. workspace_mount_path=None,
  123. )
  124. config.set_llm_config(
  125. update_llm_config_for_completions_logging(
  126. metadata.llm_config, metadata.eval_output_dir, instance['instance_id']
  127. )
  128. )
  129. agent_config = AgentConfig(
  130. codeact_enable_jupyter=False,
  131. codeact_enable_browsing=RUN_WITH_BROWSING,
  132. codeact_enable_llm_editor=False,
  133. )
  134. config.set_agent_config(agent_config)
  135. return config
  136. def initialize_runtime(
  137. runtime: Runtime,
  138. instance: pd.Series, # this argument is not required
  139. ):
  140. """Initialize the runtime for the agent.
  141. This function is called before the runtime is used to run the agent.
  142. """
  143. logger.info('-' * 30)
  144. logger.info('BEGIN Runtime Initialization Fn')
  145. logger.info('-' * 30)
  146. workspace_dir_name = _get_swebench_workspace_dir_name(instance)
  147. obs: CmdOutputObservation
  148. # Set instance id
  149. action = CmdRunAction(
  150. command=f"""echo 'export SWE_INSTANCE_ID={instance['instance_id']}' >> ~/.bashrc && echo 'export PIP_CACHE_DIR=~/.cache/pip' >> ~/.bashrc && echo "alias git='git --no-pager'" >> ~/.bashrc"""
  151. )
  152. action.timeout = 600
  153. logger.info(action, extra={'msg_type': 'ACTION'})
  154. obs = runtime.run_action(action)
  155. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  156. assert_and_raise(
  157. obs.exit_code == 0, f'Failed to export SWE_INSTANCE_ID: {str(obs)}'
  158. )
  159. action = CmdRunAction(command="""export USER=$(whoami); echo USER=${USER} """)
  160. action.timeout = 600
  161. logger.info(action, extra={'msg_type': 'ACTION'})
  162. obs = runtime.run_action(action)
  163. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  164. assert_and_raise(obs.exit_code == 0, f'Failed to export USER: {str(obs)}')
  165. if USE_INSTANCE_IMAGE:
  166. # inject the init script
  167. script_dir = os.path.dirname(__file__)
  168. # inject the instance info
  169. action = CmdRunAction(command='mkdir -p /swe_util/eval_data/instances')
  170. action.timeout = 600
  171. logger.info(action, extra={'msg_type': 'ACTION'})
  172. obs = runtime.run_action(action)
  173. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  174. assert_and_raise(
  175. obs.exit_code == 0,
  176. f'Failed to create /swe_util/eval_data/instances: {str(obs)}',
  177. )
  178. swe_instance_json_name = 'swe-bench-instance.json'
  179. with tempfile.TemporaryDirectory() as temp_dir:
  180. # Construct the full path for the desired file name within the temporary directory
  181. temp_file_path = os.path.join(temp_dir, swe_instance_json_name)
  182. # Write to the file with the desired name within the temporary directory
  183. with open(temp_file_path, 'w') as f:
  184. if not isinstance(instance, dict):
  185. json.dump([instance.to_dict()], f)
  186. else:
  187. json.dump([instance], f)
  188. # Copy the file to the desired location
  189. runtime.copy_to(temp_file_path, '/swe_util/eval_data/instances/')
  190. # inject the instance swe entry
  191. runtime.copy_to(
  192. str(os.path.join(script_dir, 'scripts/setup/instance_swe_entry.sh')),
  193. '/swe_util/',
  194. )
  195. action = CmdRunAction(command='cat ~/.bashrc')
  196. action.timeout = 600
  197. logger.info(action, extra={'msg_type': 'ACTION'})
  198. obs = runtime.run_action(action)
  199. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  200. assert_and_raise(obs.exit_code == 0, f'Failed to cat ~/.bashrc: {str(obs)}')
  201. action = CmdRunAction(command='source ~/.bashrc')
  202. action.timeout = 600
  203. logger.info(action, extra={'msg_type': 'ACTION'})
  204. obs = runtime.run_action(action)
  205. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  206. if isinstance(obs, ErrorObservation):
  207. logger.error(f'Failed to source ~/.bashrc: {str(obs)}')
  208. assert_and_raise(obs.exit_code == 0, f'Failed to source ~/.bashrc: {str(obs)}')
  209. action = CmdRunAction(command='source /swe_util/instance_swe_entry.sh')
  210. action.timeout = 3600
  211. logger.info(action, extra={'msg_type': 'ACTION'})
  212. obs = runtime.run_action(action)
  213. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  214. assert_and_raise(
  215. obs.exit_code == 0,
  216. f'Failed to source /swe_util/instance_swe_entry.sh: {str(obs)}',
  217. )
  218. else:
  219. action = CmdRunAction(command='source /swe_util/swe_entry.sh')
  220. action.timeout = 1800
  221. logger.info(action, extra={'msg_type': 'ACTION'})
  222. obs = runtime.run_action(action)
  223. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  224. assert_and_raise(
  225. obs.exit_code == 0,
  226. f'Failed to source /swe_util/swe_entry.sh: {str(obs)}',
  227. )
  228. action = CmdRunAction(command=f'cd /workspace/{workspace_dir_name}')
  229. action.timeout = 600
  230. logger.info(action, extra={'msg_type': 'ACTION'})
  231. obs = runtime.run_action(action)
  232. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  233. assert_and_raise(
  234. obs.exit_code == 0,
  235. f'Failed to cd to /workspace/{workspace_dir_name}: {str(obs)}',
  236. )
  237. action = CmdRunAction(command='git reset --hard')
  238. action.timeout = 600
  239. logger.info(action, extra={'msg_type': 'ACTION'})
  240. obs = runtime.run_action(action)
  241. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  242. assert_and_raise(obs.exit_code == 0, f'Failed to git reset --hard: {str(obs)}')
  243. action = CmdRunAction(
  244. command='for remote_name in $(git remote); do git remote remove "${remote_name}"; done'
  245. )
  246. action.timeout = 600
  247. logger.info(action, extra={'msg_type': 'ACTION'})
  248. obs = runtime.run_action(action)
  249. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  250. assert_and_raise(obs.exit_code == 0, f'Failed to remove git remotes: {str(obs)}')
  251. logger.info('-' * 30)
  252. logger.info('END Runtime Initialization Fn')
  253. logger.info('-' * 30)
  254. def complete_runtime(
  255. runtime: Runtime,
  256. instance: pd.Series, # this argument is not required, but it is used to get the workspace_dir_name
  257. ) -> dict[str, Any]:
  258. """Complete the runtime for the agent.
  259. This function is called before the runtime is used to run the agent.
  260. If you need to do something in the sandbox to get the correctness metric after
  261. the agent has run, modify this function.
  262. """
  263. logger.info('-' * 30)
  264. logger.info('BEGIN Runtime Completion Fn')
  265. logger.info('-' * 30)
  266. obs: CmdOutputObservation
  267. workspace_dir_name = _get_swebench_workspace_dir_name(instance)
  268. action = CmdRunAction(command=f'cd /workspace/{workspace_dir_name}')
  269. action.timeout = 600
  270. logger.info(action, extra={'msg_type': 'ACTION'})
  271. obs = runtime.run_action(action)
  272. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  273. assert_and_raise(
  274. isinstance(obs, CmdOutputObservation) and obs.exit_code == 0,
  275. f'Failed to cd to /workspace/{workspace_dir_name}: {str(obs)}',
  276. )
  277. action = CmdRunAction(command='git config --global core.pager ""')
  278. action.timeout = 600
  279. logger.info(action, extra={'msg_type': 'ACTION'})
  280. obs = runtime.run_action(action)
  281. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  282. assert_and_raise(
  283. isinstance(obs, CmdOutputObservation) and obs.exit_code == 0,
  284. f'Failed to git config --global core.pager "": {str(obs)}',
  285. )
  286. action = CmdRunAction(command='git add -A')
  287. action.timeout = 600
  288. logger.info(action, extra={'msg_type': 'ACTION'})
  289. obs = runtime.run_action(action)
  290. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  291. assert_and_raise(
  292. isinstance(obs, CmdOutputObservation) and obs.exit_code == 0,
  293. f'Failed to git add -A: {str(obs)}',
  294. )
  295. n_retries = 0
  296. git_patch = None
  297. while n_retries < 5:
  298. action = CmdRunAction(
  299. command=f'git diff --no-color --cached {instance["base_commit"]}',
  300. keep_prompt=False,
  301. )
  302. action.timeout = 600 + 100 * n_retries
  303. logger.info(action, extra={'msg_type': 'ACTION'})
  304. obs = runtime.run_action(action)
  305. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  306. n_retries += 1
  307. if isinstance(obs, CmdOutputObservation):
  308. if obs.exit_code == 0:
  309. git_patch = obs.content.strip()
  310. break
  311. else:
  312. logger.info('Failed to get git diff, retrying...')
  313. sleep_if_should_continue(10)
  314. elif isinstance(obs, ErrorObservation):
  315. logger.error(f'Error occurred: {obs.content}. Retrying...')
  316. sleep_if_should_continue(10)
  317. else:
  318. assert_and_raise(False, f'Unexpected observation type: {str(obs)}')
  319. assert_and_raise(git_patch is not None, 'Failed to get git diff (None)')
  320. logger.info('-' * 30)
  321. logger.info('END Runtime Completion Fn')
  322. logger.info('-' * 30)
  323. return {'git_patch': git_patch}
  324. def process_instance(
  325. instance: pd.Series,
  326. metadata: EvalMetadata,
  327. reset_logger: bool = True,
  328. ) -> EvalOutput:
  329. config = get_config(instance, metadata)
  330. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  331. if reset_logger:
  332. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  333. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  334. else:
  335. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  336. runtime = create_runtime(config)
  337. call_async_from_sync(runtime.connect)
  338. try:
  339. initialize_runtime(runtime, instance)
  340. instruction = get_instruction(instance, metadata)
  341. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  342. state: State | None = asyncio.run(
  343. run_controller(
  344. config=config,
  345. initial_user_action=MessageAction(content=instruction),
  346. runtime=runtime,
  347. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  348. metadata.agent_class
  349. ],
  350. )
  351. )
  352. # if fatal error, throw EvalError to trigger re-run
  353. if (
  354. state.last_error
  355. and 'fatal error during agent execution' in state.last_error
  356. and 'stuck in a loop' not in state.last_error
  357. ):
  358. raise EvalException('Fatal error detected: ' + state.last_error)
  359. # ======= THIS IS SWE-Bench specific =======
  360. # Get git patch
  361. return_val = complete_runtime(runtime, instance)
  362. git_patch = return_val['git_patch']
  363. logger.info(
  364. f'Got git diff for instance {instance.instance_id}:\n--------\n{git_patch}\n--------'
  365. )
  366. finally:
  367. runtime.close()
  368. # ==========================================
  369. # ======= Attempt to evaluate the agent's edits =======
  370. # we use eval_infer.sh to evaluate the agent's edits, not here
  371. # because the agent may alter the environment / testcases
  372. test_result = {
  373. 'git_patch': git_patch,
  374. }
  375. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  376. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  377. if state is None:
  378. raise ValueError('State should not be None.')
  379. # NOTE: this is NO LONGER the event stream, but an agent history that includes delegate agent's events
  380. histories = [event_to_dict(event) for event in state.history]
  381. metrics = state.metrics.get() if state.metrics else None
  382. # Save the output
  383. output = EvalOutput(
  384. instance_id=instance.instance_id,
  385. instruction=instruction,
  386. instance=instance.to_dict(), # SWE Bench specific
  387. test_result=test_result,
  388. metadata=metadata,
  389. history=histories,
  390. metrics=metrics,
  391. error=state.last_error if state and state.last_error else None,
  392. )
  393. return output
  394. def filter_dataset(dataset: pd.DataFrame, filter_column: str) -> pd.DataFrame:
  395. file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.toml')
  396. if os.path.exists(file_path):
  397. with open(file_path, 'r') as file:
  398. data = toml.load(file)
  399. if 'selected_ids' in data:
  400. selected_ids = data['selected_ids']
  401. logger.info(
  402. f'Filtering {len(selected_ids)} tasks from "selected_ids"...'
  403. )
  404. subset = dataset[dataset[filter_column].isin(selected_ids)]
  405. logger.info(f'Retained {subset.shape[0]} tasks after filtering')
  406. return subset
  407. return dataset
  408. if __name__ == '__main__':
  409. parser = get_parser()
  410. parser.add_argument(
  411. '--dataset',
  412. type=str,
  413. default='princeton-nlp/SWE-bench',
  414. help='data set to evaluate on, either full-test or lite-test',
  415. )
  416. parser.add_argument(
  417. '--split',
  418. type=str,
  419. default='test',
  420. help='split to evaluate on',
  421. )
  422. args, _ = parser.parse_known_args()
  423. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  424. # so we don't need to manage file uploading to OpenHands's repo
  425. dataset = load_dataset(args.dataset, split=args.split)
  426. logger.info(f'Loaded dataset {args.dataset} with split {args.split}')
  427. swe_bench_tests = filter_dataset(dataset.to_pandas(), 'instance_id')
  428. llm_config = None
  429. if args.llm_config:
  430. llm_config = get_llm_config_arg(args.llm_config)
  431. llm_config.log_completions = True
  432. if llm_config is None:
  433. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  434. details = {}
  435. _agent_cls = openhands.agenthub.Agent.get_cls(args.agent_cls)
  436. dataset_descrption = (
  437. args.dataset.replace('/', '__') + '-' + args.split.replace('/', '__')
  438. )
  439. metadata = make_metadata(
  440. llm_config,
  441. dataset_descrption,
  442. args.agent_cls,
  443. args.max_iterations,
  444. args.eval_note,
  445. args.eval_output_dir,
  446. details=details,
  447. )
  448. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  449. instances = prepare_dataset(swe_bench_tests, output_file, args.eval_n_limit)
  450. if len(instances) > 0 and not isinstance(
  451. instances['PASS_TO_PASS'][instances['PASS_TO_PASS'].index[0]], str
  452. ):
  453. for col in ['PASS_TO_PASS', 'FAIL_TO_PASS']:
  454. instances[col] = instances[col].apply(lambda x: str(x))
  455. run_evaluation(
  456. instances,
  457. metadata,
  458. output_file,
  459. args.eval_num_workers,
  460. process_instance,
  461. timeout_seconds=120 * 60, # 2 hour PER instance should be more than enough
  462. )