fix(platform): 汇总知识库问答与图表展示修复

This commit is contained in:
HTEWJ\26070045 committed 2026-08-06 17:28:08 +08:00
1 parent f615e56bb9
commit 59ff2dd9c7
41 files changed
+4579 -766

No files matched your search

@@ -7,6 +7,7 @@ from __future__ import annotations
from datetime import datetime
import hashlib
import re
import time
from pathlib import Path
import requests
@@ -19,6 +20,8 @@ from app.services.knowledge_cleaning.settings_service import get_kb_dify_setting
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
_DIFY_INDEXING_SUCCEEDED = frozenset({'completed', 'completed_successfully', 'succeeded', 'success'})
_DIFY_INDEXING_FAILED = frozenset({'error', 'failed', 'failure'})
def _decode_separator(value: str) -> str:
@@ -65,6 +68,9 @@ class KbDifySyncService:
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
# Dify create/update 仅表示已接收文本,索引仍在后台异步执行。
self.indexing_wait_seconds = 60
self.indexing_poll_seconds = 2
def _build_process_rule(self, source_ext: str | None = None) -> dict:
ext = str(source_ext or '').strip().lower().lstrip('.')
@@ -137,9 +143,9 @@ class KbDifySyncService:
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
'top_k': 5,
'score_threshold_enabled': True,
'score_threshold': 0.25,
},
}
return self._request('POST', '/datasets', json=payload)
@@ -243,6 +249,54 @@ class KbDifySyncService:
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
def wait_for_document_indexing(
self,
*,
dataset_id: str,
document_id: str,
initial_payload: dict | None = None,
) -> dict:
"""
确认 Dify 异步索引的最终结果,禁止把“已受理”当作“已可检索”。
核心逻辑:读取创建/更新响应或文档详情中的 indexing_status,直到 completed 或 error。
超时也按失败处理,避免工作台把仍未可检索的文件标为同步成功。
Args:
dataset_id: Dify Dataset ID,不能为空。
document_id: Dify 文档 ID,不能为空。
initial_payload: create/update 接口的原始响应,可减少一次详情请求。
Returns:
含 indexing_status 和 Dify 文档详情的字典。
Raises:
KbDifySyncError: Dify 索引失败、状态缺失或在限定时间内未完成。
"""
if not dataset_id or not document_id:
raise KbDifySyncError('Dify 文档索引校验缺少 dataset_id 或 document_id')
payload = initial_payload or {}
deadline = time.monotonic() + self.indexing_wait_seconds
last_status = ''
while True:
document = payload.get('document') if isinstance(payload, dict) else None
document = document if isinstance(document, dict) else payload
document = document if isinstance(document, dict) else {}
status = str(document.get('indexing_status') or '').strip().lower()
error = str(document.get('error') or document.get('error_message') or '').strip()
last_status = status or last_status
if status in _DIFY_INDEXING_SUCCEEDED:
return {'indexing_status': status, 'document': document}
if status in _DIFY_INDEXING_FAILED:
raise KbDifySyncError(error or f'Dify 文档索引失败(状态:{status})')
if time.monotonic() >= deadline:
raise KbDifySyncError(
f'Dify 文档索引未在 {self.indexing_wait_seconds} 秒内完成(当前状态:{last_status or "unknown"}),请在 Dify 查看文档错误后重试'
)
time.sleep(self.indexing_poll_seconds)
payload = self.get_document(dataset_id=dataset_id, document_id=document_id)
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self._request(
'DELETE',
@@ -274,9 +328,30 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
def _is_remote_document_missing(error_text: str) -> bool:
"""
判断同步记录指向的 Dify 远端文档是否已失效。
Dify 在不同版本中会对已删除或不可访问的文档返回 404/not_found,
也可能返回 400 invalid_param 和 ``Document is not available``。两种结果都表示
不能继续 update-by-text,调用方必须新建远端文档并刷新本地映射。
Args:
error_text: Dify HTTP 异常转换后的完整错误文本。
Returns:
远端文档已失效时返回 True;其他 API 错误返回 False,避免掩盖配置或网络问题。
"""
normalized_error = str(error_text or '').lower()
return (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
('404' in normalized_error and (
'document not found' in normalized_error
or '"code":"not_found"' in normalized_error
))
or (
'400' in normalized_error
and '"code":"invalid_param"' in normalized_error
and 'document is not available' in normalized_error
)
)
@@ -290,7 +365,90 @@ def _resolve_upload_name(version: KbDocumentVersion) -> str:
return f'文档-{version.document_id}'
def _save_sync_record(
*,
version: KbDocumentVersion,
dataset_id: str,
dataset_name: str,
remote_document_id: str,
remote_document_name: str | None,
sync_hash: str,
synced_by_id: int | None,
status: str,
error_message: str | None,
) -> KbDifySyncRecord:
"""
持久化本地到 Dify 的映射及最终索引结果。
核心逻辑:同一版本和远端文档复用记录;成功与失败均保存,
让工作台能展示 Dify 的真实索引状态和原因。
Args:
version: 已上传且归属有效分组的文档版本。
dataset_id: Dify Dataset ID。
remote_document_id: Dify 文档 ID。
status: 本地同步状态,仅传 synced 或 failed。
error_message: Dify 索引失败详情;成功时传 None。
Returns:
已 flush 的 KbDifySyncRecord。
"""
document = version.document
group = document.group
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=status,
sync_hash=sync_hash,
error_message=error_message,
synced_by_id=synced_by_id,
synced_at=datetime.utcnow(),
)
add_and_flush_with_sequence_retry(record, 'kb_dify_sync_records')
return record
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = status
record.sync_hash = sync_hash
record.error_message = error_message
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
return record
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
"""
同步清洗后的知识库版本,并以 Dify 最终索引结果作为成功标准。
核心逻辑:上传/更新文本后轮询 Dify 的 indexing_status;仅 completed 写入 synced,
error 时持久化失败原因并抛错,由调用任务将工作台同步步骤标红。
Args:
document_version_id: 当前待同步的 KbDocumentVersion 主键。
synced_by_id: 发起同步的用户 ID,可为空(自动任务)。
Returns:
含 Dify 映射与 indexing_status 的同步结果。
Raises:
KbDifySyncError: 本地文本、Dify API 或 Dify 索引失败。
"""
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
@@ -318,7 +476,13 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = _resolve_upload_name(version)
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
indexing_payload: dict | None = None
if (
existing_record
and existing_record.dataset_id == dataset_id
and existing_record.sync_hash == sync_hash
and existing_record.status == 'synced'
):
try:
payload = service.get_document(
dataset_id=dataset_id,
@@ -326,6 +490,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name
indexing_payload = payload
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
@@ -337,6 +502,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
@@ -357,6 +523,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
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 upload_name
indexing_payload = payload
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
@@ -366,42 +533,43 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
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,
try:
indexing_result = service.wait_for_document_indexing(
dataset_id=dataset_id,
document_id=remote_document_id,
initial_payload=indexing_payload,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
except KbDifySyncError as exc:
_save_sync_record(
version=version,
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,
status='failed',
error_message=str(exc),
)
add_and_flush_with_sequence_retry(record, "kb_dify_sync_records")
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
db.session.commit()
raise
record.synced_at = datetime.utcnow()
_save_sync_record(
version=version,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
sync_hash=sync_hash,
synced_by_id=synced_by_id,
status='synced',
error_message=None,
)
db.session.commit()
content_changed = previous_sync_hash != sync_hash
@@ -438,6 +606,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'indexing_status': indexing_result['indexing_status'],
'source_path': source_path,
}
@@ -18,14 +18,16 @@ SETTING_DEFAULTS = {
'DIFY_API_KEY': '',
'KB_DIFY_PERMISSION': 'only_me',
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
# 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。
'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': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
'KB_DIFY_REMOVE_URLS': 'false',
}
@@ -622,6 +622,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
except KbDifySyncError as exc:
version.status = 'ready'
version.error_message = str(exc)
job.status = 'failed'
job.progress = 100
job.error_message = str(exc)
@@ -632,6 +633,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
except Exception as exc:
version.status = 'ready'
version.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
job.status = 'failed'
job.progress = 100
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
@@ -642,6 +644,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
version.status = 'synced'
version.error_message = None
job.status = 'success'
job.progress = 100
job.message = '已同步到 Dify'