MLX proxy: count prompt tokens on streamed requests

Streamed responses only carry usage when the client asks for it, so the
prompt processing chart stayed at zero on Macs. The proxy now requests
the usage chunk itself and strips it from responses to clients that
didn't ask, forwarding the stream one whole event at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 05:03:49 -08:00
parent c4b54b4abd
commit 249c693e6d

View file

@ -147,16 +147,23 @@ def make_handler(inner_port, served_name, context, key, stats):
return
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
strip_usage = False
try:
body = json.loads(raw or b"{}")
if isinstance(body, dict):
body["model"] = "default_model"
# Ask for the final usage chunk so prompt tokens can be counted, and
# hide it again from clients that didn't ask for it.
opts = body.get("stream_options") or {}
if body.get("stream") and not opts.get("include_usage"):
body["stream_options"] = {**opts, "include_usage": True}
strip_usage = True
raw = json.dumps(body).encode()
except ValueError:
pass
self._forward("POST", raw)
self._forward("POST", raw, strip_usage)
def _forward(self, method, raw):
def _forward(self, method, raw, strip_usage=False):
counted = self.path.startswith("/v1/") # health checks aren't requests
if counted:
with stats.lock:
@ -186,12 +193,17 @@ def make_handler(inner_port, served_name, context, key, stats):
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
buf += chunk
# Forward whole events (the server writes one per token anyway).
while b"\n\n" in buf:
event, buf = buf.split(b"\n\n", 1)
self._count_event(event)
usage_only = self._count_event(event)
if not (strip_usage and usage_only):
self.wfile.write(event + b"\n\n")
self.wfile.flush()
if buf:
self.wfile.write(buf)
self.wfile.flush()
else:
data = resp.read()
self.send_header("Content-Length", str(len(data)))
@ -212,12 +224,13 @@ def make_handler(inner_port, served_name, context, key, stats):
stats.running -= 1
def _count_event(self, event):
"""Update token counts; returns True for a usage-only chunk (no choices)."""
if not event.startswith(b"data: {"):
return
return False
try:
d = json.loads(event[6:])
except ValueError:
return
return False
u = d.get("usage")
with stats.lock:
if u: # final usage chunk (stream_options.include_usage) is exact; prefer it
@ -226,6 +239,7 @@ def make_handler(inner_port, served_name, context, key, stats):
delta = c.get("delta") or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"):
stats.gen_total += 1 # mlx streams one token per chunk
return bool(u) and not d.get("choices")
return Proxy