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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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""Standalone evaluator for any OpenAI-compatible tool-calling server.

Scores a running server (llama-server --jinja, vLLM, SGLang, ...) against
``data_native/test.jsonl`` without any local model weights.

Data schema per line::

    {"tools": [{"name", "description", "parameters"}],
     "messages": [{"role": "user", ...},
                  {"role": "assistant", "content": "", "tool_calls": [...]} ...]}

Abstention rows have a final assistant message with plain ``content`` and no
``tool_calls``.

Example::

    python pipeline/eval_openai.py --base-url http://127.0.0.1:8080/v1 \\
        --model local --data data_native/test.jsonl \\
        --out reports/runtime_eval --limit 100
    python pipeline/eval_openai.py --base-url http://127.0.0.1:8080/v1 \\
        --model local --data data_native/mt_test.jsonl \\
        --out reports/runtime_eval_mt --staged

Requires ``pipeline/metrics_lib.py`` (imported, not created here) and the
third-party package ``requests``. Everything else is stdlib.
"""

from __future__ import annotations

import argparse
import json
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Tuple

import requests

sys.path.insert(0, str(Path(__file__).resolve().parent))

_METRICS: Dict[str, Any] | None = None


def _metrics() -> Dict[str, Any]:
    """Lazily import pipeline/metrics_lib.py (assumed to exist at eval time).

    The import is deferred so ``--help`` and CLI parsing work even when no
    server (or metrics module) is present. This function does not create or
    stub the module; it only imports the documented names.
    """
    global _METRICS
    if _METRICS is None:
        from metrics_lib import (  # type: ignore  # noqa: E402
            parse_calls,
            canon_call,
            categorize,
            failure_bucket,
        )
        _METRICS = {
            "parse_calls": parse_calls,
            "canon_call": canon_call,
            "categorize": categorize,
            "failure_bucket": failure_bucket,
        }
    return _METRICS


# --------------------------------------------------------------------------- #
# Conversion helpers
# --------------------------------------------------------------------------- #

def load_jsonl(path: str | Path) -> List[Dict[str, Any]]:
    """Load a JSONL file, skipping blank lines."""
    rows: List[Dict[str, Any]] = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def to_openai_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """Convert native tool defs to OpenAI ``{"type": "function", ...}`` form."""
    out: List[Dict[str, Any]] = []
    for t in tools or []:
        fn: Dict[str, Any] = {
            "name": t.get("name", ""),
            "description": t.get("description", ""),
        }
        params = t.get("parameters")
        if params is not None:
            if isinstance(params, dict):
                params = dict(params)
                # Native data uses "dict"; OpenAI expects "object".
                if params.get("type") == "dict":
                    params["type"] = "object"
            fn["parameters"] = params
        out.append({"type": "function", "function": fn})
    return out


def to_openai_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """Convert a native message prefix to OpenAI chat format.

    Native assistant turns carry ``tool_calls: [{name, arguments(dict)}]``
    without wire ids; we synthesize ``id`` values. Native ``tool`` turns
    lack ``tool_call_id``; we bind them to the most recent assistant call id.
    """
    out: List[Dict[str, Any]] = []
    last_ids: List[str] = []
    for k, m in enumerate(messages):
        role = m.get("role", "user")
        if role == "tool":
            content = m.get("content", "")
            if not isinstance(content, str):
                content = json.dumps(content, ensure_ascii=False)
            tool_msg: Dict[str, Any] = {
                "role": "tool",
                "content": content,
                "tool_call_id": m.get("tool_call_id") or (last_ids[0] if last_ids else "call_0"),
            }
            out.append(tool_msg)
            continue
        if role == "assistant":
            tc = m.get("tool_calls") or []
            content = m.get("content", "")
            if content is None:
                content = ""
            if not isinstance(content, str):
                content = json.dumps(content, ensure_ascii=False)
            if tc:
                last_ids = [f"call_{k}_{j}" for j in range(len(tc))]
                oai_tc: List[Dict[str, Any]] = []
                for j, c in enumerate(tc):
                    args = c.get("arguments", {})
                    oai_tc.append({
                        "id": last_ids[j],
                        "type": "function",
                        "function": {
                            "name": c.get("name", ""),
                            "arguments": json.dumps(args, ensure_ascii=False)
                            if not isinstance(args, str) else args,
                        },
                    })
                out.append({"role": "assistant", "content": content, "tool_calls": oai_tc})
            else:
                out.append({"role": "assistant", "content": content})
            continue
        # user / system / anything else: pass content through as string.
        content = m.get("content", "")
        if not isinstance(content, str):
            content = json.dumps(content, ensure_ascii=False)
        out.append({"role": role, "content": content})
    return out


def expected_calls(message: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Ground-truth calls from a native assistant message (``[]`` if abstain)."""
    tc = message.get("tool_calls") or []
    return [{"name": c.get("name", ""), "arguments": c.get("arguments", {})} for c in tc]


