run_infer.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import asyncio
  2. import functools
  3. import logging
  4. import os
  5. import pathlib
  6. from typing import Any, Dict
  7. from datasets import load_dataset
  8. from evaluation.swe_bench.swe_env_box import DockerSSHBox
  9. from evaluation.utils.shared import (
  10. EvalMetadata,
  11. make_metadata,
  12. monologue_user_response,
  13. prepare_dataset,
  14. run_evaluation,
  15. )
  16. from opendevin.controller.agent import Agent
  17. from opendevin.controller.state.state import State
  18. from opendevin.core.config import config, get_llm_config_arg, get_parser
  19. from opendevin.core.logger import get_console_handler
  20. from opendevin.core.logger import opendevin_logger as logger
  21. from opendevin.core.main import run_agent_controller
  22. from opendevin.llm.llm import LLM
  23. from .datatypes import TaskState
  24. from .env import SimplifiedEnv
  25. from .prompts import ToolPromptTemplate
  26. from .tasks import Task
  27. def codeact_user_response_mint(state: State, task: Task, task_config: Dict[str, int]):
  28. logger.info(f'Gold reference: {task.reference}')
  29. logger.info(f'Task config: {task_config}')
  30. env = SimplifiedEnv(
  31. agent_state=state,
  32. task=task,
  33. task_config=task_config,
  34. )
  35. last_action = state.history.get_last_action()
  36. result_state: TaskState = env.step(last_action.message or '')
  37. state.task_state = result_state
  38. if not result_state.latest_output:
  39. # Task is finished
  40. msg = '/exit'
  41. else:
  42. msg = result_state.latest_output['content']
  43. logger.info('User response:' + msg)
  44. return msg
  45. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  46. 'CodeActAgent': codeact_user_response_mint,
  47. 'MonologueAgent': monologue_user_response,
  48. }
  49. AGENT_CLS_TO_INST_SUFFIX = {
  50. 'CodeActAgent': '\nIMPORTANT: When your answer is confirmed by the user to be correct, you can exit using the following command: <execute_bash> exit </execute_bash>.\n'
  51. }
  52. def process_instance(
  53. instance: Any,
  54. metadata: EvalMetadata,
  55. reset_logger: bool = True,
  56. ):
  57. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(metadata.llm_config))
  58. workspace_mount_path = os.path.join(config.workspace_mount_path, '_eval_workspace')
  59. # create process-specific workspace dir
  60. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  61. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  62. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  63. if reset_logger:
  64. # Set up logger
  65. log_file = os.path.join(
  66. metadata.eval_output_dir, 'logs', f'instance_{instance.task_id}.log'
  67. )
  68. # Remove all existing handlers from logger
  69. for handler in logger.handlers[:]:
  70. logger.removeHandler(handler)
  71. # add back the console handler to print ONE line
  72. logger.addHandler(get_console_handler())
  73. logger.info(
  74. f'Starting evaluation for instance {instance.task_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  75. )
  76. # Remove all existing handlers from logger
  77. for handler in logger.handlers[:]:
  78. logger.removeHandler(handler)
  79. file_handler = logging.FileHandler(log_file)
  80. file_handler.setFormatter(
  81. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  82. )
  83. logger.addHandler(file_handler)
  84. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  85. # use a session id for concurrent processing
  86. sid = instance.task_id + '_' + str(os.getpid())
  87. sandbox = DockerSSHBox(sid=sid)
  88. requirements_host_src = 'evaluation/mint/requirements.txt'
  89. requirements_sandbox_dest = '/opendevin/plugins/mint/requirements.txt'
  90. sandbox.copy_to(
  91. host_src=requirements_host_src,
  92. sandbox_dest=requirements_sandbox_dest,
  93. recursive=False,
  94. )
  95. logger.info(
  96. f'Copied files from [{requirements_host_src}] to [{requirements_sandbox_dest}] inside sandbox.'
  97. )
  98. exit_code, output = sandbox.execute(f'pip install -r {requirements_sandbox_dest}')
  99. # Prepare instruction
  100. assert metadata.details is not None
  101. instruction = ToolPromptTemplate(use_tool=True)(
  102. max_total_steps=metadata.max_iterations,
  103. max_propose_solution=metadata.details['max_propose_solution'],
  104. in_context_example=instance.in_context_example(
  105. use_tool=True, with_feedback=False
  106. ),
  107. task_prompt='Task:\n' + instance.prompt,
  108. )
  109. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you or provide the concise RESULT inside <solution> tag AND NEVER ASK FOR HUMAN HELP.\n'
  110. # NOTE: You can actually set slightly different instruction for different agents
  111. instruction += AGENT_CLS_TO_INST_SUFFIX[agent.__class__.__name__]
  112. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  113. fake_user_response_fn = functools.partial(
  114. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[agent.__class__.__name__],
  115. task=instance,
  116. task_config={
  117. 'max_iterations': metadata.max_iterations,
  118. 'max_propose_solution': metadata.details['max_propose_solution'],
  119. },
  120. )
  121. state: State | None = asyncio.run(
  122. run_agent_controller(
  123. agent,
  124. instruction,
  125. max_iterations=metadata.max_iterations,
  126. fake_user_response_fn=fake_user_response_fn,
  127. sandbox=sandbox,
  128. sid=sid,
  129. )
  130. )
  131. if state is None:
  132. raise ValueError('State should not be None.')
  133. task_state = None
  134. if hasattr(state, 'task_state'):
  135. task_state = state.task_state
  136. logger.info('Task state: ' + str(task_state.to_dict()))
  137. metrics = state.metrics.get() if state.metrics else None
  138. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  139. # for compatibility with the existing output format, we can remake the pairs here
  140. # remove when it becomes unnecessary
  141. histories = state.history.compatibility_for_eval_history_pairs()
  142. # Save the output
  143. output = {
  144. 'id': instance.task_id,
  145. 'instance': instance.to_dict(),
  146. 'instruction': instruction,
  147. 'metadata': metadata.model_dump(),
  148. 'history': histories,
  149. 'metrics': metrics,
  150. 'error': state.last_error if state and state.last_error else None,
  151. 'test_result': task_state.success if task_state else False,
  152. }
  153. # Close the sandbox
  154. sandbox.close()
  155. return output
  156. if __name__ == '__main__':
  157. parser = get_parser()
  158. parser.add_argument(
  159. '--subset',
  160. default='math',
  161. choices=['math', 'gsm8k', 'mmlu', 'theoremqa', 'mbpp', 'humaneval'],
  162. type=str,
  163. help='subset of the dataset to be used',
  164. )
  165. parser.add_argument(
  166. '--max-propose-solution',
  167. default=2,
  168. type=int,
  169. help='maximum number of times the agent can propose a solution',
  170. )
  171. args, _ = parser.parse_known_args()
  172. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  173. # so we don't need to manage file uploading to OpenDevin's repo
  174. mint_dataset = load_dataset(
  175. 'ryanhoangt/xingyaoww-mint-bench', name=args.subset, split='test'
  176. )
  177. logger.info(f'Evaluating MINT - {args.subset} subset')
  178. mint_tests = mint_dataset.to_pandas()
  179. id_column = 'id'
  180. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  181. logger.info(f'Config for evaluation: {config}')
  182. metadata = make_metadata(
  183. llm_config,
  184. args.dataset_name,
  185. args.agent_cls,
  186. args.max_iterations,
  187. args.eval_note,
  188. args.eval_output_dir,
  189. details={'max_propose_solution': args.max_propose_solution},
  190. )
  191. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  192. instances = prepare_dataset(mint_dataset, output_file, args.eval_n_limit, id_column)
  193. run_evaluation(
  194. instances,
  195. metadata,
  196. output_file,
  197. args.eval_num_workers,
  198. process_instance,
  199. id_column,
  200. )