""" 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 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.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") @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 _convert(v): if v is None: return "" if isinstance(v, dict): return {kk: _convert(vv) for kk, vv in v.items()} if isinstance(v, list): 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 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): """ 主流程,调用 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': {}, 'query': query, 'response_mode': 'streaming', 'conversation_id': normalized_conversation_id, 'user': str(user_id), } 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() first_token_at: float | None = None message_count = 0 event_count = 0 full_answer: List[str] = [] retriever_resources: List[Any] = [] attribution_parts: List[str] = [] max_retries = 3 for attempt in range(1, max_retries + 1): try: with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) 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 = "" 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() 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 # 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 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 == 'message_end' and data.get('answer'): full_answer.append(data.get('answer', '')) DifyService._collect_metadata(retriever_resources, attribution_parts, data) if event == 'message_end': message_end_started = time.time() if current_app: current_app.logger.info( "[source-link] message_end request_id=%s collected retriever_resources=%s", request_id, len(retriever_resources), ) DifyService._enrich_retriever_resources_with_source_urls(retriever_resources) enrich_done_at = time.time() metadata = data.get('metadata') or {} metadata['retriever_resources'] = retriever_resources data['metadata'] = metadata data['retriever_resources'] = retriever_resources latency = int((time.time() - start_time) * 1000) usage = metadata.get('usage', {}) or {} db_write_started = time.time() with current_app.app_context(): chat_log_id = DifyService._log_chat( user_id=user_id, agent_id=agent.id, conversation_id=data.get('conversation_id') or normalized_conversation_id, query=query, answer=''.join(full_answer), tokens=usage.get('total_tokens', 0), latency=latency, retriever_resources=retriever_resources, attribution_parts=attribution_parts, ) db_write_done_at = time.time() if chat_log_id: data['chat_log_id'] = chat_log_id if current_app: current_app.logger.info( "[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s", request_id, latency, int((first_token_at - start_time) * 1000) if first_token_at else None, int((message_end_started - first_token_at) * 1000) if first_token_at else None, int((time.time() - message_end_started) * 1000), int((enrich_done_at - message_end_started) * 1000), int((db_write_done_at - db_write_started) * 1000), event_count, message_count, len(''.join(full_answer)), len(retriever_resources), len(attribution_parts), data.get('conversation_id') or normalized_conversation_id, ) yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" 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) if attempt < max_retries: time.sleep(attempt * 2) continue error_msg = json.dumps({'event': 'error', 'message': str(e)}) yield f"data: {error_msg}\n\n" @staticmethod def _log_chat( user_id, agent_id, conversation_id, query, answer, tokens, latency, retriever_resources=None, attribution_parts=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. """ try: chat_log = ChatLog( user_id=user_id, agent_id=agent_id, conversation_id=conversation_id, query=query, answer=answer, tokens_used=tokens or 0, latency=latency or 0, retriever_resources=retriever_resources or [], attribution_parts=attribution_parts or [], ) 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 _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('document_id') or resource.get('doc_id') or metadata.get('remote_document_id') or metadata.get('dify_document_id') or metadata.get('document_id') or metadata.get('doc_id') or DifyService._find_first_by_keys( resource, [ 'remote_document_id', 'dify_document_id', 'document_id', 'doc_id', 'source_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, )