#!/usr/bin/env python3
"""effortcheck.py - check which reasoning_effort values an OpenAI-compatible server honors.

For each effort value it reports one of
  REJECTED   the server answered 4xx/5xx (status and message shown)
  DEFAULT    accepted, and the rendered prompt is identical to the prompt without reasoning_effort
             (the value is the template's default, or the template ignores it)
  HONORED    accepted and the prompt changes (values with identical prompts are listed as aliases)
  ACCEPTED   accepted; the prompt could not be inspected (use --max-tokens to compare reasoning length)

How the prompt is inspected (no tokens are generated for this part):
  llama-server  POST /apply-template with the same body as /v1/chat/completions
  vLLM          POST /tokenize with chat_template_kwargs {reasoning_effort, enable_thinking: effort != "none"},
                which is what vLLM v0.22.0+ chat completions put into the template
                (v0.34.0's /tokenize ignores a top-level reasoning_effort, so it is not used there)
Every value is also sent to /v1/chat/completions (max_tokens 1 by default) for the real HTTP status.
With --max-tokens N (e.g. 2048) it also reports the reasoning length per value from the response.

Standard library only. Python 3.8+.
usage: python3 effortcheck.py --base-url http://localhost:8080/v1 --model <name> [--max-tokens 2048]
"""
import argparse, json, sys, urllib.request, urllib.error

LEVELS = ["none", "off", "minimal", "low", "medium", "high", "xhigh", "max"]


