QA: Update requirements and refactor message handling logic etc.
This commit is contained in:
@@ -144,6 +144,25 @@ class SenderError(HeartFCError):
|
||||
pass
|
||||
|
||||
|
||||
async def _handle_cycle_delay(action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str):
|
||||
"""处理循环延迟"""
|
||||
cycle_duration = time.monotonic() - cycle_start_time
|
||||
|
||||
try:
|
||||
sleep_duration = 0.0
|
||||
if not action_taken_this_cycle and cycle_duration < 1:
|
||||
sleep_duration = 1 - cycle_duration
|
||||
elif cycle_duration < 0.2:
|
||||
sleep_duration = 0.2
|
||||
|
||||
if sleep_duration > 0:
|
||||
await asyncio.sleep(sleep_duration)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{log_prefix} Sleep interrupted, loop likely cancelling.")
|
||||
raise
|
||||
|
||||
|
||||
class HeartFChatting:
|
||||
"""
|
||||
管理一个连续的Plan-Replier-Sender循环
|
||||
@@ -327,7 +346,7 @@ class HeartFChatting:
|
||||
self._current_cycle.timers = cycle_timers
|
||||
|
||||
# 防止循环过快消耗资源
|
||||
await self._handle_cycle_delay(action_taken, loop_cycle_start_time, self.log_prefix)
|
||||
await _handle_cycle_delay(action_taken, loop_cycle_start_time, self.log_prefix)
|
||||
|
||||
# 完成当前循环并保存历史
|
||||
self._current_cycle.complete_cycle()
|
||||
@@ -715,24 +734,6 @@ class HeartFChatting:
|
||||
if not self._shutting_down:
|
||||
logger.debug(f"{log_prefix} 该次决策耗时: {'; '.join(timer_strings)}")
|
||||
|
||||
async def _handle_cycle_delay(self, action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str):
|
||||
"""处理循环延迟"""
|
||||
cycle_duration = time.monotonic() - cycle_start_time
|
||||
|
||||
try:
|
||||
sleep_duration = 0.0
|
||||
if not action_taken_this_cycle and cycle_duration < 1:
|
||||
sleep_duration = 1 - cycle_duration
|
||||
elif cycle_duration < 0.2:
|
||||
sleep_duration = 0.2
|
||||
|
||||
if sleep_duration > 0:
|
||||
await asyncio.sleep(sleep_duration)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{log_prefix} Sleep interrupted, loop likely cancelling.")
|
||||
raise
|
||||
|
||||
async def _get_submind_thinking(self, cycle_timers: dict) -> str:
|
||||
"""
|
||||
获取子思维的思考结果
|
||||
|
||||
@@ -12,6 +12,22 @@ from src.plugins.chat.utils import calculate_typing_time
|
||||
logger = get_logger("sender")
|
||||
|
||||
|
||||
async def send_message(message: MessageSending) -> None:
|
||||
"""合并后的消息发送函数,包含WS发送和日志记录"""
|
||||
message_preview = truncate_message(message.processed_plain_text)
|
||||
|
||||
try:
|
||||
# 直接调用API发送消息
|
||||
await send_message(message)
|
||||
logger.success(f"发送消息 '{message_preview}' 成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息 '{message_preview}' 失败: {str(e)}")
|
||||
if not message.message_info.platform:
|
||||
raise ValueError(f"未找到平台:{message.message_info.platform} 的url配置,请检查配置文件") from e
|
||||
raise e # 重新抛出其他异常
|
||||
|
||||
|
||||
class HeartFCSender:
|
||||
"""管理消息的注册、即时处理、发送和存储,并跟踪思考状态。"""
|
||||
|
||||
@@ -21,21 +37,6 @@ class HeartFCSender:
|
||||
self.thinking_messages: Dict[str, Dict[str, MessageThinking]] = {}
|
||||
self._thinking_lock = asyncio.Lock() # 保护 thinking_messages 的锁
|
||||
|
||||
async def send_message(self, message: MessageSending) -> None:
|
||||
"""合并后的消息发送函数,包含WS发送和日志记录"""
|
||||
message_preview = truncate_message(message.processed_plain_text)
|
||||
|
||||
try:
|
||||
# 直接调用API发送消息
|
||||
await global_api.send_message(message)
|
||||
logger.success(f"发送消息 '{message_preview}' 成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息 '{message_preview}' 失败: {str(e)}")
|
||||
if not message.message_info.platform:
|
||||
raise ValueError(f"未找到平台:{message.message_info.platform} 的url配置,请检查配置文件") from e
|
||||
raise e # 重新抛出其他异常
|
||||
|
||||
async def register_thinking(self, thinking_message: MessageThinking):
|
||||
"""注册一个思考中的消息。"""
|
||||
if not thinking_message.chat_stream or not thinking_message.message_info.message_id:
|
||||
@@ -73,7 +74,7 @@ class HeartFCSender:
|
||||
thinking_message = self.thinking_messages.get(chat_id, {}).get(message_id)
|
||||
return thinking_message.thinking_start_time if thinking_message else None
|
||||
|
||||
async def type_and_send_message(self, message: MessageSending, type=False):
|
||||
async def type_and_send_message(self, message: MessageSending, typing=False):
|
||||
"""
|
||||
立即处理、发送并存储单个 MessageSending 消息。
|
||||
调用此方法前,应先调用 register_thinking 注册对应的思考消息。
|
||||
@@ -100,7 +101,7 @@ class HeartFCSender:
|
||||
|
||||
await message.process()
|
||||
|
||||
if type:
|
||||
if typing:
|
||||
typing_time = calculate_typing_time(
|
||||
input_string=message.processed_plain_text,
|
||||
thinking_start_time=message.thinking_start_time,
|
||||
@@ -108,7 +109,7 @@ class HeartFCSender:
|
||||
)
|
||||
await asyncio.sleep(typing_time)
|
||||
|
||||
await self.send_message(message)
|
||||
await send_message(message)
|
||||
await self.storage.store_message(message, message.chat_stream)
|
||||
|
||||
except Exception as e:
|
||||
@@ -136,7 +137,7 @@ class HeartFCSender:
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
await self.send_message(message) # 使用现有的发送方法
|
||||
await send_message(message) # 使用现有的发送方法
|
||||
await self.storage.store_message(message, message.chat_stream) # 使用现有的存储方法
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -12,11 +12,134 @@ from ..chat.chat_stream import chat_manager
|
||||
from ..chat.message_buffer import message_buffer
|
||||
from ..utils.timer_calculator import Timer
|
||||
from src.plugins.person_info.relationship_manager import relationship_manager
|
||||
from typing import Optional, Tuple
|
||||
from typing import Optional, Tuple, Dict, Any
|
||||
|
||||
logger = get_logger("chat")
|
||||
|
||||
|
||||
async def _handle_error(error: Exception, context: str, message: Optional[MessageRecv] = None) -> None:
|
||||
"""统一的错误处理函数
|
||||
|
||||
Args:
|
||||
error: 捕获到的异常
|
||||
context: 错误发生的上下文描述
|
||||
message: 可选的消息对象,用于记录相关消息内容
|
||||
"""
|
||||
logger.error(f"{context}: {error}")
|
||||
logger.error(traceback.format_exc())
|
||||
if message and hasattr(message, "raw_message"):
|
||||
logger.error(f"相关消息原始内容: {message.raw_message}")
|
||||
|
||||
|
||||
async def _process_relationship(message: MessageRecv) -> None:
|
||||
"""处理用户关系逻辑
|
||||
|
||||
Args:
|
||||
message: 消息对象,包含用户信息
|
||||
"""
|
||||
platform = message.message_info.platform
|
||||
user_id = message.message_info.user_info.user_id
|
||||
nickname = message.message_info.user_info.user_nickname
|
||||
cardname = message.message_info.user_info.user_cardname or nickname
|
||||
|
||||
is_known = await relationship_manager.is_known_some_one(platform, user_id)
|
||||
|
||||
if not is_known:
|
||||
logger.info(f"首次认识用户: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
elif not await relationship_manager.is_qved_name(platform, user_id):
|
||||
logger.info(f"给用户({nickname},{cardname})取名: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
|
||||
|
||||
async def _calculate_interest(message: MessageRecv) -> Tuple[float, bool]:
|
||||
"""计算消息的兴趣度
|
||||
|
||||
Args:
|
||||
message: 待处理的消息对象
|
||||
|
||||
Returns:
|
||||
Tuple[float, bool]: (兴趣度, 是否被提及)
|
||||
"""
|
||||
is_mentioned, _ = is_mentioned_bot_in_message(message)
|
||||
interested_rate = 0.0
|
||||
|
||||
with Timer("记忆激活"):
|
||||
interested_rate = await HippocampusManager.get_instance().get_activate_from_text(
|
||||
message.processed_plain_text,
|
||||
fast_retrieval=True,
|
||||
)
|
||||
logger.trace(f"记忆激活率: {interested_rate:.2f}")
|
||||
|
||||
if is_mentioned:
|
||||
interest_increase_on_mention = 1
|
||||
interested_rate += interest_increase_on_mention
|
||||
|
||||
return interested_rate, is_mentioned
|
||||
|
||||
|
||||
def _get_message_type(message: MessageRecv) -> str:
|
||||
"""获取消息类型
|
||||
|
||||
Args:
|
||||
message: 消息对象
|
||||
|
||||
Returns:
|
||||
str: 消息类型
|
||||
"""
|
||||
if message.message_segment.type != "seglist":
|
||||
return message.message_segment.type
|
||||
|
||||
if (
|
||||
isinstance(message.message_segment.data, list)
|
||||
and all(isinstance(x, Seg) for x in message.message_segment.data)
|
||||
and len(message.message_segment.data) == 1
|
||||
):
|
||||
return message.message_segment.data[0].type
|
||||
|
||||
return "seglist"
|
||||
|
||||
|
||||
def _check_ban_words(text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否包含过滤词
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
Returns:
|
||||
bool: 是否包含过滤词
|
||||
"""
|
||||
for word in global_config.ban_words:
|
||||
if word in text:
|
||||
chat_name = chat.group_info.group_name if chat.group_info else "私聊"
|
||||
logger.info(f"[{chat_name}]{userinfo.user_nickname}:{text}")
|
||||
logger.info(f"[过滤词识别]消息中含有{word},filtered")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _check_ban_regex(text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否匹配过滤正则表达式
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
Returns:
|
||||
bool: 是否匹配过滤正则
|
||||
"""
|
||||
for pattern in global_config.ban_msgs_regex:
|
||||
if pattern.search(text):
|
||||
chat_name = chat.group_info.group_name if chat.group_info else "私聊"
|
||||
logger.info(f"[{chat_name}]{userinfo.user_nickname}:{text}")
|
||||
logger.info(f"[正则表达式过滤]消息匹配到{pattern},filtered")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class HeartFCProcessor:
|
||||
"""心流处理器,负责处理接收到的消息并计算兴趣度"""
|
||||
|
||||
@@ -24,86 +147,7 @@ class HeartFCProcessor:
|
||||
"""初始化心流处理器,创建消息存储实例"""
|
||||
self.storage = MessageStorage()
|
||||
|
||||
async def _handle_error(self, error: Exception, context: str, message: Optional[MessageRecv] = None) -> None:
|
||||
"""统一的错误处理函数
|
||||
|
||||
Args:
|
||||
error: 捕获到的异常
|
||||
context: 错误发生的上下文描述
|
||||
message: 可选的消息对象,用于记录相关消息内容
|
||||
"""
|
||||
logger.error(f"{context}: {error}")
|
||||
logger.error(traceback.format_exc())
|
||||
if message and hasattr(message, "raw_message"):
|
||||
logger.error(f"相关消息原始内容: {message.raw_message}")
|
||||
|
||||
async def _process_relationship(self, message: MessageRecv) -> None:
|
||||
"""处理用户关系逻辑
|
||||
|
||||
Args:
|
||||
message: 消息对象,包含用户信息
|
||||
"""
|
||||
platform = message.message_info.platform
|
||||
user_id = message.message_info.user_info.user_id
|
||||
nickname = message.message_info.user_info.user_nickname
|
||||
cardname = message.message_info.user_info.user_cardname or nickname
|
||||
|
||||
is_known = await relationship_manager.is_known_some_one(platform, user_id)
|
||||
|
||||
if not is_known:
|
||||
logger.info(f"首次认识用户: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
elif not await relationship_manager.is_qved_name(platform, user_id):
|
||||
logger.info(f"给用户({nickname},{cardname})取名: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
|
||||
async def _calculate_interest(self, message: MessageRecv) -> Tuple[float, bool]:
|
||||
"""计算消息的兴趣度
|
||||
|
||||
Args:
|
||||
message: 待处理的消息对象
|
||||
|
||||
Returns:
|
||||
Tuple[float, bool]: (兴趣度, 是否被提及)
|
||||
"""
|
||||
is_mentioned, _ = is_mentioned_bot_in_message(message)
|
||||
interested_rate = 0.0
|
||||
|
||||
with Timer("记忆激活"):
|
||||
interested_rate = await HippocampusManager.get_instance().get_activate_from_text(
|
||||
message.processed_plain_text,
|
||||
fast_retrieval=True,
|
||||
)
|
||||
logger.trace(f"记忆激活率: {interested_rate:.2f}")
|
||||
|
||||
if is_mentioned:
|
||||
interest_increase_on_mention = 1
|
||||
interested_rate += interest_increase_on_mention
|
||||
|
||||
return interested_rate, is_mentioned
|
||||
|
||||
def _get_message_type(self, message: MessageRecv) -> str:
|
||||
"""获取消息类型
|
||||
|
||||
Args:
|
||||
message: 消息对象
|
||||
|
||||
Returns:
|
||||
str: 消息类型
|
||||
"""
|
||||
if message.message_segment.type != "seglist":
|
||||
return message.message_segment.type
|
||||
|
||||
if (
|
||||
isinstance(message.message_segment.data, list)
|
||||
and all(isinstance(x, Seg) for x in message.message_segment.data)
|
||||
and len(message.message_segment.data) == 1
|
||||
):
|
||||
return message.message_segment.data[0].type
|
||||
|
||||
return "seglist"
|
||||
|
||||
async def process_message(self, message_data: str) -> None:
|
||||
async def process_message(self, message_data: Dict[str, Any]) -> None:
|
||||
"""处理接收到的原始消息数据
|
||||
|
||||
主要流程:
|
||||
@@ -138,7 +182,7 @@ class HeartFCProcessor:
|
||||
await message.process()
|
||||
|
||||
# 3. 过滤检查
|
||||
if self._check_ban_words(message.processed_plain_text, chat, userinfo) or self._check_ban_regex(
|
||||
if _check_ban_words(message.processed_plain_text, chat, userinfo) or _check_ban_regex(
|
||||
message.raw_message, chat, userinfo
|
||||
):
|
||||
return
|
||||
@@ -146,7 +190,7 @@ class HeartFCProcessor:
|
||||
# 4. 缓冲检查
|
||||
buffer_result = await message_buffer.query_buffer_result(message)
|
||||
if not buffer_result:
|
||||
msg_type = self._get_message_type(message)
|
||||
msg_type = _get_message_type(message)
|
||||
type_messages = {
|
||||
"text": f"触发缓冲,消息:{message.processed_plain_text}",
|
||||
"image": "触发缓冲,表情包/图片等待中",
|
||||
@@ -160,7 +204,7 @@ class HeartFCProcessor:
|
||||
logger.trace(f"存储成功: {message.processed_plain_text}")
|
||||
|
||||
# 6. 兴趣度计算与更新
|
||||
interested_rate, is_mentioned = await self._calculate_interest(message)
|
||||
interested_rate, is_mentioned = await _calculate_interest(message)
|
||||
await subheartflow.interest_chatting.increase_interest(value=interested_rate)
|
||||
subheartflow.interest_chatting.add_interest_dict(message, interested_rate, is_mentioned)
|
||||
|
||||
@@ -175,45 +219,7 @@ class HeartFCProcessor:
|
||||
)
|
||||
|
||||
# 8. 关系处理
|
||||
await self._process_relationship(message)
|
||||
await _process_relationship(message)
|
||||
|
||||
except Exception as e:
|
||||
await self._handle_error(e, "消息处理失败", message)
|
||||
|
||||
def _check_ban_words(self, text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否包含过滤词
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
Returns:
|
||||
bool: 是否包含过滤词
|
||||
"""
|
||||
for word in global_config.ban_words:
|
||||
if word in text:
|
||||
chat_name = chat.group_info.group_name if chat.group_info else "私聊"
|
||||
logger.info(f"[{chat_name}]{userinfo.user_nickname}:{text}")
|
||||
logger.info(f"[过滤词识别]消息中含有{word},filtered")
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_ban_regex(self, text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否匹配过滤正则表达式
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
Returns:
|
||||
bool: 是否匹配过滤正则
|
||||
"""
|
||||
for pattern in global_config.ban_msgs_regex:
|
||||
if pattern.search(text):
|
||||
chat_name = chat.group_info.group_name if chat.group_info else "私聊"
|
||||
logger.info(f"[{chat_name}]{userinfo.user_nickname}:{text}")
|
||||
logger.info(f"[正则表达式过滤]消息匹配到{pattern},filtered")
|
||||
return True
|
||||
return False
|
||||
await _handle_error(e, "消息处理失败", message)
|
||||
|
||||
@@ -151,6 +151,96 @@ JSON 结构如下,包含三个字段 "action", "reasoning", "emoji_query":
|
||||
Prompt("\n你有以下这些**知识**:\n{prompt_info}\n请你**记住上面的知识**,之后可能会用到。\n", "knowledge_prompt")
|
||||
|
||||
|
||||
async def _build_prompt_focus(
|
||||
reason, current_mind_info, structured_info, chat_stream, sender_name
|
||||
) -> tuple[str, str]:
|
||||
individuality = Individuality.get_instance()
|
||||
prompt_personality = individuality.get_prompt(x_person=0, level=2)
|
||||
# 日程构建
|
||||
# schedule_prompt = f'''你现在正在做的事情是:{bot_schedule.get_current_num_task(num = 1,time_info = False)}'''
|
||||
|
||||
if chat_stream.group_info:
|
||||
chat_in_group = True
|
||||
else:
|
||||
chat_in_group = False
|
||||
|
||||
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
|
||||
chat_id=chat_stream.stream_id,
|
||||
timestamp=time.time(),
|
||||
limit=global_config.observation_context_size,
|
||||
)
|
||||
|
||||
chat_talking_prompt = await build_readable_messages(
|
||||
message_list_before_now,
|
||||
replace_bot_name=True,
|
||||
merge_messages=False,
|
||||
timestamp_mode="normal",
|
||||
read_mark=0.0,
|
||||
truncate=True,
|
||||
)
|
||||
|
||||
# 中文高手(新加的好玩功能)
|
||||
prompt_ger = ""
|
||||
if random.random() < 0.04:
|
||||
prompt_ger += "你喜欢用倒装句"
|
||||
if random.random() < 0.02:
|
||||
prompt_ger += "你喜欢用反问句"
|
||||
|
||||
reply_styles1 = [
|
||||
("给出日常且口语化的回复,平淡一些", 0.4), # 40%概率
|
||||
("给出非常简短的回复", 0.4), # 40%概率
|
||||
("给出缺失主语的回复,简短", 0.15), # 15%概率
|
||||
("给出带有语病的回复,朴实平淡", 0.05), # 5%概率
|
||||
]
|
||||
reply_style1_chosen = random.choices(
|
||||
[style[0] for style in reply_styles1], weights=[style[1] for style in reply_styles1], k=1
|
||||
)[0]
|
||||
|
||||
reply_styles2 = [
|
||||
("不要回复的太有条理,可以有个性", 0.6), # 60%概率
|
||||
("不要回复的太有条理,可以复读", 0.15), # 15%概率
|
||||
("回复的认真一些", 0.2), # 20%概率
|
||||
("可以回复单个表情符号", 0.05), # 5%概率
|
||||
]
|
||||
reply_style2_chosen = random.choices(
|
||||
[style[0] for style in reply_styles2], weights=[style[1] for style in reply_styles2], k=1
|
||||
)[0]
|
||||
|
||||
if structured_info:
|
||||
structured_info_prompt = await global_prompt_manager.format_prompt(
|
||||
"info_from_tools", structured_info=structured_info
|
||||
)
|
||||
else:
|
||||
structured_info_prompt = ""
|
||||
|
||||
logger.debug("开始构建prompt")
|
||||
|
||||
prompt = await global_prompt_manager.format_prompt(
|
||||
"heart_flow_prompt",
|
||||
info_from_tools=structured_info_prompt,
|
||||
chat_target=await global_prompt_manager.get_prompt_async("chat_target_group1")
|
||||
if chat_in_group
|
||||
else await global_prompt_manager.get_prompt_async("chat_target_private1"),
|
||||
chat_talking_prompt=chat_talking_prompt,
|
||||
bot_name=global_config.BOT_NICKNAME,
|
||||
prompt_personality=prompt_personality,
|
||||
chat_target_2=await global_prompt_manager.get_prompt_async("chat_target_group2")
|
||||
if chat_in_group
|
||||
else await global_prompt_manager.get_prompt_async("chat_target_private2"),
|
||||
current_mind_info=current_mind_info,
|
||||
reply_style2=reply_style2_chosen,
|
||||
reply_style1=reply_style1_chosen,
|
||||
reason=reason,
|
||||
prompt_ger=prompt_ger,
|
||||
moderation_prompt=await global_prompt_manager.get_prompt_async("moderation_prompt"),
|
||||
sender_name=sender_name,
|
||||
)
|
||||
|
||||
logger.debug(f"focus_chat_prompt: \n{prompt}")
|
||||
|
||||
return prompt
|
||||
|
||||
|
||||
class PromptBuilder:
|
||||
def __init__(self):
|
||||
self.prompt_built = ""
|
||||
@@ -170,7 +260,7 @@ class PromptBuilder:
|
||||
return await self._build_prompt_normal(chat_stream, message_txt, sender_name)
|
||||
|
||||
elif build_mode == "focus":
|
||||
return await self._build_prompt_focus(
|
||||
return await _build_prompt_focus(
|
||||
reason,
|
||||
current_mind_info,
|
||||
structured_info,
|
||||
@@ -179,95 +269,6 @@ class PromptBuilder:
|
||||
)
|
||||
return None
|
||||
|
||||
async def _build_prompt_focus(
|
||||
self, reason, current_mind_info, structured_info, chat_stream, sender_name
|
||||
) -> tuple[str, str]:
|
||||
individuality = Individuality.get_instance()
|
||||
prompt_personality = individuality.get_prompt(x_person=0, level=2)
|
||||
# 日程构建
|
||||
# schedule_prompt = f'''你现在正在做的事情是:{bot_schedule.get_current_num_task(num = 1,time_info = False)}'''
|
||||
|
||||
if chat_stream.group_info:
|
||||
chat_in_group = True
|
||||
else:
|
||||
chat_in_group = False
|
||||
|
||||
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
|
||||
chat_id=chat_stream.stream_id,
|
||||
timestamp=time.time(),
|
||||
limit=global_config.observation_context_size,
|
||||
)
|
||||
|
||||
chat_talking_prompt = await build_readable_messages(
|
||||
message_list_before_now,
|
||||
replace_bot_name=True,
|
||||
merge_messages=False,
|
||||
timestamp_mode="normal",
|
||||
read_mark=0.0,
|
||||
truncate=True,
|
||||
)
|
||||
|
||||
# 中文高手(新加的好玩功能)
|
||||
prompt_ger = ""
|
||||
if random.random() < 0.04:
|
||||
prompt_ger += "你喜欢用倒装句"
|
||||
if random.random() < 0.02:
|
||||
prompt_ger += "你喜欢用反问句"
|
||||
|
||||
reply_styles1 = [
|
||||
("给出日常且口语化的回复,平淡一些", 0.4), # 40%概率
|
||||
("给出非常简短的回复", 0.4), # 40%概率
|
||||
("给出缺失主语的回复,简短", 0.15), # 15%概率
|
||||
("给出带有语病的回复,朴实平淡", 0.05), # 5%概率
|
||||
]
|
||||
reply_style1_chosen = random.choices(
|
||||
[style[0] for style in reply_styles1], weights=[style[1] for style in reply_styles1], k=1
|
||||
)[0]
|
||||
|
||||
reply_styles2 = [
|
||||
("不要回复的太有条理,可以有个性", 0.6), # 60%概率
|
||||
("不要回复的太有条理,可以复读", 0.15), # 15%概率
|
||||
("回复的认真一些", 0.2), # 20%概率
|
||||
("可以回复单个表情符号", 0.05), # 5%概率
|
||||
]
|
||||
reply_style2_chosen = random.choices(
|
||||
[style[0] for style in reply_styles2], weights=[style[1] for style in reply_styles2], k=1
|
||||
)[0]
|
||||
|
||||
if structured_info:
|
||||
structured_info_prompt = await global_prompt_manager.format_prompt(
|
||||
"info_from_tools", structured_info=structured_info
|
||||
)
|
||||
else:
|
||||
structured_info_prompt = ""
|
||||
|
||||
logger.debug("开始构建prompt")
|
||||
|
||||
prompt = await global_prompt_manager.format_prompt(
|
||||
"heart_flow_prompt",
|
||||
info_from_tools=structured_info_prompt,
|
||||
chat_target=await global_prompt_manager.get_prompt_async("chat_target_group1")
|
||||
if chat_in_group
|
||||
else await global_prompt_manager.get_prompt_async("chat_target_private1"),
|
||||
chat_talking_prompt=chat_talking_prompt,
|
||||
bot_name=global_config.BOT_NICKNAME,
|
||||
prompt_personality=prompt_personality,
|
||||
chat_target_2=await global_prompt_manager.get_prompt_async("chat_target_group2")
|
||||
if chat_in_group
|
||||
else await global_prompt_manager.get_prompt_async("chat_target_private2"),
|
||||
current_mind_info=current_mind_info,
|
||||
reply_style2=reply_style2_chosen,
|
||||
reply_style1=reply_style1_chosen,
|
||||
reason=reason,
|
||||
prompt_ger=prompt_ger,
|
||||
moderation_prompt=await global_prompt_manager.get_prompt_async("moderation_prompt"),
|
||||
sender_name=sender_name,
|
||||
)
|
||||
|
||||
logger.debug(f"focus_chat_prompt: \n{prompt}")
|
||||
|
||||
return prompt
|
||||
|
||||
async def _build_prompt_normal(self, chat_stream, message_txt: str, sender_name: str = "某人") -> tuple[str, str]:
|
||||
individuality = Individuality.get_instance()
|
||||
prompt_personality = individuality.get_prompt(x_person=2, level=2)
|
||||
|
||||
Reference in New Issue
Block a user