fix(chat): 智能体支持配置分级显示

This commit is contained in:
sophie committed 2026-06-25 17:37:48 +08:00
1 parent a451951e7a
commit 70d7435b5f
27 files changed
+645 -76

No files matched your search

+5 -10
View File
@@ -12,6 +12,7 @@ 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
@@ -19,13 +20,7 @@ agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(row) -> dict:
return {
'id': row.id,
'name': row.name,
'description': row.description,
'icon_url': row.icon_url,
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
}
return serialize_agent_list_item(row)
@agents_bp.route('', methods=['GET'])
@@ -61,8 +56,8 @@ def list_user_agents():
if a.is_active
]
# 序列化为前端所需字段
return jsonify([_serialize_agent_row(row) for row in agent_rows])
# [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):
@@ -112,7 +107,7 @@ def list_public_agents():
.order_by(Agent.id.asc())
.all()
)
return jsonify([_serialize_agent_row(row) for row in agent_rows])
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
+13 -8
View File
@@ -9,6 +9,7 @@ from flask import Blueprint, request, jsonify, current_app
from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
@@ -1649,7 +1650,8 @@ def home():
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)).all()
else:
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents if agent.is_active]
agent_rows = sort_agent_rows(agent_rows)
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter(
@@ -1666,7 +1668,7 @@ def home():
agent = db.session.get(Agent, rel.agent_id)
if agent:
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [{'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], 'dify_app_type': ((a.extra_config or {}).get('dify_app_type') if hasattr(a, 'extra_config') else (a.get('extra_config') or {}).get('dify_app_type')) or 'chatflow'} for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
try:
return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc:
@@ -2137,12 +2139,15 @@ def get_agent_details(id):
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService
params = DifyService.get_app_parameters(agent)
if isinstance(params, dict):
dify_parameters = {
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
}
try:
params = DifyService.get_app_parameters(agent)
if isinstance(params, dict):
dify_parameters = {
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
}
except Exception as exc:
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
return jsonify({
'id': agent.id,
+105
View File
@@ -0,0 +1,105 @@
"""
services/agent_category.py
用途:从 Agent.extra_config 解析 P1 分类字段(category / sub_category / sort_order),并提供排序与序列化。
依赖:无外部服务;由 api/agents、api/user 在返回列表时调用。
逻辑:分类信息暂存 extra_config,P2 可迁移至独立 agent_categories 表。
"""
from __future__ import annotations
from typing import Any
def parse_agent_category_meta(extra_config: dict | None) -> dict[str, Any]:
"""
从 extra_config 解析 Agent 分类元数据。
核心逻辑:category / sub_category 去首尾空白;sort_order 非法值回退为 0。
Args:
extra_config: Agent.extra_config JSON 字典,可为 None。
Returns:
含 category (str)、sub_category (str)、sort_order (int) 的字典。
"""
extra = extra_config if isinstance(extra_config, dict) else {}
category = str(extra.get('category') or '').strip()
sub_category = str(extra.get('sub_category') or '').strip()
sort_raw = extra.get('sort_order')
try:
sort_order = int(sort_raw) if sort_raw is not None and sort_raw != '' else 0
except (TypeError, ValueError):
sort_order = 0
return {
'category': category,
'sub_category': sub_category,
'sort_order': sort_order,
}
def _row_extra_config(row: Any) -> dict | None:
"""从 ORM 行或 dict 行读取 extra_config。"""
if hasattr(row, 'extra_config'):
return row.extra_config
if isinstance(row, dict):
return row.get('extra_config')
return None
def _row_id(row: Any) -> int:
"""从 ORM 行或 dict 行读取主键 id。"""
if hasattr(row, 'id'):
return int(row.id)
if isinstance(row, dict):
return int(row.get('id') or 0)
return 0
def agent_category_sort_key(row: Any) -> tuple:
"""
生成分类排序键:sort_order → category → sub_category → id。
核心逻辑:未配置 category 的 Agent 排在同 sort_order 下的末尾(用 \\uffff 占位)。
"""
meta = parse_agent_category_meta(_row_extra_config(row))
category_key = meta['category'] or '\uffff'
sub_key = meta['sub_category'] or '\uffff'
return (meta['sort_order'], category_key, sub_key, _row_id(row))
def sort_agent_rows(rows: list) -> list:
"""
按分类元数据对 Agent 行列表原地排序并返回。
"""
return sorted(rows, key=agent_category_sort_key)
def serialize_agent_category_fields(row: Any) -> dict[str, Any]:
"""
序列化分类相关 API 字段。
空字符串 category / sub_category 输出为 None,便于前端区分「未配置」。
"""
meta = parse_agent_category_meta(_row_extra_config(row))
return {
'category': meta['category'] or None,
'sub_category': meta['sub_category'] or None,
'sort_order': meta['sort_order'],
}
def serialize_agent_list_item(row: Any) -> dict[str, Any]:
"""
序列化用户可见 Agent 列表项(聊天侧栏、工作台首页共用)。
核心逻辑:合并基础字段、dify_app_type 与分类元数据。
"""
extra = _row_extra_config(row) or {}
name = row.name if hasattr(row, 'name') else row.get('name')
description = row.description if hasattr(row, 'description') else row.get('description')
icon_url = row.icon_url if hasattr(row, 'icon_url') else row.get('icon_url')
return {
'id': _row_id(row),
'name': name,
'description': description,
'icon_url': icon_url,
'dify_app_type': extra.get('dify_app_type') or 'chatflow',
**serialize_agent_category_fields(row),
}