run_infer.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import asyncio
  2. import functools
  3. import os
  4. from typing import Any
  5. import pandas as pd
  6. from datasets import load_dataset
  7. from evaluation.benchmarks.mint.datatypes import TaskState
  8. from evaluation.benchmarks.mint.env import SimplifiedEnv
  9. from evaluation.benchmarks.mint.prompts import ToolPromptTemplate
  10. from evaluation.benchmarks.mint.tasks import Task
  11. from evaluation.utils.shared import (
  12. EvalMetadata,
  13. EvalOutput,
  14. compatibility_for_eval_history_pairs,
  15. make_metadata,
  16. prepare_dataset,
  17. reset_logger_for_multiprocessing,
  18. run_evaluation,
  19. )
  20. from openhands.controller.state.state import State
  21. from openhands.core.config import (
  22. AppConfig,
  23. SandboxConfig,
  24. get_llm_config_arg,
  25. get_parser,
  26. )
  27. from openhands.core.logger import openhands_logger as logger
  28. from openhands.core.main import create_runtime, run_controller
  29. from openhands.events.action import (
  30. Action,
  31. CmdRunAction,
  32. MessageAction,
  33. )
  34. from openhands.events.observation import CmdOutputObservation
  35. from openhands.runtime.base import Runtime
  36. from openhands.utils.async_utils import call_async_from_sync
  37. def codeact_user_response_mint(state: State, task: Task, task_config: dict[str, int]):
  38. logger.info(f'Gold reference: {task.reference}')
  39. logger.info(f'Task config: {task_config}')
  40. env = SimplifiedEnv(
  41. agent_state=state,
  42. task=task,
  43. task_config=task_config,
  44. )
  45. last_action = next(
  46. (event for event in reversed(state.history) if isinstance(event, Action)),
  47. None,
  48. )
  49. result_state: TaskState = env.step(last_action.message or '')
  50. state.extra_data['task_state'] = result_state
  51. if not result_state.latest_output:
  52. # Task is finished
  53. msg = '/exit'
  54. else:
  55. msg = result_state.latest_output['content']
  56. logger.info('User response:' + msg)
  57. return msg
  58. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  59. 'CodeActAgent': codeact_user_response_mint,
  60. }
  61. AGENT_CLS_TO_INST_SUFFIX = {
  62. 'CodeActAgent': 'IMPORTANT: When your answer is confirmed by the user to be correct, you can use the "finish" tool to finish the interaction.\n'
  63. }
  64. with open(os.path.join(os.path.dirname(__file__), 'requirements.txt'), 'r') as f:
  65. MINT_DEPENDENCIES = f.read().splitlines()
  66. def load_incontext_example(task_name: str, with_tool: bool = True):
  67. assert with_tool, 'NOT with_tool is not supported yet'
  68. subset = {
  69. 'gsm8k': 'reasoning',
  70. 'math': 'reasoning',
  71. 'mmlu': 'reasoning',
  72. 'theoremqa': 'reasoning',
  73. 'mbpp': 'mbpp',
  74. 'humaneval': 'humaneval',
  75. }[task_name]
  76. with open(
  77. os.path.join(
  78. os.path.dirname(__file__),
  79. 'tasks',
  80. 'in_context_examples',
  81. subset,
  82. 'with_tool.txt',
  83. ),
  84. 'r',
  85. ) as f:
  86. return f.read()
  87. def get_config(
  88. metadata: EvalMetadata,
  89. ) -> AppConfig:
  90. config = AppConfig(
  91. default_agent=metadata.agent_class,
  92. run_as_openhands=False,
  93. runtime='eventstream',
  94. max_iterations=metadata.max_iterations,
  95. sandbox=SandboxConfig(
  96. base_container_image='xingyaoww/od-eval-mint:v1.0',
  97. enable_auto_lint=True,
  98. use_host_network=False,
  99. runtime_extra_deps=f'$OH_INTERPRETER_PATH -m pip install {" ".join(MINT_DEPENDENCIES)}',
  100. ),
  101. # do not mount workspace
  102. workspace_base=None,
  103. workspace_mount_path=None,
  104. )
  105. config.set_llm_config(metadata.llm_config)
  106. return config
  107. def initialize_runtime(runtime: Runtime):
  108. """Initialize the runtime for the agent.
  109. This function is called before the runtime is used to run the agent.
  110. """
  111. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  112. obs: CmdOutputObservation
  113. # Set instance id
  114. action = CmdRunAction(command='mkdir -p /workspace')
  115. logger.info(action, extra={'msg_type': 'ACTION'})
  116. obs = runtime.run_action(action)
  117. assert obs.exit_code == 0
  118. action = CmdRunAction(command='cd /workspace')
  119. logger.info(action, extra={'msg_type': 'ACTION'})
  120. obs = runtime.run_action(action)
  121. assert obs.exit_code == 0
  122. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  123. def process_instance(
  124. instance: Any,
  125. metadata: EvalMetadata,
  126. reset_logger: bool = True,
  127. ):
  128. config = get_config(metadata)
  129. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  130. if reset_logger:
  131. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  132. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  133. else:
  134. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  135. # Prepare instruction
  136. assert metadata.details is not None
  137. instruction = ToolPromptTemplate(use_tool=True)(
  138. max_total_steps=metadata.max_iterations,
  139. max_propose_solution=metadata.details['max_propose_solution'],
  140. in_context_example=instance.in_context_example,
  141. task_prompt='Task:\n' + instance.prompt,
  142. )
  143. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you or provide the concise RESULT inside <solution> tag AND NEVER ASK FOR HUMAN HELP.\n'
  144. # NOTE: You can actually set slightly different instruction for different agents
  145. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  146. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  147. fake_user_response_fn = functools.partial(
  148. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[metadata.agent_class],
  149. task=instance,
  150. task_config={
  151. 'max_iterations': metadata.max_iterations,
  152. 'max_propose_solution': metadata.details['max_propose_solution'],
  153. },
  154. )
  155. runtime = create_runtime(config)
  156. call_async_from_sync(runtime.connect)
  157. initialize_runtime(runtime)
  158. state: State | None = asyncio.run(
  159. run_controller(
  160. config=config,
  161. initial_user_action=MessageAction(content=instruction),
  162. runtime=runtime,
  163. fake_user_response_fn=fake_user_response_fn,
  164. )
  165. )
  166. if state is None:
  167. raise ValueError('State should not be None.')
  168. task_state = None
  169. if 'task_state' in state.extra_data:
  170. task_state = state.extra_data['task_state']
  171. logger.info('Task state: ' + str(task_state.to_dict()))
  172. metrics = state.metrics.get() if state.metrics else None
  173. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  174. # for compatibility with the existing output format, we can remake the pairs here
  175. # remove when it becomes unnecessary
  176. histories = compatibility_for_eval_history_pairs(state.history)
  177. # Save the output
  178. output = EvalOutput(
  179. instance_id=instance.instance_id,
  180. instance=instance.to_dict(),
  181. instruction=instruction,
  182. metadata=metadata,
  183. history=histories,
  184. metrics=metrics,
  185. error=state.last_error if state and state.last_error else None,
  186. test_result={
  187. 'success': task_state.success if task_state else False,
  188. },
  189. )
  190. return output
  191. if __name__ == '__main__':
  192. parser = get_parser()
  193. SUBSETS = [
  194. # Eurus subset: https://arxiv.org/abs/2404.02078
  195. 'math',
  196. # 'gsm8k',
  197. 'mmlu',
  198. 'theoremqa',
  199. 'mbpp',
  200. 'humaneval',
  201. ]
  202. parser.add_argument(
  203. '--subset',
  204. default='all',
  205. choices=SUBSETS + ['all'],
  206. type=str,
  207. help='subset of the dataset to be used',
  208. )
  209. parser.add_argument(
  210. '--max-propose-solution',
  211. default=2,
  212. type=int,
  213. help='maximum number of times the agent can propose a solution',
  214. )
  215. args, _ = parser.parse_known_args()
  216. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  217. # so we don't need to manage file uploading to OpenHands's repo
  218. if args.subset == 'all':
  219. subsets = SUBSETS
  220. else:
  221. subsets = [args.subset]
  222. dataset_dfs = []
  223. for subset in subsets:
  224. in_context_example = load_incontext_example(subset)
  225. _cur_dataset = load_dataset(
  226. 'ryanhoangt/xingyaoww-mint-bench', name=subset, split='test'
  227. )
  228. logger.info(f'Loaded MINT - {subset} subset')
  229. _df = _cur_dataset.to_pandas().rename(columns={'id': 'instance_id'})
  230. _df['instance_id'] = _df['instance_id'].apply(lambda x: f'{subset}/{x}') # noqa
  231. _df['in_context_example'] = in_context_example
  232. dataset_dfs.append(_df)
  233. logger.info(f'Loaded {len(_df)} instances for subset: {subset}')
  234. dataset_df = pd.concat(dataset_dfs)
  235. logger.info(f'Loaded {len(dataset_df)} instances for subset: {subsets}')
  236. llm_config = None
  237. if args.llm_config:
  238. llm_config = get_llm_config_arg(args.llm_config)
  239. if llm_config is None:
  240. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  241. metadata = make_metadata(
  242. llm_config,
  243. f'MINT-{args.subset}',
  244. args.agent_cls,
  245. args.max_iterations,
  246. args.eval_note,
  247. args.eval_output_dir,
  248. details={'max_propose_solution': args.max_propose_solution},
  249. )
  250. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  251. instances = prepare_dataset(dataset_df, output_file, args.eval_n_limit)
  252. run_evaluation(
  253. instances, metadata, output_file, args.eval_num_workers, process_instance
  254. )