def call(url, body, key, timeout):
    data = json.dumps(body).encode()
    req = urllib.request.Request(url, data, {"Content-Type": "application/json", "Authorization": "Bearer " + key})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            raw = r.read() or b"{}"
            try:
                return r.status, json.loads(raw)
            except ValueError:
                return r.status, {"raw": raw[:300].decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        txt = e.read().decode("utf-8", "replace")
        try:
            return e.code, json.loads(txt)
        except ValueError:
            return e.code, {"raw": txt}
    except (urllib.error.URLError, OSError) as e:
        return 0, {"raw": str(e)}


def message_of(j):
    if not isinstance(j, dict):
        return json.dumps(j)[:220]
    e = j.get("error")
    if isinstance(e, dict):
        m = e.get("message", "")
    elif isinstance(e, str):
        m = e
    else:
        m = j.get("message") or j.get("detail") or j.get("raw") or json.dumps(j)
    m = str(m)
    # llama.cpp prefixes template errors with a source excerpt; keep the last line
    lines = [l for l in m.strip().splitlines() if l.strip()]
    return (lines[-1] if lines else m)[:220]


def root_of(base):
    b = base.rstrip("/")
    return b[:-3] if b.endswith("/v1") else b


def render_probe(args, root, msgs, effort, kind):
    """Render the prompt without generating. Returns (status, prompt-or-tokens-or-error)."""
    if kind == "llama":
        body = {"messages": msgs}
        if effort is not None:
            body["reasoning_effort"] = effort
        st, j = call(root + "/apply-template", body, args.api_key, args.timeout)
        return st, (j["prompt"] if st == 200 and "prompt" in j else message_of(j))
    b = {"model": args.model, "messages": msgs, "add_generation_prompt": True}
    if effort is not None:
        b["chat_template_kwargs"] = {"reasoning_effort": effort, "enable_thinking": effort != "none"}
    st, j = call(root + "/tokenize", b, args.api_key, args.timeout)
    return st, (j["tokens"] if st == 200 and "tokens" in j else message_of(j))


def detect(args, root, msgs):
    for kind in (["llama", "vllm"] if args.probe == "auto" else [args.probe]):
        if kind == "off":
            return None, None
        st, v = render_probe(args, root, msgs, None, kind)
        if st == 200:
            return kind, v
    return None, None


def reasoning_len(j):
    try:
        ch = j["choices"][0]["message"]
    except (KeyError, IndexError, TypeError):
        return None, None
    text = ch.get("reasoning_content") or ch.get("reasoning") or ""
    if not text and isinstance(ch.get("content"), str) and "</think>" in ch["content"]:
        text = ch["content"].split("</think>")[0]
    toks = None
    u = j.get("usage") or {}
    d = u.get("completion_tokens_details") or {}
    if isinstance(d, dict) and d.get("reasoning_tokens") is not None:
        toks = d["reasoning_tokens"]
    return len(text), toks


def run(args):
    root = root_of(args.base_url)
    msgs = [{"role": "user", "content": args.prompt}]
    levels = args.levels.split(",")
    kind, base = detect(args, root, msgs)
    rows = []
    for lv in levels:
        row = {"effort": lv}
        if kind:
            s2, v = render_probe(args, root, msgs, lv, kind)
            row["render_status"] = s2
            if s2 == 200:
                row["_prompt"] = v
                row["same_as_default"] = (v == base)
            else:
                row["render_error"] = v
        body = {"model": args.model, "messages": msgs, "reasoning_effort": lv, "max_tokens": args.max_tokens}
        if args.temperature is not None:
            body["temperature"] = args.temperature
        s3, j = call(args.base_url.rstrip("/") + "/chat/completions", body, args.api_key, args.timeout)
        row["chat_status"] = s3
        if s3 != 200:
            row["chat_error"] = message_of(j)
        elif args.max_tokens > 1:
            row["reasoning_chars"], row["reasoning_tokens"] = reasoning_len(j)
        rows.append(row)
    for r in rows:
        if "_prompt" in r:
            r["aliases"] = [o["effort"] for o in rows if o is not r and o.get("_prompt") == r["_prompt"]]
    for r in rows:
        r.pop("_prompt", None)
        if r["chat_status"] != 200 or (r.get("render_status", 200) != 200):
            r["verdict"] = "REJECTED"
        elif "same_as_default" not in r:
            r["verdict"] = "ACCEPTED"
        elif r["same_as_default"]:
            r["verdict"] = "DEFAULT"
        else:
            r["verdict"] = "HONORED"
    return kind, rows


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--base-url", required=True, help="OpenAI-compatible base URL ending in /v1")
    ap.add_argument("--model", default="default")
    ap.add_argument("--api-key", default="none")
    ap.add_argument("--levels", default=",".join(LEVELS))
    ap.add_argument("--prompt", default="What is 17 * 23? Answer with the number.")
    ap.add_argument("--max-tokens", type=int, default=1, help="1 = status only; e.g. 2048 to compare reasoning length")
    ap.add_argument("--temperature", type=float, default=None)
    ap.add_argument("--probe", choices=["auto", "llama", "vllm", "off"], default="auto")
    ap.add_argument("--timeout", type=float, default=600)
    ap.add_argument("--json", help="also write the rows to this file")
    args = ap.parse_args()
    kind, rows = run(args)
    if all(r["chat_status"] == 0 for r in rows):
        print("cannot reach %s: %s" % (args.base_url, rows[0].get("chat_error")), file=sys.stderr)
        return 2
    print("prompt inspection:", {"llama": "llama-server /apply-template", "vllm": "vLLM /tokenize"}.get(kind, "not available"))
    print("%-8s %-9s %-6s %s" % ("effort", "verdict", "HTTP", "detail"))
    for r in rows:
        if r["verdict"] == "REJECTED":
            detail = r.get("chat_error") or r.get("render_error") or ""
            code = r["chat_status"] if r["chat_status"] != 200 else r.get("render_status")
        else:
            code = r["chat_status"]
            bits = []
            if r.get("aliases"):
                bits.append("same prompt as " + ", ".join(r["aliases"]))
            if r.get("reasoning_chars") is not None:
                bits.append("reasoning %d chars" % r["reasoning_chars"])
            if r.get("reasoning_tokens") is not None:
                bits.append("%d reasoning tokens" % r["reasoning_tokens"])
            detail = "; ".join(bits)
        print("%-8s %-9s %-6s %s" % (r["effort"], r["verdict"], code, detail))
    if kind == "vllm" and all(r["verdict"] in ("DEFAULT", "REJECTED") for r in rows):
        print("note: every value rendered like the default. If this server's /tokenize ignores chat_template_kwargs,"
              " rerun with --probe off and compare reasoning length with --max-tokens.")
    if args.json:
        with open(args.json, "w") as f:
            json.dump({"inspection": kind, "rows": rows}, f, indent=1)
    return 0


if __name__ == "__main__":
    sys.exit(main())
