feat:添加了心流的配置项

This commit is contained in:
SengokuCola
2025-03-30 23:28:33 +08:00
parent efa9213849
commit cc22351104
15 changed files with 69 additions and 60 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

169
src/heart_flow/heartflow.py Normal file
View File

@@ -0,0 +1,169 @@
from .sub_heartflow import SubHeartflow
from .observation import ChattingObservation
from src.plugins.moods.moods import MoodManager
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config
from src.plugins.schedule.schedule_generator import bot_schedule
import asyncio
from src.common.logger import get_module_logger, LogConfig, HEARTFLOW_STYLE_CONFIG # noqa: E402
import time
heartflow_config = LogConfig(
# 使用海马体专用样式
console_format=HEARTFLOW_STYLE_CONFIG["console_format"],
file_format=HEARTFLOW_STYLE_CONFIG["file_format"],
)
logger = get_module_logger("heartflow", config=heartflow_config)
class CuttentState:
def __init__(self):
self.willing = 0
self.current_state_info = ""
self.mood_manager = MoodManager()
self.mood = self.mood_manager.get_prompt()
def update_current_state_info(self):
self.current_state_info = self.mood_manager.get_current_mood()
class Heartflow:
def __init__(self):
self.current_mind = "你什么也没想"
self.past_mind = []
self.current_state: CuttentState = CuttentState()
self.llm_model = LLM_request(
model=global_config.llm_heartflow, temperature=0.6, max_tokens=1000, request_type="heart_flow"
)
self._subheartflows = {}
self.active_subheartflows_nums = 0
self.personality_info = " ".join(global_config.PROMPT_PERSONALITY)
async def _cleanup_inactive_subheartflows(self):
"""定期清理不活跃的子心流"""
while True:
current_time = time.time()
inactive_subheartflows = []
# 检查所有子心流
for subheartflow_id, subheartflow in self._subheartflows.items():
if current_time - subheartflow.last_active_time > global_config.sub_heart_flow_stop_time: # 10分钟 = 600秒
inactive_subheartflows.append(subheartflow_id)
logger.info(f"发现不活跃的子心流: {subheartflow_id}")
# 清理不活跃的子心流
for subheartflow_id in inactive_subheartflows:
del self._subheartflows[subheartflow_id]
logger.info(f"已清理不活跃的子心流: {subheartflow_id}")
await asyncio.sleep(30) # 每分钟检查一次
async def heartflow_start_working(self):
# 启动清理任务
asyncio.create_task(self._cleanup_inactive_subheartflows())
while True:
# 检查是否存在子心流
if not self._subheartflows:
logger.info("当前没有子心流,等待新的子心流创建...")
await asyncio.sleep(30) # 每分钟检查一次是否有新的子心流
continue
await self.do_a_thinking()
await asyncio.sleep(global_config.heart_flow_update_interval) # 5分钟思考一次
async def do_a_thinking(self):
logger.debug("麦麦大脑袋转起来了")
self.current_state.update_current_state_info()
personality_info = self.personality_info
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
related_memory_info = "memory"
sub_flows_info = await self.get_all_subheartflows_minds()
schedule_info = bot_schedule.get_current_num_task(num=4, time_info=True)
prompt = ""
prompt += f"你刚刚在做的事情是:{schedule_info}\n"
prompt += f"{personality_info}\n"
prompt += f"你想起来{related_memory_info}"
prompt += f"刚刚你的主要想法是{current_thinking_info}"
prompt += f"你还有一些小想法,因为你在参加不同的群聊天,是你正在做的事情:{sub_flows_info}\n"
prompt += f"你现在{mood_info}"
prompt += "现在你接下去继续思考,产生新的想法,但是要基于原有的主要想法,不要分点输出,"
prompt += "输出连贯的内心独白,不要太长,但是记得结合上述的消息,关注新内容:"
reponse, reasoning_content = await self.llm_model.generate_response_async(prompt)
self.update_current_mind(reponse)
self.current_mind = reponse
logger.info(f"麦麦的总体脑内状态:{self.current_mind}")
# logger.info("麦麦想了想,当前活动:")
await bot_schedule.move_doing(self.current_mind)
for _, subheartflow in self._subheartflows.items():
subheartflow.main_heartflow_info = reponse
def update_current_mind(self, reponse):
self.past_mind.append(self.current_mind)
self.current_mind = reponse
async def get_all_subheartflows_minds(self):
sub_minds = ""
for _, subheartflow in self._subheartflows.items():
sub_minds += subheartflow.current_mind
return await self.minds_summary(sub_minds)
async def minds_summary(self, minds_str):
personality_info = self.personality_info
mood_info = self.current_state.mood
prompt = ""
prompt += f"{personality_info}\n"
prompt += f"现在{global_config.BOT_NICKNAME}的想法是:{self.current_mind}\n"
prompt += f"现在{global_config.BOT_NICKNAME}在qq群里进行聊天聊天的话题如下{minds_str}\n"
prompt += f"你现在{mood_info}\n"
prompt += """现在请你总结这些聊天内容,注意关注聊天内容对原有的想法的影响,输出连贯的内心独白
不要太长,但是记得结合上述的消息,要记得你的人设,关注新内容:"""
reponse, reasoning_content = await self.llm_model.generate_response_async(prompt)
return reponse
def create_subheartflow(self, subheartflow_id):
"""
创建一个新的SubHeartflow实例
添加一个SubHeartflow实例到self._subheartflows字典中
并根据subheartflow_id为子心流创建一个观察对象
"""
if subheartflow_id not in self._subheartflows:
logger.debug(f"创建 subheartflow: {subheartflow_id}")
subheartflow = SubHeartflow(subheartflow_id)
# 创建一个观察对象目前只可以用chat_id创建观察对象
logger.debug(f"创建 observation: {subheartflow_id}")
observation = ChattingObservation(subheartflow_id)
logger.debug("添加 observation ")
subheartflow.add_observation(observation)
logger.debug("添加 observation 成功")
# 创建异步任务
logger.debug("创建异步任务")
asyncio.create_task(subheartflow.subheartflow_start_working())
logger.debug("创建异步任务 成功")
self._subheartflows[subheartflow_id] = subheartflow
logger.info("添加 subheartflow 成功")
return self._subheartflows[subheartflow_id]
def get_subheartflow(self, observe_chat_id):
"""获取指定ID的SubHeartflow实例"""
return self._subheartflows.get(observe_chat_id)
# 创建一个全局的管理器实例
heartflow = Heartflow()

