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