自定义异常类boost::unknown_exception的测试程序

319 篇文章 ¥29.90 ¥99.00
本文介绍如何在C++中使用Boost库的boost::unknown_exception自定义异常类。通过创建继承自boost::exception的自定义异常,演示了异常抛出和捕获的测试程序,强调了其在处理程序异常情况中的应用。

在C++编程中,异常处理是一种常见的技术,用于处理程序运行中的异常情况。Boost库提供了一系列强大的异常处理工具,其中之一是boost::unknown_exception。本文将介绍如何使用boost::unknown_exception自定义异常类,并提供一个简单的测试程序。

首先,我们需要包含必要的头文件和命名空间:

#include <boost/exception/all.hpp>
#include <iostream>

using namespace boost;

接下来,我们将创建一个自定义异常类,继承自boost::exception。

你稍等一下 我看你说应该放在意识层面,你看看是这俩哪个文件里# conscious_layer.py import time import threading import logging import uuid from collections import deque from typing import Dict, List, Any, Optional, Tuple from perception_interface import PerceptionInterface, SensorType, InputPriority from conscious_memory import MemorySystem, ContextIndex, EmotionType, MemoryContentType # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger('ConsciousLayer') logger.setLevel(logging.INFO) class ConsciousFramework: """增强型意识框架实现""" def __init__(self, params: Dict = None): self.params = params or {} self.memory_capacity = self.params.get('memory_capacity', 50) self.working_memory = deque(maxlen=self.memory_capacity) self.cognitive_state = { 'attention_level': 0.7, 'cognitive_load': 0.3, 'focus_mode': 'broad', 'arousal_level': 0.5, 'stress_level': 0.3 } self.metacognition = { 'insights': [], 'last_insight': None, 'reflection_count': 0, 'last_reflection': 0.0 } self.lock = threading.RLock() # 线程安全锁 def process(self, stimulus: Dict, biological_state: Dict) -> Dict: """处理输入刺激(线程安全)""" with self.lock: # 更新认知状态 self._update_cognitive_state(stimulus, biological_state) # 计算显著性 salience = self._calculate_salience(stimulus, biological_state) # 生成行动方案 action_plan = self._generate_action_plan(stimulus, salience) # 创建处理结果 result = { 'id': f"proc_{uuid.uuid4().hex}", 'perception': stimulus, 'salience': salience, 'action_plan': action_plan, 'timestamp': time.time(), 'biological_state': biological_state.copy() } # 添加到工作记忆 self.working_memory.append(result) # 自动清理低显著性项目 if len(self.working_memory) > self.memory_capacity * 0.8: self._auto_clean_working_memory() return result def _update_cognitive_state(self, stimulus: Dict, biological_state: Dict): """更新认知状态""" # 更新基础状态 for key in ['attention_level', 'arousal_level', 'stress_level']: if key in biological_state: # 平滑更新:新状态占70%,旧状态占30% self.cognitive_state[key] = ( biological_state[key] * 0.7 + self.cognitive_state.get(key, 0.5) * 0.3 ) # 更新认知负载 urgency = stimulus.get('urgency', 1) / 5.0 self.cognitive_state['cognitive_load'] = min(1.0, self.cognitive_state.get('cognitive_load', 0.3) * 0.8 + urgency * 0.2 ) # 根据负载调整注意力模式 if self.cognitive_state['cognitive_load'] > 0.7: self.cognitive_state['focus_mode'] = 'focused' elif self.cognitive_state['cognitive_load'] > 0.4: self.cognitive_state['focus_mode'] = 'balanced' else: self.cognitive_state['focus_mode'] = 'broad' def _calculate_salience(self, stimulus: Dict, biological_state: Dict) -> float: """计算刺激的显著性""" # 基于紧急度、注意力水平和情绪影响 urgency = stimulus.get('urgency', 1) / 5.0 attention = biological_state.get('attention_level', 0.5) emotion_impact = biological_state.get('emotion_impact', 0.5) # 计算基础显著性 base_salience = min(1.0, max(0.0, urgency * attention * (1 + emotion_impact * 0.3))) # 根据当前焦点模式调整 if self.cognitive_state['focus_mode'] == 'focused': # 专注模式下降低非紧急项目的显著性 if urgency < 0.4: base_salience *= 0.6 elif self.cognitive_state['focus_mode'] == 'broad': # 广泛模式下提高低紧急度项目的显著性 if urgency < 0.4: base_salience *= 1.2 return base_salience def _generate_action_plan(self, stimulus: Dict, salience: float) -> Dict: """生成行动方案""" # 根据显著性和来源确定优先级 source = stimulus.get('source', 'unknown') if source == 'user': priority = 'critical' if salience > 0.8 else 'high' action = 'respond' elif source == 'system': priority = 'high' if salience > 0.7 else 'medium' action = 'analyze' else: priority = 'medium' if salience > 0.5 else 'low' action = 'monitor' # 确定所需资源 resources = ['processing'] if salience > 0.6: resources.append('memory') if priority == 'critical': resources.append('priority_processing') return { 'priority': priority, 'action': action, 'required_resources': resources, 'timeout': 5.0 if priority == 'critical' else 10.0 } def get_cognitive_state_report(self) -> Dict: """获取认知状态报告(线程安全)""" with self.lock: return self.cognitive_state.copy() def get_metacognition_report(self) -> Dict: """获取元认知报告(线程安全)""" with self.lock: return self.metacognition.copy() def get_working_memory_state(self, max_items: int = 10) -> List[Dict]: """获取工作记忆状态(线程安全)""" with self.lock: return list(self.working_memory)[-max_items:] def metacognition_reflection(self, force: bool = False): """元认知反思过程(线程安全)""" with self.lock: current_time = time.time() # 检查是否需要触发反思 if not force and current_time - self.metacognition['last_reflection'] < 10.0: return self.metacognition['reflection_count'] += 1 self.metacognition['last_reflection'] = current_time # 分析工作记忆状态 wm_items = self.get_working_memory_state(max_items=20) high_salience_count = sum(1 for item in wm_items if item['salience'] > 0.7) # 生成洞察 new_insight = ( f"反思 #{self.metacognition['reflection_count']}: " f"工作记忆中有 {high_salience_count}/{len(wm_items)} 个高显著性项目, " f"认知负载: {self.cognitive_state['cognitive_load']:.2f}" ) self.metacognition['last_insight'] = new_insight if new_insight not in self.metacognition['insights']: self.metacognition['insights'].append(new_insight) def _auto_clean_working_memory(self, min_salience: float = 0.3): """自动清理工作记忆中的低显著性项目""" with self.lock: # 保留高显著性项目 self.working_memory = deque( (item for item in self.working_memory if item['salience'] >= min_salience), maxlen=self.memory_capacity ) def shutdown(self) -> Dict: """关闭框架(线程安全)""" with self.lock: return { 'status': 'success', 'working_memory_items': len(self.working_memory), 'last_reflection': self.metacognition['last_insight'], 'reflection_count': self.metacognition['reflection_count'] } class ConsciousLayer: """意识层 - 连接感知和记忆系统的高级处理层(增强版)""" def __init__(self, framework_params: Dict = None, perception_buffer_size: int = 100, memory_system: MemorySystem = None): """ 初始化意识层 参数: framework_params: 意识框架的配置参数 perception_buffer_size: 感知输入缓冲区大小 memory_system: 可选的记忆系统实例(用于依赖注入) """ # 初始化记忆系统(使用依赖注入或创建新实例) if memory_system: self.memory_system = memory_system else: self.memory_system = MemorySystem() logger.info("记忆系统初始化完成") # 初始化感知接口 self.perception = PerceptionInterface(buffer_size=perception_buffer_size) logger.info(f"感知接口初始化完成,缓冲区大小: {perception_buffer_size}") # 初始化意识框架 self.framework = ConsciousFramework(params=framework_params) logger.info("意识框架初始化完成") # 性能监控 self.stats = { "total_processed": 0, "last_processed": 0, "processing_times": deque(maxlen=100), "error_count": 0, "last_error": None, "input_queue_size": 0, "last_reflection": 0.0, "memory_usage": { "working_memory": 0, "long_term_memory": 0 } } # 状态缓存 self.last_state_report = None self.last_state_time = 0 self.state_cache_ttl = 3.0 # 状态报告缓存时间(秒) # 控制线程运行的标志 self._running = False self._processing_thread = None self._maintenance_thread = None def start_processing(self): """启动处理线程""" if self._running: logger.warning("处理线程已在运行") return self._running = True # 启动主处理线程 self._processing_thread = threading.Thread( target=self._processing_loop, name="ConsciousLayer-Processor", daemon=True ) self._processing_thread.start() # 启动维护线程 self._maintenance_thread = threading.Thread( target=self._maintenance_loop, name="ConsciousLayer-Maintenance", daemon=True ) self._maintenance_thread.start() logger.info("意识层处理线程和维护线程已启动") def stop_processing(self): """停止处理线程""" if not self._running: return self._running = False # 等待线程结束 if self._processing_thread and self._processing_thread.is_alive(): self._processing_thread.join(timeout=5.0) if self._maintenance_thread and self._maintenance_thread.is_alive(): self._maintenance_thread.join(timeout=5.0) logger.info("意识层处理线程已停止") def _processing_loop(self): """处理感知输入的循环""" while self._running: try: # 获取下一个输入(带超时以避免永久阻塞) input_packet = self.perception.get_next_input(timeout=0.1) # 更新队列大小统计 self.stats["input_queue_size"] = self.perception.input_buffer.qsize() if input_packet is None: continue # 无输入时继续循环 # 记录处理开始时间 start_time = time.time() # 获取当前生物状态 biological_state = self._get_current_biological_state() # 使用框架处理输入 result = self.framework.process( stimulus=input_packet, biological_state=biological_state ) # 构建长期记忆内容 memory_content = { "type": MemoryContentType.EVENT.value, "description": f"处理输入: {input_packet.get('source', 'unknown')}", "source": "conscious_layer", "stimulus": input_packet, "result": result, "salience": result["salience"] } # 提取情感关联 emotional_associations = [] emotion = biological_state.get('current_emotion', 'NEUTRAL') if emotion: emotional_associations.append( EmotionalAssociation( emotion=EmotionType.from_string(emotion), intensity=biological_state.get('emotion_intensity', 0.5), context="stimulus_processing" ) ) # 创建上下文索引 context = ContextIndex( cognitive_state=self.framework.cognitive_state['focus_mode'], activity="processing" ) # 将结果存入长期记忆 self.memory_system.store( content=memory_content, tags=["processed_stimulus", input_packet.get('source', 'unknown')], emotional_associations=emotional_associations, context=context, importance=result["salience"] ) # 更新统计信息 self._update_stats(start_time, success=True) except Exception as e: # 记录错误信息 error_msg = f"处理刺激失败: {str(e)}" self.stats["last_error"] = { "error": error_msg, "timestamp": time.time(), "stimulus": input_packet if 'input_packet' in locals() else None } self.stats["error_count"] += 1 logger.exception("处理感知输入时发生异常") # 更新统计信息(失败) if 'start_time' in locals(): self._update_stats(start_time, success=False) def _maintenance_loop(self): """维护循环(定期执行清理和反思)""" while self._running: try: # 每5秒执行一次维护 time.sleep(5) # 清理工作记忆 cleared_count = self.clear_working_memory(min_salience=0.25) if cleared_count > 0: logger.debug(f"清理了 {cleared_count} 个工作记忆项目") # 触发内部反思 self.framework.metacognition_reflection() self.stats["last_reflection"] = time.time() # 更新内存使用统计 self._update_memory_stats() except Exception as e: logger.error(f"维护循环发生错误: {str(e)}", exc_info=True) def _get_current_biological_state(self) -> Dict[str, Any]: """获取当前生物状态(增强版)""" # 在实际系统中,这里会连接生物传感器 # 模拟实现:使用框架的认知状态和随机波动 base_state = self.framework.get_cognitive_state_report() # 添加模拟情感状态 if base_state['stress_level'] > 0.6: emotion = 'FEAR' if base_state['arousal_level'] > 0.7 else 'ANGER' intensity = min(1.0, base_state['stress_level'] * 0.8) elif base_state['arousal_level'] > 0.7: emotion = 'JOY' if base_state['cognitive_load'] < 0.4 else 'EXCITEMENT' intensity = base_state['arousal_level'] * 0.9 else: emotion = 'NEUTRAL' intensity = 0.3 return { "arousal_level": base_state['arousal_level'], "stress_level": base_state['stress_level'], "attention_level": base_state['attention_level'], "current_emotion": emotion, "emotion_intensity": intensity, "emotion_impact": intensity * 0.7 # 情感影响因子 } def _update_stats(self, start_time: float, success: bool): """更新处理统计信息""" processing_time = time.time() - start_time self.stats["total_processed"] += 1 self.stats["last_processed"] = time.time() self.stats["processing_times"].append(processing_time) def _update_memory_stats(self): """更新内存使用统计""" self.stats["memory_usage"]["working_memory"] = len(self.framework.working_memory) if hasattr(self.memory_system, 'get_stats'): mem_stats = self.memory_system.get_stats() self.stats["memory_usage"]["long_term_memory"] = mem_stats.get('total_memories', 0) def deliberate_recall(self, keyword: str, max_items: int = 5) -> Dict[str, Any]: """ 主动回忆(增强版) 参数: keyword: 回忆关键词 max_items: 最大返回项目数 返回: 回忆结果字典 """ # 1. 使用框架的工作记忆功能 working_memory_results = self.framework.get_working_memory_state(max_items=max_items) # 2. 从长期记忆中检索相关内容 context = { "keywords": [keyword], "content_types": [MemoryContentType.EVENT.value] } affective_state = self._get_current_biological_state() long_term_results = self.memory_system.retrieve( context=context, affective_state=affective_state, max_results=max_items ) # 3. 合并结果 return { "working_memory": working_memory_results, "long_term_memory": long_term_results, "timestamp": time.time() } def get_state_report(self, force_refresh: bool = False) -> Dict[str, Any]: """ 获取状态报告(增强版) 参数: force_refresh: 是否强制刷新缓存 返回: 状态报告字典 """ # 使用缓存提高性能 current_time = time.time() if not force_refresh and self.last_state_report and \ (current_time - self.last_state_time) < self.state_cache_ttl: return self.last_state_report # 获取框架报告 framework_report = self.framework.get_cognitive_state_report() meta_report = self.framework.get_metacognition_report() # 获取工作记忆摘要 wm_items = self.framework.get_working_memory_state(max_items=10) wm_summary = [] for item in wm_items: content = item["perception"]["data"].get("content", "") wm_summary.append({ "id": item.get("id", "unknown"), "content_preview": content[:50] + "..." if len(content) > 50 else content, "salience": item["salience"], "age_seconds": round(current_time - item["timestamp"], 1), "priority": item["action_plan"].get("priority", "unknown") }) # 获取感知接口状态 perception_stats = getattr(self.perception, 'get_system_stats', lambda: "N/A")() # 获取记忆系统状态 memory_stats = "N/A" if hasattr(self.memory_system, 'get_stats'): memory_stats = self.memory_system.get_stats() # 构建完整报告 report = { "timestamp": current_time, "framework": framework_report, "metacognition": meta_report, "working_memory": { "count": len(wm_items), "summary": wm_summary }, "perception_interface": perception_stats, "memory_system": memory_stats, "performance": { "total_processed": self.stats["total_processed"], "last_processed": self.stats["last_processed"], "avg_processing_time": self._calculate_avg_processing_time(), "error_count": self.stats["error_count"], "last_error": self.stats["last_error"], "input_queue_size": self.stats["input_queue_size"], "memory_usage": self.stats["memory_usage"] } } # 缓存报告 self.last_state_report = report self.last_state_time = current_time return report def _calculate_avg_processing_time(self) -> float: """计算平均处理时间""" if not self.stats["processing_times"]: return 0.0 return sum(self.stats["processing_times"]) / len(self.stats["processing_times"]) def get_insights(self, max_insights: int = 5) -> List[str]: """ 获取元认知洞察 参数: max_insights: 最大返回洞察数 返回: 元认知洞察列表 """ meta_report = self.framework.get_metacognition_report() common_insights = meta_report.get("insights", []) # 添加最后一条洞察 last_insight = meta_report.get("last_insight") if last_insight and last_insight not in common_insights: common_insights.insert(0, last_insight) return common_insights[:max_insights] def get_working_memory(self, max_items: int = 10) -> List[Dict]: """ 获取完整工作记忆内容 参数: max_items: 最大返回项目数 返回: 工作记忆项目列表 """ return self.framework.get_working_memory_state(max_items=max_items) def clear_working_memory(self, min_salience: float = 0.0) -> int: """ 清除工作记忆中的低显著性项目 参数: min_salience: 保留的最小显著性阈值 返回: 被清除的项目数量 """ # 获取当前工作记忆 wm_items = self.framework.get_working_memory_state(max_items=1000) # 过滤掉低显著性项目 remaining = [item for item in wm_items if item["salience"] >= min_salience] # 更新工作记忆 self.framework.working_memory = deque(remaining, maxlen=self.framework.memory_capacity) return len(wm_items) - len(remaining) def trigger_deep_reflection(self, topic: str = None) -> str: """ 触发深度反思过程 参数: topic: 可选反思主题 返回: 生成的深度洞察 """ # 强制触发元认知反思 self.framework.metacognition_reflection(force=True) # 获取当前状态 state_report = self.get_state_report(force_refresh=True) # 生成深度洞察 insights = self.get_insights(max_insights=3) wm_count = state_report['working_memory']['count'] avg_load = state_report['framework']['cognitive_load'] deep_insight = ( f"深度反思: 系统当前处理了 {self.stats['total_processed']} 个输入, " f"工作记忆中有 {wm_count} 个项目, " f"平均认知负载: {avg_load:.2f}. " f"近期洞察: {insights[0] if insights else '无'}" ) # 存储深度洞察 if hasattr(self.framework, 'metacognition'): self.framework.metacognition['insights'].append(deep_insight) self.framework.metacognition['last_insight'] = deep_insight return deep_insight def shutdown(self) -> Dict[str, Any]: """ 安全关闭意识层 返回: 关闭状态报告 """ # 停止处理线程 self.stop_processing() # 生成最终状态报告 final_report = self.get_state_report(force_refresh=True) # 关闭框架 framework_shutdown = self.framework.shutdown() # 关闭记忆系统(如果支持) if hasattr(self.memory_system, 'shutdown'): memory_shutdown = self.memory_system.shutdown() else: memory_shutdown = {"status": "no_shutdown_method"} # 返回关闭信息 return { "timestamp": time.time(), "final_state": final_report, "framework_shutdown": framework_shutdown, "memory_shutdown": memory_shutdown, "total_processed": self.stats["total_processed"], "avg_processing_time": self._calculate_avg_processing_time(), "error_count": self.stats["error_count"] } # ===== 测试用例 ===== if __name__ == "__main__": print("=== 意识层测试 ===") # 初始化记忆系统 memory_system = MemorySystem("test_memory.json", max_memories=100) # 初始化意识层(注入记忆系统) conscious_layer = ConsciousLayer( framework_params={'memory_capacity': 30}, memory_system=memory_system ) # 启动处理线程 conscious_layer.start_processing() # 模拟运行一段时间 print("\n模拟运行5秒...") time.sleep(5) # 获取状态报告 print("\n获取状态报告:") report = conscious_layer.get_state_report() print(f"已处理输入: {report['performance']['total_processed']}") print(f"工作记忆项目数: {report['working_memory']['count']}") print(f"长期记忆项目数: {report['memory_system'].get('total_memories', 'N/A')}") # 测试主动回忆 print("\n测试主动回忆:") recall_result = conscious_layer.deliberate_recall("test") print(f"工作记忆结果: {len(recall_result['working_memory'])} 项") print(f"长期记忆结果: {len(recall_result['long_term_memory'])} 项") # 获取洞察 print("\n获取元认知洞察:") insights = conscious_layer.get_insights() for i, insight in enumerate(insights, 1): print(f"{i}. {insight}") # 触发深度反思 print("\n触发深度反思:") deep_insight = conscious_layer.trigger_deep_reflection() print(f"深度洞察: {deep_insight}") # 安全关闭 print("\n安全关闭系统...") shutdown_report = conscious_layer.shutdown() print(f"最终状态: {shutdown_report['final_state']['performance']['total_processed']} 项已处理") print(f"平均处理时间: {shutdown_report['avg_processing_time']:.4f} 秒") print(f"关闭状态: {shutdown_report['framework_shutdown']['status']}") # conscious_framework.py import logging import time import threading from collections import deque from typing import Dict, List, Any, Optional, Union logger = logging.getLogger('ConsciousFramework') class ConsciousFramework: """意识架构 - 高级认知处理层""" # 默认参数值 DEFAULT_PARAMS = { "max_working_memory": 10, "metacognition_interval": 5.0, "focus_threshold": 0.4, "confidence_threshold": 0.5, "stale_item_threshold": 300, # 5分钟 "salience_params": { "base_arousal_factor": 0.4, "stress_penalty": 0.2, "emotional_boost": {"fear": 1.3, "joy": 1.1}, "related_memory_boost": 1.2 } } def __init__(self, params: Dict = None): """ 初始化意识框架 参数: params: 配置参数字典(可选) """ # 合并默认参数和自定义参数 self.params = {**self.DEFAULT_PARAMS, **(params or {})} # 工作记忆系统 self.working_memory = deque(maxlen=self.params["max_working_memory"]) self.memory_capacity = self.params["max_working_memory"] self.lock = threading.Lock() # 工作记忆线程锁 # 元认知系统 self.metacognition = { "monitoring": False, "interval": self.params["metacognition_interval"], "last_monitor_time": time.time(), "insights": [] } # 认知状态 self.cognitive_state = { "focus_level": 0.7, # 0.0-1.0 "processing_mode": "analytical", # analytical/intuitive "confidence": 0.8, # 0.0-1.0 "last_mode_switch": time.time() } # 启动元认知监控线程 self._start_metacognition_monitor() logger.info(f"意识框架初始化完成,工作记忆容量: {self.memory_capacity}") def _start_metacognition_monitor(self): """启动元认知监控线程""" self.metacognition["monitoring"] = True self.monitor_thread = threading.Thread(target=self._metacognition_loop, daemon=True) self.monitor_thread.start() logger.info("元认知监控已启动") def _metacognition_loop(self): """元认知监控循环""" while self.metacognition["monitoring"]: current_time = time.time() if current_time - self.metacognition["last_monitor_time"] >= self.metacognition["interval"]: try: self._perform_metacognition() except Exception as e: logger.error(f"元认知监控失败: {str(e)}", exc_info=True) self.metacognition["last_monitor_time"] = current_time # 检查间隔 time.sleep(0.5) def _perform_metacognition(self): """执行元认知监控(增强版)""" logger.debug("执行元认知监控...") insights = [] # 1. 检查工作记忆负荷 memory_load = len(self.working_memory) / self.memory_capacity if memory_load > 0.8: insight = "工作记忆接近饱和,建议优先处理高显著性项目" insights.append(insight) logger.warning(insight) # 2. 分析认知状态 if self.cognitive_state["focus_level"] < self.params["focus_threshold"]: insight = "注意力水平较低,建议调整环境或休息" insights.append(insight) logger.warning(insight) # 3. 检查处理模式 if (self.cognitive_state["processing_mode"] == "analytical" and self.cognitive_state["confidence"] < self.params["confidence_threshold"]): insight = "分析模式信心不足,建议切换到直觉模式" insights.append(insight) logger.info(insight) # 4. 检查行动执行情况 if len(self.working_memory) > 0: oldest_item = min(self.working_memory, key=lambda x: x["timestamp"]) if time.time() - oldest_item["timestamp"] > self.params["stale_item_threshold"]: content_preview = oldest_item['perception']['content'][:20] + '...' if len( oldest_item['perception']['content']) > 20 else oldest_item['perception']['content'] insight = f"项目'{content_preview}'长时间未处理" insights.append(insight) logger.warning(insight) # 添加到元认知记录 if insights: self.metacognition["insights"].extend(insights) # 5. 长期监控趋势(每10次执行一次) if len(self.metacognition["insights"]) > 10: # 统计最常见的问题 insight_counts = {} for insight in self.metacognition["insights"]: insight_counts[insight] = insight_counts.get(insight, 0) + 1 # 获取前3个最常见的问题 top_insights = sorted(insight_counts.items(), key=lambda x: x[1], reverse=True)[:3] for insight, count in top_insights: logger.info(f"频繁出现的元认知问题: {insight} (出现次数: {count})") # 保留最近的5条记录 self.metacognition["insights"] = self.metacognition["insights"][-5:] def process(self, input_data: Dict, biological_state: Dict) -> Dict: """ 认知处理流程(带错误处理) 参数: input_data: 输入数据字典 biological_state: 生物状态字典 返回: 处理结果字典 """ try: # 更新认知状态(基于生物状态) self._update_cognitive_state(biological_state) # 认知处理阶段 perception = self._perceive(input_data, biological_state) thought = self._think(perception) action_plan = self._plan_action(thought) # 添加到工作记忆 memory_item = { "perception": perception, "thought": thought, "action_plan": action_plan, "timestamp": time.time(), "salience": perception["salience"] } self._add_to_working_memory(memory_item) # 返回处理结果 return { "perception": perception, "thought": thought, "action_plan": action_plan, "working_memory": self.get_working_memory_state(), "metacognition": self.get_metacognition_report(), "cognitive_state": self.get_cognitive_state_report() } except Exception as e: logger.error(f"认知处理失败: {str(e)}", exc_info=True) # 返回错误信息 return { "error": f"处理失败: {str(e)}", "input_data": input_data, "biological_state": biological_state } def _update_cognitive_state(self, biological_state: Dict): """根据生物状态更新认知状态""" # 感官敏锐度影响注意力 sensor_acuity = biological_state.get("sensor_acuity", 0.7) self.cognitive_state["focus_level"] = min(1.0, sensor_acuity * 1.2) # 疲劳度影响处理模式 fatigue = biological_state.get("fatigue", 0.3) current_mode = self.cognitive_state["processing_mode"] # 只有在满足切换条件且距离上次切换超过30秒时才切换 if fatigue > 0.6 and current_mode != "intuitive": if time.time() - self.cognitive_state["last_mode_switch"] > 30: self.cognitive_state["processing_mode"] = "intuitive" self.cognitive_state["last_mode_switch"] = time.time() logger.info("切换到直觉处理模式") elif fatigue <= 0.6 and current_mode != "analytical": if time.time() - self.cognitive_state["last_mode_switch"] > 30: self.cognitive_state["processing_mode"] = "analytical" self.cognitive_state["last_mode_switch"] = time.time() logger.info("切换到分析处理模式") # 觉醒水平影响信心 arousal = biological_state.get("arousal_level", 0.5) self.cognitive_state["confidence"] = arousal * 0.8 def _perceive(self, input_data: Dict, biological_state: Dict) -> Dict: """ 感知阶段 - 处理输入数据 参数: input_data: 输入数据字典 biological_state: 生物状态字典 返回: 感知结果字典 """ acuity = biological_state.get("sensor_acuity", 1.0) emotional_state = biological_state.get("emotional_state", "neutral") # 计算显著性(基于生物状态) salience = self._calculate_salience(input_data, biological_state) return { "content": input_data, "acuity": acuity, "salience": salience, "emotional_context": emotional_state, "timestamp": time.time() } def _calculate_salience(self, input_data: Dict, biological_state: Dict) -> float: """计算输入数据的显著性(参数化版)""" # 基础显著性 base_salience = input_data.get("salience", 0.5) # 生物状态影响 arousal = biological_state.get("arousal_level", 0.5) stress = biological_state.get("stress", 0.3) # 情绪影响 emotional_state = biological_state.get("emotional_state", "neutral") emotional_boost = self.params["salience_params"]["emotional_boost"].get(emotional_state, 1.0) base_salience *= emotional_boost # 相关性增强 related_memories = self._check_related_memories(input_data) if related_memories: base_salience *= self.params["salience_params"]["related_memory_boost"] # 计算公式 adjusted_salience = base_salience * (0.8 + arousal * self.params["salience_params"]["base_arousal_factor"] - stress * self.params["salience_params"]["stress_penalty"]) # 限制在0.0-1.0之间 return max(0.0, min(1.0, adjusted_salience)) def _check_related_memories(self, input_data: Dict) -> List: """检查相关工作记忆""" keyword = input_data.get("keyword", "") if not keyword: return [] # 使用线程锁保证安全访问 with self.lock: return [item for item in self.working_memory if keyword in item.get("perception", {}).get("content", "")] def _think(self, perception: Dict) -> Dict: """ 思考阶段 - 推理和处理感知信息 参数: perception: 感知结果字典 返回: 思考结果字典 """ # 根据处理模式选择推理策略 if self.cognitive_state["processing_mode"] == "analytical": return self._analytical_thinking(perception) else: return self._intuitive_thinking(perception) def _analytical_thinking(self, perception: Dict) -> Dict: """分析性思考""" # 简化实现 - 实际中应包含复杂的推理逻辑 content = perception.get("content", {}) salience = perception.get("salience", 0.5) # 生成假设 hypotheses = [] if salience > 0.7: hypotheses.append("高显著性事件,需要立即关注") if "danger" in content.get("keywords", []): hypotheses.append("检测到危险信号") # 评估证据 evidence = {} if "data" in content: evidence["data_consistency"] = 0.8 evidence["data_reliability"] = 0.7 return { "type": "analytical", "hypotheses": hypotheses, "evidence": evidence, "confidence": self.cognitive_state["confidence"] * 0.9 } def _intuitive_thinking(self, perception: Dict) -> Dict: """直觉性思考""" # 基于模式和经验的快速判断 content = perception.get("content", {}) emotional_context = perception.get("emotional_context", "neutral") # 生成直觉判断 judgment = "无特别发现" if emotional_context == "fear": judgment = "可能存在威胁,建议谨慎处理" elif "opportunity" in content.get("keywords", []): judgment = "发现潜在机会" return { "type": "intuitive", "judgment": judgment, "confidence": self.cognitive_state["confidence"] * 0.7, "basis": "模式识别与经验" } def _plan_action(self, thought: Dict) -> Dict: """ 行动计划阶段 - 基于思考结果制定行动计划 参数: thought: 思考结果字典 返回: 行动计划字典 """ # 根据思考类型制定计划 if thought["type"] == "analytical": return self._plan_analytical_action(thought) else: return self._plan_intuitive_action(thought) def _plan_analytical_action(self, thought: Dict) -> Dict: """制定分析性行动计划""" actions = [] priority = "medium" # 根据假设制定行动 for hypothesis in thought.get("hypotheses", []): if "立即关注" in hypothesis: actions.append("启动紧急响应协议") priority = "high" elif "危险信号" in hypothesis: actions.append("进行风险评估") actions.append("准备应急预案") priority = "high" # 如果没有高优先级行动 if not actions: actions.append("收集更多数据") actions.append("进行深入分析") priority = "medium" return { "actions": actions, "priority": priority, "estimated_time": 15.0, # 分钟 "resources_required": ["认知资源", "数据访问权限"] } def _plan_intuitive_action(self, thought: Dict) -> Dict: """制定直觉性行动计划""" judgment = thought.get("judgment", "") if "威胁" in judgment: return { "actions": ["采取防御姿态", "评估风险", "寻求更多信息"], "priority": "high", "estimated_time": 5.0, "resources_required": ["快速响应能力"] } elif "机会" in judgment: return { "actions": ["探索机会", "制定初步方案", "评估可行性"], "priority": "medium", "estimated_time": 10.0, "resources_required": ["创造力", "灵活性"] } else: return { "actions": ["维持现状", "监控环境"], "priority": "low", "estimated_time": 2.0, "resources_required": [] } def _add_to_working_memory(self, item: Dict): """添加项目到工作记忆(线程安全版)""" with self.lock: # 使用线程锁 # 检查是否已存在类似项目 existing_items = [i for i in self.working_memory if i["perception"]["content"] == item["perception"]["content"]] if existing_items: # 只更新关键字段,避免覆盖整个对象 existing_item = existing_items[0] existing_item["thought"] = item["thought"] existing_item["action_plan"] = item["action_plan"] existing_item["timestamp"] = time.time() existing_item["salience"] = item["salience"] logger.debug(f"更新工作记忆项目: {item['perception']['content'][:20]}...") else: # 添加新项目 self.working_memory.append(item) logger.debug(f"添加到工作记忆: {item['perception']['content'][:20]}...") def get_working_memory_state(self, max_items: int = 5) -> List[Dict]: """ 获取工作记忆状态(线程安全版) 参数: max_items: 最大返回项目数 返回: 工作记忆项目列表 """ with self.lock: # 使用线程锁 # 按显著性排序 sorted_memory = sorted(self.working_memory, key=lambda x: x["salience"], reverse=True) return sorted_memory[:max_items] def get_metacognition_report(self) -> Dict: """ 获取元认知报告 返回: 元认知状态字典 """ return { "monitoring_active": self.metacognition["monitoring"], "last_insight": self.metacognition["insights"][-1] if self.metacognition["insights"] else None, "insight_count": len(self.metacognition["insights"]), "common_insights": self._get_common_insights(), "next_monitor_in": max(0, self.metacognition["interval"] - ( time.time() - self.metacognition["last_monitor_time"])) } def _get_common_insights(self) -> List[str]: """获取最常见的元认知洞察""" if not self.metacognition["insights"]: return [] # 统计洞察频率 insight_counts = {} for insight in self.metacognition["insights"]: insight_counts[insight] = insight_counts.get(insight, 0) + 1 # 按频率排序 sorted_insights = sorted(insight_counts.items(), key=lambda x: x[1], reverse=True) return [insight[0] for insight in sorted_insights[:3]] def get_cognitive_state_report(self) -> Dict: """ 获取认知状态报告 返回: 认知状态字典 """ return self.cognitive_state.copy() def shutdown(self): """安全关闭意识框架""" self.metacognition["monitoring"] = False if self.monitor_thread.is_alive(): self.monitor_thread.join(timeout=2.0) logger.info("意识框架已安全关闭") return { "final_state": { "working_memory": list(self.working_memory), "metacognition": self.metacognition, "cognitive_state": self.cognitive_state }, "timestamp": time.time() }
08-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值