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>
This commit is contained in:
neil 2026-11-03 13:03:52 -08:00
parent 1121c3f908
commit 8879db44a0
12 changed files with 886 additions and 493 deletions

View file

@ -1,45 +1,22 @@
"""MLX backend (Apple Silicon).
mlx_lm.server has no API-key support and loads whatever model a request names, so it
listens on localhost only and this module runs a small proxy on the public port that:
- checks the API key (like vLLM's --api-key),
- rejects a request for a model that isn't the loaded one (404 model_not_found),
then rewrites the request's "model" to the loaded one, and answers /v1/models with
the served name, so clients see the same API as on vLLM,
- counts in-flight requests and generated tokens for the dashboard (/llmhost/metrics).
listens on localhost only, behind llm-host's proxy (backends/proxy.py) on the public port.
This module adds what's particular to mlx_lm: a readiness probe (its /health is OK before
the model has loaded), KV usage read from its log, and a restart when its generator dies.
"""
import hmac
import http.client
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from .. import hfcache, paths, plan
RECENT_RUNS = 50 # completed requests kept for the dashboard's summary
_cfg_cache = {"mtime": None, "cfg": {}}
def live_cfg():
"""config.json, re-read when it changes. The reasoning setting is edited from the
dashboard while this process runs, and it must take effect without a restart --
a restart would unload the model, which is the whole thing we're avoiding."""
try:
mtime = paths.CONFIG_FILE.stat().st_mtime
except OSError:
return _cfg_cache["cfg"]
if mtime != _cfg_cache["mtime"]:
_cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config()
return _cfg_cache["cfg"]
from . import proxy
VENV = paths.DATA / "venv-mlx"
PY = VENV / "bin/python"
@ -56,7 +33,6 @@ def install(hw, log=print):
return {}
QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
# Lines from mlx_lm.server / huggingface_hub that add nothing to the log.
NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthenticated requests to the HF Hub")
@ -120,334 +96,17 @@ def _readiness_probe(inner_port, stats):
time.sleep(3)
class Stats:
def __init__(self):
self.lock = threading.Lock()
self.running = 0
self.gen_total = 0
self.prompt_total = 0
self.requests_total = 0
self.ttft_sum = 0.0 # seconds from request received to first generated token,
self.ttft_count = 0 # streamed requests only (non-streamed ones arrive all at once)
self.ready = False # set once the model has actually answered (see _readiness_probe)
self.kv_bytes = None # prompt cache size, from mlx_lm's own log line
self.kv_seqs = None
self.kv_peak = None
self.kv_budget = None # --prompt-cache-bytes, so usage can be a fraction
self.recent = deque(maxlen=RECENT_RUNS)
def set_kv(self, seqs, nbytes):
with self.lock:
self.kv_seqs, self.kv_bytes = seqs, nbytes
self.kv_peak = nbytes if self.kv_peak is None else max(self.kv_peak, nbytes)
def add_run(self, run):
with self.lock:
self.recent.append(run)
def snapshot(self):
with self.lock:
kv = (self.kv_bytes / self.kv_budget) if (self.kv_bytes is not None and self.kv_budget) else None
return {"running": self.running, "gen_total": self.gen_total,
"prompt_total": self.prompt_total, "requests_total": self.requests_total,
"ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count,
"kv": kv, "kv_bytes": self.kv_bytes, "kv_seqs": self.kv_seqs,
"kv_peak_bytes": self.kv_peak, "kv_budget_bytes": self.kv_budget,
"recent": list(self.recent)}
def _uncached(usage):
"""Prompt tokens the server actually processed: cached prefix tokens cost nothing."""
n = int(usage.get("prompt_tokens") or 0)
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
return max(n - int(cached), 0)
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None):
# Names a client may call the loaded model: its llm-host name, its repo id, and the
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
class Proxy(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *a):
# The dashboard polls these every 2s from localhost; logging them buries real traffic.
if self.client_address[0] in ("127.0.0.1", "::1") and self.path.split("?")[0] in QUIET_PATHS:
return
sys.stderr.write("proxy: %s - %s\n" % (self.address_string(), fmt % a))
def _json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
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._json(401, {"error": {"message": "invalid API key", "type": "auth"}})
return False
def do_GET(self):
if self.path == "/health":
# mlx_lm's /health is OK as soon as its thread runs, even while the model is
# still downloading. Report ready only after a real generation has succeeded.
if not stats.ready:
return self._json(503, {"status": "loading"})
return self._forward("GET", None)
if self.path == "/llmhost/metrics":
if self.client_address[0] not in ("127.0.0.1", "::1"):
return self._json(403, {"error": "local only"})
return self._json(200, stats.snapshot())
if not self._authed():
return
if self.path.startswith("/v1/models"):
return self._json(200, {"object": "list", "data": [
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
self._forward("GET", None)
def _model_ok(self, body):
"""One model is loaded at a time, and mlx_lm answers with whatever it has
regardless of the name asked for -- so an unrecognised name would come back
as another model's output wearing it. Refuse it instead."""
want = body.get("model")
if not isinstance(want, str) or not want.strip():
return True # no preference stated: the loaded one it is
if want.strip().lower() in accepted:
return True
self._json(404, {"error": {
"message": f"model '{want}' is not loaded; this server is serving "
f"'{served_name}'. Load it with `llmhost switch {want}` "
f"(one model is loaded at a time), or ask for '{served_name}' "
f"-- or for '{plan.SERVED_ALIAS}', which always means whatever "
f"is loaded.",
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
return False
def do_POST(self):
if not self._authed():
return
self._t0 = time.monotonic()
self._wall0 = time.time()
self._gen = 0 # tokens generated for THIS request
self._ttft = None
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
strip_usage = False
try:
body = json.loads(raw or b"{}")
if isinstance(body, dict):
if self.path.startswith("/v1/") and not self._model_ok(body):
return
# Server-side reasoning default. Only chat completions go through a
# chat template, and a key the client set itself always wins -- the
# same precedence mlx_lm applies to its own --chat-template-kwargs.
if reasoning and "chat/completions" in self.path:
kw = reasoning()
if kw:
mine = dict(kw)
theirs = body.get("chat_template_kwargs")
if isinstance(theirs, dict):
mine.update(theirs)
body["chat_template_kwargs"] = mine
# Force the preloaded model: mlx_lm would otherwise try to load a
# model matching the name it's given.
body["model"] = "default_model"
# Ask for the final usage chunk so prompt tokens can be counted, and
# hide it again from clients that didn't ask for it.
opts = body.get("stream_options") or {}
if body.get("stream") and not opts.get("include_usage"):
body["stream_options"] = {**opts, "include_usage": True}
strip_usage = True
raw = json.dumps(body).encode()
except ValueError:
pass
self._forward("POST", raw, strip_usage)
def _record_run(self, aborted):
"""One finished request, for the dashboard's run summary. Peak KV during the run
is left to the dashboard: it samples KV on a timer, so it can take the max over
this run's window, which is more than the cache size happens to be at the end."""
t0 = getattr(self, "_t0", None)
if t0 is None:
return
stats.add_run({"start": self._wall0, "end": time.time(),
"dur": time.monotonic() - t0, "gen": self._gen,
"prompt": getattr(self, "_pp", 0) or 0,
"ttft": self._ttft, "aborted": aborted})
def _forward(self, method, raw, strip_usage=False):
counted = self.path.startswith("/v1/") # health checks aren't requests
is_run = counted and method == "POST"
aborted = False
conn = None
if counted:
with stats.lock:
stats.running += 1
stats.requests_total += 1
try:
conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600) # noqa: F841 (closed in finally)
headers = {"Content-Type": self.headers.get("Content-Type", "application/json")}
if raw is not None:
headers["Content-Length"] = str(len(raw))
try:
conn.request(method, self.path, body=raw, headers=headers)
resp = conn.getresponse()
except OSError:
return self._json(503, {"error": {"message": "model server not ready", "type": "unavailable"}})
self.send_response(resp.status)
ctype = resp.getheader("Content-Type", "application/json")
self.send_header("Content-Type", ctype)
streaming = "text/event-stream" in ctype
if streaming:
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
self.close_connection = True
buf = b""
self._first = False
self._pp = 0 # prompt tokens of this request already counted
while True:
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
if not chunk:
break
buf += chunk
# Forward whole events (the server writes one per token anyway).
while b"\n\n" in buf:
event, buf = buf.split(b"\n\n", 1)
if event.startswith(b": keepalive "):
self._count_progress(event)
usage_only = self._count_event(event)
if not (strip_usage and usage_only):
self.wfile.write(event + b"\n\n")
self.wfile.flush()
if buf:
self.wfile.write(buf)
self.wfile.flush()
else:
self._pp = 0
data = resp.read()
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
try:
u = json.loads(data).get("usage") or {}
self._gen = int(u.get("completion_tokens") or 0)
self._pp = _uncached(u)
with stats.lock:
stats.gen_total += self._gen
stats.prompt_total += self._pp
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
# The client gave up mid-answer (opencode cancelling a stream, say). Drop the
# upstream connection now rather than at GC time, and say so in one line:
# mlx_lm logs its own BrokenPipeError traceback when its writes stop landing.
aborted = True
sys.stderr.write("proxy: client disconnected; aborted the upstream request\n")
finally:
if conn is not None:
try:
conn.close()
except Exception:
pass
if is_run:
self._record_run(aborted)
if counted:
with stats.lock:
stats.running -= 1
def _count_progress(self, event):
"""mlx_lm.server sends ': keepalive <done>/<total>' after each prefill step of a
streamed request (counting only the part not found in its prompt cache). Count
those as they arrive so the prompt rate shows prefill while it happens, not as
one spike when the request ends (or never, if the client gives up first)."""
try:
done = int(event[12:].split(b"/")[0])
except ValueError:
return
if done > self._pp:
with stats.lock:
stats.prompt_total += done - self._pp
self._pp = done
def _count_event(self, event):
"""Update token counts; returns True for a usage-only chunk (no choices)."""
if not event.startswith(b"data: {"):
return False
try:
d = json.loads(event[6:])
except ValueError:
return False
u = d.get("usage")
first_token = False
with stats.lock:
if u: # final usage chunk: top up whatever the progress events didn't cover
rest = _uncached(u) - self._pp
if rest > 0:
stats.prompt_total += rest
self._pp += rest
for c in d.get("choices") or []:
delta = c.get("delta") or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"):
stats.gen_total += 1 # mlx streams one token per chunk
self._gen += 1
first_token = True
if first_token and not self._first and getattr(self, "_t0", None) is not None:
self._first = True
self._ttft = time.monotonic() - self._t0
stats.ttft_sum += self._ttft
stats.ttft_count += 1
return bool(u) and not d.get("choices")
return Proxy
def _kill_stale_servers(inner_port):
"""Stop mlx_lm.server processes left behind by an earlier crash of this service.
Only processes running from our own venv are touched."""
out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"],
capture_output=True, text=True).stdout.split()
for pid in out:
cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout
if str(VENV) in cmd and "mlx_lm" in cmd:
print(f"llm-host: stopping leftover mlx_lm.server (pid {pid}) on port {inner_port}", flush=True)
try:
os.kill(int(pid), signal.SIGTERM)
except OSError:
pass
if out:
time.sleep(2)
def run_server(cfg, entry, choice, args):
"""Start the auth proxy on api_port, then mlx_lm.server as a child on api_port+1."""
"""Start the proxy on api_port, then mlx_lm.server as a child on api_port+1."""
port = cfg["api_port"]
inner = port + 1
# Claim the public port first: if it's taken, fail before starting (and orphaning) a child.
stats = Stats()
# The template is fixed for this process, so read its knobs once; the chosen level is
# read per request, since the dashboard can change it while we run.
stats = proxy.Stats()
controls = hfcache.template_controls(choice["repo"])
def reasoning():
value = (live_cfg().get("reasoning") or {}).get(entry["name"])
return plan.reasoning_kwargs(value, entry, controls)
try:
srv = ThreadingHTTPServer(("0.0.0.0", port),
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
paths.api_key(), stats, aliases=(choice.get("repo"),),
reasoning=reasoning))
except OSError as e:
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
sys.exit(1)
_kill_stale_servers(inner)
srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
effort_levels=plan.effort_levels(entry, controls)))
proxy.kill_stale(inner, VENV, "mlx_lm")
exe = str(VENV / "bin/mlx_lm.server")
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
@ -459,24 +118,4 @@ def run_server(cfg, entry, choice, args):
stats.kv_budget = int(choice["prompt_cache_gib"] * 2**30) if choice.get("prompt_cache_gib") else None
threading.Thread(target=_pump_output, args=(child.stdout, generator_died, stats), daemon=True).start()
threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start()
def stop(*_):
child.terminate()
try:
child.wait(timeout=20)
except subprocess.TimeoutExpired:
child.kill()
os._exit(0)
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True)
rc = child.wait()
print(f"llm-host: mlx_lm.server exited with {rc}", flush=True)
finally:
if child.poll() is None:
child.terminate()
time.sleep(1)
os._exit(rc or 1)
proxy.supervise(srv, child, "mlx_lm.server", port, inner)

