diff --git a/README.md b/README.md index 45b88ba..71ffa6c 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, 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. +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. -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. +To serve a different model, switch the server: `llmhost switch ` or the dashboard. Clients don't choose. Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is @@ -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": [...]}`) — 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 -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. +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. -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. +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. ## 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_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_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 @@ -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 `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 59dbea8..616a6f6 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 +from .. import hfcache, paths, plan from . import proxy VENV = paths.DATA / "venv-mlx" @@ -104,7 +104,8 @@ 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))) + aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls), + effort_levels=plan.effort_levels(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 8440d32..5edf1bf 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, dropping any the client - sent: the model and its reasoning setting are both the dashboard's to choose, + - 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, - counts in-flight requests and tokens and records each finished request for the 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, - 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 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 # 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)} @@ -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"}}) return False - 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 _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 do_POST(self): 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 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: - 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 # 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 bbcb3e8..70a01bc 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 + from .. import hfcache, plan from . import proxy port = cfg["api_port"] inner = port + 1 @@ -175,7 +175,8 @@ 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)) + upstream_model=entry["name"], upstream_key=key, + effort_levels=plan.effort_levels(entry, controls))) 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 5ac5f00..afbcdda 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -111,15 +111,6 @@ 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() @@ -178,7 +169,6 @@ 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) @@ -361,7 +351,7 @@ def cmd_switch(a): paths.save_config(cfg) service.restart("model") 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") diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 090bb7a..e0adf31 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, plan +from . import hfcache, paths, plan PROVIDER = "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 # 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_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 _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 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, "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 - entry["variants"] = effort_variants() + variants = effort_variants(_effort_levels(active)) + if variants: + entry["variants"] = variants models = {plan.SERVED_ALIAS: entry} return { "npm": "@ai-sdk/openai-compatible", @@ -381,8 +393,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 entry's - name and limits keep up with what's loaded. Never adds one: if opencode isn't wired up here, + """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(): diff --git a/llmhost/plan.py b/llmhost/plan.py index e5e08e3..a419633 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -200,11 +200,6 @@ 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"): @@ -216,3 +211,25 @@ 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 0f73e2d..2a9510b 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -309,22 +309,18 @@ 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 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()) +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")}) q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") ent = q["models"]["default"] -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"]) +check("qwen3.8 block (not downloaded: catalog levels)", + ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent) 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 5cbd7a7..96044e0 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -147,6 +147,7 @@ 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) @@ -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("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() 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.clear() post(None, port=VOUTER, reasoning_effort="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("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.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 f0cc508..6e17ddd 100644 --- a/tests/test_reasoning.py +++ b/tests/test_reasoning.py @@ -63,36 +63,29 @@ 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. 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("\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 -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("server default applied when client says nothing", + inject({"reasoning_effort": "low"}, {}) == {"reasoning_effort": "low"}) +check("client overrides the same key", + inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"reasoning_effort": "xhigh"}}) + == {"reasoning_effort": "xhigh"}) +check("client's other keys survive alongside", + inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"enable_thinking": False}}) + == {"reasoning_effort": "low", "enable_thinking": False}) +check("no server default -> body untouched", inject({}, {}) is None) +check("no server default -> client kwargs preserved", + inject({}, {"chat_template_kwargs": {"enable_thinking": False}}) == {"enable_thinking": False}) +check("a non-dict from the client isn't merged into", + inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"}) check.done(ROOT)