🤖 自动格式化代码 [skip ci]

This commit is contained in:
github-actions[bot]
2025-04-17 01:40:04 +00:00
parent e5e5b5ca09
commit ab35f1cdfd
8 changed files with 89 additions and 71 deletions

View File

@@ -138,9 +138,11 @@ class MessageBuffer:
if msg.message.message_segment.type != "seglist": if msg.message.message_segment.type != "seglist":
type = msg.message.message_segment.type type = msg.message.message_segment.type
else: else:
if (isinstance(msg.message.message_segment.data, list) if (
and all(isinstance(x, Seg) for x in msg.message.message_segment.data) isinstance(msg.message.message_segment.data, list)
and len(msg.message.message_segment.data) == 1): and all(isinstance(x, Seg) for x in msg.message.message_segment.data)
and len(msg.message.message_segment.data) == 1
):
type = msg.message.message_segment.data[0].type type = msg.message.message_segment.data[0].type
combined_text.append(msg.message.processed_plain_text) combined_text.append(msg.message.processed_plain_text)
continue continue
@@ -152,9 +154,11 @@ class MessageBuffer:
if msg.message.message_segment.type != "seglist": if msg.message.message_segment.type != "seglist":
F_type = msg.message.message_segment.type F_type = msg.message.message_segment.type
else: else:
if (isinstance(msg.message.message_segment.data, list) if (
and all(isinstance(x, Seg) for x in msg.message.message_segment.data) isinstance(msg.message.message_segment.data, list)
and len(msg.message.message_segment.data) == 1): and all(isinstance(x, Seg) for x in msg.message.message_segment.data)
and len(msg.message.message_segment.data) == 1
):
F_type = msg.message.message_segment.data[0].type F_type = msg.message.message_segment.data[0].type
if hasattr(msg.message, "processed_plain_text") and msg.message.processed_plain_text: if hasattr(msg.message, "processed_plain_text") and msg.message.processed_plain_text:
if F_type == "text": if F_type == "text":

View File

@@ -344,13 +344,13 @@ def process_llm_response(text: str) -> List[str]:
# 提取被 () 或 [] 包裹的内容 # 提取被 () 或 [] 包裹的内容
pattern = re.compile(r"[\(\[\].*?[\)\]\]") pattern = re.compile(r"[\(\[\].*?[\)\]\]")
# _extracted_contents = pattern.findall(text) # _extracted_contents = pattern.findall(text)
_extracted_contents = pattern.findall(protected_text) # 在保护后的文本上查找 _extracted_contents = pattern.findall(protected_text) # 在保护后的文本上查找
# 去除 () 和 [] 及其包裹的内容 # 去除 () 和 [] 及其包裹的内容
# cleaned_text = pattern.sub("", text) # cleaned_text = pattern.sub("", text)
cleaned_text = pattern.sub("", protected_text) cleaned_text = pattern.sub("", protected_text)
if cleaned_text == '': if cleaned_text == "":
return ["呃呃"] return ["呃呃"]
logger.debug(f"{text}去除括号处理后的文本: {cleaned_text}") logger.debug(f"{text}去除括号处理后的文本: {cleaned_text}")

View File

@@ -194,11 +194,13 @@ class ReasoningChat:
willing_manager.delete(message.message_info.message_id) willing_manager.delete(message.message_info.message_id)
F_type = "seglist" F_type = "seglist"
if message.message_segment.type != "seglist": if message.message_segment.type != "seglist":
F_type =message.message_segment.type F_type = message.message_segment.type
else: else:
if (isinstance(message.message_segment.data, list) if (
and all(isinstance(x, Seg) for x in message.message_segment.data) isinstance(message.message_segment.data, list)
and len(message.message_segment.data) == 1): and all(isinstance(x, Seg) for x in message.message_segment.data)
and len(message.message_segment.data) == 1
):
F_type = message.message_segment.data[0].type F_type = message.message_segment.data[0].type
if F_type == "text": if F_type == "text":
logger.info(f"触发缓冲,已炸飞消息:{message.processed_plain_text}") logger.info(f"触发缓冲,已炸飞消息:{message.processed_plain_text}")

View File

