File size: 5,796 Bytes
688186a | 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 | #!/usr/bin/env python3
"""Tool-calling checker for an OpenAI-compatible endpoint (vLLM, inkling tool-call parser).
reasoning_effort is pinned through chat_template_kwargs and recorded in the --out JSON.
"""
import argparse
import json
from collections import Counter
from pathlib import Path
from jsonschema import ValidationError, validate
from openai import OpenAI
def run_check(
client: OpenAI,
tools: list,
cases: list[dict],
temperature: float,
runs: int,
model: str,
reasoning_effort: str,
max_tokens: int,
) -> tuple[Counter[str], list]:
schemas = {t["function"]["name"]: t["function"]["parameters"] for t in tools}
c: Counter[str] = Counter()
fails: list[tuple] = []
for _run in range(runs):
for i, case in enumerate(cases):
exp = case["expected"]
r = client.chat.completions.create(
model=model,
messages=case["messages"],
tools=tools,
tool_choice="auto",
temperature=temperature,
max_tokens=max_tokens,
extra_body={"chat_template_kwargs": {"reasoning_effort": reasoning_effort}},
)
msg = r.choices[0].message
calls = msg.tool_calls or []
c["total"] += 1
if exp is None:
c["no_tool_cases"] += 1
if not calls:
c["no_tool_ok"] += 1
else:
fails.append((i, "called tool when none expected", calls[0].function.name))
continue
c["tool_cases"] += 1
if not calls:
fails.append((i, "no tool call", (msg.content or "")[:120]))
continue
call = calls[0].function
try:
args = json.loads(call.arguments)
c["parse_ok"] += 1
except json.JSONDecodeError:
fails.append((i, "unparseable args", call.arguments[:120]))
continue
if call.name != exp["name"]:
fails.append((i, "wrong tool", call.name))
continue
c["name_ok"] += 1
try:
validate(args, schemas[call.name])
c["schema_ok"] += 1
except ValidationError as e:
fails.append((i, "schema violation", str(e)))
continue
sub = exp.get("args_subset", {})
if all(args.get(k) == v for k, v in sub.items()):
c["exact_ok"] += 1
else:
fails.append((i, "wrong arg values", args))
return c, fails
def summarize(c: Counter[str]) -> dict:
tc, nc = max(c["tool_cases"], 1), max(c["no_tool_cases"], 1)
return {
"tool_cases": c["tool_cases"],
"parse_rate": c["parse_ok"] / tc,
"name_rate": c["name_ok"] / tc,
"schema_rate": c["schema_ok"] / tc,
"exact_rate": c["exact_ok"] / tc,
"no_tool_cases": c["no_tool_cases"],
"abstain_rate": c["no_tool_ok"] / nc,
}
def print_summary(label: str, c: Counter[str]) -> None:
s = summarize(c)
tc, nc = max(c["tool_cases"], 1), max(c["no_tool_cases"], 1)
print(f"=== {label} ===")
print(f"tool cases : {c['tool_cases']}")
print(f" JSON parse rate : {100 * c['parse_ok'] / tc:.1f}%")
print(f" correct tool name : {100 * c['name_ok'] / tc:.1f}%")
print(f" schema-valid args : {100 * c['schema_ok'] / tc:.1f}%")
print(f" exact arg match : {100 * c['exact_ok'] / tc:.1f}%")
print(f"no-tool cases : {c['no_tool_cases']}")
print(f" correctly abstained : {100 * c['no_tool_ok'] / nc:.1f}%")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("tools", default="configs/tools.json", nargs="?")
parser.add_argument("cases", default="configs/cases.jsonl", nargs="?")
parser.add_argument("--base-url", default="http://localhost:8000/v1")
parser.add_argument("--model", default="inkling", help="served model name")
parser.add_argument("--reasoning-effort", default="low")
parser.add_argument(
"--max-tokens", type=int, default=16384, help="room for reasoning before the tool call"
)
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--runs", type=int, default=1)
parser.add_argument("--out", default=None, help="JSON summary path")
parser.add_argument("--failures", default=None, help="failure dump JSON path")
args = parser.parse_args()
with open(args.tools, encoding="utf-8") as f:
tools = json.load(f)
with open(args.cases, encoding="utf-8") as f:
cases = [json.loads(line) for line in f if line.strip()]
client = OpenAI(base_url=args.base_url, api_key="EMPTY")
c, fails = run_check(client, tools, cases, args.temperature, args.runs,
args.model, args.reasoning_effort, args.max_tokens)
print_summary(f"T={args.temperature} runs={args.runs}", c)
print("\nfirst 15 failures:")
for f in fails[:15]:
print(" ", f)
out_dir = Path(args.out).parent if args.out else Path(".")
failures_path = args.failures or str(out_dir / "tool_failures.json")
with open(failures_path, "w", encoding="utf-8") as f:
json.dump(fails, f, indent=1, default=str)
if args.out:
payload = {
"temperature": args.temperature,
"runs": args.runs,
"reasoning_effort": args.reasoning_effort,
"model": args.model,
"summary": summarize(c),
"failures_path": failures_path,
}
Path(args.out).write_text(json.dumps(payload, indent=2) + "\n")
if __name__ == "__main__":
main()
|