run_infer.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import asyncio
  2. import json
  3. import os
  4. from typing import Any
  5. import browsergym.webarena # noqa F401 register webarena 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. compatibility_for_eval_history_pairs,
  12. make_metadata,
  13. prepare_dataset,
  14. reset_logger_for_multiprocessing,
  15. run_evaluation,
  16. )
  17. from openhands.controller.state.state import State
  18. from openhands.core.config import (
  19. AppConfig,
  20. SandboxConfig,
  21. get_llm_config_arg,
  22. parse_arguments,
  23. )
  24. from openhands.core.logger import openhands_logger as logger
  25. from openhands.core.main import create_runtime, run_controller
  26. from openhands.events.action import (
  27. BrowseInteractiveAction,
  28. CmdRunAction,
  29. MessageAction,
  30. )
  31. from openhands.events.observation import CmdOutputObservation
  32. from openhands.runtime.base import Runtime
  33. from openhands.runtime.browser.browser_env import (
  34. BROWSER_EVAL_GET_GOAL_ACTION,
  35. BROWSER_EVAL_GET_REWARDS_ACTION,
  36. )
  37. from openhands.utils.async_utils import call_async_from_sync
  38. SUPPORTED_AGENT_CLS = {'BrowsingAgent'}
  39. def get_config(
  40. metadata: EvalMetadata,
  41. env_id: str,
  42. ) -> AppConfig:
  43. base_url = os.environ.get('WEBARENA_BASE_URL', None)
  44. openai_api_key = os.environ.get('OPENAI_API_KEY', None)
  45. assert base_url is not None, 'WEBARENA_BASE_URL must be set'
  46. assert openai_api_key is not None, 'OPENAI_API_KEY must be set'
  47. config = AppConfig(
  48. default_agent=metadata.agent_class,
  49. run_as_openhands=False,
  50. runtime='eventstream',
  51. max_iterations=metadata.max_iterations,
  52. sandbox=SandboxConfig(
  53. base_container_image='python:3.12-bookworm',
  54. enable_auto_lint=True,
  55. use_host_network=False,
  56. browsergym_eval_env=env_id,
  57. runtime_startup_env_vars={
  58. 'BASE_URL': base_url,
  59. 'OPENAI_API_KEY': openai_api_key,
  60. 'SHOPPING': f'{base_url}:7770/',
  61. 'SHOPPING_ADMIN': f'{base_url}:7780/admin',
  62. 'REDDIT': f'{base_url}:9999',
  63. 'GITLAB': f'{base_url}:8023',
  64. 'WIKIPEDIA': f'{base_url}:8888/wikipedia_en_all_maxi_2022-05/A/User:The_other_Kiwix_guy/Landing',
  65. 'MAP': f'{base_url}:3000',
  66. 'HOMEPAGE': f'{base_url}:4399',
  67. },
  68. ),
  69. # do not mount workspace
  70. workspace_base=None,
  71. workspace_mount_path=None,
  72. )
  73. config.set_llm_config(metadata.llm_config)
  74. return config
  75. def initialize_runtime(
  76. runtime: Runtime,
  77. ) -> dict:
  78. """Initialize the runtime for the agent.
  79. This function is called before the runtime is used to run the agent.
  80. """
  81. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  82. obs: CmdOutputObservation
  83. # Set instance id
  84. action = CmdRunAction(command='mkdir -p /workspace')
  85. logger.info(action, extra={'msg_type': 'ACTION'})
  86. obs = runtime.run_action(action)
  87. assert obs.exit_code == 0
  88. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  89. logger.info(action, extra={'msg_type': 'ACTION'})
  90. obs = runtime.run_action(action)
  91. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  92. goal = obs.content
  93. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  94. return goal
  95. def complete_runtime(
  96. runtime: Runtime,
  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. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  106. logger.info(action, extra={'msg_type': 'ACTION'})
  107. obs = runtime.run_action(action)
  108. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  109. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  110. return {
  111. 'rewards': json.loads(obs.content),
  112. }
  113. def process_instance(
  114. instance: pd.Series,
  115. metadata: EvalMetadata,
  116. reset_logger: bool = True,
  117. ):
  118. env_id = instance.instance_id
  119. config = get_config(metadata, env_id)
  120. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  121. if reset_logger:
  122. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  123. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  124. else:
  125. logger.info(f'Starting evaluation for instance {env_id}.')
  126. runtime = create_runtime(config)
  127. call_async_from_sync(runtime.connect)
  128. task_str = initialize_runtime(runtime)
  129. state: State | None = asyncio.run(
  130. run_controller(
  131. config=config,
  132. initial_user_action=MessageAction(content=task_str),
  133. runtime=runtime,
  134. )
  135. )
  136. # ======= Attempt to evaluate the agent's environment impact =======
  137. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  138. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  139. if state is None:
  140. raise ValueError('State should not be None.')
  141. metrics = state.metrics.get() if state.metrics else None
  142. # Instruction is the first message from the USER
  143. instruction = ''
  144. for event in state.history:
  145. if isinstance(event, MessageAction):
  146. instruction = event.content
  147. break
  148. return_val = complete_runtime(runtime)
  149. logger.info(f'Return value from complete_runtime: {return_val}')
  150. reward = max(return_val['rewards'])
  151. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  152. # for compatibility with the existing output format, we can remake the pairs here
  153. # remove when it becomes unnecessary
  154. histories = compatibility_for_eval_history_pairs(state.history)
  155. # Save the output
  156. output = EvalOutput(
  157. instance_id=env_id,
  158. instruction=instruction,
  159. metadata=metadata,
  160. history=histories,
  161. metrics=metrics,
  162. error=state.last_error if state and state.last_error else None,
  163. test_result={
  164. 'reward': reward,
  165. },
  166. )
  167. return output
  168. if __name__ == '__main__':
  169. args = parse_arguments()
  170. dataset = pd.DataFrame(
  171. {
  172. 'instance_id': [
  173. id
  174. for id in gym.envs.registry.keys()
  175. if id.startswith('browsergym/webarena')
  176. ]
  177. }
  178. )
  179. llm_config = None
  180. if args.llm_config:
  181. llm_config = get_llm_config_arg(args.llm_config)
  182. if llm_config is None:
  183. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  184. metadata = make_metadata(
  185. llm_config,
  186. args.dataset_name,
  187. args.agent_cls,
  188. args.max_iterations,
  189. args.eval_note,
  190. args.eval_output_dir,
  191. )
  192. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  193. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  194. run_evaluation(
  195. instances,
  196. metadata,
  197. output_file,
  198. args.eval_num_workers,
  199. process_instance,
  200. )