run_infer.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import asyncio
  2. import logging
  3. import os
  4. import re
  5. import nltk
  6. import pandas as pd
  7. from datasets import load_dataset
  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 config, get_llm_config_arg, 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. # Only CodeActAgent can delegate to BrowsingAgent
  22. SUPPORTED_AGENT_CLS = {'CodeActAgent'}
  23. def process_instance(
  24. instance: pd.Series,
  25. metadata: EvalMetadata,
  26. reset_logger: bool = True,
  27. ):
  28. # Create the agent
  29. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(llm_config=metadata.llm_config))
  30. env_id = instance.instance_id
  31. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  32. if reset_logger:
  33. # Set up logger
  34. log_file = os.path.join(
  35. metadata.eval_output_dir, 'logs', f'instance_{env_id}.log'
  36. )
  37. # Remove all existing handlers from logger
  38. for handler in logger.handlers[:]:
  39. logger.removeHandler(handler)
  40. # add back the console handler to print ONE line
  41. logger.addHandler(get_console_handler())
  42. logger.info(
  43. f'Starting evaluation for instance {env_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  44. )
  45. # Remove all existing handlers from logger
  46. for handler in logger.handlers[:]:
  47. logger.removeHandler(handler)
  48. file_handler = logging.FileHandler(log_file)
  49. file_handler.setFormatter(
  50. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  51. )
  52. logger.addHandler(file_handler)
  53. else:
  54. logger.info(f'Starting evaluation for instance {env_id}.')
  55. instruction = (
  56. f'You can delegate browsing tasks to a browser agent. '
  57. 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"
  58. f'Now, solve the following query: "{instance.instruction}"\n'
  59. f'NOTE: You should copy the "query" as is into the <execute_browse> tag. DO NOT change ANYTHING in the query.'
  60. )
  61. state: State | None = asyncio.run(
  62. run_agent_controller(
  63. agent,
  64. instruction,
  65. max_iterations=metadata.max_iterations,
  66. sid=env_id,
  67. )
  68. )
  69. # ======= Attempt to evaluate the agent's environment impact =======
  70. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  71. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  72. if state is None:
  73. raise ValueError('State should not be None.')
  74. metrics = state.metrics.get() if state.metrics else None
  75. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  76. # for compatibility with the existing output format, we can remake the pairs here
  77. # remove when it becomes unnecessary
  78. histories = state.history.compatibility_for_eval_history_pairs()
  79. # find the last delegate action
  80. last_delegate_action = None
  81. result = {}
  82. for action, _ in histories:
  83. if action['action'] == 'delegate':
  84. last_delegate_action = action
  85. instruction_for_delegate = action['args']['inputs']['task']
  86. # parse `browse_actions` from `instruction_for_delegate`
  87. # task = f'{thought}. I should start with: {browse_actions}'
  88. instruction_for_delegate = re.search(
  89. r'I should start with: (.*)', instruction_for_delegate
  90. ).group(1)
  91. # calculate the edit distance between the instance.instruction and the instruction_for_delegate
  92. edit_distance = nltk.edit_distance(
  93. instance.instruction, instruction_for_delegate
  94. )
  95. is_exact_match = (
  96. instance.instruction.strip() == instruction_for_delegate.strip()
  97. )
  98. result['edit_distance'] = edit_distance
  99. result['is_exact_match'] = is_exact_match
  100. # Save the output
  101. output = {
  102. 'instance_id': env_id,
  103. 'instruction': instruction,
  104. 'metadata': metadata.model_dump(),
  105. 'history': histories,
  106. 'metrics': metrics,
  107. 'error': state.last_error if state and state.last_error else None,
  108. 'test_result': {
  109. 'query': instance.instruction,
  110. 'action': last_delegate_action,
  111. 'result': result,
  112. },
  113. }
  114. return output
  115. if __name__ == '__main__':
  116. args = parse_arguments()
  117. dataset = load_dataset('OpenDevin/eval-browsing-instructions')
  118. dataset = dataset['train'].to_pandas()
  119. assert dataset.columns.tolist() == ['instance_id', 'instruction']
  120. id_column = 'instance_id'
  121. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  122. logger.info(f'Config for evaluation: {config}')
  123. metadata = make_metadata(
  124. llm_config,
  125. 'browsing_delegation',
  126. args.agent_cls,
  127. args.max_iterations,
  128. args.eval_note,
  129. args.eval_output_dir,
  130. )
  131. if metadata.agent_class not in SUPPORTED_AGENT_CLS:
  132. raise ValueError(
  133. f'Agent class {metadata.agent_class} not supported with AgentDelegation.'
  134. )
  135. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  136. instances = prepare_dataset(dataset, output_file, args.eval_n_limit, id_column)
  137. run_evaluation(
  138. instances,
  139. metadata,
  140. output_file,
  141. args.eval_num_workers,
  142. process_instance,
  143. id_column,
  144. )