File size: 8,569 Bytes
a58d1bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import json
import os
from collections import defaultdict

import gradio as gr


# Global in-memory state (kept minimal on purpose)
CURRENT = {
    "file_path": None,
    "records": [],
    "providers": [],
    "summary_rows": [],
    "request_errors_by_provider": {},
    "toolcall_errors_by_provider": {},
}


def _extract_error_json(error_value):
    if isinstance(error_value, (dict, list)):
        return error_value
    if isinstance(error_value, str):
        # Best-effort: if it's JSON, parse it; else return wrapped
        try_parse = None
        if error_value.startswith("{") or error_value.startswith("["):
            try_parse = json.loads(error_value)
        return try_parse if try_parse is not None else {"error": error_value}
    return {"error": str(error_value)}


def _truncate(s, length=200):
    if not isinstance(s, str):
        return s
    return s if len(s) <= length else s[: length - 1] + "\u2026"


def _compute_summary(records):
    by_provider = defaultdict(lambda: {
        "total": 0,
        "request_errors": 0,
        "tool_calls_present": 0,
        "tool_call_invalid": 0,
        "success": 0,
    })

    request_errors_by_provider = defaultdict(list)
    toolcall_errors_by_provider = defaultdict(list)

    for r in records:
        provider = r.get("provider")
        if provider is None:
            continue
        stats = by_provider[provider]
        stats["total"] += 1

        finish_reason = r.get("finish_reason")
        has_error_field = bool(r.get("error"))
        is_request_error = finish_reason == "error" or has_error_field

        tool_calls_present = bool(r.get("tool_calls_present"))
        tool_calls_valid = bool(r.get("tool_calls_valid")) if tool_calls_present else True
        is_tool_call_invalid = tool_calls_present and (not tool_calls_valid)

        if is_request_error:
            stats["request_errors"] += 1
            request_errors_by_provider[provider].append({
                "sample_id": r.get("sample_id"),
                "model": r.get("model"),
                "finish_reason": finish_reason,
                "error": r.get("error"),
                "_full_record": r,
            })

        if tool_calls_present:
            stats["tool_calls_present"] += 1
        if is_tool_call_invalid:
            stats["tool_call_invalid"] += 1
            toolcall_errors_by_provider[provider].append({
                "sample_id": r.get("sample_id"),
                "model": r.get("model"),
                "finish_reason": finish_reason,
                "error": r.get("error"),
                "_full_record": r,
            })

        is_success = (not is_request_error) and (not is_tool_call_invalid)
        if is_success:
            stats["success"] += 1

    summary_rows = []
    for provider, s in by_provider.items():
        total = s["total"] if s["total"] > 0 else 1
        req_err_rate = s["request_errors"] / total
        tc_err_rate = (s["tool_call_invalid"] / s["tool_calls_present"]) if s["tool_calls_present"] > 0 else 0.0
        success_rate = s["success"] / total
        summary_rows.append({
            "provider": provider,
            "total": s["total"],
            "request_errors": s["request_errors"],
            "request_error_rate": round(req_err_rate, 3),
            "tool_calls_present": s["tool_calls_present"],
            "tool_call_invalid": s["tool_call_invalid"],
            "tool_call_error_rate": round(tc_err_rate, 3),
            "success": s["success"],
            "success_rate": round(success_rate, 3),
        })

    summary_rows.sort(key=lambda x: (-x["success_rate"], x["request_error_rate"], x["tool_call_error_rate"]))
    providers = [row["provider"] for row in summary_rows]

    return summary_rows, providers, request_errors_by_provider, toolcall_errors_by_provider