View File

@@ -0,0 +1,123 @@
# 定义了来自外部世界的信息
# 外部世界可以是某个聊天 不同平台的聊天 也可以是任意媒体
from datetime import datetime
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config
from src.common.database import db
# 所有观察的基类
class Observation:
def __init__(self, observe_type, observe_id):
self.observe_info = ""
self.observe_type = observe_type
self.observe_id = observe_id
self.last_observe_time = datetime.now().timestamp() # 初始化为当前时间
# 聊天观察
class ChattingObservation(Observation):
def __init__(self, chat_id):
super().__init__("chat", chat_id)
self.chat_id = chat_id
self.talking_message = []
self.talking_message_str = ""
self.observe_times = 0
self.summary_count = 0 # 30秒内的更新次数
self.max_update_in_30s = 2 # 30秒内最多更新2次
self.last_summary_time = 0 # 上次更新summary的时间
self.sub_observe = None
self.llm_summary = LLM_request(
model=global_config.llm_observation, temperature=0.7, max_tokens=300, request_type="outer_world"
)
# 进行一次观察 返回观察结果observe_info
async def observe(self):
# 查找新消息限制最多30条
new_messages = list(
db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}})
.sort("time", 1)
.limit(20)
) # 按时间正序排列最多20条
if not new_messages:
return self.observe_info # 没有新消息,返回上次观察结果
# 将新消息转换为字符串格式
new_messages_str = ""
for msg in new_messages:
if "sender_name" in msg and "content" in msg:
new_messages_str += f"{msg['sender_name']}: {msg['content']}\n"
# 将新消息添加到talking_message同时保持列表长度不超过20条
self.talking_message.extend(new_messages)
if len(self.talking_message) > 20:
self.talking_message = self.talking_message[-20:] # 只保留最新的20条
self.translate_message_list_to_str()
# 更新观察次数
self.observe_times += 1
self.last_observe_time = new_messages[-1]["time"]
# 检查是否需要更新summary
current_time = int(datetime.now().timestamp())
if current_time - self.last_summary_time >= 30: # 如果超过30秒重置计数
self.summary_count = 0
self.last_summary_time = current_time
if self.summary_count < self.max_update_in_30s: # 如果30秒内更新次数小于2次
await self.update_talking_summary(new_messages_str)
self.summary_count += 1
return self.observe_info
async def carefully_observe(self):
# 查找新消息限制最多40条
new_messages = list(
db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}})
.sort("time", 1)
.limit(30)
) # 按时间正序排列最多30条
if not new_messages:
return self.observe_info # 没有新消息,返回上次观察结果
# 将新消息转换为字符串格式
new_messages_str = ""
for msg in new_messages:
if "sender_name" in msg and "content" in msg:
new_messages_str += f"{msg['sender_name']}: {msg['content']}\n"
# 将新消息添加到talking_message同时保持列表长度不超过30条
self.talking_message.extend(new_messages)
if len(self.talking_message) > 30:
self.talking_message = self.talking_message[-30:] # 只保留最新的30条
self.translate_message_list_to_str()
# 更新观察次数
self.observe_times += 1
self.last_observe_time = new_messages[-1]["time"]
await self.update_talking_summary(new_messages_str)
return self.observe_info
async def update_talking_summary(self, new_messages_str):
# 基于已经有的talking_summary和新的talking_message生成一个summary
# print(f"更新聊天总结:{self.talking_summary}")
prompt = ""
prompt = f"你正在参与一个qq群聊的讨论这个群之前在聊的内容是{self.observe_info}\n"
prompt += f"现在群里的群友们产生了新的讨论,有了新的发言,具体内容如下:{new_messages_str}\n"
prompt += """以上是群里在进行的聊天,请你对这个聊天内容进行总结,总结内容要包含聊天的大致内容,
以及聊天中的一些重要信息,记得不要分点,不要太长,精简的概括成一段文本\n"""
prompt += "总结概括:"
self.observe_info, reasoning_content = await self.llm_summary.generate_response_async(prompt)
def translate_message_list_to_str(self):
self.talking_message_str = ""
for message in self.talking_message:
self.talking_message_str += message["detailed_plain_text"]

