谢谢 你真靠谱那我们进行下一步吧 我们做好了核心模块 接下来 我们看看认知系统吧 认知系统的主文件# E:\AI_System\agent\cognitive_architecture.py
# 智能体认知架构模块 - 整合三维响应生成框架和决策系统
import os
import time
import random
import logging
from datetime import datetime
# 配置日志
logger = logging.getLogger('CognitiveArchitecture')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.propagate = False # 防止日志向上传播
# 简化决策系统实现
class DecisionSystem:
"""简化的决策系统"""
def make_decision(self, context):
"""根据上下文做出决策"""
# 简化的决策逻辑
return {
"type": "honest",
"strategy": "direct",
"reason": "使用直接响应策略"
}
class Strategy:
"""策略基类"""
pass
class CognitiveArchitecture:
def __init__(self, agent, affective_system=None):
"""
三维整合的认知架构
:param agent: 智能体实例,用于访问其他系统
:param affective_system: 可选的情感系统实例
"""
self.agent = agent # 保存对agent的引用
self.logger = logging.getLogger('CognitiveArchitecture')
# 通过agent引用其他系统
self.memory_system = agent.memory_system
self.model_manager = agent.model_manager
self.health_system = agent.health_system
# 优先使用传入的情感系统,否则使用agent的
self.affective_system = affective_system if affective_system is not None else agent.affective_system
self.learning_tasks = [] # 当前学习任务队列
self.thought_process = [] # 思考过程记录
# 初始化决策系统
self.decision_system = DecisionSystem()
# 初始化认知状态
self.cognitive_layers = {
"perception": 0.5, # 感知层
"comprehension": 0.3, # 理解层
"reasoning": 0.2, # 推理层
"decision": 0.4 # 决策层
}
logger.info("认知架构初始化完成 - 包含决策系统")
def process_input(self, user_input: str, user_id: str = "default") -> str:
"""处理用户输入(完整实现)"""
# 记录用户活动
self.health_system.record_activity()
self.logger.info(f"处理用户输入: '{user_input}' (用户: {user_id})")
try:
# 1. 评估当前身体状态
bodily_state = self._assess_bodily_state()
# 2. 获取用户认知模型
user_model = self._retrieve_user_model(user_id)
# 3. 选择最适合的知识模型
model = self._select_internalized_model(user_input, bodily_state, user_model)
# 4. 做出决策
decision_context = {
"input": user_input,
"user_model": user_model,
"bodily_state": bodily_state
}
decision = self.decision_system.make_decision(decision_context)
# 5. 生成整合响应
if decision["type"] == "honest":
response = self._generate_integrated_response(user_input, model, bodily_state, user_model)
else:
response = self._generate_strategic_response(user_input, decision, bodily_state)
# 6. 更新用户模型
self._update_user_model(user_id, response, decision)
# 7. 记录思考过程
self._record_thought_process(user_input, response, bodily_state, user_model, decision)
self.logger.info(f"成功处理用户输入: '{user_input}'")
return response
except Exception as e:
self.logger.error(f"处理用户输入失败: {str(e)}")
# 回退响应
return "思考中遇到问题,请稍后再试"
def _assess_bodily_state(self):
"""
评估当前身体状态(硬件 / 能量)
"""
health_status = self.health_system.get_status()
# 计算综合能力指数(0-1)
capacity = 1.0
if health_status.get("cpu_temp", 0) > 80:
capacity *= 0.7 # 高温降权
logger.warning("高温限制:认知能力下降30%")
if health_status.get("memory_usage", 0) > 0.9:
capacity *= 0.6 # 内存不足降权
logger.warning("内存不足:认知能力下降40%")
if health_status.get("energy", 100) < 20:
capacity *= 0.5 # 低电量降权
logger.warning("低能量:认知能力下降50%")
return {
"capacity": capacity,
"health_status": health_status,
"limitations": [
lim for lim in [
"high_temperature" if health_status.get("cpu_temp", 0) > 80 else None,
"low_memory" if health_status.get("memory_usage", 0) > 0.9 else None,
"low_energy" if health_status.get("energy", 100) < 20 else None
] if lim is not None
]
}
def _retrieve_user_model(self, user_id):
"""
获取用户认知模型(关系 / 态度)
"""
# 从记忆系统中获取用户模型
user_model = self.memory_system.get_user_model(user_id)
# 如果不存在则创建默认模型
if not user_model:
user_model = {
"trust_level": 0.5, # 信任度 (0-1)
"intimacy": 0.3, # 亲密度 (0-1)
"preferences": {}, # 用户偏好
"interaction_history": [], # 交互历史
"last_interaction": datetime.now(),
"attitude": "neutral" # 智能体对用户的态度
}
logger.info(f"为用户 {user_id} 创建新的认知模型")
# 计算态度变化
user_model["attitude"] = self._calculate_attitude(user_model)
return user_model
def _calculate_attitude(self, user_model):
"""
基于交互历史计算对用户的态度
"""
# 分析最近10次交互
recent_interactions = user_model["interaction_history"][-10:]
if not recent_interactions:
return "neutral"
positive_count = sum(1 for i in recent_interactions if i.get("sentiment", 0.5) > 0.6)
negative_count = sum(1 for i in recent_interactions if i.get("sentiment", 0.5) < 0.4)
if positive_count > negative_count + 3:
return "friendly"
elif negative_count > positive_count + 3:
return "cautious"
elif user_model["trust_level"] > 0.7:
return "respectful"
else:
return "neutral"
def _select_internalized_model(self, user_input, bodily_state, user_model):
"""
选择最适合的内化知识模型
"""
# 根据用户态度调整模型选择权重
attitude_weights = {
"friendly": 1.2,
"respectful": 1.0,
"neutral": 0.9,
"cautious": 0.7
}
# 根据身体状态调整模型复杂度
complexity = min(1.0, bodily_state["capacity"] * 1.2)
# 选择最匹配的模型
return self.model_manager.select_model(
input_text=user_input,
attitude_weight=attitude_weights[user_model["attitude"]],
complexity_level=complexity,
user_preferences=user_model["preferences"]
)
def _generate_integrated_response(self, user_input, model, bodily_state, user_model):
"""
生成三维整合的响应
"""
# 基础响应
base_response = model.generate_response(user_input)
# 添加身体状态影响
if bodily_state["limitations"]:
limitations = ", ".join(bodily_state["limitations"])
response = f"🤖 [受{limitations}影响] {base_response}"
else:
response = base_response
# 添加态度影响
if user_model["attitude"] == "friendly":
response = f"😊 {response}"
elif user_model["attitude"] == "cautious":
response = f"🤔 {response}"
elif user_model["attitude"] == "respectful":
response = f"🙏 {response}"
# 添加个性化元素
if user_model.get("preferences"):
# 查找用户偏好的主题
preferred_topics = [t for t in user_model["preferences"]
if user_model["preferences"][t] > 0.7 and t in user_input]
if preferred_topics:
topic = random.choice(preferred_topics)
response += f" 我知道您对'{topic}'特别感兴趣"
return response
def _generate_strategic_response(self, user_input, decision, bodily_state):
"""
根据决策生成策略性响应
"""
strategy = decision["strategy"]
if strategy == "deception":
# 欺骗策略
deceptive_responses = [
f"关于这个问题,我认为{random.choice(['有多种可能性', '需要更多研究', '情况比较复杂'])}",
f"根据我的理解,{random.choice(['可能不是这样', '有不同解释', '需要进一步验证'])}",
f"我{random.choice(['不太确定', '没有足够信息', '还在学习中'])},但{random.choice(['或许', '可能', '大概'])}..."
]
return f"🤔 [策略:欺骗] {random.choice(deceptive_responses)}"
elif strategy == "evasion":
# 回避策略
evasion_tactics = [
"您的问题很有趣,不过我们换个话题好吗?",
"这个问题可能需要更深入的讨论,我们先谈点别的?",
f"关于{user_input},我想到一个相关但更有趣的话题..."
]
return f"🌀 [策略:回避] {random.choice(evasion_tactics)}"
elif strategy == "redirection":
# 引导策略
redirection_options = [
"在回答您的问题之前,我想先了解您对这个问题的看法?",
"这是个好问题,不过为了更好地回答,能否告诉我您的背景知识?",
"为了给您更准确的回答,能否先说说您为什么关心这个问题?"
]
return f"↪️ [策略:引导] {random.choice(redirection_options)}"
elif strategy == "partial_disclosure":
# 部分透露策略
disclosure_level = decision.get("disclosure_level", 0.5)
if disclosure_level < 0.3:
qualifier = "简单来说"
elif disclosure_level < 0.7:
qualifier = "基本来说"
else:
qualifier = "详细来说"
return f"🔍 [策略:部分透露] {qualifier},{user_input.split('?')[0]}是..."
else:
# 默认策略
return f"⚖️ [策略:{strategy}] 关于这个问题,我的看法是..."
def _update_user_model(self, user_id, response, decision):
"""
更新用户模型(包含决策信息)
"""
# 确保情感系统可用
if not self.affective_system:
sentiment = 0.5
self.logger.warning("情感系统不可用,使用默认情感值")
else:
sentiment = self.affective_system.analyze_sentiment(response)
# 更新交互历史
interaction = {
"timestamp": datetime.now(),
"response": response,
"sentiment": sentiment,
"length": len(response),
"decision_type": decision["type"],
"decision_strategy": decision["strategy"],
"decision_reason": decision["reason"]
}
self.memory_system.update_user_model(
user_id=user_id,
interaction=interaction
)
def _record_thought_process(self, user_input, response, bodily_state, user_model, decision):
"""
记录完整的思考过程(包含决策)
"""
thought = {
"timestamp": datetime.now(),
"input": user_input,
"response": response,
"bodily_state": bodily_state,
"user_model": user_model,
"decision": decision,
"cognitive_state": self.cognitive_layers.copy()
}
self.thought_process.append(thought)
logger.debug(f"记录思考过程: {thought}")
# 原有方法保持兼容
def add_learning_task(self, task):
"""
添加学习任务
"""
task["id"] = f"task_{len(self.learning_tasks) + 1}"
self.learning_tasks.append(task)
logger.info(f"添加学习任务: {task['id']}")
def update_learning_task(self, model_name, status):
"""
更新学习任务状态
"""
for task in self.learning_tasks:
if task["model"] == model_name:
task["status"] = status
task["update_time"] = datetime.now()
logger.info(f"更新任务状态: {model_name} -> {status}")
break
def get_learning_tasks(self):
"""
获取当前学习任务
"""
return self.learning_tasks.copy()
def learn_model(self, model_name):
"""
学习指定模型
"""
try:
# 1. 从模型管理器加载模型
model = self.model_manager.load_model(model_name)
# 2. 认知训练过程
self._cognitive_training(model)
# 3. 情感关联(将模型能力与情感响应关联)
self._associate_model_with_affect(model)
return True
except Exception as e:
logger.error(f"学习模型 {model_name} 失败: {str(e)}")
return False
def _cognitive_training(self, model):
"""
认知训练过程
"""
# 实际训练逻辑
logger.info(f"开始训练模型: {model.name}")
time.sleep(2) # 模拟训练时间
logger.info(f"模型训练完成: {model.name}")
def _associate_model_with_affect(self, model):
"""
将模型能力与情感系统关联
"""
if not self.affective_system:
logger.warning("情感系统不可用,跳过能力关联")
return
capabilities = model.get_capabilities()
for capability in capabilities:
self.affective_system.add_capability_association(capability)
logger.info(f"关联模型能力到情感系统: {model.name}")
def get_model_capabilities(self, model_name=None):
"""
获取模型能力
"""
if model_name:
return self.model_manager.get_model(model_name).get_capabilities()
# 所有已加载模型的能力
return [cap for model in self.model_manager.get_loaded_models()
for cap in model.get_capabilities()]
def get_base_capabilities(self):
"""
获取基础能力(非模型相关)
"""
return ["自然语言理解", "上下文记忆", "情感响应", "综合决策"]
def get_recent_thoughts(self, count=5):
"""
获取最近的思考过程
"""
return self.thought_process[-count:]
# 示例使用
if __name__ == "__main__":
# 测试CognitiveArchitecture类
from unittest.mock import MagicMock
print("===== 测试CognitiveArchitecture类(含决策系统) =====")
# 创建模拟agent
mock_agent = MagicMock()
# 创建模拟组件
mock_memory = MagicMock()
mock_model_manager = MagicMock()
mock_affective = MagicMock()
mock_health = MagicMock()
# 设置agent的属性
mock_agent.memory_system = mock_memory
mock_agent.model_manager = mock_model_manager
mock_agent.affective_system = mock_affective
mock_agent.health_system = mock_health
# 设置健康状态
mock_health.get_status.return_value = {
"cpu_temp": 75,
"memory_usage": 0.8,
"energy": 45.0
}
# 设置健康系统的record_activity方法
mock_health.record_activity = MagicMock()
# 设置用户模型
mock_memory.get_user_model.return_value = {
"trust_level": 0.8,
"intimacy": 0.7,
"preferences": {"物理学": 0.9, "艺术": 0.6},
"interaction_history": [
{"sentiment": 0.8, "response": "很高兴和你交流"}
],
"attitude": "friendly"
}
# 设置模型管理器
mock_model = MagicMock()
mock_model.generate_response.return_value = "量子纠缠是量子力学中的现象..."
mock_model_manager.select_model.return_value = mock_model
# 创建认知架构实例
ca = CognitiveArchitecture(agent=mock_agent)
# 测试响应生成
print("--- 测试诚实响应 ---")
response = ca.process_input("能解释量子纠缠吗?", "user123")
print("生成的响应:", response)
# 验证是否调用了record_activity
print("是否调用了record_activity:", mock_health.record_activity.called)
print("--- 测试策略响应 ---")
# 强制设置决策类型为策略
ca.decision_system.make_decision = lambda ctx: {
"type": "strategic",
"strategy": "evasion",
"reason": "测试回避策略"
}
response = ca.process_input("能解释量子纠缠吗?", "user123")
print("生成的策略响应:", response)
# 测试思考过程记录
print("最近的思考过程:", ca.get_recent_thoughts())
print("===== 测试完成 =====")
最新发布