run_infer.py 8.1 KB

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