run_infer.py 11 KB

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