fix(platform): 合并本地修复到测试环境
This commit is contained in:
commit
975e8bbcf5
41 files changed
+4564
-768
No files matched your search
File diff suppressed because it is too large.
Load diff
+110
-11
@@ -1,6 +1,9 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
|
||||
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||||
逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
@@ -144,6 +147,12 @@ def _kb_storage_root() -> Path:
|
||||
return root
|
||||
|
||||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
"""
|
||||
解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。
|
||||
核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。
|
||||
@param path_value: 数据库中的路径字符串
|
||||
@returns 合法绝对 Path,越界或空则 None
|
||||
"""
|
||||
if not path_value:
|
||||
return None
|
||||
raw_path = Path(str(path_value))
|
||||
@@ -155,6 +164,45 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def _existing_storage_path(path_value: str | None) -> Path | None:
|
||||
"""
|
||||
解析存储路径且要求文件真实存在。
|
||||
核心逻辑:先 _resolve_storage_path,再校验 is_file。
|
||||
@returns 存在的 Path,否则 None
|
||||
"""
|
||||
path = _resolve_storage_path(path_value)
|
||||
if path is None or not path.exists() or not path.is_file():
|
||||
return None
|
||||
return path
|
||||
|
||||
|
||||
def _markdown_storage_path(version: KbDocumentVersion) -> Path | None:
|
||||
"""
|
||||
取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。
|
||||
核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。
|
||||
"""
|
||||
for path_value in (version.cleaned_file_path, version.cleaned_preview_path):
|
||||
path = _existing_storage_path(path_value)
|
||||
if path is None:
|
||||
continue
|
||||
try:
|
||||
head = path.read_bytes()[:4096]
|
||||
except OSError:
|
||||
continue
|
||||
if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
|
||||
current_app.logger.warning(
|
||||
'[integration] skip binary cleaned path version_id=%s path=%s',
|
||||
version.id,
|
||||
path,
|
||||
)
|
||||
continue
|
||||
if b'\x00' in head:
|
||||
continue
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
@@ -165,13 +213,40 @@ def _document_query():
|
||||
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||
|
||||
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||
"""
|
||||
序列化集成侧文档元数据与可下载 URL。
|
||||
核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md),
|
||||
避免聊天预览拿到“库有映射、盘无文件”的死链。
|
||||
"""
|
||||
version = version or _current_version(document)
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
source_path = _existing_storage_path(version.source_file_path)
|
||||
markdown_path = _markdown_storage_path(version)
|
||||
markdown_download_url = (
|
||||
_build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None
|
||||
)
|
||||
if source_path is not None:
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
elif markdown_path is not None:
|
||||
# [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览
|
||||
source_download_url = markdown_download_url
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
current_app.logger.info(
|
||||
'[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
else:
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
|
||||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
@@ -196,13 +271,31 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
|
||||
return payload
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
"""
|
||||
解析下载目标路径与文件名。
|
||||
核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。
|
||||
@param version: 文档版本
|
||||
@param kind: source | md
|
||||
@returns (绝对路径, 下载文件名)
|
||||
@raises NotFoundError: 源文件与清洗稿均不存在
|
||||
"""
|
||||
if kind == 'source':
|
||||
path = _resolve_storage_path(version.source_file_path)
|
||||
if path is None:
|
||||
raise NotFoundError('File not found on disk.')
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||
path = _existing_storage_path(version.source_file_path)
|
||||
if path is not None:
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _markdown_storage_path(version)
|
||||
if preferred is not None:
|
||||
current_app.logger.warning(
|
||||
'[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s',
|
||||
version.document_id,
|
||||
version.id,
|
||||
preferred,
|
||||
)
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return (preferred, filename)
|
||||
raise NotFoundError('File not found on disk.')
|
||||
preferred = _markdown_storage_path(version)
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
@@ -248,6 +341,10 @@ def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_dify():
|
||||
"""
|
||||
按 Dify dataset/document 反查本地知识库文件元数据。
|
||||
核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。
|
||||
"""
|
||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||
if not remote_document_id:
|
||||
@@ -258,8 +355,10 @@ def get_file_detail_by_dify():
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
if not document:
|
||||
if not document or not version:
|
||||
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||
if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None:
|
||||
raise NotFoundError('No readable local file for the given Dify document.')
|
||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
|
||||
@@ -134,6 +134,38 @@ class DifyService:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
|
||||
"""将 Dify HTTP 错误转换为可执行的用户提示。
|
||||
|
||||
AI 触发时机:Dify 在建立 SSE 流前直接返回非 2xx 响应时调用。
|
||||
核心逻辑:优先识别知识检索常用的 rerank 插件授权失败,避免把上游 403 误报为网络超时;
|
||||
其余状态码则给出不泄露密钥和内部地址的通用排查方向。
|
||||
|
||||
Args:
|
||||
status_code: Dify HTTP 响应状态码。
|
||||
raw_body: 已截断的 Dify 错误正文,仅用于分类,不向用户原样透传。
|
||||
agent_name: 当前智能体名称。
|
||||
|
||||
Returns:
|
||||
面向最终用户的安全错误提示。
|
||||
"""
|
||||
text = str(raw_body or "")
|
||||
lower = text.lower()
|
||||
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
||||
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
|
||||
return (
|
||||
f"{resolved_agent_name}的知识检索重排服务授权失败。"
|
||||
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
|
||||
)
|
||||
if status_code in (401, 403):
|
||||
return f"{resolved_agent_name}暂时无法访问 Dify 服务,请联系管理员检查该应用的 API Key 与服务授权。"
|
||||
if status_code == 404:
|
||||
return f"{resolved_agent_name}的 Dify 应用地址或应用类型配置错误,请联系管理员检查 API Base URL。"
|
||||
if status_code in (429, 502, 503, 504):
|
||||
return f"{resolved_agent_name}的 Dify 服务暂时不可用或繁忙,请稍后重试。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试;如持续失败请联系管理员检查 Dify 工作流。"
|
||||
|
||||
@staticmethod
|
||||
def _merge_stream_answer_text(
|
||||
streamed_text: str,
|
||||
@@ -1028,6 +1060,23 @@ class DifyService:
|
||||
if retryable and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
if not response.ok:
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
response.status_code,
|
||||
response.text[:2000],
|
||||
getattr(agent, 'name', None),
|
||||
)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': f"[Error: {message}]",
|
||||
'metadata': {},
|
||||
},
|
||||
'error',
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
response.raise_for_status()
|
||||
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ class HRLeaveSQLServerService:
|
||||
_PERSON_NAME_PATTERNS = (
|
||||
r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)",
|
||||
r"(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)",
|
||||
r"(?P<name>[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
|
||||
r"(?P<name>[\u4e00-\u9fa5]{2,4}?).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
|
||||
)
|
||||
_PERSON_NAME_STOPWORDS = {
|
||||
"我的",
|
||||
@@ -92,6 +92,10 @@ class HRLeaveSQLServerService:
|
||||
"部门",
|
||||
}
|
||||
_OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期"
|
||||
_SALARY_CONSULTATION_PATTERN = re.compile(
|
||||
r"(?:请假|休假|年假|事假|病假).{0,12}(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)"
|
||||
r"|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(?:请假|休假|年假|事假|病假)"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def supports(cls, query: str) -> bool:
|
||||
@@ -104,6 +108,10 @@ class HRLeaveSQLServerService:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
# [STEP 1] 薪资/扣款是制度计算问答,必须交给 FAQ/Dify,不能进入个人假期余额 SQL。
|
||||
# [PROMPT_UPDATE] 公式、适用条件和计薪口径由知识库原文负责,后端只做路由保护。
|
||||
if cls._SALARY_CONSULTATION_PATTERN.search(text):
|
||||
return False
|
||||
if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in cls._PROCESS_KEYWORDS):
|
||||
@@ -129,10 +137,10 @@ class HRLeaveSQLServerService:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
|
||||
return False
|
||||
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
|
||||
return True
|
||||
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
|
||||
return False
|
||||
return bool(cls._extract_candidate_person_names(text))
|
||||
|
||||
@classmethod
|
||||
@@ -170,10 +178,10 @@ class HRLeaveSQLServerService:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
|
||||
return False
|
||||
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
|
||||
return True
|
||||
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
|
||||
return False
|
||||
self_identifiers = {
|
||||
str(getattr(user, "real_name", None) or "").strip(),
|
||||
str(getattr(user, "username", None) or "").strip(),
|
||||
@@ -181,7 +189,8 @@ class HRLeaveSQLServerService:
|
||||
}
|
||||
self_identifiers = {value for value in self_identifiers if value}
|
||||
for candidate in cls._extract_candidate_person_names(text):
|
||||
if candidate not in self_identifiers:
|
||||
normalized_candidate = candidate.rstrip("的")
|
||||
if normalized_candidate not in self_identifiers:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"""
|
||||
Integration API client for resolving original source-file download links.
|
||||
backend/app/services/integration_api.py
|
||||
|
||||
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
|
||||
依赖:Flask request/current_app、requests、Kb* 模型。
|
||||
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
@@ -223,8 +227,14 @@ class IntegrationApiService:
|
||||
|
||||
@staticmethod
|
||||
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
从本地 KbDifySyncRecord 反查可预览下载链接。
|
||||
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
|
||||
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
|
||||
"""
|
||||
if not has_app_context():
|
||||
return None
|
||||
from pathlib import Path
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||
|
||||
@@ -251,6 +261,30 @@ class IntegrationApiService:
|
||||
version = record.document_version
|
||||
document = version.document
|
||||
|
||||
def _existing(path_value: str | None):
|
||||
if not path_value:
|
||||
return None
|
||||
raw = Path(str(path_value))
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if candidate.exists() and candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
source_path = _existing(version.source_file_path)
|
||||
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
|
||||
if source_path is None and markdown_path is None:
|
||||
current_app.logger.info(
|
||||
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
return None
|
||||
|
||||
base_url = IntegrationApiService._request_origin_url()
|
||||
if not base_url:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
@@ -276,15 +310,25 @@ class IntegrationApiService:
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
|
||||
if source_path is not None:
|
||||
kind = 'source'
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
else:
|
||||
kind = 'md'
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
|
||||
source_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download'
|
||||
f'?kind=source&version_id={version.id}&token={token}'
|
||||
f'?kind={kind}&version_id={version.id}&token={token}'
|
||||
)
|
||||
|
||||
return {
|
||||
"source_download_url": source_download_url,
|
||||
"source_filename": version.source_file_name,
|
||||
"source_ext": version.source_file_ext,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": None,
|
||||
"version_id": version.id,
|
||||
"document_id": document.id,
|
||||
|
||||
@@ -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'
|
||||
|
||||
Reference in new issue
Block a user