Compare commits

..

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

10 changed files with 150 additions and 162 deletions

View file

@ -95,13 +95,13 @@ alias, and `/v1/models` reports the real slug. The local entry is labelled with
`llmhost switch`, the dashboard and `llmhost update` keep that label current. A config that still points at a `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. specific model (`llmhost/qwen3.8-27b`) is migrated to `llmhost/default` the next time llm-host writes the block.
opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, so the block carries opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, and a level the model's
`variants` that switch all three off. The effort level is set on the dashboard, next to the model it applies template doesn't define makes every request fail. So the block carries `variants` that hide the levels the
to, and the proxy drops whatever a client sends — a chooser in the client would be a menu that silently does loaded model lacks and add the ones it has (Qwen3.8 27B: no `high`, plus `xhigh`). A pasted remote block can't
nothing, listing levels the loaded model's template may not even define. follow a later switch, so the proxy also maps a level the model lacks to the nearest one it has (`high` →
`xhigh`); a stale menu entry still works.
Neither the model nor its reasoning setting is the client's to choose: both change on the dashboard (or with To serve a different model, switch the server: `llmhost switch <name>` or the dashboard. Clients don't choose.
`llmhost switch <name>`), because one model is loaded at a time and one setting applies to it.
Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the 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 provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is
@ -140,16 +140,12 @@ Ornith 1.5 9B takes only `enable_thinking`. So the dashboard builds the chooser
model's own template, with the level names from `catalog.json` (`"effort": {"levels": [...]}`) — 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. a level the template doesn't know is never offered or sent.
The dashboard is the only place it is set. The proxy puts the setting on every chat completion The setting is a default for requests that don't ask for anything: the proxy adds it to chat
and takes the client's own out first — both a top-level `reasoning_effort` and `enable_thinking` completions, and a `chat_template_kwargs` key the client sets itself always wins. Changing it
or `reasoning_effort` inside `chat_template_kwargs`. Template kwargs llm-host has no opinion takes effect on the next request with no reload, so the model stays in memory.
about are passed through untouched. Changing the setting takes effect on the next request with no
reload, so the model stays in memory.
Clients are ignored here rather than obeyed because one model is loaded at a time under one This works the same on vLLM and MLX. A client's own top-level `reasoning_effort` also wins over
setting, and because a client's menu is generic: opencode offers `high`, which Qwen3.8's template the dashboard's level, and one the model lacks is mapped to the nearest level it has.
raises on, and the user would see every request fail with nothing on their screen to explain it.
This works the same on vLLM and MLX.
## How models are chosen ## How models are chosen
@ -197,9 +193,9 @@ python3 tests/test_opencode.py # or run one directly
| | | | | |
|---|---| |---|---|
| `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache | | `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache |
| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server | | `tests/test_proxy.py` | model names, effort mapping, upstream key, streamed-run counting, against a fake server |
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing | | `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update | | `tests/test_reasoning.py` | effort options matching the real chat templates |
## Continuing on an NVIDIA box ## Continuing on an NVIDIA box
@ -253,8 +249,5 @@ On macOS the services are launchd agents, so they run while you're logged in.
- One model loaded at a time. Asking the API for a different one returns - 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. `404 model_not_found` naming the loaded model, rather than answering with it.
- Reasoning effort is set on the dashboard, not by the client. A request's own
`reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's
setting applied instead.
- AMD (ROCm), Intel and CPU-only machines aren't supported yet. - AMD (ROCm), Intel and CPU-only machines aren't supported yet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet. - The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet.

View file

@ -15,7 +15,7 @@ import sys
import threading import threading
import time import time
from .. import hfcache, paths from .. import hfcache, paths, plan
from . import proxy from . import proxy
VENV = paths.DATA / "venv-mlx" VENV = paths.DATA / "venv-mlx"
@ -104,7 +104,8 @@ def run_server(cfg, entry, choice, args):
controls = hfcache.template_controls(choice["repo"]) controls = hfcache.template_controls(choice["repo"])
srv = proxy.listen(port, proxy.make_handler( srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats, inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls))) aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
effort_levels=plan.effort_levels(entry, controls)))
proxy.kill_stale(inner, VENV, "mlx_lm") proxy.kill_stale(inner, VENV, "mlx_lm")
exe = str(VENV / "bin/mlx_lm.server") exe = str(VENV / "bin/mlx_lm.server")

View file

@ -6,8 +6,8 @@ and, so that clients see the same API on either backend:
- rejects a request for a model that isn't the loaded one (404 model_not_found), and - rejects a request for a model that isn't the loaded one (404 model_not_found), and
rewrites the request's "model" to the name the server knows it by; /v1/models answers rewrites the request's "model" to the name the server knows it by; /v1/models answers
with the served name, with the served name,
- applies the dashboard's reasoning setting to chat requests, dropping any the client - applies the dashboard's reasoning setting to chat requests, and maps an effort level
sent: the model and its reasoning setting are both the dashboard's to choose, the model doesn't have (a client's generic "high", say) to the nearest one it does,
- counts in-flight requests and tokens and records each finished request for the - counts in-flight requests and tokens and records each finished request for the
dashboard (/llmhost/metrics, localhost only). dashboard (/llmhost/metrics, localhost only).
""" """
@ -73,10 +73,11 @@ def _uncached(usage):
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None, def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None,
upstream_model="default_model", upstream_key=None): upstream_model="default_model", upstream_key=None, effort_levels=()):
"""upstream_model: what the inner server calls the loaded model ("default_model" makes """upstream_model: what the inner server calls the loaded model ("default_model" makes
mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent
on to an inner server that checks keys itself (vLLM).""" on to an inner server that checks keys itself (vLLM). effort_levels: the levels this
model's template accepts; an unknown one from a client is mapped to the nearest."""
# Names a client may call the loaded model: its llm-host name, its repo id, and the # 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). # 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)} accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
@ -142,23 +143,16 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}}) "type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
return False return False
def _set_reasoning(self, body): def _fit_effort(self, holder, k):
"""Put the dashboard's reasoning setting on the request, and drop whatever the """Map holder[k], a client's effort level, onto one this model accepts. Clients
client asked for. The setting belongs to the dashboard for the same reason the offer a generic menu (opencode: low/medium/high), and a level the template
model does: one model is loaded at a time, under one setting, and a client's doesn't define makes it raise -- every request then fails until the user finds
generic menu (opencode offers low/medium/high) lists levels this template may the setting. The nearest level is what they meant."""
not even define -- one of those would make it raise, failing every request from v = holder.get(k)
a client whose user can't see why. The client's other template kwargs, which if effort_levels and isinstance(v, str) and v not in effort_levels:
llm-host has no opinion about, are left alone.""" fit = plan.nearest_effort(v, effort_levels)
body.pop("reasoning_effort", None) # the OpenAI-style top-level field if fit:
theirs = body.get("chat_template_kwargs") holder[k] = fit
kw = {k: v for k, v in theirs.items() if k not in plan.REASONING_KEYS} \
if isinstance(theirs, dict) else {}
kw.update(reasoning() if reasoning else {})
if kw:
body["chat_template_kwargs"] = kw
else:
body.pop("chat_template_kwargs", None)
def do_POST(self): def do_POST(self):
if not self._authed(): if not self._authed():
@ -175,10 +169,22 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso
if isinstance(body, dict): if isinstance(body, dict):
if self.path.startswith("/v1/") and not self._model_ok(body): if self.path.startswith("/v1/") and not self._model_ok(body):
return return
# Only chat completions go through a chat template, so only they can
# carry a reasoning setting.
if "chat/completions" in self.path: if "chat/completions" in self.path:
self._set_reasoning(body) theirs = body.get("chat_template_kwargs")
# Server-side reasoning default. Only chat completions go through a
# chat template, and a setting the client made itself always wins --
# the same precedence mlx_lm applies to its own --chat-template-kwargs.
kw = reasoning() if reasoning else {}
if kw:
mine = dict(kw)
if "reasoning_effort" in body: # the OpenAI-style top-level field
mine.pop("reasoning_effort", None)
if isinstance(theirs, dict):
mine.update(theirs)
body["chat_template_kwargs"] = theirs = mine
self._fit_effort(body, "reasoning_effort")
if isinstance(theirs, dict):
self._fit_effort(theirs, "reasoning_effort")
# Name the loaded model the way the inner server knows it (mlx_lm would # Name the loaded model the way the inner server knows it (mlx_lm would
# otherwise try to load a model matching the name it's given). # otherwise try to load a model matching the name it's given).
body["model"] = upstream_model body["model"] = upstream_model

View file

@ -164,7 +164,7 @@ def run_server(cfg, entry, choice, args):
"""Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args). """Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args).
vLLM keeps its own API key, so the inner port isn't open to anyone else on the box; vLLM keeps its own API key, so the inner port isn't open to anyone else on the box;
the proxy checks the client's key and sends ours on.""" the proxy checks the client's key and sends ours on."""
from .. import hfcache from .. import hfcache, plan
from . import proxy from . import proxy
port = cfg["api_port"] port = cfg["api_port"]
inner = port + 1 inner = port + 1
@ -175,7 +175,8 @@ def run_server(cfg, entry, choice, args):
srv = proxy.listen(port, proxy.make_handler( srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats, inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls), aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
upstream_model=entry["name"], upstream_key=key)) upstream_model=entry["name"], upstream_key=key,
effort_levels=plan.effort_levels(entry, controls)))
proxy.kill_stale(inner, VENV, "vllm") proxy.kill_stale(inner, VENV, "vllm")
exe = str(VENV / "bin/vllm") exe = str(VENV / "bin/vllm")
# vLLM's output goes straight to ours (the service log); nothing in it needs reading. # vLLM's output goes straight to ours (the service log); nothing in it needs reading.

View file

@ -111,15 +111,6 @@ def cmd_plan(a):
say("\nNothing fits. " + (p.get("reason") or "")) say("\nNothing fits. " + (p.get("reason") or ""))
def carried_settings(old, names):
"""Settings setup must not reset. The plan is setup's to rebuild, but the reasoning
setting belongs to the dashboard, which writes it into the same file -- without this an
`llmhost update` would quietly put every model back to "Model default". Models that no
longer fit lose their setting along with their plan."""
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
return {"reasoning": kept} if kept else {}
def cmd_setup(a): def cmd_setup(a):
info = hw.detect() info = hw.detect()
cat = paths.load_catalog() cat = paths.load_catalog()
@ -178,7 +169,6 @@ def cmd_setup(a):
"models": p["models"], "excluded": p["excluded"], "active": active, "models": p["models"], "excluded": p["excluded"], "active": active,
p["backend"]: {**old.get(p["backend"], {}), **backend_info}, p["backend"]: {**old.get(p["backend"], {}), **backend_info},
} }
cfg.update(carried_settings(old, names))
paths.save_config(cfg) paths.save_config(cfg)
key = paths.api_key(create=True) key = paths.api_key(create=True)
@ -361,7 +351,7 @@ def cmd_switch(a):
paths.save_config(cfg) paths.save_config(cfg)
service.restart("model") service.restart("model")
if opencode.sync(cfg): if opencode.sync(cfg):
say(f"opencode's LLMHost (Local) provider now names {a.model} as the default model.") say(f"Updated opencode's model list; {a.model} is the one marked loaded.")
say(f"Switched to {a.model}. Watch it load with: llmhost watch") say(f"Switched to {a.model}. Watch it load with: llmhost watch")

View file

@ -22,7 +22,7 @@ import subprocess
from pathlib import Path from pathlib import Path
from urllib.parse import urlsplit from urllib.parse import urlsplit
from . import paths, plan from . import hfcache, paths, plan
PROVIDER = "llmhost" PROVIDER = "llmhost"
DISPLAY = "LLMHost" DISPLAY = "LLMHost"
@ -127,16 +127,28 @@ def model_label(active, label, name_it):
# A model's template defines its own set, and one it lacks makes the template raise, so # A model's template defines its own set, and one it lacks makes the template raise, so
# the block hides those and adds the model's own. (The proxy also maps a stray level to # the block hides those and adds the model's own. (The proxy also maps a stray level to
# the nearest real one, so a pasted block that predates a switch still works.) # the nearest real one, so a pasted block that predates a switch still works.)
# The reasoning levels opencode offers of its own accord for a model marked `reasoning`.
OPENCODE_EFFORTS = ("low", "medium", "high") OPENCODE_EFFORTS = ("low", "medium", "high")
def effort_variants(): def _effort_levels(choice):
"""opencode `variants` that switch its reasoning menu off. The effort level is set on """The active model's effort levels: from its chat template once downloaded (what the
llm-host's dashboard and the proxy drops whatever a client asks for, so a chooser here proxy itself goes by), from the catalog before that."""
would be a menu that silently does nothing -- and whose levels this model's template try:
may not even define. One model, one setting, one place to change it.""" entry = plan.catalog_entry(paths.load_catalog(), choice["name"])
return {level: {"disabled": True} for level in OPENCODE_EFFORTS} except (KeyError, OSError, ValueError):
return ()
if not entry.get("reasoning"):
return ()
if choice.get("repo") and hfcache.repo_dir(choice["repo"]).exists():
return plan.effort_levels(entry, hfcache.template_controls(choice["repo"]))
return tuple((entry.get("effort") or {}).get("levels") or ())
def effort_variants(levels):
"""opencode `variants` for a model accepting `levels`."""
v = {l: {"disabled": True} for l in OPENCODE_EFFORTS if l not in levels}
v.update({l: {"reasoningEffort": l} for l in levels if l not in OPENCODE_EFFORTS})
return v
def provider_block(cfg, host, key_path, label, mark_loaded=False): def provider_block(cfg, host, key_path, label, mark_loaded=False):
@ -149,10 +161,10 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False):
entry = {"name": model_label(active, label, mark_loaded), "tool_call": True, entry = {"name": model_label(active, label, mark_loaded), "tool_call": True,
"limit": {"context": ctx, "output": min(65536, ctx // 2)}} "limit": {"context": ctx, "output": min(65536, ctx // 2)}}
if (active or {}).get("reasoning"): if (active or {}).get("reasoning"):
# `reasoning` so opencode renders the thinking blocks; `variants` so it doesn't
# offer to set the effort itself.
entry["reasoning"] = True entry["reasoning"] = True
entry["variants"] = effort_variants() variants = effort_variants(_effort_levels(active))
if variants:
entry["variants"] = variants
models = {plan.SERVED_ALIAS: entry} models = {plan.SERVED_ALIAS: entry}
return { return {
"npm": "@ai-sdk/openai-compatible", "npm": "@ai-sdk/openai-compatible",
@ -381,8 +393,8 @@ def remove(prov_ids=None, local=True, host=None, every=False):
def sync(cfg): def sync(cfg):
"""Refresh an existing local provider block -- after a model switch, so the entry's """Refresh an existing local provider block -- after a model switch, so the "loaded"
name and limits keep up with what's loaded. Never adds one: if opencode isn't wired up here, 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.""" switching a model is no reason to wire it. Returns the provider id, or None."""
path = config_file() path = config_file()
if not path.exists(): if not path.exists():

View file

@ -200,11 +200,6 @@ def reasoning_options(entry, choice, controls):
return opts if len(opts) > 1 else [] return opts if len(opts) > 1 else []
# The chat-template knobs this server drives. A client's own values for these are dropped
# on the way through the proxy: the setting is the dashboard's, not the client's.
REASONING_KEYS = ("enable_thinking", "reasoning_effort")
def reasoning_kwargs(value, entry, controls): def reasoning_kwargs(value, entry, controls):
"""chat_template_kwargs for a setting, or {} for "default"/anything unsupported.""" """chat_template_kwargs for a setting, or {} for "default"/anything unsupported."""
if not value or value == DEFAULT or not entry.get("reasoning"): if not value or value == DEFAULT or not entry.get("reasoning"):
@ -216,3 +211,25 @@ def reasoning_kwargs(value, entry, controls):
return {"reasoning_effort": value} return {"reasoning_effort": value}
return {} return {}
# Effort levels in order, for mapping a level a model lacks onto the nearest it has.
EFFORT_SCALE = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
def effort_levels(entry, controls):
"""The effort levels this model's template accepts, or () if it takes none."""
levels = (entry.get("effort") or {}).get("levels") or []
return tuple(levels) if entry.get("reasoning") and controls.get("effort") else ()
def nearest_effort(value, levels):
"""The level in `levels` closest to `value` on EFFORT_SCALE; on a tie, the higher one
(asking for "high" between medium and xhigh means wanting more, not less). None when
either is off the scale."""
if value not in EFFORT_SCALE:
return None
want = EFFORT_SCALE.index(value)
known = [l for l in levels if l in EFFORT_SCALE]
if not known:
return None
return min(known, key=lambda l: (abs(EFFORT_SCALE.index(l) - want), -EFFORT_SCALE.index(l)))

View file

@ -309,22 +309,18 @@ check("model is <provider>/<an entry in the block>",
snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"], snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"],
(snip["model"], list(block["models"]))) (snip["model"], list(block["models"])))
check.section("24. the block never offers a reasoning chooser of its own") check.section("24. the block offers only the effort levels the loaded model accepts")
check("opencode's whole menu is switched off", check("qwen3.8: hide high, add xhigh",
opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")}, opencode.effort_variants(("low", "medium", "xhigh")) == {"high": {"disabled": True},
opencode.effort_variants()) "xhigh": {"reasoningEffort": "xhigh"}},
opencode.effort_variants(("low", "medium", "xhigh")))
check("no levels: hide opencode's whole menu",
opencode.effort_variants(()) == {l: {"disabled": True} for l in ("low", "medium", "high")})
q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local")
ent = q["models"]["default"] ent = q["models"]["default"]
check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent) check("qwen3.8 block (not downloaded: catalog levels)",
check("but every effort level is disabled", ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent)
ent.get("variants") == {l: {"disabled": True} for l in ("low", "medium", "high")}, ent)
check("no variant carries a reasoningEffort to send",
not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"])
check("the model levels from the catalog are not offered either",
not ({"xhigh"} & set(ent["variants"])), ent["variants"])
nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local") nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local")
check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"]) check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"])
check("one entry only, named for the alias, so the client can't pick a model either",
list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"]))
check.done(ROOT) check.done(ROOT)

View file

@ -147,6 +147,7 @@ vstats = proxy.Stats()
vstats.ready = True vstats.ready = True
serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",), serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",),
upstream_model="qwen3.8-27b", upstream_key="sk-inner", upstream_model="qwen3.8-27b", upstream_key="sk-inner",
effort_levels=("low", "medium", "xhigh"),
reasoning=lambda: {"reasoning_effort": "low"}), VOUTER) reasoning=lambda: {"reasoning_effort": "low"}), VOUTER)
seen.clear(); auths.clear() seen.clear(); auths.clear()
check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200) check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200)
@ -154,53 +155,31 @@ check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27
check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1]) check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1])
check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404) check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404)
check.section("10. the reasoning setting is the dashboard's; a client can't set it") check.section("10. effort levels the model lacks are mapped to the nearest it has")
for asked, sent in (("high", "xhigh"), ("medium", "medium"), ("xhigh", "xhigh"),
("minimal", "low"), ("max", "xhigh")):
seen.clear()
post(None, port=VOUTER, reasoning_effort=asked)
check(f"top-level {asked} -> {sent}", seen[-1].get("reasoning_effort") == sent, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "high"})
check("inside chat_template_kwargs too", seen[-1]["chat_template_kwargs"].get("reasoning_effort") == "xhigh",
seen[-1].get("chat_template_kwargs"))
seen.clear()
post(None, port=VOUTER, reasoning_effort="bogus")
check("an unknown word is left for the server to reject", seen[-1].get("reasoning_effort") == "bogus", seen[-1])
seen.clear() seen.clear()
post(None, port=VOUTER) post(None, port=VOUTER)
check("dashboard setting applied when the client asks for nothing", check("dashboard setting applied when the client sets none",
seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1])
seen.clear() seen.clear()
post(None, port=VOUTER, reasoning_effort="xhigh") post(None, port=VOUTER, reasoning_effort="xhigh")
check("a client's top-level reasoning_effort never reaches the model", check("a client's own top-level level wins over the dashboard's",
"reasoning_effort" not in seen[-1], seen[-1]) "reasoning_effort" not in (seen[-1].get("chat_template_kwargs") or {})
check("...and the dashboard's setting is what goes instead", and seen[-1].get("reasoning_effort") == "xhigh", seen[-1])
seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) check("mapping only where a model has levels",
seen.clear() [plan.nearest_effort("high", ()), plan.nearest_effort("high", ("low", "high"))] == [None, "high"])
post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "xhigh"}) check("a tie goes to the higher level", plan.nearest_effort("high", ("medium", "xhigh")) == "xhigh")
check("nor one inside chat_template_kwargs",
seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False})
check("a client can't turn thinking off either",
"enable_thinking" not in seen[-1]["chat_template_kwargs"], seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False, "custom_var": 7})
check("template kwargs llm-host has no opinion about are left alone",
seen[-1]["chat_template_kwargs"] == {"custom_var": 7, "reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs="not a dict")
check("junk in chat_template_kwargs is replaced, not merged into",
seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, path="/v1/completions", reasoning_effort="xhigh")
check("a non-chat request is left as it came (no template, no setting)",
seen[-1].get("reasoning_effort") == "xhigh" and "chat_template_kwargs" not in seen[-1], seen[-1])
check.section("10b. with nothing set on the dashboard, the client's setting is still dropped")
NOUTER = 18234
nstats = proxy.Stats()
nstats.ready = True
serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, nstats,
upstream_model="qwen3.8-27b", reasoning=lambda: {}), NOUTER)
seen.clear()
post(None, port=NOUTER, reasoning_effort="xhigh", chat_template_kwargs={"enable_thinking": False})
check("both forms dropped", "reasoning_effort" not in seen[-1], seen[-1])
check("and no empty kwargs left behind for the template to read",
"chat_template_kwargs" not in seen[-1], seen[-1])
seen.clear()
post(None, port=NOUTER, chat_template_kwargs={"custom_var": 7})
check("an unrelated kwarg still survives on its own",
seen[-1]["chat_template_kwargs"] == {"custom_var": 7}, seen[-1])
check.section("11. a streamed run is counted from its usage chunk, and recorded") check.section("11. a streamed run is counted from its usage chunk, and recorded")
before = vstats.snapshot() before = vstats.snapshot()

View file

@ -63,36 +63,29 @@ else:
check("no other catalog model claims levels", check("no other catalog model claims levels",
[m for m in cat.values() if m.get("effort") and m["name"] != "qwen3.8-27b"] == []) [m for m in cat.values() if m.get("effort") and m["name"] != "qwen3.8-27b"] == [])
print("\n4. every knob the dashboard can set is one the proxy takes away from clients") print("\n4. a client's own kwargs win over the server default")
# The proxy drops plan.REASONING_KEYS from a client's request before applying the def inject(server_kw, client_body):
# dashboard's setting. If reasoning_kwargs learns a new template knob and this list """The precedence rule from the proxy, which mirrors mlx_lm's own."""
# doesn't, a client could set that knob itself -- so the two must stay in step. if not server_kw:
produced = set() return client_body.get("chat_template_kwargs")
for entry, controls in ((QWEN, BOTH), (ORNITH, THINK), (QWEN, THINK)): mine = dict(server_kw)
for value, _ in plan.reasoning_options(entry, None, controls): theirs = client_body.get("chat_template_kwargs")
produced |= set(plan.reasoning_kwargs(value, entry, controls)) if isinstance(theirs, dict):
check("the dashboard's knobs are exactly the ones taken from clients", mine.update(theirs)
produced == set(plan.REASONING_KEYS), (sorted(produced), plan.REASONING_KEYS)) return mine
check("both knobs are covered", set(plan.REASONING_KEYS) == {"enable_thinking", "reasoning_effort"},
plan.REASONING_KEYS)
print("\n5. the setting survives a setup re-run (`llmhost update`)") check("server default applied when client says nothing",
from llmhost import cli inject({"reasoning_effort": "low"}, {}) == {"reasoning_effort": "low"})
NAMES = ["qwen3.8-27b", "ornith-1.5-9b"] check("client overrides the same key",
check("a set choice is carried over", inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"reasoning_effort": "xhigh"}})
cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh"}}, NAMES) == {"reasoning_effort": "xhigh"})
== {"reasoning": {"qwen3.8-27b": "xhigh"}}) check("client's other keys survive alongside",
check("every model's choice is kept, not just the active one", inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"enable_thinking": False}})
cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}, NAMES) == {"reasoning_effort": "low", "enable_thinking": False})
== {"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}) check("no server default -> body untouched", inject({}, {}) is None)
check("a model that no longer fits is dropped", check("no server default -> client kwargs preserved",
cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "gone-70b": "low"}}, NAMES) inject({}, {"chat_template_kwargs": {"enable_thinking": False}}) == {"enable_thinking": False})
== {"reasoning": {"qwen3.8-27b": "xhigh"}}) check("a non-dict from the client isn't merged into",
check("nothing set -> no key written", cli.carried_settings({}, NAMES) == {}) inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"})
check("empty setting -> no key written", cli.carried_settings({"reasoning": {}}, NAMES) == {})
check("no model still fits -> no key written",
cli.carried_settings({"reasoning": {"gone-70b": "low"}}, NAMES) == {})
check("setup's own keys are not touched",
set(cli.carried_settings({"reasoning": {"qwen3.8-27b": "low"}}, NAMES)) == {"reasoning"})
check.done(ROOT) check.done(ROOT)