diff --git a/README.md b/README.md index 270eabd..71ffa6c 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,12 @@ llm-host detects the hardware, picks the models (and the right build of each) th installs the inference backend, and runs it as a background service with a web dashboard. - **Linux + NVIDIA** → [vLLM](https://github.com/vllm-project/vllm) -- **macOS on Apple Silicon** → [MLX](https://github.com/ml-explore/mlx-lm), behind a small proxy that adds API keys +- **macOS on Apple Silicon** → [MLX](https://github.com/ml-explore/mlx-lm) Either way you get the same OpenAI-compatible API (with an API key) on port 1134 and a dashboard on port 11340. +The model server itself listens on localhost (port 1135), behind a small proxy on 1134 that checks the key, +answers to the model's names, applies the dashboard's reasoning setting and times each request — the same +proxy on both platforms, so clients and the dashboard see one API. Everything installs into your home directory; no sudo, Docker or system CUDA toolkit needed. ## Install @@ -87,12 +90,17 @@ of remote ones at once, each named after the machine it reaches: Each provider offers a **single model**, `default`, rather than every model that fits. One model is loaded at a time, so a list of them would be a menu of one entry that works and the rest answering `404 model_not_found` — and naming the loaded model would break the client's saved default on the next `llmhost switch`. `default` is a -name the API also answers to, so `llmhost/default` keeps working across switches: vLLM takes it as a second -`--served-model-name` (and still reports the real slug, being the first), and on a Mac the proxy accepts it as an -alias. The local entry is labelled with whatever is loaded — `Default model · Qwen3.8 27B (Local)` — and +name the API also answers to, so `llmhost/default` keeps working across switches: the proxy accepts it as an +alias, and `/v1/models` reports the real slug. The local entry is labelled with whatever is loaded — `Default model · Qwen3.8 27B (Local)` — and `llmhost switch`, the dashboard and `llmhost update` keep that label current. A config that still points at a specific model (`llmhost/qwen3.8-27b`) is migrated to `llmhost/default` the next time llm-host writes the block. +opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, and a level the model's +template doesn't define makes every request fail. So the block carries `variants` that hide the levels the +loaded model lacks and add the ones it has (Qwen3.8 27B: no `high`, plus `xhigh`). A pasted remote block can't +follow a later switch, so the proxy also maps a level the model lacks to the nearest one it has (`high` → +`xhigh`); a stale menu entry still works. + To serve a different model, switch the server: `llmhost switch ` or the dashboard. Clients don't choose. Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the @@ -136,8 +144,8 @@ The setting is a default for requests that don't ask for anything: the proxy add completions, and a `chat_template_kwargs` key the client sets itself always wins. Changing it takes effect on the next request with no reload, so the model stays in memory. -On Linux + NVIDIA there's no chooser: vLLM runs without a proxy in front, so nothing is in the -path to add the argument. Clients can still pass `chat_template_kwargs` themselves. +This works the same on vLLM and MLX. A client's own top-level `reasoning_effort` also wins over +the dashboard's level, and one the model lacks is mapped to the nearest level it has. ## How models are chosen @@ -185,50 +193,43 @@ python3 tests/test_opencode.py # or run one directly | | | |---|---| | `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache | -| `tests/test_proxy.py` | the API refusing a model that isn't loaded, against a fake `mlx_lm` | +| `tests/test_proxy.py` | model names, effort mapping, upstream key, streamed-run counting, against a fake server | | `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing | | `tests/test_reasoning.py` | effort options matching the real chat templates | ## Continuing on an NVIDIA box -Everything in this branch was written and tested on Apple Silicon + MLX. The parts below are -either **unverified on vLLM** or deliberately not wired there, so start here when you check the -repo out on the Linux machine. `python3 tests/run.py` passes on either platform (the suites are -hermetic and don't need a GPU), so run that first to confirm nothing is broken. +This branch was written on Apple Silicon + MLX, then checked on Linux (vLLM 0.33.0, RTX PRO 6000 +Blackwell, qwen3.8-27b) on 2026-11-03. `python3 tests/run.py` passes on either platform (the +suites are hermetic and don't need a GPU), so run that first. -**Verify first — it can stop the server from starting:** +**Verified on the NVIDIA box:** -- `--served-model-name default` (`plan.vllm_args`). vLLM documents multiple names ("the - server will respond to any of them", with the first reported back), and the CLI form is one - flag with several tokens. Not run against a real vLLM, though, so confirm `vllm serve` accepts - it and that `curl -H "Authorization: Bearer $(llmhost key)" .../v1/chat/completions -d - '{"model":"default",...}'` answers. Until that's confirmed, the `llmhost-/default` block - that `llmhost opencode-config` prints can't work from a client. -- `/v1/models` should still report the real slug, not `default`. If it reports `default`, the - dashboard's readiness check (`active in served`) will sit on "loading" forever. +- vLLM runs behind the proxy (`backends/proxy.py`), on `127.0.0.1:1135` with its own API key, + which the proxy sends on. From the LAN: a wrong key gets 401, the inner port is unreachable, + `"model":"default"` is answered, an unknown model gets the proxy's `404 model_not_found`, and + `/v1/models` lists only the slug. +- Reasoning chooser: offers what Qwen3.8's template accepts; setting "Thinking off" from the + dashboard took effect on the next request with no restart. +- Completed-requests table: filled from the proxy, with prompt tokens net of the prefix cache + (`--enable-prompt-tokens-details`) and generated tokens from the usage chunk (a vLLM stream + chunk can carry several tokens). +- opencode from another machine: streaming and tool calls through the proxy; its generic `high` + maps to `xhigh` instead of failing; the generated block hides `high` and adds `xhigh`. +- Dashboard: GPU temperature and power from `nvidia-smi`, and KV usage from vLLM's `/metrics` + (read from the inner port). `METRIC_RE` had been dropped from `web/server.py`, leaving the + dashboard stuck on "loading"; `tests/test_dashboard.py` now covers it. -**Not wired on vLLM, by design — each needs a decision, not a bug fix:** +**Still open:** -- **Reasoning chooser.** The setting is injected per request by the MLX proxy, and llm-host runs - vLLM with nothing in front of it, so there's nowhere to inject. Either put a proxy on Linux too - (it would also bring the per-request table and the API-key handling into one place) or find a - vLLM flag for default chat-template kwargs. The dashboard hides the panel rather than offer a - control that does nothing. -- **Completed-requests table.** Same reason: the per-request timings come from the proxy. vLLM - exposes histograms on `/metrics` rather than per-request rows, so this would be a different - implementation, not a port. -- **`404 model_not_found` for a model that isn't loaded.** That's the proxy. On vLLM the two - served names both answer and anything else gets vLLM's own 404, which is the same outcome by a - different route — worth confirming the message is clear enough. - -**Should work, but has never run on this hardware:** - -- GPU temperature and power come from `nvidia-smi`, so the charts the dashboard hides on a Mac - should appear here. Check that the `hasTP` test in `index.html` doesn't hide them wrongly. -- KV cache on vLLM comes from `vllm:kv_cache_usage_perc` and predates this branch; the new - log-parsing path is MLX-only. -- `llmhost opencode-remove`, the opencode credential-cache clearing, and - `uninstall --purge --keep-key` are all platform-independent, but worth one smoke test each. +- opencode 1.19 keeps credentials in `~/.local/share/opencode/opencode.db` (a `credential` + table), not `auth.json`, so `opencode.clear_auth` no longer finds a stale cached key there. +- Power is summed over the GPUs that report it, so on a multi-GPU box a card showing `[N/A]` + makes the total read low (seen with a stub `nvidia-smi`, not real hardware). +- `llmhost opencode-remove` and `uninstall --purge --keep-key` pass their hermetic tests on Linux + but haven't been run against a real install there. +- An existing install picks up the second port on the next restart; `setup` checks it's free, + a bare restart doesn't (vLLM fails to bind and the log says so). ## Files diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index f0c9ec8..616a6f6 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -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 /' 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 ", 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) diff --git a/llmhost/backends/proxy.py b/llmhost/backends/proxy.py new file mode 100644 index 0000000..5edf1bf --- /dev/null +++ b/llmhost/backends/proxy.py @@ -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 /' 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 ", 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) diff --git a/llmhost/backends/vllm.py b/llmhost/backends/vllm.py index a5c77b9..70a01bc 100644 --- a/llmhost/backends/vllm.py +++ b/llmhost/backends/vllm.py @@ -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) diff --git a/llmhost/cli.py b/llmhost/cli.py index 884b2a9..afbcdda 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -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)) diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 96471c5..e0adf31 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -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", diff --git a/llmhost/plan.py b/llmhost/plan.py index 3165b15..a419633 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -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))) diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 52dab6e..5c9d53f 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -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 { +
+

Statistics

+ + + +
+
Generation
—
Prompt processing
—
@@ -214,10 +220,9 @@ pre {
Prefix cache hits
—
prompt tokens reused
-
+
Generation tok/s
10 min agonow
Prompt processing tok/s
10 min agonow
-
Time to first token
10 min agonow
KV cache %
10 min agonow
@@ -227,17 +232,20 @@ pre {
+
+

Requests

+ + + +
+
-
-

Completed requests

- -
- - + + @@ -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() { diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 72724b3..125d9e5 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -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}) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 90d490f..39255f9 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -8,14 +8,14 @@ import harness ROOT = harness.setup() from llmhost import paths -from llmhost.backends import mlx +from llmhost.backends import mlx, proxy from llmhost.web import server as web harness.guard(paths, ROOT) check = harness.Checks() print("\n1. KV is picked out of mlx_lm's log line") -st = mlx.Stats() +st = proxy.Stats() st.kv_budget = int(77.27 * 2**30) for seg in [b"2026-11-03 01:13:31,176 - INFO - Prompt Cache: 10 sequences, 1.58 GB\n", b"2026-11-03 01:14:32,794 - INFO - Prompt Cache: 12 sequences, 4.24 GB\n", @@ -33,20 +33,20 @@ check("fraction against --prompt-cache-bytes", abs(snap["kv"] - 2.00e9 / (77.27 check("budget reported", snap["kv_budget_bytes"] == int(77.27 * 2**30)) print("\n2. no budget -> no fraction, but still a size") -st2 = mlx.Stats(); st2.set_kv(4, 1.5e9) +st2 = proxy.Stats(); st2.set_kv(4, 1.5e9) check("kv is None", st2.snapshot()["kv"] is None) check("kv_bytes still there", st2.snapshot()["kv_bytes"] == 1.5e9) -check("fresh Stats reports nothing", mlx.Stats().snapshot()["kv"] is None) +check("fresh Stats reports nothing", proxy.Stats().snapshot()["kv"] is None) print("\n3. run records survive the round trip") -st3 = mlx.Stats() +st3 = proxy.Stats() st3.add_run({"start": 100.0, "end": 110.0, "dur": 10.0, "gen": 200, "prompt": 7667, "ttft": 2.0, "aborted": False}) check("recent carries the run", len(st3.snapshot()["recent"]) == 1) -for i in range(mlx.RECENT_RUNS + 10): +for i in range(proxy.RECENT_RUNS + 10): st3.add_run({"start": float(i), "end": float(i) + 1, "dur": 1.0, "gen": 1, "prompt": 1, "ttft": 0.1, "aborted": False}) -check(f"bounded to {mlx.RECENT_RUNS}", len(st3.snapshot()["recent"]) == mlx.RECENT_RUNS, +check(f"bounded to {proxy.RECENT_RUNS}", len(st3.snapshot()["recent"]) == proxy.RECENT_RUNS, len(st3.snapshot()["recent"])) print("\n4. the sampler splits a run into prefill and generation") @@ -142,4 +142,68 @@ check("nothing claimed to be a disconnect", not any("disconnected" in l for l in check("ordinary lines pass through", web.collapse_disconnects(["a", "b"]) == ["a", "b"]) check("empty input", web.collapse_disconnects([]) == []) +print("\n8. vLLM's /metrics is parsed (lines captured from vLLM 0.33 on an RTX PRO 6000)") +VLLM_METRICS = """# HELP vllm:num_requests_running Number of requests in model execution batches. +vllm:num_requests_running{engine="0",model_name="qwen3.8-27b"} 2.0 +vllm:num_requests_waiting{engine="0",model_name="qwen3.8-27b"} 1.0 +vllm:num_requests_waiting_by_reason{engine="0",model_name="qwen3.8-27b",reason="capacity"} 5.0 +vllm:kv_cache_usage_perc{engine="0",model_name="qwen3.8-27b"} 0.25 +vllm:prefix_cache_queries_total{engine="0",model_name="qwen3.8-27b"} 57.0 +vllm:prefix_cache_hits_total{engine="0",model_name="qwen3.8-27b"} 0.0 +vllm:num_preemptions_total{engine="0",model_name="qwen3.8-27b"} 0.0 +vllm:prompt_tokens_total{engine="0",model_name="qwen3.8-27b"} 57.0 +vllm:generation_tokens_total{engine="0",model_name="qwen3.8-27b"} 37.0 +vllm:time_to_first_token_seconds_bucket{engine="0",le="0.1",model_name="qwen3.8-27b"} 1.0 +vllm:time_to_first_token_seconds_count{engine="0",model_name="qwen3.8-27b"} 1.0 +vllm:time_to_first_token_seconds_sum{engine="0",model_name="qwen3.8-27b"} 0.03685879707336426 +vllm:time_to_first_token_seconds_created{engine="0",model_name="qwen3.8-27b"} 1793704000.0""" +vm = web.parse_vllm_metrics(VLLM_METRICS) +check("running / waiting", vm["running"] == 2.0 and vm["waiting"] == 1.0, vm) +check("waiting_by_reason not added into waiting", vm["waiting"] == 1.0, vm["waiting"]) +check("kv usage", vm["kv"] == 0.25, vm["kv"]) +check("token totals", vm["prompt_total"] == 57.0 and vm["gen_total"] == 37.0, vm) +check("ttft sum and count, buckets and _created skipped", + vm["ttft_count"] == 1.0 and abs(vm["ttft_sum"] - 0.0369) < 1e-3, vm) +check("empty body", web.parse_vllm_metrics("")["kv"] is None) + +check.section("9. Statistics reset rebases the counters; Requests clear empties the table") +smp = web.Sampler(harness.config(), "k") +raw = {"gen_total": 1000.0, "prompt_total": 5000.0, "ttft_sum": 4.0, "ttft_count": 8.0, + "prefix_hits": 300.0, "prefix_queries": 1000.0, "kv": 0.2, "running": 1} +check("before a reset: as reported", smp.since_reset(raw) == raw) +smp.prev = (0, raw) +smp.history.append({"t": 0, "kv": 20.0}) +smp.reset_stats() +check("charts emptied", len(smp.history) == 0) +check("reset time recorded", smp.stats_since is not None) +later = dict(raw, gen_total=1040.0, prompt_total=5100.0, ttft_sum=4.5, ttft_count=9.0, + prefix_hits=350.0, prefix_queries=1100.0) +sh = smp.since_reset(later) +check("counters count from the reset", sh["gen_total"] == 40 and sh["prompt_total"] == 100, sh) +check("averages are of what came after", sh["ttft_sum"] / sh["ttft_count"] == 0.5 and + sh["prefix_hits"] / sh["prefix_queries"] == 0.5, sh) +check("live values untouched", sh["kv"] == 0.2 and sh["running"] == 1, sh) +check("the reported metrics aren't modified", later["gen_total"] == 1040.0) +restarted = dict(raw, gen_total=12.0, prompt_total=30.0, ttft_sum=0.1, ttft_count=1.0, + prefix_hits=0.0, prefix_queries=30.0) +check("a server restart after the reset: its own counters already start later", + smp.since_reset(restarted)["gen_total"] == 12.0, smp.since_reset(restarted)) +smp.history.extend([{"t": 1, "kv": 5.0}, {"t": 2, "kv": 9.0}, {"t": 3, "kv": None}]) +check("peak KV since the reset comes from the samples", + smp.kv_peak_pct({"kv_peak_bytes": 8e9, "kv_budget_bytes": 1e10}) == 9.0) + +smp.runs.extend([{"t": 1}, {"t": 2}]) +smp._seen_runs.update({(1, 1), (2, 2)}) +smp.clear_runs() +check("requests cleared", len(smp.runs) == 0) +check("cleared requests stay seen (they don't come back)", {(1, 1), (2, 2)} <= smp._seen_runs) + +check.section("10. a run's peak KV comes from samples in its window, or not at all") +hist = [{"t": 10, "kv": 4.0}, {"t": 12, "kv": 7.5}, {"t": 14, "kv": 3.0}, {"t": 16, "kv": None}] +check("max over the window", web.run_kv_peak(hist, {"start": 9, "end": 15}, 15, 0.0) == 7.5) +check("a short run just finished: the reading right after it", + web.run_kv_peak(hist, {"start": 16.2, "end": 16.9}, 17.0, 2.5) == 2.5) +check("a run picked up long after (dashboard restarted): unknown, not 0%", + web.run_kv_peak([], {"start": 100, "end": 400}, 900, 0.0) is None) + check.done(ROOT) diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 30ecc5b..2a9510b 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -296,4 +296,31 @@ reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/qwen3-c opencode.sync(dict(CFG, active="qwen3-coder")) check("migrated under a renamed provider too", load()["model"] == "mymac/default", load().get("model")) +check.section("23. opencode-config's default points at an entry its block has") +import argparse, io, contextlib +cli._service_check = lambda: CFG +buf = io.StringIO() +with contextlib.redirect_stdout(buf): + cli.cmd_opencode(argparse.Namespace(host="popos.local", provider=None, json=True)) +snip = json.loads(buf.getvalue()) +prov_id, block = next(iter(snip["provider"].items())) +check("provider named after the host", prov_id == "llmhost-popos", prov_id) +check("model is /", + snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"], + (snip["model"], list(block["models"]))) + +check.section("24. the block offers only the effort levels the loaded model accepts") +check("qwen3.8: hide high, add xhigh", + opencode.effort_variants(("low", "medium", "xhigh")) == {"high": {"disabled": True}, + "xhigh": {"reasoningEffort": "xhigh"}}, + opencode.effort_variants(("low", "medium", "xhigh"))) +check("no levels: hide opencode's whole menu", + opencode.effort_variants(()) == {l: {"disabled": True} for l in ("low", "medium", "high")}) +q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") +ent = q["models"]["default"] +check("qwen3.8 block (not downloaded: catalog levels)", + ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent) +nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local") +check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"]) + check.done(ROOT) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 678751b..96044e0 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -9,14 +9,15 @@ import harness ROOT = harness.setup() from llmhost import paths -from llmhost.backends import mlx +from llmhost.backends import proxy harness.guard(paths, ROOT) SERVED = "ornith-1.5-9b" REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit" KEY = "sk-test-key" -seen = [] # bodies the inner (fake mlx_lm) server received +seen = [] # bodies the inner (fake mlx_lm / vLLM) server received +auths = [] # the Authorization header each of them came with check = harness.Checks() @@ -28,6 +29,21 @@ class Inner(BaseHTTPRequestHandler): raw = self.rfile.read(n) if n else b"" try: seen.append(json.loads(raw or b"{}")) except ValueError: seen.append(None) + auths.append(self.headers.get("Authorization")) + if seen[-1] and seen[-1].get("stream"): + # vLLM with speculative decoding: one chunk can carry several tokens, so only + # the closing usage chunk has the true count. + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + for text in ("Hello", " there, how", " are you"): + self.wfile.write(b"data: " + json.dumps({"choices": [{"index": 0, "delta": {"content": text}}]}).encode() + b"\n\n") + self.wfile.write(b"data: " + json.dumps({"choices": [], "usage": { + "prompt_tokens": 30, "completion_tokens": 7, "total_tokens": 37, + "prompt_tokens_details": {"cached_tokens": 20}}}).encode() + b"\n\n") + self.wfile.write(b"data: [DONE]\n\n") + self.close_connection = True + return body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model", "created": 0, "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "pong"}}], @@ -46,20 +62,21 @@ def serve(handler, port): INNER, OUTER = 18231, 18232 serve(Inner, INNER) -stats = mlx.Stats() -serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER) +stats = proxy.Stats() +serve(proxy.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER) -def post(model, key=KEY, path="/v1/chat/completions"): - body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4} +def post(model, key=KEY, path="/v1/chat/completions", port=None, raw_reply=False, **extra): + body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4, **extra} if model is not None: body["model"] = model - req = urllib.request.Request(f"http://127.0.0.1:{OUTER}{path}", data=json.dumps(body).encode(), + req = urllib.request.Request(f"http://127.0.0.1:{port or OUTER}{path}", data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"}, method="POST") try: with urllib.request.urlopen(req, timeout=20) as r: - return r.status, json.loads(r.read() or b"{}") + data = r.read() + return r.status, (data if raw_reply else json.loads(data or b"{}")) except urllib.error.HTTPError as e: try: return e.code, json.loads(e.read() or b"{}") except ValueError: return e.code, {} @@ -89,10 +106,12 @@ check("alias is 'default'", plan.SERVED_ALIAS == "default") seen.clear() post(plan.SERVED_ALIAS) check("still forwarded as default_model", seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None) -check("vLLM is told to serve it as a second name", - plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[1:4] - == ["--served-model-name", "m", plan.SERVED_ALIAS], - plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[:5]) +va = plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8001, 1) +check("vLLM serves one name; the proxy owns the alias", + va[1:3] == ["--served-model-name", "m"] and plan.SERVED_ALIAS not in va, va[:5]) +check("vLLM listens on localhost only, behind the proxy", + va[va.index("--host") + 1] == "127.0.0.1" and va[va.index("--port") + 1] == "8001", va) +check("vLLM reports cached prompt tokens", "--enable-prompt-tokens-details" in va, va) print("\n5. a model that ISN'T loaded is refused, not silently answered") code, body = post("qwen3.8-27b") @@ -122,4 +141,56 @@ with urllib.request.urlopen(req, timeout=10) as r: d = json.loads(r.read()) check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d) +check.section("9. in front of vLLM: its model name and its own key are sent upstream") +VOUTER = 18233 +vstats = proxy.Stats() +vstats.ready = True +serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",), + upstream_model="qwen3.8-27b", upstream_key="sk-inner", + effort_levels=("low", "medium", "xhigh"), + reasoning=lambda: {"reasoning_effort": "low"}), VOUTER) +seen.clear(); auths.clear() +check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200) +check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27b", seen[-1]) +check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1]) +check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404) + +check.section("10. effort levels the model lacks are mapped to the nearest it has") +for asked, sent in (("high", "xhigh"), ("medium", "medium"), ("xhigh", "xhigh"), + ("minimal", "low"), ("max", "xhigh")): + seen.clear() + post(None, port=VOUTER, reasoning_effort=asked) + check(f"top-level {asked} -> {sent}", seen[-1].get("reasoning_effort") == sent, seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "high"}) +check("inside chat_template_kwargs too", seen[-1]["chat_template_kwargs"].get("reasoning_effort") == "xhigh", + seen[-1].get("chat_template_kwargs")) +seen.clear() +post(None, port=VOUTER, reasoning_effort="bogus") +check("an unknown word is left for the server to reject", seen[-1].get("reasoning_effort") == "bogus", seen[-1]) +seen.clear() +post(None, port=VOUTER) +check("dashboard setting applied when the client sets none", + seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, reasoning_effort="xhigh") +check("a client's own top-level level wins over the dashboard's", + "reasoning_effort" not in (seen[-1].get("chat_template_kwargs") or {}) + and seen[-1].get("reasoning_effort") == "xhigh", seen[-1]) +check("mapping only where a model has levels", + [plan.nearest_effort("high", ()), plan.nearest_effort("high", ("low", "high"))] == [None, "high"]) +check("a tie goes to the higher level", plan.nearest_effort("high", ("medium", "xhigh")) == "xhigh") + +check.section("11. a streamed run is counted from its usage chunk, and recorded") +before = vstats.snapshot() +code, data = post(None, port=VOUTER, raw_reply=True, stream=True) +after = vstats.snapshot() +check("200", code == 200, code) +check("usage chunk hidden from a client that didn't ask for it", b'"usage"' not in data, data[-200:]) +check("generated tokens from usage (3 chunks, 7 tokens)", after["gen_total"] - before["gen_total"] == 7, + after["gen_total"] - before["gen_total"]) +run = after["recent"][-1] +check("run recorded with its uncached prompt tokens", run["gen"] == 7 and run["prompt"] == 10, run) +check("time to first token recorded", run["ttft"] is not None, run) + check.done(ROOT)
FinishedDurationTTFTPromptPrompt tok/sGeneratedGen tok/sPeak KVPrompt tokPrompt tok/sGenerated tokGen tok/sPeak KV