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

1304 lines
53 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).
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 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.config import Config
from app.models import ChatLog, db
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 _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 run_workflow_streaming(
*,
agent,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
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"),
}
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] = {}
workflow_run_id: str | None = None
try:
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", "")
if event_type == "workflow_started":
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
workflow_run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
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}")
except requests.exceptions.RequestException as exc:
if result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured",
)
elif workflow_run_id:
if current_app:
current_app.logger.warning(
"[workflow-streaming] connection dropped, polling result for run_id=%s",
workflow_run_id,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
)
else:
if current_app:
current_app.logger.error(
"[workflow-streaming] request error (no run_id): %s",
exc,
)
raise
return result if isinstance(result, dict) else {}
@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,
):
"""
主流程,调用 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)
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.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if not is_file_check_chat_agent(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:
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))
resources_snapshot = json.loads(json.dumps(retriever_resources, 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=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:
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
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 == '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)
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'):
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; finish stream silently",
request_id,
attempt,
)
persist_stream_chat(
{
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
},
'message_end',
)
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)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\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),
)
DifyService._enrich_retriever_resources_with_source_urls(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.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if is_file_check_chat_agent(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
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 _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,
)