Proxy in front of vLLM too; dashboard reset/clear; opencode effort variants

- Move the MLX proxy into backends/proxy.py and run it on both backends:
  public port 1134 is the proxy, the model server listens on 127.0.0.1:1135.
  On vLLM this brings the reasoning chooser, the "default" alias and the
  per-request table. Effort levels the model lacks map to the nearest it has
  (high -> xhigh on qwen3.8); vLLM's own key is sent upstream; streamed runs
  are counted from the usage chunk (MTP packs several tokens per chunk).
- Dashboard: restore METRIC_RE (vLLM page stuck on "loading"); Statistics
  header with Reset, Requests header with Clear; drop the TTFT chart; rename
  token columns; Peak KV shows "-" when no samples cover a run.
- opencode: config snippet's model points at <provider>/default, and
  reasoning models get variants built from the levels the template accepts.
- README: proxy on both platforms; NVIDIA checklist split into verified / open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-03 13:03:52 -08:00
parent 1121c3f908
commit 8879db44a0
12 changed files with 886 additions and 493 deletions

View file

@ -9,14 +9,15 @@ import harness
ROOT = harness.setup()
from llmhost import paths
from llmhost.backends import mlx
from llmhost.backends import proxy
harness.guard(paths, ROOT)
SERVED = "ornith-1.5-9b"
REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit"
KEY = "sk-test-key"
seen = [] # bodies the inner (fake mlx_lm) server received
seen = [] # bodies the inner (fake mlx_lm / vLLM) server received
auths = [] # the Authorization header each of them came with
check = harness.Checks()
@ -28,6 +29,21 @@ class Inner(BaseHTTPRequestHandler):
raw = self.rfile.read(n) if n else b""
try: seen.append(json.loads(raw or b"{}"))
except ValueError: seen.append(None)
auths.append(self.headers.get("Authorization"))
if seen[-1] and seen[-1].get("stream"):
# vLLM with speculative decoding: one chunk can carry several tokens, so only
# the closing usage chunk has the true count.
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for text in ("Hello", " there, how", " are you"):
self.wfile.write(b"data: " + json.dumps({"choices": [{"index": 0, "delta": {"content": text}}]}).encode() + b"\n\n")
self.wfile.write(b"data: " + json.dumps({"choices": [], "usage": {
"prompt_tokens": 30, "completion_tokens": 7, "total_tokens": 37,
"prompt_tokens_details": {"cached_tokens": 20}}}).encode() + b"\n\n")
self.wfile.write(b"data: [DONE]\n\n")
self.close_connection = True
return
body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model",
"created": 0, "choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "pong"}}],
@ -46,20 +62,21 @@ def serve(handler, port):
INNER, OUTER = 18231, 18232
serve(Inner, INNER)
stats = mlx.Stats()
serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
stats = proxy.Stats()
serve(proxy.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
def post(model, key=KEY, path="/v1/chat/completions"):
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4}
def post(model, key=KEY, path="/v1/chat/completions", port=None, raw_reply=False, **extra):
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4, **extra}
if model is not None:
body["model"] = model
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}{path}", data=json.dumps(body).encode(),
req = urllib.request.Request(f"http://127.0.0.1:{port or OUTER}{path}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {key}"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=20) as r:
return r.status, json.loads(r.read() or b"{}")
data = r.read()
return r.status, (data if raw_reply else json.loads(data or b"{}"))
except urllib.error.HTTPError as e:
try: return e.code, json.loads(e.read() or b"{}")
except ValueError: return e.code, {}
@ -89,10 +106,12 @@ check("alias is 'default'", plan.SERVED_ALIAS == "default")
seen.clear()
post(plan.SERVED_ALIAS)
check("still forwarded as default_model", seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
check("vLLM is told to serve it as a second name",
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[1:4]
== ["--served-model-name", "m", plan.SERVED_ALIAS],
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[:5])
va = plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8001, 1)
check("vLLM serves one name; the proxy owns the alias",
va[1:3] == ["--served-model-name", "m"] and plan.SERVED_ALIAS not in va, va[:5])
check("vLLM listens on localhost only, behind the proxy",
va[va.index("--host") + 1] == "127.0.0.1" and va[va.index("--port") + 1] == "8001", va)
check("vLLM reports cached prompt tokens", "--enable-prompt-tokens-details" in va, va)
print("\n5. a model that ISN'T loaded is refused, not silently answered")
code, body = post("qwen3.8-27b")
@ -122,4 +141,56 @@ with urllib.request.urlopen(req, timeout=10) as r:
d = json.loads(r.read())
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
VOUTER = 18233
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)
check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27b", seen[-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.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 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 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()
code, data = post(None, port=VOUTER, raw_reply=True, stream=True)
after = vstats.snapshot()
check("200", code == 200, code)
check("usage chunk hidden from a client that didn't ask for it", b'"usage"' not in data, data[-200:])
check("generated tokens from usage (3 chunks, 7 tokens)", after["gen_total"] - before["gen_total"] == 7,
after["gen_total"] - before["gen_total"])
run = after["recent"][-1]
check("run recorded with its uncached prompt tokens", run["gen"] == 7 and run["prompt"] == 10, run)
check("time to first token recorded", run["ttft"] is not None, run)
check.done(ROOT)