run_infer.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 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_controller
  20. from opendevin.llm.llm import LLM
  21. config = load_app_config()
  22. # Only CodeActAgent can delegate to BrowsingAgent
  23. SUPPORTED_AGENT_CLS = {'CodeActAgent'}
  24. def process_instance(
  25. instance: pd.Series,
  26. metadata: EvalMetadata,
  27. reset_logger: bool = True,
  28. ):
  29. # Create the agent
  30. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(config=metadata.llm_config))
  31. env_id = instance.instance_id
  32. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  33. if reset_logger:
  34. # Set up logger
  35. log_file = os.path.join(
  36. metadata.eval_output_dir, 'logs', f'instance_{env_id}.log'
  37. )
  38. # Remove all existing handlers from logger
  39. for handler in logger.handlers[:]:
  40. logger.removeHandler(handler)
  41. # add back the console handler to print ONE line
  42. logger.addHandler(get_console_handler())
  43. logger.info(
  44. f'Starting evaluation for instance {env_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  45. )
  46. # Remove all existing handlers from logger
  47. for handler in logger.handlers[:]:
  48. logger.removeHandler(handler)
  49. file_handler = logging.FileHandler(log_file)
  50. file_handler.setFormatter(
  51. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  52. )
  53. logger.addHandler(file_handler)
  54. else:
  55. logger.info(f'Starting evaluation for instance {env_id}.')
  56. instruction = (
  57. f'You can delegate browsing tasks to a browser agent. '
  58. 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"
  59. f'Now, solve the following query: "{instance.instruction}"\n'
  60. f'NOTE: You should copy the "query" as is into the <execute_browse> tag. DO NOT change ANYTHING in the query.'
  61. )
  62. config.max_iterations = metadata.max_iterations
  63. state: State | None = asyncio.run(
  64. run_controller(
  65. config=config,
  66. task_str=instruction,
  67. agent=agent,
  68. sid=env_id,
  69. )
  70. )
  71. # ======= Attempt to evaluate the agent's environment impact =======
  72. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  73. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  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 = {
  104. 'instance_id': env_id,
  105. 'instruction': instruction,
  106. 'metadata': metadata.model_dump(),
  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('OpenDevin/eval-browsing-instructions')
  120. dataset = dataset['train'].to_pandas()
  121. assert dataset.columns.tolist() == ['instance_id', 'instruction']
  122. id_column = 'instance_id'
  123. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  124. logger.info(f'Config for evaluation: {config}')
  125. metadata = make_metadata(
  126. llm_config,
  127. 'browsing_delegation',
  128. args.agent_cls,
  129. args.max_iterations,
  130. args.eval_note,
  131. args.eval_output_dir,
  132. )
  133. if metadata.agent_class not in SUPPORTED_AGENT_CLS:
  134. raise ValueError(
  135. f'Agent class {metadata.agent_class} not supported with AgentDelegation.'
  136. )
  137. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  138. instances = prepare_dataset(dataset, output_file, args.eval_n_limit, id_column)
  139. run_evaluation(
  140. instances,
  141. metadata,
  142. output_file,
  143. args.eval_num_workers,
  144. process_instance,
  145. id_column,
  146. )