okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
9.0 KiB190 linesraw
1"""serve/runconfig.py - #564: the web page's Settings view of the run config (strata-<model>.json).
2
3A short list of documented keys can be read and changed from Strata's own page (GET / POST /config).  Everything
4else in the file - the keys setup writes, the network and security keys (host, api_key, cors_origins,
5trusted_origins, allowed_hosts), the MCP servers and before_load (which run programs), sampling keys not listed
6here - is kept as it is: a change touches only the keys it names (as setup run again keeps the user's keys, #629).
7The earlier file is kept as strata-<model>.json.bak.  The server reads the config when it starts, so a change is
8used from the next start on.
9"""
10from __future__ import annotations
11
12import json
13import shutil
14from pathlib import Path
15
16from strata_control import user_args
17from strata_control import atomic as _atomic_mod
18
19# (key, kind, help).  kind: "bool", "int>=0", "num>=0", ("enum", values), "names", or ("sampling", check) for a key
20# of the "sampling" block, ("arg", flag) for an engine option kept in "args".
21EDITABLE = [
22    ("sampling.temperature", ("sampling", "num>=0"),
23     "Default temperature for requests that send none (0 = greedy; without it the model card's: 1.0 thinking, 0.7 not)"),
24    ("sampling.top_p", ("sampling", "0<x<=1"), "Default top_p for requests that send none"),
25    ("sampling.top_k", ("sampling", "1..64"), "Default top_k for requests that send none (1-64)"),
26    ("sampling.min_p", ("sampling", "0<=x<=1"), "Default min_p for requests that send none"),
27    ("reasoning_budget_tokens", "int>=0", "Cap the thinking of every request at this many tokens (0 or empty: no cap)"),
28    ("fit_max_tokens", "bool", "Shorten a max_tokens that does not fit the context (on by default); off: answer 400 like llama.cpp"),
29    ("anthropic_thinking", ("enum", ["model", "on_request"]),
30     "Anthropic requests that do not ask for thinking: think as the model does (model) or not (on_request)"),
31    ("effort_position", ("enum", ["start", "end"]),
32     "Where a non-default reasoning effort goes: start (the default) or end (keeps the cache when it changes)"),
33    ("aliases", "names", "Other model names the server lists and answers to (comma-separated)"),
34    ("idle_unload_s", "num>=0", "Unload the model after this many seconds without requests (0 or empty: never)"),
35    ("mtp", "bool", "Draft layer (MTP): off starts the engine without it (about 1 GB less graphics memory, slower words per second); "
36                    "empty or on: as installed"),
37    ("lazy_load", "bool", "Start without loading the model; the first request loads it (text only)"),
38    ("engine_silence_s", "num>=0", "End a request when the engine says nothing for this long (default 300 s, 0 = wait)"),
39    ("api_monitor", "bool", "Keep the last 100 requests' prompts and answers in memory for /api-monitor"),
40    ("open_browser", "bool", "Open the chat page in the browser when the model is ready"),
41    ("vram_reserve_mib", ("arg", "--vram-reserve-mib"),
42     "VRAM in MiB the engine leaves free for other programs (engine default 700)"),
43]
44SPEC = {k: kind for k, kind, _ in EDITABLE}
45
46
47def _arg(cfg: dict, flag: str):
48    a = cfg.get("args") if isinstance(cfg.get("args"), list) else []
49    if flag in a[:-1]:
50        v = str(a[a.index(flag) + 1])
51        return int(v) if v.isdigit() else v
52    return None
53
54
55def value_of(cfg: dict, key: str):
56    kind = SPEC[key]
57    if isinstance(kind, tuple) and kind[0] == "sampling":
58        s = cfg.get("sampling")
59        return s.get(key.split(".", 1)[1]) if isinstance(s, dict) else None
60    if isinstance(kind, tuple) and kind[0] == "arg":
61        return _arg(cfg, kind[1])
62    return cfg.get(key)
63
64
65def view(cfg: dict, path: str | Path) -> dict:
66    """GET /config: the editable keys with their values (None: not set, the default applies)."""
67    out = []
68    for key, kind, help_ in EDITABLE:
69        k = kind[0] if isinstance(kind, tuple) else kind
70        out.append({"key": key, "value": value_of(cfg, key), "help": help_,
71                    "kind": "number" if k in ("sampling", "arg", "int>=0", "num>=0") else k,
72                    **({"choices": kind[1]} if k == "enum" else {})})
73    return {"file": Path(path).name, "keys": out,
74            "note": "Saved to the run config; used from the next start of the model."}
75
76
77def _number(key, v, whole=False, lo=0.0, hi=None, lo_open=False):
78    if isinstance(v, bool) or not isinstance(v, (int, float)) or (whole and v != int(v)) or \
79            (v <= lo if lo_open else v < lo) or (hi is not None and v > hi):
80        rng = f"{'more than' if lo_open else 'at least'} {lo:g}" + (f" and at most {hi:g}" if hi is not None else "")
81        raise ValueError(f"{key}: expected a {'whole ' if whole else ''}number, {rng}, not {v!r}")
82    return int(v) if whole else v
83
84
85def check(key: str, v, cfg: dict):
86    """The value to store for `key`, or a ValueError naming what is expected.  None removes the key (its default)."""
87    if key not in SPEC:
88        raise ValueError(f"{key!r} cannot be changed here (only the keys the Settings view lists)")
89    if v is None:
90        return None
91    kind = SPEC[key]
92    k = kind[0] if isinstance(kind, tuple) else kind
93    if k == "bool":
94        if not isinstance(v, bool):
95            raise ValueError(f"{key}: expected true or false, not {v!r}")
96        if key == "lazy_load" and v and cfg.get("vision"):
97            raise ValueError("lazy_load: lazy loading is text-only, and this model reads images (\"vision\")")
98        return v
99    if k == "enum":
100        if v not in kind[1]:
101            raise ValueError(f"{key}: expected one of {', '.join(kind[1])}, not {v!r}")
102        return v
103    if k == "names":
104        if isinstance(v, str):
105            v = [x.strip() for x in v.split(",") if x.strip()]
106        if not isinstance(v, list) or not all(isinstance(x, str) and x.strip() and len(x) <= 128 for x in v):
107            raise ValueError(f"{key}: expected a list of model names, not {v!r}")
108        return v or None
109    if k == "int>=0":
110        return _number(key, v, whole=True)
111    if k == "num>=0":
112        return _number(key, v)
113    if k == "arg":
114        return _number(key, v, whole=True)
115    rule = kind[1]                                     # a sampling key: the server's own rules
116    if rule == "num>=0":
117        return float(_number(key, v))
118    if rule == "0<x<=1":
119        return float(_number(key, v, hi=1, lo_open=True))
120    if rule == "0<=x<=1":
121        return float(_number(key, v, hi=1))
122    return _number(key, v, whole=True, lo=1, hi=64)
123
124
125def apply(cfg: dict, changes: dict) -> tuple[dict, list[str]]:
126    """The config with `changes` ({key: value or None}) made, and the keys that changed.  Every value is checked
127    first, so a request with one bad value changes nothing (ValueError)."""
128    if not isinstance(changes, dict) or not changes:
129        raise ValueError('send {"set": {"<key>": <value or null>, ...}}')
130    checked = {k: check(k, v, cfg) for k, v in changes.items()}
131    new = json.loads(json.dumps(cfg))                  # a deep copy: the caller's dict is left alone
132    changed = []
133    for key, v in checked.items():
134        if value_of(new, key) == v:
135            continue
136        kind = SPEC[key]
137        if isinstance(kind, tuple) and kind[0] == "sampling":
138            s = dict(new.get("sampling") or {}) if isinstance(new.get("sampling"), dict) else {}
139            sub = key.split(".", 1)[1]
140            if v is None:
141                s.pop(sub, None)
142            else:
143                s[sub] = v
144            if s:
145                new["sampling"] = s
146            else:
147                new.pop("sampling", None)
148        elif isinstance(kind, tuple) and kind[0] == "arg":
149            a = list(new.get("args") or [])
150            flag = kind[1]
151            if flag in a[:-1]:
152                i = a.index(flag)
153                if v is None:
154                    del a[i:i + 2]
155                else:
156                    a[i + 1] = str(v)
157            elif v is not None:
158                a += [flag, str(v)]
159            new["args"] = a
160            mine = user_args.set_flag(user_args.capture(new), flag, v)   # a value set here is the person's: it survives setup and the app
161            if mine:
162                new[user_args.USER_KEY] = mine
163            else:
164                new.pop(user_args.USER_KEY, None)
165            if user_args.WRITTEN_KEY in new:
166                new[user_args.WRITTEN_KEY] = list(a)
167        elif v is None:
168            new.pop(key, None)
169        else:
170            new[key] = v
171        changed.append(key)
172    return new, changed
173
174
175def save(path: str | Path, cfg: dict) -> Path:
176    """The config written whole (a temporary file moved over the old one), the earlier one kept as <name>.bak."""
177    path = Path(path)
178    bak = path.with_name(path.name + ".bak")
179    shutil.copyfile(path, bak)
180    tmp = path.with_name(path.name + ".tmp")
181    tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
182    _atomic_mod.replace(tmp, path)
183    return bak
184
185
186def load(path: str | Path) -> dict:
187    cfg = json.loads(Path(path).read_text(encoding="utf-8-sig"))
188    if not isinstance(cfg, dict):
189        raise ValueError(f"{Path(path).name} is not a JSON object")
190    return cfg