run_infer.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import asyncio
  2. import json
  3. import os
  4. from typing import Any
  5. import browsergym.miniwob # noqa F401 register miniwob tasks as gym environments
  6. import gymnasium as gym
  7. import pandas as pd
  8. from evaluation.utils.shared import (
  9. EvalMetadata,
  10. EvalOutput,
  11. make_metadata,
  12. prepare_dataset,
  13. reset_logger_for_multiprocessing,
  14. run_evaluation,
  15. )
  16. from openhands.controller.state.state import State
  17. from openhands.core.config import (
  18. AppConfig,
  19. SandboxConfig,
  20. get_llm_config_arg,
  21. parse_arguments,
  22. )
  23. from openhands.core.logger import openhands_logger as logger
  24. from openhands.core.main import create_runtime, run_controller
  25. from openhands.events.action import (
  26. BrowseInteractiveAction,
  27. CmdRunAction,
  28. MessageAction,
  29. )
  30. from openhands.events.observation import CmdOutputObservation
  31. from openhands.runtime.browser.browser_env import (
  32. BROWSER_EVAL_GET_GOAL_ACTION,
  33. BROWSER_EVAL_GET_REWARDS_ACTION,
  34. )
  35. from openhands.runtime.runtime import Runtime
  36. SUPPORTED_AGENT_CLS = {'BrowsingAgent'}
  37. def get_config(
  38. metadata: EvalMetadata,
  39. env_id: str,
  40. ) -> AppConfig:
  41. config = AppConfig(
  42. default_agent=metadata.agent_class,
  43. run_as_openhands=False,
  44. runtime='eventstream',
  45. max_iterations=metadata.max_iterations,
  46. sandbox=SandboxConfig(
  47. container_image='xingyaoww/od-eval-miniwob:v1.0',
  48. enable_auto_lint=True,
  49. use_host_network=False,
  50. browsergym_eval_env=env_id,
  51. ),
  52. # do not mount workspace
  53. workspace_base=None,
  54. workspace_mount_path=None,
  55. )
  56. config.set_llm_config(metadata.llm_config)
  57. return config
  58. async def initialize_runtime(
  59. runtime: Runtime,
  60. ) -> str:
  61. """Initialize the runtime for the agent.
  62. This function is called before the runtime is used to run the agent.
  63. """
  64. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  65. obs: CmdOutputObservation
  66. # Set instance id
  67. action = CmdRunAction(command='mkdir -p /workspace')
  68. logger.info(action, extra={'msg_type': 'ACTION'})
  69. obs = await runtime.run_action(action)
  70. assert obs.exit_code == 0
  71. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  72. logger.info(action, extra={'msg_type': 'ACTION'})
  73. obs = await runtime.run_action(action)
  74. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  75. goal = obs.content
  76. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  77. return goal
  78. async def complete_runtime(
  79. runtime: Runtime,
  80. ) -> dict[str, Any]:
  81. """Complete the runtime for the agent.
  82. This function is called before the runtime is used to run the agent.
  83. If you need to do something in the sandbox to get the correctness metric after
  84. the agent has run, modify this function.
  85. """
  86. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  87. obs: CmdOutputObservation
  88. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  89. logger.info(action, extra={'msg_type': 'ACTION'})
  90. obs = await runtime.run_action(action)
  91. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  92. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  93. return {
  94. 'rewards': json.loads(obs.content),
  95. }
  96. async def process_instance(
  97. instance: pd.Series,
  98. metadata: EvalMetadata,
  99. reset_logger: bool = True,
  100. ) -> EvalOutput:
  101. env_id = instance.id
  102. config = get_config(metadata, env_id)
  103. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  104. if reset_logger:
  105. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  106. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  107. else:
  108. logger.info(f'Starting evaluation for instance {env_id}.')
  109. runtime = await create_runtime(config, sid=env_id)
  110. task_str = await initialize_runtime(runtime)
  111. state: State | None = asyncio.run(
  112. run_controller(
  113. config=config,
  114. task_str=task_str, # take output from initialize_runtime
  115. runtime=runtime,
  116. )
  117. )
  118. # ======= Attempt to evaluate the agent's environment impact =======
  119. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  120. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  121. if state is None:
  122. raise ValueError('State should not be None.')
  123. metrics = state.metrics.get() if state.metrics else None
  124. # Instruction is the first message from the USER
  125. instruction = ''
  126. for event in state.history.get_events():
  127. if isinstance(event, MessageAction):
  128. instruction = event.content
  129. break
  130. return_val = await complete_runtime(runtime)
  131. logger.info(f'Return value from complete_runtime: {return_val}')
  132. reward = max(return_val['rewards'])
  133. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  134. # for compatibility with the existing output format, we can remake the pairs here
  135. # remove when it becomes unnecessary
  136. histories = state.history.compatibility_for_eval_history_pairs()
  137. # Save the output
  138. output = EvalOutput(
  139. instance_id=env_id,
  140. instruction=instruction,
  141. metadata=metadata,
  142. history=histories,
  143. metrics=metrics,
  144. error=state.last_error if state and state.last_error else None,
  145. test_result={
  146. 'reward': reward,
  147. },
  148. )
  149. return output
  150. if __name__ == '__main__':
  151. args = parse_arguments()
  152. dataset = pd.DataFrame(
  153. {
  154. 'instance_id': [
  155. id
  156. for id in gym.envs.registry.keys()
  157. if id.startswith('browsergym/miniwob')
  158. ]
  159. }
  160. )
  161. llm_config = None
  162. if args.llm_config:
  163. llm_config = get_llm_config_arg(args.llm_config)
  164. if llm_config is None:
  165. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  166. metadata = make_metadata(
  167. llm_config,
  168. 'miniwob',
  169. args.agent_cls,
  170. args.max_iterations,
  171. args.eval_note,
  172. args.eval_output_dir,
  173. )
  174. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  175. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  176. asyncio.run(
  177. run_evaluation(
  178. instances, metadata, output_file, args.eval_num_workers, process_instance
  179. )
  180. )