Files
syops/backend/app/api/agents.py
T

118 lines
3.8 KiB
Python

"""
backend/app/api/agents.py
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
依赖:app.core.auth.jwt、models、minio_service。
逻辑:按当前用户 RBAC 返回可访问 Agent;未登录 raise UnauthorizedError。
"""
import os
from flask import Blueprint, jsonify, send_from_directory
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.models import Agent, User, AgentGuide
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.minio_service import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(row) -> dict:
return serialize_agent_list_item(row)
@agents_bp.route('', methods=['GET'])
def list_user_agents():
"""
获取当前用户可见的 Agent 列表
用途:Workspace 页面展示应用网格
"""
# 获取当前用户(目前固定为 admin 用户,用于演示)
user: User = get_current_user()
if not user:
raise UnauthorizedError()
# 管理员:返回所有激活的 Agent
if user.role == 'admin':
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
else:
# 普通用户:仅返回多对多关系中已授权的 Agent
agent_rows = [
type('AgentRow', (), {
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
'extra_config': a.extra_config,
})()
for a in user.agents
if a.is_active
]
# [STEP 1] 按 extra_config 分类字段排序后序列化
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
def list_agent_guides(agent_id):
"""
获取指定应用的新手指南列表 (需登录)
用途:客户端 Chat 界面点击新手指南
"""
get_current_user() # 确保已登录
if agent_id == 0:
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
if generic_agent:
agent_id = generic_agent.id
else:
return jsonify([])
guides = (
db.session.query(AgentGuide)
.filter_by(agent_id=agent_id, status=1)
.order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc())
.all()
)
result = []
for g in guides:
result.append({
'id': g.id,
'file_name': g.file_name,
'file_type': g.file_type,
'file_url': minio_service.get_public_url(g.file_path),
'file_size': g.file_size,
'remark': g.remark,
'updated_at': g.updated_at.isoformat()
})
return jsonify(result)
@agents_bp.route('/public', methods=['GET'])
def list_public_agents():
"""
获取公开的 Agent 列表 (无需登录)
用途:登录页面展示
"""
# 返回所有激活的 Agent,包含基本信息
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
def serve_guide_file(filename):
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)