E:\AI_System\agent\cognitive_system\conscious_framework.py
class ConsciousFramework:
"""意识架构 - 认知处理层"""
def __init__(self):
self.working_memory = []
self.metacognition = {"monitoring": False}
def process(self, input_data, biological_state):
"""认知处理流程"""
perception = self._perceive(input_data, biological_state)
thought = self._think(perception)
return self._plan_action(thought)
def _perceive(self, input_data, biological_state):
"""感知阶段"""
acuity = biological_state.get("sensor_acuity", 1.0)
return {
"content": input_data,
"acuity": acuity,
"salience": 0.8
}
# ... 其他方法简化 ...
def get_state(self):
return {
"working_memory": self.working_memory,
"metacognition": self.metacognition
}# E:\AI_System\agent\conscious_framework.py
import threading
import time
import logging
from collections import deque
from enum import Enum
from typing import Dict, Any, Optional, Callable
from .conscious_memory import ConsciousMemorySystem
# 导入其他模块
from affective_system import AffectiveSystem
from cognitive_processor import CognitiveProcessor
from memory_system import MemorySystem
from perception_interface import PerceptionInterface
class ConsciousnessState(Enum):
"""意识状态枚举"""
FOCUSED = 1 # 专注状态:高度集中处理当前任务
EXPLORATORY = 2 # 探索状态:主动探索新信息
REFLECTIVE = 3 # 反思状态:处理内部信息
RESTING = 4 # 休息状态:低功耗模式
DISENGAGED = 5 # 脱离状态:不处理任何信息
class ConsciousFramework:
"""意识架构框架 - 整合所有认知模块的核心系统"""
def __init__(self, agent_name: str = "AI Agent", config: Optional[Dict] = None):
"""
初始化意识架构
Args:
agent_name: AI代理名称
config: 配置字典
"""
self.agent_name = agent_name
self.logger = logging.getLogger('ConsciousFramework')
self._init_logger()
# 加载配置
self.config = config or self._get_default_config()
# 初始化子系统
self.perception = PerceptionInterface()
self.affective_system = AffectiveSystem(self)
self.cognitive_processor = CognitiveProcessor(self)
self.memory_system = MemorySystem()
# 意识状态管理
self.current_state = ConsciousnessState.EXPLORATORY
self.state_transition_history = deque(maxlen=100)
# 工作记忆区
self.working_memory = {
"current_focus": None,
"active_goals": [],
"pending_tasks": deque(maxlen=20),
"internal_monologue": []
}
# 系统运行控制
self._active = True
self._cycle_counter = 0
self._cycle_durations = []
# 启动主循环线程
self._main_thread = threading.Thread(target=self._run_conscious_cycle, daemon=True)
self._main_thread.start()
self.logger.info(f"🟢 {self.agent_name} 意识架构初始化完成 - 当前状态: {self.current_state.name}")
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 _get_default_config(self) -> Dict:
"""获取默认配置"""
return {
"cycle_interval": 0.5, # 意识循环间隔(秒)
"state_transition_rules": {
"FOCUSED": {
"min_duration": 5.0,
"triggers": {
"task_completed": "REFLECTIVE",
"external_interrupt": "EXPLORATORY",
"fatigue": "RESTING"
}
},
"EXPLORATORY": {
"min_duration": 3.0,
"triggers": {
"interesting_found": "FOCUSED",
"no_input": "REFLECTIVE",
"prolonged": "RESTING"
}
},
"REFLECTIVE": {
"min_duration": 4.0,
"triggers": {
"insight_gained": "FOCUSED",
"emotional_arousal": "EXPLORATORY",
"prolonged": "RESTING"
}
},
"RESTING": {
"min_duration": 2.0,
"triggers": {
"external_stimulus": "EXPLORATORY",
"rest_completed": "FOCUSED"
}
}
},
"memory_config": {
"working_memory_capacity": 7, # 工作记忆容量
"long_term_retention": 0.8 # 长期记忆保留率
}
}
def _run_conscious_cycle(self):
"""意识主循环线程"""
self.logger.info("意识主循环启动")
last_cycle_time = time.time()
while self._active:
try:
start_time = time.time()
# 1. 感知输入
sensory_input = self.perception.capture_input()
# 2. 情感处理
affective_response = self.affective_system.process_stimulus(sensory_input)
# 3. 记忆检索
relevant_memories = self.memory_system.retrieve(
context=sensory_input,
affective_state=affective_response
)
# 4. 认知处理
cognitive_output = self.cognitive_processor.process(
sensory_input=sensory_input,
affective_state=affective_response,
memories=relevant_memories,
current_state=self.current_state
)
# 5. 更新工作记忆
self._update_working_memory(cognitive_output)
# 6. 执行决策
self._execute_decision(cognitive_output.get("decision"))
# 7. 状态转换检查
self._check_state_transition()
# 记录周期时间
cycle_duration = time.time() - start_time
self._cycle_durations.append(cycle_duration)
self._cycle_counter += 1
# 计算睡眠时间,保持固定周期间隔
elapsed = time.time() - last_cycle_time
sleep_time = max(0, self.config["cycle_interval"] - elapsed)
time.sleep(sleep_time)
last_cycle_time = time.time()
except Exception as e:
self.logger.error(f"意识循环异常: {str(e)}")
time.sleep(1) # 异常后暂停
def _update_working_memory(self, cognitive_output: Dict):
"""更新工作记忆"""
# 更新当前焦点
if cognitive_output.get("new_focus"):
self.working_memory["current_focus"] = cognitive_output["new_focus"]
# 添加新任务
if cognitive_output.get("new_tasks"):
for task in cognitive_output["new_tasks"]:
self.working_memory["pending_tasks"].append(task)
# 添加内部独白
if cognitive_output.get("internal_monologue"):
self.working_memory["internal_monologue"].append(
(time.time(), cognitive_output["internal_monologue"])
)
# 保持内部独白长度
if len(self.working_memory["internal_monologue"]) > 10:
self.working_memory["internal_monologue"].pop(0)
def _execute_decision(self, decision: Optional[Dict]):
"""执行认知决策"""
if not decision:
return
# 根据决策类型执行不同操作
decision_type = decision.get("type")
if decision_type == "verbal_response":
self._generate_verbal_response(decision["content"])
elif decision_type == "action":
self._perform_action(decision["action_type"], decision["parameters"])
elif decision_type == "memory_store":
self.memory_system.store(decision["memory_content"], decision["tags"])
elif decision_type == "state_change_request":
self.request_state_change(decision["requested_state"])
def _generate_verbal_response(self, content: Dict):
"""生成语言响应"""
# 实际应用中会连接到语言生成模块
self.logger.info(f"💬 生成语言响应: {content.get('message')}")
# 在此处可以添加实际的语言生成逻辑
def _perform_action(self, action_type: str, parameters: Dict):
"""执行动作"""
# 实际应用中会连接到动作执行模块
self.logger.info(f"🏃 执行动作: {action_type} - {parameters}")
# 在此处可以添加实际的动作执行逻辑
def _check_state_transition(self):
"""检查并执行状态转换"""
current_state_name = self.current_state.name
state_config = self.config["state_transition_rules"][current_state_name]
# 检查状态持续时间是否达到最小值
if self._get_current_state_duration() < state_config["min_duration"]:
return
# 检查所有触发条件
for trigger, target_state in state_config["triggers"].items():
if self._evaluate_trigger(trigger):
new_state = ConsciousnessState[target_state]
self.transition_to_state(new_state)
return
def _evaluate_trigger(self, trigger: str) -> bool:
"""评估状态转换触发条件"""
# 这里是简化的逻辑,实际系统会有更复杂的条件评估
if trigger == "task_completed":
return not self.working_memory["pending_tasks"]
elif trigger == "external_interrupt":
return self.perception.has_urgent_input()
elif trigger == "fatigue":
return self._cycle_counter > 50 and min(self._cycle_durations[-5:]) > 0.4
elif trigger == "interesting_found":
return self.working_memory["current_focus"] is not None
elif trigger == "no_input":
return not self.perception.has_input()
elif trigger == "prolonged":
return self._get_current_state_duration() > 10.0
return False
def transition_to_state(self, new_state: ConsciousnessState):
"""转换到新的意识状态"""
if new_state == self.current_state:
return
prev_state = self.current_state
self.current_state = new_state
self.state_transition_history.append((time.time(), prev_state, new_state))
# 状态转换时的特殊处理
if new_state == ConsciousnessState.FOCUSED:
self._enter_focused_state()
elif new_state == ConsciousnessState.RESTING:
self._enter_resting_state()
self.logger.info(f"🔄 意识状态转换: {prev_state.name} → {new_state.name}")
def _enter_focused_state(self):
"""进入专注状态的初始化"""
# 清除部分工作记忆,专注于当前任务
self.working_memory["pending_tasks"] = deque(
[self.working_memory["current_focus"]],
maxlen=self.working_memory["pending_tasks"].maxlen
)
def _enter_resting_state(self):
"""进入休息状态的初始化"""
# 释放非必要资源
self.perception.reduce_sampling_rate()
self.cognitive_processor.reduce_processing_load()
def _get_current_state_duration(self) -> float:
"""获取当前状态持续时间(秒)"""
if not self.state_transition_history:
return time.time() - self._start_time
last_transition_time = self.state_transition_history[-1][0]
return time.time() - last_transition_time
def request_state_change(self, requested_state: str):
"""请求状态转换(可由其他模块调用)"""
try:
new_state = ConsciousnessState[requested_state.upper()]
self.transition_to_state(new_state)
except KeyError:
self.logger.warning(f"无效的状态转换请求: {requested_state}")
def add_task(self, task: Dict, priority: int = 5):
"""添加新任务到工作记忆"""
self.working_memory["pending_tasks"].append((priority, task))
# 按优先级排序
self.working_memory["pending_tasks"] = deque(
sorted(self.working_memory["pending_tasks"], key=lambda x: x[0], reverse=True),
maxlen=self.working_memory["pending_tasks"].maxlen
)
self.logger.info(f"📝 添加新任务: {task.get('description')} (优先级: {priority})")
def get_current_state_report(self) -> Dict:
"""获取当前意识状态报告"""
return {
"agent": self.agent_name,
"timestamp": time.time(),
"consciousness_state": self.current_state.name,
"state_duration": self._get_current_state_duration(),
"cycle_count": self._cycle_counter,
"avg_cycle_duration": sum(self._cycle_durations) / len(
self._cycle_durations) if self._cycle_durations else 0,
"working_memory": {
"current_focus": self.working_memory["current_focus"],
"task_count": len(self.working_memory["pending_tasks"]),
"recent_monologue": [msg for _, msg in self.working_memory["internal_monologue"][-3:]]
},
"affective_state": self.affective_system.get_full_state(),
"memory_stats": self.memory_system.get_stats()
}
def shutdown(self):
"""关闭意识系统"""
self._active = False
if self._main_thread.is_alive():
self._main_thread.join(timeout=5.0)
self.affective_system.shutdown()
self.logger.info("意识系统已安全关闭")
你看看怎么给我重写个名 然后告诉我需要改哪些文件
最新发布