Refuse a request for a model that isn't loaded; show the slug in /models
The MLX proxy rewrote every request's "model" to the preloaded one, so asking for a model the server wasn't running returned another model's output wearing the requested name -- silently. The rewrite itself has to stay (mlx_lm would otherwise try to load a model matching the name), so validate first: a name that is neither the served name nor its repo id gets 404 model_not_found, naming what is loaded and how to switch. An unstated name still means "the loaded one", and the key is still checked before the model. opencode's /models hid the same trap twice over. Label models `<title> · <slug> (<where>)` so the list is searchable by the id used everywhere else -- titles alone had dropped the slug -- and mark the loaded one `(Local, loaded)`, refreshed by both switch paths (CLI and dashboard) through a new opencode.sync(), which only ever refreshes a block that is already there. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
8c6615dbb4
commit
2c0818ca2b
5 changed files with 78 additions and 11 deletions
|
|
@ -85,6 +85,12 @@ 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-<shorthost>` | `LLMHost (<host>)` | copied to `~/.config/opencode/llmhost-<shorthost>.key` |
|
||||
|
||||
Models are listed as `<title> · <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.
|
||||
|
||||
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
|
||||
|
|
@ -160,6 +166,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.
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@
|
|||
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
|
||||
|
|
@ -115,7 +116,10 @@ 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=()):
|
||||
# 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)}
|
||||
|
||||
class Proxy(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
|
|
@ -159,6 +163,22 @@ 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}'.",
|
||||
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
|
||||
return False
|
||||
|
||||
def do_POST(self):
|
||||
if not self._authed():
|
||||
return
|
||||
|
|
@ -169,6 +189,10 @@ def make_handler(inner_port, served_name, context, key, stats):
|
|||
try:
|
||||
body = json.loads(raw or b"{}")
|
||||
if isinstance(body, dict):
|
||||
if self.path.startswith("/v1/") and not self._model_ok(body):
|
||||
return
|
||||
# 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.
|
||||
|
|
@ -314,7 +338,7 @@ def run_server(cfg, entry, choice, args):
|
|||
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"),)))
|
||||
except OSError as e:
|
||||
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
|
||||
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
|
||||
|
|
|
|||
|
|
@ -350,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")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -113,12 +113,20 @@ def key_ref(key_path):
|
|||
return "{file:" + str(key_path) + "}"
|
||||
|
||||
|
||||
def provider_block(cfg, host, key_path, label):
|
||||
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 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 -- but show the
|
||||
# catalog's title, which is what reads well in opencode's /models list.
|
||||
entry = {"name": f"{m.get('title') or m['name']} ({label})", "tool_call": True,
|
||||
# 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
|
||||
|
|
@ -132,7 +140,9 @@ def provider_block(cfg, host, key_path, label):
|
|||
|
||||
|
||||
def local_block(cfg):
|
||||
return provider_block(cfg, "localhost", str(paths.KEY_FILE), LOCAL_LABEL)
|
||||
# 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):
|
||||
|
|
@ -333,5 +343,28 @@ def remove(prov_ids=None, local=True, host=None, every=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)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ 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, service
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SAMPLE_SECONDS = 2
|
||||
|
|
@ -205,6 +205,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]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue