64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
import json
|
|
import os
|
|
from dataclasses import asdict
|
|
from pathlib import Path
|
|
|
|
|
|
DEFAULT_PATH = Path('sloppy.json')
|
|
|
|
|
|
def load_settings(path=DEFAULT_PATH):
|
|
path = Path(path)
|
|
if not path.exists():
|
|
return {'models': {}, 'selected': {'ai1': '', 'ai2': ''}}
|
|
data = json.loads(path.read_text(encoding='utf-8'))
|
|
if not isinstance(data, dict) or not isinstance(data.get('models', {}), dict):
|
|
raise ValueError('sloppy.json must contain a models object')
|
|
data.setdefault('models', {})
|
|
data.setdefault('selected', {'ai1': '', 'ai2': ''})
|
|
if not isinstance(data['selected'], dict):
|
|
raise ValueError('sloppy.json selected must be an object')
|
|
for slot, value in data['selected'].items():
|
|
if not isinstance(slot, str) or not isinstance(value, str):
|
|
raise ValueError(f'sloppy.json selected.{slot} must be a string')
|
|
for identifier, values in data['models'].items():
|
|
if not isinstance(identifier, str) or not isinstance(values, dict):
|
|
raise ValueError(f'sloppy.json models.{identifier} must be an object')
|
|
for field in ('name', 'base_url', 'api_key', 'model', 'system_prompt'):
|
|
if field in values and not isinstance(values[field], str):
|
|
raise ValueError(f'sloppy.json models.{identifier}.{field} must be a string')
|
|
return data
|
|
|
|
|
|
def save_settings(data, path=DEFAULT_PATH):
|
|
path = Path(path)
|
|
temporary = path.with_name(path.name + '.tmp')
|
|
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
if hasattr(os, 'O_BINARY'):
|
|
flags |= os.O_BINARY
|
|
created = False
|
|
try:
|
|
descriptor = os.open(temporary, flags, 0o600)
|
|
created = True
|
|
with os.fdopen(descriptor, 'w', encoding='utf-8') as output:
|
|
output.write(json.dumps(data, indent=2, ensure_ascii=False) + '\n')
|
|
os.replace(temporary, path)
|
|
except BaseException:
|
|
if created:
|
|
temporary.unlink(missing_ok=True)
|
|
raise
|
|
|
|
|
|
def model_from_settings(data, identifier):
|
|
values = data['models'][identifier]
|
|
return {key: values.get(key, default) for key, default in (
|
|
('name', identifier), ('base_url', ''), ('api_key', ''),
|
|
('model', ''), ('system_prompt', 'You are a helpful assistant.'))}
|
|
|
|
|
|
def store_model(data, identifier, config):
|
|
identifier = identifier.strip()
|
|
if not identifier or not all((config.name.strip(), config.base_url.strip(), config.model.strip())):
|
|
raise ValueError('ID, name, base URL, and model are required')
|
|
data['models'][identifier] = asdict(config)
|