@@ -206,11 +206,13 @@ class ThinkFlowChat:
willing_manager.delete(message.message_info.message_id) willing_manager.delete(message.message_info.message_id)
F_type = "seglist" F_type = "seglist"
if message.message_segment.type != "seglist": if message.message_segment.type != "seglist":
F_type =message.message_segment.type F_type = message.message_segment.type
else: else:
if (isinstance(message.message_segment.data, list) if (
and all(isinstance(x, Seg) for x in message.message_segment.data) isinstance(message.message_segment.data, list)
and len(message.message_segment.data) == 1): and all(isinstance(x, Seg) for x in message.message_segment.data)
and len(message.message_segment.data) == 1
):
F_type = message.message_segment.data[0].type F_type = message.message_segment.data[0].type
if F_type == "text": if F_type == "text":
logger.info(f"触发缓冲,已炸飞消息:{message.processed_plain_text}") logger.info(f"触发缓冲,已炸飞消息:{message.processed_plain_text}")

View File

@@ -74,4 +74,3 @@ class ClassicalWillingManager(BaseWillingManager):
async def not_reply_handle(self, message_id): async def not_reply_handle(self, message_id):
return await super().not_reply_handle(message_id) return await super().not_reply_handle(message_id)

View File

@@ -234,4 +234,3 @@ class DynamicWillingManager(BaseWillingManager):
async def after_generate_reply_handle(self, message_id): async def after_generate_reply_handle(self, message_id):
return await super().after_generate_reply_handle(message_id) return await super().after_generate_reply_handle(message_id)

View File

