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,38 @@
|
||||
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂
|
||||
"""
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from app.config import config
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
|
||||
def create_app(config_name='default'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
# 管理员相关接口
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
|
||||
return app
|
||||
@@ -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"})
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
import os
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True
|
||||
}
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv(
|
||||
'HR_WORKFLOW_IFRAME_URL',
|
||||
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
|
||||
)
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
|
||||
)
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
# 服务器 Ubuntu PostgreSQL 配置
|
||||
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'testing': TestingConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
引用文件:flask, functools, models, db
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""
|
||||
内部工具函数:获取当前登录用户
|
||||
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
|
||||
"""
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
username = request.headers.get('X-Username')
|
||||
role = request.headers.get('X-Role', 'user')
|
||||
|
||||
user = None
|
||||
if user_id:
|
||||
try:
|
||||
user = User.query.get(int(user_id))
|
||||
except ValueError:
|
||||
user = None
|
||||
if user is None and username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if not user:
|
||||
if user_id:
|
||||
safe_id = int(user_id)
|
||||
user = User(
|
||||
id=safe_id,
|
||||
username=username or f'user_{safe_id}',
|
||||
email=f'{username or f"user_{safe_id}"}@example.com',
|
||||
department='IT',
|
||||
role=role,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
elif username:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
department='IT',
|
||||
role=role,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
else:
|
||||
# Check if guest user exists
|
||||
user = User.query.filter_by(username='guest').first()
|
||||
if not user:
|
||||
user = User(
|
||||
username='guest',
|
||||
email='guest@example.com',
|
||||
department='',
|
||||
role='guest',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 agent_id
|
||||
2. 获取当前用户 (临时固定为 ID=1)
|
||||
3. 如果用户是 admin,则放行
|
||||
4. 否则检查 user.agents 是否包含该 agent
|
||||
传入参数:
|
||||
f: 被装饰的视图函数
|
||||
返回值:
|
||||
包装后的视图函数
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 从 JSON 请求体中解析数据
|
||||
data = request.get_json() or {}
|
||||
# 获取 agent_id
|
||||
agent_id = data.get('agent_id')
|
||||
|
||||
# 如果未提供 agent_id,则返回 400 错误
|
||||
if not agent_id:
|
||||
return jsonify({'error': 'agent_id is required'}), 400
|
||||
|
||||
# 获取当前用户(此处固定为 admin 用户,用于演示)
|
||||
user = _get_current_user()
|
||||
|
||||
# 查询目标 Agent 是否存在
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
return jsonify({'error': 'Agent not found'}), 404
|
||||
|
||||
# 将 agent 对象挂在 g 上,方便下游使用
|
||||
g.current_agent = agent
|
||||
|
||||
# 如果用户是管理员,跳过权限检查直接放行
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 非管理员:检查多对多关联表中是否存在权限
|
||||
if agent not in user.agents:
|
||||
return jsonify({'error': 'Permission denied for this agent'}), 403
|
||||
|
||||
# 鉴权通过,调用原始视图函数
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
核心逻辑:
|
||||
1. 获取当前用户
|
||||
2. 判断 user.role 是否为 'admin'
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 获取当前用户(自动创建 admin)
|
||||
user = _get_current_user()
|
||||
# 如果不是管理员,则返回 403
|
||||
if user.role != 'admin':
|
||||
return jsonify({'error': 'Admin privilege required'}), 403
|
||||
# 是管理员则放行
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
@@ -0,0 +1,237 @@
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
|
||||
class Base(db.Model):
|
||||
"""
|
||||
基础模型类,设置为抽象基类
|
||||
"""
|
||||
__abstract__ = True
|
||||
|
||||
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||
# 用于存储用户拥有哪些 Agent 的访问权限
|
||||
user_agent_permissions = db.Table(
|
||||
'user_agent_permissions',
|
||||
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
|
||||
)
|
||||
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
class ZlLanguage(Base):
|
||||
"""
|
||||
多语言配置表
|
||||
用途:存储系统支持的语言列表
|
||||
"""
|
||||
__tablename__ = 'zl_languages'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
|
||||
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
|
||||
class Department(Base):
|
||||
"""
|
||||
部门表
|
||||
用途:存储公司部门列表
|
||||
"""
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
class UserHomepageConfig(Base):
|
||||
"""
|
||||
用户首页配置表
|
||||
用途:存储用户自定义的首页布局与配置
|
||||
"""
|
||||
__tablename__ = 'user_homepage_configs'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
|
||||
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
class UserFavoriteAgent(Base):
|
||||
"""
|
||||
用户收藏 Agent 表
|
||||
用途:存储用户收藏的 Agent
|
||||
"""
|
||||
__tablename__ = 'user_favorite_agents'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class UserDefaultAgent(Base):
|
||||
"""
|
||||
用户默认 Agent 表 (嵌入首页)
|
||||
用途:存储用户设置的默认嵌入 Agent (最多2个)
|
||||
"""
|
||||
__tablename__ = 'user_default_agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
用户表
|
||||
用途:存储系统用户信息
|
||||
核心逻辑:包含部门、角色等字段,关联 Agent 权限
|
||||
"""
|
||||
__tablename__ = 'users'
|
||||
|
||||
# 主键 ID
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 用户名,唯一且带索引
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||
# 邮箱,唯一
|
||||
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
# 部门信息
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
# 角色:admin 或 user
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
# 账号状态:active (正常), pending (待审批), disabled (禁用)
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
# 密码哈希
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 首选语言
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
|
||||
# 真实姓名
|
||||
real_name: Mapped[Optional[str]] = mapped_column(String(50))
|
||||
# 公司工号,唯一
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
# 手机号,唯一
|
||||
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
|
||||
|
||||
# 默认嵌入的 Agent ID (忽略权限检查)
|
||||
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
|
||||
|
||||
# 关系:用户拥有的 Agent 权限 (多对多)
|
||||
agents: Mapped[List["Agent"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="users"
|
||||
)
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
if not self.password_hash:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||
"""
|
||||
__tablename__ = 'agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 应用名称
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
# 应用描述
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
# 图标 URL
|
||||
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
|
||||
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
|
||||
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
|
||||
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
|
||||
# 类型:api (默认) 或 iframe
|
||||
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||
# 自定义 API Base URL (覆盖全局配置)
|
||||
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 额外配置 (JSON),用于存储 iframe_url 等
|
||||
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
|
||||
# 是否激活
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
# 创建时间
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关系:拥有该应用权限的用户 (多对多)
|
||||
users: Mapped[List["User"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="agents"
|
||||
)
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
用途:存储用户与 Agent 的对话记录
|
||||
"""
|
||||
__tablename__ = 'chat_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[float] = mapped_column(default=0.0) # 响应耗时
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100)) # Dify 会话 ID
|
||||
tokens_used: Mapped[Optional[int]] = mapped_column(Integer, default=0) # 消耗 token 数
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关联 Feedback
|
||||
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
|
||||
|
||||
class Feedback(Base):
|
||||
"""
|
||||
反馈表
|
||||
用途:存储用户对回答的评分与评价
|
||||
"""
|
||||
__tablename__ = 'feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||
score: Mapped[int] = mapped_column(Integer) # 1-5
|
||||
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
用途:存储用户的权限申请记录
|
||||
"""
|
||||
__tablename__ = 'permission_requests'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
reason: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储用户自定义的常用问题
|
||||
"""
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
@@ -0,0 +1,137 @@
|
||||
|
||||
"""
|
||||
backend/app/services/dify.py
|
||||
文件用途:Dify API 集成服务
|
||||
引用文件:requests, json, models, config
|
||||
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
from flask import current_app
|
||||
from app.models import ChatLog, db
|
||||
from app.config import Config
|
||||
|
||||
class DifyService:
|
||||
"""
|
||||
Dify 服务类
|
||||
用途:封装与 Dify API 的交互逻辑
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||
"""
|
||||
生成器函数:向 Dify 发起请求并流式返回
|
||||
用途:处理 /v1/chat-messages 接口的流式响应
|
||||
核心逻辑:
|
||||
1. 构造请求头与 Payload
|
||||
2. 使用 requests.post(stream=True) 发起请求
|
||||
3. 逐行读取 SSE 数据
|
||||
4. 解析 'data: ' 开头的行,透传给前端
|
||||
5. 在 'message_end' 事件中记录完整日志到数据库
|
||||
参数:
|
||||
query: 用户提问内容
|
||||
user_id: 当前用户 ID
|
||||
agent: Agent 模型对象,包含 API Key
|
||||
conversation_id: 会话 ID (可选)
|
||||
输出:
|
||||
Yields SSE 格式字符串 "data: {...}\n\n"
|
||||
"""
|
||||
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
|
||||
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}/chat-messages"
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
payload = {
|
||||
"inputs": {},
|
||||
"query": query,
|
||||
"response_mode": "streaming",
|
||||
"conversation_id": conversation_id,
|
||||
"user": str(user_id)
|
||||
}
|
||||
|
||||
# 记录开始时间,用于计算耗时
|
||||
start_time = time.time()
|
||||
# 用于收集流式片段拼接完整回答
|
||||
full_answer = []
|
||||
|
||||
try:
|
||||
# stream=True 关键参数,建立长连接
|
||||
# 设置连接超时为 5 秒,读取超时为 60 秒
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
||||
response.raise_for_status()
|
||||
|
||||
# 逐行迭代响应内容
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
# 识别 SSE 数据行
|
||||
if decoded_line.startswith('data: '):
|
||||
json_str = decoded_line[6:]
|
||||
try:
|
||||
data = json.loads(json_str)
|
||||
event = data.get('event')
|
||||
|
||||
# 核心:将 Dify 的原始数据透传给前端
|
||||
yield f"data: {json_str}\n\n"
|
||||
|
||||
# 收集完整回答用于日志
|
||||
if event == 'message':
|
||||
full_answer.append(data.get('answer', ''))
|
||||
elif event == 'message_end':
|
||||
# 对话结束,记录日志
|
||||
# 异步或在此处记录日志(为了演示简单,此处同步记录,生产环境建议放入 Celery/RQ)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
metadata = data.get('metadata', {})
|
||||
usage = metadata.get('usage', {})
|
||||
|
||||
# 创建日志条目
|
||||
# 注意:在生成器中操作 DB 需要确保应用上下文存在
|
||||
DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id'),
|
||||
query=query,
|
||||
answer="".join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency
|
||||
)
|
||||
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
else:
|
||||
# 处理 keep-alive 等其他行
|
||||
pass
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
# 异常处理:返回标准错误格式给前端
|
||||
error_msg = json.dumps({"event": "error", "message": str(e)})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
|
||||
@staticmethod
|
||||
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
|
||||
"""
|
||||
内部方法:写入数据库日志
|
||||
用途:将对话详情持久化到 ChatLog 表
|
||||
"""
|
||||
try:
|
||||
# 确保在应用上下文中(Flask stream_with_context 会保持上下文)
|
||||
chat_log = ChatLog(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
conversation_id=conversation_id,
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=tokens,
|
||||
latency=latency
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Failed to log chat: {e}")
|
||||
db.session.rollback()
|
||||
Reference in new issue
Block a user