run_infer.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  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. make_metadata,
  11. prepare_dataset,
  12. run_evaluation,
  13. )
  14. from opendevin.controller.agent import Agent
  15. from opendevin.controller.state.state import State
  16. from opendevin.core.config import get_llm_config_arg, load_app_config, parse_arguments
  17. from opendevin.core.logger import get_console_handler
  18. from opendevin.core.logger import opendevin_logger as logger
  19. from opendevin.core.main import run_agent_controller
  20. from opendevin.llm.llm import LLM
  21. from opendevin.runtime.docker.ssh_box import DockerSSHBox
  22. from opendevin.runtime.tools import RuntimeTool
  23. config = load_app_config()
  24. SUPPORTED_AGENT_CLS = {'BrowsingAgent'}
  25. docker_ssh_box: DockerSSHBox | None = None
  26. def get_sandbox():
  27. global docker_ssh_box
  28. if docker_ssh_box is None:
  29. docker_ssh_box = DockerSSHBox(
  30. config=config.sandbox,
  31. persist_sandbox=False,
  32. workspace_mount_path=config.workspace_mount_path,
  33. sandbox_workspace_dir=config.workspace_mount_path_in_sandbox,
  34. cache_dir=config.cache_dir,
  35. run_as_devin=config.run_as_devin,
  36. )
  37. return docker_ssh_box
  38. def process_instance(
  39. instance: pd.Series,
  40. metadata: EvalMetadata,
  41. reset_logger: bool = True,
  42. ):
  43. # Create the agent
  44. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(config=metadata.llm_config))
  45. env_id = instance.id
  46. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  47. if reset_logger:
  48. # Set up logger
  49. log_file = os.path.join(
  50. metadata.eval_output_dir, 'logs', f'instance_{env_id}.log'
  51. )
  52. # Remove all existing handlers from logger
  53. for handler in logger.handlers[:]:
  54. logger.removeHandler(handler)
  55. # add back the console handler to print ONE line
  56. logger.addHandler(get_console_handler())
  57. logger.info(
  58. f'Starting evaluation for instance {env_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  59. )
  60. # Remove all existing handlers from logger
  61. for handler in logger.handlers[:]:
  62. logger.removeHandler(handler)
  63. file_handler = logging.FileHandler(log_file)
  64. file_handler.setFormatter(
  65. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  66. )
  67. logger.addHandler(file_handler)
  68. else:
  69. logger.info(f'Starting evaluation for instance {env_id}.')
  70. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  71. runtime_tools_config = {
  72. RuntimeTool.BROWSER: {
  73. 'browsergym_eval': env_id,
  74. 'browsergym_eval_save_dir': metadata.eval_output_dir,
  75. }
  76. }
  77. state: State | None = asyncio.run(
  78. run_agent_controller(
  79. agent,
  80. 'PLACEHOLDER_GOAL',
  81. max_iterations=metadata.max_iterations,
  82. max_budget_per_task=config.max_budget_per_task,
  83. runtime_tools_config=runtime_tools_config,
  84. sandbox=get_sandbox(),
  85. sid=env_id,
  86. )
  87. )
  88. # ======= Attempt to evaluate the agent's environment impact =======
  89. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  90. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  91. if state is None:
  92. raise ValueError('State should not be None.')
  93. metrics = state.metrics.get() if state.metrics else None
  94. browsergym_eval_dir = os.path.join(metadata.eval_output_dir, env_id.split('/')[1])
  95. # read goal
  96. with open(
  97. os.path.join(browsergym_eval_dir, 'goal.txt'), 'r', encoding='utf-8'
  98. ) as f:
  99. instruction = f.read()
  100. # read reward
  101. with open(
  102. os.path.join(browsergym_eval_dir, 'rewards.json'), 'r', encoding='utf-8'
  103. ) as f:
  104. rewards = json.load(f)
  105. reward = max(rewards)
  106. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  107. # for compatibility with the existing output format, we can remake the pairs here
  108. # remove when it becomes unnecessary
  109. histories = state.history.compatibility_for_eval_history_pairs()
  110. # Save the output
  111. output = {
  112. 'instance_id': env_id,
  113. 'instruction': instruction,
  114. 'metadata': metadata.model_dump(),
  115. 'history': histories,
  116. 'metrics': metrics,
  117. 'error': state.last_error if state and state.last_error else None,
  118. 'test_result': reward,
  119. }
  120. return output
  121. if __name__ == '__main__':
  122. args = parse_arguments()
  123. dataset = pd.DataFrame(
  124. {
  125. 'id': [
  126. id
  127. for id in gym.envs.registry.keys()
  128. if id.startswith('browsergym/miniwob')
  129. ]
  130. }
  131. )
  132. id_column = 'id'
  133. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  134. logger.info(f'Config for evaluation: {config}')
  135. metadata = make_metadata(
  136. llm_config,
  137. args.dataset_name,
  138. args.agent_cls,
  139. args.max_iterations,
  140. args.eval_note,
  141. args.eval_output_dir,
  142. )
  143. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  144. instances = prepare_dataset(dataset, output_file, args.eval_n_limit, id_column)
  145. _ = get_sandbox() # Initialize the sandbox
  146. run_evaluation(
  147. instances,
  148. metadata,
  149. output_file,
  150. args.eval_num_workers,
  151. process_instance,
  152. id_column,
  153. )