run_infer.py 9.0 KB

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