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. 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. async 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 = await create_runtime(config, sid=instance.instance_id)
  66. state: State | None = await run_controller(
  67. config=config,
  68. task_str=instruction,
  69. runtime=runtime,
  70. )
  71. if state is None:
  72. raise ValueError('State should not be None.')
  73. metrics = state.metrics.get() if state.metrics else None
  74. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  75. # for compatibility with the existing output format, we can remake the pairs here
  76. # remove when it becomes unnecessary
  77. histories = state.history.compatibility_for_eval_history_pairs()
  78. # find the last delegate action
  79. last_delegate_action = None
  80. result = {}
  81. for action, _ in histories:
  82. if action['action'] == 'delegate':
  83. last_delegate_action = action
  84. instruction_for_delegate = action['args']['inputs']['task']
  85. # parse `browse_actions` from `instruction_for_delegate`
  86. # task = f'{thought}. I should start with: {browse_actions}'
  87. instruction_for_delegate = re.search(
  88. r'I should start with: (.*)', instruction_for_delegate
  89. ).group(1)
  90. # calculate the edit distance between the instance.instruction and the instruction_for_delegate
  91. edit_distance = nltk.edit_distance(
  92. instance.instruction, instruction_for_delegate
  93. )
  94. is_exact_match = (
  95. instance.instruction.strip() == instruction_for_delegate.strip()
  96. )
  97. result['edit_distance'] = edit_distance
  98. result['is_exact_match'] = is_exact_match
  99. # Save the output
  100. output = EvalOutput(
  101. instance_id=instance.instance_id,
  102. instruction=instruction,
  103. metadata=metadata,
  104. history=histories,
  105. metrics=metrics,
  106. error=state.last_error if state and state.last_error else None,
  107. test_result={
  108. 'query': instance.instruction,
  109. 'action': last_delegate_action,
  110. 'result': result,
  111. },
  112. )
  113. return output
  114. if __name__ == '__main__':
  115. args = parse_arguments()
  116. dataset = load_dataset('OpenHands/eval-browsing-instructions')
  117. dataset = dataset['train'].to_pandas()
  118. assert dataset.columns.tolist() == ['instance_id', 'instruction']
  119. llm_config = None
  120. if args.llm_config:
  121. llm_config = get_llm_config_arg(args.llm_config)
  122. if llm_config is None:
  123. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  124. metadata = make_metadata(
  125. llm_config,
  126. 'browsing_delegation',
  127. args.agent_cls,
  128. args.max_iterations,
  129. args.eval_note,
  130. args.eval_output_dir,
  131. )
  132. if metadata.agent_class not in SUPPORTED_AGENT_CLS:
  133. raise ValueError(
  134. f'Agent class {metadata.agent_class} not supported with AgentDelegation.'
  135. )
  136. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  137. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  138. asyncio.run(
  139. run_evaluation(
  140. instances,
  141. metadata,
  142. output_file,
  143. args.eval_num_workers,
  144. process_instance,
  145. )
  146. )