From b92b78b09296685bc4c5f92f3a0f80a7722164b0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:09:27 +0200 Subject: [PATCH 01/10] serve: a malformed "tools" value is a 400, not a dropped connection (#592) openai_to_messages / anthropic_to_messages check that tools is a list of named tool objects (a JSON-string list is decoded, as for messages) and raise ValueError otherwise; the MCP name set skips non-objects too. --- serve/frontend.py | 27 ++++++++++++++++++++++++--- serve/server.py | 2 +- serve/test_server.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 07e369d0..007d06df 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -160,6 +160,27 @@ def _object_list(value, name: str) -> list[dict]: return value +def _tool_list(value, wrapper: str | None) -> list[dict]: + """#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape + {"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or + in the Anthropic shape {"name": ...} (`wrapper` None). A value that is not (a string such as "auto", a list of + names, an object without a name) is a ValueError - a 400 naming the field - where it used to take the request + thread down with no reply at all. No value (or an empty one) is no tools, as always.""" + if not value: + return [] + shape = ('{"type": "function", "function": {"name": ..., "parameters": {...}}}' if wrapper else + '{"name": ..., "input_schema": {...}}') + try: + tools = _object_list(value, "tools") + except ValueError: + raise ValueError(f"tools must be a list of tool objects, each {shape}") from None + for i, t in enumerate(tools): + fn = t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t + if not isinstance(fn, dict) or not isinstance(fn.get("name"), str) or not fn["name"]: + raise ValueError(f"tools[{i}] has no name: each tool must be {shape}") + return tools + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -182,8 +203,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) out["tool_calls"] = calls messages.append(out) - tools = [t.get("function", t) if isinstance(t, dict) and t.get("type") == "function" else t - for t in req.get("tools") or []] or None + tools = [t.get("function", t) if t.get("type") == "function" else t + for t in _tool_list(req.get("tools"), "function")] or None kwargs = {} # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} @@ -233,7 +254,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d out["tool_calls"] = calls messages.append(out) tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})} - for t in req.get("tools") or []] or None + for t in _tool_list(req.get("tools"), None)] or None kwargs = {} # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; # "output_config": {"effort": "low" | "medium" | "high"} diff --git a/serve/server.py b/serve/server.py index 46e3fc36..606bad5d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2419,7 +2419,7 @@ def make_handler(svc: Service): svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) - own = {t.get("name") for t in tools or []} + own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence if use_mcp: if not self._own_page("MCP tools can be used"): # tools run with the user's rights on this PC return diff --git a/serve/test_server.py b/serve/test_server.py index 60a19269..51101e69 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -499,6 +499,36 @@ class ClientShapes(unittest.TestCase): self.assertEqual(status, 400, b) self.assertIn("messages must be a list of objects", b["error"]["message"]) + def test_malformed_tools_are_a_400(self): + # #592: a "tools" value that is not a list of named tool objects is a 400 naming the field, on both APIs, + # not a dropped connection (an AttributeError/TypeError in the request thread) + msgs = [{"role": "user", "content": "hi"}] + bad = ("auto", ["get_weather"], [{"description": "no name"}], {"name": "x"}, + [{"type": "function", "function": "get_weather"}], [{"type": "function", "function": {"name": ""}}]) + for path in ("/v1/chat/completions", "/v1/messages"): + for tools in bad: + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 400, b) + self.assertIn("tools", b["error"]["message"]) + status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 8, "messages": msgs}) + self.assertEqual(status, 200, b) # the server goes on + + def test_well_formed_tools_still_work(self): + msgs = [{"role": "user", "content": "hi"}] + fn = {"name": "get_weather", "description": "the weather", "parameters": {"type": "object", "properties": {}}} + for path, tools in (("/v1/chat/completions", [{"type": "function", "function": fn}]), + ("/v1/chat/completions", [fn]), # the bare shape some clients send + ("/v1/chat/completions", json.dumps([{"type": "function", "function": fn}])), + ("/v1/chat/completions", []), ("/v1/chat/completions", None), + ("/v1/messages", [{"name": "get_weather", "input_schema": {"type": "object"}}]), + ("/v1/messages", [])): + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 200, b) + if tools: + self.assertIn("get_weather", self.prompt_text()) + def test_vision_temp_image_removed_when_the_pipe_fails(self): # #352: the temporary image goes even when the encoder's pipe raises from serve.server import Vision From e294e0109b02c3c4fece855764d56cc186c3e3d5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:13:28 +0200 Subject: [PATCH 02/10] setup: running it again keeps the run config's keys it does not write (#629) A re-run for an installed model (another --context, say) rewrote strata-.json from scratch and dropped the user's sampling, mcp_servers, mcp and other blocks. Setup now carries over every key it does not write (and env/vision entries of the user's own, such as a Q8_0 mmproj), keeps the earlier file as strata-.json.bak and says what it kept and which hand-added engine options it did not. A copy set up like an earlier install carries them over from that install's config. A first install writes the same config as before. --- docs/INSTALL.md | 6 +- setup.py | 84 ++++++++++++++++++++++- tools/test_setup_config.py | 135 +++++++++++++++++++++++++++++++++++++ 3 files changed, 223 insertions(+), 2 deletions(-) create mode 100644 tools/test_setup_config.py diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 7af3a3e8..7f32e991 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -145,7 +145,11 @@ says so and starts the engine you had. kept, only their names. Another browser or a private window starts empty; clearing the site's data deletes them. - **How the model starts:** `strata-.json` in the Strata folder (context, GPUs, host, API key, ...), written by setup; next to it `run-.bat` / `.sh`, the log `strata-.log` and, when you use "Use for other - apps too", `strata-.shared-settings.json`. + apps too", `strata-.shared-settings.json`. Running setup again for the same model (another context, say) + rewrites the keys setup writes (`exe`, `args`, `port`, `gpu`, `host`, `api_key`, `vision`, ...) and keeps the + ones you added (`sampling`, `mcp_servers`, `mcp`, `cors_origins`, ...); the earlier file is kept as + `strata-.json.bak` (0.1.39). Engine options you added to `"args"` by hand are not carried over: setup names + them, and you add them again. - **The model files** (`models/`, `packs/`, `mtp/`, 70-120 GB): in **`Strata-data` next to the Strata folder**, or wherever `--data-dir` put them. - **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on diff --git a/setup.py b/setup.py index bc5cdd30..3093c8eb 100644 --- a/setup.py +++ b/setup.py @@ -2369,6 +2369,86 @@ def write_config(path: Path, cfg: dict): os.replace(tmp, path) +# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a +# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again +SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", + "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision"}) +SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_RESIDENT_PIN"}) # the "env" entries setup writes +SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) + + +def carry_over(old: dict, cfg: dict) -> list[str]: + """#629: setup run again for an installed model keeps what the user added to its run config: every key setup does + not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write + plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; + the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses + those): `args_dropped` names them.""" + kept = [] + for k, v in old.items(): + if k not in SETUP_KEYS and k not in cfg: + cfg[k] = v + kept.append(k) + env = {k: v for k, v in (old.get("env") or {}).items() if k not in SETUP_ENV and k not in (cfg.get("env") or {})} \ + if isinstance(old.get("env"), dict) else {} + if env: + cfg["env"] = {**(cfg.get("env") or {}), **env} + kept += [f"env {k}" for k in env] + ov, nv = old.get("vision"), cfg.get("vision") + if isinstance(ov, dict) and isinstance(nv, dict): + for k, v in ov.items(): + if k not in SETUP_VISION and k not in nv: + nv[k] = v + kept.append(f"vision {k}") + mm = ov.get("mmproj") # a file of the user's own: not the one setup downloads + if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): + nv["mmproj"] = mm + kept.append("vision mmproj") + return kept + + +def args_dropped(old: dict, cfg: dict) -> list[str]: + """#629: the engine options of the earlier run config that the new one has no more (by flag name): options added + by hand, which a setup run does not carry over - the start of the line that names them.""" + def flags(c): + a = c.get("args") if isinstance(c.get("args"), list) else [] + return [str(x) for x in a if str(x).startswith("--")] + new = set(flags(cfg)) + return list(dict.fromkeys(f for f in flags(old) if f not in new)) + + +def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: + """#629: setup's run config, written over an earlier one for the same model without losing what the user added + to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as + strata-.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when + this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" + old_path = cfg_path if cfg_path.is_file() else source + old = None + if old_path is not None and old_path.is_file(): + try: + old = json.loads(old_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + pass + if not isinstance(old, dict): + old = None + kept = carry_over(old, cfg) if old is not None else [] + bak = None + if cfg_path.is_file() and old != cfg: + bak = cfg_path.with_name(cfg_path.name + ".bak") + try: + shutil.copyfile(cfg_path, bak) + except OSError as e: + warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})") + bak = None + write_config(cfg_path, cfg) + if kept: + ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept)) + if bak is not None: + dropped = args_dropped(old, cfg) if old is not None else [] + say(f" the earlier run config is kept as {bak.name}" + ( + f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}" + if dropped else "")) + + def readable_config(path: Path) -> bool: """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" text = None @@ -3010,6 +3090,7 @@ def main() -> int: if a.update: # #475: UPDATE.bat / update.sh - never starts the model return update_install(have, a) explicit = a.setup or a.model or a.family or a.check or a.no_start + adopted = None # #629: the earlier install this copy is set up like if not have and not explicit: # a new copy of Strata (an update unzipped elsewhere): set it prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here if prev is not None: @@ -3018,6 +3099,7 @@ def main() -> int: say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " "copy the same way - the model files are reused, nothing big is downloaded.") a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] + adopted = prev a.kv = a.kv or ch["kv"] a.vision = a.vision or ch["vision"] a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] @@ -3664,7 +3746,7 @@ def main() -> int: import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) - write_config(cfg_path, cfg) + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) script = write_run_script(tag, cfg_path, port) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it if cal is None and not hip and not a.no_start and not a.yes and ask( diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py new file mode 100644 index 00000000..ada27efb --- /dev/null +++ b/tools/test_setup_config.py @@ -0,0 +1,135 @@ +"""Tests for what setup keeps in a model's run config when it runs again (#629), the browser choice (#609) and the +image-token flag (#625). Every outside effect is mocked (tools/test_setup_golden.py's install()). + + python -m unittest tools.test_setup_config +""" +from __future__ import annotations + +import contextlib +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 + + +def quiet(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return fn(*args, **kw), out.getvalue() + + +USER = {"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, + "mcp_servers": {"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}}, + "mcp": {"timeout_s": 60, "max_result_chars": 16000, "max_rounds": 8}, + "cors_origins": ["http://localhost:3000"], "reasoning_effort": "low"} + + +class CarryOver(unittest.TestCase): + """#629: setup run again (a different --context) keeps the keys it does not write and keeps the old file as .bak.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_user_keys_survive_a_rerun(self): + code, out, first, _ = self.run_setup("--context", "65536") + self.assertEqual(code, 0, out) + old = {**first, **USER, "args": first["args"] + ["--hand-option", "7"]} + code, out, cfg, _ = self.run_setup("--context", "131072", configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + for k, v in USER.items(): + self.assertEqual(cfg[k], v, k) + a = cfg["args"] + self.assertEqual(a[a.index("--max-context") + 1], "131072") # the new choice is used + self.assertNotIn("--hand-option", a) # setup chooses the engine options... + self.assertIn("kept from your earlier strata-q2_0.json: sampling, mcp_servers, mcp, cors_origins, " + "reasoning_effort", out) + self.assertIn("kept as strata-q2_0.json.bak", out) + self.assertIn("--hand-option", out) # ...and says which ones it did not keep + + def test_a_first_install_is_unchanged(self): + code, out, cfg, _ = self.run_setup() + self.assertEqual(code, 0, out) + self.assertNotIn("kept from", out) + self.assertNotIn(".bak", out) + self.assertFalse(set(cfg) - setup.SETUP_KEYS) # setup writes only its own keys + + def test_setup_keys_are_rewritten(self): + code, out, first, _ = self.run_setup() + old = {**first, "model_name": "renamed", "port": 9999, "draft_vocab": "en", "host": "0.0.0.0"} + code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["model_name"], first["model_name"]) + self.assertEqual(cfg["port"], first["port"]) + self.assertNotIn("host", cfg) # as before: --host is given to setup + self.assertEqual(cfg["draft_vocab"], "en") # kept by its own rule (saved_draft_vocab) + self.assertNotIn("kept from", out) + + def test_write_setup_config(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + mm = Path(d) / "mmproj-Q8_0.gguf" + mm.write_bytes(b"") + old = {"exe": "e", "args": ["--kv", "int8", "--threads", "8"], "sampling": {"temperature": 0.7}, + "env": {"STRATA_RESIDENT_PIN": "0", "MY_VAR": "1"}, + "vision": {"exe": "v", "mmproj": str(mm), "gpu": False, "max_tokens": 300, "min_tokens": 64}} + p.write_text(json.dumps(old), encoding="utf-8") + new = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, "max_tokens": 300}} + _, out = quiet(setup.write_setup_config, p, new) + got = json.loads(p.read_text(encoding="utf-8")) + self.assertEqual(got["sampling"], {"temperature": 0.7}) + self.assertEqual(got["env"], {"MY_VAR": "1"}) # setup's own env entry is setup's to write + self.assertEqual(got["vision"]["mmproj"], str(mm)) # a Q8_0 mmproj of the user's own (#625) + self.assertEqual(got["vision"]["min_tokens"], 64) + self.assertEqual(got["exe"], "e2") + self.assertEqual(json.loads((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8")), old) + self.assertIn("--threads", out) + # the same again: nothing changes, so no new copy is made + (Path(d) / "strata-x.json.bak").unlink() + again = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, + "max_tokens": 300}} + quiet(setup.write_setup_config, p, again) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), got) + + def test_an_unreadable_earlier_config_is_replaced_with_a_copy(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + p.write_text("{cut off", encoding="utf-8") + quiet(setup.write_setup_config, p, {"exe": "e", "args": []}) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": []}) + self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off") + + def test_a_missing_mmproj_is_not_carried(self): + old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}} + new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}} + self.assertEqual(setup.carry_over(old, new), []) + self.assertEqual(new["vision"]["mmproj"], "/data/mmproj-BF16.gguf") + + def test_a_copy_set_up_like_the_last_one_keeps_them_too(self): + with tempfile.TemporaryDirectory() as d: + src = Path(d) / "other" / "strata-x.json" + src.parent.mkdir() + src.write_text(json.dumps({"exe": "old", "mcp_servers": {"a": {"command": "x"}}}), encoding="utf-8") + p = Path(d) / "strata-x.json" + quiet(setup.write_setup_config, p, {"exe": "new"}, src) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), + {"exe": "new", "mcp_servers": {"a": {"command": "x"}}}) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) # nothing here was replaced + + +if __name__ == "__main__": + unittest.main() From 9b6515b37cdf7adfffd19e26b3e239107f5bcc7a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:14:39 +0200 Subject: [PATCH 03/10] setup: --no-browser / "open_browser": false keeps the chat page from opening (#609, #631) --no-browser (on a start or at setup) saves "open_browser": false in the model's run config; start() and run-.bat/.sh then leave --open out, and the server ignores --open when the config says so (a start script written earlier still has it). --browser undoes it. Without the flag the config, the command and the script are as before. --- docs/INSTALL.md | 2 ++ serve/server.py | 4 +-- setup.py | 33 +++++++++++++------ tools/test_setup_config.py | 63 +++++++++++++++++++++++++++++++++++++ tools/test_setup_golden.py | 2 +- tools/test_setup_unsloth.py | 2 +- 6 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 7f32e991..e6f721d7 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -191,6 +191,8 @@ START-HERE.bat --port 8081 another port START-HERE.bat --gpu 1 another GPU (setup picks the one with the most VRAM) START-HERE.bat --gpus 0,2 several GPUs sharing the model START-HERE.bat --vram-reserve-mib 2048 leave 2 GB of VRAM free for other programs (remembered) +START-HERE.bat --no-browser do not open the chat page when the model is ready (remembered; + --browser undoes it) START-HERE.bat --setup --backend hip the AMD engine on a PC that also has an NVIDIA card START-HERE.bat --setup --host 0.0.0.0 --api-key reachable from other devices, with a key START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start diff --git a/serve/server.py b/serve/server.py index 606bad5d..5deeb9d0 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3027,8 +3027,8 @@ def main() -> int: "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(a.port) + "\" " "-Direction Inbound -Protocol TCP -LocalPort " + str(a.port) + " -Action Allow -Profile Private\n" " (and set this network to Private in Windows' network settings)", flush=True) - if a.open: - import webbrowser + if a.open and cfg.get("open_browser") is not False: # #609: the config's "open_browser": false wins (an older + import webbrowser # run-.bat still passes --open) webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/") # #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after # the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine). diff --git a/setup.py b/setup.py index 3093c8eb..e53d0b7f 100644 --- a/setup.py +++ b/setup.py @@ -2682,6 +2682,8 @@ def settings_summary(cfg: dict, port=None) -> str: srv = [f"{cfg.get('host', '127.0.0.1')}:{port or cfg.get('port', 8080)}"] if cfg.get("api_key"): srv.append("api key set") + if cfg.get("open_browser") is False: # #609 + srv.append("no browser") for k in ("gpu", "layer_split", "draft_vocab", "fit_max_tokens", "reasoning_budget_tokens", "anthropic_thinking"): if cfg.get(k) is not None: v = cfg[k] @@ -2710,8 +2712,9 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored cfg.update(keep) write_config(cfg_path, cfg) - ok("saved for this model: " + ", ".join("api key" if k == "api_key" else f"{k.replace('_', ' ')} {v}" - for k, v in keep.items())) + ok("saved for this model: " + ", ".join( + "api key" if k == "api_key" else ("the browser opens" if v else "no browser") if k == "open_browser" + else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) cfg_path.touch() # the most recently used model if "--mtp" in cfg["args"][:-1]: refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) @@ -2779,7 +2782,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ if g is not None: cfg = ensure_engine_for([g], cfg_path, cfg, yes) ok("GPU: " + gpu_name(g)) - if open_browser: + browser = open_browser and cfg.get("open_browser") is not False # #609: "open_browser": false, --no-browser + if browser: cmd.append("--open") gb = 0.0 if "--native" in cfg["args"]: @@ -2799,7 +2803,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ say(f" Starting {cfg.get('model_name', 'the model')}: it loads {size} into RAM and locks part of it for the " "GPU.") say(" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a") - say(" restart). That is normal: please wait and don't close this window - the browser opens when it is ready.") + say(" restart). That is normal: please wait and don't close this window - " + ( + "the browser opens when it is ready." if browser else "the server says when it is ready.")) say(" Later, closing this window stops the model.") say(" " + "-" * 100) for n, line in enumerate(textwrap.wrap(f"Settings ({cfg_path.name}): {settings_summary(cfg, port)}", 100, @@ -2944,9 +2949,10 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg -def write_run_script(model, cfg_path, port): +def write_run_script(model, cfg_path, port, open_browser=True): + """run-.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out.""" serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), - "--port", str(port), "--open"] + "--port", str(port)] + (["--open"] if open_browser else []) if WIN: script = ROOT / f"run-{model.lower()}.bat" script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + @@ -3028,6 +3034,11 @@ def main() -> int: ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") + ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, + help="do not open the chat page in the browser when the model is ready (for a harness or an app " + "that uses the API; remembered for this model, also in run-.bat/.sh)") + ap.add_argument("--browser", dest="browser", action="store_true", + help="open the chat page again when the model is ready (the default; undoes --no-browser)") ap.add_argument("--data-dir", help="where the model files go (~70-120 GB): default Strata-data next to this folder, " "remembered for every Strata folder on this PC") ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") @@ -3134,14 +3145,14 @@ def main() -> int: + ("keeps" if a.no_start else "starts with") + " the default settings") return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) if have and not (a.setup or a.model or a.family or a.check or a.no_start): if not a.build: update_installed_engine(a.prebuilt) if len(have) == 1: return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) say() for i, c in enumerate(have, 1): say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") @@ -3150,7 +3161,7 @@ def main() -> int: if pick <= len(have): return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) # ---- 1. the PC step(1, "checking your PC") @@ -3734,6 +3745,8 @@ def main() -> int: cfg["api_key"] = a.api_key if draft_vocab: cfg["draft_vocab"] = draft_vocab + if a.browser is not None: # #609: only when given (else an earlier choice is carried over) + cfg["open_browser"] = a.browser if vision != "none": cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} @@ -3747,7 +3760,7 @@ def main() -> int: cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) - script = write_run_script(tag, cfg_path, port) + script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it if cal is None and not hip and not a.no_start and not a.yes and ask( "Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy " diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py index ada27efb..a08bc3e4 100644 --- a/tools/test_setup_config.py +++ b/tools/test_setup_config.py @@ -11,6 +11,7 @@ import json import sys import tempfile import unittest +import unittest.mock from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -131,5 +132,67 @@ class CarryOver(unittest.TestCase): self.assertFalse((Path(d) / "strata-x.json.bak").exists()) # nothing here was replaced +class NoBrowser(unittest.TestCase): + """#609 (#631): --no-browser keeps the chat page from opening: "open_browser": false in the run config, no --open + on the start's server command or in run-.bat/.sh. Without the flag nothing changes.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_at_setup(self): + code, out, cfg, _ = self.run_setup("--no-browser") + self.assertEqual(code, 0, out) + self.assertIs(cfg["open_browser"], False) + code, out, cfg, _ = self.run_setup() + self.assertNotIn("open_browser", cfg) # not given: the config as before + # setup run again without the flag keeps the choice (#629); --browser undoes it + code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", {"open_browser": False})]) + self.assertIs(cfg["open_browser"], False) + code, out, cfg, _ = self.run_setup("--browser", configs=[("strata-q2_0.json", {"open_browser": False})]) + self.assertIs(cfg["open_browser"], True) + + def test_run_script(self): + with tempfile.TemporaryDirectory() as d, unittest.mock.patch.object(setup, "ROOT", Path(d)): + text = lambda p: p.read_text(encoding="utf-8") # noqa: E731 + self.assertIn('"--open"', text(setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080))) + script = setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080, False) + self.assertNotIn("--open", text(script)) + self.assertIn('"--port" "8080"', text(script)) + + def start_cmd(self, cfg, keep=None): + with tempfile.TemporaryDirectory() as d: + exe = Path(d) / "strata.exe" + exe.write_bytes(b"") + p = Path(d) / "strata-q2_0.json" + p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True, **cfg})) + call = unittest.mock.Mock(return_value=0) + with unittest.mock.patch.object(setup, "gpus", lambda: self.found), \ + unittest.mock.patch.object(setup, "is_wsl", lambda: False), \ + unittest.mock.patch.object(setup, "ensure_engine_for", lambda cards, path, c, yes: c), \ + unittest.mock.patch.object(setup.subprocess, "call", call): + _, out = quiet(setup.start, p, None, None, True, True, None, keep) + return call.call_args[0][0], out, json.loads(p.read_text()) + + def test_on_a_start(self): + cmd, out, _ = self.start_cmd({}) + self.assertIn("--open", cmd) # the default, as before + self.assertIn("the browser opens when it is ready", out) + cmd, out, _ = self.start_cmd({"open_browser": False}) + self.assertNotIn("--open", cmd) + self.assertNotIn("the browser opens", out) + self.assertIn("no browser", out) # the Settings line says so + cmd, out, saved = self.start_cmd({}, {"open_browser": False}) # START-HERE --no-browser: kept from now on + self.assertNotIn("--open", cmd) + self.assertIs(saved["open_browser"], False) + self.assertIn("saved for this model: no browser", out) + cmd, out, saved = self.start_cmd({"open_browser": False}, {"open_browser": True}) + self.assertIn("--open", cmd) + self.assertIs(saved["open_browser"], True) + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index 054c1c14..8cee0bfe 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -113,7 +113,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "run", lambda *a, **k: None), mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: t / f"run-{tag}.bat"), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: t / f"run-{tag}.bat"), mock.patch.object(setup, "saved_calibration", lambda cfg: None), mock.patch.object(setup, "calibrate_config", mock.Mock(side_effect=AssertionError("calibrated"))), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index a010b5e8..804a5c43 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -174,7 +174,7 @@ class Main(unittest.TestCase): mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: self.t / f"start-{tag}.bat"), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), mock.patch.object(setup, "saved_calibration", lambda cfg: None), mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), From 021f544c60d92d72b2bdca9d05e37f5460e8d990 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:15:55 +0200 Subject: [PATCH 04/10] setup: --vision-tokens N, the most image tokens a picture becomes (#625) Kept in the run config's vision.max_tokens (the server already passes it to the encoder); a setup run again keeps it for the same encoder device. More than the default is allowed with a note on the encode time. Without the flag the config is as before. DETAILS.md: vision.mmproj can point to a Q8_0 mmproj of this model. --- docs/DETAILS.md | 11 +++++++++ setup.py | 37 +++++++++++++++++++++++++++++- tools/test_setup_config.py | 46 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9d2cc704..aeef21da 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -748,6 +748,17 @@ helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your st A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps do on every turn, is encoded only once. +**More image tokens (0.1.39, #625):** `--vision-tokens N` at setup (`START-HERE.bat --setup --vision cpu +--vision-tokens 768`) sets the most tokens a picture becomes - `"max_tokens"` in the `"vision"` section of +`strata-.json`, which you can also edit by hand. More tokens keep more detail (small text, charts, screenshots) +and take longer to encode, on the CPU most of all; a setup run again keeps the value. + +**A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for +example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library +reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads +the BF16 file, and a setup run again keeps a file of your own that still exists. We have not measured its accuracy +against BF16 yet; numbers are welcome in #625. + **A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower `--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The diff --git a/setup.py b/setup.py index e53d0b7f..8dc7c212 100644 --- a/setup.py +++ b/setup.py @@ -2835,6 +2835,31 @@ def saved_draft_vocab(cfg_path: Path) -> str | None: return v if v in DRAFT_VOCABS else None +def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int: + """#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an + earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's + default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap.""" + default = VISION[vision]["max_tokens"] + if asked is None and earlier is not None: + try: + v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision") + except (OSError, ValueError, AttributeError): + v = None + mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None + if isinstance(mt, int) and mt > 0 and mt != default: + asked = mt + if asked is None: + return default + note = "" + if vision == "cpu" and asked > default: + note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at " + "1,024 than at 300)") + elif asked > VISION["gpu"]["max_tokens"]: + note = " - more than the encoder's default needs more VRAM and context per picture" + ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}") + return asked + + DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit @@ -3020,6 +3045,10 @@ def main() -> int: "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--vision-tokens", type=int, metavar="N", + help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " + "the CPU): more reads small text and charts better, and takes longer to encode; remembered " + "for this model") ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") @@ -3081,6 +3110,8 @@ def main() -> int: a = ap.parse_args() if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32") + if a.vision_tokens is not None and a.vision_tokens < 1: + ap.error("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768") if a.vram_reserve_mib is not None and a.vram_reserve_mib < 0: ap.error("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048") if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) @@ -3748,10 +3779,14 @@ def main() -> int: if a.browser is not None: # #609: only when given (else an earlier choice is carried over) cfg["open_browser"] = a.browser if vision != "none": + old_cfg = ROOT / f"strata-{tag.lower()}.json" + vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), - "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} + "gpu": vision == "gpu", "max_tokens": vt} if vision == "cpu": cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) + elif a.vision_tokens is not None: + warn("--vision-tokens: images are off for this model, so it is not used") cfg_path = ROOT / f"strata-{tag.lower()}.json" cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now if cal is not None: diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py index a08bc3e4..cd297645 100644 --- a/tools/test_setup_config.py +++ b/tools/test_setup_config.py @@ -194,5 +194,51 @@ class NoBrowser(unittest.TestCase): self.assertIs(saved["open_browser"], True) +class VisionTokens(unittest.TestCase): + """#625: --vision-tokens N sets the config's vision.max_tokens (the most image tokens a picture becomes); a setup + run again keeps it for the same encoder device; without it the device's default, as before.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_the_flag(self): + code, out, cfg, _ = self.run_setup("--vision", "cpu") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["vision"]["max_tokens"], 300) # the default, as before + self.assertNotIn("--vision-tokens", out) + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["vision"]["max_tokens"], 768) + self.assertIn("up to 768 image tokens", out) + self.assertIn("longer to encode", out) # a note, not a cap + code, out, cfg, _ = self.run_setup("--vision", "gpu", "--vision-tokens", "2048") + self.assertEqual(cfg["vision"]["max_tokens"], 2048) + self.assertIn("more VRAM", out) + + def test_kept_when_setup_runs_again(self): + code, out, first, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") + old = [("strata-q2_0.json", first)] + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--context", "65536", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 768) + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "300", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 300) # given again: the new value + code, out, cfg, _ = self.run_setup("--vision", "gpu", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 1024) # another device: its own default + + def test_refused_and_unused(self): + with contextlib.redirect_stderr(io.StringIO()) as err: + code, out, cfg, _ = self.run_setup("--vision-tokens", "0") + self.assertEqual(code, 2) + self.assertIn("--vision-tokens takes a number", err.getvalue()) + code, out, cfg, _ = self.run_setup("--vision", "no", "--vision-tokens", "768") + self.assertEqual(code, 0, out) + self.assertNotIn("vision", cfg) + self.assertIn("images are off", out) + + if __name__ == "__main__": unittest.main() From c16f31f850342b285bd8f6e611f0df99ca621695 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:21:55 +0200 Subject: [PATCH 05/10] serve: a literal / in a message is encoded as text (#537) The tokenizer matches and as their special tokens even in plain text (type 4, as llama.cpp does), so a user quoting "" handed the model a real end-of-reasoning token and the answer came back empty. Before the template is rendered the tags in message text (user, tool, system, assistant history, tool call arguments, tool descriptions) are swapped for private-use marks; after it, those spans are encoded as ordinary text (Tokenizer.encode's new plain= spans), the template's own markers stay special. An assistant turn that opens with its own ... block keeps that block. A prompt without the tags is encoded exactly as before; count_tokens uses the same path. --- serve/frontend.py | 76 ++++++++++++++++++++++++++++++++++++++ serve/server.py | 25 +++++++++---- serve/test_server.py | 78 +++++++++++++++++++++++++++++++++++++++ tools/strata_tokenizer.py | 13 +++++-- 4 files changed, 181 insertions(+), 11 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 007d06df..02a1d2f9 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas o from __future__ import annotations import json +import re import uuid from dataclasses import dataclass, field from pathlib import Path @@ -135,6 +136,81 @@ def images_of(messages: list[dict]) -> list[str]: for item in m["content"] if item.get("type") == "image"] +# #537: a literal / inside a message's text is plain text, not the model's reasoning markers. The +# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so +# a user quoting "" used to hand the model a real end-of-reasoning token. Before the template is rendered +# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. +THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} +THINK_MARKS = {v: k for k, v in THINK_TAGS.items()} + + +def _mark(text: str) -> str: + for tag, mark in THINK_TAGS.items(): + text = text.replace(tag, mark) + return text + + +def _mark_deep(v): + if isinstance(v, str): + return _mark(v) + if isinstance(v, dict): + return {k: _mark_deep(x) for k, x in v.items()} + if isinstance(v, list): + return [_mark_deep(x) for x in v] + return v + + +def _has_tag(v) -> bool: + if isinstance(v, str): + return "" in v or "" in v + if isinstance(v, dict): + return any(_has_tag(x) for x in v.values()) + if isinstance(v, list): + return any(_has_tag(x) for x in v) + return False + + +def mark_think_literals(messages: list[dict], tools: list[dict] | None): + """#537: (messages, tools) with every literal / in their text swapped for THINK_TAGS' marks, and + whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). + An assistant message whose content opens with a whole ... block (clients that send the reasoning + inline) keeps that one block as the model's markers, as before.""" + if not _has_tag(messages) and not _has_tag(tools): + return messages, tools, False + out = [] + for m in messages: + m = dict(m) + content = m.get("content") + for k, v in m.items(): + if k != "role": + m[k] = _mark_deep(v) + if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ + and "" in content: + i, j = content.index("") + len(""), content.index("") + m["content"] = content[:i] + _mark(content[i:j]) + "" + _mark(content[j + len(""):]) + out.append(m) + return out, _mark_deep(tools), True + + +_THINK_MARK_RE = re.compile("|".join(THINK_MARKS)) + + +def unmark_think_literals(prompt: str) -> tuple[str, list[tuple[int, int]]]: + """The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those + tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans).""" + out, spans, pos, n = [], [], 0, 0 + for m in _THINK_MARK_RE.finditer(prompt): + out.append(prompt[pos:m.start()]) + n += m.start() - pos + tag = THINK_MARKS[m.group(0)] + out.append(tag) + spans.append((n, n + len(tag))) + n += len(tag) + pos = m.end() + out.append(prompt[pos:]) + return "".join(out), spans + + def _late_system_to_user(messages: list[dict]) -> list[dict]: """The chat template takes a system message only at the start ("System message must be at the beginning"). Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user diff --git a/serve/server.py b/serve/server.py index 5deeb9d0..9ed8d7be 100644 --- a/serve/server.py +++ b/serve/server.py @@ -51,7 +51,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - images_of, openai_to_messages) + images_of, mark_think_literals, openai_to_messages, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve.winjob import contain # noqa: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 @@ -893,11 +893,14 @@ class ByteTokenizer: """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"] - def encode(self, text, parse_special=False): + ALWAYS = () # specials matched without parse_special (type 4, as ) + + def encode(self, text, parse_special=False, plain=()): out, i = [], 0 while i < len(text): for k, s in enumerate(self.SPECIALS): - if parse_special and text.startswith(s, i): + if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any( + a <= i < b for a, b in plain): out.append(256 + k) i += len(s) break @@ -1334,11 +1337,20 @@ class Service: "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + def encode_prompt(self, messages, tools, kwargs) -> list[int]: + """The request's prompt: the template rendered and tokenized. #537: a / written inside a + message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).""" + marked, marked_tools, changed = mark_think_literals(messages, tools) + prompt = self.template.render(marked, tools=marked_tools, **kwargs) + if not changed: + return self.tok.encode(prompt, parse_special=True) + prompt, plain = unmark_think_literals(prompt) + return self.tok.encode(prompt, parse_special=True, plain=plain) + def prepare(self, messages, tools, kwargs, max_new=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context.""" - prompt = self.template.render(messages, tools=tools, **kwargs) - ids = self.tok.encode(prompt, parse_special=True) + ids = self.encode_prompt(messages, tools, kwargs) self.embeddings.path = None images = images_of(messages) if images: @@ -2471,8 +2483,7 @@ def make_handler(svc: Service): 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, svc.anthropic_think_unasked) - prompt = svc.template.render(messages, tools=tools, **kw) - self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) + self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) def _anthropic(self, req): svc.load() diff --git a/serve/test_server.py b/serve/test_server.py index 51101e69..cb96d1f9 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -241,6 +241,84 @@ class ImageMarkers(unittest.TestCase): svc.embeddings.path.unlink(missing_ok=True) +class ThinkTokenizer(ByteTokenizer): + """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, + as the real tokenizer does (GGUF token type 4).""" + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LiteralThinkTags(unittest.TestCase): + """#537: a / written inside a message is text, not the model's reasoning markers: a quoted + "" no longer ends the model's reasoning before it starts. The template's own markers stay special.""" + + @classmethod + def setUpClass(cls): + cls.tok = ThinkTokenizer() + cls.svc = Service(MockEngine(cls.tok, "ok", max_context=CTX), cls.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.open, cls.close = (cls.tok.encode(t)[0] for t in ("", "")) + + def ids(self, messages, tools=None, **kw): + return self.svc.prepare(messages, tools, kw)[0] + + def old_ids(self, messages, tools=None, **kw): + return self.tok.encode(self.svc.template.render(messages, tools=tools, **kw), parse_special=True) + + def test_a_quoted_tag_in_a_user_message(self): + text = "Quote this exact literal string, then explain it: and " + ids = self.ids([{"role": "user", "content": text}]) + self.assertEqual(ids.count(self.close), 0) + self.assertEqual(ids.count(self.open), 1) # the generation prompt's own + self.assertEqual(ids[-2:], [self.open, ord("\n")]) + self.assertIn(text, self.tok.decode(ids)) # the text is all there, as text + self.assertEqual(ids.count(self.close), 0) + # thinking off: the template's empty block stays two specials, the user's tag is text + ids = self.ids([{"role": "user", "content": text}], enable_thinking=False) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (1, 1)) + + def test_without_a_tag_the_prompt_is_unchanged(self): + msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "1+1?"}, + {"role": "assistant", "content": "2", "reasoning_content": "easy"}, {"role": "user", "content": "x"}] + self.assertEqual(self.ids(msgs), self.old_ids(msgs)) + self.assertEqual(self.ids(msgs, enable_thinking=False), self.old_ids(msgs, enable_thinking=False)) + + def test_history_tool_results_and_tools(self): + msgs = [{"role": "user", "content": "go"}, + {"role": "assistant", "content": "It wrote here.", "reasoning_content": "the tag", + "tool_calls": [{"function": {"name": "write", "arguments": {"text": "a b"}}}]}, + {"role": "tool", "content": "file has in it"}, + {"role": "user", "content": "why did you write "}] + tools = [{"name": "write", "description": "writes text (may contain )", "parameters": {}}] + ids = self.ids(msgs, tools) + # the template's markers: the history turn's ... and the generation prompt's + self.assertEqual((ids.count(self.open), ids.count(self.close)), (2, 1)) + text = self.tok.decode(ids) + for part in ("It wrote here.", "the tag", "a b", "file has in it", + "why did you write ", "may contain "): + self.assertIn(part, text) + + def test_a_client_that_sends_the_reasoning_inline(self): + # an assistant turn whose content opens with its own ... block keeps that block's markers + msgs = [{"role": "user", "content": "hi"}, + {"role": "assistant", "content": "\nplan: say hello\n\n\nHello, is a tag."}, + {"role": "user", "content": "again"}] + ids = self.ids(msgs) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (3, 2)) # template's + the inline block's + self.assertIn("Hello, is a tag.", self.tok.decode(ids)) + + def test_the_real_tokenizer_reads_the_tag_as_text(self): + import strata_tokenizer as ST + b2u = ST.bytes_to_unicode() + tokens = [b2u[b] for b in range(256)] + ["", "", "<|im_end|>"] + tok = ST.Tokenizer(tokens, [], [1] * 256 + [4, 4, 3]) + text = "say now<|im_end|>" + self.assertEqual(tok.encode(text, parse_special=True), [*b"say ", 257, *b" now", 258]) + start = text.index("") + plain = tok.encode(text, parse_special=True, plain=[(start, start + len(""))]) + self.assertEqual(plain, [*b"say now", 258]) # the tag as text, im_end still special + + class StatusNeedsTheKey(unittest.TestCase): """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index c14492cb..8b794191 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -213,18 +213,21 @@ class Tokenizer: out.append(i) return out - def _encode_matching(self, text: str, pat) -> list[int]: + def _encode_matching(self, text: str, pat, plain=()) -> list[int]: """Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. The split happens on the RAW text, before the byte mapping, because a special token's string is a literal to match rather than bytes to decompose. Everything between the matches is tokenized - normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. + normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts + inside one of the `plain` (start, end) spans is left to the text around it (#537). """ if pat is None: return self._encode_plain(text) out: list[int] = [] pos = 0 for m in pat.finditer(text): + if plain and any(a <= m.start() < b for a, b in plain): + continue if m.start() > pos: out.extend(self._encode_plain(text[pos:m.start()])) out.append(self.special_tokens[m.group(0)]) @@ -233,13 +236,15 @@ class Tokenizer: out.extend(self._encode_plain(text[pos:])) return out - def encode(self, text: str, parse_special: bool = False) -> list[int]: + def encode(self, text: str, parse_special: bool = False, plain=()) -> list[int]: """Tokenize `text`. `parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 USER_DEFINED ones such as `` are matched either way. See the note in `__init__`. + `plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a + `` quoted in a message (#537) - and are tokenized with the text around them. """ - return self._encode_matching(text, self._special_re if parse_special else self._always_re) + return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain) def token_bytes(self, i: int) -> bytes: """The raw bytes of one token (a multi-byte character can be split across tokens).""" From 9eceb375ab088cc2febf190eda9bcdd96a9a393e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:26:01 +0200 Subject: [PATCH 06/10] serve + engine: opt-in "effort_position": "end" keeps the cached conversation when the effort changes (#458) The effort's instruction is the first thing the template renders, so a request that only changes reasoning_effort (or turns thinking off) read the whole prompt again. With "effort_position": "end" in the run config the server renders every prompt's start as the default effort's and puts a low/medium effort in a short system turn right before the answer (thinking off: just the template's empty thinking block); the rendering is template-agnostic (history + turn + the generation prompt). Engine: --tail-role-token ID (default -1, off) moves the turn checkpoint in front of such a trailing turn, so it holds the conversation and not the effort text; INFO reports tail_role_token. The server passes the id of "system" only when the engine binary knows the flag, and says so when it does not. Without the key nothing changes: the same prompt ids, no flag. --- docs/DETAILS.md | 8 +++ serve/server.py | 64 ++++++++++++++++++++++- serve/test_server.py | 106 +++++++++++++++++++++++++++++++++++++++ src/program/generate.cpp | 21 +++++++- 4 files changed, 195 insertions(+), 4 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index aeef21da..2ea4641b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -473,6 +473,14 @@ print(r.choices[0].message.content) part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the + first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for + a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders + every request's prompt start as the default effort's and puts a `low` / `medium` effort in a short system turn + right before the answer (no thinking: the empty thinking block, as always); the engine (0.1.39+, which the server + checks) keeps its checkpoint in front of that turn, so the next request reuses the conversation whatever its + effort. The default (`"start"`) prompt is unchanged. The model sees a level that is not the default in another + place than it was trained with; how well it follows it there is not measured yet. - **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short diff --git a/serve/server.py b/serve/server.py index 9ed8d7be..0c2c65b2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -58,6 +58,13 @@ from serve.structured import StructuredOutputError, prepare_format, validated_js IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" +# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the +# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top +EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" +EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " + "conclusion without unnecessary elaboration.", + "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " + "elaboration."} VISION_START = "<|vision_start|>" # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" @@ -778,6 +785,31 @@ def gpu_list(cfg: dict) -> list[int]: return [int(str(x).strip()) for x in items if str(x).strip() != ""] +def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None: + """#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so + the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the + default) or the engine is too old for it (said once; the prompt stays the default one). ValueError for a value + other than "start" / "end".""" + pos = cfg.get("effort_position", "start") + if pos not in ("start", "end"): + raise ValueError(f'"effort_position" must be "start" (the default) or "end", not {pos!r}') + if pos == "start": + return None + try: + with open(exe, "rb") as f: + known = b"--tail-role-token" in f.read() + except OSError: + known = False + role = tok.encode("system", parse_special=True) + if not known or len(role) != 1: + print("[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning " + "effort stays at the top of the prompt", flush=True) + return None + print("[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so " + "changing it keeps the cached conversation", flush=True) + return ["--tail-role-token", str(role[0])] + + def engine_silence_s(cfg: dict) -> float: """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0.""" @@ -958,6 +990,9 @@ class Service: 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) + # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system + # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation + self.effort_end = False # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that # matters); empty = no CORS headers at all, as before self.cors_origins: list[str] = [] @@ -1337,11 +1372,29 @@ class Service: "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + def render_prompt(self, messages, tools, kwargs) -> str: + """The template rendered. #458: with `effort_end`, a request with a non-default effort (low, medium or no + thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache + keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's + empty thinking block). The engine (--tail-role-token) checkpoints in front of that turn.""" + effort = kwargs.get("reasoning_effort") + off = kwargs.get("enable_thinking") is False + if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")): + return self.template.render(messages, tools=tools, **kwargs) + base = {k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base) + full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs) + mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs) + if not full.startswith(mine): # a template this cannot take apart: rendered as asked + return full + tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"])) + return history + tail + full[len(mine):] + def encode_prompt(self, messages, tools, kwargs) -> list[int]: """The request's prompt: the template rendered and tokenized. #537: a / written inside a message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).""" marked, marked_tools, changed = mark_think_literals(messages, tools) - prompt = self.template.render(marked, tools=marked_tools, **kwargs) + prompt = self.render_prompt(marked, marked_tools, kwargs) if not changed: return self.tok.encode(prompt, parse_special=True) prompt, plain = unmark_think_literals(prompt) @@ -2933,7 +2986,12 @@ def main() -> int: silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start except ValueError as e: raise SystemExit(f"[strata] config {e}") - engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) + try: + effort_end = effort_end_args(cfg, exe, tok) # #458 + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), + env=env, lazy=lazy) engine.silence_s = silence # an attribute of its own: restart() keeps it warn_tight_ram(engine.info.get("arena_mib")) note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], @@ -2941,6 +2999,7 @@ def main() -> int: if note: # #560 #516: before --open starts a browser on that card print(note, flush=True) else: + effort_end = None engine, vision, sampling_defaults = MockEngine(tok, a.script or [ "Thinking about it.\n\nHello from the mock engine."]), None, {} # the model's own chat template (exported with its tokenizer), else the original model's @@ -2988,6 +3047,7 @@ def main() -> int: if mode not in ("model", "on_request"): raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") svc.anthropic_think_unasked = mode == "model" + svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] diff --git a/serve/test_server.py b/serve/test_server.py index cb96d1f9..bf8a74a3 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -319,6 +319,112 @@ class LiteralThinkTags(unittest.TestCase): self.assertEqual(plain, [*b"say now", 258]) # the tag as text, im_end still special +class EffortAtTheEnd(unittest.TestCase): + """#458 (opt-in "effort_position": "end"): a non-default effort goes in a system turn right before the answer, so + a request that changes only the effort keeps the cached conversation. The engine's checkpoint rule is simulated + on the token ids (src/program/generate.cpp: the last <|im_start|>, and with --tail-role-token the one in front + of a trailing system turn); the default prompt does not change.""" + + TURN = 256 # the byte tokenizer's <|im_start|> + ROLE = ord("s") # "system"'s first byte stands for its token + + def setUp(self): + self.tok = ByteTokenizer() + self.svc = Service(MockEngine(self.tok, "ok", max_context=1 << 20), self.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + + def ids(self, messages, end, **kw): + self.svc.effort_end = end + return self.svc.encode_prompt(messages, None, kw) + + def checkpoint(self, ids, tail, resume=0): + """Where the engine checkpoints a prompt (the tokens before it), as generate.cpp's serve loop does.""" + turn_at = next((i for i in range(len(ids) - 1, resume, -1) if ids[i] == self.TURN), -1) + if turn_at > 0 and tail: + i = next((i for i in range(turn_at - 1, resume, -1) if ids[i] == self.TURN), None) + if i is not None and ids[i + 1] == self.ROLE: + turn_at = i + return ids[:turn_at] + + def session(self, requests, end, tail): + """The reused tokens of each request after the first: the longest earlier checkpoint it starts with.""" + checks, reused = [], [] + for messages, kw in requests: + ids = self.ids(messages, end, **kw) + reused.append(max([len(c) for c in checks if ids[:len(c)] == c], default=0)) + checks.append(self.checkpoint(ids, tail)) + return reused[1:] + + CHAT = [{"role": "system", "content": "You are a careful assistant. " * 40}, + {"role": "user", "content": "Explain the conversation cache. " * 20}] + REPLY = {"role": "assistant", "content": "It keeps the prompt's state. " * 20, "reasoning_content": "ok"} + NEXT = {"role": "user", "content": "And the checkpoints?"} + + def test_the_default_prompt_is_unchanged(self): + for kw in ({}, {"reasoning_effort": "xhigh"}): + self.assertEqual(self.ids(self.CHAT, True, **kw), self.ids(self.CHAT, False, **kw)) + self.assertEqual(self.ids(self.CHAT, True, **kw), + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + self.assertEqual(self.ids(self.CHAT, False, **kw), # off: every effort renders as before + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + + def test_the_trailing_turn(self): + text = self.tok.decode(self.ids(self.CHAT, True, reasoning_effort="low")) + self.assertTrue(text.endswith("<|im_end|>\n<|im_start|>system\nReasoning effort is set to low. Keep your " + "thinking brief and focused, moving directly to the conclusion without " + "unnecessary elaboration.<|im_end|>\n<|im_start|>assistant\n\n"), text[-300:]) + self.assertIn("Reasoning effort is set to xhigh", text) # the top stays the default's + text = self.tok.decode(self.ids(self.CHAT, True, enable_thinking=False)) + self.assertTrue(text.endswith("<|im_start|>assistant\n\n\n\n\n")) + self.assertNotIn("<|im_start|>system\nReasoning effort", text[-200:]) + default = self.ids(self.CHAT, True) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + ids = self.ids(self.CHAT, True, **kw) + head = len(self.checkpoint(default, False)) # all before the answer's turn + self.assertEqual(ids[:head], default[:head], kw) # the same prompt up to the answer + + def test_changing_the_effort_keeps_the_conversation(self): + efforts = [{}, {"reasoning_effort": "low"}, {"enable_thinking": False}, {"reasoning_effort": "medium"}, {}] + history = len(self.checkpoint(self.ids(self.CHAT, False), False)) + # at the top (the default): another effort differs a few tokens in, and the whole prompt is read again + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], False, False)[:2], [0, 0]) + # at the end, with the engine's rule: every request reuses the whole conversation + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], True, True), [history] * 4) + + def test_the_next_turn_reuses_the_checkpoint(self): + turn1, turn2 = self.CHAT, self.CHAT + [self.REPLY, self.NEXT] + low = {"reasoning_effort": "low"} + first = len(self.checkpoint(self.ids(turn1, True, **low), True)) + # the engine's rule: the next turn (the same effort) reuses the first turn's whole conversation + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, True), [first]) + # without it the checkpoint held the effort turn and the next turn reused nothing (what #458 measured) + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, False), [0]) + + def test_the_config(self): + from serve.server import effort_end_args + + class Tok: + def encode(self, text, parse_special=False): + return [8678] if text == "system" else [1, 2] + + with tempfile.TemporaryDirectory() as d: + new, old = Path(d) / "new.exe", Path(d) / "old.exe" + new.write_bytes(b"... --tail-role-token ID --serve: ...") + old.write_bytes(b"... --turn-token ID ...") + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertIsNone(effort_end_args({}, str(new), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "start"}, str(new), Tok())) + self.assertEqual(effort_end_args({"effort_position": "end"}, str(new), Tok()), + ["--tail-role-token", "8678"]) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(old), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(new), ByteTokenizer())) + self.assertIn("needs engine 0.1.39 or newer", out.getvalue()) + with self.assertRaises(ValueError): + effort_end_args({"effort_position": "middle"}, str(new), Tok()) + + class StatusNeedsTheKey(unittest.TestCase): """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a7c77d0e..4558100b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -413,6 +413,11 @@ struct Options { /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. int64_t turn_token = 248045; + /// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn + /// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, + /// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. + /// -1 = off (the checkpoint at the last <|im_start|>, as before). + int64_t tail_role_token = -1; /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) @@ -517,6 +522,8 @@ void usage() { " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" + " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" + " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" @@ -1248,6 +1255,7 @@ int main(int argc, char** argv) { else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); + else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); @@ -4986,7 +4994,7 @@ int main(int argc, char** argv) { "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n", + "conversation_cache_min_free_mib=%lld tail_role_token=%lld engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), @@ -4997,7 +5005,7 @@ int main(int argc, char** argv) { (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib); + (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -5597,6 +5605,15 @@ int main(int argc, char** argv) { if (o.prompt_cache > 0 && o.turn_token >= 0) for (int64_t i = n - 1; i > resume; --i) if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } + // #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the + // server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another + // effort, or the next turn of the chat - finds the conversation without it + if (turn_at > 0 && o.tail_role_token >= 0) + for (int64_t i = turn_at - 1; i > resume; --i) + if (ids[(size_t) i] == o.turn_token) { + if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i; + break; + } // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. From a9fe9236bf813816c9d684f3cff4a0651de22286 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:31:20 +0200 Subject: [PATCH 07/10] web: a Conversation cache card in the Monitor tab (#596) /metrics gains "conversation_cache": the parked conversations, their bytes, parks/restores/evictions and the last switch, read from the engine's own log lines ("conversation cache: parked/restored ...") from the start of its current run on; the budget and slots from its INFO line; and the prompt tokens reused in the last request and since the start. The card shows the parked slots and memory when --conversation-cache-mib is on, the reuse lines always, and how to turn parking on when it is off. --- docs/DETAILS.md | 5 +++ serve/server.py | 74 +++++++++++++++++++++++++++++++++++++++++++ serve/test_monitor.py | 63 ++++++++++++++++++++++++++++++++++++ serve/web/app.css | 6 ++++ serve/web/app.js | 34 ++++++++++++++++++++ serve/web/index.html | 12 +++++++ 6 files changed, 194 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2ea4641b..704bc8f5 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -596,6 +596,11 @@ INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be reported separately from Linux/CUDA evidence. +The web page's Monitor tab has a **Conversation cache** card (0.1.39, #596): the parked conversations against the +slots and the RAM budget, how many were parked, restored and evicted, and the last switch (read from the engine's +log), and for every setup how many prompt tokens the cache gave back - in the last request and since the start. +`/metrics` has the same under `"conversation_cache"`. + Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. They add host RAM, not another model or VRAM allocation. The byte budget also counts an incoming snapshot during a switch. After a restore, unchanged K/V pages can be diff --git a/serve/server.py b/serve/server.py index 0c2c65b2..26c81cc7 100644 --- a/serve/server.py +++ b/serve/server.py @@ -299,6 +299,76 @@ def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True) +class ConvCacheLog: + """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation + cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr, + which is the log): read on from where it was last read, from the start of the engine's current run.""" + EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)" + r"(?: evictions=(\d+))?") + DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)") + READ_MAX = 1 << 20 # at most the last MiB of new lines per read + + def __init__(self): + self.key, self.pos = None, 0 + self.reset() + + def reset(self): + self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None, + "last_tokens": None, "last_at": None} + + def poll(self, path, start) -> dict: + """The state after the log's new lines; `start` is where the engine's current run began in it.""" + if not path or start is None: + return dict(self.state) + if self.key != (path, start): # another start of the engine: its cache starts empty + self.key, self.pos = (path, start), start + self.reset() + try: + size = os.path.getsize(path) + if size < self.pos: # the log was emptied or replaced + self.pos = 0 + if size - self.pos > self.READ_MAX: + self.pos = size - self.READ_MAX + with open(path, "rb") as f: + f.seek(self.pos) + data = f.read(size - self.pos) + except OSError: + return dict(self.state) + end = data.rfind(b"\n") + 1 # whole lines only: the rest is read next time + self.pos += end + now = time.time() + for line in data[:end].decode("utf-8", "replace").splitlines(): + if "conversation cache:" not in line: + continue + m = self.EVENT.search(line) + if m: + st = self.state + st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4)) + if m.group(5) is not None: + st["evictions"] = int(m.group(5)) + if m.group(1) != "skipped": + st["parks" if m.group(1) == "parked" else "restores"] += 1 + st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now + continue + m = self.DROPPED.search(line) + if m: + self.state["parked"] = int(m.group(1)) + return dict(self.state) + + +def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict: + """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in + --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back.""" + mib = info.get("conversation_cache_mib") + last = hist[-1] if hist else None + return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None, + "slots": info.get("conversation_cache_slots"), **parked, + "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0), + "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0), + "last_reused": last.get("reused") if last else None, + "last_prompt": last.get("prompt_tokens") if last else None} + + class StrataEngine: """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. @@ -335,6 +405,7 @@ class StrataEngine: self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL loading = threading.Event() # set once READY: the narrator below stops log_start = os.path.getsize(log) if log else 0 # where this start's lines begin (start_failure_hint) + self.log_start = log_start # #596: the Monitor's conversation cache reads from here if log: threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), daemon=True).start() @@ -993,6 +1064,7 @@ class Service: # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation self.effort_end = False + self.conv_log = ConvCacheLog() # #596: the parked conversations, from the engine's log # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that # matters); empty = no CORS headers at all, as before self.cors_origins: list[str] = [] @@ -1329,7 +1401,9 @@ class Service: engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, **dict(getattr(self.engine, "info", {}) or {})} tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} + parked = self.conv_log.poll(getattr(self.engine, "log_path", None), getattr(self.engine, "log_start", None)) return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12], + "conversation_cache": conversation_cache_view(engine, hist, totals, parked), "requests_kept": len(hist), "totals": totals, "hardware": tel["now"], "hardware_static": tel["static"], "history": tel["history"], "time": now} diff --git a/serve/test_monitor.py b/serve/test_monitor.py index ad554e00..0c82cb0b 100644 --- a/serve/test_monitor.py +++ b/serve/test_monitor.py @@ -194,5 +194,68 @@ class Monitor(unittest.TestCase): self.assertEqual(self.request("/web/../server.py")[0], 404) +class ConversationCacheCard(unittest.TestCase): + """#596: /metrics' "conversation_cache": the parked conversations from the engine's log lines, the budget and + slots from its INFO line, and how much of the prompts the cache gave back.""" + + PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 " + "snapshot_bytes=104857600 reused_kv_bytes=0\n") + RESTORE = "strata serve: conversation cache: restored 4000 tokens (exact) in 30.0 ms; parked=2 bytes=209715200\n" + + def test_the_log(self): + from serve.server import ConvCacheLog + import tempfile + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "strata.log" + log.write_text("an earlier run\n" + self.PARK, encoding="utf-8") + start = log.stat().st_size # this run starts here: the earlier run's park is not counted + c = ConvCacheLog() + self.assertEqual(c.poll(str(log), start)["parked"], 0) + with open(log, "a", encoding="utf-8") as f: + f.write("strata serve: something else\n" + self.PARK + self.RESTORE + "strata serve: conversation ca") + st = c.poll(str(log), start) + self.assertEqual((st["parked"], st["bytes"], st["parks"], st["restores"]), (2, 209715200, 1, 1)) + self.assertEqual((st["last_event"], st["last_tokens"]), ("restored", 4000)) + with open(log, "a", encoding="utf-8") as f: # the cut line is read once it is whole + f.write("che: dropped 1 superseded copy of this conversation; parked=1\n") + self.assertEqual(c.poll(str(log), start)["parked"], 1) + self.assertEqual(c.poll(str(log), log.stat().st_size)["parked"], 0) # the engine started again + self.assertEqual(c.poll(None, None)["parked"], 0) + + def test_metrics(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "Thought.\nHello.", max_context=4096) + engine.info = {"conversation_cache_mib": 8192, "conversation_cache_slots": 4} + svc = Service(engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual((c["enabled"], c["budget_mib"], c["slots"], c["parked"], c["requests"]), + (True, 8192, 4, 0, 0)) + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + r.read() + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual(c["requests"], 1) + self.assertGreater(c["last_prompt"], 0) + engine.info = {} + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + self.assertFalse(json.loads(r.read())["conversation_cache"]["enabled"]) # off: the reuse lines only + finally: + httpd.shutdown() + httpd.server_close() + + def test_the_card_is_on_the_page(self): + web = Path(__file__).parent / "web" + html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8") + for el in ("cc-card", "cc-slots-text", "cc-mem-text", "cc-facts", "cc-note"): + self.assertIn(f'id="{el}"', html) + self.assertIn(f'"{el}"', js) + + if __name__ == "__main__": unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index 4e8363d4..9caa070f 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -115,6 +115,11 @@ main { flex: 1; min-height: 0; display: flex; } .table-wrap.all { max-height: 420px; overflow-y: auto; } .req-totals { margin: 0; font-size: var(--st-fs-sm); } .req-totals:empty { display: none; } +.cc-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.cc-bars { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-2) var(--st-s-6); } +.cc-bars[hidden] { display: none; } +.cc-note { margin: 0; } +.cc-note:empty { display: none; } .mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); } .mcp-server { display: flex; flex-direction: column; gap: var(--st-s-2); padding-top: var(--st-s-3); border-top: 1px solid var(--st-line-soft); } .mcp-server:first-child { padding-top: 0; border-top: 0; } @@ -155,6 +160,7 @@ main { flex: 1; min-height: 0; display: flex; } @media (max-width: 1000px) { .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } .monitor-row { grid-template-columns: 1fr; } + .cc-bars { grid-template-columns: 1fr; } } @media (max-width: 640px) { .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } diff --git a/serve/web/app.js b/serve/web/app.js index 6e8fa6b2..64721b44 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -190,9 +190,43 @@ function render(m) { } if (live.queued > 0) setPill("queued", `${live.queued} queued`); if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); + if (tab === "monitor") renderConvCache(m.conversation_cache); if (tab === "about") renderAbout(eng, hw, st); } +// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole +// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in) +function since(t) { + if (!t) return ""; + const s = Math.max(0, Date.now() / 1000 - t); + return s < 60 ? "just now" : s < 3600 ? `${fmt(s / 60)} min ago` : `${fmt(s / 3600, 1)} h ago`; +} +function renderConvCache(c) { + $("cc-card").hidden = !c; + if (!c) return; // an older server + const pct = (a, b) => (b ? `${Math.min(100, (100 * a) / b)}%` : "0%"); + $("cc-bars").hidden = !c.enabled; + if (c.enabled) { + $("cc-slots-text").textContent = `${fmt(c.parked)} / ${fmt(c.slots)}`; + $("cc-slots-bar").style.width = pct(c.parked, c.slots); + const budget = c.budget_mib * 1048576; + $("cc-mem-text").textContent = `${gb(c.bytes)} / ${gb(budget)} GB`; + $("cc-mem-bar").style.width = pct(c.bytes, budget); + } + $("cc-sum").textContent = c.requests ? `${fmt(c.requests_reused)} of ${fmt(c.requests)} requests reused part of their prompt` : ""; + const share = c.prompt_tokens ? ` (${fmt((100 * c.reused_tokens) / c.prompt_tokens)}% of all prompt tokens)` : ""; + const event = c.last_event ? `${c.last_event === "parked" ? "Parked" : "Restored"} ${fmt(c.last_tokens)} tokens, ${since(c.last_at)}` : null; + facts($("cc-facts"), [ + ["Last request", c.last_prompt != null ? `${fmt(c.last_reused || 0)} of ${fmt(c.last_prompt)} prompt tokens reused` : null], + ["Reused since start", c.requests ? `${fmt(c.reused_tokens)} tokens${share}` : null], + ["Parked / restored", c.enabled ? `${fmt(c.parks)} / ${fmt(c.restores)}${c.evictions ? ` ยท ${fmt(c.evictions)} evicted` : ""}` : null], + ["Last switch", c.enabled ? event : null], + ]); + $("cc-note").textContent = c.enabled + ? "A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full." + : "The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md)."; +} + function renderTotals(t) { if (!t || !t.requests) return ""; const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"}); diff --git a/serve/web/index.html b/serve/web/index.html index d858d2f0..cf588762 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -125,6 +125,18 @@ +
+
Conversation cache
+ +
+

+
+ + From 8cd360707cd16071272f761c84fc152ca1e077e0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:35:47 +0200 Subject: [PATCH 10/10] web: the Model settings card's Save is the primary button (#564) --- serve/web/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/serve/web/index.html b/serve/web/index.html index 7fb559e3..1fb4caa3 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -178,7 +178,7 @@

Kept in the model's run config for every client. An empty field is the default. They take effect the next time the model starts (close Strata's window and start it again).

-
+