Metacognitive Retrieval-Augmented Large Language Models

828 篇文章

已下架不支持订阅

本文提出MetaRAG,一种结合元认知的检索增强大型语言模型,提高多跳推理的准确性。通过元认知过程,模型能自我评估和改进其响应策略,实验证明MetaRAG在多跳QA数据集上优于现有方法。

本文是LLM系列文章,针对《Metacognitive Retrieval-Augmented Large Language Models》的翻译。

摘要

检索增强生成由于其在生成事实内容方面的功效而成为自然语言处理的核心。虽然传统方法采用单时间检索,但最近的方法已转向多跳推理任务的多时间检索。然而,这些策略受到预定义推理步骤的约束,可能导致响应生成的不准确。本文介绍了MetaRAG,这是一种将检索增强生成过程与元认知相结合的方法。从认知心理学的角度来看,元认知允许一个实体自我反思和批判性地评估其认知过程。通过整合这一点,MetaRAG使模型能够监测、评估和规划其响应策略,增强其内省推理能力。通过三步元认知调节管道,该模型可以识别初始认知反应中的不足之处并加以纠正。实证评估表明,MetaRAG显著优于现有方法。

1 引言

2 相关工作

3 前言

4 元认知RAG

5 实验设置

6 结果和分析

7 结论

在本文中,我们提出了MetaRAG,这是一种新的框架,将检索增强的LLM过程与人类启发的元认知相结合,以增强多跳推理。通过一个涉及监控、评估和计划阶段的结构化元认知过程,MetaRAG促进了模型对其自身推理过程的认知。这使模型能够在推理过程中识别知识的充分性和潜在的错误。在两

已下架不支持订阅

