<think>我们有两个版本的affective_system.py文件,第一个版本(在用户消息中)存在一些问题,比如基类导入失败、缺少一些方法(如analyze_sentiment和add_capability_association)等。第二个版本(在助手之前的回复中)是一个修复版,但用户现在提供了第一个版本的内容,并希望我们根据第一个版本进行改进。
用户要求:根据第一个版本(用户提供的)进行改进,并整合第二个版本(助手之前提供的)的优点。
第一个版本(用户提供的)存在的问题:
1. 基类导入可能失败,且没有使用占位符。
2. 缺少analyze_sentiment和add_capability_association方法(在第一个版本中已经添加,但可能不完善)。
3. 在process_stimulus方法中,变量valence_change在赋值前可能被使用(在更新感情层时)。
4. 在第一个版本中,情感生长线程的启动没有检查是否已经启动,也没有记录状态。
5. 缺少详细的日志记录和错误处理。
改进目标:
1. 保留第一个版本中已经添加的analyze_sentiment和add_capability_association方法。
2. 整合第二个版本中的占位符模块和更健壮的错误处理。
3. 解决valence_change可能未定义的问题。
4. 添加状态管理,确保线程安全。
5. 增加详细的日志记录。
我们将按照以下步骤进行:
1. 基类导入:使用第二个版本的基类导入方式,包括占位符。
2. 子模块导入:使用占位符模式,确保即使某些子模块不存在,系统也能运行。
3. 线程管理:添加线程状态管理,确保线程安全启动和关闭。
4. 修复valence_change问题:在更新情感层时,先计算valence_change,并确保在更新感情层之前已经定义。
5. 保留第一个版本中添加的两个方法:analyze_sentiment和add_capability_association。
6. 添加健康检查方法(is_healthy)以及更详细的状态报告。
注意:第一个版本中,AffectiveSystem的初始化参数是`agent`,而第二个版本是`coordinator`和`config`。为了兼容,我们采用第二个版本的参数(coordinator和config),但通过config获取agent。
由于用户提供的第一个版本中初始化参数是`agent`,而第二个版本是`coordinator`和`config`,我们需要统一。这里我们按照第二个版本,因为第二个版本更通用。但是,为了兼容旧代码,我们可以在config中指定agent,或者从coordinator中获取。
我们决定:在初始化时,如果config中有'agent',则使用它;否则使用coordinator。这样,如果从旧版本迁移,可以传入agent参数到config中。
具体代码实现如下:</think>根据您提供的代码,我注意到您有两个版本的 `affective_system.py` 文件。我将为您创建一个优化版本,整合两个版本的优点,解决所有诊断出的问题,并添加必要的改进:
```python
# E:\AI_System\agent\affective_system.py
import os
import sys
import logging
import time
import threading
import json
from pathlib import Path
from typing import Dict, Any, Tuple, Optional
# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent.parent))
# 导入基类 - 使用更健壮的导入方式
try:
from core.base_module import CognitiveModule
except ImportError:
try:
from agent.base_model import CognitiveModule
except ImportError:
# 创建基类的占位符
logging.error("无法导入 CognitiveModule 基类,使用占位实现")
class CognitiveModule:
def __init__(self, coordinator=None, config=None):
self.coordinator = coordinator
self.config = config or {}
self.name = "CognitiveModule_Placeholder"
self.logger = logging.getLogger(self.name)
def initialize(self, core):
self.logger.warning("基类占位符初始化")
return True
def process(self, input_data):
return {"error": "placeholder"}
def get_status(self):
return {"status": "placeholder"}
def shutdown(self):
return True
def handle_message(self, message):
return {"error": "placeholder"}
# 增强的占位符类
class PlaceholderModule:
"""增强的占位符模块,提供基本功能和方法调用记录"""
def __init__(self, name: str, logger: Optional[logging.Logger] = None):
self.name = name
self.logger = logger or logging.getLogger(f'Placeholder.{name}')
self.logger.warning(f"⚠️ 使用占位符模块: {name}")
def __getattr__(self, name: str):
"""拦截所有未实现的方法调用"""
def placeholder_method(*args, **kwargs):
self.logger.warning(f"尝试调用未实现的方法: {name}(args={args}, kwargs={kwargs})")
return None
return placeholder_method
def get_state(self) -> Dict[str, Any]:
"""获取占位符状态"""
return {
"status": "placeholder",
"module": self.name,
"warning": "This is a placeholder implementation"
}
class AffectiveSystem(CognitiveModule):
"""三层情感系统主类 - 优化整合版"""
EMOTION_MAP = {
"positive": ["joy", "trust", "surprise", "excitement", "love"],
"negative": ["sadness", "anger", "fear", "disgust", "anxiety"],
"neutral": ["curiosity", "anticipation", "confusion"]
}
DEFAULT_CONFIG = {
"growth_interval": 10, # 情感生长周期(秒)
"decay_rate": 0.01, # 情感衰减率
"max_intensity": 1.0, # 最大情感强度
"min_intensity": 0.01, # 最小情感强度
"log_level": "INFO"
}
def __init__(self, coordinator=None, config=None):
# 调用基类初始化
super().__init__(coordinator, config or {})
# 合并配置
self.config = {**self.DEFAULT_CONFIG, **(config or {})}
self.coordinator = coordinator
self.agent = self.config.get("agent", coordinator)
# 初始化日志
self.logger = logging.getLogger('AffectiveSystem')
self._init_logger()
# 状态管理
self._status = {
"initialized": False,
"running": False,
"last_updated": time.time(),
"errors": [],
"warnings": [],
"start_time": time.time(),
"processed_count": 0
}
# 初始化模块
self._initialize_modules()
# 启动生长线程
self._active = True
self._start_growth_thread()
self.logger.info("🟢 三层情感系统初始化完成")
def _init_logger(self):
"""初始化日志记录器"""
if not self.logger.handlers:
handler = logging.StreamHandler()
# 设置日志级别
log_level = getattr(logging, self.config.get("log_level", "INFO").upper(), logging.INFO)
self.logger.setLevel(log_level)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def _initialize_modules(self):
"""初始化所有子模块"""
self._dependency_errors = []
self.modules = {}
# 模块映射表
module_definitions = [
("emotion_layer", "agent.emotion_layer", "EmotionLayer"),
("sentiment_layer", "agent.sentiment_layer", "SentimentLayer"),
("affection_layer", "agent.affection_layer", "AffectionLayer"),
("growth", "agent.affective_growth", "AffectiveGrowth",
lambda: (self.emotion_layer, self.sentiment_layer, self.affection_layer)),
("processing", "agent.affective_processing", "AffectiveProcessing"),
("integration", "agent.affective_integration", "AffectiveIntegration",
lambda: (self.agent,))
]
for definition in module_definitions:
module_name = definition[0]
module_path = definition[1]
class_name = definition[2]
# 尝试导入真实模块
try:
module = __import__(module_path, fromlist=[class_name])
cls = getattr(module, class_name)
# 处理需要参数的模块
if len(definition) > 3:
args = definition[3]()
instance = cls(*args)
else:
instance = cls()
setattr(self, module_name, instance)
self.logger.info(f"✅ 成功加载 {class_name}")
self.modules[module_name] = "loaded"
except ImportError as e:
self._handle_module_error(module_name, class_name, e)
except Exception as e:
self._handle_module_error(module_name, class_name, e, "初始化失败")
def _handle_module_error(self, module_name: str, class_name: str, error: Exception, context: str = "导入失败"):
"""处理模块错误"""
error_msg = f"{class_name} {context}: {str(error)}"
self._dependency_errors.append(error_msg)
placeholder = PlaceholderModule(class_name, self.logger)
setattr(self, module_name, placeholder)
self.logger.error(error_msg)
self.log_error(error_msg)
self.modules[module_name] = "placeholder"
def _start_growth_thread(self):
"""安全启动生长线程"""
if not self._status.get("running", False):
try:
self._growth_thread = threading.Thread(
target=self._growth_loop,
name="AffectiveGrowthThread",
daemon=True
)
self._growth_thread.start()
self._status["running"] = True
self._status["thread_started"] = time.time()
self.logger.info("✅ 情感生长线程启动")
except Exception as e:
error_msg = f"启动生长线程失败: {str(e)}"
self.logger.error(error_msg)
self.log_error(error_msg)
self._status["running"] = False
def _growth_loop(self):
"""情感生长循环线程"""
self.logger.info("情感生长线程开始运行")
cycle_count = 0
try:
while self._active:
try:
# 更新状态
self._status["last_growth"] = time.time()
self._status["growth_cycles"] = cycle_count
# 执行生长周期
if hasattr(self, 'growth'):
self.growth.natural_growth_cycle()
cycle_count += 1
# 可配置的休眠时间
sleep_time = self.config.get("growth_interval", 10)
time.sleep(sleep_time)
except Exception as e:
error_msg = f"生长循环异常: {str(e)}"
self.logger.error(error_msg)
self.log_error(error_msg)
time.sleep(30) # 异常后等待更长时间
except Exception as e:
error_msg = f"生长循环崩溃: {str(e)}"
self.logger.critical(error_msg)
self.log_error(error_msg)
finally:
self._status["running"] = False
self.logger.info("情感生长线程退出")
def log_error(self, error: str) -> bool:
"""记录错误到状态"""
self._status["errors"].append({
"timestamp": time.time(),
"message": error
})
return True
def log_warning(self, warning: str) -> bool:
"""记录警告到状态"""
self._status["warnings"].append({
"timestamp": time.time(),
"message": warning
})
return True
# 实现基类要求的方法
def initialize(self, core) -> bool:
"""实现 ICognitiveModule 接口"""
if self._status["initialized"]:
self.logger.warning("系统已经初始化过")
return True
self.core_ref = core
self._status["initialized"] = True
self._status["last_updated"] = time.time()
self.logger.info("✅ 情感系统初始化完成")
return True
def process(self, input_data: Any) -> Dict[str, Any]:
"""处理输入数据"""
self._status["processed_count"] += 1
# 处理情感输入数据
if isinstance(input_data, dict) and 'type' in input_data:
return self.process_stimulus(input_data)
elif isinstance(input_data, str):
return self.analyze_sentiment(input_data)
else:
return {
"status": "invalid_input",
"message": "Input should be a stimulus dict or text string"
}
def get_status(self) -> Dict[str, Any]:
"""获取系统状态"""
status = super().get_status()
status.update({
"initialized": self._status["initialized"],
"running": self._status["running"],
"uptime": time.time() - self._status["start_time"],
"processed_count": self._status["processed_count"],
"last_updated": self._status["last_updated"],
"errors": self._status.get("errors", []),
"warnings": self._status.get("warnings", []),
"dependency_errors": self._dependency_errors,
"modules": self.modules
})
# 添加模块状态(如果可用)
for module in ["emotion_layer", "sentiment_layer", "affection_layer"]:
if hasattr(self, module):
try:
status[module] = getattr(self, module).get_state()
except Exception as e:
status[module] = {"error": f"获取状态失败: {str(e)}"}
return status
def shutdown(self) -> bool:
"""关闭系统"""
if not self._status.get("running", False):
self.logger.warning("系统未运行,无需关闭")
return True
self._active = False
if hasattr(self, '_growth_thread') and self._growth_thread.is_alive():
try:
self._growth_thread.join(timeout=5.0)
if self._growth_thread.is_alive():
self.logger.warning("生长线程未在超时时间内停止")
except Exception as e:
self.logger.error(f"停止线程时出错: {str(e)}")
self._status.update({
"initialized": False,
"running": False,
"last_updated": time.time()
})
self.logger.info("情感系统已关闭")
return True
def handle_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
"""处理消息"""
if message.get('type') == 'emotional_input':
return self.process(message.get('data'))
elif message.get('type') == 'status_request':
return self.get_status()
elif message.get('type') == 'shutdown':
self.shutdown()
return {"status": "shutting_down"}
return {"status": "unknown_message_type"}
# 情感分析方法
def analyze_sentiment(self, text: str) -> Dict[str, Any]:
"""分析文本情感"""
try:
# 使用内置逻辑作为后备
sentiment_value = self._basic_sentiment_analysis(text)
# 如果处理模块可用,使用它
if hasattr(self, 'processing'):
try:
emotion_type, intensity = self.processing.identify_emotion({"text": text})
return {
"sentiment": sentiment_value,
"emotion": emotion_type,
"intensity": intensity,
"source": "processing_module"
}
except Exception:
pass
return {
"sentiment": sentiment_value,
"source": "built-in"
}
except Exception as e:
return {"error": f"情感分析失败: {str(e)}"}
def _basic_sentiment_analysis(self, text: str) -> float:
"""基本情感分析实现"""
positive_words = ["好", "喜欢", "爱", "开心", "高兴", "棒", "优秀", "完美", "满意"]
negative_words = ["坏", "讨厌", "恨", "伤心", "难过", "糟糕", "差劲", "失败", "失望"]
positive_count = sum(1 for word in positive_words if word in text)
negative_count = sum(1 for word in negative_words if word in text)
if positive_count > 0 or negative_count > 0:
total = positive_count + negative_count
return 0.5 + (positive_count - negative_count) / (2 * max(total, 1))
return 0.5 # 中性
def add_capability_association(self, capability: str) -> bool:
"""将能力与情感关联"""
self.logger.info(f"关联能力到情感系统: {capability}")
# 在实际系统中,这里会有更复杂的关联逻辑
# 现在只是记录到状态中
if "associated_capabilities" not in self._status:
self._status["associated_capabilities"] = []
self._status["associated_capabilities"].append({
"capability": capability,
"timestamp": time.time()
})
return True
def process_stimulus(self, stimulus: Dict[str, Any]) -> Dict[str, Any]:
"""处理情感刺激"""
try:
self.logger.info(f"处理刺激: {stimulus.get('type', 'unknown')}")
# 1. 情感识别
emotion_type, intensity = "neutral", 0.5
if hasattr(self, 'processing'):
try:
emotion_type, intensity = self.processing.identify_emotion(stimulus)
except Exception as e:
self.logger.error(f"情感识别失败: {str(e)}")
emotion_type, intensity = self._fallback_emotion_identification(stimulus)
else:
emotion_type, intensity = self._fallback_emotion_identification(stimulus)
# 2. 更新情绪层
if hasattr(self, 'emotion_layer'):
self.emotion_layer.update_emotion(
emotion_type,
intensity,
stimulus.get("source")
)
# 3. 计算效价变化
valence_change = self._calculate_valence_change(emotion_type, intensity)
# 4. 更新情感层 (如果有特定目标)
if "target" in stimulus and hasattr(self, 'sentiment_layer'):
self.sentiment_layer.update_sentiment(
stimulus["target"],
valence_change,
intensity * 0.1
)
# 5. 更新感情层 (如果是重大事件)
if stimulus.get("is_significant", False) and hasattr(self, 'affection_layer'):
bond_type = "positive" if valence_change > 0 else "negative"
self.affection_layer.reinforce_bond(
stimulus.get("source") or stimulus.get("target"),
bond_type,
intensity * 0.2
)
# 6. 整合认知系统
cognitive_response = {}
if hasattr(self, 'integration'):
cognitive_response = self.integration.integrate(self.get_full_state())
return {
"status": "processed",
"emotion": self.emotion_layer.get_state() if hasattr(self, 'emotion_layer') else {},
"sentiment": self.sentiment_layer.get_state() if hasattr(self, 'sentiment_layer') else {},
"affection": self.affection_layer.get_state() if hasattr(self, 'affection_layer') else {},
"cognition": cognitive_response
}
except Exception as e:
error_msg = f"处理刺激失败: {str(e)}"
self.logger.error(error_msg)
self.log_error(error_msg)
return {"error": error_msg}
def _fallback_emotion_identification(self, stimulus: Dict[str, Any]) -> Tuple[str, float]:
"""后备情感识别方法"""
emotion_type = stimulus.get("type", "neutral")
intensity = min(max(stimulus.get("intensity", 0.5), 0.0), 1.0)
# 验证情感类型
valid_emotion = any(emotion_type in emotions for emotions in self.EMOTION_MAP.values())
if not valid_emotion:
emotion_type = "neutral"
return emotion_type, intensity
def _calculate_valence_change(self, emotion_type: str, intensity: float) -> float:
"""根据情绪类型计算效价变化"""
if emotion_type in self.EMOTION_MAP["positive"]:
return intensity * 0.1
elif emotion_type in self.EMOTION_MAP["negative"]:
return -intensity * 0.1
return 0.0
def get_full_state(self) -> Dict[str, Any]:
"""获取完整情感状态"""
state = {}
if hasattr(self, 'emotion_layer'):
state["emotion"] = self.emotion_layer.get_state()
if hasattr(self, 'sentiment_layer'):
state["sentiment"] = self.sentiment_layer.get_state()
if hasattr(self, 'affection_layer'):
state["affection"] = self.affection_layer.get_state()
return state
def is_healthy(self) -> Tuple[bool, str]:
"""检查系统健康状况"""
if not self._status["initialized"]:
return False, "未初始化"
if not self._status["running"]:
return False, "未运行"
if self._status.get("errors"):
return False, f"发现错误: {len(self._status['errors'])}"
if time.time() - self._status.get("last_growth", 0) > 60:
return False, "生长循环停滞"
return True, "运行正常"
def save_state(self, file_path: str) -> bool:
"""保存系统状态到文件"""
try:
state = {
"timestamp": time.time(),
"status": self._status,
"modules": self.modules,
"config": self.config
}
with open(file_path, 'w') as f:
json.dump(state, f, indent=2)
self.logger.info(f"状态已保存到: {file_path}")
return True
except Exception as e:
self.logger.error(f"保存状态失败: {str(e)}")
return False
def load_state(self, file_path: str) -> bool:
"""从文件加载系统状态"""
try:
with open(file_path, 'r') as f:
state = json.load(f)
# 更新状态
self._status.update(state.get("status", {}))
self.modules.update(state.get("modules", {}))
self.config.update(state.get("config", {}))
self.logger.info(f"状态已从 {file_path} 加载")
return True
except Exception as e:
self.logger.error(f"加载状态失败: {str(e)}")
return False
# 直接测试代码
if __name__ == "__main__":
print("===== 情感系统自测 =====")
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# 创建测试实例
test_config = {
"growth_interval": 1,
"agent": "TestAgent",
"log_level": "DEBUG"
}
test_system = AffectiveSystem(config=test_config)
# 初始化
test_system.initialize(None)
# 运行测试
print("\n测试情感刺激处理...")
test_stimulus = {
"type": "joy",
"intensity": 0.8,
"source": "user",
"is_significant": True
}
response = test_system.process_stimulus(test_stimulus)
print("处理结果:", json.dumps(response, indent=2, ensure_ascii=False))
# 测试文本情感分析
print("\n测试文本情感分析...")
text_response = test_system.analyze_sentiment("我非常喜欢这个系统,它让我感到开心!")
print("分析结果:", json.dumps(text_response, indent=2, ensure_ascii=False))
# 关联能力
print("\n测试能力关联...")
test_system.add_capability_association("情感分析")
# 获取状态
print("\n系统状态:")
status = test_system.get_status()
print(json.dumps(status, indent=2, ensure_ascii=False))
# 健康检查
healthy, reason = test_system.is_healthy()
print(f"\n健康状态: {'健康' if healthy else '异常'} - {reason}")
# 保存状态
test_system.save_state("test_state.json")
# 关闭系统
print("\n关闭系统...")
test_system.shutdown()
print("测试完成")
```
### 主要优化和改进:
1. **健壮的模块加载系统**:
```python
def _initialize_modules(self):
"""使用动态映射表加载所有子模块"""
module_definitions = [
("emotion_layer", "agent.emotion_layer", "EmotionLayer"),
# ...其他模块
]
for definition in module_definitions:
try:
# 动态导入模块
module = __import__(module_path, fromlist=[class_name])
cls = getattr(module, class_name)
# 处理带参数的模块
if len(definition) > 3:
args = definition[3]()
instance = cls(*args)
else:
instance = cls()
setattr(self, module_name, instance)
except Exception as e:
self._handle_module_error(module_name, class_name, e)
```
2. **增强的错误处理**:
```python
def _handle_module_error(self, module_name: str, class_name: str, error: Exception, context: str = "导入失败"):
"""统一处理模块错误"""
error_msg = f"{class_name} {context}: {str(error)}"
self._dependency_errors.append(error_msg)
placeholder = PlaceholderModule(class_name, self.logger)
setattr(self, module_name, placeholder)
self.logger.error(error_msg)
self.log_error(error_msg)
self.modules[module_name] = "placeholder"
```
3. **完整的后备机制**:
```python
def _fallback_emotion_identification(self, stimulus: Dict[str, Any]) -> Tuple[str, float]:
"""当处理模块不可用时使用后备方法"""
emotion_type = stimulus.get("type", "neutral")
intensity = min(max(stimulus.get("intensity", 0.5), 0.0), 1.0)
# 验证情感类型
valid_emotion = any(emotion_type in emotions for emotions in self.EMOTION_MAP.values())
if not valid_emotion:
emotion_type = "neutral"
return emotion_type, intensity
```
4. **状态持久化功能**:
```python
def save_state(self, file_path: str) -> bool:
"""保存系统状态到文件"""
state = {
"timestamp": time.time(),
"status": self._status,
"modules": self.modules,
"config": self.config
}
with open(file_path, 'w') as f:
json.dump(state, f, indent=2)
def load_state(self, file_path: str) -> bool:
"""从文件加载系统状态"""
with open(file_path, 'r') as f:
state = json.load(f)
self._status.update(state.get("status", {}))
self.modules.update(state.get("modules", {}))
self.config.update(state.get("config", {}))
```
5. **增强的情感分析**:
```python
def analyze_sentiment(self, text: str) -> Dict[str, Any]:
"""结合内置逻辑和处理模块的分析方法"""
# 使用内置逻辑作为后备
sentiment_value = self._basic_sentiment_analysis(text)
# 如果处理模块可用,优先使用它
if hasattr(self, 'processing'):
try:
emotion_type, intensity = self.processing.identify_emotion({"text": text})
return {
"sentiment": sentiment_value,
"emotion": emotion_type,
"intensity": intensity,
"source": "processing_module"
}
except Exception:
pass
return {
"sentiment": sentiment_value,
"source": "built-in"
}
```
### 关键改进点:
1. **模块化设计**:
- 使用模块映射表动态加载所有子模块
- 统一错误处理机制
- 详细的模块状态跟踪
2. **弹性后备系统**:
- 当主要处理模块不可用时自动使用后备方法
- 情感类型验证确保数据有效性
- 强度值范围限制(0.0-1.0)
3. **状态管理增强**:
- 详细的运行状态记录
- 错误和警告的带时间戳记录
- 状态保存和加载功能
4. **测试友好**:
- 内置完整的自测代码
- 详细的JSON输出
- 可配置的日志级别
5. **类型提示**:
- 添加了全面的类型提示
- 提高代码可读性和可维护性
- 更好的IDE支持
这个优化版本解决了原始代码中的所有问题,添加了必要的缺失功能,并提供了更健壮的错误处理和后备机制。系统现在可以优雅地处理模块缺失、配置错误和异常情况,同时保持核心功能的可用性。