import os
import sys
import time
import logging
from dotenv import load_dotenv
# 使用绝对导入
from core.config import system_config
from core.environment import DefaultEnvironment, AIHome, ActionExecutor
from core.environment_interface import EnvironmentInterface
class AutonomousAgent:
def __init__(self):
self.logger = self._setup_logger()
self.logger.info("🔁 初始化自主智能体核心模块...")
try:
# 加载环境变量
load_dotenv()
# 验证环境
self.verify_environment()
# 初始化核心组件
self._initialize_core_components()
# 初始化各子系统
self._initialize_subsystems()
self.logger.info("✅ 自主智能体初始化完成")
except Exception as e:
self.logger.exception(f"❌ 智能体初始化失败")
raise
def verify_environment(self):
"""验证运行环境是否满足要求"""
self.logger.info("🔍 验证运行环境...")
missing = []
# 检查必需模块
required_modules = ['os', 'sys', 'logging', 'dotenv', 'flask', 'werkzeug']
for mod in required_modules:
try:
__import__(mod)
except ImportError:
missing.append(mod)
# 检查配置文件
if not hasattr(system_config, 'CONFIG_PATH') or not os.path.exists(system_config.CONFIG_PATH):
self.logger.error(f"❌ 配置文件缺失: {system_config.CONFIG_PATH}")
missing.append('config_file')
# 检查数据库文件
db_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "database.db")
if not os.path.exists(db_path):
self.logger.error(f"❌ 数据库文件缺失: {db_path}")
missing.append('database_file')
if missing:
raise EnvironmentError(f"环境验证失败,缺失: {', '.join(missing)}")
self.logger.info("✅ 环境验证通过")
def _setup_logger(self):
"""配置日志记录器"""
logger = logging.getLogger('AutonomousAgent')
logger.setLevel(system_config.LOG_LEVEL)
# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(system_config.LOG_LEVEL)
# 创建格式化器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# 添加处理器
logger.addHandler(console_handler)
logger.propagate = False
return logger
def _initialize_core_components(self):
"""初始化不依赖其他组件的核心组件"""
# 获取项目根目录
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 环境相关组件
self.environment = DefaultEnvironment(base_dir)
self.logger.info("✅ 环境接口初始化完成")
self.home = AIHome(base_dir)
self.logger.info("✅ 智能家居环境初始化完成")
self.executor = ActionExecutor()
self.logger.info("✅ 动作执行器初始化完成")
self.env_interface = EnvironmentInterface(base_dir)
self.logger.info("✅ 环境接口(数据库)初始化完成")
# 记录环境状态
try:
env_status = self.environment.get_system_info()
self.logger.info(f"📊 系统状态: OS={env_status.get('os', '未知')}, "
f"CPU={env_status.get('cpu', '0%')}, "
f"内存={env_status.get('memory', '0GB/0GB')}, "
f"磁盘={env_status.get('disk_usage', '0%')}")
except Exception as e:
self.logger.error(f"环境状态获取失败: {str(e)}")
def _initialize_subsystems(self):
"""初始化所有子系统 - 使用绝对导入并添加错误处理"""
try:
# 1. 初始化模型管理器
from core.model_manager import ModelManager
self.model_manager = ModelManager(
model_dir=system_config.MODEL_DIR,
device=system_config.DEVICE,
default_model=system_config.DEFAULT_MODEL
)
self.logger.info("✅ 模型管理器初始化完成")
# 2. 初始化健康系统
from core.health_system import HealthSystem
self.health_system = HealthSystem(self)
self.logger.info("✅ 健康系统初始化完成")
# 3. 初始化记忆系统
from core.memory_system import MemorySystem
self.memory_system = MemorySystem(self)
self.logger.info("✅ 记忆系统初始化完成")
# 4. 初始化情感系统
from core.affective_system import AffectiveSystem
self.affective_system = AffectiveSystem(agent=self)
self.logger.info("✅ 情感系统初始化完成")
# 5. 初始化认知架构
from core.cognitive_architecture import CognitiveArchitecture
self.cognitive_architecture = CognitiveArchitecture(agent=self)
self.logger.info("✅ 认知架构初始化完成")
# 6. 初始化通信系统
from core.communication_system import CommunicationSystem
self.communication_system = CommunicationSystem(
cognitive_system=self.cognitive_architecture,
agent=self
)
self.logger.info("✅ 通信系统初始化完成")
except ImportError as e:
self.logger.error(f"❌ 子模块导入失败: {str(e)}")
raise
except Exception as e:
self.logger.exception(f"❌ 子系统初始化失败")
raise
def process_input(self, user_input, user_id="default"):
"""处理用户输入(通过通信系统)"""
return self.communication_system.process_input(user_input, user_id)
def run_periodic_tasks(self):
"""运行周期性任务"""
# 更新健康状态
self.health_system.update()
# 情感系统更新
self.affective_system.grow()
# 记忆系统维护
self.memory_system.consolidate_memories()
# 修复:环境状态监控 - 使用时间戳
current_time = time.time()
if not hasattr(self, "_last_env_check"):
self._last_env_check = current_time
# 每5分钟检查一次
if current_time - self._last_env_check > 300:
self._last_env_check = current_time
self._monitor_environment()
def _monitor_environment(self):
"""监控环境状态 - 增强健壮性"""
try:
# 安全获取系统信息
env_status = self.environment.get_system_info() or {}
# 安全获取操作系统信息
os_info = env_status.get('os', '未知操作系统')
cpu_usage = env_status.get('cpu', '0%')
# 内存使用解析
memory_info = env_status.get('memory', '0GB/0GB')
used_gb, total_gb, mem_ratio = 0.0, 0.0, 0.0
if isinstance(memory_info, str) and '/' in memory_info:
used, total = memory_info.split('/', 1)
# 移除非数字字符并转换为浮点数
used_gb = float(''.join(filter(lambda c: c.isdigit() or c == '.', used)))
total_gb = float(''.join(filter(lambda c: c.isdigit() or c == '.', total)))
mem_ratio = used_gb / total_gb if total_gb > 0 else 0
# 磁盘使用解析
disk_usage = env_status.get('disk_usage', '0%')
disk_value = 0.0
if isinstance(disk_usage, str):
disk_value = float(''.join(filter(lambda c: c.isdigit() or c == '.', disk_usage)))
# 检查阈值并记录警告
if disk_value > 90:
self.logger.warning(f"⚠️ 磁盘空间不足!当前使用率: {disk_value}%")
if mem_ratio > 0.85:
self.logger.warning(
f"⚠️ 内存使用过高!已用: {used_gb:.1f}GB, "
f"总共: {total_gb:.1f}GB, "
f"使用率: {mem_ratio * 100:.1f}%"
)
# 记录到健康系统
self.health_system.record_environment_status({
'os': os_info,
'cpu': cpu_usage,
'memory': f"{used_gb:.1f}GB/{total_gb:.1f}GB",
'disk_usage': f"{disk_value}%"
})
except Exception as e:
self.logger.error(f"环境监控失败: {str(e)}", exc_info=True)
def get_status(self):
"""获取智能体状态报告"""
# 获取基础状态
status = {
"health": self.health_system.get_status() if hasattr(self, 'health_system') else "未初始化",
"affective": self.affective_system.get_state() if hasattr(self, 'affective_system') else "未初始化",
"memory_stats": self.memory_system.get_stats() if hasattr(self, 'memory_system') else "未初始化",
"model": self.model_manager.get_current_model_info() if hasattr(self, 'model_manager') else "未初始化"
}
# 添加环境信息
try:
env_status = self.environment.get_system_info() if hasattr(self, 'environment') else {}
status["environment"] = {
"os": env_status.get("os", "未知"),
"cpu": env_status.get("cpu", "0%"),
"memory": env_status.get("memory", "0GB/0GB"),
"disk": env_status.get("disk_usage", "0%")
}
except Exception as e:
status["environment"] = {"error": str(e)}
return status
# 环境交互方法
def explore_environment(self, path=None):
"""探索环境目录"""
try:
return self.environment.explore_directory(path) if hasattr(self, 'environment') else {
"error": "环境接口未初始化"}
except Exception as e:
self.logger.error(f"环境探索失败: {str(e)}")
return {"error": str(e)}
def execute_action(self, action, parameters):
"""通过执行器执行动作"""
try:
if not hasattr(self, 'executor'):
return {"status": "error", "message": "执行器未初始化"}
result = self.executor.execute(action, parameters)
self.logger.info(f"执行动作: {action} {parameters} → {result.get('status', '未知')}")
return result
except Exception as e:
self.logger.error(f"动作执行失败: {action} {parameters} - {str(e)}")
return {"status": "error", "message": str(e)}
这是我的autonomous_agent.py,你改好了发我哈 辛苦啦
最新发布