From e48517b1cfa337e75323fff8ac7cc73a4c516b27 Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 15:01:12 -0800 Subject: [PATCH 1/2] Setup: keep the dashboard's reasoning setting across an update cmd_setup rebuilds config.json from the plan, and the reasoning setting isn't part of the plan -- the dashboard writes it into the same file. So every `llmhost update` (setup --yes under the hood) silently put every model back to "Model default", losing a setting the user had chosen in the UI. Carry it over, minus models that no longer fit. The helper exists so the reason is on the record rather than implied by a dict literal; its tests cover the empty and no-longer-fits cases that must not write the key at all. Co-Authored-By: Claude Opus 5 (1M context) --- llmhost/cli.py | 10 ++++++++++ tests/test_reasoning.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/llmhost/cli.py b/llmhost/cli.py index afbcdda..99f7036 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -111,6 +111,15 @@ def cmd_plan(a): 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): info = hw.detect() cat = paths.load_catalog() @@ -169,6 +178,7 @@ def cmd_setup(a): "models": p["models"], "excluded": p["excluded"], "active": active, p["backend"]: {**old.get(p["backend"], {}), **backend_info}, } + cfg.update(carried_settings(old, names)) paths.save_config(cfg) key = paths.api_key(create=True) diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py index 6e17ddd..4ed7cba 100644 --- a/tests/test_reasoning.py +++ b/tests/test_reasoning.py @@ -88,4 +88,23 @@ check("no server default -> client kwargs preserved", check("a non-dict from the client isn't merged into", inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"}) +print("\n5. the setting survives a setup re-run (`llmhost update`)") +from llmhost import cli +NAMES = ["qwen3.8-27b", "ornith-1.5-9b"] +check("a set choice is carried over", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh"}}) +check("every model's choice is kept, not just the active one", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}) +check("a model that no longer fits is dropped", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "gone-70b": "low"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh"}}) +check("nothing set -> no key written", cli.carried_settings({}, NAMES) == {}) +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) From e24c0b771297b024481cbea97c5dbcae2fbe8f5d Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 15:01:26 -0800 Subject: [PATCH 2/2] Reasoning effort is the dashboard's to set, not the client's One model is loaded at a time under one setting, and that setting belongs next to the model it applies to -- the same reason the client can't switch models. So the proxy now takes a client's reasoning settings off the request before applying the dashboard's: a top-level reasoning_effort, and enable_thinking or reasoning_effort inside chat_template_kwargs. Other template kwargs, which llm-host has no opinion about, still pass through. This reverses the precedence the proxy had (a client's own kwargs won, mirroring mlx_lm's own rule), which was the wrong model for a single-model server: clients offer a generic menu -- opencode's low/medium/high -- and a level the template doesn't define makes it raise, so every request failed with nothing on the user's screen to explain it. - opencode: the provider block disables all three of opencode's effort levels instead of curating them. A chooser there would be a menu that does nothing. - Deletes the nearest-effort mapping (EFFORT_SCALE, nearest_effort, plan.effort_levels, the effort_levels= parameter through both backends): it existed only to rescue a client-supplied level, and none survives now. - plan.REASONING_KEYS names the knobs this server drives, with a test asserting it stays exactly equal to what reasoning_kwargs can emit -- so a new template knob can't be added without also taking it away from clients. - Two strings that still described a menu of models, from before the block held a single entry. Verified against the live MLX server: with the dashboard on xhigh, five request shapes (nothing, enable_thinking: false, effort low top-level, effort low in kwargs, and the off-scale "turbo" that used to 404) all answer identically, and the reply tracks the dashboard alone as it moves off / low / xhigh. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 33 ++++++++++++-------- llmhost/backends/mlx.py | 5 ++-- llmhost/backends/proxy.py | 54 +++++++++++++++------------------ llmhost/backends/vllm.py | 5 ++-- llmhost/cli.py | 2 +- llmhost/opencode.py | 38 ++++++++--------------- llmhost/plan.py | 27 ++++------------- tests/test_opencode.py | 22 ++++++++------ tests/test_proxy.py | 63 ++++++++++++++++++++++++++------------- tests/test_reasoning.py | 36 ++++++++-------------- 10 files changed, 134 insertions(+), 151 deletions(-) diff --git a/README.md b/README.md index 71ffa6c..45b88ba 100644 --- a/README.md +++ b/README.md @@ -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 specific model (`llmhost/qwen3.8-27b`) is migrated to `llmhost/default` the next time llm-host writes the block. -opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, and a level the model's -template doesn't define makes every request fail. So the block carries `variants` that hide the levels the -loaded model lacks and add the ones it has (Qwen3.8 27B: no `high`, plus `xhigh`). A pasted remote block can't -follow a later switch, so the proxy also maps a level the model lacks to the nearest one it has (`high` → -`xhigh`); a stale menu entry still works. +opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, so the block carries +`variants` that switch all three off. The effort level is set on the dashboard, next to the model it applies +to, and the proxy drops whatever a client sends — a chooser in the client would be a menu that silently does +nothing, listing levels the loaded model's template may not even define. -To serve a different model, switch the server: `llmhost switch ` or the dashboard. Clients don't choose. +Neither the model nor its reasoning setting is the client's to choose: both change on the dashboard (or with +`llmhost switch `), 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 provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is @@ -140,12 +140,16 @@ 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": [...]}`) — 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. +The dashboard is the only place it is set. The proxy puts the setting on every chat completion +and takes the client's own out first — both a top-level `reasoning_effort` and `enable_thinking` +or `reasoning_effort` inside `chat_template_kwargs`. Template kwargs llm-host has no opinion +about are passed through untouched. Changing the setting takes effect on the next request with no +reload, so the model stays in memory. -This works the same on vLLM and MLX. A client's own top-level `reasoning_effort` also wins over -the dashboard's level, and one the model lacks is mapped to the nearest level it has. +Clients are ignored here rather than obeyed because one model is loaded at a time under one +setting, and because a client's menu is generic: opencode offers `high`, which Qwen3.8's template +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 @@ -193,9 +197,9 @@ python3 tests/test_opencode.py # or run one directly | | | |---|---| | `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache | -| `tests/test_proxy.py` | model names, effort mapping, upstream key, streamed-run counting, against a fake server | +| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server | | `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing | -| `tests/test_reasoning.py` | effort options matching the real chat templates | +| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update | ## Continuing on an NVIDIA box @@ -249,5 +253,8 @@ 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 `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. - 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 616a6f6..59dbea8 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -15,7 +15,7 @@ import sys import threading import time -from .. import hfcache, paths, plan +from .. import hfcache, paths from . import proxy VENV = paths.DATA / "venv-mlx" @@ -104,8 +104,7 @@ def run_server(cfg, entry, choice, args): controls = hfcache.template_controls(choice["repo"]) srv = proxy.listen(port, proxy.make_handler( inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats, - aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls), - effort_levels=plan.effort_levels(entry, controls))) + aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls))) proxy.kill_stale(inner, VENV, "mlx_lm") exe = str(VENV / "bin/mlx_lm.server") diff --git a/llmhost/backends/proxy.py b/llmhost/backends/proxy.py index 5edf1bf..8440d32 100644 --- a/llmhost/backends/proxy.py +++ b/llmhost/backends/proxy.py @@ -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 rewrites the request's "model" to the name the server knows it by; /v1/models answers with the served name, - - applies the dashboard's reasoning setting to chat requests, and maps an effort level - the model doesn't have (a client's generic "high", say) to the nearest one it does, + - applies the dashboard's reasoning setting to chat requests, dropping any the client + sent: the model and its reasoning setting are both the dashboard's to choose, - counts in-flight requests and tokens and records each finished request for the dashboard (/llmhost/metrics, localhost only). """ @@ -73,11 +73,10 @@ def _uncached(usage): def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None, - upstream_model="default_model", upstream_key=None, effort_levels=()): + upstream_model="default_model", upstream_key=None): """upstream_model: what the inner server calls the loaded model ("default_model" makes mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent - on to an inner server that checks keys itself (vLLM). effort_levels: the levels this - model's template accepts; an unknown one from a client is mapped to the nearest.""" + on to an inner server that checks keys itself (vLLM).""" # 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)} @@ -143,16 +142,23 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso "type": "invalid_request_error", "code": "model_not_found", "param": "model"}}) return False - def _fit_effort(self, holder, k): - """Map holder[k], a client's effort level, onto one this model accepts. Clients - offer a generic menu (opencode: low/medium/high), and a level the template - doesn't define makes it raise -- every request then fails until the user finds - the setting. The nearest level is what they meant.""" - v = holder.get(k) - if effort_levels and isinstance(v, str) and v not in effort_levels: - fit = plan.nearest_effort(v, effort_levels) - if fit: - holder[k] = fit + def _set_reasoning(self, body): + """Put the dashboard's reasoning setting on the request, and drop whatever the + client asked for. The setting belongs to the dashboard for the same reason the + model does: one model is loaded at a time, under one setting, and a client's + generic menu (opencode offers low/medium/high) lists levels this template may + not even define -- one of those would make it raise, failing every request from + a client whose user can't see why. The client's other template kwargs, which + llm-host has no opinion about, are left alone.""" + body.pop("reasoning_effort", None) # the OpenAI-style top-level field + theirs = body.get("chat_template_kwargs") + 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): if not self._authed(): @@ -169,22 +175,10 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso if isinstance(body, dict): if self.path.startswith("/v1/") and not self._model_ok(body): return + # Only chat completions go through a chat template, so only they can + # carry a reasoning setting. if "chat/completions" in self.path: - theirs = body.get("chat_template_kwargs") - # Server-side reasoning default. Only chat completions go through a - # chat template, and a setting the client made itself always wins -- - # the same precedence mlx_lm applies to its own --chat-template-kwargs. - kw = reasoning() if reasoning else {} - if kw: - mine = dict(kw) - if "reasoning_effort" in body: # the OpenAI-style top-level field - mine.pop("reasoning_effort", None) - if isinstance(theirs, dict): - mine.update(theirs) - body["chat_template_kwargs"] = theirs = mine - self._fit_effort(body, "reasoning_effort") - if isinstance(theirs, dict): - self._fit_effort(theirs, "reasoning_effort") + self._set_reasoning(body) # Name the loaded model the way the inner server knows it (mlx_lm would # otherwise try to load a model matching the name it's given). body["model"] = upstream_model diff --git a/llmhost/backends/vllm.py b/llmhost/backends/vllm.py index 70a01bc..bbcb3e8 100644 --- a/llmhost/backends/vllm.py +++ b/llmhost/backends/vllm.py @@ -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). vLLM keeps its own API key, so the inner port isn't open to anyone else on the box; the proxy checks the client's key and sends ours on.""" - from .. import hfcache, plan + from .. import hfcache from . import proxy port = cfg["api_port"] inner = port + 1 @@ -175,8 +175,7 @@ def run_server(cfg, entry, choice, args): srv = proxy.listen(port, proxy.make_handler( inner, entry["name"], choice.get("est_context", entry["context"]), key, stats, aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls), - upstream_model=entry["name"], upstream_key=key, - effort_levels=plan.effort_levels(entry, controls))) + upstream_model=entry["name"], upstream_key=key)) proxy.kill_stale(inner, VENV, "vllm") exe = str(VENV / "bin/vllm") # vLLM's output goes straight to ours (the service log); nothing in it needs reading. diff --git a/llmhost/cli.py b/llmhost/cli.py index 99f7036..5ac5f00 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -361,7 +361,7 @@ def cmd_switch(a): 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"opencode's LLMHost (Local) provider now names {a.model} as the default model.") say(f"Switched to {a.model}. Watch it load with: llmhost watch") diff --git a/llmhost/opencode.py b/llmhost/opencode.py index e0adf31..090bb7a 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 hfcache, paths, plan +from . import paths, plan PROVIDER = "llmhost" DISPLAY = "LLMHost" @@ -127,28 +127,16 @@ def model_label(active, label, name_it): # A model's template defines its own set, and one it lacks makes the template raise, so # the block hides those and adds the model's own. (The proxy also maps a stray level to # the nearest real one, so a pasted block that predates a switch still works.) +# The reasoning levels opencode offers of its own accord for a model marked `reasoning`. OPENCODE_EFFORTS = ("low", "medium", "high") -def _effort_levels(choice): - """The active model's effort levels: from its chat template once downloaded (what the - proxy itself goes by), from the catalog before that.""" - try: - entry = plan.catalog_entry(paths.load_catalog(), choice["name"]) - except (KeyError, OSError, ValueError): - return () - if not entry.get("reasoning"): - return () - if choice.get("repo") and hfcache.repo_dir(choice["repo"]).exists(): - return plan.effort_levels(entry, hfcache.template_controls(choice["repo"])) - return tuple((entry.get("effort") or {}).get("levels") or ()) - - -def effort_variants(levels): - """opencode `variants` for a model accepting `levels`.""" - v = {l: {"disabled": True} for l in OPENCODE_EFFORTS if l not in levels} - v.update({l: {"reasoningEffort": l} for l in levels if l not in OPENCODE_EFFORTS}) - return v +def effort_variants(): + """opencode `variants` that switch its reasoning menu off. The effort level is set on + llm-host's dashboard and the proxy drops whatever a client asks for, so a chooser here + would be a menu that silently does nothing -- and whose levels this model's template + may not even define. One model, one setting, one place to change it.""" + return {level: {"disabled": True} for level in OPENCODE_EFFORTS} def provider_block(cfg, host, key_path, label, mark_loaded=False): @@ -161,10 +149,10 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False): entry = {"name": model_label(active, label, mark_loaded), "tool_call": True, "limit": {"context": ctx, "output": min(65536, ctx // 2)}} 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 - variants = effort_variants(_effort_levels(active)) - if variants: - entry["variants"] = variants + entry["variants"] = effort_variants() models = {plan.SERVED_ALIAS: entry} return { "npm": "@ai-sdk/openai-compatible", @@ -393,8 +381,8 @@ def remove(prov_ids=None, local=True, host=None, every=False): 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, + """Refresh an existing local provider block -- after a model switch, so the entry's + name and limits keep up with what's loaded. 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(): diff --git a/llmhost/plan.py b/llmhost/plan.py index a419633..e5e08e3 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -200,6 +200,11 @@ def reasoning_options(entry, choice, controls): 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): """chat_template_kwargs for a setting, or {} for "default"/anything unsupported.""" if not value or value == DEFAULT or not entry.get("reasoning"): @@ -211,25 +216,3 @@ def reasoning_kwargs(value, entry, controls): return {"reasoning_effort": value} return {} - -# Effort levels in order, for mapping a level a model lacks onto the nearest it has. -EFFORT_SCALE = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] - - -def effort_levels(entry, controls): - """The effort levels this model's template accepts, or () if it takes none.""" - levels = (entry.get("effort") or {}).get("levels") or [] - return tuple(levels) if entry.get("reasoning") and controls.get("effort") else () - - -def nearest_effort(value, levels): - """The level in `levels` closest to `value` on EFFORT_SCALE; on a tie, the higher one - (asking for "high" between medium and xhigh means wanting more, not less). None when - either is off the scale.""" - if value not in EFFORT_SCALE: - return None - want = EFFORT_SCALE.index(value) - known = [l for l in levels if l in EFFORT_SCALE] - if not known: - return None - return min(known, key=lambda l: (abs(EFFORT_SCALE.index(l) - want), -EFFORT_SCALE.index(l))) diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 2a9510b..0f73e2d 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -309,18 +309,22 @@ check("model is /", snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"], (snip["model"], list(block["models"]))) -check.section("24. the block offers only the effort levels the loaded model accepts") -check("qwen3.8: hide high, add xhigh", - opencode.effort_variants(("low", "medium", "xhigh")) == {"high": {"disabled": True}, - "xhigh": {"reasoningEffort": "xhigh"}}, - opencode.effort_variants(("low", "medium", "xhigh"))) -check("no levels: hide opencode's whole menu", - opencode.effort_variants(()) == {l: {"disabled": True} for l in ("low", "medium", "high")}) +check.section("24. the block never offers a reasoning chooser of its own") +check("opencode's whole menu is switched off", + opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")}, + opencode.effort_variants()) q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") ent = q["models"]["default"] -check("qwen3.8 block (not downloaded: catalog levels)", - ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent) +check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent) +check("but every effort level is disabled", + 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") 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) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 96044e0..5cbd7a7 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -147,7 +147,6 @@ vstats = proxy.Stats() vstats.ready = True serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",), upstream_model="qwen3.8-27b", upstream_key="sk-inner", - effort_levels=("low", "medium", "xhigh"), reasoning=lambda: {"reasoning_effort": "low"}), VOUTER) seen.clear(); auths.clear() check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200) @@ -155,31 +154,53 @@ 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("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404) -check.section("10. effort levels the model lacks are mapped to the nearest it has") -for asked, sent in (("high", "xhigh"), ("medium", "medium"), ("xhigh", "xhigh"), - ("minimal", "low"), ("max", "xhigh")): - seen.clear() - post(None, port=VOUTER, reasoning_effort=asked) - check(f"top-level {asked} -> {sent}", seen[-1].get("reasoning_effort") == sent, seen[-1]) -seen.clear() -post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "high"}) -check("inside chat_template_kwargs too", seen[-1]["chat_template_kwargs"].get("reasoning_effort") == "xhigh", - seen[-1].get("chat_template_kwargs")) -seen.clear() -post(None, port=VOUTER, reasoning_effort="bogus") -check("an unknown word is left for the server to reject", seen[-1].get("reasoning_effort") == "bogus", seen[-1]) +check.section("10. the reasoning setting is the dashboard's; a client can't set it") seen.clear() post(None, port=VOUTER) -check("dashboard setting applied when the client sets none", +check("dashboard setting applied when the client asks for nothing", seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) seen.clear() post(None, port=VOUTER, reasoning_effort="xhigh") -check("a client's own top-level level wins over the dashboard's", - "reasoning_effort" not in (seen[-1].get("chat_template_kwargs") or {}) - and seen[-1].get("reasoning_effort") == "xhigh", seen[-1]) -check("mapping only where a model has levels", - [plan.nearest_effort("high", ()), plan.nearest_effort("high", ("low", "high"))] == [None, "high"]) -check("a tie goes to the higher level", plan.nearest_effort("high", ("medium", "xhigh")) == "xhigh") +check("a client's top-level reasoning_effort never reaches the model", + "reasoning_effort" not in seen[-1], seen[-1]) +check("...and the dashboard's setting is what goes instead", + seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "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") before = vstats.snapshot() diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py index 4ed7cba..f0cc508 100644 --- a/tests/test_reasoning.py +++ b/tests/test_reasoning.py @@ -63,30 +63,18 @@ else: 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"}) +print("\n4. every knob the dashboard can set is one the proxy takes away from clients") +# The proxy drops plan.REASONING_KEYS from a client's request before applying the +# dashboard's setting. If reasoning_kwargs learns a new template knob and this list +# doesn't, a client could set that knob itself -- so the two must stay in step. +produced = set() +for entry, controls in ((QWEN, BOTH), (ORNITH, THINK), (QWEN, THINK)): + for value, _ in plan.reasoning_options(entry, None, controls): + produced |= set(plan.reasoning_kwargs(value, entry, controls)) +check("the dashboard's knobs are exactly the ones taken from clients", + produced == set(plan.REASONING_KEYS), (sorted(produced), plan.REASONING_KEYS)) +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`)") from llmhost import cli