确定把# layers/conscious.py import logging import time from collections import deque from typing import Dict, List, Optional, Any from enum import Enum from .preconscious import PreconsciousLayer from ..states import ConsciousState from ..memory import MemorySystem from ..cognitive import CognitiveProcessor, WorkloadManager from ..perception.stimulus import Stimulus from ..conscious_stream import ConsciousnessStream # 新增意识流系统 logger = logging.getLogger('ConsciousLayer') class ConsciousLayer: """增强型意识层 - 负责高级认知处理和决策,集成意识流记录""" def __init__(self, preconscious: PreconsciousLayer, memory_system: MemorySystem, cognitive_processor: Optional[CognitiveProcessor] = None, stream_system: Optional[ConsciousnessStream] = None): """ 初始化意识层 参数: preconscious: 前意识层实例 memory_system: 记忆系统实例 cognitive_processor: 认知处理器实例 (可选) stream_system: 意识流系统实例 (可选) """ self.preconscious = preconscious self.memory_system = memory_system self.cognitive_processor = cognitive_processor or CognitiveProcessor(memory_system) # 意识流系统 self.stream_system = stream_system or ConsciousnessStream() logger.info(f"意识流系统初始化完成 (容量: {self.stream_system.max_size})") # 意识状态管理 self.current_state = ConsciousState.RELAXED self.state_history = deque(maxlen=50) # 状态历史记录 # 注意力管理 self.attentional_focus = [] # 当前注意力焦点 self.focus_history = deque(maxlen=100) # 注意力历史 # 自我意识 self.self_awareness = True self.self_model = {} # 自我模型 # 元认知监控 self.metacognition = { "monitoring_interval": 5.0, # 元认知监控间隔 (秒) "last_monitor_time": time.time() } # 初始化工作负载管理器 self.workload_manager = self.cognitive_processor.workload_manager def link_stream_system(self, stream_system: ConsciousnessStream): """连接外部意识流系统""" self.stream_system = stream_system logger.info(f"已连接外部意识流系统 (容量: {stream_system.max_size})") def process(self, elevated_stimulus: Dict, biological_state: Optional[Dict] = None) -> Dict: """ 处理提升到意识层的刺激 (统一接口方法) 参数: elevated_stimulus: 提升的刺激字典 biological_state: 生物状态信息 (可选) 返回: 处理结果字典 """ return self.process_input(elevated_stimulus, biological_state) def process_input(self, elevated_stimulus: Dict, biological_state: Optional[Dict] = None) -> Dict: """ 处理提升到意识层的刺激 (详细实现) 参数: elevated_stimulus: 提升的刺激字典 biological_state: 生物状态信息 (可选) 返回: 处理结果字典 """ start_time = time.time() # 更新意识状态 self._update_state(elevated_stimulus, biological_state) # 如果有生物状态,更新刺激显著性 stimulus = elevated_stimulus["original"] if biological_state: elevated_stimulus["salience"] = stimulus.calculate_salience(biological_state) # 使用认知处理器处理刺激 processor_result = self.cognitive_processor.process_elevated_stimulus( elevated_stimulus, self.current_state, biological_state ) # 更新注意力焦点 self._update_attentional_focus(elevated_stimulus, processor_result) # 强化相关记忆 self._reinforce_related_memories(elevated_stimulus) # 更新意识状态(如果处理器建议) self._update_state_from_processor(processor_result) # 将刺激添加到工作记忆 self._add_to_working_memory(elevated_stimulus, processor_result) # 执行元认知监控 self._metacognitive_monitoring() # ===== 记录到意识流 ===== self._record_to_stream(elevated_stimulus, processor_result, biological_state) # 构建返回结果 result = { "state": self.current_state.name, "attention": self.attentional_focus, "self_awareness": self._check_self_awareness(), "workload": self.workload_manager.get_workload_report(), "working_memory": self.get_working_memory_state(), "processing_time": round(time.time() - start_time, 4), "metacognition": processor_result.get("metacognition", {}), "stream_id": processor_result.get("stream_id", None) # 返回意识流ID } result.update(processor_result) return result def _record_to_stream(self, elevated_stimulus: Dict, processor_result: Dict, biological_state: Optional[Dict] = None): """记录处理过程到意识流""" if not self.stream_system: return stimulus = elevated_stimulus["original"] content = f"处理刺激: {stimulus.content[:50]}{'...' if len(stimulus.content) > 50 else ''}" # 提取情感信息 emotional_valence = stimulus.emotional_valence emotion = "NEUTRAL" if emotional_valence < -0.7: emotion = "FEAR" elif emotional_valence < -0.3: emotion = "SADNESS" elif emotional_valence > 0.7: emotion = "JOY" elif emotional_valence > 0.3: emotion = "INTEREST" # 添加意识流条目 stream_id = self.stream_system.add_entry( event_type="stimulus_processing", content=content, cognitive_state=self.current_state.name, emotional_valence=emotional_valence, additional_data={ "stimulus_id": stimulus.id, "source": stimulus.source, "category": stimulus.category, "priority": elevated_stimulus.get("priority", 0.5), "biological_state": biological_state.copy() if biological_state else {}, "processor_result": processor_result } ) # 在处理器结果中返回流ID processor_result["stream_id"] = stream_id def deliberate_recall(self, keyword: str, context: Optional[Dict] = None, max_results: int = 5) -> List[str]: """ 主动回忆关键词相关的内容 参数: keyword: 回忆关键词 context: 回忆上下文 (可选) max_results: 最大返回结果数 返回: 回忆结果列表 """ recalled = [] # 从前意识缓冲区回忆 for item in self.preconscious.get_buffer_content(): if keyword in item["stimulus"].content: recalled.append(f"前意识: {item['stimulus'].content[:50]}...") # 从长期记忆中回忆 memory_context = context or {"keywords": [keyword]} affective_state = {"emotion": {"current_emotion": "NEUTRAL"}} related_memories = self.memory_system.retrieve( memory_context, affective_state, max_results=max_results ) for mem in related_memories: desc = mem.get("content", {}).get("description", mem["id"]) recalled.append(f"记忆: {desc[:50]}...") # 记录回忆活动 recall_task = { "id": f"recall_{int(time.time())}", "type": "memory_recall", "keyword": keyword, "results": len(recalled) } self.workload_manager.add_task(recall_task) # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="deliberate_recall", content=f"主动回忆: {keyword}", cognitive_state=self.current_state.name, emotional_valence=0.2, # 中性偏积极 additional_data={ "keyword": keyword, "results_count": len(recalled), "results": recalled[:3] # 只记录前3个结果 } ) return recalled[:max_results] def _update_state(self, stimulus: Dict, biological_state: Optional[Dict] = None): """ 根据刺激更新意识状态 参数: stimulus: 刺激字典 biological_state: 生物状态 (可选) """ emotional_valence = stimulus["original"].emotional_valence # 考虑生物状态的影响 fatigue = biological_state.get("fatigue", 0.0) if biological_state else 0.0 arousal = biological_state.get("arousal_level", 0.5) if biological_state else 0.5 # 状态转换逻辑 if emotional_valence < -0.7: new_state = ConsciousState.TRAUMATIC elif "dream" in stimulus["original"].content or fatigue > 0.8: new_state = ConsciousState.DREAMLIKE elif emotional_valence > 0.5 or stimulus.get("priority", 0) > 0.8: new_state = ConsciousState.FOCUSED elif stimulus.get("priority", 0) > 0.5: new_state = ConsciousState.EXPLORATORY elif emotional_valence < -0.2: new_state = ConsciousState.REFLECTIVE elif arousal < 0.3 or fatigue > 0.6: new_state = ConsciousState.RELAXED else: new_state = ConsciousState.RELAXED # 记录状态变化 if new_state != self.current_state: logger.info(f"意识状态变化: {self.current_state.name} -> {new_state.name}") self.state_history.append({ "timestamp": time.time(), "from": self.current_state.name, "to": new_state.name, "stimulus": stimulus["original"].content[:30] + "..." }) self.current_state = new_state # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="state_change", content=f"状态变化: {self.current_state.name} → {new_state.name}", cognitive_state=new_state.name, emotional_valence=emotional_valence ) def _update_attentional_focus(self, stimulus: Dict, processor_result: Dict): """ 更新注意力焦点 参数: stimulus: 刺激字典 processor_result: 处理器结果 """ # 确定新的注意力焦点 new_focus = processor_result.get("attentional_focus", stimulus["associations"]) # 如果焦点变化,记录历史 if new_focus != self.attentional_focus: self.focus_history.append({ "timestamp": time.time(), "previous": self.attentional_focus, "new": new_focus, "reason": processor_result.get("attention_reason", "stimulus-driven") }) # 更新当前焦点 self.attentional_focus = new_focus[:5] # 限制焦点数量 # 记录到意识流 if self.stream_system and new_focus != self.attentional_focus: self.stream_system.add_entry( event_type="attention_shift", content=f"注意力转移: {', '.join(new_focus[:2])}...", cognitive_state=self.current_state.name, emotional_valence=0.0, # 中性 additional_data={ "previous_focus": self.attentional_focus, "new_focus": new_focus } ) def _update_state_from_processor(self, processor_result: Dict): """ 根据处理器结果更新状态 参数: processor_result: 处理器结果字典 """ if "new_state" in processor_result: try: new_state = ConsciousState[processor_result["new_state"]] if new_state != self.current_state: logger.info(f"处理器建议状态变化: {self.current_state.name} -> {new_state.name}") self.current_state = new_state # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="state_change", content=f"处理器状态建议: {new_state.name}", cognitive_state=new_state.name, emotional_valence=0.5 # 积极 ) except KeyError: logger.warning(f"未知意识状态: {processor_result['new_state']}") def _reinforce_related_memories(self, elevated_stimulus: Dict): """ 强化相关记忆 参数: elevated_stimulus: 提升的刺激字典 """ for mem in elevated_stimulus.get("related_memories", []): self.memory_system.reinforce_memory(mem["id"], reinforcement=0.1) def _add_to_working_memory(self, elevated_stimulus: Dict, processor_result: Dict): """ 添加刺激到工作记忆 参数: elevated_stimulus: 提升的刺激字典 processor_result: 处理器结果 """ stimulus = elevated_stimulus["original"] memory_item = { "id": f"wm_{int(time.time())}", "content": stimulus.content[:50] + "..." if len(stimulus.content) > 50 else stimulus.content, "priority": elevated_stimulus.get("priority", 0.5), "salience": elevated_stimulus.get("salience", 0.0), "associations": elevated_stimulus["associations"], "processing_result": processor_result.get("decision", {}), "state": self.current_state.name, "timestamp": time.time() } self.workload_manager.add_to_working_memory(memory_item, memory_item["priority"]) # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="working_memory", content=f"工作记忆添加: {memory_item['content']}", cognitive_state=self.current_state.name, emotional_valence=0.3, # 轻微积极 additional_data={ "priority": memory_item["priority"], "salience": memory_item["salience"] } ) def _metacognitive_monitoring(self): """执行元认知监控""" current_time = time.time() interval = self.metacognition["monitoring_interval"] # 检查是否需要执行监控 if current_time - self.metacognition["last_monitor_time"] > interval: logger.debug("执行元认知监控...") # 记录监控开始 if self.stream_system: self.stream_system.add_entry( event_type="metacognition", content="元认知监控开始", cognitive_state=self.current_state.name, emotional_valence=0.0 ) # 1. 检查认知负荷 workload = self.workload_manager.get_workload_report() if workload["cognitive_load"] > 0.8: logger.info("元认知: 高认知负荷检测,建议减少任务") # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="metacognition", content="高认知负荷,暂停低优先级任务", cognitive_state=self.current_state.name, emotional_valence=-0.3 # 轻微负面 ) # 自动减少任务 self.workload_manager.suspend_low_priority_tasks(threshold=0.4) # 2. 检查注意力稳定性 if len(self.focus_history) > 3: last_focus_changes = list(self.focus_history)[-3:] change_count = sum(1 for change in last_focus_changes if change["reason"] == "distraction") if change_count > 2: logger.info("元认知: 注意力分散检测,建议专注训练") # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="metacognition", content="注意力分散,建议专注训练", cognitive_state=self.current_state.name, emotional_valence=-0.2 ) # 3. 更新自我模型 self._update_self_model() # 记录监控结束 if self.stream_system: self.stream_system.add_entry( event_type="metacognition", content="元认知监控完成", cognitive_state=self.current_state.name, emotional_valence=0.1 ) # 更新最后监控时间 self.metacognition["last_monitor_time"] = current_time def _update_self_model(self): """更新自我模型""" # 基于工作记忆和状态历史更新自我模型 self.self_model = { "preferred_states": self._calculate_preferred_states(), "attention_patterns": self._analyze_attention_patterns(), "memory_effectiveness": self._assess_memory_effectiveness(), "last_updated": time.time() } # 记录到意识流 if self.stream_system: self.stream_system.add_entry( event_type="self_model_update", content="自我模型更新", cognitive_state=self.current_state.name, emotional_valence=0.2, additional_data={ "preferred_state": max(self.self_model["preferred_states"].items(), key=lambda x: x[1])[0] if self.self_model["preferred_states"] else "N/A" } ) def _calculate_preferred_states(self) -> Dict: """计算偏好的意识状态""" state_counts = {} for record in self.state_history: state = record["to"] state_counts[state] = state_counts.get(state, 0) + 1 # 计算偏好分数 total = len(self.state_history) if total == 0: return {} preferences = {state: count / total for state, count in state_counts.items()} return dict(sorted(preferences.items(), key=lambda x: x[1], reverse=True)) def _analyze_attention_patterns(self) -> List[Dict]: """分析注意力模式""" # 简化实现 - 实际中应使用更复杂的分析 recent_focus = list(self.focus_history)[-10:] if not recent_focus: return [] # 计算焦点变化频率 focus_changes = len(recent_focus) avg_duration = (recent_focus[-1]["timestamp"] - recent_focus[0]["timestamp"]) / focus_changes return [{ "focus_change_count": focus_changes, "avg_duration": avg_duration, "common_reasons": self._count_reasons(recent_focus) }] def _count_reasons(self, focus_records: List) -> Dict: """计算注意力变化原因""" reasons = {} for record in focus_records: reason = record["reason"] reasons[reason] = reasons.get(reason, 0) + 1 return reasons def _assess_memory_effectiveness(self) -> float: """评估记忆有效性""" # 简化实现 - 实际中应使用记忆系统数据 recall_tasks = [t for t in self.workload_manager.completed_tasks if t.get("type") == "memory_recall"] if not recall_tasks: return 0.7 # 默认值 success_rates = [task["results"] / task.get("expected", 5) for task in recall_tasks] return round(sum(success_rates) / len(success_rates), 2) def get_working_memory_state(self, max_items: int = 5) -> List[Dict]: """ 获取工作记忆状态 参数: max_items: 最大返回项目数 返回: 工作记忆项目列表 """ return self.workload_manager.get_working_memory(max_items) def _check_self_awareness(self) -> Dict: """ 检查自我意识状态 返回: 包含自我意识状态的字典 """ workload_status = self.workload_manager.get_workload_report() return { "aware": self.self_awareness, "current_focus": workload_status.get("current_focus", None) is not None, "active_tasks": workload_status.get("tasks", {}).get("active", 0) > 0, "self_model_valid": bool(self.self_model), "metacognition_active": time.time() - self.metacognition["last_monitor_time"] < 60 } def get_consciousness_report(self) -> Dict: """ 获取意识层状态报告 返回: 包含意识层状态的字典 """ return { "state": self.current_state.name, "state_history": list(self.state_history)[-5:], "attention": { "current_focus": self.attentional_focus, "history": list(self.focus_history)[-5:] }, "self_awareness": self._check_self_awareness(), "self_model": self.self_model, "workload": self.workload_manager.get_workload_report(), "working_memory": self.get_working_memory_state(3), "metacognition": { "last_monitor": self.metacognition["last_monitor_time"], "interval": self.metacognition["monitoring_interval"] }, "stream_stats": self.stream_system.get_stats() if self.stream_system else None } def shutdown(self): """安全关闭意识层""" # 保存当前状态 shutdown_data = { "final_state": self.current_state.name, "working_memory": self.get_working_memory_state(), "self_model": self.self_model, "timestamp": time.time(), "stream_entries": self.stream_system.get_total_entries() if self.stream_system else 0 } # 存储关闭状态到记忆系统 self.memory_system.store({ "content": shutdown_data, "context": {"type": "system", "event": "shutdown"}, "emotional_valence": 0.0 }) # 记录关闭事件到意识流 if self.stream_system: self.stream_system.add_entry( event_type="shutdown", content="意识层关闭", cognitive_state=self.current_state.name, emotional_valence=0.0 ) # 关闭组件 self.cognitive_processor = None logger.info("意识层已安全关闭") return shutdown_data 改成# layers/conscious.py import logging import time from collections import deque, defaultdict from typing import Dict, List, Optional, Any from enum import Enum from .preconscious import PreconsciousLayer from .conscious_stream import ConsciousnessStream # 导入意识流系统 from ..states import ConsciousState from ..memory import MemorySystem from ..cognitive import CognitiveProcessor, WorkloadManager from ..perception.stimulus import Stimulus logger = logging.getLogger('ConsciousLayer') class ConsciousLayer: """增强型意识层 - 负责高级认知处理和决策,集成意识流记录""" def __init__(self, preconscious: PreconsciousLayer, memory_system: MemorySystem, cognitive_processor: Optional[CognitiveProcessor] = None, stream_system: Optional[ConsciousnessStream] = None): """ 初始化意识层 参数: preconscious: 前意识层实例 memory_system: 记忆系统实例 cognitive_processor: 认知处理器实例 (可选) stream_system: 意识流系统实例 (可选) """ self.preconscious = preconscious self.memory_system = memory_system self.cognitive_processor = cognitive_processor or CognitiveProcessor(memory_system) # 意识流系统 self.stream_system = stream_system or ConsciousnessStream() logger.info(f"意识流系统初始化完成 (容量: {self.stream_system.max_size})") # 意识状态管理 self.current_state = ConsciousState.RELAXED self.state_history = deque(maxlen=50) # 状态历史记录 # 注意力管理 self.attentional_focus = [] # 当前注意力焦点 self.focus_history = deque(maxlen=100) # 注意力历史 # 自我意识 self.self_awareness = True self.self_model = {} # 自我模型 # 元认知监控 self.metacognition = { "monitoring_interval": 5.0, # 元认知监控间隔 (秒) "last_monitor_time": time.time(), "insights": [] } # 初始化工作负载管理器 self.workload_manager = self.cognitive_processor.workload_manager def link_stream_system(self, stream_system: ConsciousnessStream): """连接外部意识流系统""" self.stream_system = stream_system logger.info(f"已连接外部意识流系统 (容量: {stream_system.max_size})") def process(self, elevated_stimulus: Dict, biological_state: Optional[Dict] = None) -> Dict: """ 处理提升到意识层的刺激 (统一接口方法) 参数: elevated_stimulus: 提升的刺激字典 biological_state: 生物状态信息 (可选) 返回: 处理结果字典 """ return self.process_input(elevated_stimulus, biological_state) def process_input(self, elevated_stimulus: Dict, biological_state: Optional[Dict] = None) -> Dict: """ 处理提升到意识层的刺激 (详细实现) 参数: elevated_stimulus: 提升的刺激字典 biological_state: 生物状态信息 (可选) 返回: 处理结果字典 """ start_time = time.time() # 记录处理开始 stream_id = self._record_to_stream("process_start", "开始处理刺激", elevated_stimulus, biological_state) # 更新意识状态 self._update_state(elevated_stimulus, biological_state) # 如果有生物状态,更新刺激显著性 stimulus = elevated_stimulus["original"] if biological_state: elevated_stimulus["salience"] = stimulus.calculate_salience(biological_state) # 使用认知处理器处理刺激 processor_result = self.cognitive_processor.process_elevated_stimulus( elevated_stimulus, self.current_state, biological_state ) # 更新注意力焦点 self._update_attentional_focus(elevated_stimulus, processor_result) # 强化相关记忆 self._reinforce_related_memories(elevated_stimulus) # 更新意识状态(如果处理器建议) self._update_state_from_processor(processor_result) # 将刺激添加到工作记忆 self._add_to_working_memory(elevated_stimulus, processor_result) # 执行元认知监控 self._metacognitive_monitoring() # 构建返回结果 result = { "state": self.current_state.name, "attention": self.attentional_focus, "self_awareness": self._check_self_awareness(), "workload": self.workload_manager.get_workload_report(), "working_memory": self.get_working_memory_state(), "processing_time": round(time.time() - start_time, 4), "metacognition": processor_result.get("metacognition", {}), "stream_id": stream_id, "processor_result": processor_result } # 记录处理完成 self._record_to_stream("process_complete", "刺激处理完成", elevated_stimulus, biological_state, additional_data={"result": result}) return result def _record_to_stream(self, event_type: str, content: str, elevated_stimulus: Dict, biological_state: Optional[Dict] = None, additional_data: dict = None) -> str: """记录处理过程到意识流""" if not self.stream_system: return None stimulus = elevated_stimulus["original"] emotional_valence = stimulus.emotional_valence # 创建附加数据 record_data = { "stimulus_id": stimulus.id, "source": stimulus.source, "category": stimulus.category, "priority": elevated_stimulus.get("priority", 0.5), "salience": elevated_stimulus.get("salience", 0.0), } if biological_state: record_data["biological_state"] = biological_state.copy() if additional_data: record_data.update(additional_data) # 添加意识流条目 return self.stream_system.add_entry( event_type=event_type, content=content, cognitive_state=self.current_state.name, emotional_valence=emotional_valence, additional_data=record_data ) def deliberate_recall(self, keyword: str, context: Optional[Dict] = None, max_results: int = 5) -> List[str]: """ 主动回忆关键词相关的内容 参数: keyword: 回忆关键词 context: 回忆上下文 (可选) max_results: 最大返回结果数 返回: 回忆结果列表 """ # 记录回忆开始 recall_id = self._record_to_stream("recall_start", f"开始回忆: {keyword}", {"original": Stimulus(content=keyword, source="internal")}) recalled = [] # 从前意识缓冲区回忆 for item in self.preconscious.get_buffer_content(): if keyword in item["stimulus"].content: recalled.append(f"前意识: {item['stimulus'].content[:50]}...") # 从长期记忆中回忆 memory_context = context or {"keywords": [keyword]} affective_state = {"emotion": {"current_emotion": "NEUTRAL"}} related_memories = self.memory_system.retrieve( memory_context, affective_state, max_results=max_results ) for mem in related_memories: desc = mem.get("content", {}).get("description", mem["id"]) recalled.append(f"记忆: {desc[:50]}...") # 记录回忆活动 recall_task = { "id": f"recall_{int(time.time())}", "type": "memory_recall", "keyword": keyword, "results": len(recalled) } self.workload_manager.add_task(recall_task) # 记录回忆结果 self._record_to_stream("recall_results", f"回忆完成: {keyword} ({len(recalled)}结果)", {"original": Stimulus(content=keyword, source="internal")}, additional_data={"results": recalled[:3]}) return recalled[:max_results] def _update_state(self, stimulus: Dict, biological_state: Optional[Dict] = None): """ 根据刺激更新意识状态 参数: stimulus: 刺激字典 biological_state: 生物状态 (可选) """ emotional_valence = stimulus["original"].emotional_valence # 考虑生物状态的影响 fatigue = biological_state.get("fatigue", 0.0) if biological_state else 0.0 arousal = biological_state.get("arousal_level", 0.5) if biological_state else 0.5 # 状态转换逻辑 if emotional_valence < -0.7: new_state = ConsciousState.TRAUMATIC elif "dream" in stimulus["original"].content or fatigue > 0.8: new_state = ConsciousState.DREAMLIKE elif emotional_valence > 0.5 or stimulus.get("priority", 0) > 0.8: new_state = ConsciousState.FOCUSED elif stimulus.get("priority", 0) > 0.5: new_state = ConsciousState.EXPLORATORY elif emotional_valence < -0.2: new_state = ConsciousState.REFLECTIVE elif arousal < 0.3 or fatigue > 0.6: new_state = ConsciousState.RELAXED else: new_state = ConsciousState.RELAXED # 记录状态变化 if new_state != self.current_state: logger.info(f"意识状态变化: {self.current_state.name} -> {new_state.name}") self.state_history.append({ "timestamp": time.time(), "from": self.current_state.name, "to": new_state.name, "stimulus": stimulus["original"].content[:30] + "..." }) self.current_state = new_state # 记录状态变化到意识流 self._record_to_stream("state_change", f"状态变化: {self.current_state.name} → {new_state.name}", stimulus, biological_state) def _update_attentional_focus(self, stimulus: Dict, processor_result: Dict): """ 更新注意力焦点 参数: stimulus: 刺激字典 processor_result: 处理器结果 """ # 确定新的注意力焦点 new_focus = processor_result.get("attentional_focus", stimulus["associations"]) # 如果焦点变化,记录历史 if new_focus != self.attentional_focus: self.focus_history.append({ "timestamp": time.time(), "previous": self.attentional_focus, "new": new_focus, "reason": processor_result.get("attention_reason", "stimulus-driven") }) # 更新当前焦点 self.attentional_focus = new_focus[:5] # 限制焦点数量 # 记录注意力转移 if new_focus != self.attentional_focus: self._record_to_stream("attention_shift", f"注意力转移: {', '.join(new_focus[:2])}...", stimulus) def _update_state_from_processor(self, processor_result: Dict): """ 根据处理器结果更新状态 参数: processor_result: 处理器结果字典 """ if "new_state" in processor_result: try: new_state = ConsciousState[processor_result["new_state"]] if new_state != self.current_state: logger.info(f"处理器建议状态变化: {self.current_state.name} -> {new_state.name}") self.current_state = new_state # 记录状态建议 self._record_to_stream("state_suggestion", f"处理器状态建议: {new_state.name}", {}, additional_data={"processor_result": processor_result}) except KeyError: logger.warning(f"未知意识状态: {processor_result['new_state']}") def _reinforce_related_memories(self, elevated_stimulus: Dict): """ 强化相关记忆 参数: elevated_stimulus: 提升的刺激字典 """ for mem in elevated_stimulus.get("related_memories", []): self.memory_system.reinforce_memory(mem["id"], reinforcement=0.1) # 记录记忆强化 if elevated_stimulus.get("related_memories"): self._record_to_stream("memory_reinforcement", "强化相关记忆", elevated_stimulus) def _add_to_working_memory(self, elevated_stimulus: Dict, processor_result: Dict): """ 添加刺激到工作记忆 参数: elevated_stimulus: 提升的刺激字典 processor_result: 处理器结果 """ stimulus = elevated_stimulus["original"] memory_item = { "id": f"wm_{int(time.time())}", "content": stimulus.content[:50] + "..." if len(stimulus.content) > 50 else stimulus.content, "priority": elevated_stimulus.get("priority", 0.5), "salience": elevated_stimulus.get("salience", 0.0), "associations": elevated_stimulus["associations"], "processing_result": processor_result.get("decision", {}), "state": self.current_state.name, "timestamp": time.time() } self.workload_manager.add_to_working_memory(memory_item, memory_item["priority"]) # 记录工作记忆添加 self._record_to_stream("working_memory", f"工作记忆添加: {memory_item['content']}", elevated_stimulus, additional_data=memory_item) def _metacognitive_monitoring(self): """执行元认知监控""" current_time = time.time() interval = self.metacognition["monitoring_interval"] # 检查是否需要执行监控 if current_time - self.metacognition["last_monitor_time"] > interval: logger.debug("执行元认知监控...") # 记录监控开始 monitor_id = self._record_to_stream("metacognition_start", "元认知监控开始", {}) # 1. 检查认知负荷 workload = self.workload_manager.get_workload_report() if workload["cognitive_load"] > 0.8: logger.info("元认知: 高认知负荷检测,建议减少任务") # 自动减少任务 suspended = self.workload_manager.suspend_low_priority_tasks(threshold=0.4) # 记录到意识流 self._record_to_stream("workload_adjustment", f"高负荷暂停{suspended}个任务", {}, additional_data={"workload": workload}) # 2. 检查注意力稳定性 if len(self.focus_history) > 3: last_focus_changes = list(self.focus_history)[-3:] change_count = sum(1 for change in last_focus_changes if change["reason"] == "distraction") if change_count > 2: logger.info("元认知: 注意力分散检测,建议专注训练") # 记录到意识流 self._record_to_stream("attention_warning", "注意力分散警告", {}, additional_data={"focus_history": last_focus_changes}) # 3. 更新自我模型 self._update_self_model() # 生成元认知洞察 insight = self._generate_metacognitive_insight(workload) self.metacognition["insights"].append(insight) # 记录监控完成 self._record_to_stream("metacognition_complete", "元认知监控完成", {}, additional_data={"insight": insight}) # 更新最后监控时间 self.metacognition["last_monitor_time"] = current_time def _generate_metacognitive_insight(self, workload: dict) -> str: """生成元认知洞察""" wm_count = len(self.get_working_memory_state()) avg_load = workload.get("cognitive_load", 0.5) return ( f"系统状态: {self.current_state.name}, " f"工作记忆: {wm_count}项, " f"认知负载: {avg_load:.2f}, " f"注意力焦点: {', '.join(self.attentional_focus[:2]) or '无'}" ) def _update_self_model(self): """更新自我模型""" # 基于工作记忆和状态历史更新自我模型 self.self_model = { "preferred_states": self._calculate_preferred_states(), "attention_patterns": self._analyze_attention_patterns(), "memory_effectiveness": self._assess_memory_effectiveness(), "last_updated": time.time() } # 记录自我模型更新 self._record_to_stream("self_model_update", "自我模型更新", {}, additional_data=self.self_model) def _calculate_preferred_states(self) -> Dict: """计算偏好的意识状态""" state_counts = defaultdict(int) for record in self.state_history: state = record["to"] state_counts[state] += 1 # 计算偏好分数 total = len(self.state_history) if total == 0: return {} preferences = {state: count / total for state, count in state_counts.items()} return dict(sorted(preferences.items(), key=lambda x: x[1], reverse=True)) def _analyze_attention_patterns(self) -> List[Dict]: """分析注意力模式""" recent_focus = list(self.focus_history)[-10:] if not recent_focus: return [] # 计算焦点变化频率 focus_changes = len(recent_focus) avg_duration = (recent_focus[-1]["timestamp"] - recent_focus[0]["timestamp"]) / focus_changes return [{ "focus_change_count": focus_changes, "avg_duration": avg_duration, "common_reasons": self._count_reasons(recent_focus) }] def _count_reasons(self, focus_records: List) -> Dict: """计算注意力变化原因""" reasons = defaultdict(int) for record in focus_records: reason = record["reason"] reasons[reason] += 1 return dict(reasons) def _assess_memory_effectiveness(self) -> float: """评估记忆有效性""" recall_tasks = [t for t in self.workload_manager.completed_tasks if t.get("type") == "memory_recall"] if not recall_tasks: return 0.7 # 默认值 success_rates = [task["results"] / task.get("expected", 5) for task in recall_tasks] return round(sum(success_rates) / len(success_rates), 2) def get_working_memory_state(self, max_items: int = 5) -> List[Dict]: """ 获取工作记忆状态 参数: max_items: 最大返回项目数 返回: 工作记忆项目列表 """ return self.workload_manager.get_working_memory(max_items) def _check_self_awareness(self) -> Dict: """ 检查自我意识状态 返回: 包含自我意识状态的字典 """ workload_status = self.workload_manager.get_workload_report() return { "aware": self.self_awareness, "current_focus": workload_status.get("current_focus", None) is not None, "active_tasks": workload_status.get("tasks", {}).get("active", 0) > 0, "self_model_valid": bool(self.self_model), "metacognition_active": time.time() - self.metacognition["last_monitor_time"] < 60 } def get_consciousness_report(self) -> Dict: """ 获取意识层状态报告 返回: 包含意识层状态的字典 """ return { "state": self.current_state.name, "state_history": list(self.state_history)[-5:], "attention": { "current_focus": self.attentional_focus, "history": list(self.focus_history)[-5:] }, "self_awareness": self._check_self_awareness(), "self_model": self.self_model, "workload": self.workload_manager.get_workload_report(), "working_memory": self.get_working_memory_state(3), "metacognition": { "last_monitor": self.metacognition["last_monitor_time"], "interval": self.metacognition["monitoring_interval"], "insights": self.metacognition["insights"][-3:] }, "stream_stats": self.stream_system.get_stats() if self.stream_system else None } def shutdown(self): """安全关闭意识层""" # 保存当前状态 shutdown_data = { "final_state": self.current_state.name, "working_memory": self.get_working_memory_state(), "self_model": self.self_model, "timestamp": time.time(), "stream_entries": self.stream_system.get_total_entries() if self.stream_system else 0 } # 存储关闭状态到记忆系统 self.memory_system.store({ "content": shutdown_data, "context": {"type": "system", "event": "shutdown"}, "emotional_valence": 0.0 }) # 记录关闭事件到意识流 if self.stream_system: self.stream_system.add_entry( event_type="shutdown", content="意识层关闭", cognitive_state=self.current_state.name, emotional_valence=0.0, additional_data=shutdown_data ) # 关闭组件 self.cognitive_processor = None logger.info("意识层已安全关闭") return shutdown_data 对吗?
08-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UnknownBody

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值