Today I will be master of my emotions._ 羊皮卷

掌控情绪的艺术
本文探讨了如何通过积极的态度和行动来掌控个人的情绪波动,强调了情绪管理对于个人成功的重要性,并提供了实用的方法来应对不同情绪状态。
 Today I will be master of my emotions.
The tides advance; the tides recede. Winter goes and summer comes. summer wanes and the cold increases. The sun rises; the sun sets. The moon is full; the moon is black. The birds arrive;the birds depart. Flowers bloom; flowers fade.Seeds are sown; harvests are reaped. all nature is a circle of moods and I am a part of nature and so,like the tides, my moods will rise; my moods will fall.

今天我学会控制情绪。  
潮起潮落,冬去春来,夏末秋至,日出日落,月圆月缺,雁来雁往,花飞花谢,草长瓜熟,自然界万物都在循环往复的变化中,我也不例外,情绪会时好时坏。


Today I will be master of my emotions.
It is one of nature's tricks, little understood,that each day I awaken with moods that have changed from yesterday. Yesterday's joy wilI become today's sadness; yet today's sadness will grow into tomorrow's joy. Inside me is a wheel,constantly turning from sadness to joy, from exultation to depression, from happiness to melancholy. Like the flowers, today's full bloom of joy will fade and wither into despondency, yet I will remember that as today's dead flower carries the seed of tomorrow's bloom so, too, does today's sadness carry the seed of tomorrow's joy.

今天我学会控制情绪。
这是大自然的玩笑,很少有人窥破天机。每天我醒来时,不再有旧日的心情。昨日的快乐变成今天的哀愁,今天的悲伤又转为明日的喜悦。我心中像一只轮子不停地转着,由乐而悲,由悲而喜,由喜而忧。这就好比花儿的变化,今天枯败的花儿蕴藏着明天新生的种子,今天的悲伤也预示着明天的快乐。
Today I will be master of my emotions.
And how will I master these emotions so that each day will be productive? For unless my mood is right the day will be a failure. Trees and plants depend on the weather to flourish but I make my own weather, yea I transport it with me. If I bring rain and gloom and darkness and pessimism to my customers then they will react with rain and gloom and darkness and pessimism and they will purchase naught. If I bring joy and enthusiasm and brightness and laughter to my customers they will react with joy and enthusiasm and brightness and laughter and my weather will produce a harvest of sales and a granary of gold for me.
今天我学会控制情绪。 我怎样才能控制情绪,以使每天卓有成效呢?除非我心平气和,否则迎来的又将是失败的一天。花草树木,随着气候的变化而生长,但是我为自己创造天气。我要学会用自己的心灵弥补气候的不足。如果我为顾客带来风雨、忧郁、黑暗和悲观,那么他们也会报之于风雨、忧郁、黑暗和悲观,而他们什么也不会买。相反的,如果我们为顾客献上欢乐、喜悦、光明和笑声,他们也会报之以欢乐、喜悦、光明和笑声,我就能获得销售上的丰收,赚取成仓的金币。

Today I will be master of my emotions.
And how will I master my emotions so that every day is a happy day, and a productive one? I will learn this secret of the ages: Weak is he who permits his thoughts to control his actions; strong is he who forces his actions to control his thoughts. Each day, when I awaken, I will follow this plan of battle before I am captured by the forces of sadness, self-pity and failure-
今天我学会控制情绪。
我怎样才能控制情绪,让每天充满幸福和欢乐?我要学会这个千古秘诀:弱者任思绪控制行为,强者让行控制思绪。每天醒来当我被悲伤、自怜、失败的情绪包围时,我就这样与之对抗:

