Files
syops/backend/app/services/dify.py
T

1776 lines
74 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/dify.py
File-Level Overview
-------------------
This module provides the backend service wrapper for Dify streaming chat APIs.
It is responsible for:
1) Forwarding chat requests from this system to Dify in streaming mode.
2) Relaying Dify SSE events to the frontend.
3) Aggregating answer text and metadata (retriever resources / attribution).
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
4) Enriching retriever resources with original source-file download URLs via
the integration API mapping (dataset_id + remote_document_id).
5) Persisting chat logs to the local database.
Main Data Flow
--------------
chat.py (/api/chat/completions)
-> DifyService.stream_chat(...)
-> requests.post(... stream=True) to Dify
-> parse SSE events from Dify
-> optional enrichment of source links on message_end
-> write chat log
-> yield SSE events to frontend
"""
import json
import os
import re
import time
import uuid
from datetime import datetime, timedelta
from threading import Lock, Thread
from typing import Any, List, Optional
import requests
from flask import current_app
from app.core.config.settings import Config
from app import db
from app.models import ChatLog
from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled
from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
SUPPORTED_FILE_EXTS: dict[str, set[str]] = {
"document": {
"txt",
"md",
"markdown",
"mdx",
"pdf",
"html",
"htm",
"xlsx",
"xls",
"vtt",
"properties",
"doc",
"docx",
"csv",
"eml",
"msg",
"pptx",
"ppt",
"xml",
"epub",
},
"image": {"jpg", "jpeg", "png", "gif", "webp", "svg"},
"audio": {"mp3", "m4a", "wav", "webm", "mpga"},
"video": {"mp4", "mov", "mpeg", "webm"},
}
@staticmethod
def _extract_workflow_failure_text(data: dict) -> str:
"""
从 Dify workflow_finished 失败事件里提取原始错误文本。
AI 触发时机:Dify Tool/节点失败但 HTTP 仍为 200 时,用于日志留痕和用户友好提示转译。
Args:
data: Dify SSE 事件体。
Returns:
原始错误文本;没有失败信息时返回空字符串。
"""
if data.get("event") != "workflow_finished":
return ""
wf_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if str(wf_data.get("status") or "").lower() != "failed":
return ""
candidates = [
data.get("message"),
data.get("description"),
data.get("error"),
wf_data.get("message"),
wf_data.get("description"),
wf_data.get("error"),
wf_data.get("errmsg"),
]
for candidate in candidates:
if candidate is None:
continue
if isinstance(candidate, str) and candidate.strip():
return candidate.strip()
try:
text = json.dumps(candidate, ensure_ascii=False, default=str)
except Exception:
text = str(candidate)
if text.strip() and text.strip() != "null":
return text.strip()
return ""
@staticmethod
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
"""
将 Dify/Tool 技术错误转成用户可读提示。
Args:
raw_error: Dify 返回的原始错误文本。
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
Returns:
面向用户展示的简短中文提示。
"""
text = str(raw_error or "")
lower = text.lower()
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
return f"{resolved_agent_name}暂时无法访问查询服务,请稍后重试或联系管理员检查工具授权。"
if "ssrf" in lower or "blocked" in lower or "private or local network" in lower:
return f"{resolved_agent_name}暂时无法访问查询服务,请联系管理员检查工具网络访问配置。"
if "failed to invoke tool" in lower or "tool" in lower:
return f"{resolved_agent_name}查询工具调用失败,请稍后重试;如持续失败请联系管理员。"
if "maximum context length" in lower or "input_tokens" in lower:
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):
return None
file_upload = data.get("file_upload")
if not isinstance(file_upload, dict):
return data
allowed_types = file_upload.get("allowed_file_types") or []
allowed_types_set = set(
str(v or "").strip().lower()
for v in (allowed_types if isinstance(allowed_types, list) else [])
if str(v or "").strip()
)
allowed_exts = file_upload.get("allowed_file_extensions") or []
normalized_exts = []
for v in (allowed_exts if isinstance(allowed_exts, list) else []):
s = str(v or "").strip()
if not s:
continue
if s.startswith("."):
s = s[1:]
s = s.strip()
if not s:
continue
normalized_exts.append(s.lower())
normalized_exts_set = set(normalized_exts)
has_doc_ext = any(DifyService.detect_file_type(f"file.{e}", None)[0] == "document" for e in normalized_exts_set)
doc_cfg = file_upload.get("document") if isinstance(file_upload, dict) else None
doc_enabled = None
if isinstance(doc_cfg, dict) and isinstance(doc_cfg.get("enabled"), bool):
doc_enabled = bool(doc_cfg.get("enabled"))
if "document" in allowed_types_set and doc_enabled is not False and not has_doc_ext:
add_exts = sorted(DifyService.SUPPORTED_FILE_EXTS.get("document") or [])
use_upper = any(str(v or "").strip().startswith(".") and str(v or "").strip().upper() == str(v or "").strip() for v in allowed_exts)
expanded = list(allowed_exts) if isinstance(allowed_exts, list) else []
for e in add_exts:
if e in normalized_exts_set:
continue
expanded.append(f".{e.upper()}" if use_upper else f".{e}")
normalized_exts_set.add(e)
file_upload = dict(file_upload)
file_upload["allowed_file_extensions"] = expanded
data = dict(data)
data["file_upload"] = file_upload
return data
@staticmethod
def is_known_file_extension(ext: str | None) -> bool:
value = str(ext or "").strip().lower()
if not value:
return False
return any(value in s for s in DifyService.SUPPORTED_FILE_EXTS.values())
@staticmethod
def detect_file_type(filename: str | None, mimetype: str | None) -> tuple[str | None, str]:
name = str(filename or "").strip()
mime = str(mimetype or "").strip().lower()
ext = ""
if "." in name:
ext = name.rsplit(".", 1)[-1].lower().strip()
if mime.startswith("image/"):
return "image", ext
if mime.startswith("audio/"):
return "audio", ext
if mime.startswith("video/"):
return "video", ext
if ext in DifyService.SUPPORTED_FILE_EXTS["image"]:
return "image", ext
if ext in DifyService.SUPPORTED_FILE_EXTS["document"]:
return "document", ext
in_audio = ext in DifyService.SUPPORTED_FILE_EXTS["audio"]
in_video = ext in DifyService.SUPPORTED_FILE_EXTS["video"]
if in_audio and not in_video:
return "audio", ext
if in_video:
return "video", ext
return None, ext
@staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
"""
Dify 只接受标准 UUID 会话 ID。
本项目里 ERP Text2SQL 会生成 `erp_xxx` 形式的本地会话号,
这类值不能继续透传给 Dify,否则会触发 400 invalid_param。
"""
value = str(conversation_id or "").strip()
if not value:
return ""
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
if current_app:
current_app.logger.warning(
"[chat-stream] ignore non-uuid conversation_id for dify: %s",
value,
)
return ""
@staticmethod
def _build_chat_messages_url(base_url: str) -> str:
"""
Build the Dify chat-messages endpoint URL from a base URL.
Our config/agent base_url may be:
- https://api.dify.ai/v1
- http://host:port
- http://host:port/v1
- (user mistake) http://host:port/v1/chat-messages
This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`.
"""
base = str(base_url or "").strip().rstrip("/")
if not base:
# Keep old behavior: downstream will fail with a request error.
return "/v1/chat-messages"
# User mistake hardening: strip endpoint suffix if someone stored it as base_url.
if base.endswith("/v1/chat-messages"):
base = base[: -len("/v1/chat-messages")].rstrip("/")
elif base.endswith("/chat-messages"):
base = base[: -len("/chat-messages")].rstrip("/")
# Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1".
if base.endswith("/v1"):
return f"{base}/chat-messages"
return f"{base}/v1/chat-messages"
@staticmethod
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
def _is_file_obj(v: Any) -> bool:
if not isinstance(v, dict):
return False
if not str(v.get("type") or "").strip():
return False
tm = str(v.get("transfer_method") or "").strip()
if tm not in {"local_file", "remote_url"}:
return False
if tm == "local_file":
return bool(str(v.get("upload_file_id") or "").strip())
return bool(str(v.get("url") or "").strip())
def _convert(v):
if v is None:
return ""
if _is_file_obj(v):
return v
if isinstance(v, dict):
return {kk: _convert(vv) for kk, vv in v.items()}
if isinstance(v, list):
if v and all(_is_file_obj(i) for i in v):
return v
return [_convert(i) for i in v]
return str(v)
return {k: _convert(v) for k, v in (inputs or {}).items()}
@staticmethod
def _build_workflow_url(base_url: str) -> str:
base = str(base_url or "").strip().rstrip("/")
if not base:
return "/v1/workflows/run"
if base.endswith("/v1/workflows/run"):
base = base[: -len("/v1/workflows/run")].rstrip("/")
elif base.endswith("/workflows/run"):
base = base[: -len("/workflows/run")].rstrip("/")
if base.endswith("/v1"):
return f"{base}/workflows/run"
return f"{base}/v1/workflows/run"
@staticmethod
def _build_parameters_url(base_url: str) -> str:
base = str(base_url or "").strip().rstrip("/")
if not base:
return "/v1/parameters"
if base.endswith("/v1/parameters"):
base = base[: -len("/v1/parameters")].rstrip("/")
elif base.endswith("/parameters"):
base = base[: -len("/parameters")].rstrip("/")
if base.endswith("/v1"):
return f"{base}/parameters"
return f"{base}/v1/parameters"
@staticmethod
def _build_files_upload_url(base_url: str) -> str:
base = str(base_url or "").strip().rstrip("/")
if not base:
return "/v1/files/upload"
if base.endswith("/v1/files/upload"):
base = base[: -len("/v1/files/upload")].rstrip("/")
elif base.endswith("/files/upload"):
base = base[: -len("/files/upload")].rstrip("/")
if base.endswith("/v1"):
return f"{base}/files/upload"
return f"{base}/v1/files/upload"
_PARAMETERS_CACHE: dict[str, dict[str, Any]] = {}
_PARAMETERS_CACHE_LOCK = Lock()
@staticmethod
def get_app_parameters(agent, *, ttl_seconds: int = 300, timeout: int = 8, force_refresh: bool = False) -> dict[str, Any] | None:
agent_id = str(getattr(agent, "id", "") or "")
api_key = str(getattr(agent, "dify_api_key", "") or "").strip()
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_parameters_url(base_url)
cache_key = f"{agent_id}:{url}"
now = datetime.utcnow()
stale_data: dict[str, Any] | None = None
with DifyService._PARAMETERS_CACHE_LOCK:
cached = DifyService._PARAMETERS_CACHE.get(cache_key)
if cached and isinstance(cached.get("data"), dict):
stale_data = cached.get("data")
if (not force_refresh) and cached and isinstance(cached.get("_expires_at"), datetime) and cached["_expires_at"] > now:
return cached.get("data")
if not api_key:
return stale_data
headers = {"Authorization": f"Bearer {api_key}"}
try:
resp = requests.get(url, headers=headers, timeout=timeout)
if not resp.ok:
if current_app:
current_app.logger.warning(
"[dify] get parameters failed agent_id=%s status=%s url=%s body=%s",
agent_id,
resp.status_code,
url,
(resp.text or "")[:500],
)
return DifyService._normalize_parameters_payload(stale_data) or stale_data
data = resp.json() if resp.content else {}
except Exception as exc:
if current_app:
current_app.logger.warning("[dify] get parameters exception agent_id=%s url=%s err=%s", agent_id, url, exc)
return DifyService._normalize_parameters_payload(stale_data) or stale_data
data = DifyService._normalize_parameters_payload(data) or data
with DifyService._PARAMETERS_CACHE_LOCK:
DifyService._PARAMETERS_CACHE[cache_key] = {
"_expires_at": now + timedelta(seconds=ttl_seconds),
"data": data,
}
return data
@staticmethod
def _classify_workflow_request_exception(exc: Exception) -> tuple[str, bool]:
"""
将 Workflow HTTP/网络异常归类为 error_type,并判断是否可重试。
502/503/504 与连接/读超时视为可恢复;400/401/403 不重试。
"""
if isinstance(exc, requests.exceptions.ConnectTimeout):
return "connect_timeout", True
if isinstance(exc, requests.exceptions.ReadTimeout):
return "read_timeout", True
if isinstance(exc, requests.exceptions.ConnectionError):
return "connection_error", True
if isinstance(exc, requests.exceptions.HTTPError):
status = int(getattr(getattr(exc, "response", None), "status_code", 0) or 0)
if status in (502, 503, 504):
return f"http_{status}", True
if status in (400, 401, 403):
return f"http_{status}", False
return f"http_{status}", False
return "request_error", False
@staticmethod
def _attach_workflow_reliability_meta(
result: dict[str, Any],
*,
poll_used: bool = False,
retry_count: int = 0,
error_type: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""在 Dify Workflow 响应上附加网关侧可靠性元信息(poll/重试/错误类型)。"""
out = dict(result) if isinstance(result, dict) else {}
if workflow_run_id and not out.get("workflow_run_id"):
out["workflow_run_id"] = workflow_run_id
out["_workflow_poll_used"] = bool(poll_used)
out["_workflow_retry_count"] = max(0, int(retry_count))
if error_type:
out["_workflow_error_type"] = error_type
return out
@staticmethod
def _observe_workflow_event(event_observer, event_type: str, event_data: dict[str, Any], state: dict[str, Any]) -> None:
"""向可选观察器发送脱敏 Workflow 生命周期字段;观察器错误不得中断Provider调用。"""
if event_observer is None:
return
node_data = event_data.get('node_data') if isinstance(event_data.get('node_data'), dict) else {}
try:
event_observer({
'event_type': str(event_type),
'workflow_run_id': event_data.get('workflow_run_id') or state.get('workflow_run_id'),
'node_execution_id': event_data.get('node_execution_id') or event_data.get('node_id'),
'node_type': event_data.get('node_type') or node_data.get('type'),
'node_title': event_data.get('title') or node_data.get('title'),
'event_status': event_data.get('status'),
})
except Exception:
if current_app:
current_app.logger.exception('[workflow-streaming] event observer failed')
@staticmethod
def _consume_workflow_stream(
*,
url: str,
headers: dict[str, str],
payload: dict[str, Any],
timeout: tuple[int, int],
state: dict[str, Any],
event_observer=None,
) -> dict[str, Any]:
"""
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
state 在解析过程中写入 workflow_run_id / result,供断连后补偿使用。
"""
result: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
)
resp.raise_for_status()
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
event_data = evt.get('data') if isinstance(evt.get('data'), dict) else {}
DifyService._observe_workflow_event(event_observer, str(event_type), event_data, state)
if event_type == "workflow_started":
run_id = (evt.get("data") or {}).get("workflow_run_id")
state["workflow_run_id"] = run_id
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
state["result"] = result
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
return result
@staticmethod
def run_workflow_streaming(
*,
agent,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 300),
event_observer=None,
) -> dict[str, Any]:
"""
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
对可恢复网络错误最多重试 1 次;返回体附带 _workflow_* 可靠性元信息。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_workflow_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"response_mode": "streaming",
"user": str(user or "system"),
}
max_wait = timeout[1] if isinstance(timeout, tuple) else 300
max_attempts = 2
retry_count = 0
poll_used = False
last_error_type: str | None = None
last_workflow_run_id: str | None = None
if current_app:
current_app.logger.info(
"[workflow-streaming] start user=%s agent_id=%s url=%s",
user,
getattr(agent, "id", None),
url,
)
result: dict[str, Any] = {}
stream_state: dict[str, Any] = {"workflow_run_id": None, "result": {}}
for attempt in range(max_attempts):
try:
result = DifyService._consume_workflow_stream(
url=url,
headers=headers,
payload=payload,
timeout=timeout,
state=stream_state,
event_observer=event_observer,
)
workflow_run_id = stream_state.get("workflow_run_id")
if workflow_run_id:
last_workflow_run_id = workflow_run_id
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
if not result and workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'poll_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
workflow_run_id,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or "stream_closed_early",
workflow_run_id=workflow_run_id,
)
if current_app:
current_app.logger.info(
"[workflow-streaming] attempt=%s finished run_id=%s retry_count=%s",
attempt + 1,
workflow_run_id,
retry_count,
)
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=False,
retry_count=retry_count,
workflow_run_id=workflow_run_id,
)
except requests.exceptions.RequestException as exc:
error_type, retryable = DifyService._classify_workflow_request_exception(exc)
last_error_type = error_type
workflow_run_id = stream_state.get("workflow_run_id")
partial_result = stream_state.get("result") or {}
if workflow_run_id:
last_workflow_run_id = workflow_run_id
if current_app:
current_app.logger.warning(
"[workflow-streaming] attempt=%s error_type=%s retryable=%s run_id=%s err=%s",
attempt + 1,
error_type,
retryable,
workflow_run_id,
exc,
)
if partial_result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured run_id=%s",
workflow_run_id,
)
return DifyService._attach_workflow_reliability_meta(
partial_result,
poll_used=False,
retry_count=retry_count,
error_type=error_type,
workflow_run_id=workflow_run_id,
)
if workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'stream_interrupted', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
workflow_run_id,
error_type,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or error_type,
workflow_run_id=workflow_run_id,
)
if retryable and attempt < max_attempts - 1:
retry_count += 1
DifyService._observe_workflow_event(
event_observer, 'retry_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.info(
"[workflow-streaming] retrying attempt=%s error_type=%s",
attempt + 2,
error_type,
)
continue
if current_app:
current_app.logger.error(
"[workflow-streaming] request failed (no run_id) error_type=%s err=%s",
error_type,
exc,
)
raise
return DifyService._attach_workflow_reliability_meta(
result if isinstance(result, dict) else {},
poll_used=poll_used,
retry_count=retry_count,
error_type=last_error_type,
workflow_run_id=last_workflow_run_id,
)
@staticmethod
def _poll_workflow_result(
*,
agent,
workflow_run_id: str,
max_wait: int = 300,
interval: int = 10,
) -> dict[str, Any]:
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
base = str(base_url).strip().rstrip("/")
if base.endswith("/v1/workflows/run"):
base = base[: -len("/v1/workflows/run")].rstrip("/")
elif base.endswith("/workflows/run"):
base = base[: -len("/workflows/run")].rstrip("/")
if base.endswith("/v1"):
poll_url = f"{base}/workflows/run/{workflow_run_id}"
else:
poll_url = f"{base}/v1/workflows/run/{workflow_run_id}"
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
elapsed = 0
while elapsed < max_wait:
time.sleep(interval)
elapsed += interval
try:
resp = requests.get(poll_url, headers=headers, timeout=(5, 30))
if not resp.ok:
if current_app:
current_app.logger.warning(
"[workflow-poll] status=%s url=%s",
resp.status_code, poll_url,
)
continue
data = resp.json() if resp.content else {}
status = data.get("status", "")
if current_app:
current_app.logger.info(
"[workflow-poll] run_id=%s status=%s elapsed=%ds",
workflow_run_id, status, elapsed,
)
if status in ("succeeded", "failed", "stopped"):
return data
except requests.exceptions.RequestException as exc:
if current_app:
current_app.logger.warning(
"[workflow-poll] request error: %s",
exc,
)
continue
if current_app:
current_app.logger.error(
"[workflow-poll] timed out after %ds run_id=%s",
max_wait, workflow_run_id,
)
return {}
@staticmethod
def stream_chat(
query: str,
user_id: int,
agent,
conversation_id: str = None,
request_id: str | None = None,
session_id: str | None = None,
hxops_turn_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
persist_chat_log: bool = True,
display_query: str | None = None,
):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller.
Args:
query: User prompt text.
user_id: Local user ID (sent to Dify as user string).
agent: Agent model instance, must contain dify_api_key and optional api_base_url.
conversation_id: Existing conversation ID for multi-turn context (optional).
Yields:
SSE event lines in format: `data: {...}\\n\\n`.
Side Effects:
- Collects/merges metadata from Dify events.
- Enriches retriever resources with source URLs on message_end.
- Persists chat log to DB when message_end arrives.
- Writes diagnostic logs.
"""
# Prefer agent-specific base URL; fallback to global config.
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
visible_query = str(query if display_query is None else display_query).strip()
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
'Content-Type': 'application/json',
}
payload = {
'inputs': dict(inputs or {}),
'query': query,
'response_mode': 'streaming',
'user': str(user_id),
}
if normalized_conversation_id:
payload['conversation_id'] = normalized_conversation_id
if files:
payload['files'] = files
if current_app:
current_app.logger.info(
"[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
request_id,
user_id,
getattr(agent, 'id', None),
base_url,
len(query or ''),
normalized_conversation_id or conversation_id,
)
start_time = time.time()
perf = ChatPerfTracker(request_id=request_id, agent_id=getattr(agent, "id", None))
first_token_at: float | None = None
message_count = 0
event_count = 0
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
chat_persist_started = False
has_sent_answer = False
chat_log_id_persisted: int | None = None
run_id_persisted: int | None = None
def _resolve_persist_run_id() -> int | None:
try:
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if not is_file_check_runtime_ready(agent):
return None
return resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
return None
def persist_stream_chat(data: dict, event_name: str) -> None:
if not persist_chat_log:
return
result = persist_stream_chat_async(data, event_name)
if isinstance(result, dict):
if result.get("chat_log_id") is not None:
data["chat_log_id"] = result["chat_log_id"]
if result.get("run_id") is not None:
data["run_id"] = result["run_id"]
def persist_stream_chat_async(data: dict, event_name: str) -> dict | None:
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
# [STEP 1] message_end 可能已落库但 tokens=0;workflow_finished 携带 data.total_tokens 时回写
wf_tokens = DifyService._extract_token_usage(data)
app_obj = current_app._get_current_object() if current_app else None
if app_obj and wf_tokens > 0:
with app_obj.app_context():
DifyService._update_chat_log_tokens(chat_log_id_persisted, wf_tokens)
run_id = _resolve_persist_run_id()
if run_id and run_id != run_id_persisted:
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
if update_chat_log_run_id(chat_log_id_persisted, run_id):
run_id_persisted = run_id
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted}
if chat_persist_started:
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted} if chat_log_id_persisted else None
chat_persist_started = True
app_obj = current_app._get_current_object() if current_app else None
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
resources_for_persist = data.get('retriever_resources') or retriever_resources
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
message_payload = persist_data.get('message_payload')
if not app_obj:
return None
with app_obj.app_context():
result = DifyService._persist_stream_chat_record(
data=persist_data,
event_name=event_name,
request_id=request_id,
user_id=user_id,
agent=agent,
session_id=session_id,
hxops_turn_id=hxops_turn_id,
normalized_conversation_id=normalized_conversation_id,
query=visible_query,
answer_text=answer_snapshot,
latency=latency_snapshot,
retriever_resources=resources_snapshot,
attribution_parts=attribution_snapshot,
message_payload=message_payload if isinstance(message_payload, dict) else None,
)
if isinstance(result, dict):
if result.get("chat_log_id"):
chat_log_id_persisted = int(result["chat_log_id"])
if result.get("run_id"):
run_id_persisted = int(result["run_id"])
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
return DifyService._build_final_answer_text(
streamed_parts=full_answer,
data=data,
event_name=event_name,
)
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
if attempt == 1:
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
request_id,
response.status_code,
response.reason,
attempt,
)
if not response.ok and current_app:
retryable = response.status_code in (404, 502, 503, 504)
try:
error_body = response.text[:2000]
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
request_id,
response.status_code,
url,
attempt,
error_body,
)
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
for line in response.iter_lines():
if not line:
continue
decoded_line = line.decode('utf-8')
if not decoded_line.startswith('data: '):
continue
raw_json = decoded_line[6:]
try:
data = json.loads(raw_json)
except json.JSONDecodeError:
continue
event = data.get('event')
event_count += 1
perf.on_event(event, data)
# Keep stream event logs behind an explicit switch to prevent
# flooding when global logger level is DEBUG.
if DifyService.VERBOSE_STREAM_LOG and current_app:
current_app.logger.debug(
"[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s",
request_id,
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'node_finished':
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
elif event == 'message':
message_count += 1
if data.get('answer'):
has_sent_answer = True
if first_token_at is None:
first_token_at = time.time()
if current_app:
current_app.logger.info(
"[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s",
request_id,
int((first_token_at - start_time) * 1000),
attempt,
)
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event in ('message_end', 'workflow_finished') or data.get('answer'):
has_sent_answer = True
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
raw_workflow_error = DifyService._extract_workflow_failure_text(data)
if raw_workflow_error:
friendly_error = DifyService._friendly_workflow_failure_message(
raw_workflow_error,
getattr(agent, 'name', None),
)
if current_app:
current_app.logger.warning(
"[chat-stream] workflow failed request_id=%s agent_id=%s raw_error=%s",
request_id,
getattr(agent, 'id', None),
raw_workflow_error,
)
data['message'] = friendly_error
data['error'] = friendly_error
if isinstance(data.get('data'), dict):
data['data']['message'] = friendly_error
data['data']['error'] = friendly_error
if event == 'workflow_finished' and not data.get('answer'):
final_answer = build_final_answer_text(data, event)
if final_answer:
data['answer'] = final_answer
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'):
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
persist_stream_chat(data, event)
if chat_perf_enabled():
perf_summary = perf.log_summary(current_app.logger if current_app else None)
yield f"data: {json.dumps({'event': 'chat_perf', 'perf': perf_summary}, ensure_ascii=False)}\n\n"
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
if event in ('message_end', 'workflow_finished'):
break
break
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
if current_app:
current_app.logger.warning(
"[chat-stream] read timeout after answer request_id=%s attempt=%s; emit synthetic terminal",
request_id,
attempt,
)
# [STEP 3] 已有正文时用合成 message_end 正常收口;persist 会把 chat_log_id 回写到同一事件,
# 领域 Handler 仍能在网络超时后完成状态持久化,而前端不会把本轮误判为永久处理中。
timeout_end_event = {
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
}
persist_stream_chat(timeout_end_event, 'message_end')
yield f"data: {json.dumps(timeout_end_event, ensure_ascii=False)}\n\n"
break
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2)
continue
if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
error_event = {
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'message': message,
'metadata': {},
}
persist_stream_chat(error_event, 'error')
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
@staticmethod
def _log_chat(
user_id,
agent_id,
session_id,
conversation_id,
query,
answer,
tokens,
latency,
retriever_resources=None,
attribution_parts=None,
payload=None,
run_id: int | None = None,
) -> Optional[int]:
"""
把最终问答和元数据写入 ChatLog
Persist one chat record into ChatLog table.
Args:
user_id, agent_id, conversation_id: Chat identity fields.
query: User input.
answer: Aggregated assistant answer.
tokens: Total token usage (best effort).
latency: End-to-end latency in milliseconds.
retriever_resources: Source retrieval metadata list.
attribution_parts: Attribution/annotation list.
run_id: 文件检核批次 ID(按轮问答绑定,可选)。
"""
try:
chat_log = ChatLog(
user_id=user_id,
agent_id=agent_id,
conversation_id=conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=tokens or 0,
latency=latency or 0,
retriever_resources=retriever_resources or [],
attribution_parts=attribution_parts or [],
payload=payload if isinstance(payload, dict) else None,
run_id=run_id if run_id and run_id > 0 else None,
)
db.session.add(chat_log)
db.session.commit()
return chat_log.id
except Exception as e:
if current_app:
current_app.logger.error(f'Failed to log chat: {e}')
db.session.rollback()
return None
return None
@staticmethod
def _extract_token_usage(data: dict) -> int:
"""
从 Dify SSE 事件 payload 提取 token 用量(best effort)。
核心逻辑:Chatbot 在 metadata.usage.total_tokens;Chatflow/Workflow 在 data.total_tokens
或 data.execution_metadata.total_tokens(与 chat_perf.ChatPerfTracker 对齐)。
@param data - 单条 SSE 解析后的 dict
@returns 非负整数 token 数;无法解析时返回 0
"""
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
usage = metadata.get('usage') if isinstance(metadata.get('usage'), dict) else {}
payload = data.get('data') if isinstance(data.get('data'), dict) else {}
candidates = [
usage.get('total_tokens'),
payload.get('total_tokens'),
]
exec_meta = payload.get('execution_metadata')
if isinstance(exec_meta, dict):
candidates.append(exec_meta.get('total_tokens'))
for raw in candidates:
try:
value = int(raw or 0)
if value > 0:
return value
except (TypeError, ValueError):
continue
return 0
@staticmethod
def _update_chat_log_tokens(chat_log_id: int, tokens: int) -> bool:
"""
回写已有 ChatLog 的 tokens_used。
核心逻辑:message_end 先落库时可能尚无 token;workflow_finished 到达后补写更大值。
@param chat_log_id - ChatLog 主键
@param tokens - 从 Dify 事件解析出的 token 数
@returns 是否成功更新
"""
if not chat_log_id or tokens <= 0:
return False
try:
log = db.session.get(ChatLog, chat_log_id)
if not log:
return False
if int(log.tokens_used or 0) >= tokens:
return False
log.tokens_used = tokens
db.session.commit()
return True
except Exception as e:
if current_app:
current_app.logger.error(
'Failed to update chat log tokens chat_log_id=%s: %s',
chat_log_id,
e,
)
db.session.rollback()
return False
@staticmethod
def _persist_stream_chat_record(
*,
data: dict,
event_name: str,
request_id: str | None,
user_id: int,
agent,
session_id: str | None,
hxops_turn_id: str | None,
normalized_conversation_id: str | None,
query: str,
answer_text: str,
latency: int,
retriever_resources: List[Any],
attribution_parts: List[str],
message_payload: dict | None = None,
) -> dict | None:
if not answer_text and not str(query or '').strip():
return None
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
tokens_used = DifyService._extract_token_usage(data)
db_write_started = time.time()
run_id = None
try:
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if is_file_check_runtime_ready(agent):
run_id = resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
run_id = None
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=tokens_used,
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
payload=message_payload,
run_id=run_id,
)
if chat_log_id and current_app:
current_app.logger.info(
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s tokens=%s conversation_id=%s chat_log_id=%s run_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
tokens_used,
data.get('conversation_id') or normalized_conversation_id,
chat_log_id,
run_id,
)
if not chat_log_id:
return None
try:
from app.services.file_check_tools.chat_tool_run_binding import bind_chat_log
bind_chat_log(
chat_log_id=int(chat_log_id),
turn_id=hxops_turn_id,
session_id=session_id,
query=query,
schedule_run_id=run_id,
)
except Exception as exc:
if current_app:
current_app.logger.warning(
'[file-check-bind] bind_chat_log failed chat_log_id=%s session_id=%s turn_id=%s request_id=%s err=%s',
chat_log_id,
session_id or None,
hxops_turn_id or None,
request_id,
exc,
)
return {"chat_log_id": chat_log_id, "run_id": run_id}
@staticmethod
def _normalize_resources(resources):
"""
把资源结构统一为 list
Normalize retriever resource payload into a list.
Dify events may return resources as:
- list
- dict with `data: []`
- empty / None
"""
if not resources:
return []
if isinstance(resources, list):
return resources
if isinstance(resources, dict) and isinstance(resources.get('data'), list):
return resources.get('data')
return []
@staticmethod
def _merge_retriever_resources(target: List[Any], resources):
"""
合并去重检索来源
Merge retriever resources into target list with de-duplication.
De-dup strategy: serialize each item as sorted JSON string.
"""
for item in DifyService._normalize_resources(resources):
item_key = json.dumps(item, ensure_ascii=False, sort_keys=True, default=str)
exists = any(
json.dumps(existing, ensure_ascii=False, sort_keys=True, default=str) == item_key
for existing in target
)
if not exists:
target.append(item)
@staticmethod
def _merge_attribution_parts(target: List[str], value):
"""
合并去重归属片段
Merge attribution values into target list with de-duplication.
Supports string / list / dict / arbitrary values and converts them to
stable text snippets.
"""
if value is None:
return
def push_unique(v):
text = (v or '').strip()
if text and text not in target:
target.append(text)
if isinstance(value, str):
push_unique(value)
return
if isinstance(value, list):
for item in value:
if isinstance(item, str):
push_unique(item)
elif isinstance(item, dict):
push_unique(item.get('content') or item.get('text') or item.get('title') or json.dumps(item, ensure_ascii=False))
else:
push_unique(str(item))
return
if isinstance(value, dict):
push_unique(value.get('content') or value.get('text') or value.get('title') or json.dumps(value, ensure_ascii=False))
return
push_unique(str(value))
@staticmethod
def _collect_metadata(retriever_resources: List[Any], attribution_parts: List[str], event_data: dict):
"""
从 event 和 metadata 中收集来源与归属
Collect metadata from one Dify SSE event and merge into accumulators.
Reads both top-level and nested metadata keys to improve compatibility
with different Dify event payload shapes.
"""
metadata = event_data.get('metadata', {}) or {}
DifyService._merge_retriever_resources(retriever_resources, event_data.get('retriever_resources'))
DifyService._merge_retriever_resources(retriever_resources, metadata.get('retriever_resources'))
DifyService._merge_retriever_resources(retriever_resources, metadata.get('retrieverResources'))
DifyService._merge_attribution_parts(attribution_parts, event_data.get('annotations'))
DifyService._merge_attribution_parts(attribution_parts, event_data.get('annotation_reply'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('annotations'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('annotation_reply'))
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
@staticmethod
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
"""
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
"""
if not isinstance(item, dict):
return None
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
document_name = (
item.get('document_name')
or metadata.get('document_name')
or item.get('title')
or metadata.get('title')
)
resource = {
**item,
'document_name': document_name,
'content': item.get('content') or metadata.get('content') or '',
'metadata': dict(metadata),
}
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
if value not in (None, '') and resource.get(key) in (None, ''):
resource[key] = value
return resource
@staticmethod
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
"""
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
"""
if event_data.get('event') != 'node_finished':
return
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
if node.get('node_type') != 'knowledge-retrieval':
return
if node.get('status') not in (None, 'succeeded'):
return
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
results = outputs.get('result')
if not isinstance(results, list):
return
normalized: List[Any] = []
for item in results:
resource = DifyService._normalize_knowledge_retrieval_result(item)
if resource:
normalized.append(resource)
DifyService._merge_retriever_resources(retriever_resources, normalized)
@staticmethod
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
"""
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
核心逻辑:只复制基础 retriever_resources;源文件下载链接由前端按需调用
/api/chat/source-file 解析,避免阻塞最终答案的流式结束事件。
"""
if not retriever_resources:
return
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
event_data['retriever_resources'] = snapshot
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
metadata['retriever_resources'] = snapshot
event_data['metadata'] = metadata
@staticmethod
def _extract_dify_ids(resource: dict):
"""
从 resource(含嵌套 metadata)提取 dataset_id 和 remote_document_id
Extract dataset_id and remote_document_id from a retriever resource.
Tries multiple key aliases from both top-level and metadata, then
falls back to recursive deep search for robustness.
"""
metadata = resource.get('metadata') if isinstance(resource, dict) else None
metadata = metadata if isinstance(metadata, dict) else {}
dataset_id = (
resource.get('dataset_id')
or resource.get('dify_dataset_id')
or resource.get('knowledge_base_id')
or metadata.get('dataset_id')
or metadata.get('dify_dataset_id')
or metadata.get('knowledge_base_id')
or DifyService._find_first_by_keys(
resource,
['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id'],
)
)
remote_document_id = (
resource.get('remote_document_id')
or resource.get('dify_document_id')
or resource.get('source_document_id')
or resource.get('doc_id')
or metadata.get('remote_document_id')
or metadata.get('dify_document_id')
or metadata.get('source_document_id')
or metadata.get('doc_id')
or DifyService._find_first_by_keys(
resource,
[
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
],
)
or resource.get('document_id')
or metadata.get('document_id')
)
return dataset_id, remote_document_id
@staticmethod
def _find_first_by_keys(payload: Any, key_candidates: List[str]):
"""
递归在任意嵌套结构里按候选 key 找第一个非空值
Recursively find the first non-empty value for any key in key_candidates.
"""
if isinstance(payload, dict):
for k, v in payload.items():
if k in key_candidates and v not in (None, ''):
return v
for v in payload.values():
found = DifyService._find_first_by_keys(v, key_candidates)
if found not in (None, ''):
return found
elif isinstance(payload, list):
for item in payload:
found = DifyService._find_first_by_keys(item, key_candidates)
if found not in (None, ''):
return found
return None
@staticmethod
def _enrich_retriever_resources_with_source_urls(resources: List[Any]):
"""
批量调用集成 API,把 source_download_url 回填到每个 resource
Batch enrich retriever resources with source_download_url and file meta.
Process:
1) Extract (dataset_id, remote_document_id) pairs from resources.
2) Batch query integration mapping service.
3) Write resolved source URL / filename / ext / expiry back to each item.
Notes:
- Resources without required IDs are skipped with warning logs.
- Existing source_download_url is preserved.
"""
candidates = []
index_to_key = {}
for idx, item in enumerate(resources):
if not isinstance(item, dict):
if current_app:
current_app.logger.debug(
"[source-link] resource[%s] skipped: not a dict (type=%s)",
idx,
type(item).__name__,
)
continue
if item.get('source_download_url'):
if current_app:
current_app.logger.info(
"[source-link] resource[%s] already has source_download_url",
idx,
)
continue
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
if current_app:
current_app.logger.info(
"[source-link] resource[%s] extracted ids: dataset_id=%r remote_document_id=%r",
idx,
dataset_id,
remote_document_id,
)
if not dataset_id or not remote_document_id:
if current_app:
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
current_app.logger.warning(
"[source-link] resource[%s] missing ids. top-level keys=%s metadata keys=%s",
idx,
sorted(list(item.keys())),
sorted(list(metadata.keys())),
)
continue
key = (str(dataset_id), str(remote_document_id))
index_to_key[idx] = key
candidates.append({
"dataset_id": key[0],
"remote_document_id": key[1],
})
if not candidates:
return
if current_app:
current_app.logger.info(
"[source-link] batch resolving source urls: candidates=%s",
len(candidates),
)
resolved_map = IntegrationApiService.lookup_files_by_dify(candidates)
for idx, item in enumerate(resources):
if idx not in index_to_key:
continue
dataset_id, remote_document_id = index_to_key[idx]
payload = resolved_map.get((dataset_id, remote_document_id))
if not payload:
if current_app:
current_app.logger.warning(
"[source-link] resource[%s] integration lookup empty for dataset_id=%s remote_document_id=%s",
idx,
dataset_id,
remote_document_id,
)
continue
source_url = payload.get('source_download_url')
if not source_url:
if current_app:
current_app.logger.warning(
"[source-link] resource[%s] integration payload has no source_download_url "
"(dataset_id=%s remote_document_id=%s, payload keys=%s)",
idx,
dataset_id,
remote_document_id,
sorted(list(payload.keys())) if isinstance(payload, dict) else [],
)
continue
item['source_download_url'] = source_url
if payload.get('source_filename'):
item['source_filename'] = payload.get('source_filename')
if payload.get('source_ext'):
item['source_ext'] = payload.get('source_ext')
if payload.get('download_url_expires_at'):
item['source_download_url_expires_at'] = payload.get('download_url_expires_at')
if current_app:
current_app.logger.info(
"[source-link] resource[%s] resolved source_download_url ok "
"(dataset_id=%s remote_document_id=%s)",
idx,
dataset_id,
remote_document_id,
)