| from flask import Flask, request, jsonify, send_from_directory, redirect, url_for, session
|
| from student_management import register_student_routes
|
| from flask_cors import CORS
|
| import os
|
| import time
|
| import traceback
|
| import json
|
| import re
|
| import sys
|
| import io
|
| import threading
|
| import queue
|
| import contextlib
|
| import signal
|
| import psutil
|
| from dotenv import load_dotenv
|
|
|
|
|
| from modules.knowledge_base.routes import knowledge_bp
|
| from modules.code_executor.routes import code_executor_bp
|
| from modules.visualization.routes import visualization_bp
|
| from modules.agent_builder.routes import agent_builder_bp
|
| from modules.auth.routes import auth_bp
|
|
|
|
|
| load_dotenv()
|
|
|
| app = Flask(__name__)
|
| CORS(app)
|
|
|
|
|
| DATA_DIR = os.getenv("DATA_DIR", ".")
|
| AGENTS_DIR = os.path.join(DATA_DIR, "agents")
|
| UPLOADS_DIR = os.path.join(DATA_DIR, "uploads")
|
|
|
|
|
| app.secret_key = os.getenv("SECRET_KEY", "your_secret_key_here")
|
|
|
|
|
| app.register_blueprint(knowledge_bp, url_prefix='/api/knowledge')
|
| app.register_blueprint(code_executor_bp, url_prefix='/api/code')
|
| app.register_blueprint(visualization_bp, url_prefix='/api/visualization')
|
| app.register_blueprint(agent_builder_bp, url_prefix='/api/agent')
|
| app.register_blueprint(auth_bp, url_prefix='/api/auth')
|
|
|
|
|
| os.makedirs('static', exist_ok=True)
|
| os.makedirs(UPLOADS_DIR, exist_ok=True)
|
| os.makedirs(AGENTS_DIR, exist_ok=True)
|
|
|
|
|
| execution_contexts = {}
|
|
|
|
|
| users = {
|
| "teachers": [
|
| {"username": "teacher", "password": "123456", "name": "李志刚"},
|
| {"username": "admin", "password": "admin123", "name": "管理员"}
|
| ],
|
| "students": [
|
| {"username": "student1", "password": "123456", "name": "张三"},
|
| {"username": "student2", "password": "123456", "name": "李四"}
|
| ]
|
| }
|
|
|
|
|
| student_activities = {}
|
|
|
| def get_memory_usage():
|
| """获取当前进程的内存使用情况"""
|
| process = psutil.Process(os.getpid())
|
| return f"{process.memory_info().rss / 1024 / 1024:.1f} MB"
|
|
|
| class CustomStdin:
|
| def __init__(self, input_queue):
|
| self.input_queue = input_queue
|
| self.buffer = ""
|
|
|
| def readline(self):
|
| if not self.buffer:
|
| self.buffer = self.input_queue.get() + "\n"
|
|
|
| result = self.buffer
|
| self.buffer = ""
|
| return result
|
|
|
| class InteractiveExecution:
|
| """管理Python代码的交互式执行"""
|
| def __init__(self, code):
|
| self.code = code
|
| self.context_id = str(time.time())
|
| self.is_complete = False
|
| self.is_waiting_for_input = False
|
| self.stdout_buffer = io.StringIO()
|
| self.last_read_position = 0
|
| self.input_queue = queue.Queue()
|
| self.error = None
|
| self.thread = None
|
| self.should_terminate = False
|
|
|
| def run(self):
|
| """在单独的线程中启动执行"""
|
| self.thread = threading.Thread(target=self._execute)
|
| self.thread.daemon = True
|
| self.thread.start()
|
|
|
|
|
| time.sleep(0.1)
|
| return self.context_id
|
|
|
| def _execute(self):
|
| """执行代码,处理标准输入输出"""
|
| try:
|
|
|
| orig_stdin = sys.stdin
|
| orig_stdout = sys.stdout
|
|
|
|
|
| custom_stdin = CustomStdin(self.input_queue)
|
|
|
|
|
| sys.stdin = custom_stdin
|
| sys.stdout = self.stdout_buffer
|
|
|
| try:
|
|
|
| self._last_check_time = 0
|
|
|
| def check_termination():
|
| if self.should_terminate:
|
| raise KeyboardInterrupt("Execution terminated by user")
|
|
|
|
|
| shared_namespace = {
|
| "__builtins__": __builtins__,
|
| "_check_termination": check_termination,
|
| "time": time,
|
| "__name__": "__main__"
|
| }
|
|
|
|
|
| try:
|
| exec(self.code, shared_namespace)
|
| except KeyboardInterrupt:
|
| print("\nExecution terminated by user")
|
|
|
| except Exception as e:
|
| self.error = {
|
| "error": str(e),
|
| "traceback": traceback.format_exc()
|
| }
|
|
|
| finally:
|
|
|
| sys.stdin = orig_stdin
|
| sys.stdout = orig_stdout
|
|
|
|
|
| self.is_complete = True
|
|
|
| except Exception as e:
|
| self.error = {
|
| "error": str(e),
|
| "traceback": traceback.format_exc()
|
| }
|
| self.is_complete = True
|
|
|
| def terminate(self):
|
| """终止执行"""
|
| self.should_terminate = True
|
|
|
|
|
| if self.is_waiting_for_input:
|
| self.input_queue.put("\n")
|
|
|
|
|
| time.sleep(0.2)
|
|
|
|
|
| self.is_complete = True
|
|
|
| return True
|
|
|
| def provide_input(self, user_input):
|
| """为运行的代码提供输入"""
|
| self.input_queue.put(user_input)
|
| self.is_waiting_for_input = False
|
| return True
|
|
|
| def get_output(self):
|
| """获取stdout缓冲区的当前内容"""
|
| output = self.stdout_buffer.getvalue()
|
| return output
|
|
|
| def get_new_output(self):
|
| """只获取自上次读取以来的新输出"""
|
| current_value = self.stdout_buffer.getvalue()
|
| if self.last_read_position < len(current_value):
|
| new_output = current_value[self.last_read_position:]
|
| self.last_read_position = len(current_value)
|
| return new_output
|
| return ""
|
|
|
|
|
| def record_student_activity(username, activity_type, title, agent_id=None, agent_name=None):
|
| """记录学生活动"""
|
| if username not in student_activities:
|
| student_activities[username] = []
|
|
|
|
|
| activity = {
|
| "type": activity_type,
|
| "title": title,
|
| "timestamp": int(time.time()),
|
| "agent_id": agent_id,
|
| "agent_name": agent_name
|
| }
|
|
|
|
|
| student_activities[username].insert(0, activity)
|
| if len(student_activities[username]) > 20:
|
| student_activities[username] = student_activities[username][:20]
|
|
|
| return activity
|
|
|
|
|
| @app.route('/login.html')
|
| def login_page():
|
| """登录页面"""
|
| return render_template('login.html')
|
|
|
| @app.route('/api/auth/login', methods=['POST'])
|
| def login():
|
| """处理登录请求"""
|
| data = request.json
|
| username = data.get('username')
|
| password = data.get('password')
|
| user_type = data.get('type', 'teacher')
|
|
|
| if user_type == 'teacher':
|
| user_list = users['teachers']
|
| else:
|
| user_list = users['students']
|
|
|
| for user in user_list:
|
| if user['username'] == username and user['password'] == password:
|
|
|
| session['logged_in'] = True
|
| session['username'] = username
|
| session['user_type'] = user_type
|
| session['user_name'] = user['name']
|
|
|
| return jsonify({
|
| 'success': True,
|
| 'user': {
|
| 'name': user['name'],
|
| 'type': user_type
|
| }
|
| })
|
|
|
| return jsonify({
|
| 'success': False,
|
| 'message': '用户名或密码错误'
|
| }), 401
|
|
|
| @app.route('/api/auth/logout', methods=['POST'])
|
| def logout():
|
| """处理登出请求"""
|
| session.clear()
|
| return jsonify({
|
| 'success': True
|
| })
|
|
|
| @app.route('/api/auth/check', methods=['GET'])
|
| def check_auth():
|
| """检查用户是否已登录"""
|
| if session.get('logged_in'):
|
| return jsonify({
|
| 'success': True,
|
| 'user': {
|
| 'name': session.get('user_name'),
|
| 'type': session.get('user_type')
|
| }
|
| })
|
|
|
| return jsonify({
|
| 'success': False
|
| }), 401
|
|
|
|
|
| def login_required(f):
|
| def decorated_function(*args, **kwargs):
|
| if not session.get('logged_in'):
|
| return redirect(url_for('login_page'))
|
| return f(*args, **kwargs)
|
| decorated_function.__name__ = f.__name__
|
| return decorated_function
|
|
|
|
|
| def teacher_required(f):
|
| def decorated_function(*args, **kwargs):
|
| if not session.get('logged_in') or session.get('user_type') != 'teacher':
|
| return jsonify({
|
| 'success': False,
|
| 'message': '需要教师权限'
|
| }), 403
|
| return f(*args, **kwargs)
|
| decorated_function.__name__ = f.__name__
|
| return decorated_function
|
|
|
|
|
| def student_required(f):
|
| def decorated_function(*args, **kwargs):
|
| if not session.get('logged_in') or session.get('user_type') != 'student':
|
| return jsonify({
|
| 'success': False,
|
| 'message': '需要学生权限'
|
| }), 403
|
| return f(*args, **kwargs)
|
| decorated_function.__name__ = f.__name__
|
| return decorated_function
|
|
|
|
|
| FRONTEND_DIST = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'dist')
|
|
|
|
|
| @app.route('/')
|
| def root():
|
| return send_from_directory(FRONTEND_DIST, 'index.html')
|
|
|
| @app.route('/api/progress/<task_id>', methods=['GET'])
|
| def get_progress(task_id):
|
| """获取文档处理进度"""
|
| try:
|
|
|
| from modules.knowledge_base.routes import processing_tasks
|
|
|
| progress_data = processing_tasks.get(task_id, {
|
| 'progress': 0,
|
| 'status': '未找到任务',
|
| 'error': True
|
| })
|
|
|
| return jsonify({"success": True, "data": progress_data})
|
| except Exception as e:
|
| traceback.print_exc()
|
| return jsonify({"success": False, "message": str(e)}), 500
|
|
|
| @app.route('/student/<agent_id>')
|
| def student_view(agent_id):
|
| """学生访问Agent界面"""
|
| token = request.args.get('token', '')
|
|
|
|
|
| agent_path = os.path.join(AGENTS_DIR,f"{agent_id}.json")
|
| if not os.path.exists(agent_path):
|
| return render_template('error.html',
|
| message="找不到指定的Agent",
|
| error_code=404)
|
|
|
|
|
| with open(agent_path, 'r', encoding='utf-8') as f:
|
| try:
|
| agent_config = json.load(f)
|
| except:
|
| return render_template('error.html',
|
| message="Agent配置无效",
|
| error_code=500)
|
|
|
|
|
| if token:
|
| valid_token = False
|
| if "distributions" in agent_config:
|
| for dist in agent_config["distributions"]:
|
| if dist.get("token") == token:
|
| valid_token = True
|
| break
|
|
|
| if not valid_token:
|
| return render_template('token_verification.html',
|
| message="访问令牌无效",
|
| error_code=403)
|
|
|
|
|
| if "distributions" in agent_config:
|
| for dist in agent_config["distributions"]:
|
| if dist.get("token") == token:
|
|
|
| dist["usage_count"] = dist.get("usage_count", 0) + 1
|
|
|
|
|
| if "stats" not in agent_config:
|
| agent_config["stats"] = {}
|
|
|
| agent_config["stats"]["usage_count"] = agent_config["stats"].get("usage_count", 0) + 1
|
| agent_config["stats"]["last_used"] = int(time.time())
|
|
|
|
|
| with open(agent_path, 'w', encoding='utf-8') as f:
|
| json.dump(agent_config, f, ensure_ascii=False, indent=2)
|
|
|
| break
|
|
|
|
|
| return render_template('student.html',
|
| agent_id=agent_id,
|
| agent_name=agent_config.get('name', 'AI学习助手'),
|
| agent_description=agent_config.get('description', ''),
|
| token=token)
|
|
|
| @app.route('/api/student/chat/<agent_id>', methods=['POST'])
|
| def student_chat(agent_id):
|
| """学生与Agent聊天的API"""
|
| try:
|
| data = request.json
|
| message = data.get('message', '')
|
| token = data.get('token', '')
|
|
|
| if not message:
|
| return jsonify({"success": False, "message": "消息不能为空"}), 400
|
|
|
|
|
| agent_path = os.path.join(AGENTS_DIR,f"{agent_id}.json")
|
| if not os.path.exists(agent_path):
|
| return jsonify({"success": False, "message": "Agent不存在"}), 404
|
|
|
| with open(agent_path, 'r', encoding='utf-8') as f:
|
| agent_config = json.load(f)
|
|
|
|
|
| if token and "distributions" in agent_config:
|
| valid_token = False
|
| for dist in agent_config["distributions"]:
|
| if dist.get("token") == token:
|
| valid_token = True
|
|
|
|
|
| dist["usage_count"] = dist.get("usage_count", 0) + 1
|
| break
|
|
|
| if not valid_token:
|
| return jsonify({"success": False, "message": "访问令牌无效"}), 403
|
|
|
|
|
| if "stats" not in agent_config:
|
| agent_config["stats"] = {}
|
|
|
| agent_config["stats"]["usage_count"] = agent_config["stats"].get("usage_count", 0) + 1
|
| agent_config["stats"]["last_used"] = int(time.time())
|
|
|
|
|
| with open(agent_path, 'w', encoding='utf-8') as f:
|
| json.dump(agent_config, f, ensure_ascii=False, indent=2)
|
|
|
|
|
| knowledge_bases = agent_config.get('knowledge_bases', [])
|
| plugins = agent_config.get('plugins', [])
|
|
|
|
|
| subject = agent_config.get('subject', agent_config.get('name', '通用学科'))
|
| instructor = agent_config.get('instructor', '教师')
|
|
|
|
|
| from modules.knowledge_base.generator import Generator
|
| generator = Generator(subject=subject, instructor=instructor)
|
|
|
|
|
| suggested_plugins = []
|
|
|
|
|
| if 'code' in plugins and ('代码' in message or 'python' in message.lower() or '编程' in message or 'code' in message.lower() or 'program' in message.lower()):
|
| suggested_plugins.append('code')
|
|
|
|
|
| if 'visualization' in plugins and ('3d' in message.lower() or '可视化' in message or '图形' in message):
|
| suggested_plugins.append('visualization')
|
|
|
|
|
| if 'mindmap' in plugins and ('思维导图' in message or 'mindmap' in message.lower()):
|
| suggested_plugins.append('mindmap')
|
|
|
|
|
| if session.get('logged_in'):
|
| username = session.get('username')
|
|
|
| record_student_activity(
|
| username=username,
|
| activity_type='chat',
|
| title=f'与 {agent_config.get("name", "AI助手")} 进行了对话',
|
| agent_id=agent_id,
|
| agent_name=agent_config.get('name')
|
| )
|
|
|
|
|
| if 'code' in suggested_plugins:
|
| record_student_activity(
|
| username=username,
|
| activity_type='code',
|
| title='执行了Python代码',
|
| agent_id=agent_id,
|
| agent_name=agent_config.get('name')
|
| )
|
|
|
| if 'visualization' in suggested_plugins:
|
| record_student_activity(
|
| username=username,
|
| activity_type='viz',
|
| title='查看了3D可视化图形',
|
| agent_id=agent_id,
|
| agent_name=agent_config.get('name')
|
| )
|
|
|
| if 'mindmap' in suggested_plugins:
|
| record_student_activity(
|
| username=username,
|
| activity_type='mindmap',
|
| title='生成了思维导图',
|
| agent_id=agent_id,
|
| agent_name=agent_config.get('name')
|
| )
|
|
|
|
|
| if not knowledge_bases:
|
|
|
| print(f"\n=== 处理查询: {message} (无知识库) ===")
|
|
|
|
|
| def generate_sse():
|
| try:
|
|
|
| yield f"data: {json.dumps({'type': 'start', 'plugins': suggested_plugins}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| for chunk in generator.generate_stream(message, []):
|
| if isinstance(chunk, dict):
|
| yield f"data: {json.dumps({'type': 'metadata', 'content': chunk}, ensure_ascii=False)}\n\n"
|
| else:
|
| yield f"data: {json.dumps({'type': 'content', 'content': chunk}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| yield f"data: {json.dumps({'type': 'done'}, ensure_ascii=False)}\n\n"
|
| except Exception as e:
|
| yield f"data: {json.dumps({'type': 'error', 'content': str(e)}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| from flask import Response
|
| return Response(
|
| generate_sse(),
|
| mimetype='text/event-stream',
|
| headers={
|
| 'Cache-Control': 'no-cache',
|
| 'X-Accel-Buffering': 'no',
|
| 'Access-Control-Allow-Origin': '*'
|
| }
|
| )
|
|
|
|
|
| try:
|
|
|
| from modules.knowledge_base.retriever import Retriever
|
| from modules.knowledge_base.reranker import Reranker
|
|
|
| retriever = Retriever()
|
| reranker = Reranker()
|
|
|
|
|
| tools = []
|
|
|
|
|
| tool_to_index = {}
|
|
|
| for i, index in enumerate(knowledge_bases):
|
| display_name = index[4:] if index.startswith('rag_') else index
|
|
|
|
|
| is_video = "视频" in display_name or "video" in display_name.lower()
|
|
|
|
|
| if is_video:
|
| tool_name = f"video_knowledge_base_{i+1}"
|
| description = f"在'{display_name}'视频知识库中搜索,返回带时间戳的视频链接。适用于需要视频讲解的问题。"
|
| else:
|
| tool_name = f"knowledge_base_{i+1}"
|
| description = f"在'{display_name}'知识库中搜索专业知识、概念和原理。适用于需要文本说明的问题。"
|
|
|
|
|
| tool_to_index[tool_name] = index
|
|
|
| tools.append({
|
| "type": "function",
|
| "function": {
|
| "name": tool_name,
|
| "description": description,
|
| "parameters": {
|
| "type": "object",
|
| "properties": {
|
| "keywords": {
|
| "type": "array",
|
| "items": {"type": "string"},
|
| "description": "搜索的关键词列表"
|
| }
|
| },
|
| "required": ["keywords"],
|
| "additionalProperties": False
|
| },
|
| "strict": True
|
| }
|
| })
|
|
|
|
|
| print(f"\n=== 处理查询: {message} ===")
|
| tool_calls = generator.extract_keywords_with_tools(message, tools)
|
|
|
|
|
| if not tool_calls:
|
| print("未检测到需要使用知识库,直接回答")
|
|
|
|
|
| def generate_sse_no_tools():
|
| try:
|
| yield f"data: {json.dumps({'type': 'start', 'plugins': suggested_plugins}, ensure_ascii=False)}\n\n"
|
|
|
| for chunk in generator.generate_stream(message, []):
|
| if isinstance(chunk, dict):
|
| yield f"data: {json.dumps({'type': 'metadata', 'content': chunk}, ensure_ascii=False)}\n\n"
|
| else:
|
| yield f"data: {json.dumps({'type': 'content', 'content': chunk}, ensure_ascii=False)}\n\n"
|
|
|
| yield f"data: {json.dumps({'type': 'done'}, ensure_ascii=False)}\n\n"
|
| except Exception as e:
|
| yield f"data: {json.dumps({'type': 'error', 'content': str(e)}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| from flask import Response
|
| return Response(
|
| generate_sse_no_tools(),
|
| mimetype='text/event-stream',
|
| headers={
|
| 'Cache-Control': 'no-cache',
|
| 'X-Accel-Buffering': 'no',
|
| 'Access-Control-Allow-Origin': '*'
|
| }
|
| )
|
|
|
|
|
| all_docs = []
|
|
|
|
|
| for tool_call in tool_calls:
|
| try:
|
| tool_name = tool_call["function"]["name"]
|
| actual_index = tool_to_index.get(tool_name)
|
|
|
| if not actual_index:
|
| print(f"找不到工具名称 '{tool_name}' 对应的索引")
|
| continue
|
|
|
| print(f"\n执行工具 '{tool_name}' -> 使用索引 '{actual_index}'")
|
|
|
| arguments = json.loads(tool_call["function"]["arguments"])
|
| keywords = " ".join(arguments.get("keywords", []))
|
|
|
| if not keywords:
|
| print("没有提供关键词,跳过检索")
|
| continue
|
|
|
| print(f"检索关键词: {keywords}")
|
|
|
|
|
| retrieved_docs, _ = retriever.retrieve(keywords, specific_index=actual_index)
|
| print(f"检索到 {len(retrieved_docs)} 个文档")
|
|
|
|
|
| reranked_docs = reranker.rerank(message, retrieved_docs, actual_index)
|
| print(f"重排序完成,排序后有 {len(reranked_docs)} 个文档")
|
|
|
|
|
| all_docs.extend(reranked_docs)
|
|
|
| except Exception as e:
|
| print(f"执行工具 '{tool_call.get('function', {}).get('name', '未知')}' 调用时出错: {str(e)}")
|
| import traceback
|
| traceback.print_exc()
|
|
|
|
|
| if not all_docs:
|
| print("未检索到任何相关文档,直接回答")
|
|
|
|
|
| def generate_sse_no_docs():
|
| try:
|
| yield f"data: {json.dumps({'type': 'start', 'plugins': suggested_plugins}, ensure_ascii=False)}\n\n"
|
|
|
| for chunk in generator.generate_stream(message, []):
|
| if isinstance(chunk, dict):
|
| yield f"data: {json.dumps({'type': 'metadata', 'content': chunk}, ensure_ascii=False)}\n\n"
|
| else:
|
| yield f"data: {json.dumps({'type': 'content', 'content': chunk}, ensure_ascii=False)}\n\n"
|
|
|
| yield f"data: {json.dumps({'type': 'done'}, ensure_ascii=False)}\n\n"
|
| except Exception as e:
|
| yield f"data: {json.dumps({'type': 'error', 'content': str(e)}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| from flask import Response
|
| return Response(
|
| generate_sse_no_docs(),
|
| mimetype='text/event-stream',
|
| headers={
|
| 'Cache-Control': 'no-cache',
|
| 'X-Accel-Buffering': 'no',
|
| 'Access-Control-Allow-Origin': '*'
|
| }
|
| )
|
|
|
|
|
| all_docs.sort(key=lambda x: x.get('rerank_score', 0), reverse=True)
|
| print(f"\n最终收集到 {len(all_docs)} 个文档用于生成回答")
|
|
|
|
|
| references = []
|
| for i, doc in enumerate(all_docs[:3], 1):
|
| file_name = doc['metadata'].get('file_name', '未知文件')
|
| content = doc['content']
|
|
|
|
|
| summary = content[:100] + ('...' if len(content) > 100 else '')
|
|
|
| references.append({
|
| 'index': i,
|
| 'file_name': file_name,
|
| 'content': content,
|
| 'summary': summary
|
| })
|
|
|
|
|
| def generate_sse_with_kb():
|
| try:
|
| yield f"data: {json.dumps({'type': 'start', 'plugins': suggested_plugins, 'references': references}, ensure_ascii=False)}\n\n"
|
|
|
| for chunk in generator.generate_stream(message, all_docs):
|
| if isinstance(chunk, dict):
|
| yield f"data: {json.dumps({'type': 'metadata', 'content': chunk}, ensure_ascii=False)}\n\n"
|
| else:
|
| yield f"data: {json.dumps({'type': 'content', 'content': chunk}, ensure_ascii=False)}\n\n"
|
|
|
| yield f"data: {json.dumps({'type': 'done'}, ensure_ascii=False)}\n\n"
|
| except Exception as e:
|
| yield f"data: {json.dumps({'type': 'error', 'content': str(e)}, ensure_ascii=False)}\n\n"
|
|
|
|
|
| from flask import Response
|
| return Response(
|
| generate_sse_with_kb(),
|
| mimetype='text/event-stream',
|
| headers={
|
| 'Cache-Control': 'no-cache',
|
| 'X-Accel-Buffering': 'no',
|
| 'Access-Control-Allow-Origin': '*'
|
| }
|
| )
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return jsonify({
|
| "success": False,
|
| "message": f"处理查询时出错: {str(e)}"
|
| }), 500
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return jsonify({"success": False, "message": str(e)}), 500
|
|
|
|
|
| @app.route('/api/student/activities', methods=['GET'])
|
| @student_required
|
| def get_student_activities():
|
| """获取学生活动记录"""
|
| try:
|
| username = session.get('username')
|
|
|
|
|
| activities = student_activities.get(username, [])
|
|
|
|
|
| formatted_activities = []
|
| for activity in activities:
|
|
|
| timestamp = activity['timestamp']
|
| current_time = int(time.time())
|
|
|
| if current_time - timestamp < 86400:
|
| if current_time - timestamp < 3600:
|
| time_text = f"{(current_time - timestamp) // 60}分钟前"
|
| else:
|
| time_text = f"今天 {time.strftime('%H:%M', time.localtime(timestamp))}"
|
| elif current_time - timestamp < 172800:
|
| time_text = f"昨天 {time.strftime('%H:%M', time.localtime(timestamp))}"
|
| else:
|
| time_text = time.strftime('%m月%d日 %H:%M', time.localtime(timestamp))
|
|
|
| formatted_activities.append({
|
| "type": activity['type'],
|
| "title": activity['title'],
|
| "time": time_text,
|
| "agent_id": activity.get('agent_id'),
|
| "agent_name": activity.get('agent_name')
|
| })
|
|
|
| return jsonify({
|
| "success": True,
|
| "activities": formatted_activities
|
| })
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return jsonify({
|
| "success": False,
|
| "message": str(e)
|
| }), 500
|
|
|
|
|
| @app.route('/api/verify_token', methods=['POST'])
|
| def verify_token():
|
| """验证访问令牌有效性"""
|
| try:
|
| data = request.json
|
| token = data.get('token', '')
|
| agent_id = data.get('agent_id', '')
|
|
|
| if not token:
|
| return jsonify({
|
| "success": False,
|
| "message": "未提供访问令牌"
|
| }), 400
|
|
|
|
|
| if agent_id:
|
| agent_path = os.path.join(AGENTS_DIR,f"{agent_id}.json")
|
| if not os.path.exists(agent_path):
|
| return jsonify({
|
| "success": False,
|
| "message": "Agent不存在"
|
| }), 404
|
|
|
| with open(agent_path, 'r', encoding='utf-8') as f:
|
| agent_config = json.load(f)
|
|
|
|
|
| if "distributions" in agent_config:
|
| for dist in agent_config["distributions"]:
|
| if dist.get("token") == token:
|
|
|
| if dist.get("expires_at", 0) > 0 and dist.get("expires_at", 0) < time.time():
|
| return jsonify({
|
| "success": False,
|
| "message": "访问令牌已过期"
|
| })
|
|
|
| return jsonify({
|
| "success": True,
|
| "agent": {
|
| "id": agent_id,
|
| "name": agent_config.get('name', 'AI学习助手'),
|
| "description": agent_config.get('description', ''),
|
| "subject": agent_config.get('subject', ''),
|
| "instructor": agent_config.get('instructor', '教师')
|
| }
|
| })
|
|
|
| return jsonify({
|
| "success": False,
|
| "message": "访问令牌无效"
|
| })
|
|
|
|
|
| valid_agent = None
|
|
|
| for filename in os.listdir(AGENTS_DIR):
|
| if filename.endswith('.json'):
|
| agent_path = os.path.join(AGENTS_DIR,filename)
|
| with open(agent_path, 'r', encoding='utf-8') as f:
|
| agent_config = json.load(f)
|
|
|
|
|
| if "distributions" in agent_config:
|
| for dist in agent_config["distributions"]:
|
| if dist.get("token") == token:
|
|
|
| if dist.get("expires_at", 0) > 0 and dist.get("expires_at", 0) < time.time():
|
| continue
|
|
|
| valid_agent = {
|
| "id": agent_config.get('id'),
|
| "name": agent_config.get('name', 'AI学习助手'),
|
| "description": agent_config.get('description', ''),
|
| "subject": agent_config.get('subject', ''),
|
| "instructor": agent_config.get('instructor', '教师')
|
| }
|
| break
|
|
|
| if valid_agent:
|
| break
|
|
|
| if valid_agent:
|
| return jsonify({
|
| "success": True,
|
| "agent": valid_agent
|
| })
|
|
|
| return jsonify({
|
| "success": False,
|
| "message": "未找到匹配的访问令牌"
|
| })
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return jsonify({
|
| "success": False,
|
| "message": f"验证访问令牌时出错: {str(e)}"
|
| }), 500
|
|
|
|
|
| @app.route('/api/student/agents', methods=['GET'])
|
| @student_required
|
| def get_student_agents():
|
| """获取学生可访问的Agent列表"""
|
| try:
|
|
|
|
|
| agents = []
|
|
|
| for filename in os.listdir(AGENTS_DIR):
|
| if filename.endswith('.json'):
|
| agent_path = os.path.join(AGENTS_DIR,filename)
|
| with open(agent_path, 'r', encoding='utf-8') as f:
|
| agent_config = json.load(f)
|
|
|
|
|
| agent_info = {
|
| "id": agent_config.get('id'),
|
| "name": agent_config.get('name', 'AI学习助手'),
|
| "description": agent_config.get('description', ''),
|
| "subject": agent_config.get('subject', ''),
|
| "instructor": agent_config.get('instructor', '教师'),
|
| "plugins": agent_config.get('plugins', []),
|
| "last_used": agent_config.get('stats', {}).get('last_used')
|
| }
|
|
|
|
|
| if "distributions" in agent_config and agent_config["distributions"]:
|
|
|
| agent_info["token"] = agent_config["distributions"][0].get("token")
|
|
|
| agents.append(agent_info)
|
|
|
|
|
| agents.sort(key=lambda x: x.get('last_used', 0) or 0, reverse=True)
|
|
|
| return jsonify({
|
| "success": True,
|
| "agents": agents
|
| })
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return jsonify({
|
| "success": False,
|
| "message": str(e)
|
| }), 500
|
|
|
|
|
| register_student_routes(app)
|
|
|
|
|
| @app.route('/<path:path>')
|
| def catch_all(path):
|
|
|
| file_path = os.path.join(FRONTEND_DIST, path)
|
| if os.path.isfile(file_path):
|
| return send_from_directory(FRONTEND_DIST, path)
|
|
|
| return send_from_directory(FRONTEND_DIST, 'index.html')
|
|
|
| if __name__ == '__main__':
|
| debug = os.getenv('FLASK_ENV', 'production') == 'development'
|
| app.run(debug=debug, host='0.0.0.0', port=7860) |