@@ -10,12 +10,15 @@ llmcheck 模式:
目前的使用方式是拓展到其他意愿管理模式 目前的使用方式是拓展到其他意愿管理模式
""" """
import time import time
from loguru import logger from loguru import logger
from ..models.utils_model import LLM_request from ..models.utils_model import LLM_request
from ...config.config import global_config from ...config.config import global_config
# from ..chat.chat_stream import ChatStream # from ..chat.chat_stream import ChatStream
from ..chat.utils import get_recent_group_detailed_plain_text from ..chat.utils import get_recent_group_detailed_plain_text
# from .willing_manager import BaseWillingManager # from .willing_manager import BaseWillingManager
from .mode_mxp import MxpWillingManager from .mode_mxp import MxpWillingManager
import re import re
@@ -30,9 +33,7 @@ def is_continuous_chat(self, message_id: str):
config = self.global_config config = self.global_config
length = 5 length = 5
if chat_id: if chat_id:
chat_talking_text = get_recent_group_detailed_plain_text( chat_talking_text = get_recent_group_detailed_plain_text(chat_id, limit=length, combine=True)
chat_id, limit=length, combine=True
)
if group_info: if group_info:
if str(config.BOT_QQ) in chat_talking_text: if str(config.BOT_QQ) in chat_talking_text:
return True return True
@@ -40,6 +41,7 @@ def is_continuous_chat(self, message_id: str):
return False return False
return False return False
def llmcheck_decorator(trigger_condition_func): def llmcheck_decorator(trigger_condition_func):
def decorator(func): def decorator(func):
@wraps(func) @wraps(func)
@@ -50,18 +52,17 @@ def llmcheck_decorator(trigger_condition_func):
else: else:
# 不满足条件,走默认流程 # 不满足条件,走默认流程
return func(self, message_id) return func(self, message_id)
return wrapper return wrapper
return decorator return decorator
class LlmcheckWillingManager(MxpWillingManager): class LlmcheckWillingManager(MxpWillingManager):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.model_v3 = LLM_request(model=global_config.llm_normal, temperature=0.3) self.model_v3 = LLM_request(model=global_config.llm_normal, temperature=0.3)
async def get_llmreply_probability(self, message_id: str): async def get_llmreply_probability(self, message_id: str):
message_info = self.ongoing_messages[message_id] message_info = self.ongoing_messages[message_id]
chat_id = message_info.chat_id chat_id = message_info.chat_id
@@ -77,9 +78,7 @@ class LlmcheckWillingManager(MxpWillingManager):
current_time = time.strftime("%H:%M:%S", time.localtime()) current_time = time.strftime("%H:%M:%S", time.localtime())
chat_talking_prompt = "" chat_talking_prompt = ""
if chat_id: if chat_id:
chat_talking_prompt = get_recent_group_detailed_plain_text( chat_talking_prompt = get_recent_group_detailed_plain_text(chat_id, limit=length, combine=True)
chat_id, limit=length, combine=True
)
else: else:
return 0 return 0
@@ -100,7 +99,7 @@ class LlmcheckWillingManager(MxpWillingManager):
logger.info(f"{content_check} {reasoning_check}") logger.info(f"{content_check} {reasoning_check}")
probability = self.extract_marked_probability(content_check) probability = self.extract_marked_probability(content_check)
# 兴趣系数修正 无关激活效率太高,暂时停用,待新记忆系统上线后调整 # 兴趣系数修正 无关激活效率太高,暂时停用,待新记忆系统上线后调整
probability += (message_info.interested_rate * 0.25) probability += message_info.interested_rate * 0.25
probability = min(1.0, probability) probability = min(1.0, probability)
if probability <= 0.1: if probability <= 0.1:
probability = min(0.03, probability) probability = min(0.03, probability)
@@ -117,24 +116,24 @@ class LlmcheckWillingManager(MxpWillingManager):
def extract_marked_probability(text): def extract_marked_probability(text):
"""提取带标记的概率值 该方法主要用于测试微调prompt阶段""" """提取带标记的概率值 该方法主要用于测试微调prompt阶段"""
text = text.strip() text = text.strip()
pattern = r'##PROBABILITY_START##(.*?)##PROBABILITY_END##' pattern = r"##PROBABILITY_START##(.*?)##PROBABILITY_END##"
match = re.search(pattern, text, re.DOTALL) match = re.search(pattern, text, re.DOTALL)
if match: if match:
prob_str = match.group(1).strip() prob_str = match.group(1).strip()
# 处理百分比65% → 0.65 # 处理百分比65% → 0.65
if '%' in prob_str: if "%" in prob_str:
return float(prob_str.replace('%', '')) / 100 return float(prob_str.replace("%", "")) / 100
# 处理分数2/3 → 0.666... # 处理分数2/3 → 0.666...
elif '/' in prob_str: elif "/" in prob_str:
numerator, denominator = map(float, prob_str.split('/')) numerator, denominator = map(float, prob_str.split("/"))
return numerator / denominator return numerator / denominator
# 直接处理小数 # 直接处理小数
else: else:
return float(prob_str) return float(prob_str)
percent_match = re.search(r'(\d{1,3})%', text) # 65% percent_match = re.search(r"(\d{1,3})%", text) # 65%
decimal_match = re.search(r'(0\.\d+|1\.0+)', text) # 0.65 decimal_match = re.search(r"(0\.\d+|1\.0+)", text) # 0.65
fraction_match = re.search(r'(\d+)/(\d+)', text) # 2/3 fraction_match = re.search(r"(\d+)/(\d+)", text) # 2/3
try: try:
if percent_match: if percent_match:
prob = float(percent_match.group(1)) / 100 prob = float(percent_match.group(1)) / 100
@@ -155,6 +154,4 @@ class LlmcheckWillingManager(MxpWillingManager):
@llmcheck_decorator(is_continuous_chat) @llmcheck_decorator(is_continuous_chat)
def get_reply_probability(self, message_id): def get_reply_probability(self, message_id):
return super().get_reply_probability( return super().get_reply_probability(message_id)
message_id
)

View File

