# E:\AI_System\web_ui\server.py
import sys
import os
import logging
import json # 添加json模块导入
from flask import Flask, jsonify, request, render_template, send_from_directory, Response # 添加Response导入
# 修复括号问题 - 确保项目根目录已添加到 Python 路径
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 注意:三个右括号
sys.path.insert(0, base_dir) # 使用 insert(0, ...) 确保优先搜索项目目录
# 添加必要的子目录到 Python 路径
sys.path.insert(0, os.path.join(base_dir, 'agent'))
sys.path.insert(0, os.path.join(base_dir, 'core'))
sys.path.insert(0, os.path.join(base_dir, 'utils'))
# 现在可以导入核心模块
from core.config import system_config
from agent.autonomous_agent import AutonomousAgent
# 配置Flask应用
app = Flask(__name__,
template_folder='templates', # 指定模板目录
static_folder='static') # 指定静态文件目录
# 配置日志
logging.basicConfig(
level=system_config.LOG_LEVEL,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('WebServer')
# 全局智能体实例
ai_agent = None
# 在应用启动时初始化智能体
logger.info("=" * 50)
logger.info("正在初始化智能体核心模块...")
try:
ai_agent = AutonomousAgent()
logger.info("✅ 智能体核心模块初始化成功")
except Exception as e:
logger.error(f"❌ 智能体初始化失败: {str(e)}")
# 可以选择退出程序
# sys.exit(1)
# 根路由 - 显示前端界面
@app.route('/')
def index():
"""首页路由 - 渲染前端界面"""
return render_template('agent_interface.html')
# 静态文件路由
@app.route('/static/<path:filename>')
def static_files(filename):
"""提供静态文件"""
return send_from_directory(app.static_folder, filename)
# 系统状态检查
@app.route('/status')
def status():
"""系统状态检查"""
if ai_agent:
return jsonify(ai_agent.get_status())
return jsonify({"status": "agent_not_initialized"}), 503
# 聊天请求处理 - 合并后的版本
@app.route('/chat', methods=['POST'])
def chat():
"""处理聊天请求,支持流式响应"""
if ai_agent is None:
return jsonify({"error": "Agent not initialized"}), 503
# 获取用户输入和请求参数
data = request.get_json()
user_input = data.get('message', '')
user_id = data.get('user_id', 'default')
stream = data.get('stream', False) # 默认为非流式
# 非流式处理
if not stream:
response = ai_agent.process_input(user_input, user_id)
return jsonify({"response": response})
# 流式处理 (SSE)
def generate():
# 创建回调函数用于流式输出
def stream_callback(chunk, is_final=False):
# 发送SSE格式的数据
yield f"data: {json.dumps({'chunk': chunk, 'final': is_final})}\n\n"
# 处理输入并获取响应生成器
response_gen = ai_agent.process_input_stream(user_input, user_id, stream_callback)
# 流式传输响应
for chunk in response_gen:
yield chunk
# 返回流式响应
return Response(generate(), mimetype='text/event-stream')
# 关机路由
@app.route('/shutdown', methods=['POST'])
def shutdown():
"""处理关机请求"""
try:
# 这里应该有实际的关机逻辑
# 例如: agent.shutdown(delay=data.get('delay', 2))
logger.info("收到关机请求")
return jsonify({"message": "系统将在2分钟后关闭"})
except Exception as e:
logger.error(f"关机请求失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# ========== 环境交互路由 ==========
# 环境浏览器
@app.route('/environment')
def environment_view():
"""渲染环境浏览器界面"""
return render_template('environment_view.html')
# 获取环境目录内容
@app.route('/api/explore', methods=['GET'])
def explore_directory():
"""获取指定路径的目录内容"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
path = request.args.get('path', '')
try:
# 如果路径为空,使用智能体的工作区根目录
if not path:
workspace_info = ai_agent.get_status().get('environment', {})
if workspace_info and 'workspace' in workspace_info:
path = workspace_info['workspace']
# 调用智能体的环境探索方法
result = ai_agent.explore_environment(path)
return jsonify(result)
except Exception as e:
logger.error(f"目录探索失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# 获取家具数据
@app.route('/api/furniture')
def get_furniture():
"""获取指定房间的家具数据"""
room = request.args.get('room', 'workshop')
# 这里简化实现,实际应从数据库获取
furniture_data = {
"workshop": [
{"type": "desk", "position": {"x": 0, "y": -1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "chair", "position": {"x": 0, "y": -1.5, "z": -1}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "bookshelf", "position": {"x": 3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "computer", "position": {"x": 0.5, "y": -0.5, "z": -3.2}, "rotation": {"x": 0, "y": 0, "z": 0}}
],
"lounge": [
{"type": "sofa", "position": {"x": 0, "y": -1.5, "z": -2}, "rotation": {"x": 0, "y": 180, "z": 0}},
{"type": "coffee_table", "position": {"x": 0, "y": -1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "tv", "position": {"x": 0, "y": 0.5, "z": -4}, "rotation": {"x": 0, "y": 0, "z": 0}}
],
"library": [
{"type": "bookshelf", "position": {"x": -3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "bookshelf", "position": {"x": 0, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "bookshelf", "position": {"x": 3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}},
{"type": "reading_chair", "position": {"x": 0, "y": -1.5, "z": -1}, "rotation": {"x": 0, "y": 180, "z": 0}}
]
}
return jsonify({
"room": room,
"items": furniture_data.get(room, [])
})
# 获取可用皮肤列表
@app.route('/api/skins')
def get_skins():
"""获取可用皮肤列表"""
# 这里简化实现,实际应从数据库获取
skins = [
{"id": "default", "name": "默认皮肤", "description": "简洁的蓝色主题"},
{"id": "midnight", "name": "午夜黑", "description": "深色主题,减少眼睛疲劳"},
{"id": "forest", "name": "森林绿", "description": "自然绿色主题,带来平静感"},
{"id": "tech", "name": "科技蓝", "description": "未来感十足的科技主题"},
{"id": "vintage", "name": "复古黄", "description": "复古纸张色调,怀旧风格"}
]
return jsonify(skins)
# 更换皮肤
@app.route('/api/change_skin', methods=['POST'])
def change_skin():
"""更换智能体皮肤"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
data = request.get_json()
skin_name = data.get('skin')
if not skin_name:
return jsonify({"error": "Missing skin parameter"}), 400
# 调用智能体的换肤方法
result = ai_agent.execute_action("change_skin", {"skin_name": skin_name})
if result.get("success"):
return jsonify({"success": True, "message": f"皮肤已更换为 {skin_name}"})
else:
return jsonify({"error": result.get("message", "换肤失败")}), 500
except Exception as e:
logger.error(f"更换皮肤失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# 执行环境动作
@app.route('/api/execute', methods=['POST'])
def execute_action():
"""执行环境动作"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
data = request.get_json()
action = data.get('action')
params = data.get('parameters', {})
if not action:
return jsonify({"error": "Missing action parameter"}), 400
# 调用智能体的执行方法
result = ai_agent.execute_action(action, params)
return jsonify(result)
except Exception as e:
logger.error(f"动作执行失败: {action} - {str(e)}")
return jsonify({"error": str(e)}), 500
# 环境状态路由 - 合并后的版本
@app.route('/api/environment_status')
def environment_status():
"""获取环境状态信息(包含可用动作列表)"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
# 获取智能体状态中的环境部分
status = ai_agent.get_status()
env_status = status.get('environment', {})
# 获取探索历史
history = ai_agent.environment.get_exploration_history()
# 获取可用动作列表
available_actions = ai_agent.get_available_actions()
return jsonify({
"system": env_status,
"exploration_history": history,
"available_actions": available_actions
})
except Exception as e:
logger.error(f"获取环境状态失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# ========== 新增智能体管理路由 ==========
# 获取智能体详细状态
@app.route('/api/agent_status')
def agent_status():
"""获取智能体的详细状态(核心状态、环境状态、任务队列)"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
# 获取核心状态
core_status = ai_agent.get_status()
# 获取环境状态
env_status = ai_agent.get_environment_status()
# 获取任务队列
task_queue = ai_agent.get_task_queue()
return jsonify({
"core_status": core_status,
"environment_status": env_status,
"task_queue": task_queue
})
except Exception as e:
logger.error(f"获取智能体详细状态失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# 创建目录
@app.route('/api/create_directory', methods=['POST'])
def create_directory():
"""在指定路径创建新目录"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
data = request.get_json()
path = data.get('path')
if not path:
return jsonify({"error": "Missing path parameter"}), 400
# 调用智能体的目录创建方法
result = ai_agent.execute_action("create_directory", {"path": path})
if result.get("success"):
return jsonify({"success": True, "message": f"目录 '{path}' 创建成功"})
else:
return jsonify({"error": result.get("message", "目录创建失败")}), 500
except Exception as e:
logger.error(f"创建目录失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# 删除路径
@app.route('/api/delete_path', methods=['POST'])
def delete_path():
"""删除指定路径(文件或目录)"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
data = request.get_json()
path = data.get('path')
if not path:
return jsonify({"error": "Missing path parameter"}), 400
# 调用智能体的删除方法
result = ai_agent.execute_action("delete_path", {"path": path})
if result.get("success"):
return jsonify({"success": True, "message": f"路径 '{path}' 删除成功"})
else:
return jsonify({"error": result.get("message", "路径删除失败")}), 500
except Exception as e:
logger.error(f"删除路径失败: {str(e)}")
return jsonify({"error": str(e)}), 500
# 获取当前任务列表
@app.route('/api/current_tasks')
def current_tasks():
"""获取当前正在运行的任务列表"""
if not ai_agent:
return jsonify({"error": "Agent not initialized"}), 503
try:
tasks = ai_agent.get_current_tasks()
return jsonify({
"tasks": tasks,
"count": len(tasks)
})
except Exception as e:
logger.error(f"获取当前任务失败: {str(e)}")
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
logger.info("=" * 50)
logger.info("🚀 启动Web服务: http://0.0.0.0:8000")
app.run(host='0.0.0.0', port=8000)
你再好好看看,不要删那些模块和重要的内容,正常优化 可以吗?这些代码都是我们熬了很久才写出来的 ,非常珍贵,你能理解吗?时间成本,试错成本也是成本
最新发布