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