109 lines
5.7 KiB
Python
109 lines
5.7 KiB
Python
"""Platform-wide mind-map workbench defaults; user overrides never reach here."""
|
|
from copy import deepcopy
|
|
from django.db import transaction
|
|
from rest_framework.exceptions import PermissionDenied, ValidationError, NotFound
|
|
from system_manage.models import SystemSetting
|
|
from system_manage import ai_hub as hub
|
|
|
|
SETTING = 11030
|
|
DEFAULT_SUMMARY_CONCURRENCY_LIMIT = 1
|
|
FIELDS = {'parserResourceId', 'mindmapModelId', 'mindmapLlmTemperature',
|
|
'mindmapPrompt', 'summaryOptions', 'exportResolution'}
|
|
|
|
|
|
def read(workspace, user):
|
|
row = SystemSetting.objects.filter(pk=SETTING).first()
|
|
meta = row.meta if row and isinstance(row.meta, dict) else {}
|
|
config = deepcopy(meta.get('config') or {})
|
|
unavailable = {'model_unavailable': False, 'parser_unavailable': False}
|
|
# Do not give a user an unusable default or bypass individual grants.
|
|
parser = config.get('parserResourceId')
|
|
if parser and parser != 'builtin':
|
|
try:
|
|
resource = hub.one('parsers', parser, workspace, user)
|
|
hub.require_use(user, resource)
|
|
if not resource.enabled:
|
|
config['parserResourceId'] = ''
|
|
unavailable['parser_unavailable'] = True
|
|
except (NotFound, PermissionDenied, ValidationError):
|
|
config['parserResourceId'] = ''
|
|
unavailable['parser_unavailable'] = True
|
|
if config.get('mindmapModelId'):
|
|
try:
|
|
hub.model_for(workspace, user, config['mindmapModelId'])
|
|
except (NotFound, PermissionDenied, ValidationError):
|
|
config['mindmapModelId'] = ''
|
|
unavailable['model_unavailable'] = True
|
|
limit = meta.get('summary_concurrency_limit', DEFAULT_SUMMARY_CONCURRENCY_LIMIT)
|
|
if type(limit) is not int or not 1 <= limit <= 32:
|
|
limit = DEFAULT_SUMMARY_CONCURRENCY_LIMIT
|
|
return {'config': config, 'revision': meta.get('revision', 0),
|
|
'summary_concurrency_limit': limit, **unavailable}
|
|
|
|
|
|
def summary_concurrency_limit():
|
|
row = SystemSetting.objects.filter(pk=SETTING).values_list('meta', flat=True).first()
|
|
value = (row if isinstance(row, dict) else {}).get('summary_concurrency_limit', DEFAULT_SUMMARY_CONCURRENCY_LIMIT)
|
|
return value if type(value) is int and 1 <= value <= 32 else DEFAULT_SUMMARY_CONCURRENCY_LIMIT
|
|
|
|
|
|
def validate(workspace, user, config):
|
|
if not isinstance(config, dict) or set(config) != FIELDS:
|
|
raise ValidationError('工作台设置不完整')
|
|
clean = deepcopy(config)
|
|
for key in ('parserResourceId', 'mindmapModelId'):
|
|
if not isinstance(clean[key], str) or len(clean[key]) > 64:
|
|
raise ValidationError('模型或解析服务无效')
|
|
parser = clean['parserResourceId']
|
|
if parser and parser != 'builtin':
|
|
resource = hub.one('parsers', parser, workspace, user)
|
|
hub.require_use(user, resource)
|
|
if not resource.enabled:
|
|
raise ValidationError('解析服务已停用')
|
|
hub.text(clean['mindmapPrompt'], '总结提示词', limit=16000)
|
|
if type(clean['exportResolution']) is not int or clean['exportResolution'] not in (1024, 2048, 4096, 8192):
|
|
raise ValidationError('导出长边无效')
|
|
options = clean['summaryOptions']
|
|
from system_manage.summary_plan import INTEGER_OPTIONS, validate_options
|
|
permitted = set(INTEGER_OPTIONS) | {'top_p', 'detail', 'structure_mode', 'parallel', 'auto_split'}
|
|
if not isinstance(options, dict) or set(options) - permitted:
|
|
raise ValidationError('总结参数无效')
|
|
try:
|
|
values = validate_options({**options, 'temperature': clean['mindmapLlmTemperature']})
|
|
if clean['mindmapModelId']:
|
|
from models_provider.tools import get_model_default_params
|
|
from system_manage.ai_hub_organize import resolve_settings
|
|
from system_manage.mcp_business import summary_model_defaults, summary_supported_parameters
|
|
model = hub.model_for(workspace, user, clean['mindmapModelId'])
|
|
defaults = summary_model_defaults(model, get_model_default_params(model))
|
|
resolve_settings(defaults, values)
|
|
if values.get('top_p') is not None and 'top_p' not in summary_supported_parameters(model):
|
|
raise ValueError('该模型未声明支持 top_p 参数')
|
|
except ValueError as exc:
|
|
raise ValidationError(str(exc)) from None
|
|
return clean
|
|
|
|
|
|
@transaction.atomic
|
|
def save(workspace, user, data):
|
|
hub.require_admin(user)
|
|
if not {'config', 'revision'} <= set(data) or set(data) - {'config', 'revision', 'summary_concurrency_limit'} or type(data['revision']) is not int or data['revision'] < 0:
|
|
raise ValidationError('工作台设置版本无效')
|
|
limit = data.get('summary_concurrency_limit')
|
|
if 'summary_concurrency_limit' in data and (type(limit) is not int or not 1 <= limit <= 32):
|
|
raise ValidationError('智能总结总并发数需为 1 至 32 的整数')
|
|
config = validate(workspace, user, data['config'])
|
|
# Use the same lock order as task admission, so a newly lowered limit is
|
|
# visible before another queued task reserves slots.
|
|
from system_manage.mcp_registry import settings_row
|
|
settings_row(lock=True)
|
|
row, _ = SystemSetting.objects.get_or_create(type=SETTING, defaults={'meta': {}})
|
|
row = SystemSetting.objects.select_for_update().get(pk=row.pk)
|
|
revision = (row.meta or {}).get('revision', 0)
|
|
if data['revision'] != revision:
|
|
raise ValidationError('工作台设置已更新,请刷新后重试')
|
|
row.meta = {**(row.meta or {}), 'config': config, 'revision': revision + 1,
|
|
'summary_concurrency_limit': limit if limit is not None else summary_concurrency_limit()}
|
|
row.save(update_fields=['meta', 'update_time'])
|
|
return read(workspace, user)
|