def load_results(file_path):
    assert isinstance(file_path, str) and len(file_path) > 0
    assert os.path.exists(file_path)
    with open(file_path, "r") as f:
        data = json.load(f)

    records = data.get("records") or []
    assert isinstance(records, list)

    summary_rows, providers, req_errs, tc_errs = _compute_summary(records)

    CURRENT["file_path"] = file_path
    CURRENT["records"] = records
    CURRENT["providers"] = providers
    CURRENT["summary_rows"] = summary_rows
    CURRENT["request_errors_by_provider"] = req_errs
    CURRENT["toolcall_errors_by_provider"] = tc_errs

    def pct_str(x):
        x = x or 0.0
        return f"{x * 100:.1f}%"

    df_rows = [[
        r["provider"],
        r["total"],
        r["request_errors"],
        pct_str(r["request_error_rate"]),
        r["tool_calls_present"],
        r["tool_call_invalid"],
        pct_str(r["tool_call_error_rate"]),
        r["success"],
        pct_str(r["success_rate"]),
    ] for r in summary_rows]

    return (
        gr.update(choices=providers, value=(providers[0] if providers else None)),
        df_rows,
        "Loaded",
        [],
        None,
    )


def _build_error_rows(provider, error_type):
    if not provider:
        return []
    if error_type == "Request errors":
        errs = CURRENT["request_errors_by_provider"].get(provider) or []
    else:
        errs = CURRENT["toolcall_errors_by_provider"].get(provider) or []
    rows = []
    for e in errs:
        preview = e.get("error")
        rows.append([
            e.get("sample_id"),
            e.get("model"),
            e.get("finish_reason"),
            _truncate(preview if isinstance(preview, str) else json.dumps(preview) if preview is not None else ""),
        ])
    return rows


def update_error_table(provider, error_type):
    return _build_error_rows(provider, error_type), None


def on_error_select(evt: gr.SelectData, provider, error_type):
    if not provider:
        return None
    idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index
    if error_type == "Request errors":
        errs = CURRENT["request_errors_by_provider"].get(provider) or []
    else:
        errs = CURRENT["toolcall_errors_by_provider"].get(provider) or []
    if not errs:
        return None
    if idx is None or idx < 0 or idx >= len(errs):
        return None
    rec = errs[idx]
    error_json = _extract_error_json(rec.get("error"))
    if isinstance(error_json, dict) and len(error_json) == 1 and "error" in error_json:
        # If we couldn't parse a structured error, fall back to showing the full record
        return rec.get("_full_record")
    return error_json


def build_ui(default_path):
    with gr.Blocks(title="BFCL Viewer", css=".gradio-container {max-width: 1200px}") as demo:
        gr.Markdown("## BFCL Results Viewer")

        with gr.Row():
            file_in = gr.Textbox(label="Results JSON path", value=default_path, scale=4)
            load_btn = gr.Button("Load", scale=1)
            status = gr.Markdown("")

        summary_df = gr.Dataframe(
            headers=[
                "Provider", "Total", "Req Errs", "Req Err %",
                "Tool Calls", "TC Invalid", "TC Err %",
                "Success", "Success %",
            ],
            value=[],
            interactive=False,
            wrap=True,
            label="Provider reliability summary",
        )

        with gr.Row():
            provider_dd = gr.Dropdown(choices=[], label="Provider", interactive=True)
            err_type = gr.Radio(["Request errors", "Tool-call errors"], value="Request errors", label="Error type")

        errors_df = gr.Dataframe(
            headers=["sample_id", "model", "finish_reason", "error_preview"],
            value=[],
            interactive=False,
            wrap=True,
            label="Errors",
        )

        error_json = gr.JSON(label="Selected error (JSON)")

        load_btn.click(
            fn=load_results,
            inputs=[file_in],
            outputs=[provider_dd, summary_df, status, errors_df, error_json],
        )

        provider_dd.change(
            fn=update_error_table,
            inputs=[provider_dd, err_type],
            outputs=[errors_df, error_json],
        )

        err_type.change(
            fn=update_error_table,
            inputs=[provider_dd, err_type],
            outputs=[errors_df, error_json],
        )

        errors_df.select(
            fn=on_error_select,
            inputs=[provider_dd, err_type],
            outputs=[error_json],
        )

    return demo


DEFAULT_PATH = "./bfcl_inference_results_20251029_154417.json"


if __name__ == "__main__":
    app = build_ui(DEFAULT_PATH)
    app.launch()