def parse_response(msg: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], str]:
    """Parse an OpenAI response message into native-style calls.

    Prefer ``message.tool_calls[].function`` (``arguments`` may be a JSON
    string); fall back to XML parsing of ``message.content`` via
    ``metrics_lib.parse_calls``.
    """
    content = msg.get("content") or ""
    if not isinstance(content, str):
        content = json.dumps(content, ensure_ascii=False)
    raw: str = content
    tc = msg.get("tool_calls") or []
    if tc:
        calls: List[Dict[str, Any]] = []
        for c in tc:
            fn = c.get("function", c) if isinstance(c, dict) else {}
            name = fn.get("name", "") if isinstance(fn, dict) else ""
            args = fn.get("arguments", {}) if isinstance(fn, dict) else {}
            if isinstance(args, str):
                s = args.strip()
                if not s:
                    args = {}
                else:
                    try:
                        args = json.loads(s)
                    except (json.JSONDecodeError, ValueError):
                        args = {}
            if not isinstance(args, dict):
                args = {}
            calls.append({"name": name, "arguments": args})
        if not raw:
            raw = json.dumps(
                [{"name": c["name"], "arguments": c["arguments"]} for c in calls],
                ensure_ascii=False,
            )
        return calls, raw
    try:
        calls = _metrics()["parse_calls"](content)
    except Exception:
        calls = []
    if not isinstance(calls, list):
        calls = []
    return calls, raw


def canon_sorted(calls: List[Dict[str, Any]]) -> List[Any]:
    """Canonical sort key for a call list (order-insensitive compare)."""
    canon_call = _metrics()["canon_call"]
    return sorted(canon_call(c) for c in calls)


# --------------------------------------------------------------------------- #
# HTTP
# --------------------------------------------------------------------------- #

def chat_once(
    session: requests.Session,
    url: str,
    payload: Dict[str, Any],
    timeout: float,
) -> Tuple[Dict[str, Any] | None, str]:
    """POST one /chat/completions request; never raises.

    Returns ``(message, "")`` on success or ``(None, "ERROR: ...")`` on any
    transport / HTTP-status / schema failure.
    """
    try:
        resp = session.post(url, json=payload, timeout=timeout)
    except requests.RequestException as exc:
        return None, f"ERROR: request failed: {exc}"
    if resp.status_code >= 400:
        return None, f"ERROR: HTTP {resp.status_code}: {resp.text[:300]}"
    try:
        data = resp.json()
        msg = data["choices"][0]["message"]
    except (ValueError, KeyError, IndexError, TypeError) as exc:
        return None, f"ERROR: bad response schema: {exc}"
    if not isinstance(msg, dict):
        return None, "ERROR: bad response schema: message is not an object"
    return msg, ""


# --------------------------------------------------------------------------- #
# Eval
# --------------------------------------------------------------------------- #

def evaluate_row(
    session: requests.Session,
    url: str,
    model: str,
    tools: List[Dict[str, Any]],
    prefix: List[Dict[str, Any]],
    expected: List[Dict[str, Any]],
    max_tokens: int,
    timeout: float,
) -> Tuple[List[Dict[str, Any]], str, bool]:
    """Query the server once; returns (predicted, raw, transport_ok)."""
    payload = {
        "model": model,
        "messages": to_openai_messages(prefix),
        "tools": to_openai_tools(tools),
        "tool_choice": "auto",
        "temperature": 0,
        "max_tokens": max_tokens,
    }
    msg, err = chat_once(session, url, payload, timeout)
    if msg is None:
        return [], err, False
    predicted, raw = parse_response(msg)
    return predicted, raw, True


