Merge branch 'MaiM-with-u:dev' into dev

This commit is contained in:
UnCLAS-Prommer
2025-04-21 15:26:11 +08:00
committed by GitHub
15 changed files with 92 additions and 71 deletions

View File

@@ -14,7 +14,7 @@
<p align="center">
<a href="https://github.com/MaiM-with-u/MaiBot/">
<img src="depends-data/maimai.png" alt="Logo" width="200">
<img src="depends-data/maimai.png" alt="Logo" style="max-width: 200px">
</a>
<br />
<a href="https://space.bilibili.com/1344099355">
@@ -34,7 +34,6 @@
·
<a href="https://github.com/MaiM-with-u/MaiBot/issues">提出新特性</a>
</p>
</p>
## 新版0.6.x部署前先阅读https://docs.mai-mai.org/manual/usage/mmc_q_a
@@ -53,7 +52,7 @@
<div align="center">
<a href="https://www.bilibili.com/video/BV1amAneGE3P" target="_blank">
<img src="depends-data/video.png" width="200" alt="麦麦演示视频">
<img src="depends-data/video.png" style="max-width: 200px" alt="麦麦演示视频">
<br>
👆 点击观看麦麦演示视频 👆
</a>
@@ -186,7 +185,7 @@ MaiCore是一个开源项目我们非常欢迎你的参与。你的贡献
感谢各位大佬!
<a href="https://github.com/MaiM-with-u/MaiBot/graphs/contributors">
<img src="https://contrib.rocks/image?repo=MaiM-with-u/MaiBot" />
<img alt="contributors" src="https://contrib.rocks/image?repo=MaiM-with-u/MaiBot" />
</a>
**也感谢每一位给麦麦发展提出宝贵意见与建议的用户,感谢陪伴麦麦走到现在的你们**

View File

@@ -105,3 +105,4 @@ class Individuality:
return self.personality.agreeableness
elif factor == "neuroticism":
return self.personality.neuroticism
return None

View File

@@ -18,7 +18,7 @@ from .plugins.remote import heartbeat_thread # noqa: F401
from .individuality.individuality import Individuality
from .common.server import global_server
from .plugins.chat_module.heartFC_chat.interest import InterestManager
from .plugins.chat_module.heartFC_chat.heartFC_controler import HeartFC_Controller
from .plugins.chat_module.heartFC_chat.heartFC_controler import HeartFCController
logger = get_module_logger("main")
@@ -118,8 +118,8 @@ class MainSystem:
logger.success("兴趣管理器后台任务启动成功")
# 初始化并独立启动 HeartFC_Chat
HeartFC_Controller()
heartfc_chat_instance = HeartFC_Controller.get_instance()
HeartFCController()
heartfc_chat_instance = HeartFCController.get_instance()
if heartfc_chat_instance:
await heartfc_chat_instance.start()
logger.success("HeartFC_Chat 模块独立启动成功")

View File

@@ -180,6 +180,7 @@ class Conversation:
"time": datetime.datetime.now().strftime("%H:%M:%S"),
}
)
return None
elif action == "fetch_knowledge":
self.waiter.wait_accumulated_time = 0
@@ -193,28 +194,35 @@ class Conversation:
if knowledge:
if topic not in self.conversation_info.knowledge_list:
self.conversation_info.knowledge_list.append({"topic": topic, "knowledge": knowledge})
return None
else:
self.conversation_info.knowledge_list[topic] += knowledge
return None
return None
elif action == "rethink_goal":
self.waiter.wait_accumulated_time = 0
self.state = ConversationState.RETHINKING
await self.goal_analyzer.analyze_goal(conversation_info, observation_info)
return None
elif action == "listening":
self.state = ConversationState.LISTENING
logger.info("倾听对方发言...")
await self.waiter.wait_listening(conversation_info)
return None
elif action == "end_conversation":
self.should_continue = False
logger.info("决定结束对话...")
return None
else: # wait
self.state = ConversationState.WAITING
logger.info("等待更多信息...")
await self.waiter.wait(self.conversation_info)
return None
async def _send_timeout_message(self):
"""发送超时结束消息"""

View File

