feat(chat): 为聊天功能添加上传本地文件和远程URL附件的支持

This commit is contained in:
hugo committed 2026-06-02 10:15:35 +08:00
1 parent 2a036764e3
commit a1e0fa9404
7 files changed
+1024 -17

No files matched your search

+249 -1
View File
@@ -954,6 +954,7 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
@@ -1007,21 +1008,56 @@ def chat_completions():
else:
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
normalized_files: list[dict] | None = None
if files is not None:
if not isinstance(files, list):
raise ValidationError('files must be a list')
normalized_files = []
for item in files:
if not isinstance(item, dict):
continue
transfer_method = str(item.get('transfer_method') or '').strip()
ftype = str(item.get('type') or '').strip()
if transfer_method not in ('local_file', 'remote_url'):
continue
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
continue
if transfer_method == 'local_file':
upload_file_id = str(item.get('upload_file_id') or '').strip()
if not upload_file_id:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
else:
url = str(item.get('url') or '').strip()
if not url:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
if not normalized_files:
normalized_files = None
if normalized_files and PLMOracleService.supports(query, agent_proxy):
raise ValidationError('This route does not support attachments')
if PLMOracleService.supports(query, agent_proxy):
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif kb_type == 'ERP知识库':
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.text2sql import Text2SQLService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id)
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
def relay_stream():
created_event = {
@@ -1098,6 +1134,218 @@ def chat_completions():
)
@chat_bp.route('/files/upload', methods=['POST'])
@require_agent_permission
def upload_chat_file():
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
if str(getattr(agent, 'type', '') or '').strip().lower() != 'api':
raise ValidationError('This agent does not support file upload')
if not getattr(agent, 'dify_api_key', None):
raise ValidationError('This agent does not support file upload')
upload = request.files.get('file')
if not upload:
raise ValidationError('file is required')
from app.services.dify import DifyService
from app.config import Config
params = DifyService.get_app_parameters(agent, force_refresh=True)
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {}
filename = str(getattr(upload, 'filename', '') or '').strip()
mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip()
detected_type, ext = DifyService.detect_file_type(filename, mimetype)
file_type = None
normalized_allowed_types = None
normalized_allowed_methods = None
normalized_allowed_exts = None
is_new_schema = False
if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list):
is_new_schema = True
normalized_allowed_types = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_types') or [])
if str(v or '').strip()
)
)
normalized_allowed_methods = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_upload_methods') or [])
if str(v or '').strip()
)
)
exts = []
for v in (file_upload_cfg.get('allowed_file_extensions') or []):
s = str(v or '').strip()
if not s:
continue
if s.startswith('.'):
s = s[1:]
s = s.lower().strip()
if s:
exts.append(s)
normalized_allowed_exts = set(exts) if exts else None
if detected_type:
file_type = detected_type
else:
if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None
if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})')
def _effective_type_methods(target_type: str) -> set[str]:
if not isinstance(file_upload_cfg, dict):
return set(normalized_allowed_methods or set())
cfg = file_upload_cfg.get(target_type)
transfer_methods = []
if isinstance(cfg, dict):
transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if isinstance(transfer_methods, list) and len(transfer_methods) > 0:
return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip())
return set(normalized_allowed_methods or set())
def _is_type_enabled_in_new_schema(target_type: str) -> bool:
if not (is_new_schema and normalized_allowed_types):
return False
if not isinstance(file_upload_cfg, dict):
return target_type in normalized_allowed_types
cfg = file_upload_cfg.get(target_type)
if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool):
if cfg.get('enabled') is False:
return False
if cfg.get('enabled') is True:
return True
return target_type in normalized_allowed_types
if is_new_schema and normalized_allowed_types:
if not _is_type_enabled_in_new_schema(file_type):
raise ValidationError(f'File type not enabled: {file_type}')
type_methods = _effective_type_methods(file_type)
if 'local_file' not in type_methods:
raise ValidationError('local_file upload is not enabled')
if normalized_allowed_exts:
allowed_for_type = set()
for e in normalized_allowed_exts:
t, _ = DifyService.detect_file_type(f'file.{e}', None)
if t is None:
if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)):
allowed_for_type.add(e)
continue
if t == file_type:
allowed_for_type.add(e)
if allowed_for_type and (not ext or ext not in allowed_for_type):
raise ValidationError(f'Unsupported file extension: .{ext or ""}')
else:
# legacy schema checks
type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None
if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'):
raise ValidationError(f'File type not enabled: {file_type}')
transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)):
raise ValidationError('local_file upload is not enabled')
def _mb_limit_for_type() -> float | None:
merged = {}
if isinstance(system_params, dict):
merged.update(system_params)
if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict):
merged.update(file_upload_cfg.get('fileUploadConfig') or {})
if file_type == 'image':
return merged.get('image_file_size_limit') or merged.get('file_size_limit')
if file_type == 'audio':
return merged.get('audio_file_size_limit') or merged.get('file_size_limit')
if file_type == 'video':
return merged.get('video_file_size_limit') or merged.get('file_size_limit')
return merged.get('file_size_limit')
size_limit_mb = _mb_limit_for_type()
if size_limit_mb is not None:
try:
import os
stream = getattr(upload, 'stream', None)
if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'):
cur = stream.tell()
stream.seek(0, os.SEEK_END)
size_bytes = stream.tell()
stream.seek(cur)
limit_bytes = int(float(size_limit_mb) * 1024 * 1024)
if size_bytes > limit_bytes:
raise ValidationError(f'File too large (limit {size_limit_mb}MB)')
except ValidationError:
raise
except Exception:
pass
base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE
dify_url = DifyService._build_files_upload_url(base_url)
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
try:
try:
upload.stream.seek(0)
except Exception:
pass
resp = requests.post(
dify_url,
headers=headers,
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
data={'user': str(getattr(user, 'id', 'system'))},
timeout=(5, 60),
)
except requests.RequestException as exc:
raise ServiceUnavailableError(f'Upload failed: {exc}')
if not resp.ok:
body = (resp.text or '')[:1500]
header_snapshot = {}
try:
for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'):
v = resp.headers.get(k) or resp.headers.get(k.title())
if v:
header_snapshot[k] = v
except Exception:
header_snapshot = {}
current_app.logger.warning(
'[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s',
resp.status_code,
dify_url,
header_snapshot,
body,
)
raise AppError(
code='DIFY.UPLOAD_FAILED',
message='Upload failed',
http_status=502,
details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot},
)
data = resp.json() if resp.content else {}
return jsonify({
'id': data.get('id'),
'name': data.get('name') or filename,
'size': data.get('size'),
'extension': data.get('extension') or ext,
'mime_type': data.get('mime_type') or mimetype,
'type': file_type,
})
@chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission
def submit_feedback():
+28 -2
View File
@@ -1442,7 +1442,33 @@ def get_agent_details(id):
has_permission = agent in user.agents
if not has_permission:
raise ForbiddenError('Access denied')
return jsonify({'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.extra_config.get('icon_url') if agent.extra_config else None, 'welcome_message': agent.extra_config.get('welcome_message') if agent.extra_config else None, 'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []})
extra_config = agent.extra_config or {}
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
dify_parameters = None
agent_type = str(getattr(agent, 'type', '') or '').strip().lower()
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService
params = DifyService.get_app_parameters(agent)
if isinstance(params, dict):
dify_parameters = {
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
}
return jsonify({
'id': agent.id,
'name': agent.name,
'description': agent.description,
'type': agent.type,
'icon_url': agent.icon_url,
'extra_config': extra_config if isinstance(extra_config, dict) else {},
'dify_app_type': dify_app_type,
'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None,
'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [],
'dify_parameters': dify_parameters,
})
@user_bp.route('/db', methods=['GET'])
def get_db():
@@ -1491,4 +1517,4 @@ def delete_announcement(id):
if ann:
db.session.delete(ann)
db.session.commit()
return jsonify({'message': 'Deleted'})
return jsonify({'message': 'Deleted'})
+203 -1
View File
@@ -26,6 +26,8 @@ import json
import os
import time
import uuid
from datetime import datetime, timedelta
from threading import Lock
from typing import Any, List, Optional
import requests
@@ -39,6 +41,119 @@ 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:
@@ -114,6 +229,83 @@ class DifyService:
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(
*,
@@ -292,7 +484,15 @@ class DifyService:
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):
def stream_chat(
query: str,
user_id: int,
agent,
conversation_id: str = None,
request_id: str | None = None,
session_id: str | None = None,
files: list[dict[str, Any]] | None = None,
):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller.
@@ -328,6 +528,8 @@ class DifyService:
'conversation_id': normalized_conversation_id,
'user': str(user_id),
}
if files:
payload['files'] = files
if current_app:
current_app.logger.info(