run_infer.py 5.5 KB

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