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) <noreply@anthropic.com>
This commit is contained in:
parent
e48517b1cf
commit
e24c0b7712
10 changed files with 134 additions and 151 deletions
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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():
|
||||
|
|
|
|||
|
|
@ -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)))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue