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. base_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. 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 = 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 = 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. 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 = 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. 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. 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 = 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. 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 = 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. 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 = create_runtime(config, sid=instance.instance_id)
  184. 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 = asyncio.run(
  187. run_controller(
  188. config=config,
  189. task_str=instruction,
  190. runtime=runtime,
  191. fake_user_response_fn=FAKE_RESPONSES[metadata.agent_class],
  192. )
  193. )
  194. if state is None:
  195. raise ValueError('State should not be None.')
  196. # =============================================
  197. # result evaluation
  198. # =============================================
  199. return_val = complete_runtime(runtime, instance)
  200. agent_answer = return_val['agent_answer']
  201. final_ans = return_val['final_ans']
  202. # If the agent answer is not found, retrieve it from the history
  203. if agent_answer is None:
  204. agent_answer = ''
  205. logger.info('Retrieving agent answer from history.')
  206. raw_ans = ''
  207. # retrieve the last agent message or thought
  208. for event in state.history.get_events(reverse=True):
  209. if event.source == 'agent':
  210. if isinstance(event, AgentFinishAction):
  211. raw_ans = event.thought
  212. break
  213. elif isinstance(event, MessageAction):
  214. raw_ans = event.content
  215. break
  216. elif isinstance(event, CmdRunAction):
  217. raw_ans = event.thought
  218. break
  219. # parse the answer for a solution tag
  220. agent_answer = re.findall(r'<solution>(.*?)</solution>', raw_ans, re.DOTALL)
  221. if len(agent_answer) == 0:
  222. logger.warning(f'Failed to parse model answer: {raw_ans}')
  223. agent_answer = raw_ans
  224. else:
  225. agent_answer = agent_answer[0]
  226. comparison_method = instance.comparison_method
  227. logger.info(
  228. f'Final message: {agent_answer} | Ground truth: {final_ans} | Comparison method: {comparison_method}'
  229. )
  230. test_result = compare_results(comparison_method, agent_answer, final_ans)
  231. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  232. # for compatibility with the existing output format, we can remake the pairs here
  233. # remove when it becomes unnecessary
  234. histories = state.history.compatibility_for_eval_history_pairs()
  235. metrics = state.metrics.get() if state.metrics else None
  236. # Save the output
  237. output = EvalOutput(
  238. instance_id=instance.instance_id,
  239. instance=instance.to_dict(),
  240. instruction=instruction,
  241. metadata=metadata,
  242. history=histories,
  243. metrics=metrics,
  244. error=state.last_error if state and state.last_error else None,
  245. test_result={
  246. 'agent_answer': agent_answer,
  247. 'final_answer': final_ans,
  248. 'check_method': comparison_method,
  249. 'result': test_result,
  250. },
  251. )
  252. return output
  253. if __name__ == '__main__':
  254. args = parse_arguments()
  255. dataset = load_dataset('iFurySt/AgentBench')
  256. agent_bench_tests = dataset['osbench'].to_pandas()
  257. llm_config = None
  258. if args.llm_config:
  259. llm_config = get_llm_config_arg(args.llm_config)
  260. if llm_config is None:
  261. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  262. metadata = make_metadata(
  263. llm_config,
  264. 'AgentBench-OS',
  265. args.agent_cls,
  266. args.max_iterations,
  267. args.eval_note,
  268. args.eval_output_dir,
  269. )
  270. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  271. instances = prepare_dataset(agent_bench_tests, output_file, args.eval_n_limit)
  272. run_evaluation(
  273. instances, metadata, output_file, args.eval_num_workers, process_instance
  274. )