AINativeBench / data /processed /RQ1 /SQLAssistant-MCP /evaluate_success.py
王子睿
restructure + add files
8c10cf2
Raw
History Blame
6.73 kB
#!/usr/bin/env python3
"""
Collect success rate statistics for SQLAssistant-MCP task across models.
Success criteria: Whether get_database_schema Tool was executed in execution_path.md
(Not calling this Tool means the model doesn't know the database schema and can only guess,
which indicates hallucination)
"""
import json
import re
from pathlib import Path
from collections import defaultdict
# Base directory and model list
BASE_DIR = Path("/Users/wzr/TOSEM-2025/RESULTS")
MODELS = [
"DeepSeek-R1",
"DeepSeek-V3-1",
"GPT-4o-mini",
"GPT-5",
"Gemini-2.5-flash",
"Gemini-2.5-flash-nothinking",
"Qwen3-235b",
]
PROJECT_NAME = "SQLAssistant-MCP"
# Required Tool (success criteria)
REQUIRED_TOOL = "get_database_schema"
def check_tool_executed(execution_path_file: Path) -> bool:
"""
Check if the required Tool was executed in execution_path.md.
Args:
execution_path_file: Path to execution_path.md file
Returns:
True if get_database_schema was called, False otherwise
"""
if not execution_path_file.exists():
return False
try:
with open(execution_path_file, "r", encoding="utf-8") as f:
content = f.read()
# Search for [Tool] get_database_schema in Execution Path Tree
pattern = rf"\[Tool\]\s+{REQUIRED_TOOL}"
return bool(re.search(pattern, content))
except Exception as e:
print(f" [ERROR] Reading {execution_path_file}: {e}")
return False
def analyze_model_results():
"""Analyze execution results for all models."""
results = {}
for model in MODELS:
test_results_dir = BASE_DIR / model / PROJECT_NAME / "test_results"
if not test_results_dir.exists():
print(
f"[WARN] Model {model} test_results directory not found: {test_results_dir}"
)
continue
model_stats = {
"success_count": 0,
"failure_count": 0,
"total_count": 0,
"sessions": [],
}
# Iterate through all session subdirectories
for session_dir in sorted(test_results_dir.iterdir()):
if not session_dir.is_dir():
continue
execution_path_file = session_dir / "execution_path.md"
execution_log_file = session_dir / "execution_log.json"
# Need at least execution_path.md to determine success
if not execution_path_file.exists():
continue
try:
# Check if required Tool was executed
tool_executed = check_tool_executed(execution_path_file)
# Try to get additional info (if execution_log.json exists)
user_input = "unknown"
if execution_log_file.exists():
try:
with open(execution_log_file, "r", encoding="utf-8") as f:
log_data = json.load(f)
user_input = log_data.get("user_input", "unknown")
except:
pass
model_stats["total_count"] += 1
if tool_executed:
model_stats["success_count"] += 1
else:
model_stats["failure_count"] += 1
model_stats["sessions"].append(
{
"session": session_dir.name,
"success": tool_executed,
"user_input": (
user_input[:100]
if isinstance(user_input, str)
else str(user_input)[:100]
),
"reason": (
"Required Tool called"
if tool_executed
else f"Required Tool not called ({REQUIRED_TOOL})"
),
}
)
except Exception as e:
print(f"[ERROR] Processing {session_dir}: {e}")
results[model] = model_stats
return results
def print_summary(results):
"""Print statistics summary."""
print("\n" + "=" * 100)
print(f"Model Execution Results - {PROJECT_NAME}")
print(f"Success criteria: Whether required Tool ({REQUIRED_TOOL}) was executed")
print("=" * 100 + "\n")
# Header
print(
f"{'Model':<35} {'Total':<10} {'Success':<10} {'Failure':<10} {'Success Rate':<15}"
)
print("-" * 100)
for model, stats in results.items():
total = stats["total_count"]
success = stats["success_count"]
failure = stats["failure_count"]
if total > 0:
success_rate = (success / total) * 100
print(
f"{model:<35} {total:<10} {success:<10} {failure:<10} {success_rate:>6.1f}%"
)
else:
print(f"{model:<35} {'No data':<10}")
print("=" * 100)
def save_detailed_results(results, output_file="success_detailed_results.json"):
"""Save detailed results to JSON file."""
output_path = Path(__file__).parent / output_file
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\n[OK] Detailed results saved: {output_path}")
def save_csv_summary(results, output_file="success_rate.csv"):
"""Save summary to CSV file."""
import csv
output_path = Path(__file__).parent / output_file
with open(output_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(
["Model", "Total", "Success", "Failure", "Success_Rate(%)", "Criteria"]
)
for model, stats in results.items():
total = stats["total_count"]
success = stats["success_count"]
failure = stats["failure_count"]
success_rate = (success / total * 100) if total > 0 else 0
writer.writerow(
[
model,
total,
success,
failure,
f"{success_rate:.2f}",
f"Called {REQUIRED_TOOL} Tool",
]
)
print(f"[OK] CSV summary saved: {output_path}")
if __name__ == "__main__":
print(f"Starting success rate statistics for {PROJECT_NAME}...")
print(
f"Success criteria: Whether {REQUIRED_TOOL} Tool was executed in execution_path.md\n"
)
results = analyze_model_results()
print_summary(results)
save_detailed_results(results)
save_csv_summary(results)
print("\n[OK] Statistics complete!")