run_infer.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. codeact_user_response,
  12. compatibility_for_eval_history_pairs,
  13. make_metadata,
  14. prepare_dataset,
  15. reset_logger_for_multiprocessing,
  16. run_evaluation,
  17. update_llm_config_for_completions_logging,
  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. parse_arguments,
  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. BrowseInteractiveAction,
  30. CmdRunAction,
  31. MessageAction,
  32. )
  33. from openhands.events.observation import (
  34. BrowserOutputObservation,
  35. CmdOutputObservation,
  36. )
  37. from openhands.runtime.base import Runtime
  38. from openhands.runtime.browser.browser_env import (
  39. BROWSER_EVAL_GET_GOAL_ACTION,
  40. BROWSER_EVAL_GET_REWARDS_ACTION,
  41. )
  42. from openhands.utils.async_utils import call_async_from_sync
  43. SUPPORTED_AGENT_CLS = {'BrowsingAgent', 'CodeActAgent'}
  44. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  45. 'CodeActAgent': codeact_user_response,
  46. }
  47. def get_config(
  48. metadata: EvalMetadata,
  49. env_id: str,
  50. ) -> AppConfig:
  51. config = AppConfig(
  52. default_agent=metadata.agent_class,
  53. run_as_openhands=False,
  54. runtime=os.environ.get('RUNTIME', 'eventstream'),
  55. max_iterations=metadata.max_iterations,
  56. sandbox=SandboxConfig(
  57. base_container_image='xingyaoww/od-eval-miniwob:v1.0',
  58. enable_auto_lint=True,
  59. use_host_network=False,
  60. browsergym_eval_env=env_id,
  61. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  62. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  63. keep_runtime_alive=False,
  64. timeout=120,
  65. remote_runtime_init_timeout=1800,
  66. ),
  67. # do not mount workspace
  68. workspace_base=None,
  69. workspace_mount_path=None,
  70. )
  71. config.set_llm_config(
  72. update_llm_config_for_completions_logging(
  73. metadata.llm_config, metadata.eval_output_dir, env_id
  74. )
  75. )
  76. return config
  77. def initialize_runtime(
  78. runtime: Runtime,
  79. ) -> tuple[str, BrowserOutputObservation]:
  80. """Initialize the runtime for the agent.
  81. This function is called before the runtime is used to run the agent.
  82. """
  83. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  84. obs: CmdOutputObservation
  85. # Set instance id
  86. action = CmdRunAction(command='mkdir -p /workspace')
  87. logger.info(action, extra={'msg_type': 'ACTION'})
  88. obs = runtime.run_action(action)
  89. assert obs.exit_code == 0
  90. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  91. logger.info(action, extra={'msg_type': 'ACTION'})
  92. obs = runtime.run_action(action)
  93. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  94. goal = obs.content
  95. # Run noop to get the initial browser observation (e.g., the page URL & content)
  96. action = BrowseInteractiveAction(browser_actions='noop(1000)')
  97. logger.info(action, extra={'msg_type': 'ACTION'})
  98. obs = runtime.run_action(action)
  99. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  100. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  101. return goal, obs
  102. def complete_runtime(
  103. runtime: Runtime,
  104. ) -> dict[str, Any]:
  105. """Complete the runtime for the agent.
  106. This function is called before the runtime is used to run the agent.
  107. If you need to do something in the sandbox to get the correctness metric after
  108. the agent has run, modify this function.
  109. """
  110. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  111. obs: CmdOutputObservation
  112. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  113. logger.info(action, extra={'msg_type': 'ACTION'})
  114. obs = runtime.run_action(action)
  115. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  116. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  117. return {
  118. 'rewards': json.loads(obs.content),
  119. }
  120. def process_instance(
  121. instance: pd.Series,
  122. metadata: EvalMetadata,
  123. reset_logger: bool = True,
  124. ) -> EvalOutput:
  125. env_id = instance.instance_id
  126. config = get_config(metadata, env_id)
  127. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  128. if reset_logger:
  129. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  130. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  131. else:
  132. logger.info(f'Starting evaluation for instance {env_id}.')
  133. runtime = create_runtime(config)
  134. call_async_from_sync(runtime.connect)
  135. task_str, obs = initialize_runtime(runtime)
  136. task_str += (
  137. f'\nInitial browser state (output of `noop(1000)`):\n{obs.get_agent_obs_text()}'
  138. )
  139. state: State | None = asyncio.run(
  140. run_controller(
  141. config=config,
  142. initial_user_action=MessageAction(
  143. content=task_str
  144. ), # take output from initialize_runtime
  145. runtime=runtime,
  146. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  147. metadata.agent_class
  148. ],
  149. )
  150. )
  151. # ======= Attempt to evaluate the agent's environment impact =======
  152. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  153. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  154. if state is None:
  155. raise ValueError('State should not be None.')
  156. metrics = state.metrics.get() if state.metrics else None
  157. # Instruction is the first message from the USER
  158. instruction = ''
  159. for event in state.history:
  160. if isinstance(event, MessageAction):
  161. instruction = event.content
  162. break
  163. return_val = complete_runtime(runtime)
  164. logger.info(f'Return value from complete_runtime: {return_val}')
  165. reward = max(return_val['rewards'], default=0)
  166. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  167. # for compatibility with the existing output format, we can remake the pairs here
  168. # remove when it becomes unnecessary
  169. histories = compatibility_for_eval_history_pairs(state.history)
  170. # Save the output
  171. output = EvalOutput(
  172. instance_id=env_id,
  173. instruction=instruction,
  174. metadata=metadata,
  175. history=histories,
  176. metrics=metrics,
  177. error=state.last_error if state and state.last_error else None,
  178. test_result={
  179. 'reward': reward,
  180. },
  181. )
  182. return output
  183. if __name__ == '__main__':
  184. args = parse_arguments()
  185. dataset = pd.DataFrame(
  186. {
  187. 'instance_id': [
  188. id
  189. for id in gym.envs.registry.keys()
  190. if id.startswith('browsergym/miniwob')
  191. ]
  192. }
  193. )
  194. llm_config = None
  195. if args.llm_config:
  196. llm_config = get_llm_config_arg(args.llm_config)
  197. if llm_config is None:
  198. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  199. metadata = make_metadata(
  200. llm_config,
  201. 'miniwob',
  202. args.agent_cls,
  203. args.max_iterations,
  204. args.eval_note,
  205. args.eval_output_dir,
  206. )
  207. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  208. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  209. run_evaluation(
  210. instances, metadata, output_file, args.eval_num_workers, process_instance
  211. )