mirror of https://github.com/Mai-with-u/MaiBot.git
Update self_processor.py
parent
ebdf2de581
commit
53cb094c79
|
|
@ -7,63 +7,47 @@ import traceback
|
|||
from src.common.logger_manager import get_logger
|
||||
from src.individuality.individuality import individuality
|
||||
from src.chat.utils.prompt_builder import Prompt, global_prompt_manager
|
||||
from src.chat.utils.json_utils import safe_json_dumps
|
||||
from src.chat.message_receive.chat_stream import chat_manager
|
||||
from src.person_info.relationship_manager import relationship_manager
|
||||
from .base_processor import BaseProcessor
|
||||
from src.chat.focus_chat.info.mind_info import MindInfo
|
||||
from typing import List, Optional
|
||||
from src.chat.heart_flow.observation.hfcloop_observation import HFCloopObservation
|
||||
from typing import Dict
|
||||
from src.chat.focus_chat.info.info_base import InfoBase
|
||||
from src.chat.focus_chat.info.self_info import SelfInfo
|
||||
|
||||
logger = get_logger("processor")
|
||||
|
||||
|
||||
def init_prompt():
|
||||
group_prompt = """
|
||||
你的名字是{bot_name}
|
||||
{memory_str}
|
||||
{extra_info}
|
||||
indentify_prompt = """
|
||||
{name_block}
|
||||
你是一个AI,但是你伪装成了一个人类,你的人格是,{prompt_personality}
|
||||
{indentify_block}
|
||||
|
||||
{relation_prompt}
|
||||
{cycle_info_block}
|
||||
{memory_str}
|
||||
|
||||
现在是{time_now},你正在上网,和qq群里的网友们聊天,以下是正在进行的聊天内容:
|
||||
{chat_observe_info}
|
||||
|
||||
以下是你之前对聊天的观察和规划,你的名字是{bot_name}:
|
||||
{last_mind}
|
||||
现在请你根据现有的信息,思考自我认同:请严格遵守以下规则
|
||||
1. 请严格参考最上方的人设,适当参考记忆和当前聊天内容,不要被记忆和当前聊天内容中相反的内容误导
|
||||
2. 你是一个什么样的人,你和群里的人关系如何
|
||||
3. 你的形象是什么
|
||||
4. 思考有没有人提到你,或者图片与你有关
|
||||
5. 你的自我认同是否有助于你的回答,如果你需要自我相关的信息来帮你参与聊天,请输出,否则请输出十几个字的简短自我认同
|
||||
6. 一般情况下不用输出自我认同,只需要输出十几个字的简短自我认同就好,除非有明显需要自我认同的场景
|
||||
|
||||
现在请你继续输出观察和规划,输出要求:
|
||||
1. 先关注未读新消息的内容和近期回复历史
|
||||
2. 根据新信息,修改和删除之前的观察和规划
|
||||
3. 根据聊天内容继续输出观察和规划
|
||||
4. 注意群聊的时间线索,话题由谁发起,进展状况如何,思考聊天的时间线。
|
||||
6. 语言简洁自然,不要分点,不要浮夸,不要修辞,仅输出思考内容就好"""
|
||||
Prompt(group_prompt, "sub_heartflow_prompt_before")
|
||||
输出内容平淡一些,说中文,不要浮夸,平淡一些。
|
||||
请注意不要输出多余内容(包括前后缀,冒号和引号,括号(),表情包,at或 @等 )。只输出自我认同内容,记得明确说明这是你的自我认同。
|
||||
|
||||
private_prompt = """
|
||||
你的名字是{bot_name}
|
||||
{memory_str}
|
||||
{extra_info}
|
||||
{relation_prompt}
|
||||
{cycle_info_block}
|
||||
现在是{time_now},你正在上网,和qq群里的网友们聊天,以下是正在进行的聊天内容:
|
||||
{chat_observe_info}
|
||||
|
||||
以下是你之前对聊天的观察和规划,你的名字是{bot_name}:
|
||||
{last_mind}
|
||||
|
||||
现在请你继续输出观察和规划,输出要求:
|
||||
1. 先关注未读新消息的内容和近期回复历史
|
||||
2. 根据新信息,修改和删除之前的观察和规划
|
||||
3. 根据聊天内容继续输出观察和规划
|
||||
4. 注意群聊的时间线索,话题由谁发起,进展状况如何,思考聊天的时间线。
|
||||
6. 语言简洁自然,不要分点,不要浮夸,不要修辞,仅输出思考内容就好"""
|
||||
Prompt(private_prompt, "sub_heartflow_prompt_private_before")
|
||||
"""
|
||||
Prompt(indentify_prompt, "indentify_prompt")
|
||||
|
||||
|
||||
class MindProcessor(BaseProcessor):
|
||||
log_prefix = "聊天思考"
|
||||
class SelfProcessor(BaseProcessor):
|
||||
log_prefix = "自我认同"
|
||||
|
||||
def __init__(self, subheartflow_id: str):
|
||||
super().__init__()
|
||||
|
|
@ -71,48 +55,14 @@ class MindProcessor(BaseProcessor):
|
|||
self.subheartflow_id = subheartflow_id
|
||||
|
||||
self.llm_model = LLMRequest(
|
||||
model=global_config.model.focus_chat_mind,
|
||||
temperature=global_config.model.focus_chat_mind["temp"],
|
||||
model=global_config.model.focus_self_recognize,
|
||||
temperature=global_config.model.focus_self_recognize["temp"],
|
||||
max_tokens=800,
|
||||
request_type="focus_chat_mind",
|
||||
request_type="focus_self_identify",
|
||||
)
|
||||
|
||||
self.current_mind = ""
|
||||
self.past_mind = []
|
||||
self.structured_info = []
|
||||
self.structured_info_str = ""
|
||||
|
||||
name = chat_manager.get_stream_name(self.subheartflow_id)
|
||||
self.log_prefix = f"[{name}] "
|
||||
self._update_structured_info_str()
|
||||
|
||||
def _update_structured_info_str(self):
|
||||
"""根据 structured_info 更新 structured_info_str"""
|
||||
if not self.structured_info:
|
||||
self.structured_info_str = ""
|
||||
return
|
||||
|
||||
lines = ["【信息】"]
|
||||
for item in self.structured_info:
|
||||
# 简化展示,突出内容和类型,包含TTL供调试
|
||||
type_str = item.get("type", "未知类型")
|
||||
content_str = item.get("content", "")
|
||||
|
||||
if type_str == "info":
|
||||
lines.append(f"刚刚: {content_str}")
|
||||
elif type_str == "memory":
|
||||
lines.append(f"{content_str}")
|
||||
elif type_str == "comparison_result":
|
||||
lines.append(f"数字大小比较结果: {content_str}")
|
||||
elif type_str == "time_info":
|
||||
lines.append(f"{content_str}")
|
||||
elif type_str == "lpmm_knowledge":
|
||||
lines.append(f"你知道:{content_str}")
|
||||
else:
|
||||
lines.append(f"{type_str}的信息: {content_str}")
|
||||
|
||||
self.structured_info_str = "\n".join(lines)
|
||||
logger.debug(f"{self.log_prefix} 更新 structured_info_str: \n{self.structured_info_str}")
|
||||
|
||||
async def process_info(
|
||||
self, observations: Optional[List[Observation]] = None, running_memorys: Optional[List[Dict]] = None, *infos
|
||||
|
|
@ -125,14 +75,18 @@ class MindProcessor(BaseProcessor):
|
|||
Returns:
|
||||
List[InfoBase]: 处理后的结构化信息列表
|
||||
"""
|
||||
current_mind = await self.do_thinking_before_reply(observations, running_memorys)
|
||||
self_info_str = await self.self_indentify(observations, running_memorys)
|
||||
|
||||
mind_info = MindInfo()
|
||||
mind_info.set_current_mind(current_mind)
|
||||
if self_info_str:
|
||||
self_info = SelfInfo()
|
||||
self_info.set_self_info(self_info_str)
|
||||
else:
|
||||
self_info = None
|
||||
return None
|
||||
|
||||
return [mind_info]
|
||||
return [self_info]
|
||||
|
||||
async def do_thinking_before_reply(
|
||||
async def self_indentify(
|
||||
self, observations: Optional[List[Observation]] = None, running_memorys: Optional[List[Dict]] = None
|
||||
):
|
||||
"""
|
||||
|
|
@ -148,20 +102,12 @@ class MindProcessor(BaseProcessor):
|
|||
tuple: (current_mind, past_mind, prompt) 当前想法、过去的想法列表和使用的prompt
|
||||
"""
|
||||
|
||||
# ---------- 0. 更新和清理 structured_info ----------
|
||||
if self.structured_info:
|
||||
updated_info = []
|
||||
for item in self.structured_info:
|
||||
item["ttl"] -= 1
|
||||
if item["ttl"] > 0:
|
||||
updated_info.append(item)
|
||||
else:
|
||||
logger.debug(f"{self.log_prefix} 移除过期的 structured_info 项: {item['id']}")
|
||||
self.structured_info = updated_info
|
||||
self._update_structured_info_str()
|
||||
logger.debug(
|
||||
f"{self.log_prefix} 当前完整的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}"
|
||||
)
|
||||
for observation in observations:
|
||||
if isinstance(observation, ChattingObservation):
|
||||
is_group_chat = observation.is_group_chat
|
||||
chat_target_info = observation.chat_target_info
|
||||
chat_target_name = "对方" # 私聊默认名称
|
||||
person_list = observation.person_list
|
||||
|
||||
memory_str = ""
|
||||
if running_memorys:
|
||||
|
|
@ -169,9 +115,10 @@ class MindProcessor(BaseProcessor):
|
|||
for running_memory in running_memorys:
|
||||
memory_str += f"{running_memory['topic']}: {running_memory['content']}\n"
|
||||
|
||||
# ---------- 1. 准备基础数据 ----------
|
||||
# 获取现有想法和情绪状态
|
||||
previous_mind = self.current_mind if self.current_mind else ""
|
||||
relation_prompt = ""
|
||||
for person in person_list:
|
||||
if len(person) >= 3 and person[0] and person[1]:
|
||||
relation_prompt += await relationship_manager.build_relationship_info(person, is_id=True)
|
||||
|
||||
if observations is None:
|
||||
observations = []
|
||||
|
|
@ -190,52 +137,58 @@ class MindProcessor(BaseProcessor):
|
|||
chat_observe_info = observation.get_observe_info()
|
||||
person_list = observation.person_list
|
||||
if isinstance(observation, HFCloopObservation):
|
||||
hfcloop_observe_info = observation.get_observe_info()
|
||||
# hfcloop_observe_info = observation.get_observe_info()
|
||||
pass
|
||||
|
||||
# ---------- 3. 准备个性化数据 ----------
|
||||
# 获取个性化信息
|
||||
nickname_str = ""
|
||||
for nicknames in global_config.bot.alias_names:
|
||||
nickname_str += f"{nicknames},"
|
||||
name_block = f"你的名字是{global_config.bot.nickname},你的昵称有{nickname_str},有人也会用这些昵称称呼你。"
|
||||
|
||||
relation_prompt = ""
|
||||
personality_block = individuality.get_personality_prompt(x_person=2, level=2)
|
||||
identity_block = individuality.get_identity_prompt(x_person=2, level=2)
|
||||
|
||||
if is_group_chat:
|
||||
relation_prompt_init = "在这个群聊中,你:\n"
|
||||
else:
|
||||
relation_prompt_init = ""
|
||||
for person in person_list:
|
||||
relation_prompt += await relationship_manager.build_relationship_info(person, is_id=True)
|
||||
if relation_prompt:
|
||||
relation_prompt = relation_prompt_init + relation_prompt
|
||||
else:
|
||||
relation_prompt = relation_prompt_init + "没有特别在意的人\n"
|
||||
|
||||
template_name = "sub_heartflow_prompt_before" if is_group_chat else "sub_heartflow_prompt_private_before"
|
||||
logger.debug(f"{self.log_prefix} 使用{'群聊' if is_group_chat else '私聊'}思考模板")
|
||||
|
||||
prompt = (await global_prompt_manager.get_prompt_async(template_name)).format(
|
||||
bot_name=individuality.name,
|
||||
prompt = (await global_prompt_manager.get_prompt_async("indentify_prompt")).format(
|
||||
name_block=name_block,
|
||||
prompt_personality=personality_block,
|
||||
indentify_block=identity_block,
|
||||
memory_str=memory_str,
|
||||
extra_info=self.structured_info_str,
|
||||
relation_prompt=relation_prompt,
|
||||
time_now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
|
||||
chat_observe_info=chat_observe_info,
|
||||
last_mind=previous_mind,
|
||||
cycle_info_block=hfcloop_observe_info,
|
||||
chat_target_name=chat_target_name,
|
||||
)
|
||||
|
||||
content = "(不知道该想些什么...)"
|
||||
# print(prompt)
|
||||
|
||||
content = ""
|
||||
try:
|
||||
content, _ = await self.llm_model.generate_response_async(prompt=prompt)
|
||||
if not content:
|
||||
logger.warning(f"{self.log_prefix} LLM返回空结果,思考失败。")
|
||||
logger.warning(f"{self.log_prefix} LLM返回空结果,自我识别失败。")
|
||||
except Exception as e:
|
||||
# 处理总体异常
|
||||
logger.error(f"{self.log_prefix} 执行LLM请求或处理响应时出错: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
content = "思考过程中出现错误"
|
||||
content = "自我识别过程中出现错误"
|
||||
|
||||
if content == "None":
|
||||
content = ""
|
||||
# 记录初步思考结果
|
||||
logger.debug(f"{self.log_prefix} 思考prompt: \n{prompt}\n")
|
||||
logger.info(f"{self.log_prefix} 思考结果: {content}")
|
||||
self.update_current_mind(content)
|
||||
logger.debug(f"{self.log_prefix} 自我识别prompt: \n{prompt}\n")
|
||||
logger.info(f"{self.log_prefix} 自我识别结果: {content}")
|
||||
|
||||
return content
|
||||
|
||||
def update_current_mind(self, response):
|
||||
if self.current_mind: # 只有当 current_mind 非空时才添加到 past_mind
|
||||
self.past_mind.append(self.current_mind)
|
||||
self.current_mind = response
|
||||
|
||||
|
||||
init_prompt()
|
||||
|
|
|
|||
Loading…
Reference in New Issue