run_infer.py 9.4 KB

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