View File

@@ -0,0 +1,208 @@
from .observation import Observation
import asyncio
from src.plugins.moods.moods import MoodManager
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config
import re
import time
from src.plugins.schedule.schedule_generator import bot_schedule
from src.plugins.memory_system.Hippocampus import HippocampusManager
from src.common.logger import get_module_logger, LogConfig, SUB_HEARTFLOW_STYLE_CONFIG # noqa: E402
subheartflow_config = LogConfig(
# 使用海马体专用样式
console_format=SUB_HEARTFLOW_STYLE_CONFIG["console_format"],
file_format=SUB_HEARTFLOW_STYLE_CONFIG["file_format"],
)
logger = get_module_logger("subheartflow", config=subheartflow_config)
class CuttentState:
def __init__(self):
self.willing = 0
self.current_state_info = ""
self.mood_manager = MoodManager()
self.mood = self.mood_manager.get_prompt()
def update_current_state_info(self):
self.current_state_info = self.mood_manager.get_current_mood()
class SubHeartflow:
def __init__(self, subheartflow_id):
self.subheartflow_id = subheartflow_id
self.current_mind = ""
self.past_mind = []
self.current_state: CuttentState = CuttentState()
self.llm_model = LLM_request(
model=global_config.llm_sub_heartflow, temperature=0.7, max_tokens=600, request_type="sub_heart_flow"
)
self.main_heartflow_info = ""
self.last_reply_time = time.time()
self.last_active_time = time.time() # 添加最后激活时间
if not self.current_mind:
self.current_mind = "你什么也没想"
self.personality_info = " ".join(global_config.PROMPT_PERSONALITY)
self.is_active = False
self.observations: list[Observation] = []
def add_observation(self, observation: Observation):
"""添加一个新的observation对象到列表中如果已存在相同id的observation则不添加"""
# 查找是否存在相同id的observation
for existing_obs in self.observations:
if existing_obs.observe_id == observation.observe_id:
# 如果找到相同id的observation直接返回
return
# 如果没有找到相同id的observation则添加新的
self.observations.append(observation)
def remove_observation(self, observation: Observation):
"""从列表中移除一个observation对象"""
if observation in self.observations:
self.observations.remove(observation)
def get_all_observations(self) -> list[Observation]:
"""获取所有observation对象"""
return self.observations
def clear_observations(self):
"""清空所有observation对象"""
self.observations.clear()
async def subheartflow_start_working(self):
while True:
current_time = time.time()
if current_time - self.last_reply_time > global_config.sub_heart_flow_freeze_time: # 120秒无回复/不在场,冻结
self.is_active = False
await asyncio.sleep(global_config.sub_heart_flow_update_interval) # 每60秒检查一次
else:
self.is_active = True
self.last_active_time = current_time # 更新最后激活时间
observation = self.observations[0]
await observation.observe()
self.current_state.update_current_state_info()
await self.do_a_thinking()
await self.judge_willing()
await asyncio.sleep(global_config.sub_heart_flow_update_interval)
# 检查是否超过10分钟没有激活
if current_time - self.last_active_time > global_config.sub_heart_flow_stop_time: # 5分钟无回复/不在场,销毁
logger.info(f"子心流 {self.subheartflow_id} 已经5分钟没有激活正在销毁...")
break # 退出循环,销毁自己
async def do_a_thinking(self):
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
observation = self.observations[0]
chat_observe_info = observation.observe_info
print(f"chat_observe_info{chat_observe_info}")
# 调取记忆
related_memory = await HippocampusManager.get_instance().get_memory_from_text(
text=chat_observe_info, max_memory_num=2, max_memory_length=2, max_depth=3, fast_retrieval=False
)
if related_memory:
related_memory_info = ""
for memory in related_memory:
related_memory_info += memory[1]
else:
related_memory_info = ""
# print(f"相关记忆:{related_memory_info}")
schedule_info = bot_schedule.get_current_num_task(num=1, time_info=False)
prompt = ""
prompt += f"你刚刚在做的事情是:{schedule_info}\n"
# prompt += f"麦麦的总体想法是:{self.main_heartflow_info}\n\n"
prompt += f"{self.personality_info}\n"
if related_memory_info:
prompt += f"你想起来你之前见过的回忆:{related_memory_info}\n以上是你的回忆,不一定是目前聊天里的人说的,也不一定是现在发生的事情,请记住。\n"
prompt += f"刚刚你的想法是{current_thinking_info}\n"
prompt += "-----------------------------------\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
prompt += f"你现在{mood_info}\n"
prompt += "现在你接下去继续思考,产生新的想法,不要分点输出,输出连贯的内心独白,不要太长,"
prompt += "但是记得结合上述的消息,要记得维持住你的人设,关注聊天和新内容,不要思考太多:"
reponse, reasoning_content = await self.llm_model.generate_response_async(prompt)
self.update_current_mind(reponse)
self.current_mind = reponse
logger.debug(f"prompt:\n{prompt}\n")
logger.info(f"麦麦的脑内状态:{self.current_mind}")
async def do_after_reply(self, reply_content, chat_talking_prompt):
# print("麦麦脑袋转起来了")
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
observation = self.observations[0]
chat_observe_info = observation.observe_info
message_new_info = chat_talking_prompt
reply_info = reply_content
schedule_info = bot_schedule.get_current_num_task(num=1, time_info=False)
prompt = ""
prompt += f"你现在正在做的事情是:{schedule_info}\n"
prompt += f"{self.personality_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
prompt += f"刚刚你的想法是{current_thinking_info}"
prompt += f"你现在看到了网友们发的新消息:{message_new_info}\n"
prompt += f"你刚刚回复了群友们:{reply_info}"
prompt += f"你现在{mood_info}"
prompt += "现在你接下去继续思考,产生新的想法,记得保留你刚刚的想法,不要分点输出,输出连贯的内心独白"
prompt += "不要太长,但是记得结合上述的消息,要记得你的人设,关注聊天和新内容,关注你回复的内容,不要思考太多:"
reponse, reasoning_content = await self.llm_model.generate_response_async(prompt)
self.update_current_mind(reponse)
self.current_mind = reponse
logger.info(f"麦麦回复后的脑内状态:{self.current_mind}")
self.last_reply_time = time.time()
async def judge_willing(self):
# print("麦麦闹情绪了1")
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
# print("麦麦闹情绪了2")
prompt = ""
prompt += f"{self.personality_info}\n"
prompt += "现在你正在上网和qq群里的网友们聊天"
prompt += f"你现在的想法是{current_thinking_info}"
prompt += f"你现在{mood_info}"
prompt += "现在请你思考你想不想发言或者回复请你输出一个数字1-101表示非常不想10表示非常想。"
prompt += "请你用<>包裹你的回复意愿,输出<1>表示不想回复,输出<10>表示非常想回复。请你考虑,你完全可以不回复"
response, reasoning_content = await self.llm_model.generate_response_async(prompt)
# 解析willing值
willing_match = re.search(r"<(\d+)>", response)
if willing_match:
self.current_state.willing = int(willing_match.group(1))
else:
self.current_state.willing = 0
return self.current_state.willing
def update_current_mind(self, reponse):
self.past_mind.append(self.current_mind)
self.current_mind = reponse
# subheartflow = SubHeartflow()