fix: 支持原文件下载,同时将postgres地址由localhost变更为8.152.207.171

This commit is contained in:
sophie committed 2026-04-03 11:30:49 +08:00
1 parent 70f95e9f5c
commit c380248502
12 files changed
+1273 -273

No files matched your search

+50 -1
View File
@@ -8,6 +8,7 @@ backend/app/api/chat.py
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
from sqlalchemy import func, desc
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
from app.decorators import require_agent_permission
from app.models import Agent, ChatLog, Feedback
from app import db
@@ -85,7 +86,12 @@ def get_chat_messages():
messages = []
for log in logs:
messages.append({'role': 'user', 'content': log.query})
messages.append({'role': 'assistant', 'content': log.answer})
messages.append({
'role': 'assistant',
'content': log.answer,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or []
})
return jsonify(messages)
@@ -116,8 +122,17 @@ def chat_completions():
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info(
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s",
getattr(user, 'id', None),
getattr(agent, 'id', None),
len(query or ''),
conversation_id,
)
# 安全兜底:如果装饰器未正确注入,返回错误
if user is None or agent is None:
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
return jsonify({'error': 'Missing user or agent context'}), 500
# 返回 SSE 响应,mimetype 设为 text/event-stream
@@ -128,6 +143,8 @@ def chat_completions():
mimetype='text/event-stream',
headers={
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream; charset=utf-8',
'Connection': 'keep-alive',
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
'X-Accel-Buffering': 'no'
}
@@ -193,3 +210,35 @@ def submit_feedback():
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/source-file', methods=['GET'])
@require_agent_permission
def resolve_source_file():
"""
Resolve original source download URL by Dify dataset/document IDs.
"""
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
current_app.logger.warning(
"[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s",
dataset_id,
bool(remote_document_id),
(remote_document_id[:8] + "...") if remote_document_id else "",
dict(request.args),
)
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if not payload:
return jsonify({'error': 'source file mapping not found'}), 404
return jsonify({
'dataset_id': dataset_id,
'remote_document_id': remote_document_id,
'source_filename': payload.get('source_filename'),
'source_ext': payload.get('source_ext'),
'source_download_url': payload.get('source_download_url'),
'download_url_expires_at': payload.get('download_url_expires_at'),
})
+27 -10
View File
@@ -1,9 +1,17 @@
"""
"""
backend/app/config.py
配置类,区分开发/生产环境
"""
import os
from pathlib import Path
from dotenv import load_dotenv
# Auto-load backend/.env so new shell windows also pick up local settings.
_BACKEND_DIR = Path(__file__).resolve().parents[1]
load_dotenv(_BACKEND_DIR / '.env')
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
@@ -13,7 +21,7 @@ class Config:
'pool_size': 20,
'max_overflow': 10,
'pool_recycle': 3600,
'pool_pre_ping': True
'pool_pre_ping': True,
}
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
@@ -23,10 +31,15 @@ class Config:
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
HR_WORKFLOW_IFRAME_URL = os.getenv(
'HR_WORKFLOW_IFRAME_URL',
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg',
)
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
# External integration API (resolve original source file links by Dify IDs)
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE', 'http://192.168.100.230:8891')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
@@ -35,19 +48,22 @@ class Config:
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
class DevelopmentConfig(Config):
DEBUG = True
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
)
class ProductionConfig(Config):
DEBUG = False
# 服务器 Ubuntu PostgreSQL 配置
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
'postgresql://postgres:123456@8.152.207.171:5432/hxops_prod',
)
class TestingConfig(Config):
TESTING = True
@@ -55,9 +71,10 @@ class TestingConfig(Config):
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
'default': DevelopmentConfig,
}
+3
View File
@@ -194,6 +194,9 @@ class ChatLog(Base):
latency: Mapped[int] = mapped_column(default=0)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
tokens_used: Mapped[int] = mapped_column(default=0)
# Persist citation/source metadata so history messages can still show sources.
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关联 Feedback
+459 -90
View File
@@ -1,125 +1,213 @@
"""
backend/app/services/dify.py
文件用途:Dify API 集成服务
引用文件:requests, json, models, config
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
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 requests
import json
import time
from typing import Any, List
import requests
from flask import current_app
from app.models import ChatLog, db
from app.config import Config
from app.models import ChatLog, db
from app.services.integration_api import IntegrationApiService
class DifyService:
"""
Dify 服务类
用途:封装与 Dify API 的交互逻辑
"""
"""Dify service wrapper."""
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""
生成器函数:向 Dify 发起请求并流式返回
用途:处理 /v1/chat-messages 接口的流式响应
核心逻辑:
1. 构造请求头与 Payload
2. 使用 requests.post(stream=True) 发起请求
3. 逐行读取 SSE 数据
4. 解析 'data: ' 开头的行,透传给前端
5. 在 'message_end' 事件中记录完整日志到数据库
参数:
query: 用户提问内容
user_id: 当前用户 ID
agent: Agent 模型对象,包含 API Key
conversation_id: 会话 ID (可选)
输出:
Yields SSE 格式字符串 "data: {...}\n\n"
主流程,调用 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.
"""
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
# 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
# 移除末尾斜杠以避免双斜杠问题
base_url = base_url.rstrip('/')
url = f"{base_url}/chat-messages"
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
'Content-Type': 'application/json'
'Content-Type': 'application/json',
}
payload = {
"inputs": {},
"query": query,
"response_mode": "streaming",
"conversation_id": conversation_id,
"user": str(user_id)
'inputs': {},
'query': query,
'response_mode': 'streaming',
'conversation_id': conversation_id,
'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 = []
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
try:
# stream=True 关键参数,建立长连接
# 设置连接超时为 5 秒,读取超时为 60 秒
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,
)
response.raise_for_status()
# 逐行迭代响应内容
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
# 识别 SSE 数据行
if decoded_line.startswith('data: '):
json_str = decoded_line[6:]
try:
data = json.loads(json_str)
event = data.get('event')
# 核心:将 Dify 的原始数据透传给前端
yield f"data: {json_str}\n\n"
# 收集完整回答用于日志
if event == 'message':
full_answer.append(data.get('answer', ''))
elif event == 'message_end':
# 对话结束,记录日志
latency = int((time.time() - start_time) * 1000)
metadata = data.get('metadata', {})
usage = metadata.get('usage', {})
# 显式使用应用上下文
with current_app.app_context():
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
)
except json.JSONDecodeError:
continue
else:
# 处理 keep-alive 等其他行
pass
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'):
if 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():
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 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:
# 异常处理:返回标准错误格式给前端
error_msg = json.dumps({"event": "error", "message": str(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):
def _log_chat(
user_id,
agent_id,
conversation_id,
query,
answer,
tokens,
latency,
retriever_resources=None,
attribution_parts=None,
):
"""
内部方法:写入数据库日志
用途:将对话详情持久化到 ChatLog 表
把最终问答和元数据写入 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,
@@ -127,12 +215,293 @@ class DifyService:
query=query,
answer=answer,
tokens_used=tokens or 0,
latency=latency or 0
latency=latency or 0,
retriever_resources=retriever_resources or [],
attribution_parts=attribution_parts or [],
)
db.session.add(chat_log)
db.session.commit()
except Exception as e:
# Re-acquire logger from current_app as it might be detached
if current_app:
current_app.logger.error(f"Failed to log chat: {e}")
current_app.logger.error(f'Failed to log chat: {e}')
db.session.rollback()
@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,
)
+179
View File
@@ -0,0 +1,179 @@
"""
Integration API client for resolving original source-file download links.
"""
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
import requests
from flask import current_app
from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
return (str(dataset_id), str(remote_document_id))
@staticmethod
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
exp = payload.get("download_url_expires_at")
if not exp:
return True
try:
return datetime.fromisoformat(exp) > datetime.now().astimezone()
except Exception:
return True
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
return None
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
cached = IntegrationApiService._cache.get(cache_key)
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
api_key = Config.INTEGRATION_API_KEY
if not base_url or not api_key:
return None
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
params = {
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code != 200:
return None
payload = resp.json()
if not isinstance(payload, dict):
return None
IntegrationApiService._cache[cache_key] = payload
return payload
except Exception as e:
if current_app:
current_app.logger.warning(f"Integration API lookup failed: {e}")
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
"""
Batch resolve source files by (dataset_id, remote_document_id).
Returns a mapping keyed by (dataset_id, remote_document_id).
"""
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
if not items:
return results
unresolved: List[Dict[str, str]] = []
seen = set()
for item in items:
dataset_id = str(item.get("dataset_id") or "").strip()
remote_document_id = str(item.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in seen:
continue
seen.add(key)
cached = IntegrationApiService._cache.get(key)
if cached and IntegrationApiService._is_cache_valid(cached):
results[key] = cached
else:
unresolved.append({
"dataset_id": dataset_id,
"remote_document_id": remote_document_id,
})
if not unresolved:
return results
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
api_key = Config.INTEGRATION_API_KEY
if not base_url or not api_key:
return results
url = f"{base_url}/api/integration/dify-files/resolve"
headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
body = {"items": unresolved}
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if current_app:
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
# Fallback to single lookup for reliability.
for item in unresolved:
payload = IntegrationApiService.lookup_file_by_dify(
item["dataset_id"], item["remote_document_id"]
)
if payload:
key = IntegrationApiService._cache_key(
item["dataset_id"], item["remote_document_id"]
)
results[key] = payload
return results
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, list):
return results
for row in data:
if not isinstance(row, dict):
continue
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
if not row.get("found"):
continue
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
continue
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
IntegrationApiService._cache[key] = normalized
results[key] = normalized
return results
except Exception as e:
if current_app:
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup when batch call errors.
for item in unresolved:
payload = IntegrationApiService.lookup_file_by_dify(
item["dataset_id"], item["remote_document_id"]
)
if payload:
key = IntegrationApiService._cache_key(
item["dataset_id"], item["remote_document_id"]
)
results[key] = payload
return results