run_infer.py 9.3 KB

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