"""Read the UI-managed, private NAO model configuration with legacy bootstrap.""" import json import os import re from pathlib import Path from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] SETTINGS_FILE = Path(os.environ.get('QUALITY_NAO_MODEL_CONFIG_FILE', str(ROOT / '.runtime/nao-model-config.json'))).absolute() def _read_private(path: Path, limit: int) -> bytes: if path.is_symlink() or path.parent.is_symlink() or not path.is_file(): raise ValueError('Invalid private model configuration') with path.open('rb') as stream: content = stream.read(limit + 1) if len(content) > limit: raise ValueError('Invalid private model configuration') return content def _validate(value): if not isinstance(value, dict): raise ValueError('Invalid private model configuration') base, key, model = (value.get(name) for name in ('baseUrl', 'apiKey', 'model')) if not all(isinstance(item, str) and item.strip() for item in (base, key, model)): raise ValueError('Incomplete model configuration') base, model = base.strip().rstrip('/'), model.strip() key = re.sub(r'^Bearer\s+', '', key.strip(), flags=re.IGNORECASE) u = urlsplit(base) if u.scheme not in ('http', 'https') or not u.hostname or u.username is not None or u.password is not None or u.query or u.fragment or len(base) > 2048: raise ValueError('Invalid model endpoint') if not key or len(key) > 4096 or any(c.isspace() or ord(c) < 32 or 127 <= ord(c) <= 159 for c in key): raise ValueError('Invalid model credential') if not re.fullmatch(r'[A-Za-z0-9_./:@+\-]{1,160}', model): raise ValueError('Invalid model name') return base, key, model def _legacy_settings(): # Keep the documented bootstrap format independent of ignored trial scripts. path = Path(os.environ.get('QUALITY_MODEL_CONFIG', str(ROOT / 'apikey.txt'))) content = _read_private(path, 16384) text = content.decode('utf-16' if content[:2] in (b'\xff\xfe', b'\xfe\xff') else 'utf-8-sig') lines = [line.strip() for line in text.splitlines() if line.strip()] selection = ROOT / '.runtime/dbgpt-trial/selected-profile.json' profile = 1 if selection.exists() or selection.is_symlink(): value = json.loads(_read_private(selection, 16384)) if not isinstance(value, dict): raise ValueError('Invalid model profile selection') profile = value.get('profile', 1) if type(profile) is not int or profile < 1 or len(lines) < profile * 3: raise ValueError('Selected model configuration is incomplete') base, key, model = lines[(profile - 1) * 3:profile * 3] base = base.rstrip('/') if base.endswith('/chat/completions'): base = base[:-len('/chat/completions')] if not base.endswith('/v1'): base += '/v1' return _validate(dict(baseUrl=base, apiKey=key, model=model)) def model_configuration(): if SETTINGS_FILE.is_symlink() or SETTINGS_FILE.parent.is_symlink(): raise ValueError('Invalid private model configuration') if not SETTINGS_FILE.exists(): base,key,model = _legacy_settings() value = {} else: value = json.loads(_read_private(SETTINGS_FILE, 32768).decode('utf-8')) base,key,model = _validate(value) enabled=value.get('thinkingEnabled',True) effort=value.get('thinkingEffort','medium') if type(enabled) is not bool or effort not in ('auto','low','medium','high'): raise ValueError('Invalid thinking configuration') if re.match(r'^mimo-v2\.6(?:-|$)',model,re.IGNORECASE): effort='auto' return base,key,model,{'enabled':enabled,'effort':effort, 'protocol':'chat_template' if model.lower().startswith('qwen') else 'thinking'} def model_settings(): return model_configuration()[:3] def model_request_timeout(model): """All models share the same system allowance and turn deadline.""" from nao_runtime_policy import request_timeout return request_timeout()