run_infer.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import asyncio
  2. import os
  3. import re
  4. import nltk
  5. import pandas as pd
  6. from datasets import load_dataset
  7. from evaluation.utils.shared import (
  8. EvalMetadata,
  9. EvalOutput,
  10. make_metadata,
  11. prepare_dataset,
  12. reset_logger_for_multiprocessing,
  13. run_evaluation,
  14. )
  15. from openhands.controller.state.state import State
  16. from openhands.core.config import (
  17. AppConfig,
  18. SandboxConfig,
  19. get_llm_config_arg,
  20. parse_arguments,
  21. )
  22. from openhands.core.logger import openhands_logger as logger
  23. from openhands.core.main import create_runtime, run_controller
  24. from openhands.events.action import MessageAction
  25. # Only CodeActAgent can delegate to BrowsingAgent
  26. SUPPORTED_AGENT_CLS = {'CodeActAgent'}
  27. def get_config(
  28. metadata: EvalMetadata,
  29. ) -> AppConfig:
  30. assert (
  31. metadata.max_iterations == 1
  32. ), 'max_iterations must be 1 for browsing delegation evaluation.'
  33. config = AppConfig(
  34. default_agent=metadata.agent_class,
  35. run_as_openhands=False,
  36. runtime='eventstream',
  37. max_iterations=metadata.max_iterations,
  38. sandbox=SandboxConfig(
  39. base_container_image='python:3.12-bookworm',
  40. enable_auto_lint=False,
  41. use_host_network=False,
  42. ),
  43. workspace_base=None,
  44. workspace_mount_path=None,
  45. )
  46. config.set_llm_config(metadata.llm_config)
  47. return config
  48. def process_instance(
  49. instance: pd.Series,
  50. metadata: EvalMetadata,
  51. reset_logger: bool = True,
  52. ) -> EvalOutput:
  53. config = get_config(metadata)
  54. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  55. if reset_logger:
  56. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  57. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  58. else:
  59. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  60. instruction = (
  61. f'You can delegate browsing tasks to a browser agent. '
  62. f"For example, for query 'Who is the president of the United States?', you can delegate the task to a browser agent via <execute_browse> Who is the president of the United States? </execute_browse>.\n"
  63. f'Now, solve the following query: "{instance.instruction}"\n'
  64. f'NOTE: You should copy the "query" as is into the <execute_browse> tag. DO NOT change ANYTHING in the query.'
  65. )
  66. runtime = create_runtime(config)
  67. state: State | None = asyncio.run(
  68. run_controller(
  69. config=config,
  70. initial_user_action=MessageAction(content=instruction),
  71. runtime=runtime,
  72. )
  73. )
  74. if state is None:
  75. raise ValueError('State should not be None.')
  76. metrics = state.metrics.get() if state.metrics else None
  77. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  78. # for compatibility with the existing output format, we can remake the pairs here
  79. # remove when it becomes unnecessary
  80. histories = state.history.compatibility_for_eval_history_pairs()
  81. # find the last delegate action
  82. last_delegate_action = None
  83. result = {}
  84. for action, _ in histories:
  85. if action['action'] == 'delegate':
  86. last_delegate_action = action
  87. instruction_for_delegate = action['args']['inputs']['task']
  88. # parse `browse_actions` from `instruction_for_delegate`
  89. # task = f'{thought}. I should start with: {browse_actions}'
  90. instruction_for_delegate = re.search(
  91. r'I should start with: (.*)', instruction_for_delegate
  92. ).group(1)
  93. # calculate the edit distance between the instance.instruction and the instruction_for_delegate
  94. edit_distance = nltk.edit_distance(
  95. instance.instruction, instruction_for_delegate
  96. )
  97. is_exact_match = (
  98. instance.instruction.strip() == instruction_for_delegate.strip()
  99. )
  100. result['edit_distance'] = edit_distance
  101. result['is_exact_match'] = is_exact_match
  102. # Save the output
  103. output = EvalOutput(
  104. instance_id=instance.instance_id,
  105. instruction=instruction,
  106. metadata=metadata,
  107. history=histories,
  108. metrics=metrics,
  109. error=state.last_error if state and state.last_error else None,
  110. test_result={
  111. 'query': instance.instruction,
  112. 'action': last_delegate_action,
  113. 'result': result,
  114. },
  115. )
  116. return output
  117. if __name__ == '__main__':
  118. args = parse_arguments()
  119. dataset = load_dataset('OpenHands/eval-browsing-instructions')
  120. dataset = dataset['train'].to_pandas()
  121. assert dataset.columns.tolist() == ['instance_id', 'instruction']
  122. llm_config = None
  123. if args.llm_config:
  124. llm_config = get_llm_config_arg(args.llm_config)
  125. if llm_config is None:
  126. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  127. metadata = make_metadata(
  128. llm_config,
  129. 'browsing_delegation',
  130. args.agent_cls,
  131. args.max_iterations,
  132. args.eval_note,
  133. args.eval_output_dir,
  134. )
  135. if metadata.agent_class not in SUPPORTED_AGENT_CLS:
  136. raise ValueError(
  137. f'Agent class {metadata.agent_class} not supported with AgentDelegation.'
  138. )
  139. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  140. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  141. run_evaluation(
  142. instances,
  143. metadata,
  144. output_file,
  145. args.eval_num_workers,
  146. process_instance,
  147. )