@@ -7,7 +7,7 @@ from ..chat_module.only_process.only_message_process import MessageProcessor
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
from ..chat_module.reasoning_chat.reasoning_chat import ReasoningChat
from ..chat_module.heartFC_chat.heartFC_processor import HeartFC_Processor
from ..chat_module.heartFC_chat.heartFC_processor import HeartFCProcessor
from ..utils.prompt_builder import Prompt, global_prompt_manager
import traceback
@@ -29,7 +29,7 @@ class ChatBot:
self.mood_manager = MoodManager.get_instance() # 获取情绪管理器单例
self.mood_manager.start_mood_update() # 启动情绪更新
self.reasoning_chat = ReasoningChat()
self.heartFC_processor = HeartFC_Processor() # 新增
self.heartFC_processor = HeartFCProcessor() # 新增
# 创建初始化PFC管理器的任务会在_ensure_started时执行
self.only_process_chat = MessageProcessor()

View File

@@ -1,14 +1,13 @@
import time
from dataclasses import dataclass
from typing import Dict, List, Optional
from typing import Dict, List, Optional, Union
import urllib3
from .utils_image import image_manager
from ..message.message_base import Seg, UserInfo, BaseMessageInfo, MessageBase
from .chat_stream import ChatStream
from src.common.logger import get_module_logger
from .chat_stream import ChatStream
from .utils_image import image_manager
from ..message.message_base import Seg, UserInfo, BaseMessageInfo, MessageBase
logger = get_module_logger("chat_message")
@@ -207,7 +206,7 @@ class MessageProcessBase(Message):
# 处理单个消息段
return await self._process_single_segment(segment)
async def _process_single_segment(self, seg: Seg) -> str:
async def _process_single_segment(self, seg: Seg) -> Union[str, None]:
"""处理单个消息段
Args:
@@ -233,6 +232,7 @@ class MessageProcessBase(Message):
elif seg.type == "reply":
if self.reply and hasattr(self.reply, "processed_plain_text"):
return f"[回复:{self.reply.processed_plain_text}]"
return None
else:
return f"[{seg.type}:{str(seg.data)}]"
except Exception as e:

View File

@@ -2,7 +2,7 @@ import random
import time
import re
from collections import Counter
from typing import Dict, List
from typing import Dict, List, Optional
import jieba
import numpy as np
@@ -688,7 +688,7 @@ def count_messages_between(start_time: float, end_time: float, stream_id: str) -
return 0, 0
def translate_timestamp_to_human_readable(timestamp: float, mode: str = "normal") -> str:
def translate_timestamp_to_human_readable(timestamp: float, mode: str = "normal") -> Optional[str]:
"""将时间戳转换为人类可读的时间格式
Args:
@@ -716,6 +716,7 @@ def translate_timestamp_to_human_readable(timestamp: float, mode: str = "normal"
return f"{int(diff / 86400)}天前:\n"
else:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)) + ":\n"
return None
def parse_text_timestamps(text: str, mode: str = "normal") -> str:

View File

@@ -20,18 +20,18 @@ chat_config = LogConfig(
file_format=CHAT_STYLE_CONFIG["file_format"],
)
logger = get_module_logger("HeartFC_Controller", config=chat_config)
logger = get_module_logger("HeartFCController", config=chat_config)
# 检测群聊兴趣的间隔时间
INTEREST_MONITOR_INTERVAL_SECONDS = 1
class HeartFC_Controller:
class HeartFCController:
_instance = None # For potential singleton access if needed by MessageManager
def __init__(self):
# --- Updated Init ---
if HeartFC_Controller._instance is not None:
if HeartFCController._instance is not None:
# Prevent re-initialization if used as a singleton
return
self.gpt = ResponseGenerator()
@@ -44,7 +44,7 @@ class HeartFC_Controller:
self.pf_chatting_instances: Dict[str, PFChatting] = {}
self._pf_chatting_lock = Lock()
# --- End New PFChatting Management ---
HeartFC_Controller._instance = self # Register instance
HeartFCController._instance = self # Register instance
# --- End Updated Init ---
# --- Make dependencies accessible for PFChatting ---
# These are accessed via the passed instance in PFChatting
@@ -58,7 +58,7 @@ class HeartFC_Controller:
def get_instance(cls):
if cls._instance is None:
# This might indicate an issue if called before initialization
logger.warning("HeartFC_Controller get_instance called before initialization.")
logger.warning("HeartFCController get_instance called before initialization.")
# Optionally, initialize here if a strict singleton pattern is desired
# cls._instance = cls()
return cls._instance
@@ -67,9 +67,9 @@ class HeartFC_Controller:
async def start(self):
"""启动异步任务,如回复启动器"""
logger.debug("HeartFC_Controller 正在启动异步任务...")
logger.debug("HeartFCController 正在启动异步任务...")
self._initialize_monitor_task()
logger.info("HeartFC_Controller 异步任务启动完成")
logger.info("HeartFCController 异步任务启动完成")
def _initialize_monitor_task(self):
"""启动后台兴趣监控任务,可以检查兴趣是否足以开启心流对话"""
@@ -89,7 +89,7 @@ class HeartFC_Controller:
async with self._pf_chatting_lock:
if stream_id not in self.pf_chatting_instances:
logger.info(f"为流 {stream_id} 创建新的PFChatting实例")
# 传递 self (HeartFC_Controller 实例) 进行依赖注入
# 传递 self (HeartFCController 实例) 进行依赖注入
instance = PFChatting(stream_id, self)
# 执行异步初始化
if not await instance._initialize():

