run_infer.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import asyncio
  2. import functools
  3. import json
  4. import os
  5. import tempfile
  6. from typing import Any
  7. import pandas as pd
  8. from datasets import load_dataset
  9. from evaluation.benchmarks.biocoder.utils import BiocoderData
  10. from evaluation.utils.shared import (
  11. EvalMetadata,
  12. EvalOutput,
  13. codeact_user_response,
  14. compatibility_for_eval_history_pairs,
  15. make_metadata,
  16. prepare_dataset,
  17. reset_logger_for_multiprocessing,
  18. run_evaluation,
  19. )
  20. from openhands.controller.state.state import State
  21. from openhands.core.config import (
  22. AppConfig,
  23. SandboxConfig,
  24. get_llm_config_arg,
  25. parse_arguments,
  26. )
  27. from openhands.core.logger import openhands_logger as logger
  28. from openhands.core.main import create_runtime, run_controller
  29. from openhands.events.action import CmdRunAction, MessageAction
  30. from openhands.events.observation import CmdOutputObservation
  31. from openhands.runtime.base import Runtime
  32. from openhands.utils.async_utils import call_async_from_sync
  33. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  34. 'CodeActAgent': functools.partial(
  35. codeact_user_response, encapsulate_solution=True, try_parse=None
  36. ),
  37. }
  38. AGENT_CLS_TO_INST_SUFFIX = {
  39. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please finish the interaction using the "finish" tool.\n'
  40. }
  41. FILE_EXT_MAP = {
  42. 'python': 'py',
  43. 'java': 'java',
  44. 'c': 'c',
  45. 'cpp': 'cpp',
  46. 'javascript': 'js',
  47. 'typescript': 'ts',
  48. }
  49. def get_config(
  50. metadata: EvalMetadata,
  51. ) -> AppConfig:
  52. BIOCODER_BENCH_CONTAINER_IMAGE = 'public.ecr.aws/i5g0m1f6/eval_biocoder:v1.0'
  53. config = AppConfig(
  54. default_agent=metadata.agent_class,
  55. run_as_openhands=False,
  56. runtime='eventstream',
  57. max_iterations=metadata.max_iterations,
  58. sandbox=SandboxConfig(
  59. base_container_image=BIOCODER_BENCH_CONTAINER_IMAGE,
  60. enable_auto_lint=True,
  61. use_host_network=False,
  62. ),
  63. # do not mount workspace
  64. workspace_base=None,
  65. workspace_mount_path=None,
  66. )
  67. config.set_llm_config(metadata.llm_config)
  68. return config
  69. def initialize_runtime(
  70. runtime: Runtime,
  71. instance: BiocoderData, # this argument is not required
  72. ):
  73. """Initialize the runtime for the agent.
  74. This function is called before the runtime is used to run the agent.
  75. """
  76. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  77. obs: CmdOutputObservation
  78. file_ext = FILE_EXT_MAP[instance.language.lower()]
  79. action = CmdRunAction(command='mkdir -p /workspace && mkdir -p /testing_files')
  80. logger.info(action, extra={'msg_type': 'ACTION'})
  81. obs = runtime.run_action(action)
  82. assert obs.exit_code == 0
  83. with tempfile.TemporaryDirectory() as tmpdir:
  84. context_path = os.path.join(tmpdir, 'context.' + file_ext)
  85. with open(context_path, 'w') as f:
  86. f.write(instance.contextCode)
  87. runtime.copy_to(context_path, '/testing_files')
  88. golden_path = os.path.join(tmpdir, 'golden.' + file_ext)
  89. with open(golden_path, 'w') as f:
  90. f.write(instance.goldenCode)
  91. runtime.copy_to(golden_path, '/testing_files')
  92. testcase_json = {
  93. 'test_case_id': instance.test_case_id,
  94. 'num_cases': 1000,
  95. 'language': instance.language.lower(),
  96. }
  97. testcase_path = os.path.join(tmpdir, 'testcase_biocoder.json')
  98. with open(testcase_path, 'w') as f:
  99. f.write(json.dumps(testcase_json, indent=4))
  100. runtime.copy_to(testcase_path, '/testing_files')
  101. # setup paths
  102. remove_code_script = os.path.join(
  103. os.path.dirname(__file__), 'scripts', 'setup', 'remove_code.py'
  104. )
  105. runtime.copy_to(remove_code_script, '/testing_files')
  106. action = CmdRunAction(command='cd /workspace')
  107. logger.info(action, extra={'msg_type': 'ACTION'})
  108. obs = runtime.run_action(action)
  109. assert obs.exit_code == 0
  110. # download repository archive
  111. repository_url = f"https://biocoder.lilbillbiscuit.com/repos/{instance.repository.split('/')[1]}.zip"
  112. action = CmdRunAction(command='wget -O repo.zip ' + repository_url)
  113. logger.info(action, extra={'msg_type': 'ACTION'})
  114. obs = runtime.run_action(action)
  115. assert obs.exit_code == 0, f'Failed to download the repository: {obs.content}'
  116. # unzip the repository
  117. action = CmdRunAction(command='unzip -o -q repo.zip && rm repo.zip')
  118. logger.info(action, extra={'msg_type': 'ACTION'})
  119. obs = runtime.run_action(action)
  120. assert obs.exit_code == 0, f'Failed to unzip the repository: {obs.content}'
  121. # chmod 777
  122. action = CmdRunAction(command='chmod -R 777 /workspace')
  123. logger.info(action, extra={'msg_type': 'ACTION'})
  124. obs = runtime.run_action(action)
  125. assert obs.exit_code == 0, f'Failed to chmod the files: {obs.content}'
  126. # remove code for evaluation instance
  127. target_filepath = os.path.join(
  128. '/workspace', instance.repository.split('/')[1], instance.filePath
  129. )
  130. line_start = instance.lineStart
  131. line_end = instance.lineEnd
  132. language = instance.language.lower()
  133. action = CmdRunAction(
  134. command=f'python3 /testing_files/remove_code.py --target_filepath {target_filepath} --line_start {line_start} --line_end {line_end} --language {language}'
  135. )
  136. logger.info(action, extra={'msg_type': 'ACTION'})
  137. obs = runtime.run_action(action)
  138. assert obs.exit_code == 0, f'Failed to remove the code: {obs.content}'
  139. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  140. def complete_runtime(
  141. runtime: Runtime,
  142. instance: pd.Series, # this argument is not required, but it is used to get the workspace_dir_name
  143. ) -> dict[str, Any]:
  144. """Complete the runtime for the agent.
  145. This function is called before the runtime is used to run the agent.
  146. If you need to do something in the sandbox to get the correctness metric after
  147. the agent has run, modify this function.
  148. """
  149. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  150. obs: CmdOutputObservation
  151. test_result = {'result': {}, 'metadata': {}}
  152. copy_changed_code_script = os.path.join(
  153. os.path.dirname(__file__), 'scripts', 'setup', 'copy_changed_code.py'
  154. )
  155. runtime.copy_to(copy_changed_code_script, '/testing_files')
  156. file_ext = FILE_EXT_MAP[instance.language.lower()]
  157. target_filepath = os.path.join(
  158. '/workspace', instance.repository.split('/')[1], instance.filePath
  159. )
  160. generated_path = os.path.join('/testing_files', 'generated.' + file_ext)
  161. action = CmdRunAction(
  162. command=f'python3 /testing_files/copy_changed_code.py --target_filepath {target_filepath} --generated_code_filepath {generated_path} --line_start {instance.lineStart} --include_signature'
  163. )
  164. logger.info(action, extra={'msg_type': 'ACTION'})
  165. obs = runtime.run_action(action)
  166. if obs.exit_code == 0:
  167. test_result['metadata']['1_copy_change_success'] = True
  168. action = CmdRunAction(command=f'cat {generated_path}', keep_prompt=False)
  169. logger.info(action, extra={'msg_type': 'ACTION'})
  170. obs = runtime.run_action(action)
  171. assert obs.exit_code == 0
  172. code = obs.content
  173. test_result['metadata']['1_copy_change_code'] = code
  174. else:
  175. test_result['metadata']['1_copy_change_success'] = False
  176. test_result['metadata']['1_copy_change_code'] = None
  177. action = CmdRunAction(command='cd /testing_files')
  178. logger.info(action, extra={'msg_type': 'ACTION'})
  179. obs = runtime.run_action(action)
  180. assert obs.exit_code == 0
  181. action = CmdRunAction(
  182. command='/home/openhands/mambaforge/bin/mamba run -n test python3 /testing/start_test_openhands.py'
  183. )
  184. logger.info(action, extra={'msg_type': 'ACTION'})
  185. obs = runtime.run_action(action)
  186. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  187. assert obs.exit_code == 0
  188. action = CmdRunAction(
  189. command='cat /testing_files/results_biocoder.json', keep_prompt=False
  190. )
  191. logger.info(action, extra={'msg_type': 'ACTION'})
  192. obs = runtime.run_action(action)
  193. if obs.exit_code == 0:
  194. test_result['metadata']['2_run_test_success'] = True
  195. test_result['metadata']['2_run_test_result'] = str(obs.content)
  196. json_obj = json.loads(obs.content)
  197. test_result['result'] = json_obj['result']
  198. else:
  199. test_result['metadata']['2_run_test_success'] = False
  200. test_result['metadata']['2_run_test_result'] = str(obs.content)
  201. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  202. return test_result
  203. def process_instance(
  204. instance: pd.Series,
  205. metadata: EvalMetadata,
  206. reset_logger: bool = True,
  207. ) -> EvalOutput:
  208. config = get_config(metadata)
  209. instance = BiocoderData(**instance)
  210. print(instance)
  211. instance_id = f'{instance.repository}__{instance.instance_id[:10]}'
  212. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  213. if reset_logger:
  214. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  215. reset_logger_for_multiprocessing(logger, instance_id, log_dir)
  216. else:
  217. logger.info(f'Starting evaluation for instance {instance_id}.')
  218. # Prepare instruction
  219. instruction = (
  220. f'Please complete the function "{instance.signature}" in the file /workspace/{instance.repository.split("/")[1]}/{instance.filePath}.\n'
  221. f'The environment has been set up for you to start working. You may assume all necessary tools are installed.\n'
  222. f'To complete the task, you must directly modify the file and fill in the function, keeping in mind that the function signature is on line {instance.lineStart-1}\n\n'
  223. f'The function should do the following:\n'
  224. f'{instance.promptSummaryOnly}\n\n'
  225. )
  226. instruction += (
  227. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  228. 'You should NOT modify any other files other than the file intended. This means that you should NOT write any test cases.\n'
  229. 'You may need context from other files in the repository to complete this task.'
  230. 'Do NOT add any import statements or change anything else other than the writing the function body.\n'
  231. 'You do not need to run the code to check if it works. \n'
  232. 'Make sure to include proper formatting in Java and Python, including correct braces and/or indentation.\n'
  233. )
  234. # NOTE: You can actually set slightly different instruction for different agents
  235. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  236. runtime = create_runtime(config)
  237. call_async_from_sync(runtime.connect)
  238. initialize_runtime(runtime, instance)
  239. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  240. state: State | None = asyncio.run(
  241. run_controller(
  242. config=config,
  243. initial_user_action=MessageAction(content=instruction),
  244. runtime=runtime,
  245. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  246. metadata.agent_class
  247. ],
  248. )
  249. )
  250. if state is None:
  251. raise ValueError('State should not be None.')
  252. test_result = complete_runtime(runtime, instance)
  253. metrics = state.metrics.get() if state.metrics else None
  254. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  255. # for compatibility with the existing output format, we can remake the pairs here
  256. # remove when it becomes unnecessary
  257. histories = compatibility_for_eval_history_pairs(state.history)
  258. test_result['generated'] = test_result['metadata']['1_copy_change_code']
  259. # Save the output
  260. output = EvalOutput(
  261. instance_id=instance.instance_id,
  262. instance=instance.to_dict(),
  263. instruction=instruction,
  264. metadata=metadata,
  265. history=histories,
  266. metrics=metrics,
  267. error=state.last_error if state and state.last_error else None,
  268. test_result=test_result,
  269. )
  270. return output
  271. if __name__ == '__main__':
  272. args = parse_arguments()
  273. dataset = load_dataset('lilbillbiscuit/biocoder_public')
  274. biocoder_tests = dataset['train'].to_pandas()
  275. biocoder_tests['instance_id'] = biocoder_tests['test_case_id']
  276. llm_config = None
  277. if args.llm_config:
  278. llm_config = get_llm_config_arg(args.llm_config)
  279. if llm_config is None:
  280. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  281. metadata = make_metadata(
  282. llm_config,
  283. 'biocoder',
  284. args.agent_cls,
  285. args.max_iterations,
  286. args.eval_note,
  287. args.eval_output_dir,
  288. )
  289. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  290. instances = prepare_dataset(biocoder_tests, output_file, args.eval_n_limit)
  291. run_evaluation(
  292. instances, metadata, output_file, args.eval_num_workers, process_instance
  293. )