feat(file-check): 增加文件检核 Excel 下载链接解析与展示功能

This commit is contained in:
hugo committed 2026-07-10 13:28:41 +08:00
1 parent 5e7e5a8717
commit f21216f81e
21 files changed
+885 -125

No files matched your search

+97 -19
View File
@@ -134,6 +134,98 @@ class DifyService:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _merge_stream_answer_text(
streamed_text: str,
terminal_answer: str | None,
*,
replace_answer: bool = False,
) -> str:
"""
合并流式增量文本与终态 answer,避免 Dify 结束事件重复携带整段正文导致落库翻倍。
核心逻辑:与前端 useChat.ts 终态事件去重策略保持一致。
Args:
streamed_text: message 事件累积的增量文本。
terminal_answer: message_end / workflow_finished 携带的 answer。
replace_answer: 为 True 时仅使用终态 answer。
Returns:
去重后的最终正文。
"""
current_content = str(streamed_text or '')
terminal = str(terminal_answer or '')
if replace_answer and terminal.strip():
return terminal.strip()
if not terminal:
return current_content.strip()
if not current_content.strip():
return terminal.strip()
current_stripped = current_content.strip()
terminal_stripped = terminal.strip()
if (
terminal_stripped
and current_stripped
and len(terminal_stripped) >= len(current_stripped)
and current_stripped in terminal_stripped
):
return terminal_stripped
if terminal_stripped and current_stripped and terminal_stripped in current_stripped:
return current_stripped
return (current_content + terminal).strip()
@staticmethod
def _build_final_answer_text(
*,
streamed_parts: list[str],
data: dict,
event_name: str,
) -> str:
"""
根据流式片段与终态事件组装最终落库 answer。
核心逻辑:先走 _merge_stream_answer_text 去重;workflow_finished 无 answer 时回退 outputs。
"""
streamed_text = ''.join(streamed_parts)
terminal = str(data.get('answer') or '') if data.get('answer') else ''
answer_text = DifyService._merge_stream_answer_text(
streamed_text,
terminal or None,
replace_answer=bool(data.get('replace_answer')),
)
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
@staticmethod
def _dedupe_exact_doubled_text(text: str) -> str:
"""
修复历史落库时将同一段正文原样拼接两次的记录。
核心逻辑:仅当整段文本可被均分为两段完全相同子串时才裁剪。
"""
normalized = str(text or '')
stripped = normalized.strip()
if len(stripped) < 2:
return normalized
half = len(stripped) // 2
if len(stripped) % 2 == 0 and stripped[:half] == stripped[half:]:
return stripped[:half]
return normalized
@staticmethod
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(data, dict):
@@ -896,25 +988,11 @@ class DifyService:
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip()
if data.get('answer'):
answer_text = (answer_text + str(data.get('answer') or '')).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
return DifyService._build_final_answer_text(
streamed_parts=full_answer,
data=data,
event_name=event_name,
)
max_retries = 3
@@ -108,6 +108,9 @@
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/DataSourceUnavailable"
}
}
}
@@ -533,7 +536,8 @@
"properties": {
"task_id": {
"type": "integer",
"example": 12
"example": 12,
"description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
},
"trigger_source": {
"type": "string",
@@ -561,7 +565,7 @@
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -887,6 +891,21 @@
}
}
}
},
"DataSourceUnavailable": {
"description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "data_source_unavailable",
"message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动"
}
}
}
}
}
}
+53 -11
View File
@@ -1,23 +1,42 @@
"""
backend/app/services/hxops_tool_api.py
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
依赖:Flask current_app / request。
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
def _resolve_config(config: dict | None = None) -> dict:
"""读取 Flask config 或空 dict。"""
if config is not None:
return config
if current_app:
return current_app.config
return {}
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
"""
返回 Dify / RPA 等服务端调用 Tool API 时使用的根地址(无尾斜杠)。
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
Args:
config: 可选配置字典;缺省时读 current_app.config。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
Returns:
无尾斜杠的根地址,如 http://192.168.100.192:8890。
"""
cfg = _resolve_config(config)
configured = str(cfg.get("HXOPS_TOOLS_API_BASE") or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
@@ -25,3 +44,26 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return host or ""
def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
"""
返回浏览器侧可访问的根地址,用于 Excel 签名下载等用户可见链接。
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
Args:
config: 可选配置字典;缺省时读 current_app.config。
Returns:
无尾斜杠的根地址,如 https://ai.example.com。
"""
cfg = _resolve_config(config)
for key in ("HXOPS_PUBLIC_BASE_URL", "WECOM_PUBLIC_BASE_URL"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
if has_request_context():
return request.host_url.rstrip("/")
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)