View File

@@ -25,7 +25,7 @@ logger = get_module_logger("heartFC_processor", config=processor_config)
# INTEREST_INCREASE_THRESHOLD = 0.5
class HeartFC_Processor:
class HeartFCProcessor:
def __init__(self):
self.storage = MessageStorage()
self.interest_manager = InterestManager()
@@ -97,21 +97,21 @@ class HeartFC_Processor:
# 处理缓冲器结果 (Bombing logic)
if not buffer_result:
F_type = "seglist"
f_type = "seglist"
if message.message_segment.type != "seglist":
F_type = message.message_segment.type
f_type = message.message_segment.type
else:
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
):
F_type = message.message_segment.data[0].type
if F_type == "text":
f_type = message.message_segment.data[0].type
if f_type == "text":
logger.debug(f"触发缓冲,消息:{message.processed_plain_text}")
elif F_type == "image":
elif f_type == "image":
logger.debug("触发缓冲,表情包/图片等待中")
elif F_type == "seglist":
elif f_type == "seglist":
logger.debug("触发缓冲,消息列表等待中")
return # 被缓冲器拦截,不生成回复

View File

@@ -25,7 +25,7 @@ logger = get_module_logger("PFCLoop", config=interest_log_config) # Logger Name
# Forward declaration for type hinting
if TYPE_CHECKING:
from .heartFC_controler import HeartFC_Controller
from .heartFC_controler import HeartFCController
PLANNER_TOOL_DEFINITION = [
{
@@ -61,7 +61,7 @@ class PFChatting:
只要计时器>0循环就会继续。
"""
def __init__(self, chat_id: str, heartfc_controller_instance: "HeartFC_Controller"):
def __init__(self, chat_id: str, heartfc_controller_instance: "HeartFCController"):
"""
初始化PFChatting实例。
@@ -374,6 +374,22 @@ class PFChatting:
)
action_taken_this_cycle = False
# --- Print Timer Results --- #
if cycle_timers: # 先检查cycle_timers是否非空
timer_strings = []
for name, elapsed in cycle_timers.items():
# 直接格式化存储在字典中的浮点数 elapsed
formatted_time = f"{elapsed * 1000:.2f}毫秒" if elapsed < 1 else f"{elapsed:.2f}"
timer_strings.append(f"{name}: {formatted_time}")
if timer_strings: # 如果有有效计时器数据才打印
logger.debug(
f"{log_prefix} test testtesttesttesttesttesttesttesttesttest Cycle Timers: {'; '.join(timer_strings)}"
)
# --- Timer Decrement --- #
cycle_duration = time.monotonic() - loop_cycle_start_time
except Exception as e_cycle:
logger.error(f"{log_prefix} 循环周期执行时发生错误: {e_cycle}")
logger.error(traceback.format_exc())
@@ -387,21 +403,6 @@ class PFChatting:
self._processing_lock.release()
logger.trace(f"{log_prefix} 循环释放了处理锁.")
# --- Print Timer Results --- #
if cycle_timers: # 先检查cycle_timers是否非空
timer_strings = []
for name, elapsed in cycle_timers.items():
# 直接格式化存储在字典中的浮点数 elapsed
formatted_time = f"{elapsed * 1000:.2f}毫秒" if elapsed < 1 else f"{elapsed:.2f}"
timer_strings.append(f"{name}: {formatted_time}")
if timer_strings: # 如果有有效计时器数据才打印
logger.debug(
f"{log_prefix} test testtesttesttesttesttesttesttesttesttest Cycle Timers: {'; '.join(timer_strings)}"
)
# --- Timer Decrement --- #
cycle_duration = time.monotonic() - loop_cycle_start_time
async with self._timer_lock:
self._loop_timer -= cycle_duration
# Log timer decrement less aggressively
@@ -771,7 +772,7 @@ class PFChatting:
logger.error(traceback.format_exc())
return None
# --- Methods moved from HeartFC_Controller start ---
# --- Methods moved from HeartFCController start ---
async def _create_thinking_message(self, anchor_message: Optional[MessageRecv]) -> Optional[str]:
"""创建思考消息 (尝试锚定到 anchor_message)"""
if not anchor_message or not anchor_message.chat_stream:

View File

@@ -1,25 +1,26 @@
import time
from random import random
import traceback
from typing import List
from ...memory_system.Hippocampus import HippocampusManager
from ...moods.moods import MoodManager
from ....config.config import global_config
from ...chat.emoji_manager import emoji_manager
from random import random
from typing import List, Optional
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
from .reasoning_generator import ResponseGenerator
from ...chat.chat_stream import chat_manager
from ...chat.emoji_manager import emoji_manager
from ...chat.message import MessageSending, MessageRecv, MessageThinking, MessageSet
from ...chat.message_buffer import message_buffer
from ...chat.messagesender import message_manager
from ...storage.storage import MessageStorage
from ...chat.utils import is_mentioned_bot_in_message
from ...chat.utils_image import image_path_to_base64
from ...willing.willing_manager import willing_manager
from ...memory_system.Hippocampus import HippocampusManager
from ...message import UserInfo, Seg
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
from ...chat.chat_stream import chat_manager
from ...moods.moods import MoodManager
from ...person_info.relationship_manager import relationship_manager
from ...chat.message_buffer import message_buffer
from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
from ...storage.storage import MessageStorage
from ...utils.timer_calculater import Timer
from ...willing.willing_manager import willing_manager
from ....config.config import global_config
# 定义日志配置
chat_config = LogConfig(
@@ -61,7 +62,7 @@ class ReasoningChat:
return thinking_id
@staticmethod
async def _send_response_messages(message, chat, response_set: List[str], thinking_id) -> MessageSending:
async def _send_response_messages(message, chat, response_set: List[str], thinking_id) -> Optional[MessageSending]:
"""发送回复消息"""
container = message_manager.get_container(chat.stream_id)
thinking_message = None
@@ -74,7 +75,7 @@ class ReasoningChat:
if not thinking_message:
logger.warning("未找到对应的思考消息,可能已超时被移除")
return
return None
thinking_start_time = thinking_message.thinking_start_time
message_set = MessageSet(chat, thinking_id)

View File

@@ -12,7 +12,6 @@ class Seg:
- 对于 text 类型data 是字符串
- 对于 image 类型data 是 base64 字符串
- 对于 seglist 类型data 是 Seg 列表
translated_data: 经过翻译处理的数据(可选)
"""
type: str

View File

@@ -169,7 +169,7 @@ class PersonInfoManager:
"""给某个用户取名"""
if not person_id:
logger.debug("取名失败person_id不能为空")
return
return None
old_name = await self.get_value(person_id, "person_name")
old_reason = await self.get_value(person_id, "name_reason")

View File

@@ -134,3 +134,4 @@ def main():
heartbeat_thread.start()
return heartbeat_thread # 返回线程对象,便于外部控制
return None

View File

@@ -29,8 +29,18 @@ CHAT_ANY_WHERE_KEY=
SILICONFLOW_KEY=
# 定义日志相关配置
SIMPLE_OUTPUT=true # 精简控制台输出格式
CONSOLE_LOG_LEVEL=INFO # 自定义日志的默认控制台输出日志级别
FILE_LOG_LEVEL=DEBUG # 自定义日志的默认文件输出日志级别
DEFAULT_CONSOLE_LOG_LEVEL=SUCCESS # 原生日志的控制台输出日志级别nonebot就是这一类
DEFAULT_FILE_LOG_LEVEL=DEBUG # 原生日志的默认文件输出日志级别nonebot就是这一类
# 精简控制台输出格式
SIMPLE_OUTPUT=true
# 自定义日志的默认控制台输出日志级别
CONSOLE_LOG_LEVEL=INFO
# 自定义日志的默认文件输出日志级别
FILE_LOG_LEVEL=DEBUG
# 原生日志的控制台输出日志级别nonebot就是这一类
DEFAULT_CONSOLE_LOG_LEVEL=SUCCESS
# 原生日志的默认文件输出日志级别nonebot就是这一类
DEFAULT_FILE_LOG_LEVEL=DEBUG