This commit is contained in:
墨梓柒
2025-05-28 23:29:25 +08:00
25 changed files with 230 additions and 167 deletions

View File

@@ -635,7 +635,7 @@ class EmojiManager:
"""获取所有表情包并初始化为MaiEmoji类对象更新 self.emoji_objects"""
try:
self._ensure_db()
logger.info("[数据库] 开始加载所有表情包记录 (Peewee)...")
logger.debug("[数据库] 开始加载所有表情包记录 (Peewee)...")
emoji_peewee_instances = Emoji.select()
emoji_objects, load_errors = _to_emoji_objects(emoji_peewee_instances)

View File

@@ -234,9 +234,8 @@ class DefaultExpressor:
# logger.info(f"{self.log_prefix}\nPrompt:\n{prompt}\n---------------------------\n")
logger.info(f"想要表达:{in_mind_reply}")
logger.info(f"理由:{reason}")
logger.info(f"生成回复: {content}\n")
logger.info(f"想要表达:{in_mind_reply}||理由:{reason}")
logger.info(f"最终回复: {content}\n")
info_catcher.catch_after_llm_generated(
prompt=prompt, response=content, reasoning_content=reasoning_content, model_name=model_name

View File

@@ -204,7 +204,8 @@ class ExpressionLearner:
random_msg: Optional[List[Dict[str, Any]]] = get_raw_msg_by_timestamp_random(
current_time - 3600 * 24, current_time, limit=num
)
if not random_msg:
# print(random_msg)
if not random_msg or random_msg == []:
return None
# 转化成str
chat_id: str = random_msg[0]["chat_id"]
@@ -216,7 +217,7 @@ class ExpressionLearner:
chat_str=random_msg_str,
)
# logger.info(f"学习{type_str}的prompt: {prompt}")
logger.debug(f"学习{type_str}的prompt: {prompt}")
try:
response, _ = await self.express_learn_model.generate_response_async(prompt)
@@ -224,7 +225,7 @@ class ExpressionLearner:
logger.error(f"学习{type_str}失败: {e}")
return None
logger.info(f"学习{type_str}的response: {response}")
logger.debug(f"学习{type_str}的response: {response}")
expressions: List[Tuple[str, str, str]] = self.parse_expression_response(response, chat_id)

View File

