llm-host/llmhost/web/server.py
neil 8879db44a0 Proxy in front of vLLM too; dashboard reset/clear; opencode effort variants
- Move the MLX proxy into backends/proxy.py and run it on both backends:
  public port 1134 is the proxy, the model server listens on 127.0.0.1:1135.
  On vLLM this brings the reasoning chooser, the "default" alias and the
  per-request table. Effort levels the model lacks map to the nearest it has
  (high -> xhigh on qwen3.8); vLLM's own key is sent upstream; streamed runs
  are counted from the usage chunk (MTP packs several tokens per chunk).
- Dashboard: restore METRIC_RE (vLLM page stuck on "loading"); Statistics
  header with Reset, Requests header with Clear; drop the TTFT chart; rename
  token columns; Peak KV shows "-" when no samples cover a run.
- opencode: config snippet's model points at <provider>/default, and
  reasoning models get variants built from the levels the template accepts.
- README: proxy on both platforms; NVIDIA checklist split into verified / open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:03:52 -08:00

491 lines
22 KiB
Python

"""Dashboard: status, metrics and model switching. Stdlib only.
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key.
"""
import hmac
import json
import re
import socket
import threading
import time
import urllib.request
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .. import hfcache, hw, opencode, paths, plan, service
HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2
HISTORY_POINTS = 300 # 10 minutes
RUNS_SHOWN = 20 # completed requests in the run summary
# The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view.
OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) '
r'|- INFO - HTTP Request: ')
PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]")
METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$")
# A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its
# ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the
# disconnect in one line), so collapse the block instead of letting it bury the log.
DASHES_RE = re.compile(r"^-{20,}\s*$")
EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request")
DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b")
MAX_TRACE_LINES = 80
def collapse_disconnects(lines):
"""Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other
traceback is left exactly as it is -- those are worth reading in full.
socketserver brackets each one with a row of dashes, which is what delimits a block
here; a block that never closes (the log was truncated, or is still being written)
is emitted unchanged."""
out, block = [], None
def flush(decide):
nonlocal block
if block is None:
return
if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block):
out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]")
else:
out.extend(block)
block = None
for l in lines:
bare = l.rstrip()
if block is None:
if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare):
block = [l]
else:
out.append(l)
continue
if DASHES_RE.match(bare):
block.append(l)
flush(True)
continue
block.append(l)
if len(block) > MAX_TRACE_LINES:
flush(False)
flush(False)
return out
def http_get(url, key=None, timeout=2):
req = urllib.request.Request(url)
if key:
req.add_header("Authorization", f"Bearer {key}")
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read().decode()
except Exception:
return None, ""
def run_kv_peak(history, run, now, current):
"""Peak KV % over a finished run's window, from the sampled history. A run shorter
than the sampling interval has no samples, so the reading just after it ended stands
in -- but only while that's fresh: a run picked up later (after a dashboard restart,
say) has nothing to go on, and today's idle reading would claim a peak of 0%."""
window = [q["kv"] for q in history
if q["kv"] is not None and run["start"] <= q["t"] <= run["end"]]
if window:
return max(window)
return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None
def parse_vllm_metrics(text):
vals = {}
for line in text.splitlines():
m = METRIC_RE.match(line)
if not m:
continue
name, labels, v = m.group(1), m.group(2) or "", m.group(3)
if name.endswith(("_created", "_bucket")) or "position=" in labels or "reason=" in labels or "by_source" in name:
continue
if name == "vllm:engine_sleep_state":
continue
try:
vals[name] = vals.get(name, 0.0) + float(v)
except ValueError:
pass
return {
"running": vals.get("vllm:num_requests_running"),
"waiting": vals.get("vllm:num_requests_waiting"),
"kv": vals.get("vllm:kv_cache_usage_perc"),
"gen_total": vals.get("vllm:generation_tokens_total"),
"prompt_total": vals.get("vllm:prompt_tokens_total"),
"prefix_hits": vals.get("vllm:prefix_cache_hits_total"),
"prefix_queries": vals.get("vllm:prefix_cache_queries_total"),
"spec_accepted": vals.get("vllm:spec_decode_num_accepted_tokens_total"),
"spec_drafted": vals.get("vllm:spec_decode_num_draft_tokens_total"),
"preemptions": vals.get("vllm:num_preemptions_total"),
"ttft_sum": vals.get("vllm:time_to_first_token_seconds_sum"),
"ttft_count": vals.get("vllm:time_to_first_token_seconds_count"),
}
class Sampler:
def __init__(self, cfg, key):
self.cfg = cfg
self.key = key
self.lock = threading.Lock()
self.history = deque(maxlen=HISTORY_POINTS)
self.prev = None
self.state = {}
self.action = None
self._dl_cache = (0, {})
self.last_ttft = None # (time, seconds) of the latest sample with new first tokens
self.baseline = None # counter values at the last stats reset (see reset_stats)
self.stats_since = None
self.runs = deque(maxlen=RUNS_SHOWN)
self._seen_runs = set()
def reload_cfg(self):
self.cfg = paths.load_config() or self.cfg
def downloaded(self):
t, cache = self._dl_cache
if time.time() - t > 30:
cache = {m["repo"]: hfcache.is_downloaded(m["repo"]) for m in self.cfg.get("models", [])}
self._dl_cache = (time.time(), cache)
return cache
def loop(self):
while True:
try:
self.sample()
except Exception as e:
with self.lock:
self.state["sampler_error"] = repr(e)
time.sleep(SAMPLE_SECONDS)
def sample(self):
self.reload_cfg()
cfg = self.cfg
now = time.time()
base = f"http://127.0.0.1:{cfg['api_port']}"
svc_state, uptime = service.state("model")
health, _ = http_get(base + "/health")
served, metrics = None, {}
if health == 200:
st, body = http_get(base + "/v1/models", self.key)
if st == 200:
try:
served = [m["id"] for m in json.loads(body)["data"]]
except (ValueError, KeyError):
pass
# The proxy records each request on either backend; on vLLM the engine's own
# /metrics (on the inner port) has the aggregates, KV usage included.
st, body = http_get(base + "/llmhost/metrics")
try:
proxied = json.loads(body) if st == 200 else {}
except ValueError:
proxied = {}
if cfg["backend"] == "vllm":
st, body = http_get(f"http://127.0.0.1:{cfg['api_port'] + 1}/metrics")
metrics = parse_vllm_metrics(body) if st == 200 else {}
metrics["recent"] = proxied.get("recent") or []
else:
metrics = proxied
active = cfg.get("active")
if svc_state in ("inactive", "failed"):
phase = "failed" if svc_state == "failed" else "stopped"
elif health == 200 and served and active in served:
phase = "ready"
else:
phase = "loading"
gen_rate = prompt_rate = ttft = None
if metrics.get("gen_total") is not None and self.prev:
pt, pm = self.prev
dt = now - pt
if dt > 0 and pm.get("gen_total") is not None:
gen_rate = max(metrics["gen_total"] - pm["gen_total"], 0) / dt
prompt_rate = max((metrics.get("prompt_total") or 0) - (pm.get("prompt_total") or 0), 0) / dt
# Average time to first token of the requests that got their first token since the
# last sample (none: no point, so the chart shows a gap rather than a stale value).
dn = (metrics.get("ttft_count") or 0) - (pm.get("ttft_count") or 0)
if dn > 0:
ttft = max((metrics.get("ttft_sum") or 0) - (pm.get("ttft_sum") or 0), 0) / dn
if ttft is not None:
self.last_ttft = (now, ttft)
self.prev = (now, metrics) if metrics else None
shown = self.since_reset(metrics)
gpu = hw.live_stats(cfg["kind"])
kv = metrics.get("kv")
point = {
"t": now, "gen": gen_rate, "prompt": prompt_rate, "ttft": ttft,
"kv": kv * 100 if kv is not None else None,
"util": gpu["util"] if gpu else None,
"temp": gpu["temp"] if gpu else None,
"power": gpu["power"] if gpu else None,
}
def ratio(a, b):
return shown[a] / shown[b] if shown.get(b) else None
def run_rates(r):
"""Split a run into its two phases: time to first token covers the prefill, the
rest is generation. Rates over the whole duration would blur the two together."""
dur, ttft = r.get("dur") or 0, r.get("ttft")
prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur
gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None
return gen_tps, prompt_tps
last_log = None
if phase in ("loading", "failed"):
lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)]
last_log = lines[-1][-240:] if lines else None
dl = self.downloaded()
models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])]
reasoning = self.reasoning_state(cfg, active)
with self.lock:
self.history.append(point)
# Peak KV per run is taken from the sampled history over the run's own window;
# the proxy can't do it, since it never sees KV usage (mlx_lm only logs it now and then).
for r in metrics.get("recent") or []:
key = (r.get("start"), r.get("end"))
if key in self._seen_runs or r.get("start") is None:
continue
self._seen_runs.add(key)
gen_tps, prompt_tps = run_rates(r)
self.runs.append({
"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
"gen_tps": gen_tps, "prompt_tps": prompt_tps,
"kv_peak_pct": run_kv_peak(self.history, r, now, point["kv"]),
"aborted": bool(r.get("aborted")),
})
if len(self._seen_runs) > 4 * RUNS_SHOWN:
# The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the
# oldest keys can't resurrect a run we already have.
self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | {
(q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])}
if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6:
self.action = None
self.state = {
"time": now, "phase": phase, "service": svc_state, "uptime": uptime,
"host": socket.gethostname(), "backend": cfg["backend"], "kind": cfg["kind"],
"hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"),
"active": active, "served_models": served, "models": models,
"excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log,
"reasoning": reasoning,
"action": self.action,
"metrics": {
"running": shown.get("running"), "waiting": shown.get("waiting"),
"kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate,
"gen_total": shown.get("gen_total"), "prompt_total": shown.get("prompt_total"),
"prefix_hit": ratio("prefix_hits", "prefix_queries"),
"spec_accept": ratio("spec_accepted", "spec_drafted"),
"preemptions": shown.get("preemptions"),
"ttft_last": self.last_ttft[1] if self.last_ttft else None,
"ttft_last_t": self.last_ttft[0] if self.last_ttft else None,
"ttft_avg": ratio("ttft_sum", "ttft_count"),
"ttft_count": shown.get("ttft_count"),
"kv_bytes": shown.get("kv_bytes"),
"kv_seqs": shown.get("kv_seqs"),
"kv_budget_bytes": shown.get("kv_budget_bytes"),
"kv_peak_pct": self.kv_peak_pct(shown),
},
"runs": list(self.runs)[::-1],
"stats_since": self.stats_since,
}
# Counters that run from the model server's start; a stats reset rebases these.
COUNTERS = ("gen_total", "prompt_total", "requests_total", "prefix_hits", "prefix_queries",
"spec_accepted", "spec_drafted", "preemptions", "ttft_sum", "ttft_count")
def since_reset(self, metrics):
"""metrics with the counters taken from the last reset rather than the server's
start. Rates are unaffected: they come from differences between samples."""
base = self.baseline
if not base:
return metrics
if any(metrics.get(k) is not None and base.get(k) is not None and metrics[k] < base[k]
for k in self.COUNTERS):
# The model server restarted since the reset, so its counters already start
# after it. (What came between the reset and the restart is lost.)
self.baseline = base = {}
out = dict(metrics)
for k in self.COUNTERS:
if out.get(k) is not None:
out[k] = out[k] - (base.get(k) or 0)
return out
def kv_peak_pct(self, shown):
"""Peak KV since the model started (MLX reports it); since a reset, the highest
sampled value instead -- the server's own peak can't be rebased."""
if self.stats_since is not None:
vals = [p["kv"] for p in self.history if p["kv"] is not None]
return max(vals) if vals else None
if shown.get("kv_peak_bytes") and shown.get("kv_budget_bytes"):
return shown["kv_peak_bytes"] / shown["kv_budget_bytes"] * 100
return None
def reset_stats(self):
"""Start the Statistics section over: empty the charts, count from now."""
with self.lock:
latest = self.prev[1] if self.prev else {}
self.baseline = {k: latest.get(k) for k in self.COUNTERS}
self.stats_since = time.time()
self.history.clear()
self.last_ttft = None
def clear_runs(self):
"""Empty the Requests table. Runs already seen stay seen, so they don't come back."""
with self.lock:
self.runs.clear()
def reasoning_state(self, cfg, active):
"""What the active model can be told about reasoning, and what it's set to. The
proxy in front of either backend applies it to each chat request."""
choice = next((m for m in cfg.get("models", []) if m["name"] == active), None)
if not choice:
return {"options": [], "value": plan.DEFAULT, "why": None}
entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None)
if not entry:
return {"options": [], "value": plan.DEFAULT, "why": None}
if not hfcache.repo_dir(choice["repo"]).exists():
return {"options": [], "value": plan.DEFAULT,
"why": "the model isn't downloaded yet, so its chat template can't be read"}
controls = hfcache.template_controls(choice["repo"])
opts = plan.reasoning_options(entry, choice, controls)
value = (cfg.get("reasoning") or {}).get(active) or plan.DEFAULT
if value not in [v for v, _ in opts]:
value = plan.DEFAULT
why = "" if opts else "this model's chat template exposes no reasoning controls"
return {"options": [{"value": v, "label": l} for v, l in opts], "value": value, "why": why}
def set_reasoning(self, value):
"""Takes effect on the next request -- no restart, so the model stays loaded."""
cfg = paths.load_config()
active = cfg.get("active")
allowed = [o["value"] for o in self.reasoning_state(cfg, active)["options"]]
if value not in allowed:
return False, allowed
cfg.setdefault("reasoning", {})[active] = value
paths.save_config(cfg)
self.cfg = cfg
with self.lock:
if self.state.get("reasoning"):
self.state["reasoning"]["value"] = value
return True, allowed
def snapshot(self):
with self.lock:
s = dict(self.state)
s["history"] = list(self.history)
return s
def control(self, kind, model=None):
if kind == "switch":
cfg = paths.load_config()
cfg["active"] = model
paths.save_config(cfg)
self.cfg = cfg
opencode.sync(cfg) # keep /models' "loaded" marker honest after a dashboard switch
fn = service.restart
else:
fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind]
with self.lock:
self.action = {"kind": kind, "model": model, "t": time.time()}
self.history.clear()
self.prev = None
threading.Thread(target=fn, args=("model",), daemon=True).start()
def make_handler(sampler, key):
class Handler(BaseHTTPRequestHandler):
server_version = "llm-host"
def log_message(self, fmt, *args):
pass
def send_json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def authed(self):
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
return True
self.send_json(401, {"error": "unauthorized"})
return False
def do_GET(self):
path = self.path.split("?", 1)[0]
if path in ("/", "/index.html"):
body = (HERE / "index.html").read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == "/api/status":
if self.authed():
self.send_json(200, sampler.snapshot())
elif path == "/api/logs":
if self.authed():
lines = [l for l in service.logs("model", 1500)
if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)]
self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]})
else:
self.send_json(404, {"error": "not found"})
def do_POST(self):
path = self.path.split("?", 1)[0]
if not self.authed():
return
try:
n = int(self.headers.get("Content-Length") or 0)
data = json.loads(self.rfile.read(n) or b"{}") if n else {}
except ValueError:
return self.send_json(400, {"error": "bad json"})
if path == "/api/switch":
name = str(data.get("model", ""))
if name not in {m["name"] for m in sampler.cfg.get("models", [])}:
return self.send_json(400, {"error": f"unknown model {name!r}"})
sampler.control("switch", name)
return self.send_json(202, {"ok": True, "model": name})
if path == "/api/reasoning":
ok, allowed = sampler.set_reasoning(str(data.get("value", "")))
if not ok:
return self.send_json(400, {"error": "unsupported value for this model",
"allowed": allowed})
return self.send_json(200, {"ok": True, "value": data.get("value")})
if path == "/api/stats/reset":
sampler.reset_stats()
return self.send_json(200, {"ok": True})
if path == "/api/runs/clear":
sampler.clear_runs()
return self.send_json(200, {"ok": True})
if path in ("/api/stop", "/api/start", "/api/restart"):
sampler.control(path.rsplit("/", 1)[1])
return self.send_json(202, {"ok": True})
self.send_json(404, {"error": "not found"})
return Handler
def serve():
cfg = paths.load_config()
if not cfg:
raise SystemExit("not set up; run `llmhost setup`")
key = paths.api_key()
sampler = Sampler(cfg, key)
threading.Thread(target=sampler.loop, daemon=True).start()
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
srv.serve_forever()