run_infer.py 13 KB

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