okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
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 ): 48a = cfg .get ("args" )if isinstance (cfg .get ("args" ),list )else [] 49if flag in a [:- 1 ]: 50v = str (a [a .index (flag )+ 1 ]) 51return int (v )if v .isdigit ()else v 52return None 53 54 55def value_of (cfg :dict ,key :str ): 56kind = SPEC [key ] 57if isinstance (kind ,tuple )and kind [0 ]== "sampling" : 58s = cfg .get ("sampling" ) 59return s .get (key .split ("." ,1 )[1 ])if isinstance (s ,dict )else None 60if isinstance (kind ,tuple )and kind [0 ]== "arg" : 61return _arg (cfg ,kind [1 ]) 62return 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).""" 67out = [] 68for key ,kind ,help_ in EDITABLE : 69k = kind [0 ]if isinstance (kind ,tuple )else kind 70out .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 {})}) 73return {"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 ): 78if 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 ): 80rng = f" { 'more than' if lo_open else 'at least' } { lo :g } " + (f" and at most { hi :g } " if hi is not None else "" ) 81raise ValueError (f" { key } : expected a { 'whole ' if whole else '' } number, { rng } , not { v !r } " ) 82return 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).""" 87if key not in SPEC : 88raise ValueError (f" { key !r } cannot be changed here (only the keys the Settings view lists)" ) 89if v is None : 90return None 91kind = SPEC [key ] 92k = kind [0 ]if isinstance (kind ,tuple )else kind 93if k == "bool" : 94if not isinstance (v ,bool ): 95raise ValueError (f" { key } : expected true or false, not { v !r } " ) 96if key == "lazy_load" and v and cfg .get ("vision" ): 97raise ValueError ("lazy_load: lazy loading is text-only, and this model reads images (\"vision\")" ) 98return v 99if k == "enum" : 100if v not in kind [1 ]: 101raise ValueError (f" { key } : expected one of { ', ' . join ( kind [ 1 ]) } , not { v !r } " ) 102return v 103if k == "names" : 104if isinstance (v ,str ): 105v = [x .strip ()for x in v .split ("," )if x .strip ()] 106if not isinstance (v ,list )or not all (isinstance (x ,str )and x .strip ()and len (x )<= 128 for x in v ): 107raise ValueError (f" { key } : expected a list of model names, not { v !r } " ) 108return v or None 109if k == "int>=0" : 110return _number (key ,v ,whole = True ) 111if k == "num>=0" : 112return _number (key ,v ) 113if k == "arg" : 114return _number (key ,v ,whole = True ) 115rule = kind [1 ]# a sampling key: the server's own rules 116if rule == "num>=0" : 117return float (_number (key ,v )) 118if rule == "0<x<=1" : 119return float (_number (key ,v ,hi = 1 ,lo_open = True )) 120if rule == "0<=x<=1" : 121return float (_number (key ,v ,hi = 1 )) 122return _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 127first, so a request with one bad value changes nothing (ValueError).""" 128if not isinstance (changes ,dict )or not changes : 129raise ValueError ('send {"set": {"<key>": <value or null>, ...}}' ) 130checked = {k :check (k ,v ,cfg )for k ,v in changes .items ()} 131new = json .loads (json .dumps (cfg ))# a deep copy: the caller's dict is left alone 132changed = [] 133for key ,v in checked .items (): 134if value_of (new ,key )== v : 135continue 136kind = SPEC [key ] 137if isinstance (kind ,tuple )and kind [0 ]== "sampling" : 138s = dict (new .get ("sampling" )or {})if isinstance (new .get ("sampling" ),dict )else {} 139sub = key .split ("." ,1 )[1 ] 140if v is None : 141s .pop (sub ,None ) 142else : 143s [sub ]= v 144if s : 145new ["sampling" ]= s 146else : 147new .pop ("sampling" ,None ) 148elif isinstance (kind ,tuple )and kind [0 ]== "arg" : 149a = list (new .get ("args" )or []) 150flag = kind [1 ] 151if flag in a [:- 1 ]: 152i = a .index (flag ) 153if v is None : 154del a [i :i + 2 ] 155else : 156a [i + 1 ]= str (v ) 157elif v is not None : 158a += [flag ,str (v )] 159new ["args" ]= a 160mine = user_args .set_flag (user_args .capture (new ),flag ,v )# a value set here is the person's: it survives setup and the app 161if mine : 162new [user_args .USER_KEY ]= mine 163else : 164new .pop (user_args .USER_KEY ,None ) 165if user_args .WRITTEN_KEY in new : 166new [user_args .WRITTEN_KEY ]= list (a ) 167elif v is None : 168new .pop (key ,None ) 169else : 170new [key ]= v 171changed .append (key ) 172return 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.""" 177path = Path (path ) 178bak = path .with_name (path .name + ".bak" ) 179shutil .copyfile (path ,bak ) 180tmp = path .with_name (path .name + ".tmp" ) 181tmp .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 182_atomic_mod .replace (tmp ,path ) 183return bak 184 185 186def load (path :str | Path )-> dict : 187cfg = json .loads (Path (path ).read_text (encoding = "utf-8-sig" )) 188if not isinstance (cfg ,dict ): 189raise ValueError (f" { Path ( path ). name } is not a JSON object" ) 190return cfg