fix 修复了麦麦不会回复的bug

This commit is contained in:
SengokuCola
2025-03-18 12:55:16 +08:00
parent 10f8aa08ca
commit d7165175da
7 changed files with 123 additions and 15 deletions

View File

@@ -119,6 +119,75 @@ MEMORY_STYLE_CONFIG = {
} }
} }
# 海马体日志样式配置
SENDER_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{extra[module]: <12}</cyan> | "
"<light-yellow>消息发送</light-yellow> | "
"<level>{message}</level>"
),
"file_format": (
"{time:YYYY-MM-DD HH:mm:ss} | "
"{level: <8} | "
"{extra[module]: <15} | "
"消息发送 | "
"{message}"
)
},
"simple": {
"console_format": (
"<green>{time:MM-DD HH:mm}</green> | "
"<green>消息发送</green> | "
"{message}"
),
"file_format": (
"{time:YYYY-MM-DD HH:mm:ss} | "
"{level: <8} | "
"{extra[module]: <15} | "
"消息发送 | "
"{message}"
)
}
}
LLM_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{extra[module]: <12}</cyan> | "
"<light-yellow>麦麦组织语言</light-yellow> | "
"<level>{message}</level>"
),
"file_format": (
"{time:YYYY-MM-DD HH:mm:ss} | "
"{level: <8} | "
"{extra[module]: <15} | "
"麦麦组织语言 | "
"{message}"
)
},
"simple": {
"console_format": (
"<green>{time:MM-DD HH:mm}</green> | "
"<light-green>麦麦组织语言</light-green> | "
"{message}"
),
"file_format": (
"{time:YYYY-MM-DD HH:mm:ss} | "
"{level: <8} | "
"{extra[module]: <15} | "
"麦麦组织语言 | "
"{message}"
)
}
}
# Topic日志样式配置 # Topic日志样式配置
TOPIC_STYLE_CONFIG = { TOPIC_STYLE_CONFIG = {
"advanced": { "advanced": {
@@ -156,6 +225,8 @@ TOPIC_STYLE_CONFIG = {
# 根据ENABLE_ADVANCE_OUTPUT选择配置 # 根据ENABLE_ADVANCE_OUTPUT选择配置
MEMORY_STYLE_CONFIG = MEMORY_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else MEMORY_STYLE_CONFIG["simple"] MEMORY_STYLE_CONFIG = MEMORY_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else MEMORY_STYLE_CONFIG["simple"]
TOPIC_STYLE_CONFIG = TOPIC_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else TOPIC_STYLE_CONFIG["simple"] TOPIC_STYLE_CONFIG = TOPIC_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else TOPIC_STYLE_CONFIG["simple"]
SENDER_STYLE_CONFIG = SENDER_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else SENDER_STYLE_CONFIG["simple"]
LLM_STYLE_CONFIG = LLM_STYLE_CONFIG["advanced"] if ENABLE_ADVANCE_OUTPUT else LLM_STYLE_CONFIG["simple"]
def filter_nonebot(record: dict) -> bool: def filter_nonebot(record: dict) -> bool:
"""过滤nonebot的日志""" """过滤nonebot的日志"""

View File

@@ -137,20 +137,23 @@ class ChatBot:
) )
response = None response = None
# 开始组织语言
if random() < reply_probability: if random() < reply_probability:
bot_user_info = UserInfo( bot_user_info = UserInfo(
user_id=global_config.BOT_QQ, user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME, user_nickname=global_config.BOT_NICKNAME,
platform=messageinfo.platform, platform=messageinfo.platform,
) )
#开始思考的时间点
thinking_time_point = round(time.time(), 2) thinking_time_point = round(time.time(), 2)
logger.info(f"开始思考的时间点: {thinking_time_point}")
think_id = "mt" + str(thinking_time_point) think_id = "mt" + str(thinking_time_point)
thinking_message = MessageThinking( thinking_message = MessageThinking(
message_id=think_id, message_id=think_id,
chat_stream=chat, chat_stream=chat,
bot_user_info=bot_user_info, bot_user_info=bot_user_info,
reply=message, reply=message,
thinking_start_time=thinking_time_point,
) )
message_manager.add_message(thinking_message) message_manager.add_message(thinking_message)
@@ -188,16 +191,16 @@ class ChatBot:
thinking_start_time = thinking_message.thinking_start_time thinking_start_time = thinking_message.thinking_start_time
message_set = MessageSet(chat, think_id) message_set = MessageSet(chat, think_id)
# 计算打字时间1是为了模拟打字2是避免多条回复乱序 # 计算打字时间1是为了模拟打字2是避免多条回复乱序
accu_typing_time = 0 # accu_typing_time = 0
mark_head = False mark_head = False
for msg in response: for msg in response:
# print(f"\033[1;32m[回复内容]\033[0m {msg}") # print(f"\033[1;32m[回复内容]\033[0m {msg}")
# 通过时间改变时间戳 # 通过时间改变时间戳
typing_time = calculate_typing_time(msg) # typing_time = calculate_typing_time(msg)
logger.debug(f"typing_time: {typing_time}") # logger.debug(f"typing_time: {typing_time}")
accu_typing_time += typing_time # accu_typing_time += typing_time
timepoint = thinking_time_point + accu_typing_time # timepoint = thinking_time_point + accu_typing_time
message_segment = Seg(type="text", data=msg) message_segment = Seg(type="text", data=msg)
# logger.debug(f"message_segment: {message_segment}") # logger.debug(f"message_segment: {message_segment}")
bot_message = MessageSending( bot_message = MessageSending(
@@ -209,6 +212,7 @@ class ChatBot:
reply=message, reply=message,
is_head=not mark_head, is_head=not mark_head,
is_emoji=False, is_emoji=False,
thinking_start_time=thinking_start_time,
) )
if not mark_head: if not mark_head:
mark_head = True mark_head = True

View File

@@ -11,9 +11,16 @@ from .message import MessageRecv, MessageThinking, Message
from .prompt_builder import prompt_builder from .prompt_builder import prompt_builder
from .relationship_manager import relationship_manager from .relationship_manager import relationship_manager
from .utils import process_llm_response from .utils import process_llm_response
from src.common.logger import get_module_logger from src.common.logger import get_module_logger, LogConfig, LLM_STYLE_CONFIG
logger = get_module_logger("response_gen") # 定义日志配置
llm_config = LogConfig(
# 使用消息发送专用样式
console_format=LLM_STYLE_CONFIG["console_format"],
file_format=LLM_STYLE_CONFIG["file_format"]
)
logger = get_module_logger("llm_generator", config=llm_config)
driver = get_driver() driver = get_driver()
config = driver.config config = driver.config

View File

@@ -179,6 +179,7 @@ class MessageProcessBase(Message):
bot_user_info: UserInfo, bot_user_info: UserInfo,
message_segment: Optional[Seg] = None, message_segment: Optional[Seg] = None,
reply: Optional["MessageRecv"] = None, reply: Optional["MessageRecv"] = None,
thinking_start_time: float = 0,
): ):
# 调用父类初始化 # 调用父类初始化
super().__init__( super().__init__(
@@ -191,7 +192,7 @@ class MessageProcessBase(Message):
) )
# 处理状态相关属性 # 处理状态相关属性
self.thinking_start_time = int(time.time()) self.thinking_start_time = thinking_start_time
self.thinking_time = 0 self.thinking_time = 0
def update_thinking_time(self) -> float: def update_thinking_time(self) -> float:
@@ -274,6 +275,7 @@ class MessageThinking(MessageProcessBase):
chat_stream: ChatStream, chat_stream: ChatStream,
bot_user_info: UserInfo, bot_user_info: UserInfo,
reply: Optional["MessageRecv"] = None, reply: Optional["MessageRecv"] = None,
thinking_start_time: float = 0,
): ):
# 调用父类初始化 # 调用父类初始化
super().__init__( super().__init__(
@@ -282,6 +284,7 @@ class MessageThinking(MessageProcessBase):
bot_user_info=bot_user_info, bot_user_info=bot_user_info,
message_segment=None, # 思考状态不需要消息段 message_segment=None, # 思考状态不需要消息段
reply=reply, reply=reply,
thinking_start_time=thinking_start_time,
) )
# 思考状态特有属性 # 思考状态特有属性
@@ -302,6 +305,7 @@ class MessageSending(MessageProcessBase):
reply: Optional["MessageRecv"] = None, reply: Optional["MessageRecv"] = None,
is_head: bool = False, is_head: bool = False,
is_emoji: bool = False, is_emoji: bool = False,
thinking_start_time: float = 0,
): ):
# 调用父类初始化 # 调用父类初始化
super().__init__( super().__init__(
@@ -310,6 +314,7 @@ class MessageSending(MessageProcessBase):
bot_user_info=bot_user_info, bot_user_info=bot_user_info,
message_segment=message_segment, message_segment=message_segment,
reply=reply, reply=reply,
thinking_start_time=thinking_start_time,
) )
# 发送状态特有属性 # 发送状态特有属性

