Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: /v1/messages/count_tokens, Anthropic thinking only when asked, STRATA_REQUEST_LINES, a relative exe
sergiywith4c2cd14f5f85
diff --git a/serve/frontend.py b/serve/frontend.pyindex 48dc2dbf5..edcddb79b 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -219,6 +219,11 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dickwargs.update(effort_kwargs(effort))elif isinstance(thinking, dict) and thinking.get("budget_tokens"):kwargs.update(budget_effort(thinking["budget_tokens"]))+ elif thinking is None:+ # Anthropic's thinking is opt-in. Claude Code's helper calls (a session title, a topic check) ask for none+ # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all.+ # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs.+ kwargs["enable_thinking"] = Falsereturn _late_system_to_user(messages), tools, kwargsdiff --git a/serve/server.py b/serve/server.pyindex af6665701..3637651c0 100644--- a/serve/server.py+++ b/serve/server.py@@ -30,6 +30,7 @@ import ctypesimport jsonimport osimport queue+import reimport signalimport subprocessimport sys@@ -104,6 +105,33 @@ class GpuBusy(RuntimeError):model server) is using it, so the engine is not started into the little that is left."""+ENGINE_REQUEST = re.compile(+ r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ \d+ read in (?P<read>[\d.]+) ms \((?P<pp>[\d.]+) tok/s\), "+ r"(?P<gen>\d+) generated in (?P<gen_ms>[\d.]+) ms \((?P<tg>[\d.]+) tok/s\)")+++def echo_requests(log_path: str, offset: int) -> None:+ """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log.++ The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this+ process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the+ total the two times make: `request prompt P cached C output O ttft T ms total S ms prefill X tok/s decode Y tok/s`.+ """+ with open(log_path, "r", encoding="utf-8", errors="replace") as f:+ f.seek(offset)+ while True:+ line = f.readline()+ if not line:+ time.sleep(0.2)+ continue+ m = ENGINE_REQUEST.search(line)+ if m:+ read_ms, gen_ms = float(m["read"]), float(m["gen_ms"])+ print("[strata] request prompt %s cached %s output %s ttft %.0f ms total %.0f ms prefill %s tok/s "+ "decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], m["tg"]),+ flush=True)++def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None:"""While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GBinto RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more -@@ -175,6 +203,8 @@ class StrataEngine:if log:threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading),daemon=True).start()+ if os.environ.get("STRATA_REQUEST_LINES"):+ threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start()self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)contain(self.proc) # ends with the server, however it ends (Windows)@@ -1633,6 +1663,8 @@ def make_handler(svc: Service):self._openai(req)elif path == "/v1/messages":self._anthropic(req)+ elif path == "/v1/messages/count_tokens":+ self._count_tokens(req)else:self._json(404, {"error": {"message": "not found"}})except ValueError as e:@@ -1741,6 +1773,14 @@ def make_handler(svc: Service):err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 nowself.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")+ def _count_tokens(self, req):+ """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would+ read for the same request, rendered and tokenized - the model does not run."""+ req = svc.with_shared(req, "anthropic")+ messages, tools, kw = anthropic_to_messages(req)+ prompt = svc.template.render(messages, tools=tools, **kw)+ self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))})+def _anthropic(self, req):req = svc.with_shared(req, "anthropic")messages, tools, kw = anthropic_to_messages(req)@@ -2005,7 +2045,10 @@ def main() -> int:print("loading the model (the first start takes a minute or two) ...", flush=True)if len(gpu_list(cfg)) > 1:print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True)- engine = StrataEngine(cfg["exe"], engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env)+ # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing+ # it is told about (WinError 2), so it is made absolute here+ exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"]))+ engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env)warn_tight_ram(engine.info.get("arena_mib"))else:engine, vision, sampling_defaults = MockEngine(tok, a.script or [diff --git a/serve/test_server.py b/serve/test_server.pyindex d84ebff40..e5d311843 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -65,6 +65,23 @@ class MaxTokens(unittest.TestCase):u = b.get("usage", {})return s, b, u.get("input_tokens"), u.get("output_tokens")+ def test_count_tokens_is_the_prompt_messages_reads(self):+ # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it+ msgs = [{"role": "user", "content": "how many tokens is this?"}]+ s, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": msgs})+ self.assertEqual(s, 200)+ s2, _, n_in, _ = self.call("anthropic", "how many tokens is this?", max_tokens=8)+ self.assertEqual(s2, 200)+ self.assertEqual(b["input_tokens"], n_in)++ def test_request_line_parses_the_engine_summary(self):+ line = ("strata serve: prompt 1200 tokens = 1000 reused + 200 read in 50 ms (4000.0 tok/s), 30 generated in "+ "300 ms (100.0 tok/s), drafts accepted 20 of 28, 2 checkpoints")+ from serve.server import ENGINE_REQUEST+ m = ENGINE_REQUEST.search(line)+ self.assertIsNotNone(m)+ self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0"))+def test_unset_budget_is_the_rest_of_the_context(self):cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None},{"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}],