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++
web app: "Use for other apps too" - the Chat settings as every client's defaults
Niko12211e3bded2f794
diff --git a/serve/server.py b/serve/server.pyindex 72f8fa9fe..175125ef8 100644--- a/serve/server.py+++ b/serve/server.py@@ -417,6 +417,8 @@ class Service:self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, visionself.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block+ self.shared = {} # the web app's Chat settings for every client (POST /settings)+ self.shared_path = None # where they are kept between starts (next to the config)self.fifo = threading.Lock()self.embeddings = threading.local() # the current request's image embeddings file (GENI)self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key)@@ -426,6 +428,41 @@ class Service:self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +tokenizer.encode("<|endoftext|>", parse_special=True))+ def set_shared(self, defaults) -> dict:+ """The Chat settings every client gets for what it leaves out; {} / None = clients use their own again."""+ self.shared = clean_shared_defaults(defaults)+ if self.shared_path:+ try:+ if self.shared:+ Path(self.shared_path).write_text(json.dumps(self.shared, indent=1), encoding="utf-8")+ else:+ Path(self.shared_path).unlink(missing_ok=True)+ except OSError as e:+ print(f"[strata] could not save the shared settings: {e}", flush=True)+ return self.shared++ def with_shared(self, req: dict, api: str) -> dict:+ """The request with the shared thinking level and max tokens filled in where it has none of its own."""+ s = self.shared+ if not s:+ return req+ req = dict(req)+ if "max_tokens" in s and not req.get("max_tokens") and not req.get("max_completion_tokens"):+ req["max_tokens"] = s["max_tokens"]+ effort = s.get("reasoning_effort")+ if effort:+ if api == "openai":+ ctk = req.get("chat_template_kwargs") if isinstance(req.get("chat_template_kwargs"), dict) else {}+ if not req.get("reasoning_effort") and not req.get("reasoning") and \+ "enable_thinking" not in ctk and "reasoning_effort" not in ctk:+ req["reasoning_effort"] = effort+ elif not req.get("thinking") and not req.get("output_config"):+ if effort == "none":+ req["thinking"] = {"type": "disabled"}+ else:+ req["output_config"] = {"effort": effort}+ return req+def start_telemetry(self):"""The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too."""if getattr(self, "telemetry", None) is None:@@ -548,9 +585,10 @@ class Service:def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]:"""Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..})."""- if self.sampling_defaults: # config defaults; the request's own fields win (explicit 0 stays greedy)+ defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps+ if defaults: # the request's own fields win (explicit 0 stays greedy)req_values = {k: v for k, v in (sampling or {}).items() if v is not None}- sampling = {**self.sampling_defaults, **req_values}+ sampling = {**defaults, **req_values}parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True)detok, n, finish = Detokenizer(self.tok), 0, "length"raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)@@ -877,6 +915,10 @@ def make_handler(svc: Service):if self._authorized():self._json(200, svc.metrics())return+ if path == "/settings":+ if self._authorized():+ self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared})+ returnif path == "":body = (ROOT / "serve" / "web" / "index.html").read_bytes()self.send_response(200)@@ -907,6 +949,9 @@ def make_handler(svc: Service):def do_POST(self):if not self._authorized():return+ if self.path.rstrip("/") == "/settings":+ self._settings()+ returntry:req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")if self.path.rstrip("/") == "/v1/chat/completions":@@ -920,6 +965,28 @@ def make_handler(svc: Service):except EngineDied as e: # before the answer started (not streamed)self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}})+ def _settings(self):+ # They change what every client gets, so only the app's own page may set them: JSON only (a form or a+ # "simple" cross-site request can't send it without a CORS preflight, which this server never grants),+ # and no foreign Origin+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))+ if not self.headers.get("Content-Type", "").startswith("application/json"):+ self._json(415, {"error": {"message": "send application/json"}})+ return+ origin = self.headers.get("Origin")+ if origin and origin.split("://", 1)[-1] != self.headers.get("Host", ""):+ self._json(403, {"error": {"message": "settings can only be changed from Strata's own page"}})+ return+ try:+ req = json.loads(body or b"{}")+ shared = svc.set_shared(req.get("defaults") if isinstance(req, dict) else None)+ except ValueError as e:+ self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})+ return+ print("[strata] other apps now use the Chat settings: " + ", ".join(f"{k}={v}" for k, v in shared.items())+ if shared else "[strata] other apps use their own settings again", flush=True)+ self._json(200, {"shared": bool(shared), "defaults": shared})+def _sse(self):self.send_response(200)self.send_header("Content-Type", "text/event-stream")@@ -927,6 +994,7 @@ def make_handler(svc: Service):self.end_headers()def _openai(self, req):+ req = svc.with_shared(req, "openai")messages, tools, kw = openai_to_messages(req)max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest of the contextids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)@@ -952,6 +1020,7 @@ def make_handler(svc: Service):self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")def _anthropic(self, req):+ req = svc.with_shared(req, "anthropic")messages, tools, kw = anthropic_to_messages(req)max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the contextids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)@@ -1032,6 +1101,46 @@ def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer:return httpd+SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection")+++def clean_shared_defaults(d) -> dict:+ """The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one."""+ if d is None:+ return {}+ if not isinstance(d, dict):+ raise ValueError("defaults must be an object")+ out = {}+ for key, value in d.items():+ if value is None or value == "":+ continue+ number = isinstance(value, (int, float)) and not isinstance(value, bool)+ if key == "reasoning_effort":+ if value not in ("none", "low", "medium", "high"):+ raise ValueError("reasoning_effort: none, low, medium or high")+ elif key == "temperature":+ if not number or not 0 <= value <= 2:+ raise ValueError("temperature: 0..2")+ elif key == "top_p":+ if not number or not 0 < value <= 1:+ raise ValueError("top_p: 0 < top_p <= 1")+ elif key == "top_k":+ if not number or value != int(value) or not 1 <= value <= 64:+ raise ValueError("top_k: an integer 1..64")+ value = int(value)+ elif key in ("seed", "max_tokens"):+ if not number or value != int(value) or value <= 0:+ raise ValueError(f"{key}: a positive integer")+ value = int(value)+ elif key == "experimental_speed_projection":+ if not isinstance(value, bool):+ raise ValueError("experimental_speed_projection: true or false")+ else:+ raise ValueError(f"unknown setting {key!r}")+ out[key] = float(value) if key in ("temperature", "top_p") else value+ return out++def sampling_defaults_from_config(cfg: dict) -> dict:"""The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, soa plain client gets configured sampling instead of greedy. Supported: temperature, top_p, top_k, min_p,@@ -1156,6 +1265,15 @@ def main() -> int:sampling_defaults=sampling_defaults,fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)svc.api_key = a.api_key or cfg.get("api_key", "")+ if a.config: # the Chat settings shared with other apps, from last time+ svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json"+ try:+ svc.shared = clean_shared_defaults(json.loads(Path(svc.shared_path).read_text(encoding="utf-8")))+ if svc.shared:+ print("[strata] other apps use the Chat settings: " ++ ", ".join(f"{k}={v}" for k, v in svc.shared.items()), flush=True)+ except (OSError, ValueError):+ svc.shared = {}httpd = serve(svc, host=a.host, port=a.port)here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.hostprint(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, "diff --git a/serve/test_server.py b/serve/test_server.pyindex 0bb7df3c7..2ce796cac 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -222,6 +222,100 @@ class EngineDeath(unittest.TestCase):httpd.server_close()+class SharedSettings(unittest.TestCase):+ """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults."""++ @classmethod+ def setUpClass(cls):+ import tempfile++ class Sampled(RecordingEngine):+ def generate(self, ids, max_new, sampling, cancel, embeddings=None):+ self.last_sampling = dict(sampling or {})+ yield from super().generate(ids, max_new, sampling, cancel, embeddings)++ tok = ByteTokenizer()+ cls.engine = Sampled(tok, "</think>\n\nhello", max_context=CTX)+ cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ cls.tmp = tempfile.TemporaryDirectory()+ cls.svc.shared_path = os.path.join(cls.tmp.name, "strata-x.shared-settings.json")+ cls.httpd = serve(cls.svc, port=0)+ cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"++ @classmethod+ def tearDownClass(cls):+ cls.httpd.shutdown()+ cls.httpd.server_close()+ cls.tmp.cleanup()++ def req(self, path, body, headers=None, raw=None):+ h = {"Content-Type": "application/json", **(headers or {})}+ r = urllib.request.Request(self.base + path, data=raw if raw is not None else json.dumps(body).encode(), headers=h)+ try:+ with urllib.request.urlopen(r, timeout=30) as resp:+ return resp.status, json.loads(resp.read())+ except urllib.error.HTTPError as e:+ with e:+ return e.code, json.loads(e.read())++ def chat(self, **extra):+ return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], **extra})++ def tearDown(self):+ self.svc.set_shared(None)++ def test_other_apps_get_the_chat_settings(self):+ d = {"temperature": 0.3, "top_p": 0.9, "top_k": 10, "seed": 7, "max_tokens": 77,+ "reasoning_effort": "low", "experimental_speed_projection": False}+ code, b = self.req("/settings", {"defaults": d})+ self.assertEqual(code, 200, b)+ self.assertTrue(b["shared"])+ self.assertTrue(os.path.exists(self.svc.shared_path))+ code, _ = self.chat() # a client that sets nothing+ self.assertEqual(code, 200)+ got = self.engine.last_sampling+ for k in ("temperature", "top_p", "top_k", "seed", "experimental_speed_projection"):+ self.assertEqual(got[k], d[k], k)+ self.assertEqual(self.engine.last_max_new, 77)+ code, _ = self.chat(temperature=0.9, max_tokens=5) # its own values win+ self.assertEqual(self.engine.last_sampling["temperature"], 0.9)+ self.assertEqual(self.engine.last_max_new, 5)+ r = self.svc.with_shared({"messages": []}, "openai")+ self.assertEqual(r["reasoning_effort"], "low")+ self.assertEqual(self.svc.with_shared({"reasoning_effort": "high"}, "openai")["reasoning_effort"], "high")+ self.assertEqual(self.svc.with_shared({}, "anthropic")["output_config"], {"effort": "low"})++ def test_off_again(self):+ self.req("/settings", {"defaults": {"temperature": 0.3}})+ code, b = self.req("/settings", {"defaults": None})+ self.assertEqual((code, b["shared"]), (200, False))+ self.assertFalse(os.path.exists(self.svc.shared_path))+ self.chat()+ self.assertNotIn("temperature", self.engine.last_sampling)++ def test_only_strata_s_own_page_may_set_them(self):+ code, _ = self.req("/settings", None, {"Content-Type": "text/plain"}, raw=b'{"defaults": {"temperature": 1}}')+ self.assertEqual(code, 415)+ code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://evil.example"})+ self.assertEqual(code, 403)+ code, b = self.req("/settings", {"defaults": {"temperature": 9}})+ self.assertEqual(code, 400)+ self.assertIn("temperature", b["error"]["message"])+ self.assertEqual(self.svc.shared, {})+ host = self.base.split("://", 1)[1]+ code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://" + host})+ self.assertEqual(code, 200)++ def test_they_need_the_key_when_one_is_set(self):+ self.svc.api_key = "secret"+ try:+ self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}})[0], 401)+ self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}},+ {"Authorization": "Bearer secret"})[0], 200)+ finally:+ self.svc.api_key = ""++class WebApp(unittest.TestCase):"""The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics."""diff --git a/serve/web/app.js b/serve/web/app.jsindex 776f09404..a9dc37e59 100644--- a/serve/web/app.js+++ b/serve/web/app.js@@ -655,7 +655,7 @@ function openDrawer(open) {$("drawer").dataset.open = String(open);$("drawer").setAttribute("aria-hidden", String(!open));$("scrim").hidden = !open;- if (open) loadDrawer();+ if (open) { loadDrawer(); loadShared(); }}function loadDrawer(s = settings) {for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking));@@ -664,8 +664,36 @@ function loadDrawer(s = settings) {$("s-show").setAttribute("aria-checked", String(!!s.show));$("s-esp").setAttribute("aria-checked", String(s.esp !== false));$("esp-row").hidden = !projectionLoaded();+ $("s-share").setAttribute("aria-checked", String(sharedOn));outputs();}+// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings)+let sharedOn = false;+async function loadShared() {+ try {+ const r = await fetch("/settings", {headers: headers()});+ if (r.ok) sharedOn = !!(await r.json()).shared;+ } catch (e) { /* an older server: the switch just stays off */ }+ $("s-share").setAttribute("aria-checked", String(sharedOn));+}+function sharedDefaults(s) {+ const d = {reasoning_effort: s.thinking, temperature: +s.temperature};+ if (+s.temperature > 0) Object.assign(d, {top_p: +s.top_p, top_k: +s.top_k});+ if (s.seed) d.seed = +s.seed;+ if (s.max) d.max_tokens = +s.max;+ if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false;+ return d;+}+async function saveShared(on, s) {+ const r = await fetch("/settings", {method: "POST", headers: headers(true),+ body: JSON.stringify({defaults: on ? sharedDefaults(s) : null})});+ if (!r.ok) {+ let msg = `HTTP ${r.status}`;+ try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }+ throw new Error(msg);+ }+ sharedOn = !!(await r.json()).shared;+}// the engine was started with the experimental-speed-projection control vector (INFO cvec=...)function projectionLoaded() {const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0;@@ -684,15 +712,27 @@ for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $(for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs;$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true"));$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true"));+$("s-share").onclick = () => $("s-share").setAttribute("aria-checked", String($("s-share").getAttribute("aria-checked") !== "true"));$("s-reset").onclick = () => loadDrawer(DEFAULTS);-$("s-apply").onclick = () => {+$("s-apply").onclick = async () => {const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true");settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value,top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(),show: $("s-show").getAttribute("aria-checked") === "true",esp: $("s-esp").getAttribute("aria-checked") === "true"};store.set("sampling", settings);+ const share = $("s-share").getAttribute("aria-checked") === "true";openDrawer(false);+ if (share || sharedOn) {+ try {+ await saveShared(share, settings);+ toast("success", "Sampling saved", share ? "Other apps (omp, API clients) use these settings from their next request."+ : "Other apps use their own settings again.");+ } catch (e) {+ toast("error", "Saved here, but not for other apps", e.message, 6000);+ }+ return;+ }toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : "");};$("sampling-btn").onclick = () => openDrawer(true);diff --git a/serve/web/index.html b/serve/web/index.htmlindex 150479a93..e7ac69ab8 100644--- a/serve/web/index.html+++ b/serve/web/index.html@@ -195,6 +195,9 @@<div class="toggle-row" id="esp-row" hidden><span>Experimental speed projection<br><span class="muted small">theengine's control vector; off = the stock model. Switching reads the chat again once</span></span><button class="st-toggle" id="s-esp" role="switch" aria-checked="true" aria-label="Experimental speed projection"></button></div>+ <div class="toggle-row"><span>Use for other apps too<br><span class="muted small">omp and other API clients get+ these settings for anything they don't set themselves</span></span>+ <button class="st-toggle" id="s-share" role="switch" aria-checked="false" aria-label="Use for other apps too"></button></div><div class="drawer-actions"><button class="st-btn st-btn--secondary" id="s-reset" type="button">Reset</button><button class="st-btn st-btn--primary" id="s-apply" type="button">Apply</button>