run_infer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import asyncio
  2. import os
  3. import re
  4. import tempfile
  5. from typing import Any
  6. import pandas as pd
  7. from datasets import load_dataset
  8. from evaluation.agent_bench.helper import (
  9. FAKE_RESPONSES,
  10. INST_SUFFIXES,
  11. compare_results,
  12. create_sh_file,
  13. )
  14. from evaluation.utils.shared import (
  15. EvalMetadata,
  16. EvalOutput,
  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. 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 AgentFinishAction, CmdRunAction, MessageAction
  32. from openhands.events.observation import CmdOutputObservation
  33. from openhands.runtime.runtime import Runtime
  34. def get_config(
  35. metadata: EvalMetadata,
  36. ) -> AppConfig:
  37. config = AppConfig(
  38. default_agent=metadata.agent_class,
  39. run_as_openhands=False,
  40. runtime='eventstream',
  41. max_iterations=metadata.max_iterations,
  42. sandbox=SandboxConfig(
  43. container_image='python:3.11-bookworm',
  44. enable_auto_lint=True,
  45. use_host_network=False,
  46. ),
  47. # do not mount workspace
  48. workspace_base=None,
  49. workspace_mount_path=None,
  50. )
  51. config.set_llm_config(metadata.llm_config)
  52. return config
  53. async def initialize_runtime(
  54. runtime: Runtime,
  55. instance: pd.Series, # this argument is not required
  56. ):
  57. """Initialize the runtime for the agent.
  58. This function is called before the runtime is used to run the agent.
  59. """
  60. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  61. obs: CmdOutputObservation
  62. # Set instance id
  63. action = CmdRunAction(command='mkdir -p /workspace')
  64. logger.info(action, extra={'msg_type': 'ACTION'})
  65. obs = await runtime.run_action(action)
  66. assert obs.exit_code == 0
  67. action = CmdRunAction(command='cd /workspace')
  68. logger.info(action, extra={'msg_type': 'ACTION'})
  69. obs = await runtime.run_action(action)
  70. assert obs.exit_code == 0
  71. init_cmd = instance.init
  72. if init_cmd is not None:
  73. script_name = f'{instance.instance_id}_init.sh'
  74. with tempfile.TemporaryDirectory() as tmpdir:
  75. host_script_path = os.path.join(tmpdir, script_name)
  76. create_sh_file(host_script_path, init_cmd)
  77. await runtime.copy_to(
  78. host_script_path,
  79. '/workspace',
  80. )
  81. logger.info(f'Running init script: {script_name}')
  82. action = CmdRunAction(command=f'chmod +x ./{script_name} && ./{script_name}')
  83. logger.info(action, extra={'msg_type': 'ACTION'})
  84. obs = await runtime.run_action(action)
  85. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  86. assert obs.exit_code == 0
  87. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  88. async def complete_runtime(
  89. runtime: Runtime,
  90. instance: pd.Series, # this argument is not required, but it is used to get the workspace_dir_name
  91. ) -> dict[str, Any]:
  92. """Complete the runtime for the agent.
  93. This function is called before the runtime is used to run the agent.
  94. If you need to do something in the sandbox to get the correctness metric after
  95. the agent has run, modify this function.
  96. """
  97. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  98. obs: CmdOutputObservation
  99. agent_answer = None
  100. get_agent_result_cmd = instance.get_agent_result
  101. if get_agent_result_cmd is not None:
  102. script_name = 'get_agent_result.sh'
  103. with tempfile.TemporaryDirectory() as tmpdir:
  104. host_script_path = os.path.join(tmpdir, script_name)
  105. create_sh_file(host_script_path, get_agent_result_cmd)
  106. await runtime.copy_to(
  107. host_script_path,
  108. '/workspace',
  109. )
  110. logger.info(f'Running get agent result cmd: {script_name}')
  111. action = CmdRunAction(
  112. command=f'chmod +x ./{script_name} && ./{script_name}',
  113. keep_prompt=False,
  114. )
  115. logger.info(action, extra={'msg_type': 'ACTION'})
  116. obs = await runtime.run_action(action)
  117. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  118. assert obs.exit_code == 0
  119. agent_answer = obs.content
  120. # IF the agent answer is not found, retrieve it from the history
  121. # We wait until the controller finishes
  122. final_ans = None
  123. if instance.ground_truth is not None:
  124. final_ans = instance.ground_truth
  125. else:
  126. get_ground_truth_cmd = instance.get_ground_truth
  127. if get_ground_truth_cmd is not None:
  128. script_name = 'get_ground_truth.sh'
  129. with tempfile.TemporaryDirectory() as tmpdir:
  130. host_script_path = os.path.join(tmpdir, script_name)
  131. create_sh_file(host_script_path, get_ground_truth_cmd)
  132. await runtime.copy_to(
  133. host_script_path,
  134. '/workspace',
  135. )
  136. logger.info(f'Running get ground truth cmd: {script_name}')
  137. action = CmdRunAction(
  138. command=f'chmod +x ./{script_name} && ./{script_name}',
  139. keep_prompt=False,
  140. )
  141. logger.info(action, extra={'msg_type': 'ACTION'})
  142. obs = await runtime.run_action(action)
  143. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  144. final_ans = obs.content
  145. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  146. return {
  147. 'final_ans': final_ans,
  148. 'agent_answer': agent_answer,
  149. }
  150. async def process_instance(
  151. instance: pd.Series,
  152. metadata: EvalMetadata,
  153. reset_logger: bool = True,
  154. ) -> EvalOutput:
  155. config = get_config(metadata)
  156. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  157. if reset_logger:
  158. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  159. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  160. else:
  161. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  162. # =============================================
  163. # build instruction
  164. # =============================================
  165. # Prepare instruction
  166. instruction = (
  167. f'Please fix the following issue.\n'
  168. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  169. 'Please encapsulate your final answer (answer ONLY) within <solution> and </solution>.\n'
  170. 'For example: The answer to the question is <solution> 42 </solution>.\n'
  171. '# Problem \n'
  172. f'{instance.description}\n\n'
  173. )
  174. instruction += (
  175. 'IMPORTANT: You should ONLY interact with the environment provided '
  176. 'to you AND NEVER ASK FOR HUMAN HELP.\n'
  177. )
  178. # NOTE: You can actually set slightly different instruction for different agents
  179. instruction += INST_SUFFIXES[metadata.agent_class]
  180. # =============================================
  181. # create sandbox and run the agent
  182. # =============================================
  183. runtime: Runtime = await create_runtime(config, sid=instance.instance_id)
  184. await initialize_runtime(runtime, instance=instance)
  185. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  186. state: State | None = await run_controller(
  187. config=config,
  188. task_str=instruction,
  189. runtime=runtime,
  190. fake_user_response_fn=FAKE_RESPONSES[metadata.agent_class],
  191. )
  192. if state is None:
  193. raise ValueError('State should not be None.')
  194. # =============================================
  195. # result evaluation
  196. # =============================================
  197. return_val = await complete_runtime(runtime, instance)
  198. agent_answer = return_val['agent_answer']
  199. final_ans = return_val['final_ans']
  200. # If the agent answer is not found, retrieve it from the history
  201. if agent_answer is None:
  202. agent_answer = ''
  203. logger.info('Retrieving agent answer from history.')
  204. raw_ans = ''
  205. # retrieve the last agent message or thought
  206. for event in state.history.get_events(reverse=True):
  207. if event.source == 'agent':
  208. if isinstance(event, AgentFinishAction):
  209. raw_ans = event.thought
  210. break
  211. elif isinstance(event, MessageAction):
  212. raw_ans = event.content
  213. break
  214. elif isinstance(event, CmdRunAction):
  215. raw_ans = event.thought
  216. break
  217. # parse the answer for a solution tag
  218. agent_answer = re.findall(r'<solution>(.*?)</solution>', raw_ans, re.DOTALL)
  219. if len(agent_answer) == 0:
  220. logger.warning(f'Failed to parse model answer: {raw_ans}')
  221. agent_answer = raw_ans
  222. else:
  223. agent_answer = agent_answer[0]
  224. comparison_method = instance.comparison_method
  225. logger.info(
  226. f'Final message: {agent_answer} | Ground truth: {final_ans} | Comparison method: {comparison_method}'
  227. )
  228. test_result = compare_results(comparison_method, agent_answer, final_ans)
  229. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  230. # for compatibility with the existing output format, we can remake the pairs here
  231. # remove when it becomes unnecessary
  232. histories = state.history.compatibility_for_eval_history_pairs()
  233. metrics = state.metrics.get() if state.metrics else None
  234. # Save the output
  235. output = EvalOutput(
  236. instance_id=instance.instance_id,
  237. instance=instance.to_dict(),
  238. instruction=instruction,
  239. metadata=metadata,
  240. history=histories,
  241. metrics=metrics,
  242. error=state.last_error if state and state.last_error else None,
  243. test_result={
  244. 'agent_answer': agent_answer,
  245. 'final_answer': final_ans,
  246. 'check_method': comparison_method,
  247. 'result': test_result,
  248. },
  249. )
  250. return output
  251. if __name__ == '__main__':
  252. args = parse_arguments()
  253. dataset = load_dataset('iFurySt/AgentBench')
  254. agent_bench_tests = dataset['osbench'].to_pandas()
  255. llm_config = None
  256. if args.llm_config:
  257. llm_config = get_llm_config_arg(args.llm_config)
  258. if llm_config is None:
  259. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  260. metadata = make_metadata(
  261. llm_config,
  262. 'AgentBench-OS',
  263. args.agent_cls,
  264. args.max_iterations,
  265. args.eval_note,
  266. args.eval_output_dir,
  267. )
  268. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  269. instances = prepare_dataset(agent_bench_tests, output_file, args.eval_n_limit)
  270. asyncio.run(
  271. run_evaluation(
  272. instances, metadata, output_file, args.eval_num_workers, process_instance
  273. )
  274. )