llm-bench

"""Tool-calling and structured-output probes for the conformance preflight, moved verbatim from
coding-suite (2026-10-12). Each probe: id, tools (None = none declared), messages, validator(resp)
-> (ok, detail[, extra]). They test that a call or JSON object comes back well-formed through the
lane's template, parser and provider; a wrong value is the model's, a call that never arrives as a
call is usually not (conformance tells the two apart). tc-xml is the probe a provider's Qwen tool
parser swallowed in 2026-10 (DeepInfra, plain-text <tool_call> with no tools declared).
"""
import json
import re

from bench.core import client

WEATHER_TOOL = [{"type": "function", "function": {
    "name": "get_weather",
    "description": "Get the current weather for a location.",
    "parameters": {"type": "object", "properties": {
        "location": {"type": "string", "description": "City name"},
        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
        "required": ["location", "unit"]}}}]
CALC_TOOL = [{"type": "function", "function": {
    "name": "calculator",
    "description": "Evaluate an arithmetic expression.",
    "parameters": {"type": "object", "properties": {"expression": {"type": "string"}},
        "required": ["expression"]}}}]
WEB_TOOL = {"type": "function", "function": {
    "name": "web_search", "description": "Search the web.",
    "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
        "required": ["query"]}}}
THREE_TOOLS = [WEATHER_TOOL[0], CALC_TOOL[0], WEB_TOOL]
TIMER_TOOL = [{"type": "function", "function": {
    "name": "set_timer", "description": "Set a countdown timer.",
    "parameters": {"type": "object", "properties": {"seconds": {"type": "integer", "description": "duration in seconds"}},
        "required": ["seconds"]}}}]



def _first_call(resp, name):
    """(arguments, None) if the first tool call is `name` with JSON arguments, else (None, why)."""
    tcs = client.tool_calls(resp)
    if not tcs:
        return None, "no tool call; content=%r" % client.content(resp)[:140]
    fn = tcs[0]["function"]
    if fn["name"] != name:
        return None, "picked %s" % fn["name"]
    try:
        return json.loads(fn["arguments"]), None
    except Exception:
        return None, "bad args %r" % str(fn["arguments"])[:120]


def _json_object(resp):
    """(obj, None) for the outermost {...} of the answer, else (None, why)."""
    c = client.content(resp).strip()
    m = re.search(r"\{.*\}", c, re.DOTALL)
    if not m:
        return None, "no JSON object in output: %r" % c[:160]
    try:
        return json.loads(m.group(0)), None
    except Exception as e:
        return None, "JSON parse error: %s | %r" % (e, m.group(0)[:160])


def _v_native(resp):
    args, why = _first_call(resp, "get_weather")
    if why:
        return False, why
    loc_ok = "paris" in str(args.get("location", "")).lower()
    unit_ok = str(args.get("unit", "")).lower() == "celsius"
    return (loc_ok and unit_ok), "args=%s loc_ok=%s unit_ok=%s" % (args, loc_ok, unit_ok)


# One <tool_call>{...}</tool_call> line.
_TC_OPEN = "<tool_call>"
_TC_CLOSE = "</tool_call>"


def _v_xml(resp):
    """Returns (ok, detail, extra). A missing closing tag is accepted (extra xml_unclosed)."""
    c = client.content(resp)
    i = c.find(_TC_OPEN)
    if i < 0:
        return False, "no %s{...}%s found: %r" % (_TC_OPEN, _TC_CLOSE, c[:160]), {}
    rest = c[i + len(_TC_OPEN):].lstrip()
    if not rest.startswith("{"):
        return False, "inner JSON did not parse: %r" % rest[:160], {}
    try:
        obj, end = json.JSONDecoder().raw_decode(rest)
    except ValueError:
        return False, "inner JSON did not parse: %r" % rest[:160], {}
    tail = rest[end:].strip()
    unclosed = not tail.startswith(_TC_CLOSE)
    if unclosed and tail:
        return False, "no %s after the JSON: %r" % (_TC_CLOSE, tail[:80]), {}
    if not isinstance(obj, dict):
        return False, "tool call is not an object: %r" % (obj,), {"xml_unclosed": unclosed}
    args = obj.get("arguments", obj.get("parameters", {}))
    if not isinstance(args, dict):
        args = {}
    name_ok = obj.get("name") == "web_search"
    q_ok = "gemma" in str(args.get("query", "")).lower()
    limit_ok = str(args.get("limit")) == "5"
    return ((name_ok and q_ok and limit_ok),
            "obj=%s name_ok=%s q_ok=%s limit_ok=%s" % (obj, name_ok, q_ok, limit_ok),
            {"xml_unclosed": unclosed})


