diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 340b98e4..87b0933d 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -19,6 +19,7 @@ import re import requests import uuid from app.services.wecom_notify import send_wecom_event_message +from app.services.dify import DifyService from app.auth_jwt import get_current_user as _get_auth_user admin_bp = Blueprint('admin', __name__) @@ -445,7 +446,7 @@ def test_agent(id): 'tested_at': tested_at }), 400 - request_url = f'{base_url}/chat-messages' + request_url = DifyService.build_chat_messages_url(base_url) payload = { 'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 804cb051..4b4d0464 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -37,6 +37,24 @@ 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): """ @@ -60,8 +78,7 @@ class DifyService: """ # 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}/v1/chat-messages" + url = DifyService.build_chat_messages_url(base_url) headers = { 'Authorization': f'Bearer {agent.dify_api_key}',