run_infer.py 11 KB

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