feat: Initial commit with full deployment architecture and scripts
This commit is contained in:
commit
abb3efe114
96 files changed
+16789
No files matched your search
@@ -0,0 +1,427 @@
|
||||
"""
|
||||
backend/app/api/admin.py
|
||||
文件用途:管理员相关 API 路由
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from datetime import datetime
|
||||
import csv
|
||||
import io
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
# --- Departments ---
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||||
return jsonify([
|
||||
{
|
||||
'id': d.id,
|
||||
'name': d.name,
|
||||
'code': d.code,
|
||||
'company': d.company,
|
||||
'description': d.description
|
||||
} for d in depts
|
||||
])
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
data = request.get_json() or {}
|
||||
if not data.get('name'): return jsonify({'error': 'Name is required'}), 400
|
||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||
return jsonify({'error': 'Name exists'}), 400
|
||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||
return jsonify({'error': 'Code exists'}), 400
|
||||
|
||||
dept = Department(name=data['name'], code=data.get('code'), company=data.get('company'), description=data.get('description'))
|
||||
db.session.add(dept)
|
||||
db.session.commit()
|
||||
return jsonify({'id': dept.id, 'name': dept.name}), 201
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id):
|
||||
dept = db.session.get(Department, id)
|
||||
if not dept: return jsonify({'error': 'Not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
|
||||
if 'name' in data:
|
||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != id).first():
|
||||
return jsonify({'error': 'Name exists'}), 400
|
||||
dept.name = data['name']
|
||||
if 'code' in data:
|
||||
if data['code'] and db.session.query(Department).filter(Department.code == data['code'], Department.id != id).first():
|
||||
return jsonify({'error': 'Code exists'}), 400
|
||||
dept.code = data['code']
|
||||
if 'company' in data: dept.company = data['company']
|
||||
if 'description' in data: dept.description = data['description']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_department(id):
|
||||
dept = db.session.get(Department, id)
|
||||
if dept:
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# --- Agents ---
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
|
||||
return jsonify([{
|
||||
'id': a.id, 'name': a.name, 'dify_app_id': a.dify_app_id,
|
||||
'dify_api_key': a.dify_api_key, 'is_active': a.is_active,
|
||||
'description': a.description, 'type': a.type,
|
||||
'api_base_url': a.api_base_url, 'extra_config': a.extra_config
|
||||
} for a in agents])
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@require_admin
|
||||
def create_agent():
|
||||
data = request.get_json() or {}
|
||||
|
||||
if not data.get('name'): return jsonify({'error': 'Name is required'}), 400
|
||||
|
||||
agent_type = data.get('type', 'api')
|
||||
# 对于 API 类型,必须校验 dify_app_id
|
||||
if agent_type == 'api' and not data.get('dify_app_id'):
|
||||
return jsonify({'error': 'App ID is required for API agents'}), 400
|
||||
|
||||
agent = Agent(
|
||||
name=data['name'],
|
||||
dify_app_id=data.get('dify_app_id') or None, # nullable, convert empty string to None
|
||||
dify_api_key=data.get('dify_api_key') or None, # nullable
|
||||
description=data.get('description'),
|
||||
type=agent_type,
|
||||
api_base_url=data.get('api_base_url'),
|
||||
extra_config=data.get('extra_config'),
|
||||
is_active=data.get('is_active', True)
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
return jsonify({'id': agent.id}), 201
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_agent(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent: return jsonify({'error': 'Not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
|
||||
for k in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']:
|
||||
if k in data: setattr(agent, k, data[k])
|
||||
|
||||
if 'dify_api_key' in data and data['dify_api_key']:
|
||||
agent.dify_api_key = data['dify_api_key']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_agent(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# --- Users ---
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
users = db.session.query(User).order_by(User.id.asc()).all()
|
||||
res = []
|
||||
for u in users:
|
||||
res.append({
|
||||
'id': u.id, 'username': u.username, 'email': u.email,
|
||||
'department': u.department, 'role': u.role, 'status': u.status,
|
||||
'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number,
|
||||
'agent_ids': [a.id for a in u.agents]
|
||||
})
|
||||
return jsonify(res)
|
||||
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
data = request.get_json() or {}
|
||||
if not data.get('username'): return jsonify({'error': 'Username is required'}), 400
|
||||
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
return jsonify({'error': 'Username exists'}), 400
|
||||
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=data.get('email'),
|
||||
department=data.get('department'),
|
||||
role=data.get('role', 'user'),
|
||||
status=data.get('status', 'active'),
|
||||
real_name=data.get('real_name'),
|
||||
employee_id=data.get('employee_id'),
|
||||
phone_number=data.get('phone_number')
|
||||
)
|
||||
if data.get('password'): user.set_password(data['password'])
|
||||
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return jsonify({'id': user.id}), 201
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id):
|
||||
user = db.session.get(User, id)
|
||||
if not user: return jsonify({'error': 'Not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data: setattr(user, k, data[k])
|
||||
|
||||
if data.get('password'): user.set_password(data['password'])
|
||||
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
cnt = db.session.query(User).filter_by(status='rejected').delete()
|
||||
db.session.commit()
|
||||
return jsonify({'deleted_count': cnt})
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
data = request.get_json() or {}
|
||||
ids = data.get('user_ids', [])
|
||||
current_user_id = request.headers.get('X-User-Id')
|
||||
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
|
||||
if not target_ids: return jsonify({'error': 'No valid users'}), 400
|
||||
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
return jsonify({'deleted_count': cnt})
|
||||
|
||||
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_user_permissions(id):
|
||||
user = db.session.get(User, id)
|
||||
if not user: return jsonify({'error': 'Not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
user.agents = agents
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id):
|
||||
user = db.session.get(User, id)
|
||||
if user:
|
||||
user.status = 'active'
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id):
|
||||
user = db.session.get(User, id)
|
||||
if user:
|
||||
user.status = 'rejected'
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# --- Permission Requests ---
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
reqs = db.session.query(PermissionRequest).order_by(PermissionRequest.created_at.desc()).all()
|
||||
return jsonify([{
|
||||
'id': r.id, 'user_id': r.user_id, 'agent_id': r.agent_id,
|
||||
'reason': r.reason, 'status': r.status, 'created_at': r.created_at.isoformat()
|
||||
} for r in reqs])
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id):
|
||||
req = db.session.get(PermissionRequest, id)
|
||||
if not req: return jsonify({'error': 'Not found'}), 404
|
||||
req.status = 'approved'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
|
||||
# Grant permission
|
||||
user = db.session.get(User, req.user_id)
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and agent and agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id):
|
||||
req = db.session.get(PermissionRequest, id)
|
||||
if not req: return jsonify({'error': 'Not found'}), 404
|
||||
req.status = 'rejected'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# --- Quick Questions (Common Questions) ---
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
# Only return global questions (user_id is NULL)
|
||||
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append({
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent.name if agent else 'Unknown',
|
||||
'sort_order': q.sort_order
|
||||
})
|
||||
return jsonify(res)
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or not data.get('agent_id'):
|
||||
return jsonify({'error': 'Missing required fields'}), 400
|
||||
|
||||
qq = QuickQuestion(
|
||||
user_id=None, # Global
|
||||
agent_id=data['agent_id'],
|
||||
title=data['title'],
|
||||
question=data['question'],
|
||||
sort_order=data.get('sort_order', 0)
|
||||
)
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'id': qq.id}), 201
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id):
|
||||
qq = db.session.get(QuickQuestion, id)
|
||||
if not qq: return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data: qq.title = data['title']
|
||||
if 'question' in data: qq.question = data['question']
|
||||
if 'agent_id' in data: qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data: qq.sort_order = data['sort_order']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_quick_question(id):
|
||||
qq = db.session.get(QuickQuestion, id)
|
||||
if qq:
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# --- Reports ---
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
total = db.session.query(ChatLog).count()
|
||||
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
|
||||
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
|
||||
|
||||
return jsonify({
|
||||
'total': total,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
total = db.session.query(Feedback).count()
|
||||
avg = db.session.query(func.avg(Feedback.score)).scalar() or 0
|
||||
dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all()
|
||||
|
||||
return jsonify({
|
||||
'total': total,
|
||||
'avg_score': float(avg),
|
||||
'distribution': [{'score': s, 'count': c} for s, c in dist]
|
||||
})
|
||||
|
||||
|
||||
# --- Database ---
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table):
|
||||
model_map = {
|
||||
'users': User,
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
'user_favorite_agents': UserFavoriteAgent,
|
||||
'user_default_agents': UserDefaultAgent
|
||||
}
|
||||
|
||||
model = model_map.get(table)
|
||||
if not model:
|
||||
return jsonify({'error': 'Invalid table'}), 400
|
||||
|
||||
# Build query
|
||||
query = db.session.query(model)
|
||||
|
||||
# Handle filters
|
||||
for k, v in request.args.items():
|
||||
if hasattr(model, k):
|
||||
col = getattr(model, k)
|
||||
query = query.filter(col.cast(db.String).ilike(f"%{v}%"))
|
||||
|
||||
# Use db.session.query instead of model.query to avoid ChatLog.query conflict
|
||||
items = query.limit(100).all()
|
||||
|
||||
res = []
|
||||
for item in items:
|
||||
d = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
d[col.name] = val
|
||||
res.append(d)
|
||||
|
||||
return jsonify(res)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
文件用途:普通用户可见的 Agent 列表接口
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g
|
||||
from app.models import Agent, User
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = _get_current_user()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agents = [a for a in user.agents if a.is_active]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
data = [
|
||||
{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
}
|
||||
for a in agents
|
||||
]
|
||||
return jsonify(data)
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
|
||||
"""
|
||||
backend/app/api/chat.py
|
||||
文件用途:定义聊天相关 API 路由
|
||||
引用文件:flask, services.dify, decorators, models
|
||||
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
||||
"""
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
|
||||
from sqlalchemy import func, desc
|
||||
from app.services.dify import DifyService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, Feedback
|
||||
from app import db
|
||||
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
"""
|
||||
获取当前用户与当前 Agent 的历史会话列表
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
# 聚合查询:按 conversation_id 分组,获取最新时间
|
||||
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
|
||||
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
|
||||
# 更严谨的做法是先查出 conversation_ids,再查详情。
|
||||
# 这里为了简单,我们假设 query 不为空
|
||||
|
||||
# 修正逻辑:先查出最近的 20 个 conversation_id
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
# 联表查询获取详细信息,按时间倒序
|
||||
results = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
ChatLog.query
|
||||
).join(
|
||||
ChatLog,
|
||||
(ChatLog.conversation_id == subquery.c.conversation_id) &
|
||||
(ChatLog.created_at == subquery.c.last_active)
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
sessions = []
|
||||
for row in results:
|
||||
if not row.conversation_id:
|
||||
continue
|
||||
sessions.append({
|
||||
'id': 0, # 前端需要 id key
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
|
||||
'created_at': row.last_active.isoformat()
|
||||
})
|
||||
|
||||
return jsonify(sessions)
|
||||
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_messages():
|
||||
"""
|
||||
获取指定会话的消息记录
|
||||
"""
|
||||
conversation_id = request.args.get('conversation_id')
|
||||
if not conversation_id:
|
||||
return jsonify([])
|
||||
|
||||
logs = ChatLog.query.filter_by(
|
||||
conversation_id=conversation_id
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
for log in logs:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'assistant', 'content': log.answer})
|
||||
|
||||
return jsonify(messages)
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
"""
|
||||
SSE 流式聊天接口
|
||||
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 query / agent_id / conversation_id
|
||||
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
||||
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
||||
传入参数:
|
||||
无(从 request.json 读取)
|
||||
返回值:
|
||||
Flask Response 对象,mimetype=text/event-stream
|
||||
"""
|
||||
# 解析 JSON 请求体
|
||||
data = request.get_json() or {}
|
||||
# 提取用户提问内容
|
||||
query = data.get('query')
|
||||
# 提取会话 ID(可选)
|
||||
conversation_id = data.get('conversation_id')
|
||||
|
||||
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
# 安全兜底:如果装饰器未正确注入,返回错误
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
stream_with_context(
|
||||
DifyService.stream_chat(query, user.id, agent, conversation_id)
|
||||
),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
||||
'X-Accel-Buffering': 'no'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/feedback', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def submit_feedback():
|
||||
"""
|
||||
提交对回答的评分与评论
|
||||
用途:在对话结束后,由前端发送评分(1~5)和文字意见
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 score/comment/conversation_id
|
||||
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
|
||||
3. 为该 ChatLog 创建或更新 Feedback 记录
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
score = data.get('score')
|
||||
comment = data.get('comment') or ''
|
||||
conversation_id = data.get('conversation_id')
|
||||
|
||||
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
||||
return jsonify({'error': 'feedback is disabled'}), 403
|
||||
|
||||
if score is None:
|
||||
return jsonify({'error': 'score is required'}), 400
|
||||
|
||||
try:
|
||||
score_value = int(score)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'score must be an integer'}), 400
|
||||
|
||||
if score_value < 1 or score_value > 5:
|
||||
return jsonify({'error': 'score must be between 1 and 5'}), 400
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
# 构造查询:限定在当前用户和 Agent 范围内
|
||||
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
|
||||
if conversation_id:
|
||||
query = query.filter_by(conversation_id=conversation_id)
|
||||
|
||||
# 取最新一条对话日志
|
||||
chat_log = query.order_by(ChatLog.created_at.desc()).first()
|
||||
if not chat_log:
|
||||
return jsonify({'error': 'ChatLog not found'}), 404
|
||||
|
||||
# 如果已存在反馈,则更新;否则新建
|
||||
if chat_log.feedback:
|
||||
chat_log.feedback.score = score_value
|
||||
chat_log.feedback.comment = comment
|
||||
else:
|
||||
fb = Feedback(
|
||||
chat_log_id=chat_log.id,
|
||||
score=score_value,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.add(fb)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
backend/app/api/user.py
|
||||
文件用途:用户相关 API 路由
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供用户登录、首页配置、收藏夹、常用问题等接口
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request, g, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, UserFavoriteAgent, UserHomepageConfig, QuickQuestion, UserDefaultAgent
|
||||
from app.decorators import _get_current_user
|
||||
|
||||
user_bp = Blueprint('user', __name__)
|
||||
|
||||
@user_bp.route('/login', methods=['POST'])
|
||||
def login():
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user and user.check_password(password):
|
||||
return jsonify({
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'token': 'dummy-token' # In real app use JWT
|
||||
})
|
||||
return jsonify({'error': 'Invalid credentials'}), 401
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def get_user_home():
|
||||
user = _get_current_user()
|
||||
|
||||
# Favorites
|
||||
favorites = db.session.query(Agent).join(UserFavoriteAgent).filter(UserFavoriteAgent.user_id == user.id).all()
|
||||
favorite_ids = [a.id for a in favorites]
|
||||
|
||||
# Layout
|
||||
config = UserHomepageConfig.query.get(user.id)
|
||||
layout = config.layout if config else {}
|
||||
|
||||
# Embedded agents
|
||||
embedded_agents = []
|
||||
udas = UserDefaultAgent.query.filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
for uda in udas:
|
||||
agent = Agent.query.get(uda.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'icon_url': agent.icon_url,
|
||||
'description': agent.description
|
||||
})
|
||||
|
||||
# Quick questions
|
||||
qqs = QuickQuestion.query.filter_by(user_id=user.id).all()
|
||||
quick_questions = [{
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id
|
||||
} for q in qqs]
|
||||
|
||||
# All active agents (for selection)
|
||||
all_agents = Agent.query.filter_by(is_active=True).all()
|
||||
agents_list = [{
|
||||
'id': a.id,
|
||||
'name': a.name
|
||||
} for a in all_agents]
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'real_name': user.real_name,
|
||||
'department': user.department
|
||||
},
|
||||
'favorite_agent_ids': favorite_ids,
|
||||
'layout': layout,
|
||||
'embedded_agents': embedded_agents,
|
||||
'quick_questions': quick_questions,
|
||||
'agents': agents_list
|
||||
})
|
||||
|
||||
@user_bp.route('/agents/<int:agent_id>', methods=['GET'])
|
||||
def get_agent_details(agent_id):
|
||||
"""
|
||||
获取单个 Agent 详情
|
||||
"""
|
||||
user = _get_current_user()
|
||||
agent = Agent.query.get(agent_id)
|
||||
|
||||
if not agent:
|
||||
return jsonify({'error': 'Agent not found'}), 404
|
||||
|
||||
# Check permission (optional, but good practice)
|
||||
# For now, allow if active or user is admin
|
||||
if not agent.is_active and user.role != 'admin':
|
||||
return jsonify({'error': 'Agent is not active'}), 403
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'icon_url': agent.icon_url,
|
||||
'type': agent.type,
|
||||
'extra_config': agent.extra_config
|
||||
})
|
||||
|
||||
@user_bp.route('/config', methods=['GET'])
|
||||
def get_user_config():
|
||||
"""
|
||||
获取用户/系统配置
|
||||
"""
|
||||
user = _get_current_user()
|
||||
return jsonify({
|
||||
'feedback_enabled': current_app.config.get('FEEDBACK_ENABLED', True)
|
||||
})
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST'])
|
||||
def add_favorite(agent_id):
|
||||
user = _get_current_user()
|
||||
if not UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first():
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['DELETE'])
|
||||
def remove_favorite(agent_id):
|
||||
user = _get_current_user()
|
||||
fav = UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if fav:
|
||||
db.session.delete(fav)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
config = UserHomepageConfig.query.get(user.id)
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id)
|
||||
db.session.add(config)
|
||||
|
||||
config.layout = data.get('layout', {})
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/embedded-agents', methods=['PUT'])
|
||||
def update_embedded_agents():
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
|
||||
if len(agent_ids) > 2:
|
||||
return jsonify({'error': 'Max 2 embedded agents'}), 400
|
||||
|
||||
# Clear existing
|
||||
UserDefaultAgent.query.filter_by(user_id=user.id).delete()
|
||||
|
||||
for i, aid in enumerate(agent_ids):
|
||||
uda = UserDefaultAgent(user_id=user.id, agent_id=aid, sort_order=i)
|
||||
db.session.add(uda)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT'])
|
||||
def update_quick_question(qq_id: int):
|
||||
"""
|
||||
更新常用问题
|
||||
"""
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
|
||||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||
if not qq:
|
||||
return jsonify({"error": "QuickQuestion not found"}), 404
|
||||
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"status": "ok"})
|
||||
Reference in new issue
Block a user