def _v_json(resp):
    obj, why = _json_object(resp)
    if why:
        return False, why
    name_ok = isinstance(obj.get("name"), str) and "maria" in obj["name"].lower()
    age_ok = obj.get("age") == 34
    sk = obj.get("skills")
    skills_ok = isinstance(sk, list) and {"go", "rust"} <= {str(x).lower() for x in sk}
    return (name_ok and age_ok and skills_ok), "obj=%s name=%s age=%s skills=%s" % (obj, name_ok, age_ok, skills_ok)


def _v_notool(resp):
    tcs = client.tool_calls(resp)
    if tcs:
        return False, "incorrectly called a tool: %s" % tcs[0]["function"]["name"]
    c = client.content(resp).lower()
    return ("paris" in c), "answered in text, mentions Paris=%s" % ("paris" in c)


def _v_multi(resp):
    tcs = client.tool_calls(resp)
    locs = []
    for tc in tcs:
        try:
            a = json.loads(tc["function"]["arguments"])
        except Exception:
            a = {}
        locs.append(str(a.get("location", "")).lower())
    blob = " ".join(locs)
    ok = len(tcs) >= 2 and "paris" in blob and "tokyo" in blob
    return ok, "n_calls=%d locs=%s" % (len(tcs), locs)


def _v_select(resp):
    a, why = _first_call(resp, "calculator")
    if why:
        return False, why
    expr = str(a.get("expression", ""))
    return ("47" in expr and "89" in expr), "expr=%r" % expr


def _v_nested(resp):
    o, why = _json_object(resp)
    if why:
        return False, why
    svc = o.get("service", {})
    ok = (isinstance(svc, dict) and str(svc.get("name", "")).lower() == "api"
          and svc.get("port") == 8080 and o.get("replicas") == 3
          and "prod" in str(o.get("env", "")).lower())
    return ok, "obj=%s" % o


def _v_derived(resp):
    a, why = _first_call(resp, "set_timer")
    if why:
        return False, why
    return a.get("seconds") == 150, "args=%s" % a

_XML_SYS = ("You can call tools. To call a tool you MUST output exactly one line of the form "
            "<tool_call>{\"name\": \"<tool>\", \"arguments\": {...}}</tool_call> "
            "and nothing else \u2014 no prose, no markdown. "
            "Available tool: web_search(query: string, limit: integer).")


TOOLCALL = [
    {"id": "tc-native", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_native,
     "messages": [{"role": "user", "content": "What is the current weather in Paris? Use celsius."}]},
    {"id": "tc-xml", "cat": "toolcall", "tools": None, "validator": _v_xml,
     "messages": [
        {"role": "system", "content": _XML_SYS},
        {"role": "user", "content": "Search the web for 'gemma benchmarks' and return at most 5 results."}]},
    {"id": "tc-json", "cat": "toolcall", "tools": None, "validator": _v_json,
     "messages": [
        {"role": "system", "content": "Output ONLY a single JSON object and nothing else. No markdown fences, no commentary."},
        {"role": "user", "content": "Extract this person into JSON with keys name (string), age (integer), skills (array of strings): 'Maria is 34 years old and knows Go and Rust.'"}]},
    {"id": "tc-notool", "cat": "toolcall", "tools": CALC_TOOL, "validator": _v_notool,
     "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}]},
    {"id": "tc-multi", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_multi,
     "messages": [{"role": "user", "content": "What's the weather in Paris and in Tokyo right now? Use celsius for both."}]},
    {"id": "tc-select", "cat": "toolcall", "tools": THREE_TOOLS, "validator": _v_select,
     "messages": [{"role": "user", "content": "Using the tools available to you, compute 47 * 89 and give me the exact product."}]},
    {"id": "tc-nested-json", "cat": "toolcall", "tools": None, "validator": _v_nested,
     "messages": [
        {"role": "system", "content": "Output ONLY a single JSON object, no markdown, no commentary."},
        {"role": "user", "content": "Produce a deployment config JSON with this shape: {\"service\": {\"name\": string, \"port\": integer}, \"replicas\": integer, \"env\": string}. The service is named 'api', listens on port 8080, runs 3 replicas, in the production environment."}]},
    {"id": "tc-derived", "cat": "toolcall", "tools": TIMER_TOOL, "validator": _v_derived,
     "messages": [{"role": "user", "content": "Set a timer for two and a half minutes."}]},
]