better:更好的心流结构,使用了观察取代外部世界

This commit is contained in:
SengokuCola
2025-03-29 23:30:27 +08:00
parent 803ae55876
commit b8828e81c6
39 changed files with 304 additions and 420 deletions

View File

@@ -7,8 +7,8 @@ from pathlib import Path
from dotenv import load_dotenv
# from ..plugins.chat.config import global_config
# 加载 .env.prod 文件
env_path = Path(__file__).resolve().parent.parent.parent / ".env.prod"
# 加载 .env 文件
env_path = Path(__file__).resolve().parent.parent.parent / ".env"
load_dotenv(dotenv_path=env_path)
# 保存原生处理器ID

View File

@@ -26,8 +26,8 @@ from src.common.database import db # noqa: E402
if os.path.exists(os.path.join(root_dir, ".env.dev")):
load_dotenv(os.path.join(root_dir, ".env.dev"))
logger.info("成功加载开发环境配置")
elif os.path.exists(os.path.join(root_dir, ".env.prod")):
load_dotenv(os.path.join(root_dir, ".env.prod"))
elif os.path.exists(os.path.join(root_dir, ".env")):
load_dotenv(os.path.join(root_dir, ".env"))
logger.info("成功加载生产环境配置")
else:
logger.error("未找到环境配置文件")

View File

