545 lines
22 KiB
Python
545 lines
22 KiB
Python
"""
|
|
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 time
|
|
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."""
|
|
|
|
@staticmethod
|
|
def build_chat_messages_url(raw_base_url: str) -> str:
|
|
"""
|
|
统一构建 Dify chat-messages URL,兼容以下输入:
|
|
- http(s)://host
|
|
- http(s)://host/v1
|
|
- http(s)://host/chat-messages
|
|
- http(s)://host/v1/chat-messages
|
|
"""
|
|
base_url = (raw_base_url or '').strip().rstrip('/')
|
|
if not base_url:
|
|
return ''
|
|
if base_url.endswith('/v1/chat-messages') or base_url.endswith('/chat-messages'):
|
|
return base_url
|
|
if base_url.endswith('/v1'):
|
|
return f'{base_url}/chat-messages'
|
|
return f'{base_url}/v1/chat-messages'
|
|
|
|
@staticmethod
|
|
def stream_chat(query: str, user_id: int, agent, conversation_id: str = 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)
|
|
|
|
headers = {
|
|
'Authorization': f'Bearer {agent.dify_api_key}',
|
|
'Content-Type': 'application/json',
|
|
}
|
|
payload = {
|
|
'inputs': {},
|
|
'query': query,
|
|
'response_mode': 'streaming',
|
|
'conversation_id': conversation_id or '',
|
|
'user': str(user_id),
|
|
}
|
|
|
|
if current_app:
|
|
current_app.logger.info(
|
|
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
|
|
user_id,
|
|
getattr(agent, 'id', None),
|
|
base_url,
|
|
len(query or ''),
|
|
conversation_id,
|
|
)
|
|
|
|
start_time = time.time()
|
|
full_answer: List[str] = []
|
|
retriever_resources: List[Any] = []
|
|
attribution_parts: List[str] = []
|
|
|
|
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 status=%s reason=%s",
|
|
response.status_code,
|
|
response.reason,
|
|
)
|
|
if not response.ok and current_app:
|
|
try:
|
|
error_body = response.text[:2000]
|
|
except Exception:
|
|
error_body = "<failed to read response body>"
|
|
current_app.logger.error(
|
|
"[chat-stream] dify bad response status=%s url=%s payload=%s body=%s",
|
|
response.status_code,
|
|
url,
|
|
json.dumps(payload, ensure_ascii=False),
|
|
error_body,
|
|
)
|
|
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')
|
|
if current_app:
|
|
current_app.logger.info(
|
|
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
|
|
event,
|
|
len(data.get('answer', '') or ''),
|
|
bool(data.get('metadata')),
|
|
data.get('conversation_id') or conversation_id,
|
|
)
|
|
|
|
if event == 'message':
|
|
full_answer.append(data.get('answer', ''))
|
|
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
|
|
|
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
|
# Keep metadata from non-message events, but avoid appending
|
|
# intermediate workflow/agent outputs into final user answer.
|
|
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':
|
|
if current_app:
|
|
current_app.logger.info(
|
|
"[source-link] message_end: collected retriever resources=%s",
|
|
len(retriever_resources),
|
|
)
|
|
# Resolve original source file URLs from external integration API.
|
|
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
|
|
|
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 {}
|
|
|
|
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 conversation_id,
|
|
query=query,
|
|
answer=''.join(full_answer),
|
|
tokens=usage.get('total_tokens', 0),
|
|
latency=latency,
|
|
retriever_resources=retriever_resources,
|
|
attribution_parts=attribution_parts,
|
|
)
|
|
if chat_log_id:
|
|
data['chat_log_id'] = chat_log_id
|
|
if current_app:
|
|
current_app.logger.info(
|
|
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
|
data.get('conversation_id') or conversation_id,
|
|
len(''.join(full_answer)),
|
|
len(retriever_resources),
|
|
len(attribution_parts),
|
|
latency,
|
|
)
|
|
|
|
# Pass-through SSE event (after optional enrichment).
|
|
# SSE frame delimiter must be real newlines, not literal "\n".
|
|
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
if current_app:
|
|
current_app.logger.exception("[chat-stream] request exception: %s", e)
|
|
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,
|
|
)
|