fix(platform): 汇总知识库问答与图表展示修复
This commit is contained in:
1 parent
f615e56bb9
commit
55c6467d83
41 files changed
+4569
-770
No files matched your search
+2
-1
@@ -29,10 +29,11 @@ EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
EDKB_PDF_FILE_TIMEOUT_SEC=900
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=1200
|
||||
|
||||
# 采购合同全面审核:三环境一致的异步任务与输入保护参数
|
||||
# 清洗产物目录由各环境相对 backend/ 根目录解析;容器部署可由 Compose 覆盖为 /app/data/procurement_contract
|
||||
|
||||
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'
|
||||
|
||||
@@ -243,6 +243,7 @@ def _normalize_path_for_match(p: Path | str) -> str:
|
||||
|
||||
|
||||
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
|
||||
_PDF_TIMEOUT_EXTS = {".pdf"}
|
||||
# Excel/CSV are fast and in-process; skip spawn timeout wrapper (macOS/gevent safe).
|
||||
_FAST_PATH_EXTS = {".xlsx", ".xls", ".csv", ".txt", ".md"}
|
||||
|
||||
@@ -257,6 +258,19 @@ def _parse_timeout_env(name: str, default: str = "0") -> int | None:
|
||||
|
||||
|
||||
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
|
||||
"""
|
||||
按源文件类型选择清洗子进程的最长运行时间。
|
||||
|
||||
图文 PDF 的 OCR、版面恢复和分段通常显著慢于 Office 文档;若直接复用全局
|
||||
时限,大型手册会在内容尚未产出时被误杀。PDF 可用独立环境变量延长时限,
|
||||
其他格式仍使用全局上限,避免异常任务无限占用 worker。
|
||||
|
||||
Args:
|
||||
file_path: 待清洗源文件路径;仅使用其扩展名进行策略选择。
|
||||
|
||||
Returns:
|
||||
正整数秒数表示启用子进程时限;None 表示该格式不使用 spawn 时限包装。
|
||||
"""
|
||||
suffix = str(getattr(file_path, "suffix", "") or "").lower()
|
||||
if suffix in _FAST_PATH_EXTS:
|
||||
return None
|
||||
@@ -264,6 +278,10 @@ def _file_timeout_sec(file_path: Path | None = None) -> int | None:
|
||||
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
|
||||
if specific:
|
||||
return specific
|
||||
if suffix in _PDF_TIMEOUT_EXTS:
|
||||
specific = _parse_timeout_env("EDKB_PDF_FILE_TIMEOUT_SEC")
|
||||
if specific:
|
||||
return specific
|
||||
return _parse_timeout_env("EDKB_FILE_TIMEOUT_SEC")
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
|
||||
"""Tests for Dify sync process_rule selection (all document types preserve complete semantic blocks)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
@@ -10,14 +10,14 @@ def _make_service(monkeypatch, **overrides):
|
||||
'DIFY_API_KEY': 'dataset-test-key',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'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',
|
||||
}
|
||||
settings.update(overrides)
|
||||
@@ -31,15 +31,18 @@ def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
||||
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 50
|
||||
# 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 600
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 100
|
||||
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
||||
|
||||
|
||||
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
|
||||
def test_build_process_rule_docx_uses_custom_semantic_blocks(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
rule = service._build_process_rule('docx')
|
||||
assert rule == {'mode': 'automatic'}
|
||||
# 断言制度类文档的标题、规则、例外条件保留在同一个检索片段中。
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
|
||||
|
||||
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
@@ -65,7 +68,7 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
process_rule = captured['json']['process_rule']
|
||||
assert process_rule['mode'] == 'custom'
|
||||
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 600
|
||||
|
||||
|
||||
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
@@ -78,6 +81,59 @@ def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
assert remove_urls['enabled'] is True
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_rejects_dify_error(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
|
||||
try:
|
||||
service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={
|
||||
'document': {
|
||||
'id': 'document-001',
|
||||
'indexing_status': 'error',
|
||||
'error': 'embedding credential invalid',
|
||||
},
|
||||
},
|
||||
)
|
||||
except dify_sync_module.KbDifySyncError as exc:
|
||||
# 断言 Dify 的原始原因被保留,供工作台展示而不是误报同步成功。
|
||||
assert 'embedding credential invalid' in str(exc)
|
||||
else:
|
||||
raise AssertionError('Dify indexing error must fail the local sync')
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_accepts_completed_status(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
result = service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={'document': {'id': 'document-001', 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
# completed 是唯一可将本地同步记录写为 synced 的终态。
|
||||
assert result['indexing_status'] == 'completed'
|
||||
|
||||
|
||||
def test_remote_document_not_available_is_recreated(monkeypatch):
|
||||
"""400 invalid_param 的不可用文档错误必须触发创建新远端文档的恢复流程。"""
|
||||
error = (
|
||||
'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text '
|
||||
'failed: 400 {"code":"invalid_param","message":"Document is not available","status":400}'
|
||||
)
|
||||
|
||||
# 断言该 Dify 版本特有的 400 响应不会被当成不可恢复的同步失败。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is True
|
||||
|
||||
|
||||
def test_remote_document_other_invalid_parameter_is_not_treated_as_missing():
|
||||
"""非文档失效的参数错误仍应原样失败,避免错误地重复创建文档。"""
|
||||
error = 'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text failed: 400 {"code":"invalid_param","message":"Invalid process rule","status":400}'
|
||||
|
||||
# 断言只有精确的“文档不可用”语义才走自动恢复分支。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is False
|
||||
|
||||
|
||||
def test_resolve_source_file_ext_from_filename():
|
||||
class _Version:
|
||||
source_file_ext = None
|
||||
|
||||
@@ -78,6 +78,16 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||
|
||||
|
||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
400,
|
||||
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||
agent_name='通用入口',
|
||||
)
|
||||
assert message == '通用入口的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。'
|
||||
|
||||
|
||||
def test_persist_stream_chat_record_uses_workflow_finished_tokens(app):
|
||||
"""workflow_finished 首次落库应写入 data.total_tokens。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -18,6 +18,14 @@ def test_word_still_uses_word_timeout(monkeypatch):
|
||||
assert _file_timeout_sec(Path('manual.docx')) == 420
|
||||
|
||||
|
||||
def test_pdf_uses_dedicated_timeout_for_figure_rich_handbooks(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '300')
|
||||
monkeypatch.setenv('EDKB_PDF_FILE_TIMEOUT_SEC', '900')
|
||||
|
||||
# 断言大型图文手册不会被通用 300 秒时限提前终止。
|
||||
assert _file_timeout_sec(Path('mechanical-design-handbook.pdf')) == 900
|
||||
|
||||
|
||||
def test_other_formats_use_global_timeout(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
assert _file_timeout_sec(Path('slides.pptx')) == 180
|
||||
@@ -1527,7 +1527,7 @@ def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeyp
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
|
||||
@@ -16,6 +16,13 @@ def test_supports_rejects_leave_process_questions():
|
||||
assert not HRLeaveSQLServerService.supports("年假制度是什么")
|
||||
|
||||
|
||||
def test_supports_rejects_salary_calculation_questions():
|
||||
# 断言:制度扣薪问题必须走 FAQ/Dify,不能触发 HR 假期余额查询。
|
||||
assert not HRLeaveSQLServerService.supports("请病假怎么扣钱")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣多少薪资")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣款计算公式")
|
||||
|
||||
|
||||
def test_supports_other_person_leave_queries_for_guardrail():
|
||||
assert HRLeaveSQLServerService.supports("张三还有多少假期")
|
||||
assert HRLeaveSQLServerService.supports("曹惠鹏还有多少假期")
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
backend/tests/test_integration_source_fallback.py
|
||||
|
||||
用途:验证源文件缺失时 integration 下载与序列化回退到清洗 Markdown。
|
||||
依赖:pytest、kb 模型与 integration 路由。
|
||||
逻辑:模拟磁盘无 source、有 cleaned md,断言 kind=source 仍可读且序列化返回 .md。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, User
|
||||
|
||||
|
||||
def _configure(app, tmp_path: Path) -> Path:
|
||||
root = tmp_path / 'kb-storage'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
app.config.update(
|
||||
SECRET_KEY='test-secret-key-with-sufficient-length-123456',
|
||||
KB_STORAGE_ROOT=str(root),
|
||||
WECOM_PUBLIC_BASE_URL='https://ai.example.com',
|
||||
INTEGRATION_API_KEY='test-integration-key',
|
||||
INTEGRATION_API_MODE='local',
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def _ensure_admin() -> User:
|
||||
user = db.session.query(User).filter_by(username='admin').first()
|
||||
if user:
|
||||
return user
|
||||
user = User(username='admin', email='admin@example.com', role='admin', status='active')
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _seed_doc_with_missing_source(root: Path) -> tuple[KbDocument, KbDocumentVersion]:
|
||||
"""创建文档:source_file_path 指向不存在文件,cleaned md 真实存在。"""
|
||||
_ensure_admin()
|
||||
group = KbGroup(name='fallback-group', description='t', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.flush()
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group.id,
|
||||
title='员工入职须知',
|
||||
status='ready',
|
||||
source_type='upload',
|
||||
is_deleted=False,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
|
||||
missing_source = root / 'docs' / 'missing-source.pdf'
|
||||
cleaned = root / 'docs' / 'cleaned.md'
|
||||
cleaned.parent.mkdir(parents=True, exist_ok=True)
|
||||
cleaned.write_text('# 入职须知\n\n欢迎加入。', encoding='utf-8')
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=1,
|
||||
status='ready',
|
||||
is_current=True,
|
||||
source_file_name='员工入职须知.pdf',
|
||||
source_file_path=str(missing_source),
|
||||
source_file_ext='pdf',
|
||||
source_file_size=12,
|
||||
sha256='abc',
|
||||
cleaned_file_path=str(cleaned),
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
sync = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id='ds-fallback',
|
||||
remote_document_id='remote-fallback',
|
||||
status='synced',
|
||||
)
|
||||
db.session.add(sync)
|
||||
db.session.commit()
|
||||
return document, version
|
||||
|
||||
|
||||
def test_download_source_falls_back_to_markdown(app, client, tmp_path):
|
||||
"""断言:kind=source 时源文件不存在,仍返回清洗 Markdown 内容。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
document, version = _seed_doc_with_missing_source(root)
|
||||
document_id = document.id
|
||||
version_id = version.id
|
||||
|
||||
response = client.get(
|
||||
f'/api/integration/files/{document_id}/download',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={'kind': 'source', 'version_id': version_id},
|
||||
)
|
||||
assert response.status_code == 200, response.get_data(as_text=True)
|
||||
body = response.get_data(as_text=True)
|
||||
assert '入职须知' in body
|
||||
assert '欢迎加入' in body
|
||||
|
||||
|
||||
def test_serialize_prefers_markdown_when_source_missing(app, client, tmp_path):
|
||||
"""断言:dify-file 在源文件缺失时返回 kind=md 与 .md 扩展名。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
_seed_doc_with_missing_source(root)
|
||||
|
||||
response = client.get(
|
||||
'/api/integration/dify-file',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={
|
||||
'dataset_id': 'ds-fallback',
|
||||
'remote_document_id': 'remote-fallback',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
payload = response.get_json()
|
||||
assert payload['source_ext'] == 'md'
|
||||
assert str(payload['source_filename']).endswith('.md')
|
||||
assert 'kind=md' in str(payload['source_download_url'])
|
||||
@@ -115,7 +115,7 @@ def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_test_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -159,7 +159,7 @@ def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_integration_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -232,7 +232,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_old_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -252,7 +252,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_new_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
|
||||
+9
-2
@@ -44,16 +44,19 @@ services:
|
||||
- KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker}
|
||||
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
|
||||
# kb-worker 自动回收长时间 running 的任务(秒)
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-1200}
|
||||
# 采购合同异步审核:清洗产物与任务/模型输入保护
|
||||
- PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract}
|
||||
- PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160}
|
||||
|
||||
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
|
||||
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
|
||||
# LibreOffice 单次格式转换超时(秒)
|
||||
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
|
||||
# 图文 PDF 可能包含 OCR/版面恢复;独立时限避免被通用清洗上限提前终止
|
||||
- EDKB_PDF_FILE_TIMEOUT_SEC=${EDKB_PDF_FILE_TIMEOUT_SEC:-900}
|
||||
# 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC
|
||||
- FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}
|
||||
- FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-}
|
||||
@@ -116,16 +119,20 @@ services:
|
||||
- KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker}
|
||||
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
|
||||
# kb-worker 自动回收长时间 running 的任务(秒)
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-1200}
|
||||
|
||||
# 采购合同异步审核:Worker 与后端必须指向同一持久化目录
|
||||
- PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract}
|
||||
- PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160}
|
||||
|
||||
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
|
||||
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
|
||||
# LibreOffice 单次格式转换超时(秒)
|
||||
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
|
||||
# 与 API 容器保持一致,确保 worker 实际读取到 PDF 专用清洗时限
|
||||
- EDKB_PDF_FILE_TIMEOUT_SEC=${EDKB_PDF_FILE_TIMEOUT_SEC:-900}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
|
||||
@@ -132,6 +132,7 @@
|
||||
|
||||
- 员工在 `企业知识库` 或 `ERP知识库` 中,针对“我还有多少假期”“我的年假还有多少”等强意图问题,可以直接获取本人假期数据。
|
||||
- 流程/制度类问题仍继续走知识库问答,不进入数据库强查询。
|
||||
- 薪资扣除、福利计算等制度计算问题(如“请假扣多少薪资”“请假如何扣薪”)不得触发请假申请表单,应优先检索知识库并返回权威计算公式及适用条件。
|
||||
|
||||
### 5.2 申请类目标
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 知识库同步状态校验
|
||||
|
||||
- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。
|
||||
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
|
||||
|
||||
## 设备维保助手
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -221,6 +226,8 @@
|
||||
- 我要请明天下午假
|
||||
- 帮我提一个请假单
|
||||
|
||||
制度计算类问法(例如“请假扣多少薪资”“请假扣薪计算公式”)不属于申请意图,必须继续进入 FAQ/Dify 知识库问答,返回制度原文中的计算公式。
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 识别“申请类意图”
|
||||
@@ -441,6 +448,7 @@
|
||||
- 如何请假
|
||||
- 请假制度有哪些
|
||||
- 年假规则是什么
|
||||
- 请假扣多少薪资 / 请假扣薪计算公式
|
||||
|
||||
## 4. 数据源清单
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# 知识库 Excel/CSV 切块与 Dify 同步
|
||||
|
||||
> 说明 Excel/CSV 清洗成 Markdown 后如何与 Dify custom 分段配合,以及版本目录下调试产物路径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题背景
|
||||
|
||||
知识库 Excel(如 RoHS/供应商排程宽表)经 edkb 清洗成 Markdown 后,同步 Dify 时若使用默认 `process_rule.mode=automatic`,宽表 pipe 行或长段落会被 Dify 按 token/标点切散,导致**同一数据行字段落入不同 segment**,Hit testing 检索时上下文不完整。
|
||||
|
||||
典型症状:
|
||||
|
||||
- 问「某供应商编码 + 物料」命中片段只有半行字段;
|
||||
- Dify 文档分段数远大于 Excel 数据行数,或一行被拆成多段。
|
||||
|
||||
---
|
||||
|
||||
## 2. 改造后数据流
|
||||
|
||||
```text
|
||||
上传 xlsx/csv
|
||||
→ edkb loader_excel / loader_csv
|
||||
→ table_linearize(宽表行文本化 / 窄表 pipe 行 \n\n 分隔)
|
||||
→ document.md(写入 KB 版本目录)
|
||||
→ [可选] 04_chunks.jsonl / chunks/(调试,不传 Dify)
|
||||
→ sync_dify:create-by-text / update-by-text
|
||||
→ Dify process_rule.mode=custom(Excel/CSV 专用,separator=\n\n)
|
||||
```
|
||||
|
||||
### table_linearize 输出规则(摘要)
|
||||
|
||||
| 表类型 | 条件 | 输出格式 |
|
||||
| --- | --- | --- |
|
||||
| 条件/处理/责任表 | 表头含「条件」「处理」等关键词 | 每条 bullet 之间 `\n\n` |
|
||||
| 窄表 | 列数 ≤ 8 | 表头块 + 每个数据行单独 `\| ... \|` 块,行间 `\n\n` |
|
||||
| 宽表 | 列数 > 8 | `- 【行】列1=值1;列2=值2;...`,行间 `\n\n` |
|
||||
|
||||
示例(宽表,与 RoHS 排程类文件一致):
|
||||
|
||||
```markdown
|
||||
## Sheet: result
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;...
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 配置项(KB_DIFY_*)
|
||||
|
||||
可通过 **环境变量** 或管理台 **AppSetting** 覆盖;读取入口:`get_kb_dify_settings()`。
|
||||
|
||||
| 键 | 默认值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `KB_DIFY_PROCESS_MODE` | `custom` | 非 Excel/CSV 文档的 Dify 分段模式;按空行保留标题、规则和例外条件组成的完整知识单元 |
|
||||
| `KB_DIFY_PROCESS_MODE_EXCEL` | `custom` | xlsx / xls / csv 专用分段模式 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR` | `\n\n`(env 写 `\\n\\n`) | custom 模式通用分隔符 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR_EXCEL` | `\n\n` | Excel/CSV custom 分隔符,与 table_linearize 对齐 |
|
||||
| `KB_DIFY_SEGMENT_MAX_TOKENS` | `600` | custom 模式 max_tokens |
|
||||
| `KB_DIFY_SEGMENT_CHUNK_OVERLAP` | `100` | custom 模式 chunk_overlap,保留相邻段落的必要上下文 |
|
||||
| `KB_DIFY_REMOVE_URLS` | `false` | 映射 Dify `remove_urls_emails`;RoHS 等表含 PDF 链接,默认关闭 |
|
||||
|
||||
`.env` 示例:
|
||||
|
||||
```bash
|
||||
KB_DIFY_PROCESS_MODE=automatic
|
||||
KB_DIFY_PROCESS_MODE_EXCEL=custom
|
||||
KB_DIFY_SEGMENT_SEPARATOR_EXCEL=\n\n
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS=800
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP=50
|
||||
KB_DIFY_REMOVE_URLS=false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 版本目录与调试文件
|
||||
|
||||
清洗完成后,单版本目录结构(相对 `backend/data/kb/` 或部署挂载路径):
|
||||
|
||||
```text
|
||||
group_XXXX/document_XXXXXX/vXXX/
|
||||
su_schedule_5.xlsx # 原始上传
|
||||
document.md # 清洗结果(sync_dify 读取此文件)
|
||||
document_preview.md # 可选,含图片预览时
|
||||
04_chunks.jsonl # 可选,edkb 切块调试(不传 Dify)
|
||||
chunks/
|
||||
chunk_0000.md
|
||||
chunk_0001.md
|
||||
...
|
||||
```
|
||||
|
||||
- `document.md`:权威同步文本;
|
||||
- `04_chunks.jsonl`:edkb export 阶段产物,一行一个 chunk JSON,便于与 Dify segment 列表对照;
|
||||
- 若清洗失败回退占位,会出现 `*.preview.txt`(含 `clean_status=placeholder_success`),**不应**作为 Dify 同步源。
|
||||
|
||||
---
|
||||
|
||||
## 5. 手动验收(curl)
|
||||
|
||||
对已有 dataset 创建文本文档,模拟 Excel custom 分段(需替换 `DATASET_ID`、`API_KEY`):
|
||||
|
||||
```bash
|
||||
curl -X POST "http://<DIFY_HOST>/v1/datasets/<DATASET_ID>/document/create-by-text" \
|
||||
-H "Authorization: Bearer <API_KEY>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "excel-chunk-test.md",
|
||||
"text": "## Sheet: result\n\n- 【行】列1=a;列2=b。\n\n- 【行】列1=c;列2=d。",
|
||||
"indexing_technique": "high_quality",
|
||||
"doc_form": "text_model",
|
||||
"process_rule": {
|
||||
"mode": "custom",
|
||||
"rules": {
|
||||
"pre_processing_rules": [
|
||||
{"id": "remove_extra_spaces", "enabled": true},
|
||||
{"id": "remove_urls_emails", "enabled": false}
|
||||
],
|
||||
"segmentation": {
|
||||
"separator": "\n\n",
|
||||
"max_tokens": 800,
|
||||
"chunk_overlap": 50
|
||||
}
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 对比 Dify 分段与本地 jsonl
|
||||
|
||||
1. 打开 Dify 知识库 → 该文档 → **分段列表**,记录 segment 数量与首段内容;
|
||||
2. 打开版本目录 `04_chunks.jsonl`,统计非空行数:`wc -l 04_chunks.jsonl`;
|
||||
3. 宽表场景:segment 数应接近 **数据行数**(每行一条 `【行】` bullet,经 `\n\n` 切开);
|
||||
4. 在 Dify **Hit testing** 用表中存在的「供应商编码 + 物料名称」提问,应命中包含完整行字段的片段。
|
||||
|
||||
---
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
| 层级 | 做法 |
|
||||
| --- | --- |
|
||||
| Dify 分段 | 设 `KB_DIFY_PROCESS_MODE_EXCEL=automatic`,并对已有 Excel 文档 **重新 sync_dify** |
|
||||
| 清洗格式 | git revert `table_linearize` 相关提交(document.md 格式恢复旧行为) |
|
||||
| 调试文件 | 忽略 `04_chunks.jsonl`,不影响线上同步 |
|
||||
|
||||
> **发版说明**:环境变量变更后,**已有 Excel 文档需触发重新 sync_dify** 才会应用新的 `process_rule`;仅重新清洗不会更新 Dify 远端分段规则。
|
||||
|
||||
---
|
||||
|
||||
## 8. 本地开发注意
|
||||
|
||||
- API 与 KB worker 须使用同一虚拟环境:
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python run.py # 终端 1
|
||||
python worker_kb.py # 终端 2
|
||||
```
|
||||
|
||||
- `.env.shared` 中 `EDKB_FILE_TIMEOUT_SEC` 对 Word 等慢格式启用 spawn 超时;**Excel/CSV 已在代码中豁免**,避免 macOS 本地 `Operation not permitted`。
|
||||
- 相关代码:`edkb_system/skills/table_linearize.py`、`app/services/knowledge_cleaning/dify_sync_service.py`、`edkb_adapter.py`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关测试
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python -m pytest tests/test_dify_sync_process_rule.py \
|
||||
tests/test_table_linearize.py \
|
||||
tests/test_kb_excel_cleaning.py \
|
||||
tests/test_edkb_adapter_chunks.py \
|
||||
tests/test_edkb_file_timeout.py -q
|
||||
```
|
||||
@@ -0,0 +1,175 @@
|
||||
# 主平台知识库运行时部署说明
|
||||
|
||||
## 目标
|
||||
|
||||
将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。
|
||||
|
||||
当前主平台 `docker-compose.yml` 已接入:
|
||||
|
||||
- `kb-redis`
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- 共享卷 `hxops_runtime_data`
|
||||
|
||||
## 容器职责
|
||||
|
||||
### `hxops-backend`
|
||||
|
||||
- 提供主平台 API
|
||||
- 提供知识库 API:`/api/kb/*`
|
||||
- 提供集成 API:`/api/integration/*`
|
||||
- 挂载知识库存储根目录到 `/app/data`
|
||||
|
||||
### `hxops-kb-worker`
|
||||
|
||||
- 轮询执行知识库 `clean` 任务
|
||||
- 复用后端镜像,避免维护第二套依赖
|
||||
- 与后端共享数据库、Redis、知识库存储卷
|
||||
|
||||
### `kb-redis`
|
||||
|
||||
- 提供知识库异步任务所需 Redis
|
||||
- 当前主要用于主平台知识库运行时接入与后续队列化扩展
|
||||
|
||||
## 关键环境变量
|
||||
|
||||
部署主平台知识库运行时时,至少确认以下变量:
|
||||
|
||||
| 变量名 | 用途 | 建议值/说明 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 |
|
||||
| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 |
|
||||
| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` |
|
||||
| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` |
|
||||
| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` |
|
||||
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 |
|
||||
| `KB_JOB_RUNNING_TIMEOUT_SECONDS` | running 任务超时回收 | 图文 PDF 建议 `1200`,必须大于 `EDKB_PDF_FILE_TIMEOUT_SEC` |
|
||||
| `EDKB_SOFFICE_TIMEOUT_SEC` | LibreOffice 转换超时 | 默认 `120` |
|
||||
| `EDKB_PDF_FILE_TIMEOUT_SEC` | 图文 PDF 清洗总超时 | 建议 `900`;应小于 `KB_JOB_RUNNING_TIMEOUT_SECONDS`,避免 PDF OCR/版面恢复被通用时限提前中止 |
|
||||
| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` |
|
||||
| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 |
|
||||
| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 |
|
||||
| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 |
|
||||
| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 |
|
||||
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 |
|
||||
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` |
|
||||
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` |
|
||||
| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 |
|
||||
| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 |
|
||||
|
||||
补充说明:
|
||||
|
||||
- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。
|
||||
- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。
|
||||
- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。
|
||||
- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。
|
||||
- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。
|
||||
- OCR 依赖(OpenCV/RapidOCR)在 `backend/requirements-ocr.txt`,由 `backend/Dockerfile` 分步安装,避免同时下载 `opencv-python` 与 `opencv-python-headless` 两个大 wheel。
|
||||
- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。
|
||||
- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。
|
||||
- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。
|
||||
|
||||
## 启动步骤
|
||||
|
||||
### 1. 构建并启动
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若使用私有镜像仓库,可先设置:
|
||||
|
||||
```bash
|
||||
$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine"
|
||||
$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim"
|
||||
$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine"
|
||||
$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine"
|
||||
$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若需要同时启用内置 Redis,再改为:
|
||||
|
||||
```bash
|
||||
docker compose --profile kb-redis up -d --build
|
||||
```
|
||||
|
||||
### 2. 执行数据库迁移
|
||||
|
||||
```bash
|
||||
docker compose exec hxops-backend flask db upgrade
|
||||
```
|
||||
|
||||
### 3. 检查服务状态
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
预期:
|
||||
|
||||
- `hxops-backend` 为 `Up`
|
||||
- `hxops-kb-worker` 为 `Up`(与 backend 共用镜像;Jenkins/`deploy_compose.sh` 在后端变更时会一并重建)
|
||||
- `hxops-frontend` 为 `Up`
|
||||
|
||||
若启用了 `kb-redis` profile,则额外确认:
|
||||
|
||||
- `kb-redis` 为 `Up`
|
||||
|
||||
### 4. 检查 worker 日志
|
||||
|
||||
```bash
|
||||
docker compose logs -f hxops-kb-worker
|
||||
```
|
||||
|
||||
预期可见:
|
||||
|
||||
```text
|
||||
[kb-worker] started, poll_seconds=2.0
|
||||
```
|
||||
|
||||
## 端口与卷
|
||||
|
||||
当前主平台容器端口关系:
|
||||
|
||||
- 宿主机 `5002` -> `hxops-backend:5000`
|
||||
- 宿主机 `8890` -> `hxops-frontend:80`
|
||||
|
||||
当前关键卷:
|
||||
|
||||
- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录
|
||||
- `hxops_redis_data`:Redis 持久化数据
|
||||
|
||||
## 切换前检查
|
||||
|
||||
切换 `xinxin2` 运行时前,至少确认:
|
||||
|
||||
1. 主平台已完成数据库迁移
|
||||
2. 主平台后台可正常打开知识库管理页
|
||||
3. 上传文件后会生成 `upload/clean` 任务
|
||||
4. `hxops-kb-worker` 能持续消费待执行任务
|
||||
5. Dify 设置已在主平台管理端保存并通过健康检查
|
||||
6. 聊天侧 `INTEGRATION_API_MODE=local`
|
||||
7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名
|
||||
|
||||
## 切换后冒烟清单
|
||||
|
||||
建议按顺序验证:
|
||||
|
||||
1. 登录主平台并进入知识库工作台
|
||||
2. 新建一个分组和一个文档条目
|
||||
3. 上传一个 `txt` 或 `md` 文件
|
||||
4. 确认任务状态从 `pending/running` 进入 `success`
|
||||
5. 在文档详情里触发一次 Dify 同步
|
||||
6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射
|
||||
7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台
|
||||
|
||||
## 常见注意事项
|
||||
|
||||
- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。
|
||||
- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。
|
||||
- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。
|
||||
- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。
|
||||
- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。
|
||||
- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。
|
||||
Generated
+775
-662
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
@@ -19,6 +19,7 @@ import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingEx
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import { buildMermaidFlowFallbackHtml } from '../../utils/mermaidChart';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
@@ -126,6 +127,33 @@ const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
|
||||
));
|
||||
const markdownContainer = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* 用途:将回答中的 Mermaid 流程图代码块转换成内嵌流程卡片。
|
||||
* 依赖:useChatPageMarkdown 为 `mermaid` 代码块保留 `.chat-mermaid` 标记。
|
||||
* 逻辑:不直接执行 Mermaid,避免 Dify 非标准图语法使 Mermaid 在页面根节点注入错误 SVG;
|
||||
* 对可提取的主流程展示节点卡片和箭头,其余图表代码块静默隐藏,不影响普通文本与表格。
|
||||
*/
|
||||
const renderMermaidCharts = async () => {
|
||||
await nextTick();
|
||||
const container = markdownContainer.value;
|
||||
if (!container) return;
|
||||
const nodes = Array.from(container.querySelectorAll<HTMLElement>('pre.chat-mermaid:not([data-mermaid-rendered])'));
|
||||
if (!nodes.length) return;
|
||||
for (const node of nodes) {
|
||||
node.dataset.mermaidRendered = 'pending';
|
||||
const fallbackHtml = buildMermaidFlowFallbackHtml(node.textContent || '');
|
||||
if (fallbackHtml) {
|
||||
node.outerHTML = fallbackHtml;
|
||||
continue;
|
||||
}
|
||||
node.remove();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => { void renderMermaidCharts(); });
|
||||
watch(renderedMarkdown, () => { void renderMermaidCharts(); });
|
||||
const inlineDownloadFiles = computed(() => (
|
||||
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
|
||||
));
|
||||
@@ -1055,6 +1083,71 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-diagram) {
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(219 234 254);
|
||||
border-radius: 0.75rem;
|
||||
background: linear-gradient(135deg, rgb(248 250 252), rgb(239 246 255));
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-diagram svg) {
|
||||
display: block;
|
||||
min-width: 36rem;
|
||||
max-width: none;
|
||||
height: auto;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-error) {
|
||||
white-space: pre;
|
||||
overflow: auto;
|
||||
color: rgb(127 29 29);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-error-tip) {
|
||||
margin: 0.75rem 0 0.25rem;
|
||||
color: rgb(185 28 28);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(191 219 254);
|
||||
border-radius: 0.75rem;
|
||||
background: linear-gradient(135deg, rgb(248 250 252), rgb(239 246 255));
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback-card) {
|
||||
flex: 0 0 auto;
|
||||
min-width: 8.5rem;
|
||||
max-width: 13rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid rgb(96 165 250);
|
||||
border-radius: 0.625rem;
|
||||
background: white;
|
||||
color: rgb(30 64 175);
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
text-align: center;
|
||||
box-shadow: 0 2px 8px rgb(59 130 246 / 0.12);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback-arrow) {
|
||||
flex: 0 0 auto;
|
||||
color: rgb(37 99 235);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-table-scroll) {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
|
||||
@@ -41,8 +41,13 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
|
||||
const stopContainerWatch = watch(container, syncScrollListener, { immediate: true });
|
||||
|
||||
/**
|
||||
* 判断是否显示“回到最新消息”按钮。
|
||||
* 核心逻辑:只要用户离开底部就提供入口;流式回复只有两条消息时同样需要可恢复跟随。
|
||||
* @returns 用户是否正在查看历史内容。
|
||||
*/
|
||||
const showScrollToBottom = computed(() =>
|
||||
messages.value.length >= 4 && !isNearBottom.value,
|
||||
messages.value.length > 0 && !isNearBottom.value,
|
||||
);
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
@@ -118,9 +123,15 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
stopContainerWatch();
|
||||
};
|
||||
|
||||
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
||||
/**
|
||||
* 监听流式消息与会话状态,决定是否继续贴底跟随。
|
||||
* 核心逻辑:用户在底部时显示最新生成内容;用户手动向上阅读后停止自动滚动,
|
||||
* 直到其主动点击“回到最新消息”。
|
||||
* @param isThinking - 当前回复是否仍在生成,用于纳入监听依赖。
|
||||
* @param conversationId - 当前会话标识,用于在切换会话后重新评估滚动状态。
|
||||
* @returns 无返回值;监听会在 composable 卸载时自动清理。
|
||||
*/
|
||||
const setupThinkingScrollWatch = (isThinking: Ref<boolean>, conversationId?: Ref<string | null>) => {
|
||||
let wasThinking = false;
|
||||
watch(
|
||||
() => ({
|
||||
messageCount: messages.value.length,
|
||||
@@ -130,14 +141,14 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
conversationId: conversationId?.value || '',
|
||||
}),
|
||||
() => {
|
||||
if (wasThinking && !isThinking.value) {
|
||||
wasThinking = false;
|
||||
void scrollToUserQuestion();
|
||||
} else {
|
||||
if (isThinking.value) wasThinking = true;
|
||||
if (isNearBottom.value) scheduleScrollToBottom();
|
||||
else window.requestAnimationFrame(updateNearBottomState);
|
||||
// [STEP 1] 用户停留在底部时随新内容向下滚动;离开底部后保留阅读位置。
|
||||
if (isNearBottom.value) {
|
||||
scheduleScrollToBottom();
|
||||
return;
|
||||
}
|
||||
|
||||
// [STEP 2] 内容高度变化可能使“接近底部”状态恢复,重新计算但不主动移动视口。
|
||||
window.requestAnimationFrame(updateNearBottomState);
|
||||
},
|
||||
{ deep: false },
|
||||
);
|
||||
|
||||
@@ -12,6 +12,12 @@ describe('isStrongLeaveIntent', () => {
|
||||
// 断言:规则咨询不应触发本地请假表单,应继续走 Dify 问答。
|
||||
expect(isStrongLeaveIntent('年假可以按照小时请假吗?')).toBe(false);
|
||||
expect(isStrongLeaveIntent('怎么请年假?年假可以按照小时请假吗?')).toBe(false);
|
||||
// 断言:扣薪/薪资计算属于知识库制度问答,不应弹出请假申请表单。
|
||||
expect(isStrongLeaveIntent('请假扣多少薪资')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请假如何扣除薪资')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请病假怎么扣钱')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请假扣多少钱,计算公式是什么')).toBe(false);
|
||||
expect(isStrongLeaveIntent('薪资福利中的请假扣款怎么算')).toBe(false);
|
||||
});
|
||||
|
||||
it('保留强请假意图触发表单', () => {
|
||||
|
||||
@@ -140,6 +140,10 @@ export function getLeaveIntentNormalized(content: string): string {
|
||||
/** 区分「真请假」与「咨询流程/材料」类弱意图 */
|
||||
export function isStrongLeaveIntent(content: string): boolean {
|
||||
const normalized = getLeaveIntentNormalized(content);
|
||||
// [STEP 1] 薪资/扣薪属于制度计算问答,必须交给 Dify/FAQ,不能被“请假”关键词抢先拦截为申请表单。
|
||||
// [PROMPT_UPDATE] 保留知识库中的计算公式、适用条件和口径,由知识库回答而非前端自行生成。
|
||||
const leaveSalaryConsultationIntent = /(请假|休假|年假|事假|病假).{0,12}(薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(请假|休假|年假|事假|病假)/;
|
||||
if (leaveSalaryConsultationIntent.test(normalized)) return false;
|
||||
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
|
||||
const weakLeaveQuestionIntent = /((怎么|如何).{0,8}(请假|请年假|休假|休年假|年假)|(请假|年假|休假).{0,12}(可以|可否|能否|是否|支持).{0,8}(按小时|按照小时|小时请|小时休))/;
|
||||
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
|
||||
|
||||
@@ -55,7 +55,23 @@ function displayFixedAssetHeader(header: string): string {
|
||||
const key = FIXED_ASSET_HEADER_I18N_KEYS[header as keyof typeof FIXED_ASSET_HEADER_I18N_KEYS];
|
||||
return key ? tt(key) : header;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:为聊天中的 Mermaid 代码块保留可识别标记,交由消息组件渲染为 SVG 图表。
|
||||
* 逻辑:仅处理明确标为 `mermaid` 的代码块;其余代码仍保持 marked 的默认安全展示,
|
||||
* 避免把普通文本或 ASCII 图误当作可执行图表语法。
|
||||
*/
|
||||
const chatMarkdownRenderer = new marked.Renderer();
|
||||
chatMarkdownRenderer.code = ({ text, lang }: { text: string; lang?: string | null }) => {
|
||||
if (String(lang || '').trim().toLowerCase() === 'mermaid') {
|
||||
return `<pre class="chat-mermaid">${text}</pre>`;
|
||||
}
|
||||
const escaped = String(text || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
const languageClass = String(lang || '').trim().replace(/[^a-zA-Z0-9_-]/g, '');
|
||||
return `<pre><code${languageClass ? ` class="language-${languageClass}"` : ''}>${escaped}</code></pre>`;
|
||||
};
|
||||
const INLINE_FILE_BLOCK_REGEX = /\[FILE_START\]([\s\S]*?)\[FILE_END\]/g;
|
||||
const INLINE_ATTACHMENT_HINT_REGEX = /^.*(?:如果您需要查看全部数据,请下载附件。?|请下载附件。?).*$/gim;
|
||||
|
||||
@@ -462,7 +478,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
|
||||
);
|
||||
try {
|
||||
const rendered = marked.parse(displayText);
|
||||
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
|
||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||
return enhanceAssetHistoryTableLinks(html)
|
||||
.replace(/<(td|th)\b([^>]*)>(?:\s| |<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 用途:验证 Mermaid 兼容规范化,防止中文分组标题再次导致流程图解析失败。
|
||||
* 依赖:vitest、mermaidChart。
|
||||
* 逻辑:覆盖无 ID 中文 subgraph 的标准化以及原本标准语法的不变性。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildMermaidFlowFallbackHtml, normalizeMermaidChart } from './mermaidChart';
|
||||
|
||||
describe('normalizeMermaidChart', () => {
|
||||
it('为中文 subgraph 标题补齐可解析的 ASCII ID', () => {
|
||||
// 断言:Dify 常见的中文分组写法被转为 Mermaid 标准分组声明。
|
||||
expect(normalizeMermaidChart('graph TD\nsubgraph 项目启动阶段\nA[接单]\nend'))
|
||||
.toContain('subgraph group_1["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('保留已有 ID 的标准 subgraph', () => {
|
||||
// 断言:已规范的 Mermaid 不被重复改写。
|
||||
expect(normalizeMermaidChart('subgraph phase_start["项目启动阶段"]'))
|
||||
.toBe('subgraph phase_start["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('将无法解析的主流程降级为可视化卡片', () => {
|
||||
// 断言:即使 Mermaid 语法异常,用户仍能看到节点和顺序,而不是红色源码。
|
||||
const html = buildMermaidFlowFallbackHtml('A[接单] --> B[项目立项]\nB --> C[项目启动阶段]');
|
||||
expect(html).toContain('接单');
|
||||
expect(html).toContain('项目启动阶段');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 用途:规范化智能体输出的 Mermaid 图表文本,兼容中文分组标题等常见非标准写法。
|
||||
* 依赖:由 ChatMessageBubble 在调用 mermaid.render 前使用。
|
||||
* 逻辑:保留合法语句不变;仅为没有 ID 的 subgraph 补充稳定 ASCII ID 与带引号标题,
|
||||
* 避免 Mermaid 把中文标题解析为图语法 token 而导致整张流程图无法显示。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 用途:将常见的中文 Mermaid 分组语法转换为 Mermaid 可稳定解析的标准形式。
|
||||
* AI 触发时机:智能体返回 `subgraph 项目启动阶段` 等没有 ASCII 节点 ID 的分组标题时调用。
|
||||
* 核心逻辑:逐行识别 subgraph;已经包含 ID、方括号或引号的标准写法不变;其余标题生成唯一 ID。
|
||||
* 参数与输出约束:输入必须为 Mermaid 文本;输出只调整 subgraph 声明,不修改节点、连线及 end 语句。
|
||||
*/
|
||||
export function normalizeMermaidChart(source: string): string {
|
||||
let subgraphIndex = 0;
|
||||
return String(source || '')
|
||||
.replace(/^\s*graph\s+/im, (matched) => matched.replace(/graph/i, 'flowchart'))
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
const match = line.match(/^(\s*)subgraph\s+(.+?)\s*$/i);
|
||||
if (!match) return line;
|
||||
const indent = match[1] || '';
|
||||
const rawTitle = (match[2] || '').trim();
|
||||
if (!rawTitle || /[\[\]"']/.test(rawTitle) || /^[A-Za-z_][A-Za-z0-9_-]*\s/.test(rawTitle)) return line;
|
||||
subgraphIndex += 1;
|
||||
return `${indent}subgraph group_${subgraphIndex}["${rawTitle.replace(/"/g, '\\"')}"]`;
|
||||
})
|
||||
.join('\n')
|
||||
// Mermaid 对含括号、标点或中文的节点标签需要显式引号;Dify 常会遗漏它。
|
||||
.replace(/([A-Za-z][A-Za-z0-9_-]*)\[([^\]"\n]+)\]/g, (_matched, nodeId: string, label: string) => (
|
||||
`${nodeId}["${label.trim().replace(/"/g, '\\"')}"]`
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:在 Mermaid 仍无法解析时,将简单流程图转换为可读的流程卡片。
|
||||
* AI 触发时机:图表库抛出语法异常且原文中存在 `A[节点] --> B[节点]` 这类链路时调用。
|
||||
* 核心逻辑:提取节点顺序和标签,输出已转义的 HTML 卡片;忽略不影响主流程的 subgraph 细节。
|
||||
* 参数与输出约束:只用于展示兜底,不执行任何模型输出中的 HTML 或脚本。
|
||||
*/
|
||||
export function buildMermaidFlowFallbackHtml(source: string): string | null {
|
||||
const labels = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
const text = String(source || '');
|
||||
const nodePattern = /([A-Za-z][A-Za-z0-9_-]*)\s*\[\s*"?([^\]\n"]+)"?\s*\]/g;
|
||||
const edgePattern = /([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?\s*--+>\s*([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?/g;
|
||||
const escapeHtml = (value: string) => String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
for (const match of text.matchAll(nodePattern)) {
|
||||
const nodeId = match[1];
|
||||
const label = match[2];
|
||||
if (nodeId && label) labels.set(nodeId, label.trim());
|
||||
}
|
||||
for (const match of text.matchAll(edgePattern)) {
|
||||
const fromId = match[1];
|
||||
const toId = match[2];
|
||||
if (!fromId || !toId) continue;
|
||||
if (!order.includes(fromId)) order.push(fromId);
|
||||
if (!order.includes(toId)) order.push(toId);
|
||||
}
|
||||
if (order.length < 2) return null;
|
||||
const cards = order.map((id, index) => {
|
||||
const card = `<div class="chat-flow-fallback-card">${escapeHtml(labels.get(id) || id)}</div>`;
|
||||
return index < order.length - 1 ? `${card}<div class="chat-flow-fallback-arrow" aria-hidden="true">↓</div>` : card;
|
||||
});
|
||||
return `<div class="chat-flow-fallback" role="img" aria-label="流程图">${cards.join('')}</div>`;
|
||||
}
|
||||
@@ -122,12 +122,16 @@ export const getDocumentWorkflowState = (
|
||||
let syncStage: WorkflowStageState;
|
||||
if (!doc.latest_version || cleanStage.code === 'failed') {
|
||||
syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
|
||||
} else if (syncJob?.status === 'failed') {
|
||||
} else if (syncJob?.status === 'failed' || (latestStatus === 'ready' && Boolean(doc.latest_version?.error_message))) {
|
||||
syncStage = {
|
||||
code: 'failed',
|
||||
label: t('kbWorkspace.status.failed'),
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync', t),
|
||||
errorMessage: normalizeWorkflowErrorMessage(
|
||||
syncJob?.error_message || syncJob?.message || doc.latest_version?.error_message,
|
||||
'sync',
|
||||
t,
|
||||
),
|
||||
};
|
||||
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
|
||||
syncStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
"authFailed": "Authentication failed, please try again",
|
||||
"passwordPolicy": "New password does not meet security requirements",
|
||||
"setPasswordFailed": "Failed to change password. Please try again or contact the administrator.",
|
||||
"incorrectCurrentPassword": "Current password is incorrect",
|
||||
"incorrectCurrentPassword": "Original: current password is incorrect. New: the password you entered is incorrect; please try again.",
|
||||
"userNotInIdp": "Your account has not been registered in the authentication system. Please contact the administrator to sync your account before changing your password."
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"codes": {
|
||||
"AUTH_UNAUTHORIZED": "Please log in first.",
|
||||
"AUTH_INCORRECT_PASSWORD": "Incorrect password",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "Incorrect current password",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "Original: current password is incorrect. New: the password you entered is incorrect; please try again.",
|
||||
"AUTH_USER_NOT_FOUND": "User not found",
|
||||
"AUTH_ACCOUNT_DISABLED": "Account is disabled",
|
||||
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor did not return a stable user identity. Check the OIDC configuration.",
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"authFailed": "เข้าสู่ระบบไม่สำเร็จ กรุณาลองใหม่",
|
||||
"passwordPolicy": "รหัสผ่านใหม่ไม่ตรงตามข้อกำหนดด้านความปลอดภัย",
|
||||
"setPasswordFailed": "เปลี่ยนรหัสผ่านไม่สำเร็จ กรุณาลองใหม่หรือติดต่อผู้ดูแลระบบ",
|
||||
"incorrectCurrentPassword": "รหัสผ่านปัจจุบันไม่ถูกต้อง",
|
||||
"incorrectCurrentPassword": "เดิม: รหัสผ่านปัจจุบันไม่ถูกต้อง ใหม่: รหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง",
|
||||
"userNotInIdp": "บัญชีของคุณยังไม่ได้ลงทะเบียนในระบบยืนยันตัวตน กรุณาติดต่อผู้ดูแลระบบเพื่อซิงค์บัญชีก่อนเปลี่ยนรหัสผ่าน"
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"codes": {
|
||||
"AUTH_UNAUTHORIZED": "กรุณาเข้าสู่ระบบก่อน",
|
||||
"AUTH_INCORRECT_PASSWORD": "รหัสผ่านไม่ถูกต้อง",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "รหัสผ่านปัจจุบันไม่ถูกต้อง",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "เดิม: รหัสผ่านปัจจุบันไม่ถูกต้อง ใหม่: รหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง",
|
||||
"AUTH_USER_NOT_FOUND": "ไม่พบผู้ใช้",
|
||||
"AUTH_ACCOUNT_DISABLED": "บัญชีถูกปิดใช้งาน",
|
||||
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor ไม่ได้ส่งคืนข้อมูลระบุตัวผู้ใช้ที่คงที่ โปรดตรวจสอบการตั้งค่า OIDC",
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
"authFailed": "登录失败,请稍后重试",
|
||||
"passwordPolicy": "新密码不符合安全要求",
|
||||
"setPasswordFailed": "修改密码失败,请稍后重试或联系管理员",
|
||||
"incorrectCurrentPassword": "当前密码不正确",
|
||||
"incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入",
|
||||
"userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。"
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"codes": {
|
||||
"AUTH_UNAUTHORIZED": "请先登录。",
|
||||
"AUTH_INCORRECT_PASSWORD": "密码错误",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "当前密码不正确",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "原:当前密码不正确,新:您输入的原密码有误,请重新输入",
|
||||
"AUTH_USER_NOT_FOUND": "用户不存在",
|
||||
"AUTH_ACCOUNT_DISABLED": "账号已禁用",
|
||||
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回稳定用户身份,请联系管理员检查 OIDC 配置。",
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"authFailed": "登入失敗,請稍後重試",
|
||||
"passwordPolicy": "新密碼不符合安全要求",
|
||||
"setPasswordFailed": "修改密碼失敗,請稍後重試或聯繫管理員",
|
||||
"incorrectCurrentPassword": "當前密碼不正確",
|
||||
"incorrectCurrentPassword": "原:當前密碼不正確,新:您輸入的原密碼有誤,請重新輸入",
|
||||
"userNotInIdp": "您的賬號尚未在統一認證系統中開通,請聯繫管理員同步賬號後再修改密碼。"
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"codes": {
|
||||
"AUTH_UNAUTHORIZED": "請先登入。",
|
||||
"AUTH_INCORRECT_PASSWORD": "密碼錯誤",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "當前密碼不正確",
|
||||
"AUTH_INCORRECT_CURRENT_PASSWORD": "原:當前密碼不正確,新:您輸入的原密碼有誤,請重新輸入",
|
||||
"AUTH_USER_NOT_FOUND": "用戶不存在",
|
||||
"AUTH_ACCOUNT_DISABLED": "帳號已禁用",
|
||||
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回穩定用戶身份,請聯絡管理員檢查 OIDC 設定。",
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/FilePreviewModal.vue
|
||||
* 文件预览弹窗(图片/PDF 等)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* FilePreviewModal.vue
|
||||
* 文件用途:文件预览弹窗,用于在聊天页预览来源文件内容
|
||||
* 引用文件:vue, marked
|
||||
* 逻辑关系:
|
||||
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
|
||||
* - 根据扩展名选择预览模式(markdown/image/iframe/office)
|
||||
* - Excel 预览优先走 Office 风格渲染,尽量还原原始表格观感;失败时再降级为简化表格
|
||||
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
|
||||
* 用途:聊天页源文件预览弹窗(图片/PDF/Office/Markdown/表格)。
|
||||
* 依赖:vue、marked、xlsx、@vue-office/*、lucide-vue-next。
|
||||
* 逻辑:ChatViewOverlays 传入 file/files;按扩展名选择模式;源文件缺失时尊重后端 X-Preview-Actual-Ext 回退文本预览。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -382,7 +373,38 @@ const fallbackToSheetPreview = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
/**
|
||||
* 判断预览载荷是否为 Office/PDF 等二进制,避免 UTF-8 解码后 Markdown 乱码。
|
||||
*/
|
||||
const isBinaryPreviewPayload = (buffer: ArrayBuffer): boolean => {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
if (bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d) {
|
||||
return true; // %PDF-
|
||||
}
|
||||
if (bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
|
||||
return true; // ZIP / OOXML
|
||||
}
|
||||
if (
|
||||
bytes.length >= 8
|
||||
&& bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0
|
||||
&& bytes[4] === 0xa1 && bytes[5] === 0xb1 && bytes[6] === 0x1a && bytes[7] === 0xe1
|
||||
) {
|
||||
return true; // OLE Compound Document (.doc/.xls/.ppt)
|
||||
}
|
||||
const sample = bytes.subarray(0, Math.min(bytes.length, 512));
|
||||
let nul = 0;
|
||||
for (let i = 0; i < sample.length; i += 1) {
|
||||
if (sample[i] === 0) nul += 1;
|
||||
}
|
||||
return nul > sample.length * 0.02;
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取 PDF/Office 预览内容;若后端因源文件缺失回退到文本,则按 X-Preview-Actual-Ext 渲染 Markdown。
|
||||
* 核心逻辑:请求 /preview-file-raw,根据实际扩展名在 iframe / office / sheet / markdown 间切换。
|
||||
* @returns 最终预览模式
|
||||
*/
|
||||
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet' | 'markdown'> => {
|
||||
if (!props.file?.url) return 'iframe';
|
||||
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
|
||||
|
||||
@@ -413,6 +435,16 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
const actualExt = (res.headers.get('X-Preview-Actual-Ext') || '').toLowerCase();
|
||||
const blobType = (blob.type || '').toLowerCase();
|
||||
const effectiveExt = actualExt || ext.value;
|
||||
const binaryPayload = isBinaryPreviewPayload(buffer);
|
||||
// 源文件丢失时后端可能回退到清洗稿/分段文本;二进制载荷绝不能当 Markdown 解码
|
||||
if (
|
||||
!binaryPayload
|
||||
&& (['md', 'markdown', 'txt'].includes(actualExt) || blobType.includes('markdown'))
|
||||
) {
|
||||
const text = new TextDecoder('utf-8').decode(buffer);
|
||||
markdownHtml.value = marked.parse(text) as string;
|
||||
return 'markdown';
|
||||
}
|
||||
const isDocxPayload = actualExt === 'docx' || blobType.includes('wordprocessingml.document');
|
||||
const isExcelPayload = ['xlsx', 'xls'].includes(actualExt) || blobType.includes('spreadsheetml.sheet') || blobType.includes('application/vnd.ms-excel');
|
||||
if (isExcelPayload) {
|
||||
@@ -431,6 +463,15 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
officeKind.value = 'docx';
|
||||
return 'office';
|
||||
}
|
||||
// 旧版 .doc 仍是 OLE:后端应转 PDF;若仍返回原始 OLE,给出明确错误而非乱码
|
||||
if (
|
||||
binaryPayload
|
||||
&& (effectiveExt === 'doc' || ext.value === 'doc')
|
||||
&& !blobType.includes('pdf')
|
||||
&& !(actualExt === 'pdf')
|
||||
) {
|
||||
throw new Error('旧版 Word(.doc)未能转换为可预览格式,请安装 LibreOffice/Word 后重试,或改为上传 .docx/.pdf');
|
||||
}
|
||||
if (!blobType.includes('pdf') && officePreviewExts.has(effectiveExt)) {
|
||||
throw new Error(t('filePreview.unsupportedRawPreview'));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
scripts/seed_fire_extinguisher_faq.py
|
||||
|
||||
用途:为“人事规章”Agent 写入灭火器常见问题的本地 FAQ 兜底。
|
||||
依赖:Flask 应用、PostgreSQL quick_questions 表。
|
||||
逻辑:按 Agent 名称和标准问题幂等查找;不存在则创建,存在则补齐同义问法与标准答案。
|
||||
执行:在仓库根目录运行 `python scripts/seed_fire_extinguisher_faq.py`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'backend'))
|
||||
|
||||
from app import create_app, db # noqa: E402
|
||||
from app.models import Agent, QuickQuestion # noqa: E402
|
||||
|
||||
|
||||
FAQ_ITEMS = [
|
||||
{
|
||||
'title': '水型灭火器适用场合',
|
||||
'question': '水型灭火器适用场合',
|
||||
'aliases': [
|
||||
'水型灭火器适用于什么火灾',
|
||||
'水基灭火器能灭什么火',
|
||||
'水型灭火器适用范围',
|
||||
'A类火灾用什么灭火器',
|
||||
],
|
||||
'answer': (
|
||||
'水型灭火器主要适用于 A 类火灾,即木材、纸张、棉麻等固体可燃物火灾。'
|
||||
'不适用于油类、汽油等 B 类液体火灾,也不适用于带电设备火灾;具体以现场灭火器标识和公司安全制度为准。'
|
||||
),
|
||||
},
|
||||
{
|
||||
'title': '不同类型灭火器怎么使用',
|
||||
'question': '不同类型灭火器怎么使用',
|
||||
'aliases': [
|
||||
'灭火器使用方法',
|
||||
'灭火器适用场合和使用注意事项',
|
||||
'各种灭火器分别适合什么火灾',
|
||||
],
|
||||
'answer': (
|
||||
'使用灭火器前先确认火灾类型并站在上风口。水型灭火器主要用于 A 类固体火灾;'
|
||||
'干粉灭火器适用范围较广,但仍需按瓶身标识选择;二氧化碳灭火器常用于电气设备和精密仪器。'
|
||||
'油类、电气等场景不要盲目使用水型灭火器,应先断电并按现场安全制度处置。'
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
agent = db.session.query(Agent).filter(Agent.name == '人事规章').first()
|
||||
if not agent:
|
||||
raise RuntimeError('未找到“人事规章”Agent,请先确认 Agent 已初始化。')
|
||||
for item in FAQ_ITEMS:
|
||||
faq = db.session.query(QuickQuestion).filter(
|
||||
QuickQuestion.user_id.is_(None),
|
||||
QuickQuestion.agent_id == agent.id,
|
||||
QuickQuestion.question == item['question'],
|
||||
).first()
|
||||
if faq is None:
|
||||
faq = QuickQuestion(user_id=None, agent_id=agent.id, sort_order=10)
|
||||
db.session.add(faq)
|
||||
faq.title = item['title']
|
||||
faq.question = item['question']
|
||||
faq.aliases = item['aliases']
|
||||
faq.answer = item['answer']
|
||||
faq.cache_enabled = True
|
||||
faq.is_enabled = True
|
||||
faq.stale_at = None
|
||||
faq.stale_reason = None
|
||||
db.session.commit()
|
||||
print(f'已为 Agent={agent.id} 写入 {len(FAQ_ITEMS)} 条灭火器 FAQ。')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user