feat(knowdge-base): 知识库-dify配置增加一些top-k等参数
This commit is contained in:
1 parent
9722de1621
commit
7736a6991e
14 files changed
+587
-292
No files matched your search
@@ -16,7 +16,7 @@ from app.models import KbGroup, ScheduleTask
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncError, KbDifySyncService
|
||||
|
||||
DEFAULT_TOP_K = 5
|
||||
MAX_TOP_K = 20
|
||||
MAX_TOP_K = 10
|
||||
MIN_TOP_K = 1
|
||||
DEFAULT_SCORE_THRESHOLD = 0.3
|
||||
|
||||
@@ -178,7 +178,7 @@ def search_file_check_history(
|
||||
Args:
|
||||
task_id: ScheduleTask.id(Agent 绑定的 schedule_task_id)。
|
||||
query: 用户自然语言检索问题。
|
||||
top_k: 返回片段数,默认 5,最大 20。
|
||||
top_k: 返回片段数,默认 5,最大 10。
|
||||
score_threshold: 相似度阈值,默认 0.3。
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -702,7 +702,7 @@
|
||||
"top_k": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
"maximum": 10,
|
||||
"default": 5,
|
||||
"description": "返回片段数,默认 5"
|
||||
},
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
|
||||
用途:将知识库文档版本同步至 Dify Dataset,并提供 Dataset 创建、检索和远端文档管理能力。
|
||||
依赖:requests、知识库 ORM 模型及 settings_service 的运行时 Dify 配置。
|
||||
逻辑:知识库 Job/文件检核历史查询调用本服务;服务读取管理端配置并向 Dify Dataset API 发起请求,结果再写回本地同步记录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from math import isfinite
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -33,6 +37,54 @@ def _as_bool_setting(value: str | None) -> bool:
|
||||
return str(value or '').strip().lower() in ('true', '1', 'yes', 'on')
|
||||
|
||||
|
||||
def _as_int_setting(value: str | int | None, *, default: int, minimum: int, maximum: int) -> int:
|
||||
"""
|
||||
解析受边界约束的整数配置,兼容旧环境中尚未写入的新配置。
|
||||
|
||||
Args:
|
||||
value: 原始配置值。
|
||||
default: 原始值无效时使用的默认值。
|
||||
minimum: 允许的最小值。
|
||||
maximum: 允许的最大值。
|
||||
|
||||
Returns:
|
||||
int: 位于最小值和最大值之间的整数。
|
||||
"""
|
||||
try:
|
||||
parsed = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
parsed = default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def _as_float_setting(
|
||||
value: str | float | int | None,
|
||||
*,
|
||||
default: float,
|
||||
minimum: float,
|
||||
maximum: float,
|
||||
) -> float:
|
||||
"""
|
||||
解析受边界约束的浮点配置,兼容旧环境中尚未写入的新配置。
|
||||
|
||||
Args:
|
||||
value: 原始配置值。
|
||||
default: 原始值无效时使用的默认值。
|
||||
minimum: 允许的最小值。
|
||||
maximum: 允许的最大值。
|
||||
|
||||
Returns:
|
||||
float: 位于最小值和最大值之间的浮点数。
|
||||
"""
|
||||
try:
|
||||
parsed = float(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
parsed = default
|
||||
if not isfinite(parsed):
|
||||
parsed = default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def resolve_source_file_ext(version: KbDocumentVersion) -> str | None:
|
||||
"""Lowercase extension without dot, e.g. xlsx."""
|
||||
ext = str(version.source_file_ext or '').strip().lower().lstrip('.')
|
||||
@@ -50,7 +102,17 @@ class KbDifySyncError(RuntimeError):
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
"""封装知识库与 Dify Dataset API 的同步及检索交互。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
读取当前运行时 Dify 配置并初始化 Dataset API 客户端参数。
|
||||
|
||||
核心逻辑:管理端保存的 AppSetting 优先于部署环境变量;新建 Dataset 时使用其中的检索模型默认值。
|
||||
|
||||
Returns:
|
||||
None.
|
||||
"""
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
@@ -58,6 +120,15 @@ class KbDifySyncService:
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.reranking_enable = _as_bool_setting(settings.get('KB_DIFY_RERANKING_ENABLE', 'true'))
|
||||
self.top_k = _as_int_setting(settings.get('KB_DIFY_TOP_K'), default=5, minimum=1, maximum=10)
|
||||
self.score_threshold_enabled = _as_bool_setting(settings.get('KB_DIFY_SCORE_THRESHOLD_ENABLED'))
|
||||
self.score_threshold = _as_float_setting(
|
||||
settings.get('KB_DIFY_SCORE_THRESHOLD'),
|
||||
default=0.25,
|
||||
minimum=0.0,
|
||||
maximum=1.0,
|
||||
)
|
||||
self.process_mode = str(settings.get('KB_DIFY_PROCESS_MODE') or 'automatic').strip().lower()
|
||||
self.process_mode_excel = str(settings.get('KB_DIFY_PROCESS_MODE_EXCEL') or 'custom').strip().lower()
|
||||
self.segment_separator = _decode_separator(str(settings.get('KB_DIFY_SEGMENT_SEPARATOR') or '\\n\\n'))
|
||||
@@ -134,6 +205,21 @@ class KbDifySyncService:
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
"""
|
||||
在 Dify 中创建知识库 Dataset,并写入管理端配置的默认检索模型。
|
||||
|
||||
核心逻辑:组合权限、索引和 retrieval_model 配置后调用 Dify ``POST /datasets``;仅在本地分组尚未绑定 Dataset 时由同步流程触发。
|
||||
|
||||
Args:
|
||||
name: Dataset 名称,必须是知识库分组的非空显示名称。
|
||||
description: Dataset 说明;未提供时向 Dify 提交空字符串。
|
||||
|
||||
Returns:
|
||||
dict: Dify 创建 Dataset 接口返回的原始 JSON。
|
||||
|
||||
Raises:
|
||||
KbDifySyncError: Dify 地址、密钥未配置或远端创建请求失败。
|
||||
"""
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
@@ -142,10 +228,10 @@ class KbDifySyncService:
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 5,
|
||||
'score_threshold_enabled': True,
|
||||
'score_threshold': 0.25,
|
||||
'reranking_enable': self.reranking_enable,
|
||||
'top_k': self.top_k,
|
||||
'score_threshold_enabled': self.score_threshold_enabled,
|
||||
'score_threshold': self.score_threshold,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
@@ -219,7 +305,7 @@ class KbDifySyncService:
|
||||
Args:
|
||||
dataset_id: Dify Dataset UUID。
|
||||
query: 检索问题。
|
||||
top_k: 返回片段数(1–20)。
|
||||
top_k: 返回片段数(1–10)。
|
||||
score_threshold: 相似度阈值;为 None 时不启用阈值过滤。
|
||||
|
||||
Returns:
|
||||
@@ -228,10 +314,10 @@ class KbDifySyncService:
|
||||
normalized_query = str(query or '').strip()
|
||||
if not normalized_query:
|
||||
raise KbDifySyncError('检索 query 不能为空')
|
||||
normalized_top_k = max(1, min(int(top_k or 5), 20))
|
||||
normalized_top_k = _as_int_setting(top_k, default=5, minimum=1, maximum=10)
|
||||
retrieval_model: dict[str, object] = {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'reranking_enable': self.reranking_enable,
|
||||
'top_k': normalized_top_k,
|
||||
}
|
||||
if score_threshold is None:
|
||||
@@ -239,7 +325,12 @@ class KbDifySyncService:
|
||||
retrieval_model['score_threshold'] = None
|
||||
else:
|
||||
retrieval_model['score_threshold_enabled'] = True
|
||||
retrieval_model['score_threshold'] = max(0.0, min(float(score_threshold), 1.0))
|
||||
retrieval_model['score_threshold'] = _as_float_setting(
|
||||
score_threshold,
|
||||
default=0.3,
|
||||
minimum=0.0,
|
||||
maximum=1.0,
|
||||
)
|
||||
payload = {
|
||||
'query': normalized_query,
|
||||
'retrieval_model': retrieval_model,
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.sync_hash == sync_hash:
|
||||
remote_document_id = existing_record.remote_document_id
|
||||
remote_document_name = existing_record.remote_document_name
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
error_text = str(exc)
|
||||
remote_missing = (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
if not remote_missing:
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
if not remote_document_id:
|
||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_version_id == version.id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not record:
|
||||
record = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
dataset_name=dataset_name,
|
||||
remote_document_id=remote_document_id,
|
||||
remote_document_name=remote_document_name,
|
||||
status='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
record.remote_document_name = remote_document_name
|
||||
record.status = 'synced'
|
||||
record.sync_hash = sync_hash
|
||||
record.error_message = None
|
||||
record.synced_by_id = synced_by_id
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/settings_service.py
|
||||
文件用途:知识库 Dify 设置读写服务
|
||||
|
||||
用途:读取、校验并持久化知识库 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
|
||||
|
||||
|
||||
@@ -21,6 +26,11 @@ SETTING_DEFAULTS = {
|
||||
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/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',
|
||||
@@ -32,6 +42,137 @@ SETTING_DEFAULTS = {
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
@@ -49,7 +190,20 @@ def get_kb_dify_settings() -> dict:
|
||||
|
||||
|
||||
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(),
|
||||
|
||||
@@ -12,6 +12,10 @@ def _make_service(monkeypatch, **overrides):
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_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',
|
||||
@@ -71,6 +75,84 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 600
|
||||
|
||||
|
||||
def test_build_process_rule_uses_configured_segment_limits(monkeypatch):
|
||||
service = _make_service(
|
||||
monkeypatch,
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS='900',
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP='150',
|
||||
)
|
||||
rule = service._build_process_rule('docx')
|
||||
|
||||
# 断言管理端保存的分段参数会透传给 Dify 文档同步的自定义分段规则。
|
||||
assert rule['rules']['segmentation'] == {
|
||||
'separator': '\n\n',
|
||||
'max_tokens': 900,
|
||||
'chunk_overlap': 150,
|
||||
}
|
||||
|
||||
|
||||
def test_create_dataset_uses_admin_retrieval_settings(monkeypatch):
|
||||
service = _make_service(
|
||||
monkeypatch,
|
||||
KB_DIFY_RERANKING_ENABLE='true',
|
||||
KB_DIFY_TOP_K='8',
|
||||
KB_DIFY_SCORE_THRESHOLD_ENABLED='false',
|
||||
KB_DIFY_SCORE_THRESHOLD='0.45',
|
||||
)
|
||||
captured: dict = {}
|
||||
|
||||
def fake_request(method, path, **kwargs):
|
||||
captured['method'] = method
|
||||
captured['path'] = path
|
||||
captured['json'] = kwargs.get('json')
|
||||
return {'id': 'dataset-1', 'name': 'demo'}
|
||||
|
||||
monkeypatch.setattr(service, '_request', fake_request)
|
||||
service.create_dataset(name='demo', description=None)
|
||||
|
||||
# 断言管理端保存的检索模型参数原样传给新建 Dataset,而不是继续使用代码常量。
|
||||
retrieval_model = captured['json']['retrieval_model']
|
||||
assert captured['method'] == 'POST'
|
||||
assert captured['path'] == '/datasets'
|
||||
assert retrieval_model == {
|
||||
'search_method': 'hybrid_search',
|
||||
'reranking_enable': True,
|
||||
'top_k': 8,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': 0.45,
|
||||
}
|
||||
|
||||
|
||||
def test_create_dataset_clamps_legacy_top_k_to_ten(monkeypatch):
|
||||
service = _make_service(monkeypatch, KB_DIFY_TOP_K='17')
|
||||
captured: dict = {}
|
||||
|
||||
def fake_request(method, path, **kwargs):
|
||||
captured['json'] = kwargs.get('json')
|
||||
return {'id': 'dataset-1', 'name': 'demo'}
|
||||
|
||||
monkeypatch.setattr(service, '_request', fake_request)
|
||||
service.create_dataset(name='demo', description=None)
|
||||
|
||||
# 断言历史配置即使仍为旧上限 20 内的值,也不会向 Dify 发送超过新上限 10 的 Top K。
|
||||
assert captured['json']['retrieval_model']['top_k'] == 10
|
||||
|
||||
|
||||
def test_retrieve_dataset_uses_reranking_default(monkeypatch):
|
||||
service = _make_service(monkeypatch, KB_DIFY_RERANKING_ENABLE='true')
|
||||
captured: dict = {}
|
||||
|
||||
def fake_request(method, path, **kwargs):
|
||||
captured['json'] = kwargs.get('json')
|
||||
return {'records': []}
|
||||
|
||||
monkeypatch.setattr(service, '_request', fake_request)
|
||||
service.retrieve_dataset(dataset_id='dataset-1', query='历史报告')
|
||||
|
||||
# 断言历史检索请求也沿用管理端的默认重排序开关。
|
||||
assert captured['json']['retrieval_model']['reranking_enable'] is True
|
||||
|
||||
|
||||
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
service = _make_service(monkeypatch, KB_DIFY_REMOVE_URLS='true')
|
||||
rule = service._build_process_rule('csv')
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。
|
||||
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
|
||||
- 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。
|
||||
|
||||
## 设备维保助手
|
||||
|
||||
|
||||
@@ -710,7 +710,7 @@
|
||||
"top_k": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
"maximum": 10,
|
||||
"default": 5,
|
||||
"description": "返回片段数,默认 5"
|
||||
},
|
||||
@@ -945,4 +945,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,12 @@ export interface KbDifySettings {
|
||||
KB_DIFY_INDEXING_TECHNIQUE: string;
|
||||
KB_DIFY_SEARCH_METHOD: string;
|
||||
KB_DIFY_DOC_FORM: string;
|
||||
KB_DIFY_RERANKING_ENABLE: boolean | string;
|
||||
KB_DIFY_TOP_K: number | string;
|
||||
KB_DIFY_SCORE_THRESHOLD_ENABLED: boolean | string;
|
||||
KB_DIFY_SCORE_THRESHOLD: number | string;
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS: number | string;
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP: number | string;
|
||||
dify_api_configured?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/kb/components/DifySettingsDialog.vue
|
||||
* 知识库 Dify 配置弹窗。
|
||||
* 用途:提供知识库 Dify 连接及默认同步参数的查看、编辑和保存界面。
|
||||
* 依赖:Vue 响应式 API、Vue I18n、kb.api 的 Dify 设置读写接口。
|
||||
* 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。
|
||||
*/
|
||||
|
||||
import { reactive, ref, watch } from 'vue';
|
||||
@@ -21,10 +23,47 @@ const form = reactive({
|
||||
KB_DIFY_INDEXING_TECHNIQUE: 'high_quality',
|
||||
KB_DIFY_SEARCH_METHOD: 'semantic_search',
|
||||
KB_DIFY_DOC_FORM: 'text_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_SEGMENT_MAX_TOKENS: 600,
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP: 100,
|
||||
});
|
||||
|
||||
/**
|
||||
* 将后端持久化的布尔配置转换为 checkbox 可消费的布尔值。
|
||||
* 核心逻辑:兼容运行时配置服务返回的字符串与新提交表单返回的布尔值。
|
||||
* @param value - 待转换的 Dify 配置值。
|
||||
* @returns checkbox 使用的布尔值。
|
||||
*/
|
||||
const toBooleanSetting = (value: boolean | string | undefined): boolean => value === true || value === 'true';
|
||||
|
||||
/**
|
||||
* 将后端持久化的数值配置转换为 number input 可消费的有限数值。
|
||||
* 核心逻辑:保留 0 这类合法阈值;仅在缺失或非数值时使用指定默认值。
|
||||
* @param value - 待转换的 Dify 配置值。
|
||||
* @param fallback - 原始值无效时显示的默认值。
|
||||
* @returns number input 使用的有限数值。
|
||||
*/
|
||||
const toNumberSetting = (value: number | string | undefined, fallback: number): number => {
|
||||
if (value === '' || value === undefined) return fallback;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
};
|
||||
|
||||
/**
|
||||
* 关闭 Dify 设置弹窗而不更改当前表单数据。
|
||||
* 核心逻辑:向父组件发送 close 事件,由父组件更新弹窗可见状态。
|
||||
* @returns void
|
||||
*/
|
||||
const close = () => emit('close');
|
||||
|
||||
/**
|
||||
* 在弹窗打开时读取当前知识库 Dify 设置并填充表单。
|
||||
* 核心逻辑:调用设置查询接口,并把持久化的字符串布尔值/数值转换为表单控件所需类型;读取失败时向父组件发送已本地化的错误消息。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadSettings = async () => {
|
||||
loading.value = true;
|
||||
const settings = await getKbDifySettings();
|
||||
@@ -33,9 +72,21 @@ const loadSettings = async () => {
|
||||
emit('error', t('kbDifySettings.msg.loadFailed'));
|
||||
return;
|
||||
}
|
||||
Object.assign(form, settings);
|
||||
Object.assign(form, settings, {
|
||||
KB_DIFY_RERANKING_ENABLE: toBooleanSetting(settings.KB_DIFY_RERANKING_ENABLE),
|
||||
KB_DIFY_TOP_K: toNumberSetting(settings.KB_DIFY_TOP_K, 5),
|
||||
KB_DIFY_SCORE_THRESHOLD_ENABLED: toBooleanSetting(settings.KB_DIFY_SCORE_THRESHOLD_ENABLED),
|
||||
KB_DIFY_SCORE_THRESHOLD: toNumberSetting(settings.KB_DIFY_SCORE_THRESHOLD, 0.25),
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS: toNumberSetting(settings.KB_DIFY_SEGMENT_MAX_TOKENS, 600),
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP: toNumberSetting(settings.KB_DIFY_SEGMENT_CHUNK_OVERLAP, 100),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存当前表单中的 Dify 设置,并在成功后关闭弹窗。
|
||||
* 核心逻辑:提交设置更新接口;失败反馈接口错误或本地化兜底消息,成功反馈后关闭。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const save = async () => {
|
||||
saving.value = true;
|
||||
const result = await updateKbDifySettings(form);
|
||||
@@ -55,10 +106,10 @@ watch(() => props.open, (open) => {
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="dialog-overlay" @click="close">
|
||||
<div class="dialog-panel max-w-3xl p-6" @click.stop>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="dialog-panel max-w-3xl max-h-[92vh] overflow-y-auto" @click.stop>
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="section-title text-xl">{{ t('kbDifySettings.title') }}</h3>
|
||||
<h3 class="section-title">{{ t('kbDifySettings.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('kbDifySettings.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" @click="close">
|
||||
@@ -66,48 +117,72 @@ watch(() => props.open, (open) => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifySettings.loading') }}</div>
|
||||
<div v-else class="mt-6 grid gap-4 md:grid-cols-2 form-stack">
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="label-field block">Dify Base URL</span>
|
||||
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
|
||||
<div v-if="loading" class="px-5 sm:px-8 py-16 text-center text-sm text-muted">{{ t('kbDifySettings.loading') }}</div>
|
||||
<div v-else class="px-5 sm:px-8 py-5 grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.baseUrl') }}</span>
|
||||
<input v-model="form.DIFY_API_BASE" class="input-field text-sm" placeholder="https://api.dify.ai/v1" />
|
||||
</label>
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="label-field block">Dify API Key</span>
|
||||
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.apiKey') }}</span>
|
||||
<input v-model="form.DIFY_API_KEY" class="input-field text-sm" placeholder="app-..." />
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Permission</span>
|
||||
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
|
||||
<option value="only_me">only_me</option>
|
||||
<option value="all_team_members">all_team_members</option>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.permission') }}</span>
|
||||
<select v-model="form.KB_DIFY_PERMISSION" class="input-field text-sm">
|
||||
<option value="only_me">{{ t('kbDifySettings.options.permission.onlyMe') }}</option>
|
||||
<option value="all_team_members">{{ t('kbDifySettings.options.permission.allTeamMembers') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Indexing Technique</span>
|
||||
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
|
||||
<option value="high_quality">high_quality</option>
|
||||
<option value="economy">economy</option>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.indexingTechnique') }}</span>
|
||||
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field text-sm">
|
||||
<option value="high_quality">{{ t('kbDifySettings.options.indexingTechnique.highQuality') }}</option>
|
||||
<option value="economy">{{ t('kbDifySettings.options.indexingTechnique.economy') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Search Method</span>
|
||||
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
|
||||
<option value="semantic_search">semantic_search</option>
|
||||
<option value="hybrid_search">hybrid_search</option>
|
||||
<option value="full_text_search">full_text_search</option>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.searchMethod') }}</span>
|
||||
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field text-sm">
|
||||
<option value="semantic_search">{{ t('kbDifySettings.options.searchMethod.semanticSearch') }}</option>
|
||||
<option value="hybrid_search">{{ t('kbDifySettings.options.searchMethod.hybridSearch') }}</option>
|
||||
<option value="full_text_search">{{ t('kbDifySettings.options.searchMethod.fullTextSearch') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Doc Form</span>
|
||||
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
|
||||
<option value="text_model">text_model</option>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.documentForm') }}</span>
|
||||
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field text-sm">
|
||||
<option value="text_model">{{ t('kbDifySettings.options.documentForm.textModel') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 space-y-0">
|
||||
<input v-model="form.KB_DIFY_RERANKING_ENABLE" type="checkbox" class="h-4 w-4" />
|
||||
<span class="label-field">{{ t('kbDifySettings.fields.rerankingEnable') }}</span>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.topK') }}</span>
|
||||
<input v-model.number="form.KB_DIFY_TOP_K" type="number" min="1" max="10" step="1" class="input-field text-sm" />
|
||||
</label>
|
||||
<label class="flex items-center gap-2 space-y-0">
|
||||
<input v-model="form.KB_DIFY_SCORE_THRESHOLD_ENABLED" type="checkbox" class="h-4 w-4" />
|
||||
<span class="label-field">{{ t('kbDifySettings.fields.scoreThresholdEnabled') }}</span>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.scoreThreshold') }}</span>
|
||||
<input v-model.number="form.KB_DIFY_SCORE_THRESHOLD" type="number" min="0" max="1" step="0.01" class="input-field text-sm" :disabled="!form.KB_DIFY_SCORE_THRESHOLD_ENABLED" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.segmentMaxTokens') }}</span>
|
||||
<input v-model.number="form.KB_DIFY_SEGMENT_MAX_TOKENS" type="number" min="1" step="1" class="input-field text-sm" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="label-field block">{{ t('kbDifySettings.fields.segmentChunkOverlap') }}</span>
|
||||
<input v-model.number="form.KB_DIFY_SEGMENT_CHUNK_OVERLAP" type="number" min="0" step="1" class="input-field text-sm" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button type="button" class="btn-secondary" @click="close">
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="close">
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" :disabled="saving" @click="save">
|
||||
|
||||
@@ -5,6 +5,38 @@
|
||||
"loading": "Loading settings...",
|
||||
"save": "Save Settings",
|
||||
"saving": "Saving...",
|
||||
"fields": {
|
||||
"baseUrl": "Dify Base URL",
|
||||
"apiKey": "Dify API Key",
|
||||
"permission": "Visibility permission",
|
||||
"indexingTechnique": "Indexing mode",
|
||||
"searchMethod": "Search Method",
|
||||
"documentForm": "Document Form",
|
||||
"rerankingEnable": "Enable reranking",
|
||||
"topK": "Result count (Top K)",
|
||||
"scoreThresholdEnabled": "Enable score threshold",
|
||||
"scoreThreshold": "Score threshold",
|
||||
"segmentMaxTokens": "Maximum tokens per segment",
|
||||
"segmentChunkOverlap": "Overlapping tokens per segment"
|
||||
},
|
||||
"options": {
|
||||
"permission": {
|
||||
"onlyMe": "Only me",
|
||||
"allTeamMembers": "All team members"
|
||||
},
|
||||
"indexingTechnique": {
|
||||
"highQuality": "High quality",
|
||||
"economy": "Economy"
|
||||
},
|
||||
"searchMethod": {
|
||||
"semanticSearch": "Semantic search",
|
||||
"hybridSearch": "Hybrid search",
|
||||
"fullTextSearch": "Full-text search"
|
||||
},
|
||||
"documentForm": {
|
||||
"textModel": "Text model"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load Dify settings",
|
||||
"saveFailed": "Failed to save Dify settings",
|
||||
|
||||
@@ -5,6 +5,38 @@
|
||||
"loading": "กำลังโหลดการตั้งค่า...",
|
||||
"save": "บันทึกการตั้งค่า",
|
||||
"saving": "กำลังบันทึก...",
|
||||
"fields": {
|
||||
"baseUrl": "URL พื้นฐานของ Dify",
|
||||
"apiKey": "คีย์ API ของ Dify",
|
||||
"permission": "สิทธิ์การเข้าถึง",
|
||||
"indexingTechnique": "โหมดการทำดัชนี",
|
||||
"searchMethod": "วิธีการค้นหา",
|
||||
"documentForm": "รูปแบบเอกสาร",
|
||||
"rerankingEnable": "เปิดใช้การจัดอันดับใหม่",
|
||||
"topK": "จำนวนผลลัพธ์ (Top K)",
|
||||
"scoreThresholdEnabled": "เปิดใช้เกณฑ์คะแนน",
|
||||
"scoreThreshold": "เกณฑ์คะแนน",
|
||||
"segmentMaxTokens": "จำนวนโทเค็นสูงสุดต่อส่วน",
|
||||
"segmentChunkOverlap": "จำนวนโทเค็นที่ซ้อนทับระหว่างส่วน"
|
||||
},
|
||||
"options": {
|
||||
"permission": {
|
||||
"onlyMe": "เฉพาะฉัน",
|
||||
"allTeamMembers": "สมาชิกทีมทุกคน"
|
||||
},
|
||||
"indexingTechnique": {
|
||||
"highQuality": "คุณภาพสูง",
|
||||
"economy": "ประหยัด"
|
||||
},
|
||||
"searchMethod": {
|
||||
"semanticSearch": "ค้นหาเชิงความหมาย",
|
||||
"hybridSearch": "ค้นหาแบบผสม",
|
||||
"fullTextSearch": "ค้นหาแบบข้อความเต็ม"
|
||||
},
|
||||
"documentForm": {
|
||||
"textModel": "โมเดลข้อความ"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"loadFailed": "โหลดการตั้งค่า Dify ล้มเหลว",
|
||||
"saveFailed": "บันทึกการตั้งค่า Dify ล้มเหลว",
|
||||
|
||||
@@ -5,6 +5,38 @@
|
||||
"loading": "正在加载设置...",
|
||||
"save": "保存设置",
|
||||
"saving": "保存中...",
|
||||
"fields": {
|
||||
"baseUrl": "Dify 基础 URL",
|
||||
"apiKey": "Dify API 密钥",
|
||||
"permission": "可见权限",
|
||||
"indexingTechnique": "索引模式",
|
||||
"searchMethod": "检索方式",
|
||||
"documentForm": "文档形式",
|
||||
"rerankingEnable": "启用重排序",
|
||||
"topK": "返回片段数(Top K)",
|
||||
"scoreThresholdEnabled": "启用相似度阈值",
|
||||
"scoreThreshold": "相似度阈值",
|
||||
"segmentMaxTokens": "分段最大 Token 数",
|
||||
"segmentChunkOverlap": "分段重叠 Token 数"
|
||||
},
|
||||
"options": {
|
||||
"permission": {
|
||||
"onlyMe": "仅自己",
|
||||
"allTeamMembers": "所有团队成员"
|
||||
},
|
||||
"indexingTechnique": {
|
||||
"highQuality": "高质量",
|
||||
"economy": "经济型"
|
||||
},
|
||||
"searchMethod": {
|
||||
"semanticSearch": "语义检索",
|
||||
"hybridSearch": "混合检索",
|
||||
"fullTextSearch": "全文检索"
|
||||
},
|
||||
"documentForm": {
|
||||
"textModel": "文本模型"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"loadFailed": "加载 Dify 设置失败",
|
||||
"saveFailed": "保存 Dify 设置失败",
|
||||
|
||||
@@ -5,6 +5,38 @@
|
||||
"loading": "正在載入設定...",
|
||||
"save": "儲存設定",
|
||||
"saving": "儲存中...",
|
||||
"fields": {
|
||||
"baseUrl": "Dify 基礎 URL",
|
||||
"apiKey": "Dify API 金鑰",
|
||||
"permission": "可見權限",
|
||||
"indexingTechnique": "索引模式",
|
||||
"searchMethod": "檢索方式",
|
||||
"documentForm": "文件形式",
|
||||
"rerankingEnable": "啟用重排序",
|
||||
"topK": "返回片段數(Top K)",
|
||||
"scoreThresholdEnabled": "啟用相似度閾值",
|
||||
"scoreThreshold": "相似度閾值",
|
||||
"segmentMaxTokens": "分段最大 Token 數",
|
||||
"segmentChunkOverlap": "分段重疊 Token 數"
|
||||
},
|
||||
"options": {
|
||||
"permission": {
|
||||
"onlyMe": "僅自己",
|
||||
"allTeamMembers": "所有團隊成員"
|
||||
},
|
||||
"indexingTechnique": {
|
||||
"highQuality": "高品質",
|
||||
"economy": "經濟型"
|
||||
},
|
||||
"searchMethod": {
|
||||
"semanticSearch": "語意檢索",
|
||||
"hybridSearch": "混合檢索",
|
||||
"fullTextSearch": "全文檢索"
|
||||
},
|
||||
"documentForm": {
|
||||
"textModel": "文字模型"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"loadFailed": "載入 Dify 設定失敗",
|
||||
"saveFailed": "儲存 Dify 設定失敗",
|
||||
|
||||
Reference in new issue
Block a user