2026-03-07 09:01:00 +08:00
|
|
|
|
"""
|
|
|
|
|
|
知你客服 Agent 代理 API(方式一:App 后端代理)
|
|
|
|
|
|
"""
|
|
|
|
|
|
from flask import Blueprint, request, jsonify
|
|
|
|
|
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
|
|
|
|
|
from app.services.agent_proxy import chat_with_agent
|
|
|
|
|
|
from flask import current_app
|
|
|
|
|
|
|
|
|
|
|
|
agent_bp = Blueprint("agent", __name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@agent_bp.route("/chat", methods=["POST"])
|
|
|
|
|
|
@jwt_required()
|
|
|
|
|
|
def agent_chat():
|
|
|
|
|
|
"""
|
|
|
|
|
|
请求体: { "message": "用户输入", "user_id": "可选,App 侧用户唯一 ID,用于多轮记忆" }
|
|
|
|
|
|
响应: { "reply": "知你客服回复文本" }
|
|
|
|
|
|
"""
|
|
|
|
|
|
data = request.get_json() or {}
|
|
|
|
|
|
message = (data.get("message") or data.get("query") or "").strip()
|
|
|
|
|
|
if not message:
|
|
|
|
|
|
return jsonify({"error": "message 不能为空"}), 400
|
|
|
|
|
|
user_id = data.get("user_id") or get_jwt_identity()
|
|
|
|
|
|
base_url = current_app.config.get("PLATFORM_BASE_URL", "")
|
|
|
|
|
|
username = current_app.config.get("PLATFORM_USERNAME", "")
|
|
|
|
|
|
password = current_app.config.get("PLATFORM_PASSWORD", "")
|
|
|
|
|
|
agent_id = current_app.config.get("PLATFORM_AGENT_ID", "")
|
|
|
|
|
|
if not all([base_url, username, password, agent_id]):
|
|
|
|
|
|
return jsonify({"error": "未配置知你客服代理(PLATFORM_BASE_URL/USERNAME/PASSWORD/AGENT_ID)"}), 503
|
|
|
|
|
|
try:
|
|
|
|
|
|
reply = chat_with_agent(base_url, username, password, agent_id, message, user_id)
|
|
|
|
|
|
return jsonify({"reply": reply or ""})
|
2026-03-07 13:59:49 +08:00
|
|
|
|
except ValueError as e:
|
|
|
|
|
|
err = str(e)
|
|
|
|
|
|
if "401" in err or "登录失败" in err:
|
|
|
|
|
|
return jsonify({"error": err}), 503
|
|
|
|
|
|
return jsonify({"error": err}), 502
|
2026-03-07 09:01:00 +08:00
|
|
|
|
except Exception as e:
|
2026-03-07 13:59:49 +08:00
|
|
|
|
err = str(e)
|
|
|
|
|
|
# 任何包含 401/Unauthorized 的异常都视为平台认证失败,返回友好提示
|
|
|
|
|
|
if "401" in err or "Unauthorized" in err:
|
|
|
|
|
|
return jsonify({
|
|
|
|
|
|
"error": "知你客服平台登录失败(401),请确认 8037 服务已启动且 PLATFORM_USERNAME/PLATFORM_PASSWORD 正确"
|
|
|
|
|
|
}), 503
|
|
|
|
|
|
return jsonify({"error": err}), 502
|