239 lines
8.8 KiB
Python
239 lines
8.8 KiB
Python
"""
|
|
backend/app/services/knowledge_cleaning/settings_service.py
|
|
|
|
用途:读取、校验并持久化知识库 Dify 连接、同步和检索模型默认配置。
|
|
依赖:AppSetting、env_persistence、Flask current_app 及知识库同步相关 ORM 模型。
|
|
逻辑:知识库 Dify API 调用本模块读写运行时配置;KbDifySyncService 随后读取这些配置以创建 Dataset 或检索文档。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from math import isfinite
|
|
|
|
from flask import current_app
|
|
|
|
from app import db
|
|
from app.core.config.env_persistence import persist_env_settings
|
|
from app.core.errors import ValidationError
|
|
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
|
|
|
|
|
|
SETTING_DEFAULTS = {
|
|
'DIFY_API_BASE': '',
|
|
'DIFY_API_KEY': '',
|
|
'KB_DIFY_PERMISSION': 'only_me',
|
|
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
|
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。
|
|
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
|
|
'KB_DIFY_DOC_FORM': 'text_model',
|
|
# Dify Dataset 创建/检索使用的默认 retrieval_model 参数。
|
|
'KB_DIFY_RERANKING_ENABLE': 'true',
|
|
'KB_DIFY_TOP_K': '5',
|
|
'KB_DIFY_SCORE_THRESHOLD_ENABLED': 'true',
|
|
'KB_DIFY_SCORE_THRESHOLD': '0.25',
|
|
# 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。
|
|
'KB_DIFY_PROCESS_MODE': 'custom',
|
|
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
|
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
|
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
|
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
|
|
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
|
'KB_DIFY_REMOVE_URLS': 'false',
|
|
}
|
|
|
|
|
|
def _normalize_retrieval_settings(values: dict[str, object]) -> dict[str, object]:
|
|
"""
|
|
校验并规范化管理端提交的 Dify 检索及文档分段参数,防止无效值持久化后导致 Dify 请求失败。
|
|
|
|
Args:
|
|
values: API 提交的配置键值,可能只包含部分可编辑项。
|
|
|
|
Returns:
|
|
dict[str, object]: 保留其他字段,并将布尔值和数值转换为可安全持久化的标准值。
|
|
|
|
Raises:
|
|
ValidationError: 布尔值、Top K、相似度阈值或分段参数不在支持范围内。
|
|
"""
|
|
normalized = dict(values)
|
|
for key in ('KB_DIFY_RERANKING_ENABLE', 'KB_DIFY_SCORE_THRESHOLD_ENABLED'):
|
|
if key not in normalized:
|
|
continue
|
|
value = normalized[key]
|
|
if isinstance(value, bool):
|
|
normalized[key] = value
|
|
continue
|
|
text = str(value or '').strip().lower()
|
|
if text not in ('true', 'false'):
|
|
raise ValidationError(f'{key} 必须为 true 或 false')
|
|
normalized[key] = text == 'true'
|
|
|
|
if 'KB_DIFY_TOP_K' in normalized:
|
|
raw_top_k = normalized['KB_DIFY_TOP_K']
|
|
try:
|
|
if isinstance(raw_top_k, bool):
|
|
raise ValueError
|
|
top_k = int(str(raw_top_k).strip())
|
|
except (TypeError, ValueError):
|
|
raise ValidationError('KB_DIFY_TOP_K 必须是 1 到 10 的整数')
|
|
if not 1 <= top_k <= 10:
|
|
raise ValidationError('KB_DIFY_TOP_K 必须是 1 到 10 的整数')
|
|
normalized['KB_DIFY_TOP_K'] = top_k
|
|
|
|
if 'KB_DIFY_SCORE_THRESHOLD' in normalized:
|
|
raw_threshold = normalized['KB_DIFY_SCORE_THRESHOLD']
|
|
try:
|
|
if isinstance(raw_threshold, bool):
|
|
raise ValueError
|
|
threshold = float(str(raw_threshold).strip())
|
|
except (TypeError, ValueError):
|
|
raise ValidationError('KB_DIFY_SCORE_THRESHOLD 必须是 0 到 1 的数值')
|
|
if not isfinite(threshold) or not 0 <= threshold <= 1:
|
|
raise ValidationError('KB_DIFY_SCORE_THRESHOLD 必须是 0 到 1 的数值')
|
|
normalized['KB_DIFY_SCORE_THRESHOLD'] = threshold
|
|
|
|
segment_max_tokens = _normalize_positive_integer_setting(
|
|
normalized,
|
|
'KB_DIFY_SEGMENT_MAX_TOKENS',
|
|
minimum=1,
|
|
maximum=10000,
|
|
)
|
|
segment_chunk_overlap = _normalize_positive_integer_setting(
|
|
normalized,
|
|
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
|
|
minimum=0,
|
|
maximum=9999,
|
|
)
|
|
effective_segment_max_tokens = segment_max_tokens if segment_max_tokens is not None else _get_positive_integer_setting(
|
|
'KB_DIFY_SEGMENT_MAX_TOKENS',
|
|
default=600,
|
|
)
|
|
effective_segment_chunk_overlap = segment_chunk_overlap if segment_chunk_overlap is not None else _get_positive_integer_setting(
|
|
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
|
|
default=100,
|
|
)
|
|
if effective_segment_chunk_overlap >= effective_segment_max_tokens:
|
|
raise ValidationError('KB_DIFY_SEGMENT_CHUNK_OVERLAP 必须小于 KB_DIFY_SEGMENT_MAX_TOKENS')
|
|
|
|
return normalized
|
|
|
|
|
|
def _normalize_positive_integer_setting(
|
|
values: dict[str, object],
|
|
key: str,
|
|
*,
|
|
minimum: int,
|
|
maximum: int,
|
|
) -> int | None:
|
|
"""
|
|
校验并标准化一个可选的正整数运行时配置。
|
|
|
|
Args:
|
|
values: 管理端提交的可持久化配置。
|
|
key: 要校验的配置键。
|
|
minimum: 允许的最小整数。
|
|
maximum: 允许的最大整数。
|
|
|
|
Returns:
|
|
int | None: 键未提交时返回 None,否则返回已标准化整数。
|
|
|
|
Raises:
|
|
ValidationError: 值不是指定范围内的整数。
|
|
"""
|
|
if key not in values:
|
|
return None
|
|
raw_value = values[key]
|
|
try:
|
|
if isinstance(raw_value, bool):
|
|
raise ValueError
|
|
normalized_value = int(str(raw_value).strip())
|
|
except (TypeError, ValueError):
|
|
raise ValidationError(f'{key} 必须是 {minimum} 到 {maximum} 的整数')
|
|
if not minimum <= normalized_value <= maximum:
|
|
raise ValidationError(f'{key} 必须是 {minimum} 到 {maximum} 的整数')
|
|
values[key] = normalized_value
|
|
return normalized_value
|
|
|
|
|
|
def _get_positive_integer_setting(key: str, *, default: int) -> int:
|
|
"""
|
|
读取当前已保存的整数配置,用于校验 PATCH 中未提交的关联字段。
|
|
|
|
Args:
|
|
key: 要读取的运行时配置键。
|
|
default: 当前值缺失或无效时使用的安全默认值。
|
|
|
|
Returns:
|
|
int: 当前设置或安全默认值。
|
|
"""
|
|
try:
|
|
value = int(_get_setting_value(key))
|
|
except (TypeError, ValueError):
|
|
return default
|
|
return value if value >= 0 else default
|
|
|
|
|
|
def _get_setting_value(key: str) -> str:
|
|
row = db.session.get(AppSetting, key)
|
|
if row and row.value is not None:
|
|
return row.value
|
|
config_value = current_app.config.get(key)
|
|
if config_value is not None:
|
|
return str(config_value)
|
|
return str(os.getenv(key, SETTING_DEFAULTS.get(key, '')))
|
|
|
|
|
|
def get_kb_dify_settings() -> dict:
|
|
payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS}
|
|
payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY'))
|
|
return payload
|
|
|
|
|
|
def save_kb_dify_settings(values: dict[str, object]) -> dict:
|
|
"""
|
|
保存知识库 Dify 配置,并在写入前校验检索参数的类型与取值范围。
|
|
|
|
Args:
|
|
values: 管理端提交的部分或全部知识库 Dify 设置。
|
|
|
|
Returns:
|
|
dict: 读取后的完整设置和 Dify API Key 是否已配置标记。
|
|
|
|
Raises:
|
|
ValidationError: Top K、阈值或布尔开关无效。
|
|
"""
|
|
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
|
|
allowed = _normalize_retrieval_settings(allowed)
|
|
persisted = persist_env_settings(allowed)
|
|
return {
|
|
**get_kb_dify_settings(),
|
|
**persisted,
|
|
'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()),
|
|
}
|
|
|
|
|
|
def get_kb_dify_health_payload() -> dict:
|
|
settings = get_kb_dify_settings()
|
|
base_url = settings.get('DIFY_API_BASE') or ''
|
|
api_key = settings.get('DIFY_API_KEY') or ''
|
|
|
|
payload = {
|
|
'dify_base_url': base_url,
|
|
'dify_api_configured': bool(api_key),
|
|
'api': {
|
|
'configured': bool(api_key),
|
|
'reachable': False,
|
|
'dataset_count': None,
|
|
'error': None,
|
|
},
|
|
'local_sync_health': {
|
|
'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(),
|
|
'sync_records': db.session.query(KbDifySyncRecord).count(),
|
|
'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(),
|
|
'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(),
|
|
'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(),
|
|
'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(),
|
|
},
|
|
}
|
|
return payload
|