def safe_bucket(expected: List[Dict[str, Any]], predicted: List[Dict[str, Any]], raw: str) -> str:
    """Call metrics_lib.failure_bucket without ever aborting the run."""
    try:
        return str(_metrics()["failure_bucket"](expected, predicted, raw))
    except Exception as exc:
        return f"eval_error: {exc}"


def safe_category(row: Dict[str, Any]) -> str:
    """Call metrics_lib.categorize without ever aborting the run."""
    try:
        return str(_metrics()["categorize"](row))
    except Exception:
        return "unknown"


def print_table(metrics: Dict[str, Any]) -> None:
    """Print a compact ASCII summary table."""
    rows = [
        ("n", str(metrics.get("n", 0))),
        ("exact_call_rate", f"{metrics.get('exact_call_rate', 0.0):.3f}"),
        ("name_accuracy", f"{metrics.get('name_accuracy', 0.0):.3f}"),
        ("parse_rate", f"{metrics.get('parse_rate', 0.0):.3f}"),
        ("abstention_accuracy", f"{metrics.get('abstention_accuracy', 0.0):.3f}"),
        ("false_positive_rate", f"{metrics.get('false_positive_rate', 0.0):.3f}"),
    ]
    if "stage1_exact" in metrics:
        rows.append(("stage1_exact", f"{metrics['stage1_exact']:.3f}"))
    if "stage2_type_accuracy" in metrics:
        rows.append(("stage2_type_accuracy", f"{metrics['stage2_type_accuracy']:.3f}"))
    width = max(len(k) for k, _ in rows)
    print("=" * (width + 12))
    print(f"{'metric':<{width}} | value")
    print("-" * (width + 12))
    for k, v in rows:
        print(f"{k:<{width}} | {v}")
    print("-" * (width + 12))
    by_cat = metrics.get("by_category", {})
    if by_cat:
        print("by_category:")
        for cat in sorted(by_cat):
            c = by_cat[cat]
            print(
                f"  {cat}: n={c.get('n', 0)} "
                f"exact={c.get('exact_call_rate', 0.0):.3f} "
                f"name={c.get('name_accuracy', 0.0):.3f}"
            )
    print("=" * (width + 12))


def build_parser() -> argparse.ArgumentParser:
    """Build the CLI parser."""
    ap = argparse.ArgumentParser(
        description="Score an OpenAI-compatible tool-calling server "
        "against data_native/test.jsonl (or any native JSONL).",
        epilog="Example: python pipeline/eval_openai.py "
        "--base-url http://127.0.0.1:8080/v1 --model local "
        "--data data_native/test.jsonl --out reports/runtime_eval --limit 100",
    )
    ap.add_argument("--base-url", default="http://127.0.0.1:8080/v1",
                    help="Server base URL (appended with /chat/completions).")
    ap.add_argument("--model", default="local", help="Model name sent in the request.")
    ap.add_argument("--data", default="data_native/test.jsonl", help="Input native JSONL.")
    ap.add_argument("--out", default="reports/runtime_eval", help="Output directory.")
    ap.add_argument("--limit", type=int, default=0,
                    help="Max rows to evaluate (0 = all).")
    ap.add_argument("--staged", action="store_true",
                    help="For 4-message rows also query stage 1 (messages[:1]) and "
                    "report stage1_exact / stage2_type_accuracy.")
    ap.add_argument("--timeout", type=float, default=120.0,
                    help="Per-request timeout in seconds.")
    ap.add_argument("--max-tokens", type=int, default=256,
                    help="max_tokens sent per request.")
    return ap


