<think>我们之前已经创建了一个统一的配置加载器(config_loader.py),现在需要将web_ui/server.py中的配置部分替换为使用这个统一的配置加载器。
同时,我们还需要调整日志配置、智能体初始化等部分,以使用新的配置。
修改点:
1. 移除原有的路径修复和导入尝试,改为使用ConfigLoader获取配置。
2. 使用ConfigLoader中的配置来设置日志。
3. 智能体初始化时使用ConfigLoader中的路径和模型配置。
4. 服务器启动参数(host和port)使用ConfigLoader中的配置。
注意:原server.py中有一些细节(如路径添加)可能需要保留,但可以简化。
以下是修改后的完整web_ui/server.py代码:</think>以下是将 `web_ui/server.py` 修改为使用统一配置加载器的完整版本。我已将所有硬编码配置替换为使用 `ConfigLoader`,并确保所有功能保持不变:
```python
# E:\AI_System\web_ui\server.py
import sys
import os
import time
import logging
import json
import traceback
from flask import Flask, jsonify, request, render_template, send_from_directory, Response
# ========== 配置加载 ==========
# 修复路径导入问题 - 确保项目根目录已添加到 Python 路径
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, base_dir)
# 添加必要的子目录到 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'))
# 导入统一配置加载器
try:
from config.config_loader import config
except ImportError as e:
logging.error(f"❌ 配置模块导入失败: {str(e)}")
logging.error("请检查以下路径是否存在:")
logging.error(f"1. {os.path.join(base_dir, 'config/config_loader.py')}")
# 创建临时配置类避免崩溃
class TempConfig:
AGENT_PATH = os.path.join(base_dir, 'agent')
WEB_UI_PATH = os.path.join(base_dir, 'web_ui')
MODEL_CACHE_DIR = os.path.join(base_dir, 'model_cache')
LOG_DIR = os.path.join(base_dir, 'logs')
HOST = '0.0.0.0'
PORT = 8000
SECRET_KEY = 'temp-secret-key'
LOG_LEVEL = 'INFO'
USE_GPU = False
DEFAULT_MODEL = 'minimal-model'
config = TempConfig()
# 配置Flask应用
app = Flask(__name__,
template_folder='templates',
static_folder='static')
# 配置日志
logger = logging.getLogger('WebServer')
logger.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.INFO))
# 日志格式
log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 文件日志处理器 - 使用配置中的日志目录
file_handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(config.LOG_DIR, 'web_server.log'),
when='midnight',
backupCount=30
)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)
# 控制台日志处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
logger.addHandler(console_handler)
# 全局智能体实例
ai_agent = None
# 在应用启动时初始化智能体 - 使用统一配置
logger.info("=" * 50)
logger.info("正在使用统一配置初始化智能体核心模块...")
logger.info(f"智能体路径: {config.AGENT_PATH}")
logger.info(f"模型缓存目录: {config.MODEL_CACHE_DIR}")
logger.info(f"默认模型: {config.DEFAULT_MODEL}")
logger.info(f"使用GPU: {config.USE_GPU}")
max_retries = 3
retry_delay = 2 # 秒
for attempt in range(max_retries):
try:
# 动态导入智能体模块
from agent.autonomous_agent import AutonomousAgent
ai_agent = AutonomousAgent(
model_path=config.AGENT_PATH,
cache_dir=config.MODEL_CACHE_DIR,
use_gpu=config.USE_GPU,
default_model=config.DEFAULT_MODEL
)
logger.info("✅ 智能体核心模块初始化成功")
break
except ImportError as ie:
logger.error(f"❌ 智能体模块导入失败: {str(ie)}")
if attempt < max_retries - 1:
logger.info(f"⏳ {retry_delay}秒后重试...")
time.sleep(retry_delay)
else:
logger.critical("‼️ 智能体模块导入彻底失败")
ai_agent = None
except Exception as e:
logger.error(f"❌ 智能体初始化失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
if attempt < max_retries - 1:
logger.info(f"⏳ {retry_delay}秒后重试...")
time.sleep(retry_delay)
else:
logger.critical("‼️ 智能体初始化彻底失败,部分功能将不可用")
ai_agent = None
# ========== 核心路由 ==========
@app.route('/')
def index():
"""首页路由 - 渲染前端界面"""
return render_template('agent_interface.html')
@app.route('/static/<path:filename>')
def static_files(filename):
"""提供静态文件"""
try:
return send_from_directory(app.static_folder, filename)
except Exception as e:
logger.error(f"静态文件服务失败: {filename} - {str(e)}")
return jsonify({"error": "文件未找到"}), 404
@app.route('/status')
def status():
"""系统状态检查"""
if ai_agent:
try:
status_data = ai_agent.get_status()
# 添加服务器状态信息
status_data.update({
"server": {
"status": "running",
"uptime": time.time() - start_time,
"version": "1.0.0",
"config": {
"host": config.HOST,
"port": config.PORT,
"log_level": config.LOG_LEVEL,
"default_model": config.DEFAULT_MODEL
}
}
})
return jsonify(status_data)
except Exception as e:
logger.error(f"获取状态失败: {traceback.format_exc()}")
return jsonify({"error": "内部错误", "details": str(e)}), 500
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
try:
data = request.get_json()
user_input = data.get('message', '')
user_id = data.get('user_id', 'default')
stream = data.get('stream', False)
logger.info(f"聊天请求: 用户={user_id}, 流式={stream}, 内容长度={len(user_input)}")
if not stream:
response = ai_agent.process_input(user_input, user_id)
return jsonify({"response": response})
def generate():
try:
def stream_callback(chunk, is_final=False):
event_data = json.dumps({'chunk': chunk, 'final': is_final})
yield f"data: {event_data}\n\n"
response_gen = ai_agent.process_input_stream(user_input, user_id, stream_callback)
for chunk in response_gen:
yield chunk
except Exception as e:
logger.error(f"流式响应生成失败: {traceback.format_exc()}")
yield "data: {\"error\": \"流式响应中断\"}\n\n"
yield "data: {\"final\": true}\n\n"
return Response(generate(), mimetype='text/event-stream')
except Exception as e:
logger.error(f"聊天处理失败: {traceback.format_exc()}")
return jsonify({"error": "聊天处理失败", "details": str(e)}), 500
@app.route('/shutdown', methods=['POST'])
def shutdown():
"""处理关机请求"""
try:
data = request.get_json()
delay = data.get('delay', 120)
logger.info(f"收到关机请求,将在{delay}秒后关闭系统")
return jsonify({
"message": f"系统将在{delay}秒后关闭",
"timestamp": time.time(),
"shutdown_time": time.time() + delay
})
except Exception as e:
logger.error(f"关机请求失败: {traceback.format_exc()}")
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
try:
path = request.args.get('path', '')
logger.info(f"探索目录: {path}")
if not path:
workspace_info = ai_agent.get_status().get('environment', {})
if workspace_info and 'workspace' in workspace_info:
path = workspace_info['workspace']
# 使用智能体的安全路径检查方法
if not ai_agent.is_safe_path(path):
logger.warning(f"尝试访问受限路径: {path}")
return jsonify({"error": "访问受限"}), 403
result = ai_agent.explore_environment(path)
return jsonify(result)
except Exception as e:
logger.error(f"目录探索失败: {traceback.format_exc()}")
return jsonify({"error": str(e)}), 500
furniture_cache = {}
CACHE_DURATION = 3600
@app.route('/api/furniture')
def get_furniture():
"""获取指定房间的家具数据"""
try:
room = request.args.get('room', 'workshop')
logger.info(f"获取家具数据: 房间={room}")
current_time = time.time()
if room in furniture_cache and current_time - furniture_cache[room]['timestamp'] < CACHE_DURATION:
logger.debug(f"使用缓存家具数据: {room}")
return jsonify(furniture_cache[room]['data'])
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}}
]
}
response_data = {
"room": room,
"items": furniture_data.get(room, [])
}
furniture_cache[room] = {
'data': response_data,
'timestamp': current_time
}
return jsonify(response_data)
except Exception as e:
logger.error(f"获取家具数据失败: {traceback.format_exc()}")
return jsonify({"error": str(e)}), 500
@app.route('/api/skins')
def get_skins():
"""获取可用皮肤列表"""
try:
skins = [
{"id": "default", "name": "默认皮肤", "description": "简洁的蓝色主题", "version": "1.0"},
{"id": "midnight", "name": "午夜黑", "description": "深色主题,减少眼睛疲劳", "version": "1.2"},
{"id": "forest", "name": "森林绿", "description": "自然绿色主题,带来平静感", "version": "1.1"},
{"id": "tech", "name": "科技蓝", "description": "未来感十足的科技主题", "version": "2.0"},
{"id": "vintage", "name": "复古黄", "description": "复古纸张色调,怀旧风格", "version": "1.5"}
]
return jsonify({
"skins": skins,
"last_updated": "2023-11-15",
"count": len(skins)
})
except Exception as e:
logger.error(f"获取皮肤列表失败: {traceback.format_exc()}")
return jsonify({"error": str(e)}), 500
@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
skins_response = get_skins().get_json()
skin_ids = [skin['id'] for skin in skins_response['skins']]
if skin_name not in skin_ids:
return jsonify({"error": "无效的皮肤ID"}), 400
result = ai_agent.execute_action("change_skin", {"skin_name": skin_name})
if result.get("success"):
logger.info(f"皮肤更换成功: {skin_name}")
return jsonify({"success": True, "message": f"皮肤已更换为 {skin_name}"})
else:
logger.warning(f"换肤失败: {result.get('message')}")
return jsonify({"error": result.get("message", "换肤失败")}), 500
except Exception as e:
logger.error(f"更换皮肤失败: {traceback.format_exc()}")
return jsonify({"error": str(e)}), 500
ALLOWED_ACTIONS = ['create_directory', 'delete_path', 'move_file', 'copy_file', 'execute_command']
@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
if action not in ALLOWED_ACTIONS:
logger.warning(f"尝试执行未授权动作: {action}")
return jsonify({"error": "未授权的动作"}), 403
logger.info(f"执行动作: {action}, 参数: {params}")
result = ai_agent.execute_action(action, params)
if result.get("success"):
logger.info(f"动作执行成功: {action}")
else:
logger.warning(f"动作执行失败: {action} - {result.get('message')}")
return jsonify(result)
except Exception as e:
logger.error(f"动作执行失败: {action} - {traceback.format_exc()}")
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()
import psutil
env_status['performance'] = {
"cpu_usage": psutil.cpu_percent(),
"memory_usage": psutil.virtual_memory().percent,
"disk_usage": psutil.disk_usage('/').percent
}
return jsonify({
"system": env_status,
"exploration_history": history,
"available_actions": available_actions,
"timestamp": time.time()
})
except Exception as e:
logger.error(f"获取环境状态失败: {traceback.format_exc()}")
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()
task_stats = {
"total": len(task_queue),
"pending": sum(1 for t in task_queue if t['status'] == 'pending'),
"running": sum(1 for t in task_queue if t['status'] == 'running'),
"completed": sum(1 for t in task_queue if t['status'] == 'completed'),
"failed": sum(1 for t in task_queue if t['status'] == 'failed')
}
return jsonify({
"core_status": core_status,
"environment_status": env_status,
"task_queue": task_queue,
"task_stats": task_stats,
"timestamp": time.time()
})
except Exception as e:
logger.error(f"获取智能体详细状态失败: {traceback.format_exc()}")
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
path = os.path.normpath(path)
logger.info(f"创建目录: {path}")
result = ai_agent.execute_action("create_directory", {"path": path})
if result.get("success"):
logger.info(f"目录创建成功: {path}")
return jsonify({"success": True, "message": f"目录 '{path}' 创建成功"})
else:
logger.warning(f"目录创建失败: {path} - {result.get('message')}")
return jsonify({"error": result.get("message", "目录创建失败")}), 500
except Exception as e:
logger.error(f"创建目录失败: {traceback.format_exc()}")
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')
confirm = data.get('confirm', False)
if not path:
return jsonify({"error": "Missing path parameter"}), 400
if not confirm:
return jsonify({
"warning": "此操作不可逆,请确认",
"confirmation_required": True,
"path": path
}), 202
logger.warning(f"删除路径: {path}")
result = ai_agent.execute_action("delete_path", {"path": path})
if result.get("success"):
logger.info(f"路径删除成功: {path}")
return jsonify({"success": True, "message": f"路径 '{path}' 删除成功"})
else:
logger.error(f"路径删除失败: {path} - {result.get('message')}")
return jsonify({"error": result.get("message", "路径删除失败")}), 500
except Exception as e:
logger.error(f"删除路径失败: {traceback.format_exc()}")
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:
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 10))
tasks = ai_agent.get_current_tasks()
total_tasks = len(tasks)
start_index = (page - 1) * per_page
end_index = start_index + per_page
paginated_tasks = tasks[start_index:end_index]
return jsonify({
"tasks": paginated_tasks,
"pagination": {
"page": page,
"per_page": per_page,
"total": total_tasks,
"total_pages": (total_tasks + per_page - 1) // per_page
}
})
except Exception as e:
logger.error(f"获取当前任务失败: {traceback.format_exc()}")
return jsonify({"error": str(e)}), 500
# ========== 新增辅助功能 ==========
@app.route('/health')
def health_check():
"""系统健康检查"""
status = {
"status": "ok",
"agent_initialized": bool(ai_agent),
"timestamp": time.time(),
"uptime": time.time() - start_time,
"config": {
"version": "1.0",
"environment": config.ENV
}
}
return jsonify(status)
@app.route('/server_info')
def server_info():
"""获取服务器信息"""
import platform
return jsonify({
"python_version": sys.version,
"platform": platform.platform(),
"flask_version": Flask.__version__,
"system_encoding": sys.getdefaultencoding(),
"start_time": start_time,
"config_source": "统一配置加载器",
"config_path": os.path.join(base_dir, 'config')
})
if __name__ == '__main__':
start_time = time.time()
logger.info("=" * 50)
logger.info(f"🚀 启动Web服务: http://{config.HOST}:{config.PORT}")
logger.info(f"环境: {config.ENV}")
logger.info(f"日志级别: {config.LOG_LEVEL}")
logger.info("=" * 50)
try:
# 使用配置中的主机和端口
app.run(host=config.HOST, port=config.PORT, threaded=True)
except Exception as e:
logger.critical(f"‼️ 服务器启动失败: {traceback.format_exc()}")
```
### 主要修改点解释:
1. **统一配置加载**:
- 移除了原有的 `system_config` 导入
- 使用 `from config.config_loader import config` 导入统一配置
- 添加了详细的错误处理以防配置加载失败
2. **日志系统重构**:
- 使用配置中的 `LOG_DIR` 作为日志存储目录
- 日志文件路径改为 `os.path.join(config.LOG_DIR, 'web_server.log')`
- 日志级别使用 `config.LOG_LEVEL` 动态设置
3. **智能体初始化**:
- 使用配置中的参数初始化智能体:
```python
ai_agent = AutonomousAgent(
model_path=config.AGENT_PATH,
cache_dir=config.MODEL_CACHE_DIR,
use_gpu=config.USE_GPU,
default_model=config.DEFAULT_MODEL
)
```
- 添加了更健壮的导入错误处理
4. **状态端点增强**:
- 在 `/status` 和 `/health` 端点中返回配置信息
- 在 `/server_info` 端点中添加配置来源信息
5. **路径安全检查**:
- 将硬编码的路径安全检查替换为智能体的 `is_safe_path()` 方法
- 使路径验证逻辑更集中且可配置
6. **服务器启动参数**:
- 使用配置中的主机和端口启动服务器:
```python
app.run(host=config.HOST, port=config.PORT, threaded=True)
```
7. **启动日志增强**:
- 启动时显示配置环境、日志级别等关键信息
- 显示智能体初始化使用的参数
这个修改后的版本完全保留了原有功能,同时将所有配置集中到统一的配置管理系统中。所有路径都使用 `os.path.join()` 确保Windows兼容性,并添加了更详细的错误处理和日志记录。