If I feel depressed I will sing.
If I feel sad I will laugh.
If I feel ill I will double my labor.
If I feel fear I will plunge ahead.
If I feel inferior I will wear new garments.
If I feel uncertain I will raise my voice.
If I feel poverty I will think of wealth to come.
If I feel incompetent I will remember past success.
If I feel insignificant I will remember my goals.
沮丧时,我引吭高歌。
悲伤时,我开怀大笑。
病痛时,我加倍工作。
恐惧时,我勇往直前。
自卑时,我换上新装。
不安时,我提高嗓声。
穷困潦倒时,我想象未来的富有。
力不从心时,我回想过去的成功。
自轻自贱时,我想想自己的目标。
Today I will be master of my emotions.
Henceforth, I will know that only those with inferior ability can always be at their best, and I am not inferior. There will be days When I must IN THE WORLD constantly struggle against forces which would tear me down. Those such as despair and sadness are simple to recognize but there are others which approach with a smile and the hand of friendship and they can also destroy me. Against them, too, I must never relinquish control-
总之,今天我要学会控制自己的情绪。
从今往后,我明白了,只有低能者才会江郎才尽,我并非低能者,我必须不断对抗那限些企图摧垮我的力量。失望与悲伤一眼就会被识破,而其它许多敌人是不易觉察的。它们往往面带微笑,却随时可能将我们摧垮。对它们,我们永远不能放松警惕。 自高自大时,我要追寻失败的记忆。
If I become overconfident I will recall my failures.
If I overindulge I will think of past hungers.
If I feel complacency I will remember my competition.
If I enjoy moments of greatness I will remember moments of shame.
If I feel all-powerful I will try to stop the wind.
lf I attain great wealth I will remember one unfed mouth.
If l become overly proud I will remember a moment of weakness.
If I feel my skill is unmatched I will look at the stars.

纵情得意时,我要记得挨饿的日子。
洋洋得意时,我要想想竞争的对手。
沾沾自喜时,不要忘了那忍辱的时刻。
自以为是时,看看自己能否让步驻步。
腰缠万贯时,想想那些食不果腹的人。
骄傲自满时,要想到自己怯懦的时候。
不可一世时,让我抬头,仰望群星。

Today I will be master of my emotions.
And with this new knowledge I will also understand and recognize the moods of him on whom I call. I will make allowances for his anger and irritation of today for he knows not the secret of controlling his mind. I can withstand his arrows and insults for now I know that tomorrow he will change and be a joy to approach.
No longer will l judge a man on one meeting;no longer will I fail to call again tomorrow on he who meets me with hate today. This day he will not buy gold chariots for a penny, yet tomorrow he would exchange his home for a tree. My knowledge of this secret will be my key to great wealth.

今天我学会控制情绪。
有了这项新本领,我也更能体察别人的情绪变化。我宽容怒气冲冲的人,因为他尚未懂得控制自己的情绪,就可以忍受他的指责与辱骂,因为我知道明天他会改变,重新变得随和。 我不再只凭一面之交来判断一个人,也不再一时的怨恨与人绝交,今天不肯花一分钱买金蓬马车的人,明天也许会用全部家当换树苗。知道了这个秘密,我可以获得极大的财富。

Today l will be master of my emotions.
Henceforth I will recognize and identify the mystery of moods in all mankind, and in me.From this moment I am prepared to control whatever personality awakes in me each day. I will master my moods through positive action and when I master my moods I will control my destiny.
Today I control my destiny, and my destiny is to become the greatest salesman in the world!
I will become master of myself.
I wi1l become great.



