From 9af7f1e545b6bda6b752613ee1b3b2b82a35055d Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 02:26:34 -0800 Subject: [PATCH] opencode: offer one model, not a menu where four of five fail Only one model is loaded at a time, so listing every model that fits gave a picker with one working entry and four that now answer 404 -- and the entry that worked changed id on every `llmhost switch`, invalidating any client's saved default. Replace the list with a single entry, `default`, which is a name the API itself answers to: vLLM takes it as a second --served-model-name and still reports the real slug, being first in the list; the MLX proxy accepts it as an alias. So `llmhost/default` survives a switch. The local entry is labelled with whatever is loaded, refreshed by both switch paths; a remote block is pasted once and never refreshed, so it names no model rather than make a claim that goes stale. Existing configs point at a specific model, which this provider no longer has and opencode would reject, so configure() and sync() migrate `/` to `/default`. Other providers' defaults are untouched, and an older remote block that still lists many models keeps working, including as the fallback when the local provider is removed. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 18 +++++++---- llmhost/backends/mlx.py | 9 ++++-- llmhost/opencode.py | 53 ++++++++++++++++++++---------- llmhost/plan.py | 10 +++++- tests/test_opencode.py | 72 ++++++++++++++++++++++++++++------------- tests/test_proxy.py | 12 +++++++ 6 files changed, 124 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 0179441..718449f 100644 --- a/README.md +++ b/README.md @@ -72,8 +72,7 @@ A config with comments (`.jsonc`) is never rewritten, since that would drop them **On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (popos.local)` -— under the provider id `llmhost-`. Only one model is loaded at a time; pick the one the server is -currently running. +— under the provider id `llmhost-`. ### One opencode, several servers @@ -85,11 +84,16 @@ of remote ones at once, each named after the machine it reaches: | local | `llmhost` | `LLMHost (Local)` | read straight from `~/.config/llm-host/api_key` | | remote | `llmhost-` | `LLMHost ()` | copied to `~/.config/opencode/llmhost-.key` | -Models are listed as ` · <slug> (<where>)` — `Qwen3.8 27B · qwen3.8-27b (Local)` — so the picker is -searchable by the slug, which is the id used everywhere else (`--model llmhost/<slug>`, `llmhost switch <slug>`). -Since only one model is loaded at a time, the local provider marks the loaded one `(Local, loaded)` and -`llmhost switch` (and the dashboard) refresh that marker. Picking one of the others is not a silent mistake: -the API answers `404 model_not_found` naming what is actually loaded. +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 <name>` or the dashboard. Clients don't choose. Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index 8f96c5c..f0c9ec8 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -164,8 +164,9 @@ def _uncached(usage): 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 and its repo id. - accepted = {served_name.lower(), *(a.lower() for a in aliases if a)} + # 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" @@ -222,7 +223,9 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso 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"(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 diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 5edf7d3..96471c5 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -22,7 +22,7 @@ import subprocess from pathlib import Path from urllib.parse import urlsplit -from . import paths +from . import paths, plan PROVIDER = "llmhost" DISPLAY = "LLMHost" @@ -113,24 +113,28 @@ def key_ref(key_path): return "{file:" + str(key_path) + "}" -def model_label(m, label, loaded=False): - """What opencode shows in /models: the catalog title to read, then the slug, which is - the id used everywhere else (`--model llmhost/<slug>`, `llmhost switch <slug>`) and so - the thing worth being able to search for.""" - where = f"{label}, loaded" if loaded else label - return f"{m.get('title') or m['name']} \u00b7 {m['name']} ({where})" +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): - models = {} - for m in cfg["models"]: - # Key by the slug -- that's the model id the API answers to. - entry = {"name": model_label(m, label, mark_loaded and m["name"] == cfg.get("active")), - "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 + # 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"{DISPLAY} ({label})", @@ -270,7 +274,9 @@ def configure(cfg): existed = prov in providers providers[prov] = local_block(cfg) if "model" not in data: - data["model"] = f"{prov}/{cfg['active']}" + 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: @@ -280,6 +286,18 @@ def configure(cfg): 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. @@ -360,6 +378,7 @@ def sync(cfg): 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) diff --git a/llmhost/plan.py b/llmhost/plan.py index 6e633a6..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}", @@ -162,6 +162,14 @@ def mlx_args(entry, choice, port): 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 diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 0f918de..30ecc5b 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -7,7 +7,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import harness ROOT = harness.setup() -from llmhost import opencode, paths +from llmhost import opencode, paths, plan harness.guard(paths, ROOT) CFG = harness.config() @@ -36,15 +36,15 @@ 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", d["model"] == "llmhost/ornith-1.5-9b", d.get("model")) +check("model set to the alias", d["model"] == "llmhost/default", d.get("model")) mods = d["provider"]["llmhost"]["models"] -check("model keyed by slug", "qwen3.8-27b" in mods, list(mods)) -check("label = title + slug", mods["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (Local)", mods["qwen3.8-27b"]["name"]) -check("active model marked loaded", mods[CFG["active"]]["name"].endswith("(Local, loaded)"), mods[CFG["active"]]["name"]) -check("only the active one is marked", - sum(v["name"].endswith(", loaded)") for v in mods.values()) == 1, - [v["name"] for v in mods.values()]) -check("slug searchable for every model", all(k in v["name"] for k, v in mods.items())) +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") @@ -53,9 +53,9 @@ 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 model label", rb["models"]["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (popos.local)", rb["models"]["qwen3.8-27b"]["name"]) -check("remote block is NOT marked loaded", not any(", loaded)" in v["name"] for v in rb["models"].values()), - [v["name"] for v in rb["models"].values()]) +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"]) @@ -70,24 +70,35 @@ 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/ornith-1.5-9b"}) +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("status unchanged", st == "unchanged", st) +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/ornith-1.5-9b"}) +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"])) -first = CFG["models"][0]["name"] -check("model repointed to remote's first (plan-order) model", - new_model == f"{rp}/{first}" and d["model"] == new_model, (new_model, d.get("model"))) +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"}) @@ -249,13 +260,16 @@ 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/" + CFG["active"]}) +reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/default"}) switched = dict(CFG, active="qwen3-coder") prov = opencode.sync(switched) -mods = load()["provider"]["llmhost"]["models"] +d = load() +mods = d["provider"]["llmhost"]["models"] check("reported the provider", prov == "llmhost", prov) -check("new model marked loaded", mods["qwen3-coder"]["name"].endswith("(Local, loaded)"), mods["qwen3-coder"]["name"]) -check("old one unmarked", not mods[CFG["active"]]["name"].endswith(", loaded)"), mods[CFG["active"]]["name"]) +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") @@ -268,4 +282,18 @@ 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 index 2c5a547..678751b 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -82,6 +82,18 @@ 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)