430
llmhost/backends/proxy.py Normal file
View file

@ -0,0 +1,430 @@
"""The proxy llm-host puts in front of every model server (vLLM and mlx_lm.server alike).
The model server listens on localhost (api_port + 1); this listens on the public api_port
and, so that clients see the same API on either backend:
- checks the API key,
- rejects a request for a model that isn't the loaded one (404 model_not_found), and
rewrites the request's "model" to the name the server knows it by; /v1/models answers
with the served name,
- applies the dashboard's reasoning setting to chat requests, and maps an effort level
the model doesn't have (a client's generic "high", say) to the nearest one it does,
- counts in-flight requests and tokens and records each finished request for the
dashboard (/llmhost/metrics, localhost only).
"""
import hmac
import http.client
import json
import os
import signal
import subprocess
import sys
import threading
import time
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from .. import paths, plan
RECENT_RUNS = 50 # completed requests kept for the dashboard's summary
QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
class Stats:
def __init__(self):
self.lock = threading.Lock()
self.running = 0
self.gen_total = 0
self.prompt_total = 0
self.requests_total = 0
self.ttft_sum = 0.0 # seconds from request received to first generated token,
self.ttft_count = 0 # streamed requests only (non-streamed ones arrive all at once)
self.ready = False # MLX: set once the model has answered; vLLM: from the start
self.kv_bytes = None # MLX prompt cache size, from mlx_lm's own log line
self.kv_seqs = None
self.kv_peak = None
self.kv_budget = None # --prompt-cache-bytes, so usage can be a fraction
self.recent = deque(maxlen=RECENT_RUNS)
def set_kv(self, seqs, nbytes):
with self.lock:
self.kv_seqs, self.kv_bytes = seqs, nbytes
self.kv_peak = nbytes if self.kv_peak is None else max(self.kv_peak, nbytes)
def add_run(self, run):
with self.lock:
self.recent.append(run)
def snapshot(self):
with self.lock:
kv = (self.kv_bytes / self.kv_budget) if (self.kv_bytes is not None and self.kv_budget) else None
return {"running": self.running, "gen_total": self.gen_total,
"prompt_total": self.prompt_total, "requests_total": self.requests_total,
"ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count,
"kv": kv, "kv_bytes": self.kv_bytes, "kv_seqs": self.kv_seqs,
"kv_peak_bytes": self.kv_peak, "kv_budget_bytes": self.kv_budget,
"recent": list(self.recent)}
def _uncached(usage):
"""Prompt tokens the server actually processed: cached prefix tokens cost nothing."""
n = int(usage.get("prompt_tokens") or 0)
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
return max(n - int(cached), 0)
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None,
upstream_model="default_model", upstream_key=None, effort_levels=()):
"""upstream_model: what the inner server calls the loaded model ("default_model" makes
mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent
on to an inner server that checks keys itself (vLLM). effort_levels: the levels this
model's template accepts; an unknown one from a client is mapped to the nearest."""
# Names a client may call the loaded model: its llm-host name, its repo id, and the
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
class Proxy(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *a):
# The dashboard polls these every 2s from localhost; logging them buries real traffic.
if self.client_address[0] in ("127.0.0.1", "::1") and self.path.split("?")[0] in QUIET_PATHS:
return
sys.stderr.write("proxy: %s - %s\n" % (self.address_string(), fmt % a))
def _json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
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._json(401, {"error": {"message": "invalid API key", "type": "auth"}})
return False
def do_GET(self):
if self.path == "/health":
# mlx_lm's /health is OK as soon as its thread runs, even while the model is
# still downloading. Report ready only after a real generation has succeeded.
if not stats.ready:
return self._json(503, {"status": "loading"})
return self._forward("GET", None)
if self.path == "/llmhost/metrics":
if self.client_address[0] not in ("127.0.0.1", "::1"):
return self._json(403, {"error": "local only"})
return self._json(200, stats.snapshot())
if not self._authed():
return
if self.path.startswith("/v1/models"):
return self._json(200, {"object": "list", "data": [
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
self._forward("GET", None)
def _model_ok(self, body):
"""One model is loaded at a time, and mlx_lm answers with whatever it has
regardless of the name asked for -- so an unrecognised name would come back
as another model's output wearing it. Refuse it instead."""
want = body.get("model")
if not isinstance(want, str) or not want.strip():
return True # no preference stated: the loaded one it is
if want.strip().lower() in accepted:
return True
self._json(404, {"error": {
"message": f"model '{want}' is not loaded; this server is serving "
f"'{served_name}'. Load it with `llmhost switch {want}` "
f"(one model is loaded at a time), or ask for '{served_name}' "
f"-- or for '{plan.SERVED_ALIAS}', which always means whatever "
f"is loaded.",
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
return False
def _fit_effort(self, holder, k):
"""Map holder[k], a client's effort level, onto one this model accepts. Clients
offer a generic menu (opencode: low/medium/high), and a level the template
doesn't define makes it raise -- every request then fails until the user finds
the setting. The nearest level is what they meant."""
v = holder.get(k)
if effort_levels and isinstance(v, str) and v not in effort_levels:
fit = plan.nearest_effort(v, effort_levels)
if fit:
holder[k] = fit
def do_POST(self):
if not self._authed():
return
self._t0 = time.monotonic()
self._wall0 = time.time()
self._gen = 0 # tokens generated for THIS request
self._ttft = None
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
strip_usage = False
try:
body = json.loads(raw or b"{}")
if isinstance(body, dict):
if self.path.startswith("/v1/") and not self._model_ok(body):
return
if "chat/completions" in self.path:
theirs = body.get("chat_template_kwargs")
# Server-side reasoning default. Only chat completions go through a
# chat template, and a setting the client made itself always wins --
# the same precedence mlx_lm applies to its own --chat-template-kwargs.
kw = reasoning() if reasoning else {}
if kw:
mine = dict(kw)
if "reasoning_effort" in body: # the OpenAI-style top-level field
mine.pop("reasoning_effort", None)
if isinstance(theirs, dict):
mine.update(theirs)
body["chat_template_kwargs"] = theirs = mine
self._fit_effort(body, "reasoning_effort")
if isinstance(theirs, dict):
self._fit_effort(theirs, "reasoning_effort")
# Name the loaded model the way the inner server knows it (mlx_lm would
# otherwise try to load a model matching the name it's given).
body["model"] = upstream_model
# Ask for the final usage chunk so prompt tokens can be counted, and
# hide it again from clients that didn't ask for it.
opts = body.get("stream_options") or {}
if body.get("stream") and not opts.get("include_usage"):
body["stream_options"] = {**opts, "include_usage": True}
strip_usage = True
raw = json.dumps(body).encode()
except ValueError:
pass
self._forward("POST", raw, strip_usage)
def _record_run(self, aborted):
"""One finished request, for the dashboard's run summary. Peak KV during the run
is left to the dashboard: it samples KV on a timer, so it can take the max over
this run's window, which is more than the cache size happens to be at the end."""
t0 = getattr(self, "_t0", None)
if t0 is None:
return
stats.add_run({"start": self._wall0, "end": time.time(),
"dur": time.monotonic() - t0, "gen": self._gen,
"prompt": getattr(self, "_pp", 0) or 0,
"ttft": self._ttft, "aborted": aborted})
def _forward(self, method, raw, strip_usage=False):
counted = self.path.startswith("/v1/") # health checks aren't requests
is_run = counted and method == "POST"
aborted = False
conn = None
if counted:
with stats.lock:
stats.running += 1
stats.requests_total += 1
try:
conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600) # noqa: F841 (closed in finally)
headers = {"Content-Type": self.headers.get("Content-Type", "application/json")}
if upstream_key:
headers["Authorization"] = f"Bearer {upstream_key}"
if raw is not None:
headers["Content-Length"] = str(len(raw))
try:
conn.request(method, self.path, body=raw, headers=headers)
resp = conn.getresponse()
except OSError:
return self._json(503, {"error": {"message": "model server not ready", "type": "unavailable"}})
self.send_response(resp.status)
ctype = resp.getheader("Content-Type", "application/json")
self.send_header("Content-Type", ctype)
streaming = "text/event-stream" in ctype
if streaming:
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
self.close_connection = True
buf = b""
self._first = False
self._pp = 0 # prompt tokens of this request already counted
while True:
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
if not chunk:
break
buf += chunk
# Forward whole events (the server writes one per token anyway).
while b"\n\n" in buf:
event, buf = buf.split(b"\n\n", 1)
if event.startswith(b": keepalive "):
self._count_progress(event)
usage_only = self._count_event(event)
if not (strip_usage and usage_only):
self.wfile.write(event + b"\n\n")
self.wfile.flush()
if buf:
self.wfile.write(buf)
self.wfile.flush()
else:
self._pp = 0
data = resp.read()
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
try:
u = json.loads(data).get("usage") or {}
self._gen = int(u.get("completion_tokens") or 0)
self._pp = _uncached(u)
with stats.lock:
stats.gen_total += self._gen
stats.prompt_total += self._pp
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
# The client gave up mid-answer (opencode cancelling a stream, say). Drop the
# upstream connection now rather than at GC time, and say so in one line:
# mlx_lm logs its own BrokenPipeError traceback when its writes stop landing.
aborted = True
sys.stderr.write("proxy: client disconnected; aborted the upstream request\n")
finally:
if conn is not None:
try:
conn.close()
except Exception:
pass
if is_run:
self._record_run(aborted)
if counted:
with stats.lock:
stats.running -= 1
def _count_progress(self, event):
"""mlx_lm.server sends ': keepalive <done>/<total>' after each prefill step of a
streamed request (counting only the part not found in its prompt cache). Count
those as they arrive so the prompt rate shows prefill while it happens, not as
one spike when the request ends (or never, if the client gives up first)."""
try:
done = int(event[12:].split(b"/")[0])
except ValueError:
return
if done > self._pp:
with stats.lock:
stats.prompt_total += done - self._pp
self._pp = done
def _count_event(self, event):
"""Update token counts; returns True for a usage-only chunk (no choices)."""
if not event.startswith(b"data: {"):
return False
try:
d = json.loads(event[6:])
except ValueError:
return False
u = d.get("usage")
first_token = False
with stats.lock:
if u: # final usage chunk: top up whatever the stream itself didn't cover
rest = _uncached(u) - self._pp
if rest > 0:
stats.prompt_total += rest
self._pp += rest
# One chunk is usually one token, but not always (vLLM with speculative
# decoding sends several at once), so the usage count is the truth.
more = int(u.get("completion_tokens") or 0) - self._gen
if more > 0:
stats.gen_total += more
self._gen += more
for c in d.get("choices") or []:
delta = c.get("delta") or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"):
stats.gen_total += 1
self._gen += 1
first_token = True
if first_token and not self._first and getattr(self, "_t0", None) is not None:
self._first = True
self._ttft = time.monotonic() - self._t0
stats.ttft_sum += self._ttft
stats.ttft_count += 1
return bool(u) and not d.get("choices")
return Proxy
_cfg_cache = {"mtime": None, "cfg": {}}
def live_cfg():
"""config.json, re-read when it changes. The reasoning setting is edited from the
dashboard while this process runs, and it must take effect without a restart --
a restart would unload the model, which is the whole thing we're avoiding."""
try:
mtime = paths.CONFIG_FILE.stat().st_mtime
except OSError:
return _cfg_cache["cfg"]
if mtime != _cfg_cache["mtime"]:
_cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config()
return _cfg_cache["cfg"]
def reasoning_setting(entry, controls):
"""The dashboard's reasoning setting as chat_template_kwargs, read per request: the
dashboard changes it while the server runs, and a restart would unload the model.
The template's knobs are fixed for the process, so they're read once by the caller."""
def kwargs():
value = (live_cfg().get("reasoning") or {}).get(entry["name"])
return plan.reasoning_kwargs(value, entry, controls)
return kwargs
def kill_stale(inner_port, venv, marker):
"""Stop model servers left behind on the inner port by an earlier crash of this
service. Only processes running from our own venv are touched."""
try:
out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"],
capture_output=True, text=True).stdout.split()
except FileNotFoundError:
return
for pid in out:
cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout
if str(venv) in cmd and marker in cmd:
print(f"llm-host: stopping leftover {marker} (pid {pid}) on port {inner_port}", flush=True)
try:
os.kill(int(pid), signal.SIGTERM)
except OSError:
pass
if out:
time.sleep(2)
class _Server(ThreadingHTTPServer):
daemon_threads = True
request_queue_size = 128 # the default of 5 is easy to exceed with parallel agent requests
def listen(port, handler):
"""Claim the public port before starting a child, so a clash fails before orphaning one."""
try:
return _Server(("0.0.0.0", port), handler)
except OSError as e:
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
sys.exit(1)
def supervise(srv, child, name, port, inner, stop_timeout=20):
"""Serve the proxy until the model server exits, then exit non-zero so the service
manager restarts us. SIGTERM stops the child first."""
def stop(*_):
child.terminate()
try:
child.wait(timeout=stop_timeout)
except subprocess.TimeoutExpired:
child.kill()
os._exit(0)
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
rc = 1
try:
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"llm-host: proxy on :{port} -> {name} on 127.0.0.1:{inner}", flush=True)
rc = child.wait()
print(f"llm-host: {name} exited with {rc}", flush=True)
finally:
if child.poll() is None:
child.terminate()
time.sleep(1)
os._exit(rc or 1)

View file

@ -160,7 +160,26 @@ def run_env(cfg, hw=None, include_key=True):
return env
def exec_server(cfg, args):
"""Replace this process with `vllm serve` (so the service manager tracks vLLM directly)."""
def run_server(cfg, entry, choice, args):
"""Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args).
vLLM keeps its own API key, so the inner port isn't open to anyone else on the box;
the proxy checks the client's key and sends ours on."""
from .. import hfcache, plan
from . import proxy
port = cfg["api_port"]
inner = port + 1
stats = proxy.Stats()
stats.ready = True # vLLM's own /health is only OK once the model is loaded
controls = hfcache.template_controls(choice["repo"])
key = paths.api_key()
srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
upstream_model=entry["name"], upstream_key=key,
effort_levels=plan.effort_levels(entry, controls)))
proxy.kill_stale(inner, VENV, "vllm")
exe = str(VENV / "bin/vllm")
os.execve(exe, [exe, "serve", *args], run_env(cfg))
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.
child = subprocess.Popen([exe, "serve", *args], env=run_env(cfg))
# vLLM shuts its engine processes down on SIGTERM; give that time before killing.
proxy.supervise(srv, child, "vllm", port, inner, stop_timeout=45)

View file

@ -140,8 +140,8 @@ def cmd_setup(a):
# Our own services would hold the ports on a re-run; stop them so anything still
# listening belongs to another program. (--no-start leaves a running setup alone.)
# MLX needs two ports: the proxy, and mlx_lm.server on the next one.
api_span = 2 if p["backend"] == "mlx" else 1
# Two ports: the proxy, and the model server behind it on the next one.
api_span = 2
if not a.no_start:
with Spinner("Stopping llm-host's running services"):
for name in service.NAMES:
@ -474,7 +474,7 @@ def cmd_opencode(a):
snippet = {
"$schema": "https://opencode.ai/config.json",
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host)},
"model": f"{prov}/{cfg['active']}",
"model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry
}
if a.json:
say(json.dumps(snippet, indent=2))
@ -549,7 +549,7 @@ def cmd_uninstall(a):
# Stopping returns before the processes have exited (launchd especially). Wait, so a
# reinstall right after this finds the ports free instead of moving to other ones.
if cfg.get("api_port"):
span = 2 if cfg.get("backend") == "mlx" else 1
span = 2 # the proxy and the model server behind it
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
with Spinner("Waiting for the services to exit"):
wait_ports_free(ours, timeout=30)
@ -621,7 +621,7 @@ def cmd_run_model(a):
say(f"llm-host {VERSION}: starting {entry['name']} ({choice['repo']}, {choice['format']}) on {cfg['backend']}")
if cfg["backend"] == "vllm":
from .backends import vllm
vllm.exec_server(cfg, plan.vllm_args(entry, choice, cfg["api_port"], cfg.get("tp", 1)))
vllm.run_server(cfg, entry, choice, plan.vllm_args(entry, choice, cfg["api_port"] + 1, cfg.get("tp", 1)))
else:
from .backends import mlx
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))

