run_analysis.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import json
  2. import os
  3. import pprint
  4. import tqdm
  5. from openhands.core.config import get_llm_config_arg, get_parser, load_app_config
  6. from openhands.core.logger import openhands_logger as logger
  7. from openhands.llm.llm import LLM
  8. config = load_app_config()
  9. def extract_test_results(res_file_path: str) -> tuple[list[str], list[str]]:
  10. passed = []
  11. failed = []
  12. costs = []
  13. instance_ids = set()
  14. instances = []
  15. with open(res_file_path, 'r') as file:
  16. for line in file:
  17. data = json.loads(line.strip())
  18. success = data['metrics']['success']
  19. if data['instance_id'] in instance_ids:
  20. print(f'WARNING: Duplicate instance_id found: {data["instance_id"]}')
  21. continue
  22. instance_ids.add(data['instance_id'])
  23. instances.append(data)
  24. if success:
  25. passed.append(
  26. {
  27. 'instance_id': data['instance_id'],
  28. 'repo': data['repo'],
  29. 'instruction': data['instruction'],
  30. 'eval_script': data['eval_script'],
  31. 'eval_exit_code': data['eval_exit_code'],
  32. 'eval_output': data['eval_output'],
  33. 'accumulated_cost': data['metrics']['accumulated_cost'],
  34. }
  35. )
  36. else:
  37. failed.append(
  38. {
  39. 'instance_id': data['instance_id'],
  40. 'repo': data['repo'],
  41. 'instruction': data['instruction'],
  42. 'metadata': data['metadata'],
  43. 'history': data['history'],
  44. 'eval_script': data['eval_script'],
  45. 'eval_exit_code': data['eval_exit_code'],
  46. 'eval_output': data['eval_output'],
  47. 'accumulated_cost': data['metrics']['accumulated_cost'],
  48. }
  49. )
  50. costs.append(data['metrics']['accumulated_cost'])
  51. # sort by instance_id
  52. instances.sort(key=lambda x: x['instance_id'])
  53. with open(res_file_path, 'w') as file:
  54. for instance in instances:
  55. file.write(json.dumps(instance) + '\n')
  56. return passed, failed, costs
  57. def classify_error(llm: LLM, failed_case: dict) -> str:
  58. prompt = f"""
  59. Please classify the error for the following failed case based on the history and eval_output:
  60. Instruction:
  61. {failed_case['instruction']}
  62. Eval Script:
  63. {failed_case['eval_script']}s
  64. History:
  65. {failed_case['history']}
  66. Eval Output:
  67. {failed_case['eval_output']}
  68. The error categories are:
  69. E1: Hallucination Errors - The model misinterpreted the user's intention, misplaced Python code and bash script, or generated random or irrelevant code.
  70. E2: Lack of Knowledge or Information - The model lacks sufficient information or domain-specific knowledge to satisfy the user's requirements.
  71. E3: Knowledge Manipulation - The model failed to integrate or manipulate information properly.
  72. E4: Syntax Errors - The model generated code with syntax errors.
  73. E5: Operational Error - The model gave up easily or exited without finishing the tasks.
  74. Please provide only the error category (E1, E2, E3, E4, or E5) without any explanation.
  75. """
  76. try:
  77. response = llm.completion(messages=[{'content': prompt, 'role': 'user'}])
  78. error_category = response.choices[0].message['content']
  79. except Exception as e:
  80. logger.error(
  81. f"Failed to classify the error for the failed case: {failed_case['instance_id']}"
  82. )
  83. logger.error(e)
  84. error_category = input(
  85. failed_case['instruction']
  86. + ': '
  87. + failed_case['eval_script']
  88. + ' - '
  89. + failed_case['eval_output']
  90. )
  91. if error_category not in ['E1', 'E2', 'E3', 'E4', 'E5']:
  92. raise ValueError(f'Invalid error category: {error_category}')
  93. return error_category
  94. if __name__ == '__main__':
  95. parser = get_parser()
  96. parser.add_argument(
  97. '--json_file_path',
  98. type=str,
  99. required=True,
  100. help='Path to the jsonl file containing the evaluation results',
  101. )
  102. args, _ = parser.parse_known_args()
  103. # Check https://github.com/All-Hands-AI/OpenHands/blob/main/evaluation/swe_bench/README.md#configure-openhands-and-your-llm
  104. # for details of how to set `llm_config`
  105. if args.llm_config:
  106. specified_llm_config = get_llm_config_arg(args.llm_config)
  107. if specified_llm_config:
  108. config.llm = specified_llm_config
  109. logger.info(f'Config for evaluation: {config}')
  110. llm = LLM(llm_config=specified_llm_config)
  111. passed, new_failed, costs = extract_test_results(args.json_file_path)
  112. failed = []
  113. if os.path.exists(args.json_file_path.replace('.jsonl', '_failed.jsonl')):
  114. with open(args.json_file_path.replace('.jsonl', '_failed.jsonl'), 'r') as file:
  115. for line in file:
  116. failed.append(json.loads(line.strip()))
  117. print(
  118. f'Loaded {len(failed)} failed cases from {args.json_file_path.replace(".jsonl", "_failed.jsonl")}'
  119. )
  120. for failed_case in tqdm.tqdm(new_failed):
  121. if failed_case['instance_id'] in [case['instance_id'] for case in failed]:
  122. continue
  123. error_category = classify_error(llm, failed_case)
  124. failed_case['error_category'] = error_category
  125. failed.append(failed_case)
  126. with open(args.json_file_path.replace('.jsonl', '_failed.jsonl'), 'a') as file:
  127. file.write(json.dumps(failed_case) + '\n')
  128. # Print the summary
  129. print('Summary:')
  130. print(f'Passed: {len(passed)}')
  131. print(f'Failed: {len(failed)}')
  132. print(f'Costs: {costs}')
  133. print('Failed cases:')
  134. error_categories = {}
  135. for case in failed:
  136. error_category = case['error_category']
  137. if error_category not in error_categories:
  138. error_categories[error_category] = 0
  139. error_categories[error_category] += 1
  140. pprint.pprint(error_categories)