@@ -54,7 +54,7 @@ CONSECUTIVE_NO_REPLY_THRESHOLD = 3 # 连续不回复的阈值
logger = get_logger("hfc") # Logger Name Changed
# 设定处理器超时时间(秒)
PROCESSOR_TIMEOUT = 20
PROCESSOR_TIMEOUT = 40
async def _handle_cycle_delay(action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str):
@@ -406,15 +406,13 @@ class HeartFChatting:
try:
# 使用 await task 来获取结果或触发异常
result_list = await task
logger.info(
f"{self.log_prefix} 处理器 {processor_name} 已完成,信息已处理: {duration_since_parallel_start:.2f}"
)
logger.info(f"{self.log_prefix} 处理器 {processor_name} 已完成!")
if result_list is not None:
all_plan_info.extend(result_list)
else:
logger.warning(f"{self.log_prefix} 处理器 {processor_name} 返回了 None")
except asyncio.TimeoutError:
logger.error(f"{self.log_prefix} 处理器 {processor_name} 超时(>{PROCESSOR_TIMEOUT}s已跳过")
logger.info(f"{self.log_prefix} 处理器 {processor_name} 超时(>{PROCESSOR_TIMEOUT}s已跳过")
except Exception as e:
logger.error(
f"{self.log_prefix} 处理器 {processor_name} 执行失败,耗时 (自并行开始): {duration_since_parallel_start:.2f}秒. 错误: {e}",
@@ -493,7 +491,7 @@ class HeartFChatting:
else:
action_str = action_type
logger.info(f"{self.log_prefix} 麦麦决定'{action_str}', 原因'{reasoning}'")
logger.debug(f"{self.log_prefix} 麦麦想要:'{action_str}', 原因'{reasoning}'")
success, reply_text, command = await self._handle_action(
action_type, reasoning, action_data, cycle_timers, thinking_id
@@ -576,8 +574,8 @@ class HeartFChatting:
else:
success, reply_text = result
command = ""
logger.info(
f"{self.log_prefix} 麦麦决定'{action}', 原因'{reasoning}',返回结果'{success}', '{reply_text}', '{command}'"
logger.debug(
f"{self.log_prefix} 麦麦执行了'{action}', 原因'{reasoning}',返回结果'{success}', '{reply_text}', '{command}'"
)
return success, reply_text, command

View File

@@ -1,18 +1,21 @@
import traceback
from ..memory_system.Hippocampus import HippocampusManager
from ...config.config import global_config
from ..message_receive.message import MessageRecv
from ..message_receive.storage import MessageStorage
from ..utils.utils import is_mentioned_bot_in_message
from src.chat.memory_system.Hippocampus import HippocampusManager
from src.config.config import global_config
from src.chat.message_receive.message import MessageRecv
from src.chat.message_receive.storage import MessageStorage
from src.chat.heart_flow.heartflow import heartflow
from src.chat.message_receive.chat_stream import chat_manager, ChatStream
from src.chat.utils.utils import is_mentioned_bot_in_message
from src.chat.utils.timer_calculator import Timer
from src.common.logger_manager import get_logger
from ..message_receive.chat_stream import chat_manager
from src.person_info.relationship_manager import relationship_manager
import math
import re
import traceback
from typing import Optional, Tuple, Dict, Any
from maim_message import UserInfo
# from ..message_receive.message_buffer import message_buffer
from ..utils.timer_calculator import Timer
from src.person_info.relationship_manager import relationship_manager
from typing import Optional, Tuple, Dict, Any
logger = get_logger("chat")
@@ -109,7 +112,7 @@ async def _calculate_interest(message: MessageRecv) -> Tuple[float, bool]:
# return "seglist"
def _check_ban_words(text: str, chat, userinfo) -> bool:
def _check_ban_words(text: str, chat: ChatStream, userinfo: UserInfo) -> bool:
"""检查消息是否包含过滤词
Args:
@@ -129,7 +132,7 @@ def _check_ban_words(text: str, chat, userinfo) -> bool:
return False
def _check_ban_regex(text: str, chat, userinfo) -> bool:
def _check_ban_regex(text: str, chat: ChatStream, userinfo: UserInfo) -> bool:
"""检查消息是否匹配过滤正则表达式
Args:
@@ -141,7 +144,7 @@ def _check_ban_regex(text: str, chat, userinfo) -> bool:
bool: 是否匹配过滤正则
"""
for pattern in global_config.message_receive.ban_msgs_regex:
if pattern.search(text):
if re.search(pattern, 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")

View File

@@ -227,7 +227,7 @@ class MindProcessor(BaseProcessor):
# 记录初步思考结果
logger.debug(f"{self.log_prefix} 思考prompt: \n{prompt}\n")
logger.info(f"{self.log_prefix} 思考结果: {content}")
logger.info(f"{self.log_prefix} 聊天规划: {content}")
self.update_current_mind(content)
return content

View File

@@ -186,7 +186,7 @@ class SelfProcessor(BaseProcessor):
content = ""
# 记录初步思考结果
logger.debug(f"{self.log_prefix} 自我识别prompt: \n{prompt}\n")
logger.info(f"{self.log_prefix} 自我识别结果: {content}")
logger.info(f"{self.log_prefix} 自我认知: {content}")
return content

View File

@@ -93,7 +93,7 @@ class WorkingMemoryProcessor(BaseProcessor):
# chat_info_truncate = observation.talking_message_str_truncate
if not working_memory:
logger.warning(f"{self.log_prefix} 没有找到工作记忆对象")
logger.debug(f"{self.log_prefix} 没有找到工作记忆对象")
mind_info = MindInfo()
return [mind_info]
except Exception as e:
@@ -180,7 +180,7 @@ class WorkingMemoryProcessor(BaseProcessor):
working_memory_info.add_working_memory(memory_str)
logger.debug(f"{self.log_prefix} 取得工作记忆: {memory_str}")
else:
logger.warning(f"{self.log_prefix} 没有找到工作记忆")
logger.debug(f"{self.log_prefix} 没有找到工作记忆")
# 根据聊天内容添加新记忆
if new_memory:

View File

@@ -100,6 +100,7 @@ class ReplyAction(BaseAction):
"emojis": "微笑" # 表情关键词列表(可选)
}
"""
logger.info(f"{self.log_prefix} 决定回复: {self.reasoning}")
# 从聊天观察获取锚定消息
chatting_observation: ChattingObservation = next(

View File

@@ -399,7 +399,7 @@ class MemoryManager:
try:
# 调用LLM修改总结、概括和要点
response, _ = await self.llm_summarizer.generate_response_async(prompt)
logger.info(f"精简记忆响应: {response}")
logger.debug(f"精简记忆响应: {response}")
# 使用repair_json处理响应
try:
# 修复JSON格式

View File

@@ -87,8 +87,6 @@ class BackgroundTaskManager:
),
]
)
else:
logger.info("聊天模式为 normal跳过启动清理任务、私聊激活任务和专注评估任务")
# 统一启动所有任务
for task_func, log_level, log_msg, task_attr_name in task_configs:

View File

@@ -78,18 +78,13 @@ class SubHeartflow:
logger.debug(
f"SubHeartflow {self.chat_id} initialized: is_group={self.is_group_chat}, target_info={self.chat_target_info}"
)
# --- End using utility function ---
# Initialize interest system (existing logic)
# await self.interest_chatting.initialize()
# logger.debug(f"{self.log_prefix} InterestChatting 实例已初始化。")
# 根据配置决定初始状态
if global_config.chat.chat_mode == "focus":
logger.info(f"{self.log_prefix} 配置为 focus 模式,将直接尝试进入 FOCUSED 状态。")
logger.debug(f"{self.log_prefix} 配置为 focus 模式,将直接尝试进入 FOCUSED 状态。")
await self.change_chat_state(ChatState.FOCUSED)
else: # "auto" 或其他模式保持原有逻辑或默认为 NORMAL
logger.info(f"{self.log_prefix} 配置为 auto 或其他模式,将尝试进入 NORMAL 状态。")
logger.debug(f"{self.log_prefix} 配置为 auto 或其他模式,将尝试进入 NORMAL 状态。")
await self.change_chat_state(ChatState.NORMAL)
def update_last_chat_state_time(self):
@@ -281,9 +276,9 @@ class SubHeartflow:
self.update_last_chat_state_time()
self.history_chat_state.append((current_state, self.chat_state_last_time))
logger.info(
f"{log_prefix} 麦麦的聊天状态从 {current_state.value} (持续了 {int(self.chat_state_last_time)} 秒) 变更为 {new_state.value}"
)
# logger.info(
# f"{log_prefix} 麦麦的聊天状态从 {current_state.value} (持续了 {int(self.chat_state_last_time)} 秒) 变更为 {new_state.value}"
# )
self.chat_state.chat_status = new_state
self.chat_state_last_time = 0

View File

@@ -223,8 +223,9 @@ class MessageManager:
# f"[message.apply_set_reply_logic:{message.apply_set_reply_logic},message.is_head:{message.is_head},thinking_messages_count:{thinking_messages_count},thinking_messages_length:{thinking_messages_length},message.is_private_message():{message.is_private_message()}]"
# )
if (
message.apply_set_reply_logic # 检查标记
and message.is_head
# message.apply_set_reply_logic # 检查标记
# and message.is_head
message.is_head
and (thinking_messages_count > 3 or thinking_messages_length > 200)
and not message.is_private_message()
):

View File

@@ -39,6 +39,7 @@ class NormalChat:
self.chat_target_info: Optional[dict] = None
self.willing_amplifier = 1
self.start_time = time.time()
# Other sync initializations
self.gpt = NormalChatGenerator()
@@ -64,7 +65,7 @@ class NormalChat:
self.is_group_chat, self.chat_target_info = await get_chat_type_and_target_info(self.stream_id)
self.stream_name = chat_manager.get_stream_name(self.stream_id) or self.stream_id
self._initialized = True
logger.info(f"[{self.stream_name}] NormalChat 实例 initialize 完成 (异步部分)。")
logger.debug(f"[{self.stream_name}] NormalChat 初始化完成 (异步部分)。")
# 改为实例方法
async def _create_thinking_message(self, message: MessageRecv, timestamp: Optional[float] = None) -> str:
@@ -208,7 +209,10 @@ class NormalChat:
for msg_id, (message, interest_value, is_mentioned) in items_to_process:
try:
# 处理消息
self.adjust_reply_frequency()
if time.time() - self.start_time > 600:
self.adjust_reply_frequency(duration=600 / 60)
else:
self.adjust_reply_frequency(duration=(time.time() - self.start_time) / 60)
await self.normal_response(
message=message,
@@ -256,7 +260,7 @@ class NormalChat:
logger.info(
f"[{mes_name}]"
f"{message.message_info.user_info.user_nickname}:" # 使用 self.chat_stream
f"{message.processed_plain_text}[回复概率:{reply_probability * 100:.1f}%]"
f"{message.processed_plain_text}[兴趣:{interested_rate:.2f}][回复概率:{reply_probability * 100:.1f}%]"
)
do_reply = False
response_set = None # 初始化 response_set
@@ -304,7 +308,7 @@ class NormalChat:
willing_manager.delete(message.message_info.message_id)
return # 不执行后续步骤
logger.info(f"[{self.stream_name}] 回复内容: {response_set}")
# logger.info(f"[{self.stream_name}] 回复内容: {response_set}")
if self._disabled:
logger.info(f"[{self.stream_name}] 已停用,忽略 normal_response。")
@@ -357,7 +361,7 @@ class NormalChat:
trigger_msg = message.processed_plain_text
response_msg = " ".join(response_set)
logger.info(
f"[{self.stream_name}] 触发消息: {trigger_msg[:20]}... | 推理消息: {response_msg[:20]}... | 性能计时: {timing_str}"
f"[{self.stream_name}]回复消息: {trigger_msg[:30]}... | 回复内容: {response_msg[:30]}... | 计时: {timing_str}"
)
elif not do_reply:
# 不回复处理
@@ -376,7 +380,7 @@ class NormalChat:
self._disabled = False # 启动时重置停用标志
if self._chat_task is None or self._chat_task.done():
logger.info(f"[{self.stream_name}] 开始处理兴趣消息...")
# logger.info(f"[{self.stream_name}] 开始处理兴趣消息...")
polling_task = asyncio.create_task(self._reply_interested_message())
polling_task.add_done_callback(lambda t: self._handle_task_completion(t))
self._chat_task = polling_task
@@ -483,21 +487,39 @@ class NormalChat:
调整回复频率
"""
# 获取最近30分钟内的消息统计
print(f"willing_amplifier: {self.willing_amplifier}")
stats = get_recent_message_stats(minutes=duration, chat_id=self.stream_id)
bot_reply_count = stats["bot_reply_count"]
print(f"[{self.stream_name}] 最近{duration}分钟内回复数量: {bot_reply_count}")
total_message_count = stats["total_message_count"]
print(f"[{self.stream_name}] 最近{duration}分钟内消息总数: {total_message_count}")
if total_message_count == 0:
return
logger.debug(
f"[{self.stream_name}]({self.willing_amplifier}) 最近{duration}分钟 回复数量: {bot_reply_count},消息总数: {total_message_count}"
)
# 计算回复频率
_reply_frequency = bot_reply_count / total_message_count
differ = global_config.normal_chat.talk_frequency - (bot_reply_count / duration)
# 如果回复频率低于0.5,增加回复概率
if bot_reply_count / duration < global_config.normal_chat.talk_frequency:
# differ = global_config.normal_chat.talk_frequency - reply_frequency
logger.info(f"[{self.stream_name}] 回复频率低于{global_config.normal_chat.talk_frequency},增加回复概率")
self.willing_amplifier += 0.1
else:
logger.info(f"[{self.stream_name}] 回复频率高于{global_config.normal_chat.talk_frequency},减少回复概率")
self.willing_amplifier -= 0.1
if differ > 0.1:
mapped = 1 + (differ - 0.1) * 4 / 0.9
mapped = max(1, min(5, mapped))
logger.info(
f"[{self.stream_name}] 回复频率低于{global_config.normal_chat.talk_frequency}增加回复概率differ={differ:.3f},映射值={mapped:.2f}"
)
self.willing_amplifier += mapped * 0.1 # 你可以根据实际需要调整系数
elif differ < -0.1:
mapped = 1 - (differ + 0.1) * 4 / 0.9
mapped = max(1, min(5, mapped))
logger.info(
f"[{self.stream_name}] 回复频率高于{global_config.normal_chat.talk_frequency}减少回复概率differ={differ:.3f},映射值={mapped:.2f}"
)
self.willing_amplifier -= mapped * 0.1
if self.willing_amplifier > 5:
self.willing_amplifier = 5
elif self.willing_amplifier < 0.1:
self.willing_amplifier = 0.1

View File

@@ -11,7 +11,7 @@ from src.chat.utils.info_catcher import info_catcher_manager
from src.person_info.person_info import person_info_manager
logger = get_logger("llm")
logger = get_logger("normal_chat_response")
class NormalChatGenerator:
@@ -40,25 +40,25 @@ class NormalChatGenerator:
"""根据当前模型类型选择对应的生成函数"""
# 从global_config中获取模型概率值并选择模型
if random.random() < global_config.normal_chat.normal_chat_first_probability:
self.current_model_type = "深深地"
current_model = self.model_reasoning
self.current_model_name = current_model.model_name
else:
self.current_model_type = "浅浅的"
current_model = self.model_normal
self.current_model_name = current_model.model_name
logger.info(
f"{self.current_model_type}思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}"
f"{self.current_model_name}思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}"
) # noqa: E501
model_response = await self._generate_response_with_model(message, current_model, thinking_id)
if model_response:
logger.info(f"{global_config.bot.nickname}的回复是:{model_response}")
logger.debug(f"{global_config.bot.nickname}原始回复是:{model_response}")
model_response = await self._process_response(model_response)
return model_response
else:
logger.info(f"{self.current_model_type}思考,失败")
logger.info(f"{self.current_model_name}思考,失败")
return None
async def _generate_response_with_model(self, message: MessageThinking, model: LLMRequest, thinking_id: str):

View File

@@ -441,6 +441,7 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
处理 回复<aaa:bbb> 和 @<aaa:bbb> 字段将bbb映射为匿名占位符。
"""
if not messages:
print("111111111111没有消息无法构建匿名消息")
return ""
person_map = {}
@@ -450,7 +451,12 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
def get_anon_name(platform, user_id):
if user_id == global_config.bot.qq_account:
return "SELF"
person_id = person_info_manager.get_person_id(platform, user_id)
try:
person_id = person_info_manager.get_person_id(platform, user_id)
except Exception as e:
person_id = None
if not person_id:
return "?"
if person_id not in person_map:
nonlocal current_char
person_map[person_id] = chr(current_char)
@@ -458,56 +464,74 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
return person_map[person_id]
for msg in messages:
user_info = msg.get("user_info", {})
platform = user_info.get("platform")
user_id = user_info.get("user_id")
timestamp = msg.get("time")
if msg.get("display_message"):
content = msg.get("display_message")
else:
content = msg.get("processed_plain_text", "")
try:
# user_info = msg.get("user_info", {})
platform = msg.get("chat_info_platform")
user_id = msg.get("chat_info_user_id")
timestamp = msg.get("time")
# print(f"msg:{msg}")
# print(f"platform:{platform}")
# print(f"user_id:{user_id}")
# print(f"timestamp:{timestamp}")
if msg.get("display_message"):
content = msg.get("display_message")
else:
content = msg.get("processed_plain_text", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if not all([platform, user_id, timestamp is not None]):
# if not all([platform, user_id, timestamp is not None]):
# continue
anon_name = get_anon_name(platform, user_id)
# print(f"anon_name:{anon_name}")
# 处理 回复<aaa:bbb>
reply_pattern = r"回复<([^:<>]+):([^:<>]+)>"
match = re.search(reply_pattern, content)
if match:
# print(f"发现回复match:{match}")
bbb = match.group(2)
try:
anon_reply = get_anon_name(platform, bbb)
except Exception:
anon_reply = "?"
content = re.sub(reply_pattern, f"回复 {anon_reply}", content, count=1)
# 处理 @<aaa:bbb>无嵌套def
at_pattern = r"@<([^:<>]+):([^:<>]+)>"
at_matches = list(re.finditer(at_pattern, content))
if at_matches:
# print(f"发现@match:{at_matches}")
new_content = ""
last_end = 0
for m in at_matches:
new_content += content[last_end:m.start()]
bbb = m.group(2)
try:
anon_at = get_anon_name(platform, bbb)
except Exception:
anon_at = "?"
new_content += f"@{anon_at}"
last_end = m.end()
new_content += content[last_end:]
content = new_content
header = f"{anon_name}"
output_lines.append(header)
stripped_line = content.strip()
if stripped_line:
if stripped_line.endswith(""):
stripped_line = stripped_line[:-1]
output_lines.append(f"{stripped_line}")
# print(f"output_lines:{output_lines}")
output_lines.append("\n")
except Exception:
continue
anon_name = get_anon_name(platform, user_id)
# 处理 回复<aaa:bbb>
reply_pattern = r"回复<([^:<>]+):([^:<>]+)>"
def reply_replacer(match, platform=platform):
# aaa = match.group(1)
bbb = match.group(2)
anon_reply = get_anon_name(platform, bbb) # noqa
return f"回复 {anon_reply}"
content = re.sub(reply_pattern, reply_replacer, content, count=1)
# 处理 @<aaa:bbb>
at_pattern = r"@<([^:<>]+):([^:<>]+)>"
def at_replacer(match, platform=platform):
# aaa = match.group(1)
bbb = match.group(2)
anon_at = get_anon_name(platform, bbb) # noqa
return f"@{anon_at}"
content = re.sub(at_pattern, at_replacer, content)
header = f"{anon_name}"
output_lines.append(header)
stripped_line = content.strip()
if stripped_line:
if stripped_line.endswith(""):
stripped_line = stripped_line[:-1]
output_lines.append(f"{stripped_line}")
output_lines.append("\n")
formatted_string = "".join(output_lines).strip()
return formatted_string

View File

@@ -100,7 +100,7 @@ class InfoCatcher:
time_end = message_end.message_info.time
chat_id = message_start.chat_stream.stream_id
print(f"查询参数: time_start={time_start}, time_end={time_end}, chat_id={chat_id}")
# print(f"查询参数: time_start={time_start}, time_end={time_end}, chat_id={chat_id}")
messages_between_query = (
Messages.select()
@@ -109,10 +109,10 @@ class InfoCatcher:
)
result = list(messages_between_query)
print(f"查询结果数量: {len(result)}")
if result:
print(f"第一条消息时间: {result[0].time}")
print(f"最后一条消息时间: {result[-1].time}")
# print(f"查询结果数量: {len(result)}")
# if result:
# print(f"第一条消息时间: {result[0].time}")
# print(f"最后一条消息时间: {result[-1].time}")
return result
except Exception as e:
print(f"获取消息时出错: {str(e)}")

View File

@@ -225,22 +225,37 @@ SCHEDULE_STYLE_CONFIG = {
},
}
LLM_STYLE_CONFIG = {
NORMAL_CHAT_RESPONSE_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<light-yellow>麦麦组织语言</light-yellow> | "
"<light-yellow>普通水群回复</light-yellow> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦组织语言 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群回复 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <light-green>麦麦组织语言</light-green> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦组织语言 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <light-green>普通水群回复</light-green> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群回复 | {message}",
},
}
EXPRESS_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<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": "<level>{time:HH:mm:ss}</level> | <fg #E595FF>麦麦表达</fg #E595FF> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦表达 | {message}",
},
}
# Topic日志样式配置
TOPIC_STYLE_CONFIG = {
@@ -282,14 +297,14 @@ NORMAL_CHAT_STYLE_CONFIG = {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<green>一般水群</green> | "
"<green>普通水群</green> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 一般水群 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #00B741>一般水群</fg #00B741> | <fg #00B741>{message}</fg #00B741>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 一般水群 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #00B741>普通水群</fg #00B741> | <fg #00B741>{message}</fg #00B741>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群 | {message}",
},
}
@@ -310,6 +325,7 @@ FOCUS_CHAT_STYLE_CONFIG = {
},
}
REMOTE_STYLE_CONFIG = {
"advanced": {
"console_format": (
@@ -530,19 +546,19 @@ EMOJI_STYLE_CONFIG = {
},
}
MAI_STATE_CONFIG = {
STATISTIC_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<light-blue>麦麦状态</light-blue> | "
"<light-blue>麦麦统计</light-blue> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦状态 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦统计 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #66CCFF>麦麦状态 | {message} </fg #66CCFF>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦状态 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #66CCFF>麦麦统计 | {message} </fg #66CCFF>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦统计 | {message}",
},
}
@@ -906,7 +922,9 @@ MEMORY_STYLE_CONFIG = MEMORY_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else MEMORY
CHAT_STREAM_STYLE_CONFIG = CHAT_STREAM_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CHAT_STREAM_STYLE_CONFIG["advanced"]
TOPIC_STYLE_CONFIG = TOPIC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else TOPIC_STYLE_CONFIG["advanced"]
SENDER_STYLE_CONFIG = SENDER_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SENDER_STYLE_CONFIG["advanced"]
LLM_STYLE_CONFIG = LLM_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else LLM_STYLE_CONFIG["advanced"]
NORMAL_CHAT_RESPONSE_STYLE_CONFIG = (
NORMAL_CHAT_RESPONSE_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else NORMAL_CHAT_RESPONSE_STYLE_CONFIG["advanced"]
)
CHAT_STYLE_CONFIG = CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CHAT_STYLE_CONFIG["advanced"]
MOOD_STYLE_CONFIG = MOOD_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else MOOD_STYLE_CONFIG["advanced"]
RELATION_STYLE_CONFIG = RELATION_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else RELATION_STYLE_CONFIG["advanced"]
@@ -919,7 +937,7 @@ SUB_HEARTFLOW_MIND_STYLE_CONFIG = (
SUB_HEARTFLOW_MIND_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SUB_HEARTFLOW_MIND_STYLE_CONFIG["advanced"]
)
WILLING_STYLE_CONFIG = WILLING_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else WILLING_STYLE_CONFIG["advanced"]
MAI_STATE_CONFIG = MAI_STATE_CONFIG["simple"] if SIMPLE_OUTPUT else MAI_STATE_CONFIG["advanced"]
STATISTIC_STYLE_CONFIG = STATISTIC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else STATISTIC_STYLE_CONFIG["advanced"]
CONFIG_STYLE_CONFIG = CONFIG_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CONFIG_STYLE_CONFIG["advanced"]
TOOL_USE_STYLE_CONFIG = TOOL_USE_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else TOOL_USE_STYLE_CONFIG["advanced"]
PFC_STYLE_CONFIG = PFC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else PFC_STYLE_CONFIG["advanced"]
@@ -971,6 +989,7 @@ INTEREST_CHAT_STYLE_CONFIG = (
)
NORMAL_CHAT_STYLE_CONFIG = NORMAL_CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else NORMAL_CHAT_STYLE_CONFIG["advanced"]
FOCUS_CHAT_STYLE_CONFIG = FOCUS_CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else FOCUS_CHAT_STYLE_CONFIG["advanced"]
EXPRESS_STYLE_CONFIG = EXPRESS_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else EXPRESS_STYLE_CONFIG["advanced"]
def is_registered_module(record: dict) -> bool:

View File

@@ -9,7 +9,6 @@ from src.common.logger import (
RELATION_STYLE_CONFIG,
CONFIG_STYLE_CONFIG,
HEARTFLOW_STYLE_CONFIG,
LLM_STYLE_CONFIG,
CHAT_STYLE_CONFIG,
EMOJI_STYLE_CONFIG,
SUB_HEARTFLOW_STYLE_CONFIG,
@@ -20,7 +19,7 @@ from src.common.logger import (
PERSON_INFO_STYLE_CONFIG,
WILLING_STYLE_CONFIG,
PFC_ACTION_PLANNER_STYLE_CONFIG,
MAI_STATE_CONFIG,
STATISTIC_STYLE_CONFIG,
NORMAL_CHAT_STYLE_CONFIG,
FOCUS_CHAT_STYLE_CONFIG,
LPMM_STYLE_CONFIG,
@@ -47,6 +46,8 @@ from src.common.logger import (
INIT_STYLE_CONFIG,
INTEREST_CHAT_STYLE_CONFIG,
API_SERVER_STYLE_CONFIG,
NORMAL_CHAT_RESPONSE_STYLE_CONFIG,
EXPRESS_STYLE_CONFIG,
)
# 可根据实际需要补充更多模块配置
@@ -60,7 +61,7 @@ MODULE_LOGGER_CONFIGS = {
"relation": RELATION_STYLE_CONFIG, # 关系
"config": CONFIG_STYLE_CONFIG, # 配置
"heartflow": HEARTFLOW_STYLE_CONFIG, # 麦麦大脑袋
"llm": LLM_STYLE_CONFIG, # 麦麦组织语言
"normal_chat_response": NORMAL_CHAT_RESPONSE_STYLE_CONFIG, # 麦麦组织语言
"chat": CHAT_STYLE_CONFIG, # 见闻
"emoji": EMOJI_STYLE_CONFIG, # 表情包
"sub_heartflow": SUB_HEARTFLOW_STYLE_CONFIG, # 麦麦水群
@@ -71,7 +72,7 @@ MODULE_LOGGER_CONFIGS = {
"person_info": PERSON_INFO_STYLE_CONFIG, # 人物信息
"willing": WILLING_STYLE_CONFIG, # 意愿
"pfc_action_planner": PFC_ACTION_PLANNER_STYLE_CONFIG, # PFC私聊规划
"mai_state": MAI_STATE_CONFIG, # 麦麦状态
"statistic": STATISTIC_STYLE_CONFIG, # 麦麦统计
"lpmm": LPMM_STYLE_CONFIG, # LPMM
"hfc": HFC_STYLE_CONFIG, # HFC
"observation": OBSERVATION_STYLE_CONFIG, # 聊天观察
@@ -98,6 +99,7 @@ MODULE_LOGGER_CONFIGS = {
"api": API_SERVER_STYLE_CONFIG, # API服务器
"normal_chat": NORMAL_CHAT_STYLE_CONFIG, # 一般水群
"focus_chat": FOCUS_CHAT_STYLE_CONFIG, # 专注水群
"expressor": EXPRESS_STYLE_CONFIG, # 麦麦表达
# ...如有更多模块,继续添加...
}

View File

@@ -45,7 +45,7 @@ class MainSystem:
# 其他初始化任务
await asyncio.gather(self._init_components())
logger.success("系统初始化完成")
logger.debug("系统初始化完成")
async def _init_components(self):
"""初始化其他组件"""
@@ -73,7 +73,7 @@ class MainSystem:
await async_task_manager.add_task(MoodPrintTask())
# 检查并清除person_info冗余字段启动个人习惯推断
await person_info_manager.del_all_undefined_field()
# await person_info_manager.del_all_undefined_field()
asyncio.create_task(person_info_manager.personal_habit_deduction())
# 启动愿望管理器
@@ -142,29 +142,30 @@ class MainSystem:
"""记忆遗忘任务"""
while True:
await asyncio.sleep(global_config.memory.forget_memory_interval)
print("\033[1;32m[记忆遗忘]\033[0m 开始遗忘记忆...")
logger.info("[记忆遗忘] 开始遗忘记忆...")
await HippocampusManager.get_instance().forget_memory(
percentage=global_config.memory.memory_forget_percentage
)
print("\033[1;32m[记忆遗忘]\033[0m 记忆遗忘完成")
logger.info("[记忆遗忘] 记忆遗忘完成")
@staticmethod
async def consolidate_memory_task():
"""记忆整合任务"""
while True:
await asyncio.sleep(global_config.memory.consolidate_memory_interval)
print("\033[1;32m[记忆整合]\033[0m 开始整合记忆...")
logger.info("[记忆整合] 开始整合记忆...")
await HippocampusManager.get_instance().consolidate_memory()
print("\033[1;32m[记忆整合]\033[0m 记忆整合完成")
logger.info("[记忆整合] 记忆整合完成")
@staticmethod
async def learn_and_store_expression_task():
"""学习并存储表达方式任务"""
while True:
await asyncio.sleep(global_config.expression.learning_interval)
print("\033[1;32m[表达方式学习]\033[0m 开始学习表达方式...")
await expression_learner.learn_and_store_expression()
print("\033[1;32m[表达方式学习]\033[0m 表达方式学习完成")
if global_config.expression.enable_expression_learning:
logger.info("[表达方式学习] 开始学习表达方式...")
await expression_learner.learn_and_store_expression()
logger.info("[表达方式学习] 表达方式学习完成")
# async def print_mood_task(self):
# """打印情绪状态"""

View File

@@ -103,7 +103,7 @@ class AsyncTaskManager:
) # 添加完成回调函数-用户自定义或默认的FallBack
self.tasks[task.task_name] = task_inst # 将任务添加到任务列表
logger.info(f"已启动任务 '{task.task_name}'")
logger.debug(f"已启动任务 '{task.task_name}'")
def get_tasks_status(self) -> Dict[str, Dict[str, str]]:
"""

View File

@@ -425,13 +425,13 @@ class PersonInfoManager:
return result
@staticmethod
async def del_all_undefined_field():
"""删除所有项里的未定义字段 - 对于Peewee (SQL),此操作通常不适用,因为模式是固定的。"""
logger.info(
"del_all_undefined_field: 对于使用Peewee的SQL数据库此操作通常不适用或不需要因为表结构是预定义的。"
)
return
# @staticmethod
# async def del_all_undefined_field():
# """删除所有项里的未定义字段 - 对于Peewee (SQL),此操作通常不适用,因为模式是固定的。"""
# logger.info(
# "del_all_undefined_field: 对于使用Peewee的SQL数据库此操作通常不适用或不需要因为表结构是预定义的。"
# )
# return
@staticmethod
async def get_specific_value_list(

View File

@@ -56,14 +56,14 @@ class RelationshipManager:
self.positive_feedback_value = 0
if abs(self.positive_feedback_value) > 1:
logger.info(f"触发mood变更增益当前增益系数{self.gain_coefficient[abs(self.positive_feedback_value)]}")
logger.debug(f"触发mood变更增益当前增益系数{self.gain_coefficient[abs(self.positive_feedback_value)]}")
def mood_feedback(self, value):
"""情绪反馈"""
mood_manager = self.mood_manager
mood_gain = mood_manager.current_mood.valence**2 * math.copysign(1, value * mood_manager.current_mood.valence)
value += value * mood_gain
logger.info(f"当前relationship增益系数{mood_gain:.3f}")
logger.debug(f"当前relationship增益系数{mood_gain:.3f}")
return value
def feedback_to_mood(self, mood_value):

View File

@@ -12,8 +12,8 @@ class MuteAction(PluginAction):
action_name = "mute_action"
action_description = "如果某人违反了公序良俗,或者别人戳你太多,或者某人刷屏,一定要禁言某人,如果你很生气,可以禁言某人,可以自选禁言时长,视严重程度而定。"
action_parameters = {
"target": "禁言对象,输入你要禁言的对象的名字,必填",
"duration": "禁言时长,输入你要禁言的时长(秒),单位为秒,必填,必须为数字",
"target": "禁言对象,必填,输入你要禁言的对象的名字",
"duration": "禁言时长,必填,输入你要禁言的时长(秒),单位为秒,必须为数字",
"reason": "禁言理由,可选",
}
action_require = [
@@ -24,8 +24,8 @@ class MuteAction(PluginAction):
"当你想回避某个话题时使用",
]
default = True # 默认动作,是否手动添加到使用集
# associated_types = ["command", "text"]
associated_types = ["text"]
associated_types = ["command", "text"]
# associated_types = ["text"]
async def process(self) -> Tuple[bool, str]:
"""处理群聊禁言动作"""