@@ -36,7 +36,9 @@ class MxpWillingManager(BaseWillingManager):
self.last_response_person: Dict[str, tuple[str, int]] = {} # 上次回复的用户信息 self.last_response_person: Dict[str, tuple[str, int]] = {} # 上次回复的用户信息
self.temporary_willing: float = 0 # 临时意愿值 self.temporary_willing: float = 0 # 临时意愿值
self.chat_bot_message_time: Dict[str, list[float]] = {} # 聊天流ID: bot已回复消息时间 self.chat_bot_message_time: Dict[str, list[float]] = {} # 聊天流ID: bot已回复消息时间
self.chat_fatigue_punishment_list: Dict[str, list[tuple[float, float]]] = {} # 聊天流疲劳惩罚列, 聊天流ID: 惩罚时间列(开始时间,持续时间) self.chat_fatigue_punishment_list: Dict[
str, list[tuple[float, float]]
] = {} # 聊天流疲劳惩罚列, 聊天流ID: 惩罚时间列(开始时间,持续时间)
self.chat_fatigue_willing_attenuation: Dict[str, float] = {} # 聊天流疲劳意愿衰减值 self.chat_fatigue_willing_attenuation: Dict[str, float] = {} # 聊天流疲劳意愿衰减值
# 可变参数 # 可变参数
@@ -70,8 +72,9 @@ class MxpWillingManager(BaseWillingManager):
w_info = self.ongoing_messages[message_id] w_info = self.ongoing_messages[message_id]
if w_info.chat_id not in self.chat_bot_message_time: if w_info.chat_id not in self.chat_bot_message_time:
self.chat_bot_message_time[w_info.chat_id] = [] self.chat_bot_message_time[w_info.chat_id] = []
self.chat_bot_message_time[w_info.chat_id] = \ self.chat_bot_message_time[w_info.chat_id] = [
[t for t in self.chat_bot_message_time[w_info.chat_id] if current_time - t < 60] t for t in self.chat_bot_message_time[w_info.chat_id] if current_time - t < 60
]
self.chat_bot_message_time[w_info.chat_id].append(current_time) self.chat_bot_message_time[w_info.chat_id].append(current_time)
if len(self.chat_bot_message_time[w_info.chat_id]) == int(self.fatigue_messages_triggered_num): if len(self.chat_bot_message_time[w_info.chat_id]) == int(self.fatigue_messages_triggered_num):
time_interval = 60 - (current_time - self.chat_bot_message_time[w_info.chat_id].pop(0)) time_interval = 60 - (current_time - self.chat_bot_message_time[w_info.chat_id].pop(0))
@@ -127,7 +130,9 @@ class MxpWillingManager(BaseWillingManager):
if w_info.interested_rate > 0: if w_info.interested_rate > 0:
current_willing += math.atan(w_info.interested_rate / 2) / math.pi * 2 * self.interest_willing_gain current_willing += math.atan(w_info.interested_rate / 2) / math.pi * 2 * self.interest_willing_gain
if self.is_debug: if self.is_debug:
self.logger.debug(f"兴趣增益:{math.atan(w_info.interested_rate / 2) / math.pi * 2 * self.interest_willing_gain}") self.logger.debug(
f"兴趣增益:{math.atan(w_info.interested_rate / 2) / math.pi * 2 * self.interest_willing_gain}"
)
self.chat_person_reply_willing[w_info.chat_id][w_info.person_id] = current_willing self.chat_person_reply_willing[w_info.chat_id][w_info.person_id] = current_willing
@@ -144,7 +149,9 @@ class MxpWillingManager(BaseWillingManager):
): ):
current_willing += self.single_chat_gain * (2 * self.last_response_person[w_info.chat_id][1] + 1) current_willing += self.single_chat_gain * (2 * self.last_response_person[w_info.chat_id][1] + 1)
if self.is_debug: if self.is_debug:
self.logger.debug(f"单聊增益:{self.single_chat_gain * (2 * self.last_response_person[w_info.chat_id][1] + 1)}") self.logger.debug(
f"单聊增益:{self.single_chat_gain * (2 * self.last_response_person[w_info.chat_id][1] + 1)}"
)
current_willing += self.chat_fatigue_willing_attenuation.get(w_info.chat_id, 0) current_willing += self.chat_fatigue_willing_attenuation.get(w_info.chat_id, 0)
if self.is_debug: if self.is_debug:
@@ -169,7 +176,6 @@ class MxpWillingManager(BaseWillingManager):
if self.is_debug: if self.is_debug:
self.logger.debug("进行中消息惩罚归0") self.logger.debug("进行中消息惩罚归0")
probability = self._willing_to_probability(current_willing) probability = self._willing_to_probability(current_willing)
if w_info.is_emoji: if w_info.is_emoji:
@@ -225,18 +231,21 @@ class MxpWillingManager(BaseWillingManager):
if chat.stream_id not in self.chat_fatigue_punishment_list: if chat.stream_id not in self.chat_fatigue_punishment_list:
self.chat_fatigue_punishment_list[chat.stream_id] = [ self.chat_fatigue_punishment_list[chat.stream_id] = [
(current_time, self.number_of_message_storage * self.basic_maximum_willing / self.expected_replies_per_min * 60) (
current_time,
self.number_of_message_storage * self.basic_maximum_willing / self.expected_replies_per_min * 60,
)
] ]
self.chat_fatigue_willing_attenuation[chat.stream_id] = - 2 * self.basic_maximum_willing * self.fatigue_coefficient self.chat_fatigue_willing_attenuation[chat.stream_id] = (
-2 * self.basic_maximum_willing * self.fatigue_coefficient
)
def _willing_to_probability(self, willing: float) -> float: def _willing_to_probability(self, willing: float) -> float:
"""意愿值转化为概率""" """意愿值转化为概率"""
willing = max(0, willing) willing = max(0, willing)
if willing < 2: if willing < 2:
probability = math.atan(willing * 2) / math.pi * 2 probability = math.atan(willing * 2) / math.pi * 2
elif willing <2.5: elif willing < 2.5:
probability = math.atan(willing * 4) / math.pi * 2 probability = math.atan(willing * 4) / math.pi * 2
else: else:
probability = 1 probability = 1
@@ -252,8 +261,13 @@ class MxpWillingManager(BaseWillingManager):
# 清理过期消息 # 清理过期消息
current_time = time.time() current_time = time.time()
message_times = [ message_times = [
msg_time for msg_time in message_times if current_time - msg_time < msg_time
self.number_of_message_storage * self.basic_maximum_willing / self.expected_replies_per_min * 60 for msg_time in message_times
if current_time - msg_time
< self.number_of_message_storage
* self.basic_maximum_willing
/ self.expected_replies_per_min
* 60
] ]
self.chat_new_message_time[chat_id] = message_times self.chat_new_message_time[chat_id] = message_times
@@ -271,7 +285,6 @@ class MxpWillingManager(BaseWillingManager):
if self.is_debug: if self.is_debug:
self.logger.debug(f"聊天流意愿值更新:{self.chat_reply_willing}") self.logger.debug(f"聊天流意愿值更新:{self.chat_reply_willing}")
def _get_relationship_level_num(self, relationship_value) -> int: def _get_relationship_level_num(self, relationship_value) -> int:
"""关系等级计算""" """关系等级计算"""
if -1000 <= relationship_value < -227: if -1000 <= relationship_value < -227:
@@ -292,8 +305,7 @@ class MxpWillingManager(BaseWillingManager):
def _basic_willing_culculate(self, t: float) -> float: def _basic_willing_culculate(self, t: float) -> float:
"""基础意愿值计算""" """基础意愿值计算"""
return math.tan(t * self.expected_replies_per_min * math.pi return math.tan(t * self.expected_replies_per_min * math.pi / 120 / self.number_of_message_storage) / 2
/ 120 / self.number_of_message_storage) / 2
async def _fatigue_attenuation(self): async def _fatigue_attenuation(self):
"""疲劳衰减""" """疲劳衰减"""
@@ -305,10 +317,13 @@ class MxpWillingManager(BaseWillingManager):
fatigue_list = [z for z in fatigue_list if current_time - z[0] < z[1]] fatigue_list = [z for z in fatigue_list if current_time - z[0] < z[1]]
self.chat_fatigue_willing_attenuation[chat_id] = 0 self.chat_fatigue_willing_attenuation[chat_id] = 0
for start_time, duration in fatigue_list: for start_time, duration in fatigue_list:
self.chat_fatigue_willing_attenuation[chat_id] += \ self.chat_fatigue_willing_attenuation[chat_id] += (
(self.chat_reply_willing[chat_id] * 2 / math.pi * math.asin( self.chat_reply_willing[chat_id]
2 * (current_time - start_time) / duration - 1 * 2
) - self.chat_reply_willing[chat_id]) * self.fatigue_coefficient / math.pi
* math.asin(2 * (current_time - start_time) / duration - 1)
- self.chat_reply_willing[chat_id]
) * self.fatigue_coefficient
async def get_willing(self, chat_id): async def get_willing(self, chat_id):
return self.temporary_willing return self.temporary_willing