"""Cold prompt speed of an OpenAI-compatible server: a fresh prompt of about N tokens per request, max_tokens 1.
Prefill tok/s = prompt_tokens (from the server's usage) / time to first streamed token. Each prompt starts with a
unique line so no prompt cache can reuse it. Standard library only.
  python3 prefill_ttft.py http://127.0.0.1:8080 MODEL --tokens 2048 --reps 3
"""
import argparse, json, random, time, urllib.request

WORDS = ("river stone lantern copper meadow signal harbor quiet orbit candle market thunder velvet compass "
         "garden mirror pilot winter canyon ember silver forest mosaic beacon ledger prism tundra").split()

def prompt_of(n_tokens: int, salt: int) -> str:
    rnd = random.Random(salt)
    words = [rnd.choice(WORDS) for _ in range(int(n_tokens * 0.75))]
    return f"Note {salt}-{rnd.random():.12f}. Count the words below silently and answer only 'ok'.\n" + " ".join(words)

def once(base: str, model: str, n: int, salt: int, chat: bool) -> dict:
    body = {"model": model, "max_tokens": 1, "temperature": 0, "stream": True,
            "stream_options": {"include_usage": True}, "cache_prompt": False}
    text = prompt_of(n, salt)
    if chat:
        url = base + "/v1/chat/completions"
        body["messages"] = [{"role": "user", "content": text}]
        body["chat_template_kwargs"] = {"enable_thinking": False}
    else:
        url, body["prompt"] = base + "/v1/completions", text
    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    t0 = time.perf_counter(); first = None; usage = None
    with urllib.request.urlopen(req, timeout=1800) as resp:
        for raw in resp:
            line = raw.decode().strip()
            if not line.startswith("data:") or line == "data: [DONE]":
                continue
            chunk = json.loads(line[5:])
            if chunk.get("usage"):
                usage = chunk["usage"]
            for choice in chunk.get("choices", []):
                delta = choice.get("delta") or {}
                piece = choice.get("text") or delta.get("content") or delta.get("reasoning_content") or ""
                if first is None and piece:
                    first = time.perf_counter()  # the first real token, not a role-only opening chunk
    pt = (usage or {}).get("prompt_tokens")
    ttft = (first - t0) if first else None
    return {"prompt_tokens": pt, "ttft_s": ttft, "prefill_tps": (pt / ttft) if pt and ttft else None}

def main():
    p = argparse.ArgumentParser()
    p.add_argument("base"); p.add_argument("model")
    p.add_argument("--tokens", type=int, default=2048); p.add_argument("--reps", type=int, default=3)
    p.add_argument("--completion", action="store_true"); p.add_argument("--label", default="")
    a = p.parse_args()
    rows = [once(a.base, a.model, a.tokens, 1000 * a.tokens + i + int(time.time()), not a.completion) for i in range(a.reps)]
    tps = sorted(r["prefill_tps"] for r in rows if r["prefill_tps"])
    print(json.dumps({"label": a.label, "target_tokens": a.tokens, "runs": rows,
                      "median_prefill_tps": tps[len(tps) // 2] if tps else None}))

if __name__ == "__main__":
    main()
