run_infer.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import asyncio
  2. import copy
  3. import os
  4. import tempfile
  5. from typing import Any
  6. import pandas as pd
  7. from datasets import load_dataset
  8. from evaluation.benchmarks.aider_bench.helper import (
  9. FAKE_RESPONSES,
  10. INST_SUFFIXES,
  11. INSTRUCTIONS_ADDENDUM,
  12. )
  13. from evaluation.utils.shared import (
  14. EvalMetadata,
  15. EvalOutput,
  16. compatibility_for_eval_history_pairs,
  17. make_metadata,
  18. prepare_dataset,
  19. reset_logger_for_multiprocessing,
  20. run_evaluation,
  21. )
  22. from openhands.controller.state.state import State
  23. from openhands.core.config import (
  24. AppConfig,
  25. SandboxConfig,
  26. get_llm_config_arg,
  27. load_from_toml,
  28. parse_arguments,
  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
  34. from openhands.runtime.base import Runtime
  35. from openhands.utils.async_utils import call_async_from_sync
  36. # Configure visibility of unit tests to the Agent.
  37. USE_UNIT_TESTS = os.environ.get('USE_UNIT_TESTS', 'false').lower() == 'true'
  38. SKIP_NUM = os.environ.get('SKIP_NUM')
  39. SKIP_NUM = (
  40. int(SKIP_NUM) if SKIP_NUM and SKIP_NUM.isdigit() and int(SKIP_NUM) >= 0 else None
  41. )
  42. def get_config(
  43. metadata: EvalMetadata,
  44. ) -> AppConfig:
  45. config = AppConfig(
  46. default_agent=metadata.agent_class,
  47. run_as_openhands=False,
  48. runtime=os.environ.get('RUNTIME', 'eventstream'),
  49. max_iterations=metadata.max_iterations,
  50. sandbox=SandboxConfig(
  51. base_container_image='python:3.11-bookworm',
  52. enable_auto_lint=True,
  53. use_host_network=False,
  54. timeout=100,
  55. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  56. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  57. keep_runtime_alive=False,
  58. remote_runtime_init_timeout=1800,
  59. ),
  60. # do not mount workspace
  61. workspace_base=None,
  62. workspace_mount_path=None,
  63. )
  64. config.set_llm_config(metadata.llm_config)
  65. # copy 'draft_editor' config if exists
  66. config_copy = copy.deepcopy(config)
  67. load_from_toml(config_copy)
  68. if 'draft_editor' in config_copy.llms:
  69. config.set_llm_config(config_copy.llms['draft_editor'], 'draft_editor')
  70. return config
  71. def initialize_runtime(
  72. runtime: Runtime,
  73. instance: pd.Series,
  74. ):
  75. """Initialize the runtime for the agent.
  76. This function is called before the runtime is used to run the agent.
  77. """
  78. logger.info(f"\n{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}\n")
  79. obs: CmdOutputObservation
  80. # Set instance id
  81. action = CmdRunAction(command='mkdir -p /workspace')
  82. logger.info(action, extra={'msg_type': 'ACTION'})
  83. obs = runtime.run_action(action)
  84. assert obs.exit_code == 0
  85. action = CmdRunAction(command='cd /workspace')
  86. logger.info(action, extra={'msg_type': 'ACTION'})
  87. obs = runtime.run_action(action)
  88. assert obs.exit_code == 0
  89. with tempfile.TemporaryDirectory() as tmpdir:
  90. file_path = os.path.join(tmpdir, f'{instance.instance_name}.py')
  91. with open(file_path, 'w') as f:
  92. f.write(instance.signature)
  93. runtime.copy_to(
  94. file_path,
  95. '/workspace',
  96. )
  97. if USE_UNIT_TESTS:
  98. file_path = os.path.join(tmpdir, f'{instance.instance_name}_test.py')
  99. with open(file_path, 'w') as f:
  100. f.write(instance.test)
  101. runtime.copy_to(
  102. file_path,
  103. '/workspace',
  104. )
  105. logger.info(f"\n{'-' * 50} END Runtime Initialization Fn {'-' * 50}\n")
  106. def complete_runtime(
  107. runtime: Runtime,
  108. instance: pd.Series,
  109. ) -> dict[str, Any]:
  110. """Complete the runtime for the agent.
  111. This function is called before the runtime is used to run the agent.
  112. If you need to do something in the sandbox to get the correctness metric after
  113. the agent has run, modify this function.
  114. """
  115. logger.info(f"\n{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}\n")
  116. obs: CmdOutputObservation
  117. # Rewriting the test file to ignore any changes Agent may have made.
  118. script_name = f'{instance.instance_name}_test.py'
  119. with tempfile.TemporaryDirectory() as tmpdir:
  120. file_path = os.path.join(tmpdir, script_name)
  121. with open(file_path, 'w') as f:
  122. f.write(instance.test)
  123. runtime.copy_to(
  124. file_path,
  125. '/workspace',
  126. )
  127. logger.info(f'Running test file: {script_name}')
  128. action = CmdRunAction(
  129. command=f'python3 -m unittest {script_name}',
  130. keep_prompt=False,
  131. )
  132. logger.info(action, extra={'msg_type': 'ACTION'})
  133. obs = runtime.run_action(action)
  134. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  135. exit_code = 1
  136. if isinstance(obs, CmdOutputObservation):
  137. exit_code = obs.exit_code
  138. logger.info(f"\n{'-' * 50} END Runtime Completion Fn {'-' * 50}\n")
  139. runtime.close()
  140. return {
  141. 'test_output': obs.content,
  142. 'exit_code': exit_code,
  143. }
  144. def process_instance(
  145. instance: pd.Series,
  146. metadata: EvalMetadata,
  147. reset_logger: bool = True,
  148. ) -> EvalOutput:
  149. config = get_config(metadata)
  150. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  151. if reset_logger:
  152. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  153. reset_logger_for_multiprocessing(logger, str(instance.instance_id), log_dir)
  154. else:
  155. logger.info(
  156. f'\nStarting evaluation for instance {str(instance.instance_id)}.\n'
  157. )
  158. # =============================================
  159. # build instruction
  160. # =============================================
  161. # Prepare instruction
  162. logger.info(instance)
  163. instruction = instance.instruction
  164. instruction += INSTRUCTIONS_ADDENDUM.format(
  165. signature_file=f'{instance.instance_name}.py',
  166. )
  167. if USE_UNIT_TESTS:
  168. logger.info(
  169. f'\nInstruction to run test_file: {instance.instance_name}_test.py\n'
  170. )
  171. instruction += (
  172. f'Use `python -m unittest {instance.instance_name}_test.py` to run the test_file '
  173. 'and verify the correctness of your solution. DO NOT EDIT the test file.\n\n'
  174. )
  175. instruction += (
  176. 'IMPORTANT: You should ONLY interact with the environment provided '
  177. 'to you AND NEVER ASK FOR HUMAN HELP.\n'
  178. )
  179. # NOTE: You can actually set slightly different instruction for different agents
  180. instruction += INST_SUFFIXES[metadata.agent_class]
  181. # =============================================
  182. # create sandbox and run the agent
  183. # =============================================
  184. runtime: Runtime = create_runtime(config)
  185. call_async_from_sync(runtime.connect)
  186. initialize_runtime(runtime, instance=instance)
  187. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  188. state: State | None = asyncio.run(
  189. run_controller(
  190. config=config,
  191. initial_user_action=MessageAction(content=instruction),
  192. runtime=runtime,
  193. fake_user_response_fn=FAKE_RESPONSES[metadata.agent_class],
  194. )
  195. )
  196. if state is None:
  197. raise ValueError('State should not be None.')
  198. # # =============================================
  199. # # result evaluation
  200. # # =============================================
  201. return_val = complete_runtime(runtime, instance)
  202. exit_code = return_val['exit_code']
  203. test_output = return_val['test_output']
  204. errors = []
  205. test_cases = None
  206. if test_output.find('SyntaxError') != -1:
  207. errors += 'SyntaxError'
  208. elif test_output.find('IndentationError') != -1:
  209. errors += 'IndentationError'
  210. else:
  211. test_cases = test_output[: test_output.find('\r')]
  212. test_result = {
  213. 'exit_code': exit_code,
  214. 'test_cases': test_cases,
  215. 'errors': errors,
  216. }
  217. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  218. # for compatibility with the existing output format, we can remake the pairs here
  219. # remove when it becomes unnecessary
  220. histories = compatibility_for_eval_history_pairs(state.history)
  221. metrics = state.metrics.get() if state.metrics else None
  222. # Save the output
  223. output = EvalOutput(
  224. instance_id=str(instance.instance_id),
  225. instance=instance.to_dict(),
  226. instruction=instruction,
  227. metadata=metadata,
  228. history=histories,
  229. metrics=metrics,
  230. error=state.last_error if state and state.last_error else None,
  231. test_result=test_result,
  232. )
  233. return output
  234. if __name__ == '__main__':
  235. args = parse_arguments()
  236. dataset = load_dataset('RajMaheshwari/Exercism-Python')
  237. aider_bench_tests = dataset['train'].to_pandas()
  238. llm_config = None
  239. if args.llm_config:
  240. llm_config = get_llm_config_arg(args.llm_config)
  241. if llm_config is None:
  242. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  243. metadata = make_metadata(
  244. llm_config,
  245. 'AiderBench',
  246. args.agent_cls,
  247. args.max_iterations,
  248. args.eval_note,
  249. args.eval_output_dir,
  250. )
  251. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  252. # Parse dataset IDs if provided
  253. eval_ids = None
  254. if args.eval_ids:
  255. eval_ids = str(args.eval_ids).split(',')
  256. logger.info(f'\nUsing specific dataset IDs: {eval_ids}\n')
  257. instances = prepare_dataset(
  258. aider_bench_tests,
  259. output_file,
  260. args.eval_n_limit,
  261. eval_ids=eval_ids,
  262. skip_num=SKIP_NUM,
  263. )
  264. run_evaluation(
  265. instances,
  266. metadata,
  267. output_file,
  268. args.eval_num_workers,
  269. process_instance,
  270. )