"""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()