diff --git a/README.md b/README.md index 16bae9e..270eabd 100644 --- a/README.md +++ b/README.md @@ -52,8 +52,9 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac | `llmhost key` | print the API key | | `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-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 uninstall [--purge] [--models]` | remove services and backends; asks before deleting downloaded models (`--models` deletes without asking) | +| `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 | The dashboard (`http://.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. @@ -62,14 +63,81 @@ 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 installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` -pointing at `http://localhost:/v1` and reading the key straight from llm-host's key file. Other -providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`. +pointing at `http://localhost:/v1` and reading the key straight from llm-host's key file. It shows up +in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs +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` (`--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. **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. Only one model is loaded at a time; pick the one the server is currently running. +that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (popos.local)` +— under the provider id `llmhost-`. + +### 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-` | `LLMHost ()` | copied to `~/.config/opencode/llmhost-.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: vLLM takes it as a second +`--served-model-name` (and still reports the real slug, being the first), and on a Mac the proxy accepts it as an +alias. The local entry is labelled with whatever is loaded — `Default model · Qwen3.8 27B (Local)` — and +`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. + +To serve a different model, switch the server: `llmhost switch ` or the dashboard. Clients don't choose. + +Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the +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. + +On Linux + NVIDIA there's no chooser: vLLM runs without a proxy in front, so nothing is in the +path to add the argument. Clients can still pass `chat_template_kwargs` themselves. ## How models are chosen @@ -102,6 +170,66 @@ 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). - `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` | the API refusing a model that isn't loaded, against a fake `mlx_lm` | +| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing | +| `tests/test_reasoning.py` | effort options matching the real chat templates | + +## Continuing on an NVIDIA box + +Everything in this branch was written and tested on Apple Silicon + MLX. The parts below are +either **unverified on vLLM** or deliberately not wired there, so start here when you check the +repo out on the Linux machine. `python3 tests/run.py` passes on either platform (the suites are +hermetic and don't need a GPU), so run that first to confirm nothing is broken. + +**Verify first — it can stop the server from starting:** + +- `--served-model-name default` (`plan.vllm_args`). vLLM documents multiple names ("the + server will respond to any of them", with the first reported back), and the CLI form is one + flag with several tokens. Not run against a real vLLM, though, so confirm `vllm serve` accepts + it and that `curl -H "Authorization: Bearer $(llmhost key)" .../v1/chat/completions -d + '{"model":"default",...}'` answers. Until that's confirmed, the `llmhost-/default` block + that `llmhost opencode-config` prints can't work from a client. +- `/v1/models` should still report the real slug, not `default`. If it reports `default`, the + dashboard's readiness check (`active in served`) will sit on "loading" forever. + +**Not wired on vLLM, by design — each needs a decision, not a bug fix:** + +- **Reasoning chooser.** The setting is injected per request by the MLX proxy, and llm-host runs + vLLM with nothing in front of it, so there's nowhere to inject. Either put a proxy on Linux too + (it would also bring the per-request table and the API-key handling into one place) or find a + vLLM flag for default chat-template kwargs. The dashboard hides the panel rather than offer a + control that does nothing. +- **Completed-requests table.** Same reason: the per-request timings come from the proxy. vLLM + exposes histograms on `/metrics` rather than per-request rows, so this would be a different + implementation, not a port. +- **`404 model_not_found` for a model that isn't loaded.** That's the proxy. On vLLM the two + served names both answer and anything else gets vLLM's own 404, which is the same outcome by a + different route — worth confirming the message is clear enough. + +**Should work, but has never run on this hardware:** + +- GPU temperature and power come from `nvidia-smi`, so the charts the dashboard hides on a Mac + should appear here. Check that the `hasTP` test in `index.html` doesn't hide them wrongly. +- KV cache on vLLM comes from `vllm:kv_cache_usage_perc` and predates this branch; the new + log-parsing path is MLX-only. +- `llmhost opencode-remove`, the opencode credential-cache clearing, and + `uninstall --purge --keep-key` are all platform-independent, but worth one smoke test each. + ## Files | Path | | @@ -118,6 +246,7 @@ On macOS the services are launchd agents, so they run while you're logged in. ## Limitations -- One model loaded at a time. +- One model loaded at a time. Asking the API for a different one returns + `404 model_not_found` naming the loaded model, rather than answering with it. - 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. diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index 44daf2e..f0c9ec8 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -3,23 +3,43 @@ mlx_lm.server has no API-key support and loads whatever model a request names, so it listens on localhost only and this module runs a small proxy on the public port that: - checks the API key (like vLLM's --api-key), - - 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, + - rejects a request for a model that isn't the loaded one (404 model_not_found), + then rewrites the request's "model" to the loaded one, and answers /v1/models with + the served name, so clients see the same API as on vLLM, - counts in-flight requests and generated tokens for the dashboard (/llmhost/metrics). """ import hmac import http.client import json import os +import re import shutil import signal import subprocess import sys import threading import time +from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from .. import paths +from .. import hfcache, paths, plan + +RECENT_RUNS = 50 # completed requests kept for the dashboard's summary + +_cfg_cache = {"mtime": None, "cfg": {}} + + +def live_cfg(): + """config.json, re-read when it changes. The reasoning setting is edited from the + dashboard while this process runs, and it must take effect without a restart -- + a restart would unload the model, which is the whole thing we're avoiding.""" + try: + mtime = paths.CONFIG_FILE.stat().st_mtime + except OSError: + return _cfg_cache["cfg"] + if mtime != _cfg_cache["mtime"]: + _cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config() + return _cfg_cache["cfg"] VENV = paths.DATA / "venv-mlx" PY = VENV / "bin/python" @@ -44,10 +64,16 @@ NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthentic FATAL = b"generation thread died" -def _pump_output(stream, on_fatal=None): +# mlx_lm logs the prompt cache's size periodically; it has no endpoint for it, so this +# 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 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"" out = sys.stdout.buffer while True: @@ -66,6 +92,10 @@ def _pump_output(stream, on_fatal=None): if on_fatal and FATAL in seg: on_fatal() 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: out.write(buf) out.flush() @@ -100,12 +130,30 @@ class Stats: self.ttft_sum = 0.0 # seconds from request received to first generated token, self.ttft_count = 0 # streamed requests only (non-streamed ones arrive all at once) self.ready = False # set once the model has actually answered (see _readiness_probe) + self.kv_bytes = None # prompt cache size, from mlx_lm's own log line + self.kv_seqs = None + self.kv_peak = None + self.kv_budget = None # --prompt-cache-bytes, so usage can be a fraction + self.recent = deque(maxlen=RECENT_RUNS) + + def set_kv(self, seqs, nbytes): + with self.lock: + self.kv_seqs, self.kv_bytes = seqs, nbytes + self.kv_peak = nbytes if self.kv_peak is None else max(self.kv_peak, nbytes) + + def add_run(self, run): + with self.lock: + self.recent.append(run) def snapshot(self): with self.lock: + kv = (self.kv_bytes / self.kv_budget) if (self.kv_bytes is not None and self.kv_budget) else None return {"running": self.running, "gen_total": self.gen_total, "prompt_total": self.prompt_total, "requests_total": self.requests_total, - "ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count} + "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): @@ -115,7 +163,11 @@ def _uncached(usage): return max(n - int(cached), 0) -def make_handler(inner_port, served_name, context, key, stats): +def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None): + # Names a client may call the loaded model: its llm-host name, its repo id, and the + # stable alias that means "whatever is loaded" (plan.SERVED_ALIAS). + accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)} + class Proxy(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" @@ -159,16 +211,52 @@ def make_handler(inner_port, served_name, context, key, stats): {"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]}) self._forward("GET", None) + def _model_ok(self, body): + """One model is loaded at a time, and mlx_lm answers with whatever it has + regardless of the name asked for -- so an unrecognised name would come back + as another model's output wearing it. Refuse it instead.""" + want = body.get("model") + if not isinstance(want, str) or not want.strip(): + return True # no preference stated: the loaded one it is + if want.strip().lower() in accepted: + return True + self._json(404, {"error": { + "message": f"model '{want}' is not loaded; this server is serving " + f"'{served_name}'. Load it with `llmhost switch {want}` " + f"(one model is loaded at a time), or ask for '{served_name}' " + f"-- or for '{plan.SERVED_ALIAS}', which always means whatever " + f"is loaded.", + "type": "invalid_request_error", "code": "model_not_found", "param": "model"}}) + return False + def do_POST(self): if not self._authed(): return self._t0 = time.monotonic() + self._wall0 = time.time() + self._gen = 0 # tokens generated for THIS request + self._ttft = None n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n else b"" strip_usage = False try: body = json.loads(raw or b"{}") if isinstance(body, dict): + if self.path.startswith("/v1/") and not self._model_ok(body): + return + # Server-side reasoning default. Only chat completions go through a + # chat template, and a key the client set itself always wins -- the + # same precedence mlx_lm applies to its own --chat-template-kwargs. + if reasoning and "chat/completions" in self.path: + kw = reasoning() + if kw: + mine = dict(kw) + theirs = body.get("chat_template_kwargs") + if isinstance(theirs, dict): + mine.update(theirs) + body["chat_template_kwargs"] = mine + # Force the preloaded model: mlx_lm would otherwise try to load a + # model matching the name it's given. body["model"] = "default_model" # Ask for the final usage chunk so prompt tokens can be counted, and # hide it again from clients that didn't ask for it. @@ -181,14 +269,29 @@ def make_handler(inner_port, served_name, context, key, stats): 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) + conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600) # noqa: F841 (closed in finally) headers = {"Content-Type": self.headers.get("Content-Type", "application/json")} if raw is not None: headers["Content-Length"] = str(len(raw)) @@ -227,20 +330,34 @@ def make_handler(inner_port, served_name, context, key, stats): 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 += int(u.get("completion_tokens") or 0) - stats.prompt_total += _uncached(u) + stats.gen_total += self._gen + stats.prompt_total += self._pp except (ValueError, AttributeError): pass except (BrokenPipeError, ConnectionResetError): - pass + # 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 @@ -279,10 +396,12 @@ def make_handler(inner_port, served_name, context, key, stats): delta = c.get("delta") or {} if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"): stats.gen_total += 1 # mlx streams one token per chunk + self._gen += 1 first_token = True if first_token and not self._first and getattr(self, "_t0", None) is not None: self._first = True - stats.ttft_sum += time.monotonic() - self._t0 + 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 @@ -311,10 +430,19 @@ def run_server(cfg, entry, choice, args): inner = port + 1 # Claim the public port first: if it's taken, fail before starting (and orphaning) a child. stats = Stats() + # The template is fixed for this process, so read its knobs once; the chosen level is + # read per request, since the dashboard can change it while we run. + controls = hfcache.template_controls(choice["repo"]) + + def reasoning(): + value = (live_cfg().get("reasoning") or {}).get(entry["name"]) + return plan.reasoning_kwargs(value, entry, controls) + try: srv = ThreadingHTTPServer(("0.0.0.0", port), make_handler(inner, entry["name"], choice.get("est_context", entry["context"]), - paths.api_key(), stats)) + paths.api_key(), stats, aliases=(choice.get("repo"),), + reasoning=reasoning)) except OSError as e: print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; " f"pick a free port with: llmhost setup --api-port ", flush=True) @@ -328,7 +456,8 @@ def run_server(cfg, entry, choice, args): print("llm-host: mlx_lm.server's generator crashed (often: out of GPU memory); restarting it", flush=True) child.terminate() - threading.Thread(target=_pump_output, args=(child.stdout, generator_died), daemon=True).start() + stats.kv_budget = int(choice["prompt_cache_gib"] * 2**30) if choice.get("prompt_cache_gib") else None + threading.Thread(target=_pump_output, args=(child.stdout, generator_died, stats), daemon=True).start() threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start() def stop(*_): diff --git a/llmhost/catalog.json b/llmhost/catalog.json index 71ad868..98cd58e 100644 --- a/llmhost/catalog.json +++ b/llmhost/catalog.json @@ -9,16 +9,52 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_coder", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "mtp_tokens": 3}, + "vllm": { + "tool_parser": "qwen3_coder", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "mtp_tokens": 3 + }, "mlx": {}, "variants": { - "fp8": {"repo": "Qwen/Qwen3.8-27B-FP8", "gb": 30.9, "mtp": true}, - "bf16": {"repo": "Qwen/Qwen3.8-27B", "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} + "fp8": { + "repo": "Qwen/Qwen3.8-27B-FP8", + "gb": 30.9, + "mtp": true + }, + "bf16": { + "repo": "Qwen/Qwen3.8-27B", + "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" } }, { @@ -29,16 +65,44 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "fp8": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", "gb": 39.4}, - "bf16": {"repo": "ornith-ai/Ornith-1.5-35B-A3B", "gb": 71.9}, - "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} + "fp8": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", + "gb": 39.4 + }, + "bf16": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B", + "gb": 71.9 + }, + "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 + } } }, { @@ -49,15 +113,36 @@ "context": 262144, "hybrid": false, "reasoning": false, - "vllm": {"tool_parser": "qwen3_coder", "kv_cache_dtype": "fp8"}, + "vllm": { + "tool_parser": "qwen3_coder", + "kv_cache_dtype": "fp8" + }, "mlx": {}, "variants": { - "fp8": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", "gb": 31.2}, - "bf16": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", "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} + "fp8": { + "repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", + "gb": 31.2 + }, + "bf16": { + "repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", + "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 + } } }, { @@ -68,15 +153,40 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "fp8": {"repo": "ornith-ai/Ornith-1.5-122B-FP8", "gb": 132.9}, - "bf16": {"repo": "ornith-ai/Ornith-1.5-122B", "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} + "fp8": { + "repo": "ornith-ai/Ornith-1.5-122B-FP8", + "gb": 132.9 + }, + "bf16": { + "repo": "ornith-ai/Ornith-1.5-122B", + "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 + } } }, { @@ -87,15 +197,40 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "bf16": {"repo": "ornith-ai/Ornith-1.5-9B", "gb": 19.3}, - "nvfp4": {"repo": "ornith-ai/Ornith-1.5-9B-NVFP4", "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} + "bf16": { + "repo": "ornith-ai/Ornith-1.5-9B", + "gb": 19.3 + }, + "nvfp4": { + "repo": "ornith-ai/Ornith-1.5-9B-NVFP4", + "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 + } } } ] diff --git a/llmhost/cli.py b/llmhost/cli.py index 34ea8e1..884b2a9 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -209,15 +209,23 @@ 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") return say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")") - status, path = opencode.configure(cfg) - if status == "has-comments": - say(f"\n{path} has comments, which an automatic edit would delete, so it was left as is.\n" - f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg)}") + status, path, prov, auth_cleared = opencode.configure(cfg) + if status in ("has-comments", "unparsable"): + why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON" + say(f"\n{path} {why}, so it was left as is.\n" + f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg, prov)}") return msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status] - say(f"\nopencode: {msg} the `{opencode.PROVIDER}` provider in {path} (http://localhost:{cfg['api_port']}/v1).") + label = f"{opencode.DISPLAY} ({opencode.LOCAL_LABEL})" + 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": - say(f"Start it with: opencode (pick a model with /models; this server answers as {opencode.PROVIDER}/{cfg['active']})") + say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{cfg['active']})") def cmd_opencode_setup(a): @@ -342,6 +350,8 @@ def cmd_switch(a): cfg["active"] = a.model paths.save_config(cfg) 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") @@ -459,11 +469,11 @@ def cmd_download(a): def cmd_opencode(a): cfg = _service_check() host = a.host or default_host() - prov = a.provider or f"llmhost-{host.split('.')[0]}" - keyfile = f"~/.config/opencode/{prov}.key" + prov = a.provider or opencode.remote_provider(host) + keyfile = opencode.remote_key_file(prov) snippet = { "$schema": "https://opencode.ai/config.json", - "provider": {prov: opencode.provider_block(cfg, host, keyfile, host.split(".")[0])}, + "provider": {prov: opencode.provider_block(cfg, host, keyfile, host)}, "model": f"{prov}/{cfg['active']}", } if a.json: @@ -480,7 +490,10 @@ On another machine running opencode: 2. Merge this into ~/.config/opencode/opencode.json: """) say(json.dumps(snippet, indent=2)) - say(f"\nOnly the active model answers at a time; switch with `llmhost switch ` or the dashboard.") + say(f""" +It shows up in opencode as "{opencode.DISPLAY} ({host})". Only the active model answers at a +time; switch with `llmhost switch ` or the dashboard. If this server goes away, remove +the block there with: llmhost opencode-remove --host {host}""") def cmd_update(a): @@ -510,6 +523,23 @@ def hf_cache_rm_cmd(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): # Read the catalog now: --purge deletes it along with the rest of llm-host. cached = cached_catalog_models() @@ -526,11 +556,23 @@ def cmd_uninstall(a): for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"): shutil.rmtree(paths.DATA / d, ignore_errors=True) 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: - shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True) - shutil.rmtree(paths.DATA, ignore_errors=True) - paths.SHIM.unlink(missing_ok=True) - say("Removed config, API key and llm-host itself.") + kept = purge(a.keep_key) + if kept is None: + say("Removed config, API key and llm-host itself.") + say("A reinstall mints a new API key, so clients elsewhere will need the new one\n" + "(`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: return total = sum(g for _, g in cached) @@ -554,6 +596,22 @@ def cmd_uninstall(a): + " ".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): cfg = _service_check() cat = paths.load_catalog() @@ -626,12 +684,19 @@ def main(argv=None): s.add_argument("--provider", help="opencode provider id") s.add_argument("--json", action="store_true", help="print only the JSON") 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.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend") s.set_defaults(fn=cmd_update) 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("--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) sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-web").set_defaults(fn=cmd_run_web) diff --git a/llmhost/hfcache.py b/llmhost/hfcache.py index bb92895..b6be77a 100644 --- a/llmhost/hfcache.py +++ b/llmhost/hfcache.py @@ -59,3 +59,36 @@ def download_gib(repo): except OSError: pass 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} diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 365f58d..96471c5 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -1,18 +1,33 @@ """opencode integration: install it if missing, and register llm-host as a provider. -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 -model list in sync with the current plan. Other providers and settings are left untouched. +Two shapes of provider, both created from here: + + local this machine's server, reached over localhost, reading llm-host's key file + directly. Provider id `llmhost`, display name "LLMHost (Local)". + remote another machine's server, reached by hostname with the key copied into + ~/.config/opencode/.key. Provider id `llmhost-`, + display name "LLMHost ()". 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 os import shutil import subprocess from pathlib import Path +from urllib.parse import urlsplit -from . import paths +from . import paths, plan PROVIDER = "llmhost" +DISPLAY = "LLMHost" +LOCAL_LABEL = "Local" +LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]") INSTALL_URL = "https://opencode.ai/install" @@ -43,22 +58,133 @@ def config_file(): return d / "opencode.json" -def provider_block(cfg, host, key_path, label): - models = {} - 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)}} - if m.get("reasoning"): - entry["reasoning"] = True - models[m["name"]] = entry +def auth_file(): + """opencode's credential store (XDG_DATA_HOME, not the config dir).""" + return Path(os.environ.get("XDG_DATA_HOME") or paths.HOME / ".local/share") / "opencode" / "auth.json" + + +def clear_auth(*provs): + """Drop opencode's cached API key for these providers. Returns the ids cleared. + + 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})" + + +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 + models = {plan.SERVED_ALIAS: entry} return { "npm": "@ai-sdk/openai-compatible", - "name": f"llm-host ({label})", - "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + key_path + "}"}, + "name": f"{DISPLAY} ({label})", + "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, "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): """Remove comments and trailing commas outside strings. Returns (clean_text, had_comments).""" out, i, n, had_comments = [], 0, len(text), False @@ -93,41 +219,171 @@ def _strip_jsonc(text): return "".join(out), had_comments -def configure(cfg): - """Add or refresh the llmhost provider. Returns (status, path); status is one of - added, updated, unchanged, or has-comments (file left alone because rewriting would drop them).""" - path = config_file() - if path.exists(): - text = path.read_text() +def _read(path): + """Returns (data, "") or (None, reason) when the file can't be rewritten safely.""" + if not path.exists(): + return {"$schema": "https://opencode.ai/config.json"}, "" + text = path.read_text() + try: + return json.loads(text), "" + except ValueError: + clean, had_comments = _strip_jsonc(text) + if had_comments: + return None, "has-comments" try: - data = json.loads(text) + return json.loads(clean), "" # only trailing commas; safe to normalize except ValueError: - 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"} + return None, "unparsable" - 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) - if path.exists(): - backup = path.with_name(path.name + ".before-llmhost") - if not backup.exists(): - shutil.copy2(path, backup) + if backup and path.exists(): + before = path.with_name(path.name + ".before-llmhost") + if not before.exists(): + shutil.copy2(path, before) tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(data, indent=2) + "\n") os.replace(tmp, path) - return ("updated" if existed else "added"), path -def snippet(cfg): - return json.dumps({"provider": {PROVIDER: provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")}}, indent=2) +def configure(cfg): + """Add or refresh this machine's provider. Returns (status, path, prov_id, auth_cleared); + 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) diff --git a/llmhost/plan.py b/llmhost/plan.py index d0e948e..3165b15 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -120,7 +120,7 @@ def catalog_entry(catalog, name): def vllm_args(entry, choice, port, tp): """Arguments after `vllm serve`.""" v = entry.get("vllm", {}) - args = [choice["repo"], "--served-model-name", entry["name"], + args = [choice["repo"], "--served-model-name", entry["name"], SERVED_ALIAS, "--host", "0.0.0.0", "--port", str(port), "--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native) "--gpu-memory-utilization", f"{choice['util']:.2f}", @@ -160,3 +160,47 @@ def mlx_args(entry, choice, port): args += ["--prompt-concurrency", "1", "--decode-concurrency", "4"] args += x.get("extra_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. vLLM takes it as a second --served-model-name and +# still reports the real slug, being the first; the MLX proxy accepts it as an alias. +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 {} diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 70f5bf5..52dab6e 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -63,6 +63,15 @@ h1 span { color: var(--muted); font-weight: 500; } } .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; } +.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 { 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); @@ -116,6 +125,20 @@ button.danger { color: var(--bad); } } .chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; } +.runs { margin-top: 14px; } +.runs .head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 10px; } +.runs .head h2 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; } +.runs .head .sub { color: var(--muted); font-size: 12px; } +.runs .scroll { overflow-x: auto; } +.runs table { width: 100%; border-collapse: collapse; font-size: 12.5px; font-variant-numeric: tabular-nums; } +.runs th, .runs td { padding: 5px 10px 5px 0; text-align: right; white-space: nowrap; } +.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 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: "▸ "; } @@ -157,6 +180,15 @@ pre {
Loading
+ +
@@ -188,12 +220,32 @@ pre {
Time to first token
10 min agonow
KV cache %
10 min agonow
-
+
GPU utilization %
10 min agonow
-
GPU temperature °C
10 min ago0–100 °Cnow
-
GPU power W
10 min agonow
+
GPU temperature °C
10 min ago0–100 °Cnow
+
GPU power W
10 min agonow
+
+
+
+

Completed requests

+ +
+
+ + + + + + + + +
FinishedDurationTTFTPromptPrompt tok/sGeneratedGen tok/sPeak KV
+
+ +
+
Server log
…
@@ -339,6 +391,10 @@ function render(s) { $("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) : "—", "%"); $("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), ""); $("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)}/ ${(g.mem_total / 1024).toFixed(0)} GiB` : "—"; @@ -354,11 +410,126 @@ function render(s) { chart("c-util", h.map((p) => p.util), "var(--c2)", 100, (v) => fmt.pct(v)); chart("c-kv", h.map((p) => p.kv), "var(--c3)", null, (v) => fmt.n(v, 1) + "%"); // Fixed scales so the shape means something: 0–100 °C, and 0 to the board power limit. - chart("c-temp", h.map((p) => p.temp), "var(--c4)", 100, (v) => Math.round(v) + " °C"); - $("c-temp-max").textContent = g.temp == null ? "not reported on this hardware" : "0–100 °C"; - const plim = g.power_limit || 600; - $("c-power-max").textContent = g.power == null ? "not reported on this hardware" : `0–${Math.round(plim)} W`; - chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W"); + // Apple Silicon reports neither through any API that works without root (powermetrics + // needs sudo), so hide the panels instead of drawing two charts that can never fill. + const hasTP = g.temp != null || g.power != null || h.some((p) => p.temp != null || p.power != null); + $("p-temp").hidden = !hasTP; + $("p-power").hidden = !hasTP; + $("p-nogpu").hidden = hasTP; + $("gpu-charts").classList.toggle("four", false); + if (!hasTP) { + $("nogpu-why").textContent = s.kind === "apple" + ? "macOS only exposes GPU temperature and power to root (powermetrics), so they aren't charted here." + : "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: on vLLM there's no proxy + // to inject the kwarg, and 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"); + $("runs-empty").hidden = runs.length > 0; + $("runs").hidden = s.backend !== "mlx" && runs.length === 0; + body.textContent = ""; + foot.textContent = ""; + if (!runs.length) { + $("runs-sub").textContent = s.backend === "mlx" ? "" : "per-request timings are only collected on MLX"; + 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 diff --git a/llmhost/web/server.py b/llmhost/web/server.py index db20b16..72724b3 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -13,16 +13,61 @@ from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from .. import hfcache, hw, paths, service +from .. import hfcache, hw, opencode, paths, plan, service HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 HISTORY_POINTS = 300 # 10 minutes +RUNS_SHOWN = 20 # completed requests in the run summary # The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view. OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) ' r'|- INFO - HTTP Request: ') PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]") -METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$") +# A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its +# ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the +# disconnect in one line), so collapse the block instead of letting it bury the log. +DASHES_RE = re.compile(r"^-{20,}\s*$") +EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request") +DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b") +MAX_TRACE_LINES = 80 + + +def collapse_disconnects(lines): + """Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other + traceback is left exactly as it is -- those are worth reading in full. + + socketserver brackets each one with a row of dashes, which is what delimits a block + here; a block that never closes (the log was truncated, or is still being written) + is emitted unchanged.""" + out, block = [], None + + def flush(decide): + nonlocal block + if block is None: + return + if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block): + out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]") + else: + out.extend(block) + block = None + + for l in lines: + bare = l.rstrip() + if block is None: + if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare): + block = [l] + else: + out.append(l) + continue + if DASHES_RE.match(bare): + block.append(l) + flush(True) + continue + block.append(l) + if len(block) > MAX_TRACE_LINES: + flush(False) + flush(False) + return out def http_get(url, key=None, timeout=2): @@ -78,6 +123,8 @@ class Sampler: self.action = None self._dl_cache = (0, {}) self.last_ttft = None # (time, seconds) of the latest sample with new first tokens + self.runs = deque(maxlen=RUNS_SHOWN) + self._seen_runs = set() def reload_cfg(self): self.cfg = paths.load_config() or self.cfg @@ -160,6 +207,15 @@ class Sampler: def ratio(a, b): 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 if phase in ("loading", "failed"): lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)] @@ -167,9 +223,32 @@ class Sampler: dl = self.downloaded() models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])] + reasoning = self.reasoning_state(cfg, active) with self.lock: self.history.append(point) + # Peak KV per run is taken from the sampled history over the run's own window; + # the proxy can't do it, since it only learns KV when mlx_lm happens to log it. + for r in metrics.get("recent") or []: + key = (r.get("start"), r.get("end")) + if key in self._seen_runs or r.get("start") is None: + continue + self._seen_runs.add(key) + window = [q["kv"] for q in self.history + if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]] + gen_tps, prompt_tps = run_rates(r) + self.runs.append({ + "t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), + "prompt": r.get("prompt"), "ttft": r.get("ttft"), + "gen_tps": gen_tps, "prompt_tps": prompt_tps, + "kv_peak_pct": max(window) if window else point["kv"], + "aborted": bool(r.get("aborted")), + }) + if len(self._seen_runs) > 4 * RUNS_SHOWN: + # The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the + # oldest keys can't resurrect a run we already have. + self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | { + (q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])} if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6: self.action = None self.state = { @@ -178,6 +257,7 @@ class Sampler: "hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"), "active": active, "served_models": served, "models": models, "excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log, + "reasoning": reasoning, "action": self.action, "metrics": { "running": metrics.get("running"), "waiting": metrics.get("waiting"), @@ -190,9 +270,51 @@ class Sampler: "ttft_last_t": self.last_ttft[0] if self.last_ttft else None, "ttft_avg": ratio("ttft_sum", "ttft_count"), "ttft_count": metrics.get("ttft_count"), + "kv_bytes": metrics.get("kv_bytes"), + "kv_seqs": metrics.get("kv_seqs"), + "kv_budget_bytes": metrics.get("kv_budget_bytes"), + "kv_peak_pct": (metrics["kv_peak_bytes"] / metrics["kv_budget_bytes"] * 100) + if metrics.get("kv_peak_bytes") and metrics.get("kv_budget_bytes") else None, }, + "runs": list(self.runs)[::-1], } + def reasoning_state(self, cfg, active): + """What the active model can be told about reasoning, and what it's set to. + Only MLX: on vLLM llm-host has no proxy in front, so nothing here could inject + the kwarg into a client's request.""" + choice = next((m for m in cfg.get("models", []) if m["name"] == active), None) + if not choice or cfg.get("backend") != "mlx": + return {"options": [], "value": plan.DEFAULT, "why": "" if choice else None} + entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None) + if not entry: + return {"options": [], "value": plan.DEFAULT, "why": None} + if not hfcache.repo_dir(choice["repo"]).exists(): + return {"options": [], "value": plan.DEFAULT, + "why": "the model isn't downloaded yet, so its chat template can't be read"} + controls = hfcache.template_controls(choice["repo"]) + opts = plan.reasoning_options(entry, choice, controls) + value = (cfg.get("reasoning") or {}).get(active) or plan.DEFAULT + if value not in [v for v, _ in opts]: + value = plan.DEFAULT + why = "" if opts else "this model's chat template exposes no reasoning controls" + return {"options": [{"value": v, "label": l} for v, l in opts], "value": value, "why": why} + + def set_reasoning(self, value): + """Takes effect on the next request -- no restart, so the model stays loaded.""" + cfg = paths.load_config() + active = cfg.get("active") + allowed = [o["value"] for o in self.reasoning_state(cfg, active)["options"]] + if value not in allowed: + return False, allowed + cfg.setdefault("reasoning", {})[active] = value + paths.save_config(cfg) + self.cfg = cfg + with self.lock: + if self.state.get("reasoning"): + self.state["reasoning"]["value"] = value + return True, allowed + def snapshot(self): with self.lock: s = dict(self.state) @@ -205,6 +327,7 @@ class Sampler: cfg["active"] = model paths.save_config(cfg) self.cfg = cfg + opencode.sync(cfg) # keep /models' "loaded" marker honest after a dashboard switch fn = service.restart else: fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind] @@ -256,7 +379,7 @@ def make_handler(sampler, key): if self.authed(): lines = [l for l in service.logs("model", 1500) if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)] - self.send_json(200, {"lines": lines[-80:]}) + self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]}) else: self.send_json(404, {"error": "not found"}) @@ -275,6 +398,12 @@ def make_handler(sampler, key): return self.send_json(400, {"error": f"unknown model {name!r}"}) sampler.control("switch", name) return self.send_json(202, {"ok": True, "model": name}) + if path == "/api/reasoning": + ok, allowed = sampler.set_reasoning(str(data.get("value", ""))) + if not ok: + return self.send_json(400, {"error": "unsupported value for this model", + "allowed": allowed}) + return self.send_json(200, {"ok": True, "value": data.get("value")}) if path in ("/api/stop", "/api/start", "/api/restart"): sampler.control(path.rsplit("/", 1)[1]) return self.send_json(202, {"ok": True}) diff --git a/tests/fixtures/config.json b/tests/fixtures/config.json new file mode 100644 index 0000000..d669e0c --- /dev/null +++ b/tests/fixtures/config.json @@ -0,0 +1,92 @@ +{ + "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": {} +} diff --git a/tests/harness.py b/tests/harness.py new file mode 100644 index 0000000..5875fcc --- /dev/null +++ b/tests/harness.py @@ -0,0 +1,76 @@ +"""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) diff --git a/tests/run.py b/tests/run.py new file mode 100755 index 0000000..51a7c11 --- /dev/null +++ b/tests/run.py @@ -0,0 +1,45 @@ +#!/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)) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py new file mode 100644 index 0000000..90d490f --- /dev/null +++ b/tests/test_dashboard.py @@ -0,0 +1,145 @@ +"""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 +from llmhost.web import server as web + +harness.guard(paths, ROOT) +check = harness.Checks() + +print("\n1. KV is picked out of mlx_lm's log line") +st = mlx.Stats() +st.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 = mlx.Stats(); st2.set_kv(4, 1.5e9) +check("kv is None", st2.snapshot()["kv"] is None) +check("kv_bytes still there", st2.snapshot()["kv_bytes"] == 1.5e9) +check("fresh Stats reports nothing", mlx.Stats().snapshot()["kv"] is None) + +print("\n3. run records survive the round trip") +st3 = mlx.Stats() +st3.add_run({"start": 100.0, "end": 110.0, "dur": 10.0, "gen": 200, "prompt": 7667, + "ttft": 2.0, "aborted": False}) +check("recent carries the run", len(st3.snapshot()["recent"]) == 1) +for i in range(mlx.RECENT_RUNS + 10): + st3.add_run({"start": float(i), "end": float(i) + 1, "dur": 1.0, "gen": 1, "prompt": 1, + "ttft": 0.1, "aborted": False}) +check(f"bounded to {mlx.RECENT_RUNS}", len(st3.snapshot()["recent"]) == mlx.RECENT_RUNS, + 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([]) == []) + +check.done(ROOT) diff --git a/tests/test_opencode.py b/tests/test_opencode.py new file mode 100644 index 0000000..30ecc5b --- /dev/null +++ b/tests/test_opencode.py @@ -0,0 +1,299 @@ +"""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.done(ROOT) diff --git a/tests/test_proxy.py b/tests/test_proxy.py new file mode 100644 index 0000000..678751b --- /dev/null +++ b/tests/test_proxy.py @@ -0,0 +1,125 @@ +"""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 mlx + +harness.guard(paths, ROOT) + +SERVED = "ornith-1.5-9b" +REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit" +KEY = "sk-test-key" +seen = [] # bodies the inner (fake mlx_lm) server received +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) + 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 = mlx.Stats() +serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER) + + +def post(model, key=KEY, path="/v1/chat/completions"): + body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4} + if model is not None: + body["model"] = model + req = urllib.request.Request(f"http://127.0.0.1:{OUTER}{path}", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", + "Authorization": f"Bearer {key}"}, method="POST") + try: + with urllib.request.urlopen(req, timeout=20) as r: + return r.status, json.loads(r.read() or b"{}") + 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) +check("vLLM is told to serve it as a second name", + plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[1:4] + == ["--served-model-name", "m", plan.SERVED_ALIAS], + plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[:5]) + +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.done(ROOT) diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py new file mode 100644 index 0000000..6e17ddd --- /dev/null +++ b/tests/test_reasoning.py @@ -0,0 +1,91 @@ +"""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)