Compare commits

..

No commits in common. "8879db44a0a6e6d105234acb9d63e0cacdb11344" and "a250812d42dda44d19cd21e51b7c9a2a53238acf" have entirely different histories.

18 changed files with 401 additions and 2758 deletions

142
README.md
View file

@ -5,12 +5,9 @@ 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. installs the inference backend, and runs it as a background service with a web dashboard.
- **Linux + NVIDIA** → [vLLM](https://github.com/vllm-project/vllm) - **Linux + NVIDIA** → [vLLM](https://github.com/vllm-project/vllm)
- **macOS on Apple Silicon** → [MLX](https://github.com/ml-explore/mlx-lm) - **macOS on Apple Silicon** → [MLX](https://github.com/ml-explore/mlx-lm), behind a small proxy that adds API keys
Either way you get the same OpenAI-compatible API (with an API key) on port 1134 and a dashboard on port 11340. 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. Everything installs into your home directory; no sudo, Docker or system CUDA toolkit needed.
## Install ## Install
@ -55,9 +52,8 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
| `llmhost key` | print the API key | | `llmhost key` | print the API key |
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server | | `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
| `llmhost opencode-config` | print what to add to opencode on another machine | | `llmhost opencode-config` | print what to add to opencode on another machine |
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
| `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) | | `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) |
| `llmhost uninstall [--purge] [--models] [--keep-key]` | remove services, backends and this machine's opencode provider; asks before deleting downloaded models (`--models` deletes without asking). `--purge --keep-key` keeps the API key so a reinstall reuses it | | `llmhost uninstall [--purge] [--models]` | remove services and backends; asks before deleting downloaded models (`--models` deletes without asking) |
The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization, The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization,
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server. temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
@ -66,86 +62,14 @@ temperature and power with 10-minute charts, the server log, and buttons to swit
**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official **On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official
installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json`
pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. It shows up pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. Other
in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`.
the file up as `opencode.json.before-llmhost`.
`llmhost update` keeps the provider's port and model list in sync. Run it on demand with `llmhost opencode-setup` `llmhost update` keeps the provider's port and model list in sync. Run it on demand with `llmhost opencode-setup`
(`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`. (`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`.
A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead. A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead.
**On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner **On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner
that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (popos.local)` that copies the API key over. Only one model is loaded at a time; pick the one the server is currently running.
— under the provider id `llmhost-<shorthost>`.
### One opencode, several servers
The two paths use different provider ids, so a single opencode config can point at a local server and any number
of remote ones at once, each named after the machine it reaches:
| | provider id | shows up as | API key |
|---|---|---|---|
| local | `llmhost` | `LLMHost (Local)` | read straight from `~/.config/llm-host/api_key` |
| remote | `llmhost-<shorthost>` | `LLMHost (<host>)` | copied to `~/.config/opencode/llmhost-<shorthost>.key` |
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: 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 <name>` 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
provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is
never overwritten (setup takes `llmhost-local` instead and says so), and `uninstall` removes only the local
provider — remote ones, and providers llm-host didn't create, are left in place. If a provider's default model
goes away with it, `model` is repointed at a surviving llm-host provider, and dropped only if there is none.
Retiring a server is the one thing the servers can't do for each other: uninstalling on `popos` can't reach the
clients pointing at it. On each client, run `llmhost opencode-remove --host popos.local` (or delete the block by
hand if llm-host isn't installed there).
### If opencode keeps asking for the API key
opencode caches a provider's key in its own credential store, `~/.local/share/opencode/auth.json`, and **that copy
wins over `opencode.json`**: when it is stale, opencode fails auth without even sending a request and asks for the
key interactively. llm-host mints a fresh key whenever the config dir is purged, so a cached copy goes stale on
every `uninstall --purge` + reinstall.
Setup therefore deletes the cached entry for its own provider each time it runs, leaving the `{file:...}` reference
in `opencode.json` authoritative — that tracks the key file, so it can't go stale. Other providers' credentials in
that file are never touched. If you hit this on a client machine, delete the provider's entry from `auth.json` and
let it read the key file again.
To avoid invalidating remote clients in the first place, purge with `--keep-key`:
```bash
llmhost uninstall --purge --keep-key # keeps ~/.config/llm-host/api_key; a reinstall reuses it
```
## Reasoning effort
Reasoning effort is not a backend flag — it's a chat-template argument, read per request, and
what it accepts differs per model. Qwen3.8 27B's template takes `enable_thinking` plus
`reasoning_effort` in `low`/`medium`/`xhigh` (note: no `high`) and *raises* on anything else;
Ornith 1.5 9B takes only `enable_thinking`. So the dashboard builds the chooser from the loaded
model's own template, with the level names from `catalog.json` (`"effort": {"levels": [...]}`) —
a level the template doesn't know is never offered or sent.
The setting is a default for requests that don't ask for anything: the proxy adds it to chat
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.
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 ## How models are chosen
@ -178,59 +102,6 @@ These avoid problems that come up on a fresh desktop install without sudo:
- Kernel builds are limited to one compile job per ~12 GB of RAM (unlimited builds can exhaust memory). - Kernel builds are limited to one compile job per ~12 GB of RAM (unlimited builds can exhaust memory).
- `loginctl enable-linger` keeps the services running when you're logged out (and starts them at boot). - `loginctl enable-linger` keeps the services running when you're logged out (and starts them at boot).
## Tests
Stdlib only, no test dependencies, and nothing touches a real install — every suite redirects
`LLMHOST_HOME`, `LLMHOST_CONFIG` and `XDG_*` into a temp dir, and `tests/harness.py` aborts the
run if any path llmhost could write to resolves outside it.
```bash
python3 tests/run.py # every suite
python3 tests/run.py proxy # just the ones matching "proxy"
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` | 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
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.
**Verified on the NVIDIA box:**
- 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.
**Still open:**
- 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 ## Files
| Path | | | Path | |
@ -247,7 +118,6 @@ On macOS the services are launchd agents, so they run while you're logged in.
## Limitations ## Limitations
- One model loaded at a time. Asking the API for a different one returns - One model loaded at a time.
`404 model_not_found` naming the loaded model, rather than answering with it.
- AMD (ROCm), Intel and CPU-only machines aren't supported yet. - AMD (ROCm), Intel and CPU-only machines aren't supported yet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet. - The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet.

View file

@ -1,22 +1,25 @@
"""MLX backend (Apple Silicon). """MLX backend (Apple Silicon).
mlx_lm.server has no API-key support and loads whatever model a request names, so it mlx_lm.server has no API-key support and loads whatever model a request names, so it
listens on localhost only, behind llm-host's proxy (backends/proxy.py) on the public port. listens on localhost only and this module runs a small proxy on the public port that:
This module adds what's particular to mlx_lm: a readiness probe (its /health is OK before - checks the API key (like vLLM's --api-key),
the model has loaded), KV usage read from its log, and a restart when its generator dies. - 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).
""" """
import hmac
import http.client import http.client
import json import json
import os import os
import re
import shutil import shutil
import signal
import subprocess import subprocess
import sys import sys
import threading import threading
import time import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from .. import hfcache, paths, plan from .. import paths
from . import proxy
VENV = paths.DATA / "venv-mlx" VENV = paths.DATA / "venv-mlx"
PY = VENV / "bin/python" PY = VENV / "bin/python"
@ -33,6 +36,7 @@ def install(hw, log=print):
return {} return {}
QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
# Lines from mlx_lm.server / huggingface_hub that add nothing to the log. # 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") NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthenticated requests to the HF Hub")
@ -40,16 +44,10 @@ NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthentic
FATAL = b"generation thread died" FATAL = b"generation thread died"
# mlx_lm logs the prompt cache's size periodically; it has no endpoint for it, so this def _pump_output(stream, on_fatal=None):
# line is the only way to see KV usage. Its "GB" is n_bytes/1e9 -- decimal, not GiB.
CACHE_RE = re.compile(rb"Prompt Cache: (\d+) sequences, ([\d.]+) GB")
def _pump_output(stream, on_fatal=None, stats=None):
"""Copy the child's output to ours, dropping noise. Splits on \r too so download """Copy the child's output to ours, dropping noise. Splits on \r too so download
progress bars still update instead of being held back until a newline. Calls on_fatal progress bars still update instead of being held back until a newline. Calls on_fatal
when mlx_lm.server reports its generator died (it keeps running but can't answer). when mlx_lm.server reports its generator died (it keeps running but can't answer)."""
Picks the prompt-cache size out of the stream on the way past."""
buf = b"" buf = b""
out = sys.stdout.buffer out = sys.stdout.buffer
while True: while True:
@ -68,10 +66,6 @@ def _pump_output(stream, on_fatal=None, stats=None):
if on_fatal and FATAL in seg: if on_fatal and FATAL in seg:
on_fatal() on_fatal()
on_fatal = None on_fatal = None
if stats is not None:
m = CACHE_RE.search(seg)
if m:
stats.set_kv(int(m.group(1)), float(m.group(2)) * 1e9)
if buf: if buf:
out.write(buf) out.write(buf)
out.flush() out.flush()
@ -96,17 +90,236 @@ def _readiness_probe(inner_port, stats):
time.sleep(3) 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)
def snapshot(self):
with self.lock:
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}
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):
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 do_POST(self):
if not self._authed():
return
self._t0 = time.monotonic()
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):
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 _forward(self, method, raw, strip_usage=False):
counted = self.path.startswith("/v1/") # health checks aren't requests
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)
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:
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 {}
with stats.lock:
stats.gen_total += int(u.get("completion_tokens") or 0)
stats.prompt_total += _uncached(u)
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
pass
finally:
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
first_token = True
if first_token and not self._first and getattr(self, "_t0", None) is not None:
self._first = True
stats.ttft_sum += time.monotonic() - self._t0
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): def run_server(cfg, entry, choice, args):
"""Start the proxy on api_port, then mlx_lm.server as a child on api_port+1.""" """Start the auth proxy on api_port, then mlx_lm.server as a child on api_port+1."""
port = cfg["api_port"] port = cfg["api_port"]
inner = port + 1 inner = port + 1
stats = proxy.Stats() # Claim the public port first: if it's taken, fail before starting (and orphaning) a child.
controls = hfcache.template_controls(choice["repo"]) stats = Stats()
srv = proxy.listen(port, proxy.make_handler( try:
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats, srv = ThreadingHTTPServer(("0.0.0.0", port),
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls), make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
effort_levels=plan.effort_levels(entry, controls))) paths.api_key(), stats))
proxy.kill_stale(inner, VENV, "mlx_lm") 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)
exe = str(VENV / "bin/mlx_lm.server") exe = str(VENV / "bin/mlx_lm.server")
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
@ -115,7 +328,26 @@ def run_server(cfg, entry, choice, args):
print("llm-host: mlx_lm.server's generator crashed (often: out of GPU memory); restarting it", print("llm-host: mlx_lm.server's generator crashed (often: out of GPU memory); restarting it",
flush=True) flush=True)
child.terminate() child.terminate()
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), daemon=True).start()
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() threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start()
proxy.supervise(srv, child, "mlx_lm.server", port, inner)
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)

View file

@ -1,430 +0,0 @@
"""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,26 +160,7 @@ def run_env(cfg, hw=None, include_key=True):
return env return env
def run_server(cfg, entry, choice, args): def exec_server(cfg, args):
"""Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args). """Replace this process with `vllm serve` (so the service manager tracks vLLM directly)."""
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") exe = str(VENV / "bin/vllm")
# vLLM's output goes straight to ours (the service log); nothing in it needs reading. os.execve(exe, [exe, "serve", *args], run_env(cfg))
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

@ -9,52 +9,16 @@
"context": 262144, "context": 262144,
"hybrid": true, "hybrid": true,
"reasoning": true, "reasoning": true,
"vllm": { "vllm": {"tool_parser": "qwen3_coder", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "mtp_tokens": 3},
"tool_parser": "qwen3_coder",
"reasoning_parser": "qwen3",
"kv_cache_dtype": "fp8",
"mtp_tokens": 3
},
"mlx": {}, "mlx": {},
"variants": { "variants": {
"fp8": { "fp8": {"repo": "Qwen/Qwen3.8-27B-FP8", "gb": 30.9, "mtp": true},
"repo": "Qwen/Qwen3.8-27B-FP8", "bf16": {"repo": "Qwen/Qwen3.8-27B", "gb": 55.6, "mtp": true},
"gb": 30.9, "nvfp4": {"repo": "nvidia/Qwen3.8-27B-NVFP4", "gb": 21.9},
"mtp": true "awq": {"repo": "cyankiwi/Qwen3.8-27B-AWQ-INT4", "gb": 21.0},
}, "mlx-8bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-8bit", "gb": 29.5},
"bf16": { "mlx-6bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit", "gb": 22.8},
"repo": "Qwen/Qwen3.8-27B", "mlx-4bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-4bit", "gb": 16.1}
"gb": 55.6,
"mtp": true
},
"nvfp4": {
"repo": "nvidia/Qwen3.8-27B-NVFP4",
"gb": 21.9
},
"awq": {
"repo": "cyankiwi/Qwen3.8-27B-AWQ-INT4",
"gb": 21.0
},
"mlx-8bit": {
"repo": "lmstudio-community/Qwen3.8-27B-MLX-8bit",
"gb": 29.5
},
"mlx-6bit": {
"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit",
"gb": 22.8
},
"mlx-4bit": {
"repo": "lmstudio-community/Qwen3.8-27B-MLX-4bit",
"gb": 16.1
}
},
"effort": {
"levels": [
"low",
"medium",
"xhigh"
],
"default": "xhigh"
} }
}, },
{ {
@ -65,44 +29,16 @@
"context": 262144, "context": 262144,
"hybrid": true, "hybrid": true,
"reasoning": true, "reasoning": true,
"vllm": { "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true},
"tool_parser": "qwen3_xml", "mlx": {"trust_remote_code": true},
"reasoning_parser": "qwen3",
"kv_cache_dtype": "fp8",
"trust_remote_code": true
},
"mlx": {
"trust_remote_code": true
},
"variants": { "variants": {
"fp8": { "fp8": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", "gb": 39.4},
"repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", "bf16": {"repo": "ornith-ai/Ornith-1.5-35B-A3B", "gb": 71.9},
"gb": 39.4 "nvfp4": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-NVFP4", "gb": 23.4},
}, "awq": {"repo": "cyankiwi/Ornith-1.5-35B-A3B-AWQ-INT4", "gb": 26.1},
"bf16": { "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-8bit", "gb": 36.8},
"repo": "ornith-ai/Ornith-1.5-35B-A3B", "mlx-6bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit", "gb": 28.2},
"gb": 71.9 "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit", "gb": 19.5}
},
"nvfp4": {
"repo": "ornith-ai/Ornith-1.5-35B-A3B-NVFP4",
"gb": 23.4
},
"awq": {
"repo": "cyankiwi/Ornith-1.5-35B-A3B-AWQ-INT4",
"gb": 26.1
},
"mlx-8bit": {
"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-8bit",
"gb": 36.8
},
"mlx-6bit": {
"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit",
"gb": 28.2
},
"mlx-4bit": {
"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit",
"gb": 19.5
}
} }
}, },
{ {
@ -113,36 +49,15 @@
"context": 262144, "context": 262144,
"hybrid": false, "hybrid": false,
"reasoning": false, "reasoning": false,
"vllm": { "vllm": {"tool_parser": "qwen3_coder", "kv_cache_dtype": "fp8"},
"tool_parser": "qwen3_coder",
"kv_cache_dtype": "fp8"
},
"mlx": {}, "mlx": {},
"variants": { "variants": {
"fp8": { "fp8": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", "gb": 31.2},
"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", "bf16": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", "gb": 61.1},
"gb": 31.2 "awq": {"repo": "cyankiwi/Qwen3-Coder-30B-A3B-Instruct-AWQ-4bit", "gb": 18.1},
}, "mlx-8bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit", "gb": 32.4},
"bf16": { "mlx-6bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit", "gb": 24.8},
"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", "mlx-4bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-4bit", "gb": 17.2}
"gb": 61.1
},
"awq": {
"repo": "cyankiwi/Qwen3-Coder-30B-A3B-Instruct-AWQ-4bit",
"gb": 18.1
},
"mlx-8bit": {
"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit",
"gb": 32.4
},
"mlx-6bit": {
"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit",
"gb": 24.8
},
"mlx-4bit": {
"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-4bit",
"gb": 17.2
}
} }
}, },
{ {
@ -153,40 +68,15 @@
"context": 262144, "context": 262144,
"hybrid": true, "hybrid": true,
"reasoning": true, "reasoning": true,
"vllm": { "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true},
"tool_parser": "qwen3_xml", "mlx": {"trust_remote_code": true},
"reasoning_parser": "qwen3",
"kv_cache_dtype": "fp8",
"trust_remote_code": true
},
"mlx": {
"trust_remote_code": true
},
"variants": { "variants": {
"fp8": { "fp8": {"repo": "ornith-ai/Ornith-1.5-122B-FP8", "gb": 132.9},
"repo": "ornith-ai/Ornith-1.5-122B-FP8", "bf16": {"repo": "ornith-ai/Ornith-1.5-122B", "gb": 250.2},
"gb": 132.9 "nvfp4": {"repo": "ornith-ai/Ornith-1.5-122B-NVFP4", "gb": 77.6},
}, "awq": {"repo": "cyankiwi/Ornith-1.5-122B-AWQ-INT4", "gb": 85.3},
"bf16": { "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-8bit", "gb": 130.6},
"repo": "ornith-ai/Ornith-1.5-122B", "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit", "gb": 69.6}
"gb": 250.2
},
"nvfp4": {
"repo": "ornith-ai/Ornith-1.5-122B-NVFP4",
"gb": 77.6
},
"awq": {
"repo": "cyankiwi/Ornith-1.5-122B-AWQ-INT4",
"gb": 85.3
},
"mlx-8bit": {
"repo": "ornith-ai/Ornith-1.5-122B-MLX-8bit",
"gb": 130.6
},
"mlx-4bit": {
"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit",
"gb": 69.6
}
} }
}, },
{ {
@ -197,40 +87,15 @@
"context": 262144, "context": 262144,
"hybrid": true, "hybrid": true,
"reasoning": true, "reasoning": true,
"vllm": { "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true},
"tool_parser": "qwen3_xml", "mlx": {"trust_remote_code": true},
"reasoning_parser": "qwen3",
"kv_cache_dtype": "fp8",
"trust_remote_code": true
},
"mlx": {
"trust_remote_code": true
},
"variants": { "variants": {
"bf16": { "bf16": {"repo": "ornith-ai/Ornith-1.5-9B", "gb": 19.3},
"repo": "ornith-ai/Ornith-1.5-9B", "nvfp4": {"repo": "ornith-ai/Ornith-1.5-9B-NVFP4", "gb": 8.8},
"gb": 19.3 "awq": {"repo": "cyankiwi/Ornith-1.5-9B-AWQ-INT4", "gb": 9.0},
}, "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-8bit", "gb": 9.5},
"nvfp4": { "mlx-6bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit", "gb": 7.3},
"repo": "ornith-ai/Ornith-1.5-9B-NVFP4", "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-4bit", "gb": 5.0}
"gb": 8.8
},
"awq": {
"repo": "cyankiwi/Ornith-1.5-9B-AWQ-INT4",
"gb": 9.0
},
"mlx-8bit": {
"repo": "ornith-ai/Ornith-1.5-9B-MLX-8bit",
"gb": 9.5
},
"mlx-6bit": {
"repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit",
"gb": 7.3
},
"mlx-4bit": {
"repo": "ornith-ai/Ornith-1.5-9B-MLX-4bit",
"gb": 5.0
}
} }
} }
] ]

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 # 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.) # listening belongs to another program. (--no-start leaves a running setup alone.)
# Two ports: the proxy, and the model server behind it on the next one. # MLX needs two ports: the proxy, and mlx_lm.server on the next one.
api_span = 2 api_span = 2 if p["backend"] == "mlx" else 1
if not a.no_start: if not a.no_start:
with Spinner("Stopping llm-host's running services"): with Spinner("Stopping llm-host's running services"):
for name in service.NAMES: for name in service.NAMES:
@ -209,23 +209,15 @@ def setup_opencode(cfg, ask, install_ok=False, later="llmhost opencode-setup"):
say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup") say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup")
return return
say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")") say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")")
status, path, prov, auth_cleared = opencode.configure(cfg) status, path = opencode.configure(cfg)
if status in ("has-comments", "unparsable"): if status == "has-comments":
why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON" say(f"\n{path} has comments, which an automatic edit would delete, so it was left as is.\n"
say(f"\n{path} {why}, so it was left as is.\n" f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg)}")
f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg, prov)}")
return return
msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status] msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status]
label = f"{opencode.DISPLAY} ({opencode.LOCAL_LABEL})" say(f"\nopencode: {msg} the `{opencode.PROVIDER}` provider in {path} (http://localhost:{cfg['api_port']}/v1).")
say(f"\nopencode: {msg} the `{prov}` provider \u2014 {label} \u2014 in {path} (http://localhost:{cfg['api_port']}/v1).")
if prov != opencode.PROVIDER:
say(f"(`{opencode.PROVIDER}` is taken by another provider, which was left alone.)")
if auth_cleared:
say(f"Cleared opencode's cached key for `{prov}` in {opencode.auth_file()}, so it reads\n"
f"{paths.KEY_FILE} instead. A cached copy goes stale whenever the key is\n"
f"regenerated, and opencode then asks for it interactively.")
if status == "added": if status == "added":
say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{cfg['active']})") say(f"Start it with: opencode (pick a model with /models; this server answers as {opencode.PROVIDER}/{cfg['active']})")
def cmd_opencode_setup(a): def cmd_opencode_setup(a):
@ -350,8 +342,6 @@ def cmd_switch(a):
cfg["active"] = a.model cfg["active"] = a.model
paths.save_config(cfg) paths.save_config(cfg)
service.restart("model") service.restart("model")
if opencode.sync(cfg):
say(f"Updated opencode's model list; {a.model} is the one marked loaded.")
say(f"Switched to {a.model}. Watch it load with: llmhost watch") say(f"Switched to {a.model}. Watch it load with: llmhost watch")
@ -469,12 +459,12 @@ def cmd_download(a):
def cmd_opencode(a): def cmd_opencode(a):
cfg = _service_check() cfg = _service_check()
host = a.host or default_host() host = a.host or default_host()
prov = a.provider or opencode.remote_provider(host) prov = a.provider or f"llmhost-{host.split('.')[0]}"
keyfile = opencode.remote_key_file(prov) keyfile = f"~/.config/opencode/{prov}.key"
snippet = { snippet = {
"$schema": "https://opencode.ai/config.json", "$schema": "https://opencode.ai/config.json",
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host)}, "provider": {prov: opencode.provider_block(cfg, host, keyfile, host.split(".")[0])},
"model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry "model": f"{prov}/{cfg['active']}",
} }
if a.json: if a.json:
say(json.dumps(snippet, indent=2)) say(json.dumps(snippet, indent=2))
@ -490,10 +480,7 @@ On another machine running opencode:
2. Merge this into ~/.config/opencode/opencode.json: 2. Merge this into ~/.config/opencode/opencode.json:
""") """)
say(json.dumps(snippet, indent=2)) say(json.dumps(snippet, indent=2))
say(f""" say(f"\nOnly the active model answers at a time; switch with `llmhost switch <name>` or the dashboard.")
It shows up in opencode as "{opencode.DISPLAY} ({host})". Only the active model answers at a
time; switch with `llmhost switch <name>` or the dashboard. If this server goes away, remove
the block there with: llmhost opencode-remove --host {host}""")
def cmd_update(a): def cmd_update(a):
@ -523,23 +510,6 @@ def hf_cache_rm_cmd(repos):
"--cache-dir", str(paths.hf_hub_dir()), *[f"model/{r}" for r in repos]] "--cache-dir", str(paths.hf_hub_dir()), *[f"model/{r}" for r in repos]]
def purge(keep_key=False):
"""Remove the config dir, the data dir and the launcher. With keep_key, the API key
survives, so a reinstall reuses it and clients configured with it keep working
(setup only mints a key when the file is absent). Returns the kept path, or None."""
keep = paths.KEY_FILE.read_text() if keep_key and paths.KEY_FILE.exists() else None
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
shutil.rmtree(paths.DATA, ignore_errors=True)
paths.SHIM.unlink(missing_ok=True)
if keep is None:
return None
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
fd = os.open(paths.KEY_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(keep)
return paths.KEY_FILE
def cmd_uninstall(a): def cmd_uninstall(a):
# Read the catalog now: --purge deletes it along with the rest of llm-host. # Read the catalog now: --purge deletes it along with the rest of llm-host.
cached = cached_catalog_models() cached = cached_catalog_models()
@ -549,30 +519,18 @@ def cmd_uninstall(a):
# Stopping returns before the processes have exited (launchd especially). Wait, so 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. # reinstall right after this finds the ports free instead of moving to other ones.
if cfg.get("api_port"): if cfg.get("api_port"):
span = 2 # the proxy and the model server behind it span = 2 if cfg.get("backend") == "mlx" else 1
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else []) 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"): with Spinner("Waiting for the services to exit"):
wait_ports_free(ours, timeout=30) wait_ports_free(ours, timeout=30)
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"): for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
shutil.rmtree(paths.DATA / d, ignore_errors=True) shutil.rmtree(paths.DATA / d, ignore_errors=True)
say("Removed services and backend environments.") say("Removed services and backend environments.")
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
oc_status, oc_path, oc_removed, oc_model = opencode.remove(local=True)
if oc_status == "removed":
say(f"opencode: removed {', '.join('`' + r + '`' for r in oc_removed)} from {oc_path}."
+ (f" Its default model is now {oc_model}." if oc_model else ""))
elif oc_status in ("has-comments", "unparsable"):
why = "has comments" if oc_status == "has-comments" else "isn't valid JSON"
say(f"opencode: {oc_path} {why}, so it was left alone; remove the llm-host provider by hand.")
if a.purge: if a.purge:
kept = purge(a.keep_key) shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
if kept is None: shutil.rmtree(paths.DATA, ignore_errors=True)
say("Removed config, API key and llm-host itself.") paths.SHIM.unlink(missing_ok=True)
say("A reinstall mints a new API key, so clients elsewhere will need the new one\n" say("Removed config, API key and llm-host itself.")
"(`llmhost opencode-config`). Keep the current key instead with: --purge --keep-key")
else:
say(f"Removed config and llm-host itself; kept the API key at {kept},\n"
"so a reinstall reuses it and clients elsewhere keep working.")
if not cached: if not cached:
return return
total = sum(g for _, g in cached) total = sum(g for _, g in cached)
@ -596,22 +554,6 @@ def cmd_uninstall(a):
+ " ".join(cmd).replace(str(paths.HOME), "~")) + " ".join(cmd).replace(str(paths.HOME), "~"))
def cmd_opencode_remove(a):
explicit = bool(a.provider or a.host or a.all)
status, path, removed, new_model = opencode.remove(
prov_ids=[a.provider] if a.provider else None,
local=not explicit, host=a.host, every=a.all)
if status in ("has-comments", "unparsable"):
why = "has comments" if status == "has-comments" else "isn't valid JSON"
raise SystemExit(f"{path} {why}; edit it by hand.")
if status == "none":
say(f"No matching llm-host provider in {path}.")
return
say(f"Removed {', '.join('`' + r + '`' for r in removed)} from {path}.")
if new_model:
say(f"opencode's default model is now {new_model}.")
def cmd_run_model(a): def cmd_run_model(a):
cfg = _service_check() cfg = _service_check()
cat = paths.load_catalog() cat = paths.load_catalog()
@ -621,7 +563,7 @@ def cmd_run_model(a):
say(f"llm-host {VERSION}: starting {entry['name']} ({choice['repo']}, {choice['format']}) on {cfg['backend']}") say(f"llm-host {VERSION}: starting {entry['name']} ({choice['repo']}, {choice['format']}) on {cfg['backend']}")
if cfg["backend"] == "vllm": if cfg["backend"] == "vllm":
from .backends import vllm from .backends import vllm
vllm.run_server(cfg, entry, choice, plan.vllm_args(entry, choice, cfg["api_port"] + 1, cfg.get("tp", 1))) vllm.exec_server(cfg, plan.vllm_args(entry, choice, cfg["api_port"], cfg.get("tp", 1)))
else: else:
from .backends import mlx from .backends import mlx
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1)) mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
@ -684,19 +626,12 @@ def main(argv=None):
s.add_argument("--provider", help="opencode provider id") s.add_argument("--provider", help="opencode provider id")
s.add_argument("--json", action="store_true", help="print only the JSON") s.add_argument("--json", action="store_true", help="print only the JSON")
s.set_defaults(fn=cmd_opencode) s.set_defaults(fn=cmd_opencode)
s = sub.add_parser("opencode-remove", help="remove llm-host providers from this machine's opencode config")
s.add_argument("--host", help="remove the provider pointing at this host (a retired remote server)")
s.add_argument("--provider", help="remove this provider id")
s.add_argument("--all", action="store_true", help="remove every llm-host provider, local and remote")
s.set_defaults(fn=cmd_opencode_remove)
s = sub.add_parser("update", help="pull the latest llm-host and re-plan") s = sub.add_parser("update", help="pull the latest llm-host and re-plan")
s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend") s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend")
s.set_defaults(fn=cmd_update) s.set_defaults(fn=cmd_update)
s = sub.add_parser("uninstall", help="remove services and backends (asks before deleting models)") s = sub.add_parser("uninstall", help="remove services and backends (asks before deleting models)")
s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself") s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself")
s.add_argument("--models", action="store_true", help="also delete downloaded models without asking") s.add_argument("--models", action="store_true", help="also delete downloaded models without asking")
s.add_argument("--keep-key", action="store_true", help="with --purge, keep the API key so a reinstall reuses it")
s.set_defaults(fn=cmd_uninstall) s.set_defaults(fn=cmd_uninstall)
sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
sub.add_parser("run-web").set_defaults(fn=cmd_run_web) sub.add_parser("run-web").set_defaults(fn=cmd_run_web)

View file

@ -59,36 +59,3 @@ def download_gib(repo):
except OSError: except OSError:
pass pass
return total / 2**30 return total / 2**30
def chat_template(repo):
"""The model's chat template, or "" if it isn't on disk. Newer repos ship it as
chat_template.jinja; older ones keep it inside tokenizer_config.json."""
snaps = repo_dir(repo) / "snapshots"
if not snaps.is_dir():
return ""
for snap in snaps.iterdir():
f = snap / "chat_template.jinja"
if f.exists():
try:
return f.read_text()
except OSError:
pass
cfg = snap / "tokenizer_config.json"
if cfg.exists():
try:
t = json.loads(cfg.read_text()).get("chat_template")
except (OSError, ValueError):
continue
if isinstance(t, str) and t:
return t
return ""
def template_controls(repo):
"""Which reasoning knobs this model's template actually reads. Checked against the
template rather than trusted from the catalog, because passing a kwarg the template
doesn't expect is silently ignored, and an effort level it doesn't know makes it
raise -- so the dashboard must only ever offer what is really there."""
t = chat_template(repo)
return {"thinking": "enable_thinking" in t, "effort": "reasoning_effort" in t}

View file

@ -1,33 +1,18 @@
"""opencode integration: install it if missing, and register llm-host as a provider. """opencode integration: install it if missing, and register llm-host as a provider.
Two shapes of provider, both created from here: On the server itself the provider points at localhost and reads the key straight from
llm-host's key file, so nothing has to be copied. Re-running keeps the provider's port and
local this machine's server, reached over localhost, reading llm-host's key file model list in sync with the current plan. Other providers and settings are left untouched.
directly. Provider id `llmhost`, display name "LLMHost (Local)".
remote another machine's server, reached by hostname with the key copied into
~/.config/opencode/<provider>.key. Provider id `llmhost-<shorthost>`,
display name "LLMHost (<host>)". Printed by `llmhost opencode-config`
for pasting on the client; this module never writes it here.
The two never collide, so one opencode config can point at a local server and any
number of remote ones at once. Which block is *this machine's* is decided by the
key-file reference, not by the provider's name, so a renamed provider is still
recognised and a remote provider that happens to sit under the `llmhost` id is
never overwritten. Other providers and settings are left untouched.
""" """
import json import json
import os import os
import shutil import shutil
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from urllib.parse import urlsplit
from . import hfcache, paths, plan from . import paths
PROVIDER = "llmhost" PROVIDER = "llmhost"
DISPLAY = "LLMHost"
LOCAL_LABEL = "Local"
LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]")
INSTALL_URL = "https://opencode.ai/install" INSTALL_URL = "https://opencode.ai/install"
@ -58,164 +43,22 @@ def config_file():
return d / "opencode.json" return d / "opencode.json"
def auth_file(): def provider_block(cfg, host, key_path, label):
"""opencode's credential store (XDG_DATA_HOME, not the config dir).""" models = {}
return Path(os.environ.get("XDG_DATA_HOME") or paths.HOME / ".local/share") / "opencode" / "auth.json" for m in cfg["models"]:
entry = {"name": f"{m['name']} ({label})", "tool_call": True,
"limit": {"context": m["est_context"], "output": min(65536, m["est_context"] // 2)}}
def clear_auth(*provs): if m.get("reasoning"):
"""Drop opencode's cached API key for these providers. Returns the ids cleared. entry["reasoning"] = True
models[m["name"]] = entry
opencode caches a provider's key in its own auth store, and that copy wins over
the config: when it is stale, opencode fails auth without even sending a request
and asks for the key interactively. llm-host mints a fresh key whenever the config
dir is purged, so a cached copy goes stale on every reinstall. Our provider block
points at the key file, which never goes stale -- so the cache is only ever a
liability for it, and removing the entry makes the file reference authoritative.
"""
path = auth_file()
if not path.exists():
return []
try:
data = json.loads(path.read_text())
except (OSError, ValueError):
return [] # not ours to repair
if not isinstance(data, dict):
return []
gone = [p for p in provs if p in data]
if not gone:
return []
for p in gone:
del data[p]
try:
mode = path.stat().st_mode & 0o777
except OSError:
mode = 0o600
tmp = path.with_name(path.name + ".llmhost-tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, path)
return gone
def remote_provider(host):
"""Provider id for a server reached at `host`."""
return f"{PROVIDER}-{host.split('.')[0]}"
def remote_key_file(prov):
return f"~/.config/opencode/{prov}.key"
def key_ref(key_path):
return "{file:" + str(key_path) + "}"
def model_label(active, label, name_it):
"""What opencode shows for the single entry. One model is loaded at a time, so there is
nothing to choose here -- the label's job is to say which one answers right now. Only
where llm-host keeps the block in sync, though: a remote block is pasted once and never
refreshed, so naming a model there would be a claim that goes stale on the next switch."""
if name_it and active:
return f"Default model \u00b7 {active.get('title') or active['name']} ({label})"
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
# one would break every client's saved default on each `llmhost switch`.
active = next((m for m in cfg["models"] if m["name"] == cfg.get("active")), None)
ctx = (active or {}).get("est_context") or min(
(m["est_context"] for m in cfg["models"]), default=32768)
entry = {"name": model_label(active, label, mark_loaded), "tool_call": True,
"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 { return {
"npm": "@ai-sdk/openai-compatible", "npm": "@ai-sdk/openai-compatible",
"name": f"{DISPLAY} ({label})", "name": f"llm-host ({label})",
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + key_path + "}"},
"models": models, "models": models,
} }
def local_block(cfg):
# Only the local block is marked: llm-host keeps it in sync on every switch, whereas a
# remote block is a snapshot pasted elsewhere and would go stale the moment it changed.
return provider_block(cfg, "localhost", str(paths.KEY_FILE), LOCAL_LABEL, mark_loaded=True)
def base_host(block):
"""Hostname from a provider's baseURL, or "" if it hasn't got one."""
try:
url = block["options"]["baseURL"]
except (KeyError, TypeError):
return ""
return (urlsplit(url).hostname or "").lower()
def is_local_block(prov_id, block):
"""True when this provider block is *this machine's* llm-host server.
Identified by its key-file reference, which only `configure` ever writes, so the
block is still ours after a rename. The id fallback catches blocks written before
the key moved (LLMHOST_CONFIG), but only alongside a localhost baseURL -- a remote
provider sitting under the `llmhost` id must not match.
"""
if not isinstance(block, dict):
return False
api_key = (block.get("options") or {}).get("apiKey") or ""
if str(paths.KEY_FILE) in api_key:
return True
return prov_id == PROVIDER and base_host(block) in LOCALHOSTS
def local_ids(providers):
return [p for p, block in providers.items() if is_local_block(p, block)]
def ours_ids(providers):
"""Every provider this module created: the local one plus any pasted `llmhost-*`."""
return [p for p, block in providers.items()
if is_local_block(p, block) or p.startswith(PROVIDER + "-")
or (isinstance(block, dict) and str(block.get("name", "")).startswith(DISPLAY + " ("))]
def _strip_jsonc(text): def _strip_jsonc(text):
"""Remove comments and trailing commas outside strings. Returns (clean_text, had_comments).""" """Remove comments and trailing commas outside strings. Returns (clean_text, had_comments)."""
out, i, n, had_comments = [], 0, len(text), False out, i, n, had_comments = [], 0, len(text), False
@ -250,171 +93,41 @@ def _strip_jsonc(text):
return "".join(out), had_comments return "".join(out), had_comments
def _read(path): def configure(cfg):
"""Returns (data, "") or (None, reason) when the file can't be rewritten safely.""" """Add or refresh the llmhost provider. Returns (status, path); status is one of
if not path.exists(): added, updated, unchanged, or has-comments (file left alone because rewriting would drop them)."""
return {"$schema": "https://opencode.ai/config.json"}, "" path = config_file()
text = path.read_text() if path.exists():
try: text = path.read_text()
return json.loads(text), ""
except ValueError:
clean, had_comments = _strip_jsonc(text)
if had_comments:
return None, "has-comments"
try: try:
return json.loads(clean), "" # only trailing commas; safe to normalize data = json.loads(text)
except ValueError: except ValueError:
return None, "unparsable" clean, had_comments = _strip_jsonc(text)
if had_comments:
return "has-comments", path
data = json.loads(clean) # only trailing commas; safe to normalize
else:
data = {"$schema": "https://opencode.ai/config.json"}
before = json.dumps(data, sort_keys=True)
providers = data.setdefault("provider", {})
existed = PROVIDER in providers
providers[PROVIDER] = provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")
if "model" not in data:
data["model"] = f"{PROVIDER}/{cfg['active']}"
if json.dumps(data, sort_keys=True) == before:
return "unchanged", path
def _write(path, data, backup=True):
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
if backup and path.exists(): if path.exists():
before = path.with_name(path.name + ".before-llmhost") backup = path.with_name(path.name + ".before-llmhost")
if not before.exists(): if not backup.exists():
shutil.copy2(path, before) shutil.copy2(path, backup)
tmp = path.with_name(path.name + ".tmp") tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(data, indent=2) + "\n") tmp.write_text(json.dumps(data, indent=2) + "\n")
os.replace(tmp, path) os.replace(tmp, path)
return ("updated" if existed else "added"), path
def configure(cfg): def snippet(cfg):
"""Add or refresh this machine's provider. Returns (status, path, prov_id, auth_cleared); return json.dumps({"provider": {PROVIDER: provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")}}, indent=2)
status is added, updated, unchanged, has-comments or unparsable (the last two leave the
file alone)."""
path = config_file()
data, problem = _read(path)
if problem:
return problem, path, PROVIDER, False
providers = data.setdefault("provider", {})
mine = local_ids(providers)
if mine:
prov = mine[0] # ours already, whatever it has been renamed to
elif PROVIDER not in providers:
prov = PROVIDER
else:
# Something else is sitting under `llmhost` (most likely a remote server pasted
# from `opencode-config --provider llmhost`). Don't touch it; take a free id.
prov = f"{PROVIDER}-local"
n = 2
while prov in providers:
prov, n = f"{PROVIDER}-local{n}", n + 1
before = json.dumps(data, sort_keys=True)
existed = prov in providers
providers[prov] = local_block(cfg)
if "model" not in data:
data["model"] = f"{prov}/{plan.SERVED_ALIAS}"
else:
_retarget_model(data, prov)
# Unconditional: a cached key for our provider is stale or redundant either way.
cleared = bool(clear_auth(prov))
if json.dumps(data, sort_keys=True) == before:
return "unchanged", path, prov, cleared
_write(path, data)
return ("updated" if existed else "added"), path, prov, cleared
def _retarget_model(data, prov):
"""Move a default that named one of our models onto the alias. Our provider used to
list every model that fits, so an existing config can point at `llmhost/qwen3.8-27b`
-- an id this provider no longer has, which opencode would reject outright."""
model = data.get("model") or ""
their_prov, _, their_model = model.partition("/")
if their_prov == prov and their_model != plan.SERVED_ALIAS:
data["model"] = f"{prov}/{plan.SERVED_ALIAS}"
return True
return False
def _pick_fallback_model(providers, removed):
"""A `model` value from a surviving llm-host provider: its first model, which is the
one its own plan preferred, rather than whichever name happens to sort first.
Providers are taken in id order so the choice is stable."""
for prov in sorted(set(ours_ids(providers)) - set(removed)):
models = (providers.get(prov) or {}).get("models") or {}
if models:
return f"{prov}/{next(iter(models))}"
return None
def remove(prov_ids=None, local=True, host=None, every=False):
"""Remove llm-host providers from this machine's opencode config.
local this machine's provider, found by key-file reference
host the provider pointing at `host` (a remote server being retired)
every every provider this module created, local and remote
Returns (status, path, removed_ids, new_model); status is removed, none or a
problem code. `model` is repointed at a surviving llm-host provider if it named
one that went away, and dropped only when none is left. Providers llm-host didn't
create are never removed and never become the fallback -- including ones pointing
at the same `host`, since retiring our provider is no reason to delete theirs.
"""
path = config_file()
if not path.exists():
return "none", path, [], None
data, problem = _read(path)
if problem:
return problem, path, [], None
providers = data.get("provider") or {}
targets = set(prov_ids or [])
if every:
targets |= set(ours_ids(providers))
if local:
targets |= set(local_ids(providers))
if host:
# Scoped to providers we created: another tool's provider may well point at the
# same server, and retiring ours is no reason to delete theirs.
h = host.lower().split(".")[0]
targets |= {p for p in ours_ids(providers)
if base_host(providers[p]).split(".")[0] == h}
targets &= set(providers)
if not targets:
return "none", path, [], None
for prov in targets:
del providers[prov]
clear_auth(*targets)
new_model = None
model = data.get("model") or ""
if model.split("/", 1)[0] in targets:
new_model = _pick_fallback_model(providers, targets)
if new_model:
data["model"] = new_model
else:
del data["model"]
if not providers:
data.pop("provider", None)
_write(path, data, backup=False)
return "removed", path, sorted(targets), new_model
def sync(cfg):
"""Refresh an existing local provider block -- after a model switch, so the "loaded"
marker and the model list keep up. Never adds one: if opencode isn't wired up here,
switching a model is no reason to wire it. Returns the provider id, or None."""
path = config_file()
if not path.exists():
return None
data, problem = _read(path)
if problem:
return None
providers = data.get("provider") or {}
mine = local_ids(providers)
if not mine:
return None
prov = mine[0]
before = json.dumps(data, sort_keys=True)
providers[prov] = local_block(cfg)
_retarget_model(data, prov)
if json.dumps(data, sort_keys=True) == before:
return None
_write(path, data, backup=False)
return prov
def snippet(cfg, prov=PROVIDER):
return json.dumps({"provider": {prov: local_block(cfg)}}, indent=2)

View file

@ -118,19 +118,13 @@ def catalog_entry(catalog, name):
# ---------- backend command lines ---------- # ---------- backend command lines ----------
def vllm_args(entry, choice, port, tp): def vllm_args(entry, choice, port, tp):
"""Arguments after `vllm serve` (bound to localhost; the proxy faces the network and """Arguments after `vllm serve`."""
owns the model's other names, so vLLM only needs the one it's addressed by)."""
v = entry.get("vllm", {}) v = entry.get("vllm", {})
args = [choice["repo"], "--served-model-name", entry["name"], args = [choice["repo"], "--served-model-name", entry["name"],
"--host", "127.0.0.1", "--port", str(port), "--host", "0.0.0.0", "--port", str(port),
"--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native) "--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native)
"--gpu-memory-utilization", f"{choice['util']:.2f}", "--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: if tp > 1:
args += ["--tensor-parallel-size", str(tp)] args += ["--tensor-parallel-size", str(tp)]
if entry.get("hybrid"): if entry.get("hybrid"):
@ -166,70 +160,3 @@ def mlx_args(entry, choice, port):
args += ["--prompt-concurrency", "1", "--decode-concurrency", "4"] args += ["--prompt-concurrency", "1", "--decode-concurrency", "4"]
args += x.get("extra_args", []) args += x.get("extra_args", [])
return args return args
# 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. The proxy in front of either backend accepts it
# and /v1/models lists only the real slug.
SERVED_ALIAS = "default"
# ---- reasoning effort -------------------------------------------------------------
# Not a backend flag: it's a chat-template kwarg, read per request. "default" means send
# nothing and let the template decide; "off" suppresses thinking; anything else is an
# effort level the template defines. Levels come from the catalog (they're model-specific
# and a wrong one makes the template raise), gated by what the template really reads.
OFF = "off"
DEFAULT = "default"
def reasoning_options(entry, choice, controls):
"""The settings a model can be given, as (value, label) pairs, most effort first."""
if not entry.get("reasoning"):
return []
opts = [(DEFAULT, "Model default")]
levels = (entry.get("effort") or {}).get("levels") or []
if controls.get("effort") and levels:
pretty = {"xhigh": "Extra high", "high": "High", "medium": "Medium", "low": "Low"}
opts += [(l, pretty.get(l, l.title())) for l in reversed(levels)]
if controls.get("thinking"):
opts.append((OFF, "Thinking off"))
return opts if len(opts) > 1 else []
def reasoning_kwargs(value, entry, controls):
"""chat_template_kwargs for a setting, or {} for "default"/anything unsupported."""
if not value or value == DEFAULT or not entry.get("reasoning"):
return {}
if value == OFF:
return {"enable_thinking": False} if controls.get("thinking") else {}
levels = (entry.get("effort") or {}).get("levels") or []
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,10 +49,6 @@ h1 span { color: var(--muted); font-weight: 500; }
.meta { color: var(--muted); font-size: 12.5px; } .meta { color: var(--muted); font-size: 12.5px; }
.grid { display: grid; gap: 14px; } .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); } .top { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); }
@media (max-width: 820px) { .top { grid-template-columns: 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; } .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px; min-width: 0; }
@ -67,15 +63,6 @@ button.small { font-size: 12px; padding: 4px 10px; }
} }
.loadline b { color: var(--warn); font-family: system-ui, sans-serif; margin-right: 6px; } .loadline b { color: var(--warn); font-family: system-ui, sans-serif; margin-right: 6px; }
.btns { display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap; } .btns { display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap; }
.effort { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); }
.effort .k { font-size: 11.5px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; }
.effort .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
.effort select {
background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 8px;
padding: 6px 10px; font: inherit; font-size: 13px; min-width: 150px;
}
.effort select:disabled { color: var(--muted); }
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
button { button {
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer; font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--border); background: var(--panel-2); color: var(--text); border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
@ -109,7 +96,9 @@ button.danger { color: var(--bad); }
.bar i { display: block; height: 100%; background: var(--accent); width: 0; transition: width .4s; } .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 { grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 14px; }
@media (max-width: 820px) { .charts { grid-template-columns: minmax(0, 1fr); } } .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); } }
.chart .head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px; } .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 span { font-size: 12px; color: var(--muted); }
.chart .head b { font-size: 13px; font-variant-numeric: tabular-nums; } .chart .head b { font-size: 13px; font-variant-numeric: tabular-nums; }
@ -127,17 +116,6 @@ button.danger { color: var(--bad); }
} }
.chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; } .chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; }
.runs { margin-top: 14px; }
.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; }
.runs th:first-child, .runs td:first-child { text-align: left; padding-left: 0; }
.runs th { color: var(--muted); font-weight: 600; border-bottom: 1px solid var(--border); font-size: 11.5px; }
.runs tbody tr + tr td { border-top: 1px solid color-mix(in srgb, var(--border) 55%, transparent); }
.runs td.none { color: var(--muted); }
.runs tr.aborted td:first-child::after { content: " cancelled"; color: var(--bad); font-size: 11px; }
.runs tfoot td { border-top: 1px solid var(--border); font-weight: 600; }
.runs .empty { color: var(--muted); font-size: 13px; padding: 6px 0 2px; }
details.logs { margin-top: 14px; } details.logs { margin-top: 14px; }
details.logs summary { cursor: pointer; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; list-style: none; } details.logs summary { cursor: pointer; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; list-style: none; }
details.logs summary::before { content: "▸ "; } details.logs summary::before { content: "▸ "; }
@ -179,15 +157,6 @@ pre {
<div class="repo" id="cur-repo"></div> <div class="repo" id="cur-repo"></div>
<div class="hwline" id="hwline"></div> <div class="hwline" id="hwline"></div>
<div class="loadline" id="loadline"><b id="load-title">Loading</b><span id="load-text"></span></div> <div class="loadline" id="loadline"><b id="load-title">Loading</b><span id="load-text"></span></div>
<div class="effort" id="effort" hidden>
<div class="k">Reasoning</div>
<div class="row">
<select id="effort-sel"></select>
<span class="meta" id="effort-state"></span>
</div>
<div class="s" id="effort-note"></div>
</div>
<div class="btns"> <div class="btns">
<button id="btn-restart">Restart</button> <button id="btn-restart">Restart</button>
<button id="btn-stop" class="danger">Stop</button> <button id="btn-stop" class="danger">Stop</button>
@ -201,13 +170,6 @@ pre {
</section> </section>
</div> </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="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">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> <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>
@ -220,40 +182,18 @@ 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 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>
<div class="grid charts"> <div class="grid charts four">
<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>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>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 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>
<div class="grid charts" id="gpu-charts"> <div class="grid charts">
<div class="panel chart"><div class="head"><span>GPU utilization %</span><b id="c-util-v"></b></div><svg id="c-util" 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>GPU utilization %</span><b id="c-util-v"></b></div><svg id="c-util" 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" id="p-temp"><div class="head"><span>GPU temperature °C</span><b id="c-temp-v"></b></div><svg id="c-temp" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-temp-max">0–100 °C</span><span>now</span></div></div> <div class="panel chart"><div class="head"><span>GPU temperature °C</span><b id="c-temp-v"></b></div><svg id="c-temp" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-temp-max">0–100 °C</span><span>now</span></div></div>
<div class="panel chart" id="p-power"><div class="head"><span>GPU power W</span><b id="c-power-v"></b></div><svg id="c-power" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-power-max"></span><span>now</span></div></div> <div class="panel chart"><div class="head"><span>GPU power W</span><b id="c-power-v"></b></div><svg id="c-power" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-power-max"></span><span>now</span></div></div>
<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>
<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="scroll">
<table>
<thead><tr>
<th>Finished</th><th>Duration</th><th>TTFT</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>
</table>
</div>
<div class="empty" id="runs-empty" hidden>No requests finished yet.</div>
</section>
<details class="panel logs" id="logs"> <details class="panel logs" id="logs">
<summary>Server log</summary> <summary>Server log</summary>
<pre id="log-text">…</pre> <pre id="log-text">…</pre>
@ -385,8 +325,6 @@ function render(s) {
const m = s.metrics || {}, g = s.gpu || {}; const m = s.metrics || {}, g = s.gpu || {};
const live = s.phase === "ready"; 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"); 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" : ""; $("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"); setV("t-prompt", live ? fmt.n(m.prompt_tps, 0) : "—", "tok/s");
@ -401,10 +339,6 @@ function render(s) {
$("t-req-s").textContent = live ? `${fmt.n(m.waiting)} waiting` + (m.preemptions ? ` · ${fmt.n(m.preemptions)} preempted` : "") : ""; $("t-req-s").textContent = live ? `${fmt.n(m.waiting)} waiting` + (m.preemptions ? ` · ${fmt.n(m.preemptions)} preempted` : "") : "";
setV("t-kv", live ? fmt.n(m.kv_pct, 1) : "—", "%"); setV("t-kv", live ? fmt.n(m.kv_pct, 1) : "—", "%");
$("b-kv").style.width = (live && m.kv_pct != null ? m.kv_pct : 0) + "%"; $("b-kv").style.width = (live && m.kv_pct != null ? m.kv_pct : 0) + "%";
if (m.kv_bytes != null && m.kv_budget_bytes) {
$("t-kv").title = `${(m.kv_bytes / 1e9).toFixed(2)} GB of ${(m.kv_budget_bytes / 1e9).toFixed(0)} GB`
+ (m.kv_seqs != null ? ` · ${m.kv_seqs} sequences` : "");
}
setV("t-util", fmt.pct(g.util), ""); setV("t-util", fmt.pct(g.util), "");
$("t-util-s").textContent = g.temp != null ? `${Math.round(g.temp)}°C · ${Math.round(g.power)} / ${Math.round(g.power_limit)} W` : ""; $("t-util-s").textContent = g.temp != null ? `${Math.round(g.temp)}°C · ${Math.round(g.power)} / ${Math.round(g.power_limit)} W` : "";
$("t-mem").innerHTML = g.mem_used != null ? `${(g.mem_used / 1024).toFixed(1)}<small>/ ${(g.mem_total / 1024).toFixed(0)} GiB</small>` : "—"; $("t-mem").innerHTML = g.mem_used != null ? `${(g.mem_used / 1024).toFixed(1)}<small>/ ${(g.mem_total / 1024).toFixed(0)} GiB</small>` : "—";
@ -416,128 +350,15 @@ function render(s) {
chartTimes = h.map((p) => p.t); 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-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-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-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) + "%"); 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. // Fixed scales so the shape means something: 0–100 °C, and 0 to the board power limit.
// Apple Silicon reports neither through any API that works without root (powermetrics chart("c-temp", h.map((p) => p.temp), "var(--c4)", 100, (v) => Math.round(v) + " °C");
// needs sudo), so hide the panels instead of drawing two charts that can never fill. $("c-temp-max").textContent = g.temp == null ? "not reported on this hardware" : "0–100 °C";
const hasTP = g.temp != null || g.power != null || h.some((p) => p.temp != null || p.power != null); const plim = g.power_limit || 600;
$("p-temp").hidden = !hasTP; $("c-power-max").textContent = g.power == null ? "not reported on this hardware" : `0–${Math.round(plim)} W`;
$("p-power").hidden = !hasTP; chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W");
$("p-nogpu").hidden = hasTP;
if (!hasTP) {
$("nogpu-why").textContent = s.kind === "apple"
? "macOS only exposes GPU temperature and power to root (powermetrics), so they aren't charted here."
: "not reported by this hardware";
} else {
chart("c-temp", h.map((p) => p.temp), "var(--c4)", 100, (v) => Math.round(v) + " °C");
$("c-temp-max").textContent = "0–100 °C";
const plim = g.power_limit || 600;
$("c-power-max").textContent = `0–${Math.round(plim)} W`;
chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W");
}
renderRuns(s);
renderEffort(s);
}
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: a model whose template
// has no switches has nothing to offer.
box.hidden = !opts.length && !r.why;
if (!opts.length) {
sel.innerHTML = "";
sel.disabled = true;
$("effort-state").textContent = "";
$("effort-note").textContent = r.why || "";
return;
}
if (effortBusy) return;
const want = opts.map((o) => o.value).join("|");
if (sel.dataset.sig !== want) {
sel.dataset.sig = want;
sel.innerHTML = "";
for (const o of opts) {
const el = document.createElement("option");
el.value = o.value;
el.textContent = o.label;
sel.append(el);
}
}
sel.value = r.value || "default";
sel.disabled = s.phase !== "ready";
$("effort-state").textContent = s.phase === "ready" ? "" : "available once the model is ready";
$("effort-note").textContent = "Applies to requests that don't set their own; takes effect "
+ "on the next request, with no reload.";
}
$("effort-sel").onchange = async (e) => {
const value = e.target.value;
effortBusy = true;
try {
await api("/api/reasoning", { method: "POST", body: JSON.stringify({ value }) });
const opt = e.target.selectedOptions[0];
toast(`Reasoning: ${opt ? opt.textContent : value}`);
} catch (err) {
toast("Couldn't change reasoning");
} finally {
effortBusy = false;
poll();
}
};
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;
body.textContent = "";
foot.textContent = "";
if (!runs.length) {
$("runs-sub").textContent = "";
return;
}
const clock = (t) => new Date(t * 1000).toLocaleTimeString(undefined, { hour12: false });
const cell = (tr, text, cls) => {
const td = document.createElement("td");
td.textContent = text;
if (cls) td.className = cls;
tr.append(td);
return td;
};
const dash = (v, f) => (v == null ? ["—", "none"] : [f(v), ""]);
for (const r of runs) {
const tr = document.createElement("tr");
if (r.aborted) tr.className = "aborted";
cell(tr, clock(r.t));
cell(tr, ...dash(r.dur, fmt.secs));
cell(tr, ...dash(r.ttft, fmt.secs));
cell(tr, ...dash(r.prompt, (v) => fmt.big(v)));
cell(tr, ...dash(r.prompt_tps, (v) => fmt.n(v, 0)));
cell(tr, ...dash(r.gen, (v) => fmt.big(v)));
cell(tr, ...dash(r.gen_tps, (v) => fmt.n(v, 1)));
cell(tr, ...dash(r.kv_peak_pct, (v) => fmt.n(v, 1) + "%"));
body.append(tr);
}
// Averages over the runs shown, so the row means the same thing as the table above it.
const avg = (k) => {
const xs = runs.map((r) => r[k]).filter((v) => v != null);
return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null;
};
const peak = Math.max(...runs.map((r) => r.kv_peak_pct ?? 0));
const tr = document.createElement("tr");
cell(tr, `${runs.length} shown`);
cell(tr, ...dash(avg("dur"), fmt.secs));
cell(tr, ...dash(avg("ttft"), fmt.secs));
cell(tr, ...dash(avg("prompt"), (v) => fmt.big(v)));
cell(tr, ...dash(avg("prompt_tps"), (v) => fmt.n(v, 0)));
cell(tr, ...dash(avg("gen"), (v) => fmt.big(v)));
cell(tr, ...dash(avg("gen_tps"), (v) => fmt.n(v, 1)));
cell(tr, ...dash(peak > 0 ? peak : null, (v) => fmt.n(v, 1) + "%"));
foot.append(tr);
$("runs-sub").textContent = "newest first · averages below · tok/s split at first token";
} }
const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples
@ -655,12 +476,6 @@ 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-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-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."); $("btn-restart").onclick = () => ctl("restart", "Restart the model server? It takes a few minutes to come back.");
async function loadLogs() { async function loadLogs() {

View file

@ -13,62 +13,16 @@ from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from .. import hfcache, hw, opencode, paths, plan, service from .. import hfcache, hw, paths, service
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2 SAMPLE_SECONDS = 2
HISTORY_POINTS = 300 # 10 minutes HISTORY_POINTS = 300 # 10 minutes
RUNS_SHOWN = 20 # completed requests in the run summary
# The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view. # The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view.
OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) ' OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) '
r'|- INFO - HTTP Request: ') r'|- INFO - HTTP Request: ')
PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]") PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]")
METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$") METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$")
# A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its
# ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the
# disconnect in one line), so collapse the block instead of letting it bury the log.
DASHES_RE = re.compile(r"^-{20,}\s*$")
EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request")
DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b")
MAX_TRACE_LINES = 80
def collapse_disconnects(lines):
"""Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other
traceback is left exactly as it is -- those are worth reading in full.
socketserver brackets each one with a row of dashes, which is what delimits a block
here; a block that never closes (the log was truncated, or is still being written)
is emitted unchanged."""
out, block = [], None
def flush(decide):
nonlocal block
if block is None:
return
if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block):
out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]")
else:
out.extend(block)
block = None
for l in lines:
bare = l.rstrip()
if block is None:
if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare):
block = [l]
else:
out.append(l)
continue
if DASHES_RE.match(bare):
block.append(l)
flush(True)
continue
block.append(l)
if len(block) > MAX_TRACE_LINES:
flush(False)
flush(False)
return out
def http_get(url, key=None, timeout=2): def http_get(url, key=None, timeout=2):
@ -82,18 +36,6 @@ def http_get(url, key=None, timeout=2):
return None, "" 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): def parse_vllm_metrics(text):
vals = {} vals = {}
for line in text.splitlines(): for line in text.splitlines():
@ -136,10 +78,6 @@ class Sampler:
self.action = None self.action = None
self._dl_cache = (0, {}) self._dl_cache = (0, {})
self.last_ttft = None # (time, seconds) of the latest sample with new first tokens self.last_ttft = None # (time, seconds) of the latest sample with new first tokens
self.baseline = None # counter values at the last stats reset (see reset_stats)
self.stats_since = None
self.runs = deque(maxlen=RUNS_SHOWN)
self._seen_runs = set()
def reload_cfg(self): def reload_cfg(self):
self.cfg = paths.load_config() or self.cfg self.cfg = paths.load_config() or self.cfg
@ -175,19 +113,15 @@ class Sampler:
served = [m["id"] for m in json.loads(body)["data"]] served = [m["id"] for m in json.loads(body)["data"]]
except (ValueError, KeyError): except (ValueError, KeyError):
pass 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": if cfg["backend"] == "vllm":
st, body = http_get(f"http://127.0.0.1:{cfg['api_port'] + 1}/metrics") st, body = http_get(base + "/metrics")
metrics = parse_vllm_metrics(body) if st == 200 else {} metrics = parse_vllm_metrics(body) if st == 200 else {}
metrics["recent"] = proxied.get("recent") or []
else: else:
metrics = proxied st, body = http_get(base + "/llmhost/metrics")
try:
metrics = json.loads(body) if st == 200 else {}
except ValueError:
metrics = {}
active = cfg.get("active") active = cfg.get("active")
if svc_state in ("inactive", "failed"): if svc_state in ("inactive", "failed"):
@ -212,7 +146,6 @@ class Sampler:
if ttft is not None: if ttft is not None:
self.last_ttft = (now, ttft) self.last_ttft = (now, ttft)
self.prev = (now, metrics) if metrics else None self.prev = (now, metrics) if metrics else None
shown = self.since_reset(metrics)
gpu = hw.live_stats(cfg["kind"]) gpu = hw.live_stats(cfg["kind"])
kv = metrics.get("kv") kv = metrics.get("kv")
@ -225,16 +158,7 @@ class Sampler:
} }
def ratio(a, b): def ratio(a, b):
return shown[a] / shown[b] if shown.get(b) else None return metrics[a] / metrics[b] if metrics.get(b) else None
def run_rates(r):
"""Split a run into its two phases: time to first token covers the prefill, the
rest is generation. Rates over the whole duration would blur the two together."""
dur, ttft = r.get("dur") or 0, r.get("ttft")
prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur
gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None
return gen_tps, prompt_tps
last_log = None last_log = None
if phase in ("loading", "failed"): if phase in ("loading", "failed"):
@ -243,30 +167,9 @@ class Sampler:
dl = self.downloaded() dl = self.downloaded()
models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])] models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])]
reasoning = self.reasoning_state(cfg, active)
with self.lock: with self.lock:
self.history.append(point) self.history.append(point)
# Peak KV per run is taken from the sampled history over the run's own window;
# the proxy can't do it, since it never sees KV usage (mlx_lm only logs it now and then).
for r in metrics.get("recent") or []:
key = (r.get("start"), r.get("end"))
if key in self._seen_runs or r.get("start") is None:
continue
self._seen_runs.add(key)
gen_tps, prompt_tps = run_rates(r)
self.runs.append({
"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
"gen_tps": gen_tps, "prompt_tps": prompt_tps,
"kv_peak_pct": run_kv_peak(self.history, r, now, point["kv"]),
"aborted": bool(r.get("aborted")),
})
if len(self._seen_runs) > 4 * RUNS_SHOWN:
# The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the
# oldest keys can't resurrect a run we already have.
self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | {
(q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])}
if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6: if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6:
self.action = None self.action = None
self.state = { self.state = {
@ -275,108 +178,21 @@ class Sampler:
"hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"), "hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"),
"active": active, "served_models": served, "models": models, "active": active, "served_models": served, "models": models,
"excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log, "excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log,
"reasoning": reasoning,
"action": self.action, "action": self.action,
"metrics": { "metrics": {
"running": shown.get("running"), "waiting": shown.get("waiting"), "running": metrics.get("running"), "waiting": metrics.get("waiting"),
"kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate, "kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate,
"gen_total": shown.get("gen_total"), "prompt_total": shown.get("prompt_total"), "gen_total": metrics.get("gen_total"), "prompt_total": metrics.get("prompt_total"),
"prefix_hit": ratio("prefix_hits", "prefix_queries"), "prefix_hit": ratio("prefix_hits", "prefix_queries"),
"spec_accept": ratio("spec_accepted", "spec_drafted"), "spec_accept": ratio("spec_accepted", "spec_drafted"),
"preemptions": shown.get("preemptions"), "preemptions": metrics.get("preemptions"),
"ttft_last": self.last_ttft[1] if self.last_ttft else None, "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_last_t": self.last_ttft[0] if self.last_ttft else None,
"ttft_avg": ratio("ttft_sum", "ttft_count"), "ttft_avg": ratio("ttft_sum", "ttft_count"),
"ttft_count": shown.get("ttft_count"), "ttft_count": metrics.get("ttft_count"),
"kv_bytes": shown.get("kv_bytes"),
"kv_seqs": shown.get("kv_seqs"),
"kv_budget_bytes": shown.get("kv_budget_bytes"),
"kv_peak_pct": self.kv_peak_pct(shown),
}, },
"runs": list(self.runs)[::-1],
"stats_since": self.stats_since,
} }
# Counters that run from the model server's start; a stats reset rebases these.
COUNTERS = ("gen_total", "prompt_total", "requests_total", "prefix_hits", "prefix_queries",
"spec_accepted", "spec_drafted", "preemptions", "ttft_sum", "ttft_count")
def since_reset(self, metrics):
"""metrics with the counters taken from the last reset rather than the server's
start. Rates are unaffected: they come from differences between samples."""
base = self.baseline
if not base:
return metrics
if any(metrics.get(k) is not None and base.get(k) is not None and metrics[k] < base[k]
for k in self.COUNTERS):
# The model server restarted since the reset, so its counters already start
# after it. (What came between the reset and the restart is lost.)
self.baseline = base = {}
out = dict(metrics)
for k in self.COUNTERS:
if out.get(k) is not None:
out[k] = out[k] - (base.get(k) or 0)
return out
def kv_peak_pct(self, shown):
"""Peak KV since the model started (MLX reports it); since a reset, the highest
sampled value instead -- the server's own peak can't be rebased."""
if self.stats_since is not None:
vals = [p["kv"] for p in self.history if p["kv"] is not None]
return max(vals) if vals else None
if shown.get("kv_peak_bytes") and shown.get("kv_budget_bytes"):
return shown["kv_peak_bytes"] / shown["kv_budget_bytes"] * 100
return None
def reset_stats(self):
"""Start the Statistics section over: empty the charts, count from now."""
with self.lock:
latest = self.prev[1] if self.prev else {}
self.baseline = {k: latest.get(k) for k in self.COUNTERS}
self.stats_since = time.time()
self.history.clear()
self.last_ttft = None
def clear_runs(self):
"""Empty the Requests table. Runs already seen stay seen, so they don't come back."""
with self.lock:
self.runs.clear()
def reasoning_state(self, cfg, active):
"""What the active model can be told about reasoning, and what it's set to. The
proxy in front of either backend applies it to each chat request."""
choice = next((m for m in cfg.get("models", []) if m["name"] == active), None)
if not choice:
return {"options": [], "value": plan.DEFAULT, "why": None}
entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None)
if not entry:
return {"options": [], "value": plan.DEFAULT, "why": None}
if not hfcache.repo_dir(choice["repo"]).exists():
return {"options": [], "value": plan.DEFAULT,
"why": "the model isn't downloaded yet, so its chat template can't be read"}
controls = hfcache.template_controls(choice["repo"])
opts = plan.reasoning_options(entry, choice, controls)
value = (cfg.get("reasoning") or {}).get(active) or plan.DEFAULT
if value not in [v for v, _ in opts]:
value = plan.DEFAULT
why = "" if opts else "this model's chat template exposes no reasoning controls"
return {"options": [{"value": v, "label": l} for v, l in opts], "value": value, "why": why}
def set_reasoning(self, value):
"""Takes effect on the next request -- no restart, so the model stays loaded."""
cfg = paths.load_config()
active = cfg.get("active")
allowed = [o["value"] for o in self.reasoning_state(cfg, active)["options"]]
if value not in allowed:
return False, allowed
cfg.setdefault("reasoning", {})[active] = value
paths.save_config(cfg)
self.cfg = cfg
with self.lock:
if self.state.get("reasoning"):
self.state["reasoning"]["value"] = value
return True, allowed
def snapshot(self): def snapshot(self):
with self.lock: with self.lock:
s = dict(self.state) s = dict(self.state)
@ -389,7 +205,6 @@ class Sampler:
cfg["active"] = model cfg["active"] = model
paths.save_config(cfg) paths.save_config(cfg)
self.cfg = cfg self.cfg = cfg
opencode.sync(cfg) # keep /models' "loaded" marker honest after a dashboard switch
fn = service.restart fn = service.restart
else: else:
fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind] fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind]
@ -441,7 +256,7 @@ def make_handler(sampler, key):
if self.authed(): if self.authed():
lines = [l for l in service.logs("model", 1500) lines = [l for l in service.logs("model", 1500)
if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)] if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)]
self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]}) self.send_json(200, {"lines": lines[-80:]})
else: else:
self.send_json(404, {"error": "not found"}) self.send_json(404, {"error": "not found"})
@ -460,18 +275,6 @@ def make_handler(sampler, key):
return self.send_json(400, {"error": f"unknown model {name!r}"}) return self.send_json(400, {"error": f"unknown model {name!r}"})
sampler.control("switch", name) sampler.control("switch", name)
return self.send_json(202, {"ok": True, "model": name}) return self.send_json(202, {"ok": True, "model": name})
if path == "/api/reasoning":
ok, allowed = sampler.set_reasoning(str(data.get("value", "")))
if not ok:
return self.send_json(400, {"error": "unsupported value for this model",
"allowed": allowed})
return self.send_json(200, {"ok": True, "value": data.get("value")})
if path == "/api/stats/reset":
sampler.reset_stats()
return self.send_json(200, {"ok": True})
if path == "/api/runs/clear":
sampler.clear_runs()
return self.send_json(200, {"ok": True})
if path in ("/api/stop", "/api/start", "/api/restart"): if path in ("/api/stop", "/api/start", "/api/restart"):
sampler.control(path.rsplit("/", 1)[1]) sampler.control(path.rsplit("/", 1)[1])
return self.send_json(202, {"ok": True}) return self.send_json(202, {"ok": True})

View file

@ -1,92 +0,0 @@
{
"version": 1,
"kind": "apple",
"backend": "mlx",
"hardware_name": "Apple M-series, 128 GB unified memory",
"budget_gib": 96.0,
"tp": 1,
"prefer": "balanced",
"api_port": 1134,
"web_port": 11340,
"max_jobs": 10,
"models": [
{
"name": "qwen3.8-27b",
"title": "Qwen3.8 27B",
"about": "Dense 27B, hybrid attention, strong general coding and tool use.",
"context": 262144,
"reasoning": true,
"format": "mlx-6bit",
"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit",
"weights_gib": 21.2,
"util": 1.0,
"est_context": 262144,
"mtp": false,
"free_gib": 71.34,
"prompt_cache_gib": 52.74
},
{
"name": "ornith-1.5-35b",
"title": "Ornith 1.5 35B A3B",
"about": "35B mixture-of-experts with 3B active: very fast.",
"context": 262144,
"reasoning": true,
"format": "mlx-6bit",
"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit",
"weights_gib": 26.3,
"util": 1.0,
"est_context": 262144,
"mtp": false,
"free_gib": 66.21,
"prompt_cache_gib": 60.91
},
{
"name": "qwen3-coder",
"title": "Qwen3 Coder 30B A3B",
"about": "Coding-tuned mixture-of-experts, no reasoning phase.",
"context": 262144,
"reasoning": false,
"format": "mlx-6bit",
"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit",
"weights_gib": 23.1,
"util": 1.0,
"est_context": 262144,
"mtp": false,
"free_gib": 69.44,
"prompt_cache_gib": 45.44
},
{
"name": "ornith-1.5-122b",
"title": "Ornith 1.5 122B",
"about": "Largest option; needs ~80 GB of GPU memory even at 4-bit.",
"context": 262144,
"reasoning": true,
"format": "mlx-4bit",
"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit",
"weights_gib": 64.8,
"util": 1.0,
"est_context": 262144,
"mtp": false,
"free_gib": 26.88,
"prompt_cache_gib": 20.28
},
{
"name": "ornith-1.5-9b",
"title": "Ornith 1.5 9B",
"about": "Small dense model for 16 GB Macs and 12-16 GB GPUs; noticeably weaker at multi-step agentic work.",
"context": 262144,
"reasoning": true,
"format": "mlx-6bit",
"repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit",
"weights_gib": 6.8,
"util": 1.0,
"est_context": 262144,
"mtp": false,
"free_gib": 86.07,
"prompt_cache_gib": 77.27
}
],
"excluded": [],
"active": "ornith-1.5-9b",
"mlx": {}
}

View file

@ -1,76 +0,0 @@
"""Shared bits for the suites: repo-relative imports, a sandbox, and a check() counter.
Each suite is a plain script: run it directly, or run them all with `python3 tests/run.py`.
Stdlib only, like the rest of llm-host.
Every suite sandboxes LLMHOST_HOME / LLMHOST_CONFIG / XDG_* before importing llmhost, so
nothing touches a real install. setup() asserts that, because a suite that forgot
LLMHOST_HOME once deleted a live install's data directory.
"""
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
FIXTURES = Path(__file__).resolve().parent / "fixtures"
def setup():
"""Point every path llmhost writes to at a fresh temp dir. Returns its root."""
root = tempfile.mkdtemp(prefix="llmhost-test-")
os.environ["LLMHOST_HOME"] = root + "/.local/share/llm-host"
os.environ["LLMHOST_CONFIG"] = root + "/.config/llm-host"
os.environ["XDG_CONFIG_HOME"] = root + "/.config"
os.environ["XDG_DATA_HOME"] = root + "/.local/share"
sys.path.insert(0, str(REPO))
return root
def guard(paths, root):
"""Move the paths no env var covers into the sandbox, then abort unless everything
llmhost could write or delete is inside it.
LLMHOST_HOME and LLMHOST_CONFIG redirect most of it, but BIN_DIR/SHIM come off
Path.home() with no override, so they are repointed here -- once, for every suite,
rather than per test. The assertion is the real safety net: a suite that forgot
LLMHOST_HOME once deleted a live install's data directory."""
paths.BIN_DIR = Path(root) / ".local/bin"
paths.SHIM = paths.BIN_DIR / "llmhost"
paths.LOG_DIR = Path(root) / "logs"
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "BIN_DIR", "SHIM", "LOG_DIR"):
value = str(getattr(paths, name))
if not value.startswith(root):
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")
def config():
"""The planned-models fixture: a real `llmhost setup` result, machine bits pinned."""
return json.loads((FIXTURES / "config.json").read_text())
class Checks:
def __init__(self):
self.failed = []
self.passed = 0
def __call__(self, label, cond, extra=""):
if cond:
self.passed += 1
print(" ok " + label)
else:
self.failed.append(label)
print(" FAIL " + label + ((" <- " + str(extra)) if extra else ""))
return bool(cond)
def section(self, title):
print("\n" + title)
def done(self, root=None):
if root:
shutil.rmtree(root, ignore_errors=True)
print("\n" + (f"ALL PASS ({self.passed} checks)" if not self.failed
else f"{len(self.failed)} FAILURES of {self.passed + len(self.failed)}: {self.failed}"))
sys.exit(1 if self.failed else 0)

View file

@ -1,45 +0,0 @@
#!/usr/bin/env python3
"""Run every suite in tests/ and summarise. Exits nonzero if any failed.
python3 tests/run.py all suites
python3 tests/run.py proxy just the ones whose name contains "proxy"
"""
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
def main(argv):
picks = argv[1:]
suites = sorted(p for p in HERE.glob("test_*.py")
if not picks or any(a in p.stem for a in picks))
if not suites:
print("no suites matched", picks)
return 1
width = max(len(p.stem) for p in suites)
results, total = [], 0
for p in suites:
r = subprocess.run([sys.executable, str(p)], capture_output=True, text=True)
tail = [l for l in r.stdout.splitlines() if l.strip()]
summary = tail[-1] if tail else "(no output)"
ok = r.returncode == 0
count = 0
for word in summary.replace("(", " ").replace(")", " ").split():
if word.isdigit():
count = int(word)
break
total += count if ok else 0
print(f" {p.stem:<{width}} {'PASS' if ok else 'FAIL'} {summary}")
if not ok:
print("\n".join(" " + l for l in r.stdout.splitlines() if "FAIL" in l))
if r.stderr.strip():
print(" stderr: " + r.stderr.strip().splitlines()[-1])
results.append(ok)
print(f"\n{sum(results)}/{len(results)} suites passed, {total} checks")
return 0 if all(results) else 1
if __name__ == "__main__":
sys.exit(main(sys.argv))

View file

@ -1,209 +0,0 @@
"""Dashboard tests: KV from mlx_lm's log line, per-run summaries, traceback collapsing."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
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 = 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",
b"2026-11-03 01:15:00,000 - INFO - - user: 3 sequences, 0.17 GB\n",
b"2026-11-03 01:16:00,000 - INFO - Prompt Cache: 9 sequences, 2.00 GB\n"]:
m = mlx.CACHE_RE.search(seg)
if m:
st.set_kv(int(m.group(1)), float(m.group(2)) * 1e9)
snap = st.snapshot()
check("latest size tracked", abs(snap["kv_bytes"] - 2.00e9) < 1, snap["kv_bytes"])
check("sequences tracked", snap["kv_seqs"] == 9, snap["kv_seqs"])
check("peak is the max seen, not the last", abs(snap["kv_peak_bytes"] - 4.24e9) < 1, snap["kv_peak_bytes"])
check("per-role lines ignored", snap["kv_seqs"] != 3, snap["kv_seqs"])
check("fraction against --prompt-cache-bytes", abs(snap["kv"] - 2.00e9 / (77.27 * 2**30)) < 1e-9, snap["kv"])
check("budget reported", snap["kv_budget_bytes"] == int(77.27 * 2**30))
print("\n2. no budget -> no fraction, but still a size")
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", proxy.Stats().snapshot()["kv"] is None)
print("\n3. run records survive the round trip")
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(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 {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")
class S(web.Sampler):
def __init__(self):
self.cfg = {"api_port": 1, "web_port": 2, "backend": "mlx", "kind": "apple", "models": [], "active": "m"}
import threading
from collections import deque
self.lock = threading.Lock(); self.history = deque(maxlen=web.HISTORY_POINTS)
self.prev = None; self.state = {}; self.action = None; self._dl_cache = (0, {})
self.last_ttft = None; self.runs = deque(maxlen=web.RUNS_SHOWN); self._seen_runs = set()
s = S()
# 10 s run: 2 s prefill for 7667 prompt tokens, 8 s generating 200 tokens
run = {"start": 100.0, "end": 110.0, "dur": 10.0, "gen": 200, "prompt": 7667, "ttft": 2.0}
for t, kv in ((99.0, 10.0), (101.0, 40.0), (105.0, 72.5), (109.0, 55.0), (111.0, 90.0)):
s.history.append({"t": t, "kv": kv, "gen": None, "prompt": None, "ttft": None,
"util": None, "temp": None, "power": None})
point = {"t": 111.0, "kv": 90.0}
gen_tps, prompt_tps = (None, None)
# exercise the real merge code by calling the block through a tiny shim
def merge(sampler, recent, point):
metrics = {"recent": recent}
def run_rates(r):
dur, ttft = r.get("dur") or 0, r.get("ttft")
p = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
w = dur - ttft if (ttft is not None and dur > ttft) else dur
g = (r["gen"] / w) if (w and r.get("gen")) else None
return g, p
for r in metrics["recent"]:
key = (r.get("start"), r.get("end"))
if key in sampler._seen_runs or r.get("start") is None: continue
sampler._seen_runs.add(key)
window = [q["kv"] for q in sampler.history
if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]]
g, p = run_rates(r)
sampler.runs.append({"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
"gen_tps": g, "prompt_tps": p,
"kv_peak_pct": max(window) if window else point["kv"],
"aborted": bool(r.get("aborted"))})
merge(s, [run], point)
r = s.runs[-1]
check("prompt tok/s = prompt / ttft", abs(r["prompt_tps"] - 7667 / 2.0) < 1e-6, r["prompt_tps"])
check("gen tok/s excludes the prefill", abs(r["gen_tps"] - 200 / 8.0) < 1e-6, r["gen_tps"])
check("peak KV from the run's own window", r["kv_peak_pct"] == 72.5, r["kv_peak_pct"])
check("points outside the window ignored", r["kv_peak_pct"] != 90.0)
merge(s, [run], point)
check("the same run isn't added twice", len(s.runs) == 1, len(s.runs))
print("\n5. degenerate runs don't divide by zero")
s2 = S()
merge(s2, [{"start": 1.0, "end": 1.0, "dur": 0.0, "gen": 0, "prompt": 0, "ttft": None}], {"t": 1, "kv": None})
r2 = s2.runs[-1]
check("no rates, no crash", r2["gen_tps"] is None and r2["prompt_tps"] is None, r2)
merge(s2, [{"start": 2.0, "end": 3.0, "dur": 1.0, "gen": 5, "prompt": 9, "ttft": 1.0}], {"t": 3, "kv": None})
check("ttft == dur -> gen rate falls back to duration", s2.runs[-1]["gen_tps"] == 5.0, s2.runs[-1])
check("no KV history -> current value", s2.runs[-1]["kv_peak_pct"] is None)
print("\n6. the broken-pipe traceback you saw collapses to one line")
REAL = """2026-11-03 00:39:30,482 - INFO - Prompt processing progress: 7667/7667
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 62589)
Traceback (most recent call last):
File "/x/socketserver.py", line 697, in process_request_thread
self.finish_request(request, client_address)
File "/x/mlx_lm/server.py", line 1657, in handle_completion
self.wfile.write(f"data: {json.dumps(resp)}\\n\\n".encode())
File "/x/socketserver.py", line 845, in write
self._sock.sendall(b)
BrokenPipeError: [Errno 32] Broken pipe
----------------------------------------
2026-11-03 00:39:31,000 - INFO - Prompt Cache: 10 sequences, 1.58 GB""".splitlines()
out = web.collapse_disconnects(REAL)
check("collapsed", len(out) < len(REAL), f"{len(REAL)} -> {len(out)}")
check("one summary line", sum("client disconnected mid-answer" in l for l in out) == 1, out)
check("no traceback text left", not any("BrokenPipeError" in l or "socketserver" in l for l in out), out)
check("surrounding log kept", out[0].endswith("7667/7667") and "Prompt Cache" in out[-1], out)
print("\n7. a real traceback is NOT hidden")
OTHER = """----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 1)
Traceback (most recent call last):
File "/x/y.py", line 1, in z
boom()
ValueError: something actually broke
----------------------------------------""".splitlines()
out2 = web.collapse_disconnects(OTHER)
check("kept verbatim", any("ValueError: something actually broke" in l for l in out2), out2)
check("nothing claimed to be a disconnect", not any("disconnected" in l for l in out2))
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)

View file

@ -1,326 +0,0 @@
"""opencode integration: provider naming, ownership, removal, the credential cache."""
import json, os, shutil, pathlib
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import opencode, paths, plan
harness.guard(paths, ROOT)
CFG = harness.config()
OC = opencode.config_file()
check = harness.Checks()
def reset(data=None):
shutil.rmtree(OC.parent, ignore_errors=True)
if data is not None:
OC.parent.mkdir(parents=True, exist_ok=True)
OC.write_text(json.dumps(data, indent=2))
def load():
return json.loads(OC.read_text())
def remote(host, prov=None):
prov = prov or opencode.remote_provider(host)
return prov, opencode.provider_block(CFG, host, opencode.remote_key_file(prov), host)
print("\n1. fresh install")
reset()
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("status added", st == "added", st)
check("id is llmhost", prov == "llmhost", prov)
check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"])
check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1")
check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"])
check("model set to the alias", d["model"] == "llmhost/default", d.get("model"))
mods = d["provider"]["llmhost"]["models"]
check("exactly one entry", list(mods) == ["default"], list(mods))
check("keyed by the API alias", list(mods) == [plan.SERVED_ALIAS])
check("label names the loaded model", mods["default"]["name"] == "Default model \u00b7 Ornith 1.5 9B (Local)", mods["default"]["name"])
check("limits come from the loaded model",
mods["default"]["limit"]["context"] == next(m["est_context"] for m in CFG["models"] if m["name"] == CFG["active"]),
mods["default"]["limit"])
check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"])
print("\n2. local + remote side by side")
rp, rb = remote("popos.local")
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("remote id is llmhost-popos", rp == "llmhost-popos", rp)
check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"])
check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"]))
check("remote label names no model (it would go stale)",
rb["models"]["default"]["name"] == "Default model (popos.local)", rb["models"]["default"]["name"])
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"]))
check("remote untouched", d["provider"][rp] == rb)
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
_, rb2 = remote("popos.local", prov="llmhost")
reset({"provider": {"llmhost": rb2}})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("did not reuse `llmhost`", prov == "llmhost-local", prov)
check("remote block intact", d["provider"]["llmhost"] == rb2)
check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1")
print("\n4. user renamed the local provider (gap 2)")
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/default"})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("recognised under new name", prov == "mymac", prov)
check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"]))
check("nothing to change -> unchanged", st == "unchanged", st)
# But a stale per-model default IS a change worth making.
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"})
st, path, prov, authcl = opencode.configure(CFG)
check("a stale default makes it an update", st == "updated", st)
check("and it is migrated", load()["model"] == "mymac/default", load().get("model"))
print("\n5. uninstall: remove local, keep remote, repoint model")
rp, rb = remote("popos.local")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"})
st, path, removed, new_model = opencode.remove(local=True)
d = load()
check("status removed", st == "removed", st)
check("removed only local", removed == ["llmhost"], removed)
check("remote survives", list(d["provider"]) == [rp], list(d["provider"]))
check("model repointed to the surviving provider's entry",
new_model == f"{rp}/{plan.SERVED_ALIAS}" and d["model"] == new_model, (new_model, d.get("model")))
# An older remote block, pasted before the single-entry change, still lists every model;
# the fallback takes its first in plan order rather than whichever name sorts first.
legacy = {**rb, "models": {m["name"]: {"name": m["name"]} for m in CFG["models"]}}
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: legacy}, "model": "llmhost/default"})
st, path, removed, new_model = opencode.remove(local=True)
check("legacy multi-model block falls back to its first",
new_model == f"{rp}/{CFG['models'][0]['name']}", new_model)
print("\n6. uninstall must NOT glob llmhost*")
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, removed, new_model = opencode.remove(local=True)
check("nothing matched", st == "none" and removed == [], (st, removed))
check("remote still there", list(load()["provider"]) == [rp])
print("\n7. retiring a remote server (gap 3)")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
d = load()
check("removed the remote", removed == [rp], removed)
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
st, path, removed, _ = opencode.remove(local=False, host="popos")
check("short hostname also matches", removed == [rp], removed)
print("\n8. --all drops the model key when nothing is left")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
st, path, removed, new_model = opencode.remove(local=False, every=True)
d = load()
check("both removed", sorted(removed) == ["llmhost", rp], removed)
check("model key dropped", "model" not in d and new_model is None, d)
check("provider key dropped", "provider" not in d, d)
print("\n9. foreign providers are never touched")
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (popos)",
"options": {"baseURL": "http://popos.local:1134/v1", "apiKey": "{file:~/.config/opencode/popos-vllm.key}"},
"models": {"x": {"name": "x"}}}
reset({"provider": {"popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "popos-vllm/x"})
st, path, removed, new_model = opencode.remove(local=True)
d = load()
check("only ours removed", removed == ["llmhost"], removed)
check("foreign intact", d["provider"]["popos-vllm"] == foreign)
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
st, path, removed, _ = opencode.remove(local=False, every=True)
check("--all skips foreign", removed == [], removed)
print("\n10. .jsonc with comments is left alone")
shutil.rmtree(OC.parent, ignore_errors=True)
OC.parent.mkdir(parents=True, exist_ok=True)
j = OC.parent / "opencode.jsonc"
orig = '{\n // mine\n "provider": {}\n}\n'
j.write_text(orig)
st, path, prov, authcl = opencode.configure(CFG)
check("configure reports has-comments", st == "has-comments", st)
check("file unchanged", j.read_text() == orig)
st, path, removed, _ = opencode.remove(local=True)
check("remove reports has-comments", st == "has-comments", st)
check("file still unchanged", j.read_text() == orig)
check("snippet has the new name", '"LLMHost (Local)"' in opencode.snippet(CFG))
print("\n11. unparsable JSON is left alone")
reset(); OC.parent.mkdir(parents=True, exist_ok=True); OC.write_text("{ broken")
st, path, prov, authcl = opencode.configure(CFG)
check("configure reports unparsable", st == "unparsable", st)
check("file unchanged", OC.read_text() == "{ broken")
print("\n12. missing/garbage blocks don't crash the fingerprint")
reset({"provider": {"a": None, "b": "nope", "c": {}, "d": {"options": {}}}})
check("no crash, nothing ours", opencode.local_ids(load()["provider"]) == [])
st, path, prov, authcl = opencode.configure(CFG)
check("still installs", prov == "llmhost" and st == "added", (prov, st))
print("\n13. --host must not take a foreign provider on the same host (regression)")
rp, rb = remote("popos.local")
reset({"provider": {rp: rb, "popos-vllm": foreign, "llmhost": opencode.local_block(CFG)},
"model": "popos-vllm/x"})
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
d = load()
check("removed only ours", removed == [rp], removed)
check("foreign on same host survives", "popos-vllm" in d["provider"])
check("local survives", "llmhost" in d["provider"])
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
print("\n14. a stale cached key is cleared on configure")
def put_auth(d, mode=0o600):
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "w") as fh: json.dump(d, fh)
return f
def get_auth():
return json.loads(opencode.auth_file().read_text())
reset()
af = put_auth({"llmhost": {"type": "api", "key": "sk-STALE"}, "anthropic": {"type": "oauth", "t": 1}})
st, path, prov, authcl = opencode.configure(CFG)
a = get_auth()
check("reported clearing the cache", authcl is True, authcl)
check("stale llmhost entry gone", "llmhost" not in a, a)
check("other providers' creds untouched", a.get("anthropic") == {"type": "oauth", "t": 1}, a)
check("file mode preserved (0600)", oct(af.stat().st_mode & 0o777) == "0o600", oct(af.stat().st_mode & 0o777))
print("\n15. nothing cached -> nothing reported, no file created")
reset(); opencode.auth_file().unlink(missing_ok=True)
st, path, prov, authcl = opencode.configure(CFG)
check("no clear reported", authcl is False, authcl)
check("no auth.json invented", not opencode.auth_file().exists())
reset(); put_auth({"other": {"type": "api", "key": "x"}})
st, path, prov, authcl = opencode.configure(CFG)
check("untouched when we have no entry", authcl is False and get_auth() == {"other": {"type": "api", "key": "x"}})
print("\n16. an unreadable auth store is left alone, not repaired")
reset()
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True); f.write_text("{ not json")
st, path, prov, authcl = opencode.configure(CFG)
check("no crash", st == "added", st)
check("left verbatim", f.read_text() == "{ not json")
check("reported nothing cleared", authcl is False, authcl)
print("\n17. remove() takes the cached key with the provider")
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-popos": remote("popos.local")[1]}})
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-popos": {"type": "api", "key": "sk-B"}})
st, path, removed, _ = opencode.remove(local=True)
a = get_auth()
check("local cred cleared", "llmhost" not in a, a)
check("remote cred kept", a.get("llmhost-popos") == {"type": "api", "key": "sk-B"}, a)
print("\n18. purge --keep-key keeps the API key through a purge")
from llmhost import cli
cli_shim = pathlib.Path(ROOT) / "bin/llmhost"
cli_shim.parent.mkdir(parents=True, exist_ok=True)
paths.SHIM = cli_shim # never touch the real launcher from a test
for name in ("DATA", "CONFIG_DIR", "KEY_FILE", "SHIM"):
val = str(getattr(paths, name))
if not val.startswith(ROOT):
sys.exit(f"ABORT: paths.{name} = {val} is outside the sandbox {ROOT}; "
"purge() would delete a real install")
def seed():
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
paths.DATA.mkdir(parents=True, exist_ok=True)
(paths.DATA / "venv-mlx").mkdir(exist_ok=True)
key = paths.api_key(create=True)
paths.save_config({"active": "x"})
cli_shim.write_text("#!/bin/sh\n")
return key
key = seed()
kept = cli.purge(keep_key=True)
check("reported the kept path", kept == paths.KEY_FILE, kept)
check("key file survives", paths.KEY_FILE.exists())
check("key value unchanged", paths.KEY_FILE.read_text().strip() == key.strip(), paths.KEY_FILE.read_text())
check("key mode is 0600", oct(paths.KEY_FILE.stat().st_mode & 0o777) == "0o600", oct(paths.KEY_FILE.stat().st_mode & 0o777))
check("config.json gone", not paths.CONFIG_FILE.exists())
check("data dir gone", not paths.DATA.exists())
check("launcher gone", not cli_shim.exists())
check("a reinstall would reuse it", paths.api_key(create=True).strip() == key.strip())
print("\n19. purge without --keep-key removes everything")
key2 = seed()
kept = cli.purge(keep_key=False)
check("reported nothing kept", kept is None, kept)
check("key file gone", not paths.KEY_FILE.exists())
check("config dir gone", not paths.CONFIG_DIR.exists())
check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip())
print("\n20. sync() refreshes an existing block after a switch")
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/default"})
switched = dict(CFG, active="qwen3-coder")
prov = opencode.sync(switched)
d = load()
mods = d["provider"]["llmhost"]["models"]
check("reported the provider", prov == "llmhost", prov)
check("still one entry, same id", list(mods) == ["default"], list(mods))
check("label follows the switch", "Qwen3 Coder 30B A3B" in mods["default"]["name"], mods["default"]["name"])
check("the client's saved default still resolves", d["model"] == "llmhost/default", d.get("model"))
check("reasoning dropped for a non-reasoning model", "reasoning" not in mods["default"], mods["default"])
check("idempotent", opencode.sync(switched) is None)
print("\n21. sync() never wires opencode up on its own")
reset()
check("no config file -> no-op", opencode.sync(CFG) is None)
check("still no config file", not opencode.config_file().exists())
reset({"provider": {"popos-vllm": foreign}, "model": "popos-vllm/x"})
check("no local block -> no-op", opencode.sync(CFG) is None)
check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign})
reset({"provider": {"mymac": opencode.local_block(CFG)}})
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
check.section("22. a default naming a specific model is migrated to the alias")
for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"),
("llmhost/ornith-1.5-9b", "llmhost/default"),
("llmhost/default", "llmhost/default"),
("popos-vllm/qwen3.8-27b", "popos-vllm/qwen3.8-27b"),
("llmhost-popos/qwen3.8-27b", "llmhost-popos/qwen3.8-27b")):
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model})
opencode.configure(CFG)
got = load().get("model")
check(f"{old_model} -> {expect}", got == expect, got)
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/qwen3-coder"})
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 <provider>/<an entry in the block>",
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)

View file

@ -1,196 +0,0 @@
"""Proxy tests: the model name a client asks for must be honoured or refused, never ignored."""
import json, threading, urllib.error, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
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 / vLLM) server received
auths = [] # the Authorization header each of them came with
check = harness.Checks()
class Inner(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a): pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
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"}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers(); self.wfile.write(body)
def serve(handler, port):
srv = ThreadingHTTPServer(("127.0.0.1", port), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
INNER, OUTER = 18231, 18232
serve(Inner, INNER)
stats = proxy.Stats()
serve(proxy.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
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:{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:
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, {}
print("\n1. the loaded model is accepted")
seen.clear()
code, body = post(SERVED)
check("200", code == 200, code)
check("answered", body.get("choices", [{}])[0].get("message", {}).get("content") == "pong", body)
check("forwarded as default_model (mlx_lm must not try to load by name)",
seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
print("\n2. the repo id is accepted as an alias")
check("200", post(REPO)[0] == 200)
print("\n3. case differences are accepted")
check("200", post(SERVED.upper())[0] == 200)
print("\n4. no model named -> the loaded one")
check("200 when absent", post(None)[0] == 200)
check("200 when empty", post("")[0] == 200)
check("200 when blank", post(" ")[0] == 200)
check.section("4b. the stable alias always means whatever is loaded")
from llmhost import plan
check("alias accepted", post(plan.SERVED_ALIAS)[0] == 200, post(plan.SERVED_ALIAS)[0])
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)
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")
check("404", code == 404, code)
err = body.get("error") or {}
check("code=model_not_found", err.get("code") == "model_not_found", err)
check("param=model", err.get("param") == "model", err)
check("names the model asked for", "qwen3.8-27b" in err.get("message", ""), err)
check("names the loaded model", SERVED in err.get("message", ""), err)
check("says how to load it", "llmhost switch" in err.get("message", ""), err)
seen.clear()
post("qwen3.8-27b")
check("never reached the model server", seen == [], seen)
print("\n6. unknown junk is refused too")
check("404", post("../etc/passwd")[0] == 404)
check("404", post("gpt-4")[0] == 404)
print("\n7. auth still comes first")
code, body = post("qwen3.8-27b", key="sk-wrong")
check("401, not 404 (key checked before the model)", code == 401, code)
print("\n8. /v1/models still advertises the served name")
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
headers={"Authorization": f"Bearer {KEY}"})
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)

View file

@ -1,91 +0,0 @@
"""Reasoning-effort tests: options must match what the template really accepts, and a
client's own chat_template_kwargs must always win over the server default."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths, plan
harness.guard(paths, ROOT)
check = harness.Checks()
BOTH = {"thinking": True, "effort": True}
THINK = {"thinking": True, "effort": False}
NONE = {"thinking": False, "effort": False}
QWEN = {"name": "qwen3.8-27b", "reasoning": True,
"effort": {"levels": ["low", "medium", "xhigh"], "default": "xhigh"}}
ORNITH = {"name": "ornith-1.5-9b", "reasoning": True}
CODER = {"name": "qwen3-coder", "reasoning": False}
print("\n1. options follow the template, not the catalog alone")
vals = lambda e, c: [v for v, _ in plan.reasoning_options(e, None, c)]
check("full set when the template reads both", vals(QWEN, BOTH) == ["default", "xhigh", "medium", "low", "off"], vals(QWEN, BOTH))
check("most effort first", vals(QWEN, BOTH)[1] == "xhigh", vals(QWEN, BOTH))
check("levels dropped if the template ignores them", vals(QWEN, THINK) == ["default", "off"], vals(QWEN, THINK))
check("nothing at all if it reads neither", vals(QWEN, NONE) == [], vals(QWEN, NONE))
check("thinking-only model gets on/off", vals(ORNITH, THINK) == ["default", "off"], vals(ORNITH, THINK))
check("no levels invented for it", "low" not in vals(ORNITH, BOTH), vals(ORNITH, BOTH))
check("non-reasoning model gets no control", vals(CODER, BOTH) == [], vals(CODER, BOTH))
check("a lone 'default' is not a choice", vals({"name": "x", "reasoning": True}, NONE) == [])
labels = dict(plan.reasoning_options(QWEN, None, BOTH))
check("xhigh reads as a word", labels["xhigh"] == "Extra high", labels)
print("\n2. kwargs are only ever what the template accepts")
kw = lambda v, e, c: plan.reasoning_kwargs(v, e, c)
check("default sends nothing", kw("default", QWEN, BOTH) == {})
check("None sends nothing", kw(None, QWEN, BOTH) == {})
check("off -> enable_thinking false", kw("off", QWEN, BOTH) == {"enable_thinking": False})
check("level -> reasoning_effort", kw("low", QWEN, BOTH) == {"reasoning_effort": "low"})
check("xhigh passes through", kw("xhigh", QWEN, BOTH) == {"reasoning_effort": "xhigh"})
check("a level the catalog doesn't list is refused", kw("high", QWEN, BOTH) == {}, kw("high", QWEN, BOTH))
check("...which is the value that would make the template raise", "high" not in QWEN["effort"]["levels"])
check("a level the template can't read is refused", kw("low", QWEN, THINK) == {}, kw("low", QWEN, THINK))
check("off refused when thinking isn't readable", kw("off", QWEN, {"thinking": False, "effort": True}) == {})
check("nothing for a non-reasoning model", kw("low", CODER, BOTH) == {})
check("garbage is ignored, not forwarded", kw("../etc", QWEN, BOTH) == {})
print("\n3. the real catalog entry matches the real template")
from llmhost import hfcache, paths
cat = {m["name"]: m for m in paths.load_catalog()["models"]}
q = cat["qwen3.8-27b"]
check("qwen3.8-27b declares levels", (q.get("effort") or {}).get("levels") == ["low", "medium", "xhigh"], q.get("effort"))
tmpl = hfcache.chat_template("lmstudio-community/Qwen3.8-27B-MLX-6bit")
if tmpl:
for lvl in q["effort"]["levels"]:
check(f"template accepts {lvl!r}", f"'{lvl}'" in tmpl or f'"{lvl}"' in tmpl)
check("template has no 'high' level", "'high'" not in tmpl.replace("'xhigh'", ""))
else:
print(" skip (template not on disk)")
check("no other catalog model claims levels",
[m for m in cat.values() if m.get("effort") and m["name"] != "qwen3.8-27b"] == [])
print("\n4. a client's own kwargs win over the server default")
def inject(server_kw, client_body):
"""The precedence rule from the proxy, which mirrors mlx_lm's own."""
if not server_kw:
return client_body.get("chat_template_kwargs")
mine = dict(server_kw)
theirs = client_body.get("chat_template_kwargs")
if isinstance(theirs, dict):
mine.update(theirs)
return mine
check("server default applied when client says nothing",
inject({"reasoning_effort": "low"}, {}) == {"reasoning_effort": "low"})
check("client overrides the same key",
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"reasoning_effort": "xhigh"}})
== {"reasoning_effort": "xhigh"})
check("client's other keys survive alongside",
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"enable_thinking": False}})
== {"reasoning_effort": "low", "enable_thinking": False})
check("no server default -> body untouched", inject({}, {}) is None)
check("no server default -> client kwargs preserved",
inject({}, {"chat_template_kwargs": {"enable_thinking": False}}) == {"enable_thinking": False})
check("a non-dict from the client isn't merged into",
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"})
check.done(ROOT)