def main() -> None:
    """Run the evaluation and write predictions.jsonl + metrics.json."""
    ap = build_parser()
    args = ap.parse_args()

    try:
        _metrics()
    except ImportError as exc:
        print(f"error: pipeline/metrics_lib.py is required but could not be imported: {exc}",
              file=sys.stderr)
        sys.exit(2)

    rows = load_jsonl(args.data)
    if args.limit and args.limit > 0:
        rows = rows[: args.limit]

    url = args.base_url.rstrip("/") + "/chat/completions"
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)

    session = requests.Session()
    details: List[Dict[str, Any]] = []
    n_exact = n_name = n_parse = 0
    neg_total = neg_ok = neg_fp = 0
    by_cat: Dict[str, Dict[str, int]] = {}
    # Staged accumulators (4-message rows only).
    s1_total = s1_exact = 0
    s2_total = s2_type_ok = 0

    t0 = time.time()
    for i, row in enumerate(rows):
        messages = row.get("messages", [])
        tools = row.get("tools", [])
        category = safe_category(row)
        expected = expected_calls(messages[-1]) if messages else []
        prefix = messages[:-1] if len(messages) > 1 else messages

        predicted, raw, ok = evaluate_row(
            session, url, args.model, tools, prefix, expected,
            args.max_tokens, args.timeout,
        )
        if ok:
            exact = canon_sorted(predicted) == canon_sorted(expected)
            name_match = sorted(c.get("name", "") for c in predicted) == sorted(
                c.get("name", "") for c in expected
            )
            parse_ok = bool(predicted) or not expected
        else:
            # Transport / HTTP / schema failure: never award points.
            exact = False
            name_match = False
            parse_ok = False
        bucket = safe_bucket(expected, predicted, raw)

        n_exact += exact
        n_name += name_match
        n_parse += parse_ok
        if not expected:
            neg_total += 1
            neg_ok += not predicted
            neg_fp += bool(predicted)
        cell = by_cat.setdefault(category, {"n": 0, "exact": 0, "name": 0})
        cell["n"] += 1
        cell["exact"] += exact
        cell["name"] += name_match

        details.append({
            "i": i,
            "category": category,
            "expected": expected,
            "predicted": predicted,
            "raw": raw[:2000] if isinstance(raw, str) else raw,
            "exact": exact,
            "name_match": name_match,
            "bucket": bucket,
        })

        # Staged multi-turn scoring for 4-message loops.
        if args.staged and len(messages) == 4:
            exp1 = expected_calls(messages[1])
            pred1, _, ok1 = evaluate_row(
                session, url, args.model, tools, messages[:1], exp1,
                args.max_tokens, args.timeout,
            )
            s1_total += 1
            # Stage 2 reuses the main request above (prefix == messages[:3]).
            s2_total += 1
            if ok1 and canon_sorted(pred1) == canon_sorted(exp1):
                s1_exact += 1
            exp2 = expected  # messages[3] ground truth
            if (not predicted) == (not exp2) and ok:
                s2_type_ok += 1

        if (i + 1) % 25 == 0 or (i + 1) == len(rows):
            print(f"[{i + 1}/{len(rows)}] exact={n_exact / (i + 1):.3f}", flush=True)

    n = len(rows)
    metrics: Dict[str, Any] = {
        "n": n,
        "exact_call_rate": n_exact / n if n else 0.0,
        "name_accuracy": n_name / n if n else 0.0,
        "parse_rate": n_parse / n if n else 0.0,
        "abstention_accuracy": (neg_ok / neg_total) if neg_total else 0.0,
        "false_positive_rate": (neg_fp / neg_total) if neg_total else 0.0,
        "n_abstention": neg_total,
        "by_category": {
            cat: {
                "n": c["n"],
                "exact_call_rate": c["exact"] / c["n"] if c["n"] else 0.0,
                "name_accuracy": c["name"] / c["n"] if c["n"] else 0.0,
            }
            for cat, c in by_cat.items()
        },
        "model": args.model,
        "base_url": args.base_url,
        "data": str(args.data),
        "elapsed_s": round(time.time() - t0, 1),
    }
    if args.staged:
        metrics["stage1_n"] = s1_total
        metrics["stage2_n"] = s2_total
        metrics["stage1_exact"] = (s1_exact / s1_total) if s1_total else 0.0
        metrics["stage2_type_accuracy"] = (s2_type_ok / s2_total) if s2_total else 0.0

    (out / "predictions.jsonl").write_text(
        "\n".join(json.dumps(d, ensure_ascii=False) for d in details), encoding="utf-8"
    )
    (out / "metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
    print(f"wrote {out / 'predictions.jsonl'} + {out / 'metrics.json'}")
    print_table(metrics)


if __name__ == "__main__":
    main()