diff --git a/docs/DETAILS.md b/docs/DETAILS.md index e30c2954..084aab8e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -482,6 +482,40 @@ print(r.choices[0].message.content) 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the connection or pressing stop in your app really stops the model, so the next request starts at once. - **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. +- **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the field + names are OpenCode's, so check its config docs if your version differs: + + ```jsonc + { + "$schema": "https://opencode.ai/config.json", + "provider": { + "strata": { + "npm": "@ai-sdk/openai-compatible", + "name": "Strata (local)", + "options": { "baseURL": "http://127.0.0.1:8080/v1", "apiKey": "none" }, // or your api_key + "models": { + "strata": { + "name": "Qwen3.8-Flash-Next (Strata)", + // context: what you chose in setup; output: what one reply may use (prompt + output must fit) + "limit": { "context": 262144, "output": 32768 }, + "options": { "reasoningEffort": "high" }, // sent as reasoning_effort + "variants": { // switch between them in OpenCode + "low": { "reasoningEffort": "low" }, + "medium": { "reasoningEffort": "medium" }, + "none": { "reasoningEffort": "none" } + } + } + } + } + }, + "model": "strata/strata" + } + ``` + + Set `limit.context` to the context you chose in setup: OpenCode compacts the conversation before it gets there. + Keep `limit.output` well under it: a request whose prompt plus `max_tokens` runs past the context is refused (see + **Context** below), or add `"fit_max_tokens": true` to `strata-.json`. For a hard cap on the thinking, add + `"reasoning_budget_tokens": N` to `strata-.json` (see above). - **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one). diff --git a/serve/server.py b/serve/server.py index 27095560..4f438e1d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1380,7 +1380,9 @@ class Service: elif max_new > room: if not self.fit_max_tokens: raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " - f"({self.engine.max_context}); requests are never truncated") + f"({self.engine.max_context}); requests are never truncated. Send a smaller " + f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " + "model's strata-.json to shorten it to the room left (#545)") max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 return ids, kwargs.get("enable_thinking", True) is not False, max_new @@ -1585,6 +1587,10 @@ class Service: hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else "" print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) + if finish == "length" and parser.state == "reasoning": # #530 + print("[strata] the reply reached max tokens while still thinking, so it has no " + "answer: a thinking budget (reasoning_budget_tokens, in the request or in " + "strata-.json for every request) leaves room to answer", flush=True) if os.environ.get("STRATA_DEBUG") and raw_ids: print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True) self.status["busy"] = False diff --git a/serve/test_server.py b/serve/test_server.py index 8f34a74b..756c1f54 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4,6 +4,8 @@ """ from __future__ import annotations +import contextlib +import io import json import os import sys @@ -135,6 +137,8 @@ class MaxTokens(unittest.TestCase): s, b, _, _ = self.call(api, max_tokens=CTX) self.assertEqual(s, 400) self.assertIn("exceeds the context", b["error"]["message"]) + self.assertIn("\"fit_max_tokens\": true", b["error"]["message"]) # #545: says how to get past it + self.assertRegex(b["error"]["message"], r"at most \d+ here") def test_unset_budget_with_a_near_full_prompt(self): _, _, pt0, _ = self.call("openai", max_tokens=1) @@ -1811,6 +1815,20 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(len(self.engine.prompts), 1) self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20]) + def test_a_reply_cut_while_thinking_is_named_in_the_log(self): + """#530: max tokens reached inside the thinking gives an empty answer; the server log says what helps.""" + hint = "reached max tokens while still thinking" + for extra, said in (({"max_tokens": 10}, True), ({}, False)): + with self.subTest(extra=extra): + out = io.StringIO() + with contextlib.redirect_stdout(out): + code, b = self.openai(**extra) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["finish_reason"], "length" if said else "stop") + self.assertEqual(hint in out.getvalue(), said, out.getvalue()) + if said: + self.assertIn("reasoning_budget_tokens", out.getvalue()) + def test_a_bad_value_is_a_400(self): for bad in ("lots", 2.5, True, [1]): with self.subTest(value=bad): diff --git a/setup.py b/setup.py index eee21159..55a48cfb 100644 --- a/setup.py +++ b/setup.py @@ -50,6 +50,7 @@ import shutil import struct import subprocess import sys +import textwrap import time import urllib.error import urllib.request @@ -2429,8 +2430,25 @@ def find_in(roots: list, rel: str): # ------------------------------------------------------------------------------------------------ start +def model_config(path: Path) -> bool: + """#549: a model's run config (a JSON object with "exe" and "args"). Any other strata-*.json in the folder (a + file of the user's own, a cut-off one) is skipped with a warning naming it instead of stopping setup.""" + try: + cfg = json.loads(path.read_text(encoding="utf-8-sig")) + if isinstance(cfg, dict) and cfg.get("exe") and isinstance(cfg.get("args"), list): + return True + why = 'no "exe" or "args"' + except OSError as e: + why = e.strerror or str(e) + except ValueError: + why = "not valid JSON" + warn(f"skipped {path.name} ({why}): it is not a Strata model config") + return False + + def installed_configs(): - return sorted(ROOT.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + return [p for p in sorted(ROOT.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + if model_config(p)] def source_version() -> str: @@ -2545,6 +2563,7 @@ def update_install(have: list, a) -> int: setup needs a newer one (MIN_ENGINE; a compiled engine when its source changed), each installed model's config upgrades and its draft subset. No question is asked and the model files are not touched; a model still running keeps its engine (update_installed_engine says to close it and run this again).""" + have = [p for p in have if model_config(p)] # #549: a strata-*.json that is no model config is skipped if not have: say(" No model is installed in this Strata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -") say(" it finds an earlier install's model files next to it and reuses them.") @@ -2567,6 +2586,29 @@ def update_install(have: list, a) -> int: return 0 +def settings_summary(cfg: dict, port=None) -> str: + """#564: the settings a start uses, in one line: the config's engine options (the model's file paths left out) + and the server's own fields, so a change made by hand to strata-.json can be checked without the log.""" + a, out, i = [str(x) for x in cfg.get("args") or []], [], 0 + while i < len(a): + flag = a[i] + val = a[i + 1] if i + 1 < len(a) and not a[i + 1].startswith("--") else None + i += 1 if val is None else 2 + if not flag.startswith("--"): + continue # a positional: the model file + if val is not None and ("/" in val or "\\" in val or val.lower().endswith((".gguf", ".bin"))): + continue # a path: --native, --mtp, --profile ... + out.append(flag if val is None else f"{flag} {val}") + 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") + 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] + srv.append(f"{k} {','.join(map(str, v)) if isinstance(v, list) else str(v).lower() if isinstance(v, bool) else v}") + return " ".join(out) + ("; " if out else "") + "server " + ", ".join(srv) + + def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, layer_split=None, keep=None) -> int: """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, @@ -2680,6 +2722,9 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ say(" restart). That is normal: please wait and don't close this window - the browser opens 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, + break_on_hyphens=False)): # #564: what this start uses + say((" " if n == 0 else " ") + line) if not WIN and os.environ.get("STRATA_EXECV"): # Replace this process instead of spawning a child. The Docker image sets STRATA_EXECV=1, # so there the server is PID 1 and docker stop's SIGTERM reaches the process that can diff --git a/tools/test_setup_update.py b/tools/test_setup_update.py index 56a33082..12b1026e 100644 --- a/tools/test_setup_update.py +++ b/tools/test_setup_update.py @@ -69,6 +69,29 @@ class Update(unittest.TestCase): m.assert_not_called() self.assertIn("START-HERE.bat", out) + def test_a_json_that_is_no_model_config_is_skipped(self): + """#549: a strata-*.json without "args" (not written by setup) stopped update.sh with KeyError: 'args'.""" + with tempfile.TemporaryDirectory() as d: + p = self.config(Path(d)) + other = Path(d) / "strata-notes.json" + other.write_text(json.dumps({"note": "mine"}), encoding="utf-8") + broken = Path(d) / "strata-cut.json" + broken.write_text("{\"args\": [", encoding="utf-8") + rc, pip, eng, dv, start, call, out = self.run_update([other, broken, p]) + self.assertEqual(rc, 0, out) + self.assertIn('skipped strata-notes.json (no "exe" or "args"): it is not a Strata model config', out) + self.assertIn("skipped strata-cut.json (not valid JSON)", out) + dv.assert_called_once() # the real model is still refreshed + self.assertIn("Qwen IQ3_S: up to date", out) + self.assertIn("Strata is updated", out) + + def test_installed_configs_lists_only_model_configs(self): + with tempfile.TemporaryDirectory() as d: + p = self.config(Path(d)) + (Path(d) / "strata-notes.json").write_text("{}", encoding="utf-8") + with mock.patch.object(setup, "ROOT", Path(d)), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(setup.installed_configs(), [p]) + def test_main_update_never_starts(self): with tempfile.TemporaryDirectory() as d: p = self.config(Path(d)) @@ -83,5 +106,40 @@ class Update(unittest.TestCase): start.assert_not_called() +class SettingsLine(unittest.TestCase): + """#564: a start prints the settings it uses (the engine options without the model's paths, and the server's + fields), so a change made by hand to strata-.json shows without reading the log.""" + + CFG = {"exe": "x", "host": "0.0.0.0", "port": 8081, "api_key": "secret", "gpu": [0, 1], "fit_max_tokens": True, + "args": ["--native", "E:\\Strata\\packs\\iq3_s", "--mtp", "/s/mtp/rt", "m.gguf", "--kv", "int8", + "--kv-resident", "32768", "--spec-min-p", "0.5", "--vram-reserve-mib", "2048", "--mmap-experts", + "--prefill", "auto"]} + + def test_summary(self): + s = setup.settings_summary(self.CFG) + self.assertEqual(s, "--kv int8 --kv-resident 32768 --spec-min-p 0.5 --vram-reserve-mib 2048 --mmap-experts " + "--prefill auto; server 0.0.0.0:8081, api key set, gpu 0,1, fit_max_tokens true") + self.assertNotIn("secret", s) + self.assertIn("127.0.0.1:9000", setup.settings_summary({"args": []}, 9000)) + + def test_a_start_prints_it(self): + with tempfile.TemporaryDirectory() as d: + exe = Path(d) / "strata.exe" + exe.write_bytes(b"") + p = Path(d) / "strata-iq3_s.json" + args = [x for x in self.CFG["args"] if x != "m.gguf"] # no model file here + p.write_text(json.dumps({**self.CFG, "exe": str(exe), "gpu": 0, "args": args}), encoding="utf-8") + out = io.StringIO() + with mock.patch.object(setup, "gpus", lambda: []), \ + mock.patch.object(setup, "refresh_draft_vocab"), \ + mock.patch.object(setup, "is_wsl", lambda: False), \ + mock.patch.object(setup.subprocess, "call", return_value=0), \ + contextlib.redirect_stdout(out): + setup.start(p, None, open_browser=False, yes=True) + text = " ".join(out.getvalue().split()) + self.assertIn("Settings (strata-iq3_s.json): --kv int8 --kv-resident 32768", text) + self.assertIn("--vram-reserve-mib 2048", text) + + if __name__ == "__main__": unittest.main()