run_infer.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import asyncio
  2. import importlib.util
  3. import os
  4. import pandas as pd
  5. from evaluation.integration_tests.tests.base import BaseIntegrationTest, TestResult
  6. from evaluation.utils.shared import (
  7. EvalMetadata,
  8. EvalOutput,
  9. codeact_user_response,
  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. from openhands.events.action import MessageAction
  25. from openhands.runtime.base import Runtime
  26. FAKE_RESPONSES = {
  27. 'CodeActAgent': codeact_user_response,
  28. }
  29. def get_config(
  30. metadata: EvalMetadata,
  31. ) -> AppConfig:
  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. # use default base_container_image
  39. enable_auto_lint=True,
  40. use_host_network=False,
  41. timeout=100,
  42. ),
  43. # do not mount workspace
  44. workspace_base=None,
  45. workspace_mount_path=None,
  46. )
  47. config.set_llm_config(metadata.llm_config)
  48. return config
  49. def process_instance(
  50. instance: pd.Series,
  51. metadata: EvalMetadata,
  52. reset_logger: bool = True,
  53. ) -> EvalOutput:
  54. config = get_config(metadata)
  55. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  56. if reset_logger:
  57. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  58. reset_logger_for_multiprocessing(logger, str(instance.instance_id), log_dir)
  59. else:
  60. logger.info(
  61. f'\nStarting evaluation for instance {str(instance.instance_id)}.\n'
  62. )
  63. # =============================================
  64. # import test instance
  65. # =============================================
  66. instance_id = instance.instance_id
  67. spec = importlib.util.spec_from_file_location(instance_id, instance.file_path)
  68. test_module = importlib.util.module_from_spec(spec)
  69. spec.loader.exec_module(test_module)
  70. assert hasattr(
  71. test_module, 'Test'
  72. ), f'Test module {instance_id} does not have a Test class'
  73. test_class: type[BaseIntegrationTest] = test_module.Test
  74. assert issubclass(
  75. test_class, BaseIntegrationTest
  76. ), f'Test class {instance_id} does not inherit from BaseIntegrationTest'
  77. instruction = test_class.INSTRUCTION
  78. # =============================================
  79. # create sandbox and run the agent
  80. # =============================================
  81. runtime: Runtime = create_runtime(config)
  82. test_class.initialize_runtime(runtime)
  83. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  84. state: State | None = asyncio.run(
  85. run_controller(
  86. config=config,
  87. initial_user_action=MessageAction(content=instruction),
  88. runtime=runtime,
  89. fake_user_response_fn=FAKE_RESPONSES[metadata.agent_class],
  90. )
  91. )
  92. if state is None:
  93. raise ValueError('State should not be None.')
  94. # # =============================================
  95. # # result evaluation
  96. # # =============================================
  97. histories = state.history.get_events()
  98. test_result: TestResult = test_class.verify_result(runtime, histories)
  99. metrics = state.metrics.get() if state.metrics else None
  100. # Save the output
  101. output = EvalOutput(
  102. instance_id=str(instance.instance_id),
  103. instance=instance.to_dict(),
  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=test_result.model_dump(),
  110. )
  111. return output
  112. def load_integration_tests() -> pd.DataFrame:
  113. """Load tests from python files under ./tests"""
  114. cur_dir = os.path.dirname(os.path.abspath(__file__))
  115. test_dir = os.path.join(cur_dir, 'tests')
  116. test_files = [
  117. os.path.join(test_dir, f)
  118. for f in os.listdir(test_dir)
  119. if f.startswith('t') and f.endswith('.py')
  120. ]
  121. df = pd.DataFrame(test_files, columns=['file_path'])
  122. df['instance_id'] = df['file_path'].apply(
  123. lambda x: os.path.basename(x).rstrip('.py')
  124. )
  125. return df
  126. if __name__ == '__main__':
  127. args = parse_arguments()
  128. integration_tests = load_integration_tests()
  129. llm_config = None
  130. if args.llm_config:
  131. llm_config = get_llm_config_arg(args.llm_config)
  132. if llm_config is None:
  133. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  134. metadata = make_metadata(
  135. llm_config,
  136. 'integration_tests',
  137. args.agent_cls,
  138. args.max_iterations,
  139. args.eval_note,
  140. args.eval_output_dir,
  141. )
  142. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  143. # Parse dataset IDs if provided
  144. eval_ids = None
  145. if args.eval_ids:
  146. eval_ids = str(args.eval_ids).split(',')
  147. logger.info(f'\nUsing specific dataset IDs: {eval_ids}\n')
  148. instances = prepare_dataset(
  149. integration_tests,
  150. output_file,
  151. args.eval_n_limit,
  152. eval_ids=eval_ids,
  153. )
  154. run_evaluation(
  155. instances,
  156. metadata,
  157. output_file,
  158. args.eval_num_workers,
  159. process_instance,
  160. )
  161. df = pd.read_json(output_file, lines=True, orient='records')
  162. df['success'] = df['test_result'].apply(lambda x: x['success'])
  163. df['reason'] = df['test_result'].apply(lambda x: x['reason'])
  164. logger.info('-' * 100)
  165. logger.info(
  166. f'Success rate: {df["success"].mean():.2%} ({df["success"].sum()}/{len(df)})'
  167. )
  168. logger.info(
  169. '\nEvaluation Results:'
  170. + '\n'
  171. + df[['instance_id', 'success', 'reason']].to_string(index=False)
  172. )
  173. logger.info('-' * 100)