View file

@ -22,7 +22,7 @@ import subprocess
from pathlib import Path
from urllib.parse import urlsplit
from . import paths, plan
from . import hfcache, paths, plan
PROVIDER = "llmhost"
DISPLAY = "LLMHost"
@ -123,6 +123,34 @@ def model_label(active, label, name_it):
return f"Default model ({label})"
# The effort levels opencode offers on its own for an OpenAI-compatible reasoning model.
# A model's template defines its own set, and one it lacks makes the template raise, so
# the block hides those and adds the model's own. (The proxy also maps a stray level to
# the nearest real one, so a pasted block that predates a switch still works.)
OPENCODE_EFFORTS = ("low", "medium", "high")
def _effort_levels(choice):
"""The active model's effort levels: from its chat template once downloaded (what the
proxy itself goes by), from the catalog before that."""
try:
entry = plan.catalog_entry(paths.load_catalog(), choice["name"])
except (KeyError, OSError, ValueError):
return ()
if not entry.get("reasoning"):
return ()
if choice.get("repo") and hfcache.repo_dir(choice["repo"]).exists():
return plan.effort_levels(entry, hfcache.template_controls(choice["repo"]))
return tuple((entry.get("effort") or {}).get("levels") or ())
def effort_variants(levels):
"""opencode `variants` for a model accepting `levels`."""
v = {l: {"disabled": True} for l in OPENCODE_EFFORTS if l not in levels}
v.update({l: {"reasoningEffort": l} for l in levels if l not in OPENCODE_EFFORTS})
return v
def provider_block(cfg, host, key_path, label, mark_loaded=False):
# A single entry, keyed by the alias the API also answers to. Listing every model that
# fits would be a menu of four things that 404 and one that works, and naming the loaded
@ -134,6 +162,9 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False):
"limit": {"context": ctx, "output": min(65536, ctx // 2)}}
if (active or {}).get("reasoning"):
entry["reasoning"] = True
variants = effort_variants(_effort_levels(active))
if variants:
entry["variants"] = variants
models = {plan.SERVED_ALIAS: entry}
return {
"npm": "@ai-sdk/openai-compatible",

View file

@ -118,13 +118,19 @@ def catalog_entry(catalog, name):
# ---------- backend command lines ----------
def vllm_args(entry, choice, port, tp):
"""Arguments after `vllm serve`."""
"""Arguments after `vllm serve` (bound to localhost; the proxy faces the network and
owns the model's other names, so vLLM only needs the one it's addressed by)."""
v = entry.get("vllm", {})
args = [choice["repo"], "--served-model-name", entry["name"], SERVED_ALIAS,
"--host", "0.0.0.0", "--port", str(port),
args = [choice["repo"], "--served-model-name", entry["name"],
"--host", "127.0.0.1", "--port", str(port),
"--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native)
"--gpu-memory-utilization", f"{choice['util']:.2f}",
"--enable-prefix-caching"]
"--enable-prefix-caching",
# usage.prompt_tokens_details.cached_tokens, so a run's prompt count is the part
# actually processed -- what mlx_lm reports too
"--enable-prompt-tokens-details",
# every request now comes from the proxy, which logs the real client itself
"--disable-uvicorn-access-log"]
if tp > 1:
args += ["--tensor-parallel-size", str(tp)]
if entry.get("hybrid"):
@ -165,8 +171,8 @@ def mlx_args(entry, choice, port):
# A second name the API answers to, besides the model's own. opencode (and any client
# with a saved default) points at this instead of a specific model, so the choice keeps
# working after `llmhost switch` -- only one model is loaded at a time, so naming one in
# a client config only ever goes stale. vLLM takes it as a second --served-model-name and
# still reports the real slug, being the first; the MLX proxy accepts it as an alias.
# a client config only ever goes stale. The proxy in front of either backend accepts it
# and /v1/models lists only the real slug.
SERVED_ALIAS = "default"
@ -204,3 +210,26 @@ def reasoning_kwargs(value, entry, controls):
if controls.get("effort") and value in levels:
return {"reasoning_effort": value}
return {}
# Effort levels in order, for mapping a level a model lacks onto the nearest it has.
EFFORT_SCALE = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
def effort_levels(entry, controls):
"""The effort levels this model's template accepts, or () if it takes none."""
levels = (entry.get("effort") or {}).get("levels") or []
return tuple(levels) if entry.get("reasoning") and controls.get("effort") else ()
def nearest_effort(value, levels):
"""The level in `levels` closest to `value` on EFFORT_SCALE; on a tie, the higher one
(asking for "high" between medium and xhigh means wanting more, not less). None when
either is off the scale."""
if value not in EFFORT_SCALE:
return None
want = EFFORT_SCALE.index(value)
known = [l for l in levels if l in EFFORT_SCALE]
if not known:
return None
return min(known, key=lambda l: (abs(EFFORT_SCALE.index(l) - want), -EFFORT_SCALE.index(l)))

View file

@ -49,6 +49,10 @@ h1 span { color: var(--muted); font-weight: 500; }
.meta { color: var(--muted); font-size: 12.5px; }
.grid { display: grid; gap: 14px; }
.section-head { display: flex; align-items: center; gap: 10px; margin: 26px 0 -2px; }
.section-head h2 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; }
.section-head .sub { color: var(--muted); font-size: 12px; }
button.small { font-size: 12px; padding: 4px 10px; }
.top { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); }
@media (max-width: 820px) { .top { grid-template-columns: minmax(0, 1fr); } }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px; min-width: 0; }
@ -105,9 +109,7 @@ button.danger { color: var(--bad); }
.bar i { display: block; height: 100%; background: var(--accent); width: 0; transition: width .4s; }
.charts { grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 14px; }
.charts.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
@media (max-width: 1100px) { .charts.four { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 820px) { .charts, .charts.four { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 820px) { .charts { grid-template-columns: minmax(0, 1fr); } }
.chart .head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px; }
.chart .head span { font-size: 12px; color: var(--muted); }
.chart .head b { font-size: 13px; font-variant-numeric: tabular-nums; }
@ -126,9 +128,6 @@ button.danger { color: var(--bad); }
.chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; }
.runs { margin-top: 14px; }
.runs .head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.runs .head h2 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; }
.runs .head .sub { color: var(--muted); font-size: 12px; }
.runs .scroll { overflow-x: auto; }
.runs table { width: 100%; border-collapse: collapse; font-size: 12.5px; font-variant-numeric: tabular-nums; }
.runs th, .runs td { padding: 5px 10px 5px 0; text-align: right; white-space: nowrap; }
@ -202,6 +201,13 @@ pre {
</section>
</div>
<div class="section-head">
<h2>Statistics</h2>
<span class="sub" id="stats-since"></span>
<span class="spacer"></span>
<button id="btn-stats-reset" class="small" title="Empty the charts and count totals and averages from now">Reset</button>
</div>
<div class="grid tiles">
<div class="tile"><div class="k">Generation</div><div class="v" id="t-gen">—</div><div class="s" id="t-gen-s"></div></div>
<div class="tile"><div class="k">Prompt processing</div><div class="v" id="t-prompt">—</div><div class="s" id="t-prompt-s"></div></div>
@ -214,10 +220,9 @@ pre {
<div class="tile"><div class="k">Prefix cache hits</div><div class="v" id="t-prefix">—</div><div class="s">prompt tokens reused</div></div>
</div>
<div class="grid charts four">
<div class="grid charts">
<div class="panel chart"><div class="head"><span>Generation tok/s</span><b id="c-gen-v"></b></div><svg id="c-gen" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>Prompt processing tok/s</span><b id="c-prompt-v"></b></div><svg id="c-prompt" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>Time to first token</span><b id="c-ttft-v"></b></div><svg id="c-ttft" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>KV cache %</span><b id="c-kv-v"></b></div><svg id="c-kv" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
</div>
<div class="grid charts" id="gpu-charts">
@ -227,17 +232,20 @@ pre {
<div class="panel chart" id="p-nogpu" hidden><div class="head"><span>GPU temperature &amp; power</span></div><div class="empty" id="nogpu-why">not available on this hardware</div></div>
</div>
<div class="section-head">
<h2>Requests</h2>
<span class="sub" id="runs-sub"></span>
<span class="spacer"></span>
<button id="btn-runs-clear" class="small" title="Empty this table">Clear</button>
</div>
<section class="panel runs" id="runs">
<div class="head">
<h2>Completed requests</h2>
<span class="sub" id="runs-sub"></span>
</div>
<div class="scroll">
<table>
<thead><tr>
<th>Finished</th><th>Duration</th><th>TTFT</th>
<th>Prompt</th><th>Prompt tok/s</th>
<th>Generated</th><th>Gen tok/s</th><th>Peak KV</th>
<th>Prompt tok</th><th>Prompt tok/s</th>
<th>Generated tok</th><th>Gen tok/s</th><th>Peak KV</th>
</tr></thead>
<tbody id="runs-body"></tbody>
<tfoot id="runs-foot"></tfoot>
@ -377,6 +385,8 @@ function render(s) {
const m = s.metrics || {}, g = s.gpu || {};
const live = s.phase === "ready";
$("stats-since").textContent = s.stats_since
? "since " + new Date(s.stats_since * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "";
setV("t-gen", live ? fmt.n(m.gen_tps, m.gen_tps < 10 ? 1 : 0) : "—", "tok/s");
$("t-gen-s").textContent = live && m.gen_total != null ? fmt.big(m.gen_total) + " generated" : "";
setV("t-prompt", live ? fmt.n(m.prompt_tps, 0) : "—", "tok/s");
@ -406,7 +416,6 @@ function render(s) {
chartTimes = h.map((p) => p.t);
chart("c-gen", h.map((p) => p.gen), "var(--c1)", null, (v) => fmt.n(v, 0) + " tok/s");
chart("c-prompt", h.map((p) => p.prompt), "var(--c6)", null, (v) => fmt.n(v, 0) + " tok/s");
chart("c-ttft", h.map((p) => p.ttft), "var(--c7)", null, (v) => fmt.secs(v));
chart("c-util", h.map((p) => p.util), "var(--c2)", 100, (v) => fmt.pct(v));
chart("c-kv", h.map((p) => p.kv), "var(--c3)", null, (v) => fmt.n(v, 1) + "%");
// Fixed scales so the shape means something: 0–100 °C, and 0 to the board power limit.
@ -416,7 +425,6 @@ function render(s) {
$("p-temp").hidden = !hasTP;
$("p-power").hidden = !hasTP;
$("p-nogpu").hidden = hasTP;
$("gpu-charts").classList.toggle("four", false);
if (!hasTP) {
$("nogpu-why").textContent = s.kind === "apple"
? "macOS only exposes GPU temperature and power to root (powermetrics), so they aren't charted here."
@ -437,8 +445,8 @@ let effortBusy = false;
function renderEffort(s) {
const r = s.reasoning || {}, box = $("effort"), sel = $("effort-sel");
const opts = r.options || [];
// Hidden rather than disabled when there is nothing to choose: on vLLM there's no proxy
// to inject the kwarg, and a model whose template has no switches has nothing to offer.
// Hidden rather than disabled when there is nothing to choose: a model whose template
// has no switches has nothing to offer.
box.hidden = !opts.length && !r.why;
if (!opts.length) {
sel.innerHTML = "";
@ -483,12 +491,12 @@ $("effort-sel").onchange = async (e) => {
function renderRuns(s) {
const runs = s.runs || [], body = $("runs-body"), foot = $("runs-foot");
$("btn-runs-clear").disabled = !runs.length;
$("runs-empty").hidden = runs.length > 0;
$("runs").hidden = s.backend !== "mlx" && runs.length === 0;
body.textContent = "";
foot.textContent = "";
if (!runs.length) {
$("runs-sub").textContent = s.backend === "mlx" ? "" : "per-request timings are only collected on MLX";
$("runs-sub").textContent = "";
return;
}
const clock = (t) => new Date(t * 1000).toLocaleTimeString(undefined, { hour12: false });
@ -647,6 +655,12 @@ async function ctl(kind, confirmMsg) {
}
$("btn-stop").onclick = () => ctl("stop", "Stop the model server? This frees GPU memory; clients won't work until you start it again.");
$("btn-start").onclick = () => ctl("start");
$("btn-stats-reset").onclick = async () => {
try { await api("/api/stats/reset", { method: "POST" }); poll(); } catch (e) { toast("Reset failed: " + e.message); }
};
$("btn-runs-clear").onclick = async () => {
try { await api("/api/runs/clear", { method: "POST" }); poll(); } catch (e) { toast("Clear failed: " + e.message); }
};
$("btn-restart").onclick = () => ctl("restart", "Restart the model server? It takes a few minutes to come back.");
async function loadLogs() {

View file

@ -23,6 +23,7 @@ RUNS_SHOWN = 20 # completed requests in the run summary
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.
@ -81,6 +82,18 @@ def http_get(url, key=None, timeout=2):
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():
@ -123,6 +136,8 @@ class Sampler:
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()
@ -160,15 +175,19 @@ class Sampler:
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(base + "/metrics")
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:
st, body = http_get(base + "/llmhost/metrics")
try:
metrics = json.loads(body) if st == 200 else {}
except ValueError:
metrics = {}
metrics = proxied
active = cfg.get("active")
if svc_state in ("inactive", "failed"):
@ -193,6 +212,7 @@ class Sampler:
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")
@ -205,7 +225,7 @@ class Sampler:
}
def ratio(a, b):
return metrics[a] / metrics[b] if metrics.get(b) else None
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
@ -228,20 +248,18 @@ class Sampler:
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 only learns KV when mlx_lm happens to log it.
# 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)
window = [q["kv"] for q in self.history
if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]]
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": max(window) if window else point["kv"],
"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:
@ -260,32 +278,76 @@ class Sampler:
"reasoning": reasoning,
"action": self.action,
"metrics": {
"running": metrics.get("running"), "waiting": metrics.get("waiting"),
"running": shown.get("running"), "waiting": shown.get("waiting"),
"kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate,
"gen_total": metrics.get("gen_total"), "prompt_total": metrics.get("prompt_total"),
"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": metrics.get("preemptions"),
"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": metrics.get("ttft_count"),
"kv_bytes": metrics.get("kv_bytes"),
"kv_seqs": metrics.get("kv_seqs"),
"kv_budget_bytes": metrics.get("kv_budget_bytes"),
"kv_peak_pct": (metrics["kv_peak_bytes"] / metrics["kv_budget_bytes"] * 100)
if metrics.get("kv_peak_bytes") and metrics.get("kv_budget_bytes") else None,
"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.
Only MLX: on vLLM llm-host has no proxy in front, so nothing here could inject
the kwarg into a client's request."""
"""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 or cfg.get("backend") != "mlx":
return {"options": [], "value": plan.DEFAULT, "why": "" if choice else 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}
@ -404,6 +466,12 @@ def make_handler(sampler, key):
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})