@@ -8,10 +8,8 @@ from .plugins.chat.emoji_manager import emoji_manager
from .plugins.chat.relationship_manager import relationship_manager
from .plugins.willing.willing_manager import willing_manager
from .plugins.chat.chat_stream import chat_manager
from .think_flow_demo.heartflow import heartflow
from .plugins.memory_system.Hippocampus import HippocampusManager
from .plugins.chat import auto_speak_manager
from .think_flow_demo.heartflow import subheartflow_manager
from .think_flow_demo.outer_world import outer_world
from .plugins.chat.message_sender import message_manager
from .plugins.chat.storage import MessageStorage
from .plugins.config.config import global_config
@@ -73,8 +71,8 @@ class MainSystem:
asyncio.create_task(chat_manager._auto_save_task())
# 使用HippocampusManager初始化海马体
self.hippocampus_manager.initialize(global_config=global_config)
# await asyncio.sleep(0.5) #防止logger输出飞了
# 初始化日程
bot_schedule.initialize(
@@ -89,14 +87,12 @@ class MainSystem:
self.app.register_message_handler(chat_bot.message_process)
try:
asyncio.create_task(outer_world.open_eyes())
logger.success("大脑和外部世界启动成功")
# 启动心流系统
asyncio.create_task(subheartflow_manager.heartflow_start_working())
asyncio.create_task(heartflow.heartflow_start_working())
logger.success("心流系统启动成功")
init_end_time = time.time()
logger.success(f"初始化完成,用时{init_end_time - init_start_time}")
init_time = int(1000*(time.time()- init_start_time))
logger.success(f"初始化完成,神经元放电{init_time}")
except Exception as e:
logger.error(f"启动大脑和外部世界失败: {e}")
raise
@@ -107,9 +103,7 @@ class MainSystem:
tasks = [
self.build_memory_task(),
self.forget_memory_task(),
# self.merge_memory_task(),
self.print_mood_task(),
# self.generate_schedule_task(),
self.remove_recalled_message_task(),
emoji_manager.start_periodic_check(),
self.app.run(),
@@ -132,26 +126,12 @@ class MainSystem:
print("\033[1;32m[记忆遗忘]\033[0m 记忆遗忘完成")
await asyncio.sleep(global_config.forget_memory_interval)
# async def merge_memory_task(self):
# """记忆整合任务"""
# while True:
# logger.info("正在进行记忆整合")
# await asyncio.sleep(global_config.build_memory_interval + 10)
async def print_mood_task(self):
"""打印情绪状态"""
while True:
self.mood_manager.print_mood_status()
await asyncio.sleep(30)
# async def generate_schedule_task(self):
# """生成日程任务"""
# while True:
# await bot_schedule.initialize()
# if not bot_schedule.enable_output:
# bot_schedule.print_schedule()
# await asyncio.sleep(7200)
async def remove_recalled_message_task(self):
"""删除撤回消息任务"""
while True:

View File

@@ -10,7 +10,7 @@ from .message_sender import message_manager
from ..moods.moods import MoodManager
from .llm_generator import ResponseGenerator
from src.common.logger import get_module_logger
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.heartflow import heartflow
from ...common.database import db
logger = get_module_logger("auto_speak")
@@ -42,7 +42,7 @@ class AutoSpeakManager:
while True and global_config.enable_think_flow:
# 获取所有活跃的子心流
active_subheartflows = []
for chat_id, subheartflow in subheartflow_manager._subheartflows.items():
for chat_id, subheartflow in heartflow._subheartflows.items():
if (
subheartflow.is_active and subheartflow.current_state.willing > 0
): # 只考虑活跃且意愿值大于0.5的子心流

View File

@@ -1,7 +1,6 @@
import re
import time
from random import random
import json
from ..memory_system.Hippocampus import HippocampusManager
from ..moods.moods import MoodManager # 导入情绪管理器
@@ -18,10 +17,9 @@ from .storage import MessageStorage
from .utils import is_mentioned_bot_in_message, get_recent_group_detailed_plain_text
from .utils_image import image_path_to_base64
from ..willing.willing_manager import willing_manager # 导入意愿管理器
from ..message import UserInfo, GroupInfo, Seg
from ..message import UserInfo, Seg
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.outer_world import outer_world
from src.think_flow_demo.heartflow import heartflow
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
# 定义日志配置
@@ -58,7 +56,7 @@ class ChatBot:
5. 更新关系
6. 更新情绪
"""
message = MessageRecv(message_data)
groupinfo = message.message_info.group_info
userinfo = message.message_info.user_info
@@ -74,18 +72,8 @@ class ChatBot:
)
message.update_chat_stream(chat)
# 创建 心流 观察
await outer_world.check_and_add_new_observe()
subheartflow_manager.create_subheartflow(chat.stream_id)
timer1 = time.time()
await relationship_manager.update_relationship(
chat_stream=chat,
)
await relationship_manager.update_relationship_value(chat_stream=chat, relationship_value=0)
timer2 = time.time()
logger.info(f"1关系更新时间: {timer2 - timer1}")
# 创建 心流与chat的观察
heartflow.create_subheartflow(chat.stream_id)
timer1 = time.time()
await message.process()
@@ -99,10 +87,9 @@ class ChatBot:
):
return
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
# 根据话题计算激活度
await self.storage.store_message(message, chat)
timer1 = time.time()
interested_rate = 0
@@ -117,8 +104,8 @@ class ChatBot:
if global_config.enable_think_flow:
current_willing_old = willing_manager.get_willing(chat_stream=chat)
current_willing_new = (subheartflow_manager.get_subheartflow(chat.stream_id).current_state.willing - 5) / 4
print(f"4旧回复意愿:{current_willing_old},新回复意愿:{current_willing_new}")
current_willing_new = (heartflow.get_subheartflow(chat.stream_id).current_state.willing - 5) / 4
print(f"旧回复意愿:{current_willing_old},新回复意愿:{current_willing_new}")
current_willing = (current_willing_old + current_willing_new) / 2
else:
current_willing = willing_manager.get_willing(chat_stream=chat)
@@ -147,7 +134,8 @@ class ChatBot:
else:
mes_name = '私聊'
# print(f"mes_name: {mes_name}")
#打印收到的信息的信息
current_time = time.strftime("%H:%M:%S", time.localtime(messageinfo.time))
logger.info(
f"[{current_time}][{mes_name}]"
f"{chat.user_info.user_nickname}:"
@@ -225,7 +213,7 @@ class ChatBot:
return response_set, thinking_id
async def _update_using_response(self, message, chat, response_set):
async def _update_using_response(self, message, response_set):
# 更新心流状态
stream_id = message.chat_stream.stream_id
chat_talking_prompt = ""
@@ -234,10 +222,10 @@ class ChatBot:
stream_id, limit=global_config.MAX_CONTEXT_SIZE, combine=True
)
if subheartflow_manager.get_subheartflow(stream_id):
await subheartflow_manager.get_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
if heartflow.get_subheartflow(stream_id):
await heartflow.get_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
else:
await subheartflow_manager.create_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
await heartflow.create_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
async def _send_response_messages(self, message, chat, response_set, thinking_id):

View File

@@ -97,9 +97,7 @@ class ResponseGenerator:
logger.info(f"构建prompt时间: {timer2 - timer1}")
try:
print(111111111111111111111111111111111111111111111111111111111)
content, reasoning_content, self.current_model_name = await model.generate_response(prompt)
print(222222222222222222222222222222222222222222222222222222222)
except Exception:
logger.exception("生成回复时出错")
return None

View File

@@ -12,7 +12,7 @@ from .chat_stream import chat_manager
from .relationship_manager import relationship_manager
from src.common.logger import get_module_logger
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.heartflow import heartflow
logger = get_module_logger("prompt")
@@ -34,12 +34,11 @@ class PromptBuilder:
# )
# outer_world_info = outer_world.outer_world_info
if global_config.enable_think_flow:
current_mind_info = subheartflow_manager.get_subheartflow(stream_id).current_mind
else:
current_mind_info = ""
relation_prompt = ""
current_mind_info = heartflow.get_subheartflow(stream_id).current_mind
# relation_prompt = ""
# for person in who_chat_in_group:
# relation_prompt += relationship_manager.build_relationship_info(person)
@@ -74,23 +73,22 @@ class PromptBuilder:
chat_talking_prompt = chat_talking_prompt
# print(f"\033[1;34m[调试]\033[0m 已从数据库获取群 {group_id} 的消息记录:{chat_talking_prompt}")
logger.info(f"聊天上下文prompt: {chat_talking_prompt}")
# 使用新的记忆获取方法
memory_prompt = ""
start_time = time.time()
# 调用 hippocampus 的 get_relevant_memories 方法
# relevant_memories = await HippocampusManager.get_instance().get_memory_from_text(
# text=message_txt, max_memory_num=3, max_memory_length=2, max_depth=2, fast_retrieval=True
# )
# memory_str = ""
# for _topic, memories in relevant_memories:
# memory_str += f"{memories}\n"
#调用 hippocampus 的 get_relevant_memories 方法
relevant_memories = await HippocampusManager.get_instance().get_memory_from_text(
text=message_txt, max_memory_num=3, max_memory_length=2, max_depth=2, fast_retrieval=False
)
memory_str = ""
for _topic, memories in relevant_memories:
memory_str += f"{memories}\n"
# if relevant_memories:
# # 格式化记忆内容
# memory_prompt = f"你回忆起:\n{memory_str}\n"
if relevant_memories:
# 格式化记忆内容
memory_prompt = f"你回忆起:\n{memory_str}\n"
end_time = time.time()
logger.info(f"回忆耗时: {(end_time - start_time):.3f}")

View File

@@ -29,7 +29,7 @@ class EnvConfig:
if env_type == 'dev':
env_file = self.ROOT_DIR / '.env.dev'
elif env_type == 'prod':
env_file = self.ROOT_DIR / '.env.prod'
env_file = self.ROOT_DIR / '.env'
if env_file.exists():
load_dotenv(env_file, override=True)

View File

@@ -1266,13 +1266,13 @@ class HippocampusManager:
node_count = len(memory_graph.nodes())
edge_count = len(memory_graph.edges())
logger.success("--------------------------------")
logger.success("记忆系统参数配置:")
logger.success(f"构建间隔: {global_config.build_memory_interval}秒|样本数: {config.build_memory_sample_num},长度: {config.build_memory_sample_length}|压缩率: {config.memory_compress_rate}") # noqa: E501
logger.success(f"记忆构建分布: {config.memory_build_distribution}")
logger.success(f"遗忘间隔: {global_config.forget_memory_interval}秒|遗忘比例: {global_config.memory_forget_percentage}|遗忘: {config.memory_forget_time}小时之后") # noqa: E501
logger.success(f"记忆图统计信息: 节点数量: {node_count}, 连接数量: {edge_count}")
logger.success("--------------------------------")
logger.success(f'''--------------------------------
记忆系统参数配置:
构建间隔: {global_config.build_memory_interval}秒|样本数: {config.build_memory_sample_num},长度: {config.build_memory_sample_length}|压缩率: {config.memory_compress_rate}
记忆构建分布: {config.memory_build_distribution}
遗忘间隔: {global_config.forget_memory_interval}秒|遗忘比例: {global_config.memory_forget_percentage}|遗忘: {config.memory_forget_time}小时之后
记忆图统计信息: 节点数量: {node_count}, 连接数量: {edge_count}
--------------------------------''') #noqa: E501
return self._hippocampus

View File

@@ -164,7 +164,7 @@ class LLM_request:
# 常见Error Code Mapping
error_code_mapping = {
400: "参数不正确",
401: "API key 错误,认证失败,请检查/config/bot_config.toml和.env.prod中的配置是否正确哦~",
401: "API key 错误,认证失败,请检查/config/bot_config.toml和.env中的配置是否正确哦~",
402: "账号余额不足",
403: "需要实名,或余额不足",
404: "Not Found",

View File

@@ -10,7 +10,7 @@ import random
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -17,7 +17,7 @@ import matplotlib.font_manager as fm
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -9,7 +9,7 @@ from scipy import stats # 添加scipy导入用于t检验
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -20,7 +20,7 @@ import sys
"""
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -20,7 +20,7 @@ import sys
"""
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -7,7 +7,7 @@ from typing import List, Dict, Optional
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -84,7 +84,7 @@ class ScheduleGenerator:
self.print_schedule()
# 执行当前活动
# mind_thinking = subheartflow_manager.current_state.current_mind
# mind_thinking = heartflow.current_state.current_mind
await self.move_doing()

View File

@@ -16,7 +16,7 @@ sys.path.append(root_path)
from src.common.database import db # noqa E402
# 加载根目录下的env.edv文件
env_path = os.path.join(root_path, ".env.prod")
env_path = os.path.join(root_path, ".env")
if not os.path.exists(env_path):
raise FileNotFoundError(f"配置文件不存在: {env_path}")
load_dotenv(env_path)

View File

@@ -1,7 +1,8 @@
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, BotConfig
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
@@ -107,15 +108,29 @@ class Heartflow:
return reponse
def create_subheartflow(self, observe_chat_id):
"""创建一个新的SubHeartflow实例"""
if observe_chat_id not in self._subheartflows:
subheartflow = SubHeartflow()
subheartflow.assign_observe(observe_chat_id)
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(f"添加 observation ")
subheartflow.add_observation(observation)
logger.debug(f"添加 observation 成功")
# 创建异步任务
logger.debug(f"创建异步任务")
asyncio.create_task(subheartflow.subheartflow_start_working())
self._subheartflows[observe_chat_id] = subheartflow
return self._subheartflows[observe_chat_id]
logger.debug(f"创建异步任务 成功")
self._subheartflows[subheartflow_id] = subheartflow
logger.debug(f"添加 subheartflow 成功")
return self._subheartflows[subheartflow_id]
def get_subheartflow(self, observe_chat_id):
"""获取指定ID的SubHeartflow实例"""
@@ -123,4 +138,4 @@ class Heartflow:
# 创建一个全局的管理器实例
subheartflow_manager = Heartflow()
heartflow = Heartflow()

View File

@@ -0,0 +1,120 @@
#定义了来自外部世界的信息
#外部世界可以是某个聊天 不同平台的聊天 也可以是任意媒体
import asyncio
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_outer_world, 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

@@ -1,144 +0,0 @@
#定义了来自外部世界的信息
import asyncio
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 Talking_info:
def __init__(self,chat_id):
self.chat_id = chat_id
self.talking_message = []
self.talking_message_str = ""
self.talking_summary = ""
self.last_observe_time = int(datetime.now().timestamp()) #初始化为当前时间
self.observe_times = 0
self.activate = 360
self.last_summary_time = int(datetime.now().timestamp()) # 上次更新summary的时间
self.summary_count = 0 # 30秒内的更新次数
self.max_update_in_30s = 2
self.oberve_interval = 3
self.llm_summary = LLM_request(
model=global_config.llm_outer_world, temperature=0.7, max_tokens=300, request_type="outer_world")
async def start_observe(self):
while True:
if self.activate <= 0:
print(f"聊天 {self.chat_id} 活跃度不足,进入休眠状态")
await self.waiting_for_activate()
print(f"聊天 {self.chat_id} 被重新激活")
await self.observe_world()
await asyncio.sleep(self.oberve_interval)
async def waiting_for_activate(self):
while True:
# 检查从上次观察时间之后的新消息数量
new_messages_count = db.messages.count_documents({
"chat_id": self.chat_id,
"time": {"$gt": self.last_observe_time}
})
if new_messages_count > 15:
self.activate = 360*(self.observe_times+1)
return
await asyncio.sleep(8) # 每10秒检查一次
async def observe_world(self):
# 查找新消息限制最多20条
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:
self.activate += -1
return
# 将新消息添加到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()
self.summary_count += 1
async def update_talking_summary(self):
#基于已经有的talking_summary和新的talking_message生成一个summary
# print(f"更新聊天总结:{self.talking_summary}")
prompt = ""
prompt = f"你正在参与一个qq群聊的讨论这个群之前在聊的内容是{self.talking_summary}\n"
prompt += f"现在群里的群友们产生了新的讨论,有了新的发言,具体内容如下:{self.talking_message_str}\n"
prompt += '''以上是群里在进行的聊天,请你对这个聊天内容进行总结,总结内容要包含聊天的大致内容,
以及聊天中的一些重要信息,记得不要分点,不要太长,精简的概括成一段文本\n'''
prompt += "总结概括:"
self.talking_summary, 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"]
class SheduleInfo:
def __init__(self):
self.shedule_info = ""
class OuterWorld:
def __init__(self):
self.talking_info_list = [] #装的一堆talking_info
self.shedule_info = "无日程"
# self.interest_info = "麦麦你好"
self.outer_world_info = ""
self.start_time = int(datetime.now().timestamp())
self.llm_summary = LLM_request(
model=global_config.llm_outer_world, temperature=0.7, max_tokens=600, request_type="outer_world_info")
async def check_and_add_new_observe(self):
# 获取所有聊天流
all_streams = db.chat_streams.find({})
# 遍历所有聊天流
for data in all_streams:
stream_id = data.get("stream_id")
# 检查是否已存在该聊天流的观察对象
existing_info = next((info for info in self.talking_info_list if info.chat_id == stream_id), None)
# 如果不存在创建新的Talking_info对象并添加到列表中
if existing_info is None:
print(f"发现新的聊天流: {stream_id}")
new_talking_info = Talking_info(stream_id)
self.talking_info_list.append(new_talking_info)
# 启动新对象的观察任务
asyncio.create_task(new_talking_info.start_observe())
async def open_eyes(self):
while True:
print("检查新的聊天流")
await self.check_and_add_new_observe()
await asyncio.sleep(60)
def get_world_by_stream_id(self,stream_id):
for talking_info in self.talking_info_list:
if talking_info.chat_id == stream_id:
return talking_info
return None
outer_world = OuterWorld()
if __name__ == "__main__":
asyncio.run(outer_world.open_eyes())

View File

@@ -1,8 +1,8 @@
from .outer_world import outer_world
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, BotConfig
from src.plugins.config.config import global_config
import re
import time
from src.plugins.schedule.schedule_generator import bot_schedule
@@ -30,18 +30,17 @@ class CuttentState:
class SubHeartflow:
def __init__(self):
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.outer_world = None
self.main_heartflow_info = ""
self.observe_chat_id = None
self.last_reply_time = time.time()
if not self.current_mind:
@@ -50,10 +49,31 @@ class SubHeartflow:
self.personality_info = " ".join(global_config.PROMPT_PERSONALITY)
self.is_active = False
self.observations : list[Observation] = []
def assign_observe(self,stream_id):
self.outer_world = outer_world.get_world_by_stream_id(stream_id)
self.observe_chat_id = stream_id
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:
@@ -64,27 +84,34 @@ class SubHeartflow:
await asyncio.sleep(60) # 每30秒检查一次
else:
self.is_active = True
observation = self.observations[0]
observation.observe()
self.current_state.update_current_state_info()
await self.do_a_thinking()
await self.judge_willing()
await asyncio.sleep(60)
async def do_a_thinking(self):
self.current_state.update_current_state_info()
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
message_stream_info = self.outer_world.talking_summary
print(f"message_stream_info{message_stream_info}")
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=message_stream_info,
text=chat_observe_info,
max_memory_num=2,
max_memory_length=2,
max_depth=3,
fast_retrieval=False
)
# print(f"相关记忆:{related_memory}")
if related_memory:
related_memory_info = ""
for memory in related_memory:
@@ -104,8 +131,7 @@ class SubHeartflow:
prompt += f"你想起来你之前见过的回忆:{related_memory_info}\n以上是你的回忆,不一定是目前聊天里的人说的,也不一定是现在发生的事情,请记住。\n"
prompt += f"刚刚你的想法是{current_thinking_info}\n"
prompt += "-----------------------------------\n"
if message_stream_info:
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{message_stream_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
prompt += f"你现在{mood_info}\n"
prompt += "现在你接下去继续思考,产生新的想法,不要分点输出,输出连贯的内心独白,不要太长,"
prompt += "但是记得结合上述的消息,要记得维持住你的人设,关注聊天和新内容,不要思考太多:"
@@ -119,12 +145,13 @@ class SubHeartflow:
async def do_after_reply(self,reply_content,chat_talking_prompt):
# print("麦麦脑袋转起来了")
self.current_state.update_current_state_info()
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
# related_memory_info = 'memory'
message_stream_info = self.outer_world.talking_summary
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)
@@ -133,8 +160,7 @@ class SubHeartflow:
prompt = ""
prompt += f"你刚刚在做的事情是:{schedule_info}\n"
prompt += f"{self.personality_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{message_stream_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
# if related_memory_info:
# prompt += f"你想起来{related_memory_info}。"
prompt += f"刚刚你的想法是{current_thinking_info}"
@@ -174,14 +200,8 @@ class SubHeartflow:
else:
self.current_state.willing = 0
logger.info(f"{self.observe_chat_id}麦麦的回复意愿:{self.current_state.willing}")
return self.current_state.willing
def build_outer_world_info(self):
outer_world_info = outer_world.outer_world_info
return outer_world_info
def update_current_mind(self,reponse):
self.past_mind.append(self.current_mind)
self.current_mind = reponse