View File

@@ -12,7 +12,17 @@ from .storage import MessageStorage
from .config import global_config from .config import global_config
from .utils import truncate_message from .utils import truncate_message
logger = get_module_logger("msg_sender") from src.common.logger import get_module_logger, LogConfig, SENDER_STYLE_CONFIG
# 定义日志配置
sender_config = LogConfig(
# 使用消息发送专用样式
console_format=SENDER_STYLE_CONFIG["console_format"],
file_format=SENDER_STYLE_CONFIG["file_format"]
)
logger = get_module_logger("msg_sender", config=sender_config)
class Message_Sender: class Message_Sender:
"""发送器""" """发送器"""
@@ -174,6 +184,7 @@ class MessageManager:
if isinstance(message_earliest, MessageThinking): if isinstance(message_earliest, MessageThinking):
message_earliest.update_thinking_time() message_earliest.update_thinking_time()
thinking_time = message_earliest.thinking_time thinking_time = message_earliest.thinking_time
# print(thinking_time)
print( print(
f"消息正在思考中,已思考{int(thinking_time)}\r", f"消息正在思考中,已思考{int(thinking_time)}\r",
end="", end="",
@@ -186,11 +197,17 @@ class MessageManager:
container.remove_message(message_earliest) container.remove_message(message_earliest)
else: else:
# print(message_earliest.is_head)
# print(message_earliest.update_thinking_time())
# print(message_earliest.is_private_message())
# thinking_time = message_earliest.update_thinking_time()
# print(thinking_time)
if ( if (
message_earliest.is_head message_earliest.is_head
and message_earliest.update_thinking_time() > 10 and message_earliest.update_thinking_time() > 15
and not message_earliest.is_private_message() # 避免在私聊时插入reply and not message_earliest.is_private_message() # 避免在私聊时插入reply
): ):
logger.debug(f"设置回复消息{message_earliest.processed_plain_text}")
message_earliest.set_reply() message_earliest.set_reply()
await message_earliest.process() await message_earliest.process()
@@ -212,11 +229,15 @@ class MessageManager:
continue continue
try: try:
# print(msg.is_head)
# print(msg.update_thinking_time())
# print(msg.is_private_message())
if ( if (
msg.is_head msg.is_head
and msg.update_thinking_time() > 10 and msg.update_thinking_time() > 15
and not msg.is_private_message() # 避免在私聊时插入reply and not msg.is_private_message() # 避免在私聊时插入reply
): ):
logger.debug(f"设置回复消息{msg.processed_plain_text}")
msg.set_reply() msg.set_reply()
await msg.process() await msg.process()

View File

@@ -336,7 +336,7 @@ def random_remove_punctuation(text: str) -> str:
def process_llm_response(text: str) -> List[str]: def process_llm_response(text: str) -> List[str]:
# processed_response = process_text_with_typos(content) # processed_response = process_text_with_typos(content)
if len(text) > 200: if len(text) > 100:
logger.warning(f"回复过长 ({len(text)} 字符),返回默认回复") logger.warning(f"回复过长 ({len(text)} 字符),返回默认回复")
return ['懒得说'] return ['懒得说']
# 处理长消息 # 处理长消息
@@ -358,7 +358,7 @@ def process_llm_response(text: str) -> List[str]:
sentences.append(sentence) sentences.append(sentence)
# 检查分割后的消息数量是否过多超过3条 # 检查分割后的消息数量是否过多超过3条
if len(sentences) > 5: if len(sentences) > 3:
logger.warning(f"分割后消息数量过多 ({len(sentences)} 条),返回默认回复") logger.warning(f"分割后消息数量过多 ({len(sentences)} 条),返回默认回复")
return [f'{global_config.BOT_NICKNAME}不知道哦'] return [f'{global_config.BOT_NICKNAME}不知道哦']

View File

@@ -21,7 +21,7 @@ def get_unique_id():
with open(UUID_FILE, "r") as f: with open(UUID_FILE, "r") as f:
data = json.load(f) data = json.load(f)
if "client_id" in data: if "client_id" in data:
print("从本地文件读取客户端ID") # print("从本地文件读取客户端ID")
return data["client_id"] return data["client_id"]
except (json.JSONDecodeError, IOError) as e: except (json.JSONDecodeError, IOError) as e:
print(f"读取UUID文件出错: {e}将生成新的UUID") print(f"读取UUID文件出错: {e}将生成新的UUID")