feat(chat): 为聊天功能添加上传本地文件和远程URL附件的支持
This commit is contained in:
1 parent
2a036764e3
commit
a1e0fa9404
7 files changed
+1024
-17
No files matched your search
+249
-1
@@ -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():
|
||||
|
||||
Reference in new issue
Block a user