File size: 6,730 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/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!")