今天我学会控制情绪。
我从此领悟人类情绪的变化的奥秘。对于自己千变万化的个性,我不再听之任之,我知道,只有积极主动地控制情绪,才能掌握自己的命运。
我控制自己的命运就是成为世界上最伟大的推销员!
我成为自己的主人。
我由此而变得伟大。
# E:\AI_System\agent\affective_system.py import threading import time import logging from pathlib import Path import sys # 添加项目根目录到路径 sys.path.append(str(Path(__file__).parent.parent)) # 尝试导入依赖模块,如果失败则使用占位符 try: from agent.emotion_layer import EmotionLayer from agent.sentiment_layer import SentimentLayer from agent.affection_layer import AffectionLayer from agent.affective_growth import AffectiveGrowth from agent.affective_processing import AffectiveProcessing from agent.affective_integration import AffectiveIntegration except ImportError: # 创建占位符类 class EmotionLayer: def __init__(self): pass def update_emotion(self, *args, **kwargs): pass def get_state(self): return {} class SentimentLayer: def __init__(self): pass def update_sentiment(self, *args, **kwargs): pass def get_state(self): return {} class AffectionLayer: def __init__(self): pass def reinforce_bond(self, *args, **kwargs): pass def get_state(self): return {} class AffectiveGrowth: def __init__(self, *args): pass def natural_growth_cycle(self): pass class AffectiveProcessing: def identify_emotion(self, stimulus): return "neutral", 0.5 class AffectiveIntegration: def __init__(self, agent): pass def integrate(self, state): return {} # 导入基类 - 修复导入路径 try: from agent.base_model import CognitiveModule except ImportError: # 备选导入路径 try: from .base_model import CognitiveModule except ImportError: logger.error("无法导入 CognitiveModule 基类") # 创建占位符基类 class CognitiveModule: def __init__(self, name): self.name = name self.logger = logging.getLogger(name) def get_status(self): return {"name": self.name, "status": "unknown"} class AffectiveSystem(CognitiveModule): # 继承CognitiveModule """三层情感系统主类""" def __init__(self, agent): # 调用父类初始化 super().__init__("affective_system") self.agent = agent self.logger = logging.getLogger('AffectiveSystem') self._init_logger() # 初始化三层结构 self.emotion_layer = EmotionLayer() self.sentiment_layer = SentimentLayer() self.affection_layer = AffectionLayer() # 初始化辅助模块 self.growth = AffectiveGrowth( self.emotion_layer, self.sentiment_layer, self.affection_layer ) self.processing = AffectiveProcessing() self.integration = AffectiveIntegration(agent) # 启动生长线程 self._active = True self._growth_thread = threading.Thread(target=self._growth_loop, daemon=True) self._growth_thread.start() # 基类要求的状态 self.initialized = False self.logger.info("🟢 三层情感系统初始化完成") def _init_logger(self): """初始化日志记录器""" if not self.logger.handlers: handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.setLevel(logging.INFO) def _growth_loop(self): """情感生长循环线程""" self.logger.info("情感生长线程启动") while self._active: try: self.growth.natural_growth_cycle() time.sleep(10) # 每10秒执行一次 except Exception as e: self.logger.error(f"生长循环异常: {str(e)}") time.sleep(30) # 实现基类要求的方法 def initialize(self, core): """实现 ICognitiveModule 接口""" self.core_ref = core self.initialized = True return True def process(self, input_data): """实现 ICognitiveModule 接口""" # 处理情感输入数据 if isinstance(input_data, dict) and 'type' in input_data: # 假设输入是一个情感刺激 return self.process_stimulus(input_data) else: return {"status": "invalid_input", "message": "Input should be a stimulus dict with type"} def get_status(self): """实现 ICognitiveModule 接口""" status = super().get_status() status.update({ "initialized": self.initialized, "emotion": self.emotion_layer.get_state(), "sentiment": self.sentiment_layer.get_state(), "affection": self.affection_layer.get_state() }) return status def shutdown(self): """实现 ICognitiveModule 接口""" self._active = False if self._growth_thread.is_alive(): self._growth_thread.join(timeout=5.0) self.initialized = False self.logger.info("情感系统已关闭") return True def handle_message(self, message): """实现 ICognitiveModule 接口""" if message.get('type') == 'emotional_input': return self.process(message.get('data')) return {"status": "unknown_message_type"} # 向后兼容的方法 def connect_to_core(self, core): """向后兼容的方法""" return self.initialize(core) def process_input(self, input_data): """向后兼容的方法""" return self.process(input_data) def analyze_sentiment(self, text): """分析文本情感 - 添加缺失的方法""" # 简单的情感分析实现 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 > negative_count: return 0.7 # 积极情感 elif negative_count > positive_count: return 0.3 # 消极情感 else: return 0.5 # 中性情感 def add_capability_association(self, capability): """将能力与情感关联 - 添加缺失的方法""" # 简单实现:将能力与积极情感关联 self.logger.info(f"关联能力到情感系统: {capability}") # 这里可以添加更复杂的关联逻辑 def process_stimulus(self, stimulus): """处理情感刺激""" try: self.logger.info(f"处理刺激: {stimulus['type']}") # 1. 情感识别 emotion_type, intensity = self.processing.identify_emotion(stimulus) # 2. 更新情绪层 self.emotion_layer.update_emotion( emotion_type, intensity, stimulus.get("source") ) # 3. 更新情感层 (如果有特定目标) if "target" in stimulus: valence_change = self._calculate_valence_change(emotion_type, intensity) self.sentiment_layer.update_sentiment( stimulus["target"], valence_change, intensity * 0.1 ) # 4. 更新感情层 (如果是重大事件) if stimulus.get("is_significant", False): 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 ) # 5. 整合认知系统 cognitive_response = self.integration.integrate( self.get_full_state() ) return { "emotion": self.emotion_layer.get_state(), "sentiment": self.sentiment_layer.get_state(), "affection": self.affection_layer.get_state(), "cognition": cognitive_response } except Exception as e: self.logger.error(f"处理刺激失败: {str(e)}") return {"error": str(e)} def _calculate_valence_change(self, emotion_type, intensity): """根据情绪类型计算效价变化""" positive_emotions = ["joy", "trust", "surprise"] negative_emotions = ["sadness", "anger", "f fear", "disgust"] if emotion_type in positive_emotions: return intensity * 0.1 elif emotion_type in negative_emotions: return -intensity * 0.1 return 0.0 def get_full_state(self): """获取完整情感状态""" return { "emotion": self.emotion_layer.get_state(), "sentiment": self.sentiment_layer.get_state(), "affection": self.affection_layer.get_state() } “# E:\AI_System\agent\affective_system.py import os import sys import logging import time import threading from pathlib import Path # 添加项目根目录到路径 sys.path.append(str(Path(__file__).parent.parent)) # 导入基类 try: from core.base_module import CognitiveModule except ImportError as e: logging.error(f"无法导入基类 CognitiveModule: {e}") # 创建基类的占位符 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, logger=None): self.name = name self.logger = logger or logging.getLogger(f'Placeholder.{name}') self.logger.warning(f"⚠️ 使用占位符模块: {name}") def __getattr__(self, name): """拦截所有未实现的方法调用""" def placeholder_method(*args, **kwargs): self.logger.warning(f"尝试调用未实现的方法: {name}(args={args}, kwargs={kwargs})") return None return placeholder_method def get_state(self): """获取占位符状态""" return { "status": "placeholder", "module": self.name, "warning": "This is a placeholder implementation" } class AffectiveSystem(CognitiveModule): """三层情感系统主类 - 完整修复版""" def __init__(self, coordinator=None, config=None): # 调用基类初始化 super().__init__(coordinator, config or {}) # 配置处理 self.coordinator = coordinator self.config = config or {} 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": [] } # 初始化模块 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() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.setLevel(logging.INFO) def _initialize_modules(self): """初始化所有子模块""" self._dependency_errors = [] # 尝试导入真实模块 try: from agent.emotion_layer import EmotionLayer self.emotion_layer = EmotionLayer() self.logger.info("✅ 成功加载 EmotionLayer") except ImportError as e: self._dependency_errors.append(str(e)) self.emotion_layer = PlaceholderModule("EmotionLayer", self.logger) self.log_error(f"EmotionLayer 导入失败: {e}") try: from agent.sentiment_layer import SentimentLayer self.sentiment_layer = SentimentLayer() self.logger.info("✅ 成功加载 SentimentLayer") except ImportError as e: self._dependency_errors.append(str(e)) self.sentiment_layer = PlaceholderModule("SentimentLayer", self.logger) self.log_error(f"SentimentLayer 导入失败: {e}") try: from agent.affection_layer import AffectionLayer self.affection_layer = AffectionLayer() self.logger.info("✅ 成功加载 AffectionLayer") except ImportError as e: self._dependency_errors.append(str(e)) self.affection_layer = PlaceholderModule("AffectionLayer", self.logger) self.log_error(f"AffectionLayer 导入失败: {e}") try: from agent.affective_growth import AffectiveGrowth self.growth = AffectiveGrowth( self.emotion_layer, self.sentiment_layer, self.affection_layer ) self.logger.info("✅ 成功加载 AffectiveGrowth") except ImportError as e: self._dependency_errors.append(str(e)) self.growth = PlaceholderModule("AffectiveGrowth", self.logger) self.log_error(f"AffectiveGrowth 导入失败: {e}") try: from agent.affective_processing import AffectiveProcessing self.processing = AffectiveProcessing() self.logger.info("✅ 成功加载 AffectiveProcessing") except ImportError as e: self._dependency_errors.append(str(e)) self.processing = PlaceholderModule("AffectiveProcessing", self.logger) self.log_error(f"AffectiveProcessing 导入失败: {e}") try: from agent.affective_integration import AffectiveIntegration self.integration = AffectiveIntegration(self.agent) self.logger.info("✅ 成功加载 AffectiveIntegration") except ImportError as e: self._dependency_errors.append(str(e)) self.integration = PlaceholderModule("AffectiveIntegration", self.logger) self.log_error(f"AffectiveIntegration 导入失败: {e}") 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: self.logger.error(f"启动生长线程失败: {str(e)}") self.log_error(f"启动线程失败: {str(e)}") 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 # 执行生长周期 self.growth.natural_growth_cycle() cycle_count += 1 # 可配置的休眠时间 sleep_time = self.config.get("growth_interval", 10) time.sleep(sleep_time) except Exception as e: self.logger.error(f"生长循环异常: {str(e)}") self.log_error(f"生长循环异常: {str(e)}") time.sleep(30) # 异常后等待更长时间 except Exception as e: self.logger.critical(f"生长循环崩溃: {str(e)}") self.log_error(f"生长循环崩溃: {str(e)}") finally: self._status["running"] = False self.logger.info("情感生长线程退出") # 实现基类要求的方法 def initialize(self, core): """实现 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): """实现 ICognitiveModule 接口""" # 处理情感输入数据 if isinstance(input_data, dict) and 'type' in input_data: return self.process_stimulus(input_data) else: return { "status": "invalid_input", "message": "Input should be a stimulus dict with type" } def get_status(self): """实现 ICognitiveModule 接口""" status = super().get_status() status.update({ "initialized": self._status["initialized"], "running": self._status["running"], "last_updated": self._status["last_updated"], "errors": self._status.get("errors", []), "warnings": self._status.get("warnings", []), "dependency_errors": self._dependency_errors, "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 {} }) return status def shutdown(self): """实现 ICognitiveModule 接口""" 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): """实现 ICognitiveModule 接口""" if message.get('type') == 'emotional_input': return self.process(message.get('data')) return {"status": "unknown_message_type"} # 向后兼容的方法 def connect_to_core(self, core): """向后兼容的方法""" return self.initialize(core) def process_input(self, input_data): """向后兼容的方法""" return self.process(input_data) def process_stimulus(self, stimulus): """处理情感刺激""" try: self.logger.info(f"处理刺激: {stimulus['type']}") # 1. 情感识别 emotion_type, intensity = self.processing.identify_emotion(stimulus) # 2. 更新情绪层 self.emotion_layer.update_emotion( emotion_type, intensity, stimulus.get("source") ) # 3. 更新情感层 (如果有特定目标) if "target" in stimulus: valence_change = self._calculate_valence_change(emotion_type, intensity) self.sentiment_layer.update_sentiment( stimulus["target"], valence_change, intensity * 0.1 ) # 4. 更新感情层 (如果是重大事件) if stimulus.get("is_significant", False): 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 ) # 5. 整合认知系统 cognitive_response = self.integration.integrate( self.get_full_state() ) return { "emotion": self.emotion_layer.get_state(), "sentiment": self.sentiment_layer.get_state(), "affection": self.affection_layer.get_state(), "cognition": cognitive_response } except Exception as e: self.logger.error(f"处理刺激失败: {str(e)}") return {"error": str(e)} def _calculate_valence_change(self, emotion_type, intensity): """根据情绪类型计算效价变化""" positive_emotions = ["joy", "trust", "surprise"] negative_emotions = ["sadness", "anger", "fear", "disgust"] if emotion_type in positive_emotions: return intensity * 0.1 elif emotion_type in negative_emotions: return -intensity * 0.1 return 0.0 def get_full_state(self): """获取完整情感状态""" return { "emotion": self.emotion_layer.get_state(), "sentiment": self.sentiment_layer.get_state(), "affection": self.affection_layer.get_state() } def is_healthy(self): """检查系统健康状况""" 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, "运行正常" # 直接测试代码 if __name__ == "__main__": print("===== 情感系统自测 =====") # 配置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 创建测试实例 test_system = AffectiveSystem(config={"growth_interval": 1}) # 初始化 test_system.initialize(None) # 运行测试 print("测试情感刺激处理...") test_stimulus = { "type": "joy", "intensity": 0.8, "source": "user", "is_significant": True } response = test_system.process_stimulus(test_stimulus) print("处理结果:", response) # 获取状态 print("\n系统状态:") status = test_system.get_status() for key, value in status.items(): if key in ["emotion", "sentiment", "affection"]: print(f"{key}: [状态数据]") else: print(f"{key}: {value}") # 健康检查 healthy, reason = test_system.is_healthy() print(f"\n健康状态: {'健康' if healthy else '异常'} - {reason}") # 关闭系统 print("\n关闭系统...") test_system.shutdown() print("测试完成") ”
08-25
<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支持 这个优化版本解决了原始代码中的所有问题,添加了必要的缺失功能,并提供了更健壮的错误处理和后备机制。系统现在可以优雅地处理模块缺失、配置错误和异常情况,同时保持核心功能的可用性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值