fix:拯救大兵ruff 2
This commit is contained in:
@@ -4,6 +4,7 @@ import time
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
from src.common.logger import get_module_logger
|
||||
|
||||
# from ...common.database import db # 数据库依赖似乎不需要了,注释掉
|
||||
from ..message.api import global_api
|
||||
from .message import MessageSending, MessageThinking, MessageSet
|
||||
@@ -75,7 +76,7 @@ class MessageSender:
|
||||
await self.send_via_ws(message)
|
||||
else:
|
||||
await self.send_via_ws(message)
|
||||
logger.success(f"发送消息 '{message_preview}' 成功") # 调整日志格式
|
||||
logger.success(f"发送消息 '{message_preview}' 成功") # 调整日志格式
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息 '{message_preview}' 失败: {str(e)}")
|
||||
|
||||
@@ -86,7 +87,7 @@ class MessageContainer:
|
||||
def __init__(self, chat_id: str, max_size: int = 100):
|
||||
self.chat_id = chat_id
|
||||
self.max_size = max_size
|
||||
self.messages: List[Union[MessageThinking, MessageSending]] = [] # 明确类型
|
||||
self.messages: List[Union[MessageThinking, MessageSending]] = [] # 明确类型
|
||||
self.last_send_time = 0
|
||||
self.thinking_wait_timeout = 20 # 思考等待超时时间(秒) - 从旧 sender 合并
|
||||
|
||||
@@ -118,7 +119,7 @@ class MessageContainer:
|
||||
earliest_message = None
|
||||
for msg in self.messages:
|
||||
# 确保消息有 thinking_start_time 属性
|
||||
msg_time = getattr(msg, 'thinking_start_time', float('inf'))
|
||||
msg_time = getattr(msg, "thinking_start_time", float("inf"))
|
||||
if msg_time < earliest_time:
|
||||
earliest_time = msg_time
|
||||
earliest_message = msg
|
||||
@@ -156,7 +157,7 @@ class MessageContainer:
|
||||
|
||||
def get_all_messages(self) -> List[Union[MessageSending, MessageThinking]]:
|
||||
"""获取所有消息"""
|
||||
return list(self.messages) # 返回副本
|
||||
return list(self.messages) # 返回副本
|
||||
|
||||
|
||||
class MessageManager:
|
||||
@@ -164,29 +165,28 @@ class MessageManager:
|
||||
|
||||
def __init__(self):
|
||||
self.containers: Dict[str, MessageContainer] = {}
|
||||
self.storage = MessageStorage() # 添加 storage 实例
|
||||
self._running = True # 处理器运行状态
|
||||
self._container_lock = asyncio.Lock() # 保护 containers 字典的锁
|
||||
self.storage = MessageStorage() # 添加 storage 实例
|
||||
self._running = True # 处理器运行状态
|
||||
self._container_lock = asyncio.Lock() # 保护 containers 字典的锁
|
||||
# self.message_sender = MessageSender() # 创建发送器实例 (改为全局实例)
|
||||
|
||||
async def start(self):
|
||||
"""启动后台处理器任务。"""
|
||||
# 检查是否已有任务在运行,避免重复启动
|
||||
if hasattr(self, '_processor_task') and not self._processor_task.done():
|
||||
logger.warning("Processor task already running.")
|
||||
return
|
||||
if hasattr(self, "_processor_task") and not self._processor_task.done():
|
||||
logger.warning("Processor task already running.")
|
||||
return
|
||||
self._processor_task = asyncio.create_task(self._start_processor_loop())
|
||||
logger.info("MessageManager processor task started.")
|
||||
|
||||
def stop(self):
|
||||
"""停止后台处理器任务。"""
|
||||
self._running = False
|
||||
if hasattr(self, '_processor_task') and not self._processor_task.done():
|
||||
self._processor_task.cancel()
|
||||
logger.info("MessageManager processor task stopping.")
|
||||
else:
|
||||
logger.info("MessageManager processor task not running or already stopped.")
|
||||
|
||||
"""停止后台处理器任务。"""
|
||||
self._running = False
|
||||
if hasattr(self, "_processor_task") and not self._processor_task.done():
|
||||
self._processor_task.cancel()
|
||||
logger.info("MessageManager processor task stopping.")
|
||||
else:
|
||||
logger.info("MessageManager processor task not running or already stopped.")
|
||||
|
||||
async def get_container(self, chat_id: str) -> MessageContainer:
|
||||
"""获取或创建聊天流的消息容器 (异步,使用锁)"""
|
||||
@@ -200,18 +200,18 @@ class MessageManager:
|
||||
chat_stream = message.chat_stream
|
||||
if not chat_stream:
|
||||
logger.error("消息缺少 chat_stream,无法添加到容器")
|
||||
return # 或者抛出异常
|
||||
return # 或者抛出异常
|
||||
container = await self.get_container(chat_stream.stream_id)
|
||||
container.add_message(message)
|
||||
|
||||
def check_if_sending_message_exist(self, chat_id, thinking_id):
|
||||
"""检查指定聊天流的容器中是否存在具有特定 thinking_id 的 MessageSending 消息 或 emoji 消息"""
|
||||
# 这个方法现在是非异步的,因为它只读取数据
|
||||
container = self.containers.get(chat_id) # 直接 get,因为读取不需要锁
|
||||
container = self.containers.get(chat_id) # 直接 get,因为读取不需要锁
|
||||
if container and container.has_messages():
|
||||
for message in container.get_all_messages():
|
||||
if isinstance(message, MessageSending):
|
||||
msg_id = getattr(message.message_info, 'message_id', None)
|
||||
msg_id = getattr(message.message_info, "message_id", None)
|
||||
# 检查 message_id 是否匹配 thinking_id 或以 "me" 开头 (emoji)
|
||||
if msg_id == thinking_id or (msg_id and msg_id.startswith("me")):
|
||||
# logger.debug(f"检查到存在相同thinking_id或emoji的消息: {msg_id} for {thinking_id}")
|
||||
@@ -221,7 +221,7 @@ class MessageManager:
|
||||
async def _handle_sending_message(self, container: MessageContainer, message: MessageSending):
|
||||
"""处理单个 MessageSending 消息 (包含 set_reply 逻辑)"""
|
||||
try:
|
||||
_ = message.update_thinking_time() # 更新思考时间
|
||||
_ = message.update_thinking_time() # 更新思考时间
|
||||
thinking_start_time = message.thinking_start_time
|
||||
now_time = time.time()
|
||||
thinking_messages_count, thinking_messages_length = count_messages_between(
|
||||
@@ -230,16 +230,18 @@ class MessageManager:
|
||||
|
||||
# --- 条件应用 set_reply 逻辑 ---
|
||||
if (
|
||||
message.apply_set_reply_logic # 检查标记
|
||||
message.apply_set_reply_logic # 检查标记
|
||||
and message.is_head
|
||||
and (thinking_messages_count > 4 or thinking_messages_length > 250)
|
||||
and not message.is_private_message()
|
||||
):
|
||||
logger.debug(f"[{message.chat_stream.stream_id}] 应用 set_reply 逻辑: {message.processed_plain_text[:20]}...")
|
||||
logger.debug(
|
||||
f"[{message.chat_stream.stream_id}] 应用 set_reply 逻辑: {message.processed_plain_text[:20]}..."
|
||||
)
|
||||
message.set_reply()
|
||||
# --- 结束条件 set_reply ---
|
||||
|
||||
await message.process() # 预处理消息内容
|
||||
await message.process() # 预处理消息内容
|
||||
|
||||
# 使用全局 message_sender 实例
|
||||
await message_sender.send_message(message)
|
||||
@@ -250,22 +252,23 @@ class MessageManager:
|
||||
# logger.debug(f"[{message.chat_stream.stream_id}] Sent and removed message: {message.message_info.message_id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{message.chat_stream.stream_id}] 处理发送消息 {getattr(message.message_info, 'message_id', 'N/A')} 时出错: {e}")
|
||||
logger.error(
|
||||
f"[{message.chat_stream.stream_id}] 处理发送消息 {getattr(message.message_info, 'message_id', 'N/A')} 时出错: {e}"
|
||||
)
|
||||
logger.exception("详细错误信息:")
|
||||
# 考虑是否移除出错的消息,防止无限循环
|
||||
removed = container.remove_message(message)
|
||||
if removed:
|
||||
logger.warning(f"[{message.chat_stream.stream_id}] 已移除处理出错的消息。")
|
||||
|
||||
logger.warning(f"[{message.chat_stream.stream_id}] 已移除处理出错的消息。")
|
||||
|
||||
async def _process_chat_messages(self, chat_id: str):
|
||||
"""处理单个聊天流消息 (合并后的逻辑)"""
|
||||
container = await self.get_container(chat_id) # 获取容器是异步的了
|
||||
container = await self.get_container(chat_id) # 获取容器是异步的了
|
||||
|
||||
if container.has_messages():
|
||||
message_earliest = container.get_earliest_message()
|
||||
|
||||
if not message_earliest: # 如果最早消息为空,则退出
|
||||
if not message_earliest: # 如果最早消息为空,则退出
|
||||
return
|
||||
|
||||
if isinstance(message_earliest, MessageThinking):
|
||||
@@ -273,7 +276,7 @@ class MessageManager:
|
||||
message_earliest.update_thinking_time()
|
||||
thinking_time = message_earliest.thinking_time
|
||||
# 减少控制台刷新频率或只在时间显著变化时打印
|
||||
if int(thinking_time) % 5 == 0: # 每5秒打印一次
|
||||
if int(thinking_time) % 5 == 0: # 每5秒打印一次
|
||||
print(
|
||||
f"消息 {message_earliest.message_info.message_id} 正在思考中,已思考 {int(thinking_time)} 秒\r",
|
||||
end="",
|
||||
@@ -282,9 +285,11 @@ class MessageManager:
|
||||
|
||||
# 检查是否超时
|
||||
if thinking_time > global_config.thinking_timeout:
|
||||
logger.warning(f"[{chat_id}] 消息思考超时 ({thinking_time:.1f}秒),移除消息 {message_earliest.message_info.message_id}")
|
||||
logger.warning(
|
||||
f"[{chat_id}] 消息思考超时 ({thinking_time:.1f}秒),移除消息 {message_earliest.message_info.message_id}"
|
||||
)
|
||||
container.remove_message(message_earliest)
|
||||
print() # 超时后换行,避免覆盖下一条日志
|
||||
print() # 超时后换行,避免覆盖下一条日志
|
||||
|
||||
elif isinstance(message_earliest, MessageSending):
|
||||
# --- 处理发送消息 ---
|
||||
@@ -300,7 +305,7 @@ class MessageManager:
|
||||
if msg is message_earliest:
|
||||
continue
|
||||
logger.info(f"[{chat_id}] 处理超时发送消息: {msg.message_info.message_id}")
|
||||
await self._handle_sending_message(container, msg) # 复用处理逻辑
|
||||
await self._handle_sending_message(container, msg) # 复用处理逻辑
|
||||
|
||||
# 清理空容器 (可选)
|
||||
# async with self._container_lock:
|
||||
@@ -308,7 +313,6 @@ class MessageManager:
|
||||
# logger.debug(f"[{chat_id}] 容器已空,准备移除。")
|
||||
# del self.containers[chat_id]
|
||||
|
||||
|
||||
async def _start_processor_loop(self):
|
||||
"""消息处理器主循环"""
|
||||
while self._running:
|
||||
@@ -319,8 +323,8 @@ class MessageManager:
|
||||
chat_ids = list(self.containers.keys())
|
||||
|
||||
for chat_id in chat_ids:
|
||||
# 为每个 chat_id 创建一个处理任务
|
||||
tasks.append(asyncio.create_task(self._process_chat_messages(chat_id)))
|
||||
# 为每个 chat_id 创建一个处理任务
|
||||
tasks.append(asyncio.create_task(self._process_chat_messages(chat_id)))
|
||||
|
||||
if tasks:
|
||||
try:
|
||||
@@ -331,13 +335,14 @@ class MessageManager:
|
||||
|
||||
# 等待一小段时间,避免CPU空转
|
||||
try:
|
||||
await asyncio.sleep(0.1) # 稍微降低轮询频率
|
||||
await asyncio.sleep(0.1) # 稍微降低轮询频率
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Processor loop sleep cancelled.")
|
||||
break # 退出循环
|
||||
logger.info("Processor loop sleep cancelled.")
|
||||
break # 退出循环
|
||||
logger.info("MessageManager processor loop finished.")
|
||||
|
||||
|
||||
# --- 创建全局实例 ---
|
||||
message_manager = MessageManager()
|
||||
message_sender = MessageSender()
|
||||
# --- 结束全局实例 ---
|
||||
# --- 结束全局实例 ---
|
||||
|
||||
@@ -13,11 +13,12 @@ from src.plugins.models.utils_model import LLMRequest
|
||||
from src.config.config import global_config
|
||||
from src.plugins.chat.utils_image import image_path_to_base64 # Local import needed after move
|
||||
from src.plugins.utils.timer_calculater import Timer # <--- Import Timer
|
||||
|
||||
# --- Import necessary dependencies directly ---
|
||||
from .heartFC_generator import ResponseGenerator # Assuming this is the type for gpt
|
||||
from .heartFC_generator import ResponseGenerator # Assuming this is the type for gpt
|
||||
from src.do_tool.tool_use import ToolUser
|
||||
from src.plugins.chat.emoji_manager import EmojiManager # Assuming this is the type
|
||||
from ..chat.message_sender import message_manager # <-- Import the global manager
|
||||
from src.plugins.chat.emoji_manager import EmojiManager # Assuming this is the type
|
||||
from ..chat.message_sender import message_manager # <-- Import the global manager
|
||||
# --- End import ---
|
||||
|
||||
|
||||
@@ -37,7 +38,7 @@ if TYPE_CHECKING:
|
||||
# Keep this if HeartFCController methods are still needed elsewhere,
|
||||
# but the instance variable will be removed from HeartFChatting
|
||||
# from .heartFC_controler import HeartFCController
|
||||
from src.heart_flow.heartflow import SubHeartflow, heartflow # <-- 同时导入 heartflow 实例用于类型检查
|
||||
from src.heart_flow.heartflow import SubHeartflow, heartflow # <-- 同时导入 heartflow 实例用于类型检查
|
||||
|
||||
PLANNER_TOOL_DEFINITION = [
|
||||
{
|
||||
@@ -74,16 +75,17 @@ class HeartFChatting:
|
||||
现在由其关联的 SubHeartflow 管理生命周期。
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
chat_id: str,
|
||||
# 显式依赖注入
|
||||
gpt_instance: ResponseGenerator, # 文本回复生成器
|
||||
tool_user_instance: ToolUser, # 工具使用实例
|
||||
emoji_manager_instance: EmojiManager, # 表情管理实例
|
||||
):
|
||||
def __init__(
|
||||
self,
|
||||
chat_id: str,
|
||||
# 显式依赖注入
|
||||
gpt_instance: ResponseGenerator, # 文本回复生成器
|
||||
tool_user_instance: ToolUser, # 工具使用实例
|
||||
emoji_manager_instance: EmojiManager, # 表情管理实例
|
||||
):
|
||||
"""
|
||||
HeartFChatting 初始化函数
|
||||
|
||||
|
||||
参数:
|
||||
chat_id: 聊天流唯一标识符(如stream_id)
|
||||
gpt_instance: 文本回复生成器实例
|
||||
@@ -94,7 +96,7 @@ class HeartFChatting:
|
||||
self.stream_id: str = chat_id # 聊天流ID
|
||||
self.chat_stream: Optional[ChatStream] = None # 关联的聊天流
|
||||
self.sub_hf: Optional[SubHeartflow] = None # 关联的子心流
|
||||
|
||||
|
||||
# 初始化状态控制
|
||||
self._initialized = False # 是否已初始化标志
|
||||
self._init_lock = asyncio.Lock() # 初始化锁(确保只初始化一次)
|
||||
@@ -145,6 +147,7 @@ class HeartFChatting:
|
||||
|
||||
# <-- 在这里导入 heartflow 实例
|
||||
from src.heart_flow.heartflow import heartflow
|
||||
|
||||
self.sub_hf = heartflow.get_subheartflow(self.stream_id)
|
||||
if not self.sub_hf:
|
||||
logger.warning(f"{log_prefix} 获取SubHeartflow失败。一些功能可能受限。")
|
||||
@@ -391,7 +394,9 @@ class HeartFChatting:
|
||||
logger.info(f"{log_prefix} 等待新消息的 sleep 被中断。")
|
||||
raise # 重新抛出取消错误,以便外层循环处理
|
||||
else:
|
||||
logger.warning(f"{log_prefix} HeartFChatting: 无法获取 Observation 实例,无法等待新消息。")
|
||||
logger.warning(
|
||||
f"{log_prefix} HeartFChatting: 无法获取 Observation 实例,无法等待新消息。"
|
||||
)
|
||||
# --- 等待结束 ---
|
||||
|
||||
elif action == "error": # Action specifically set to error by planner
|
||||
@@ -413,9 +418,7 @@ class HeartFChatting:
|
||||
timer_strings.append(f"{name}: {formatted_time}")
|
||||
|
||||
if timer_strings: # 如果有有效计时器数据才打印
|
||||
logger.debug(
|
||||
f"{log_prefix} 该次决策耗时: {'; '.join(timer_strings)}"
|
||||
)
|
||||
logger.debug(f"{log_prefix} 该次决策耗时: {'; '.join(timer_strings)}")
|
||||
|
||||
# --- Timer Decrement --- #
|
||||
cycle_duration = time.monotonic() - loop_cycle_start_time
|
||||
@@ -484,8 +487,12 @@ class HeartFChatting:
|
||||
self.sub_hf = heartflow.get_subheartflow(self.stream_id)
|
||||
if not self.sub_hf:
|
||||
logger.error(f"{log_prefix}[Planner] SubHeartflow is not available. Cannot proceed.")
|
||||
return {"action": "error", "reasoning": "SubHeartflow unavailable", "llm_error": True, "observed_messages": []}
|
||||
|
||||
return {
|
||||
"action": "error",
|
||||
"reasoning": "SubHeartflow unavailable",
|
||||
"llm_error": True,
|
||||
"observed_messages": [],
|
||||
}
|
||||
|
||||
try:
|
||||
# Access observation via self.sub_hf
|
||||
@@ -503,9 +510,7 @@ class HeartFChatting:
|
||||
# --- (Moved from _replier_work) 1. 思考前使用工具 --- #
|
||||
try:
|
||||
# Access tool_user directly
|
||||
tool_result = await self.tool_user.use_tool(
|
||||
message_txt=observed_messages_str, sub_heartflow=self.sub_hf
|
||||
)
|
||||
tool_result = await self.tool_user.use_tool(message_txt=observed_messages_str, sub_heartflow=self.sub_hf)
|
||||
if tool_result.get("used_tools", False):
|
||||
tool_result_info = tool_result.get("structured_info", {})
|
||||
logger.debug(f"{log_prefix}[Planner] 规划前工具结果: {tool_result_info}")
|
||||
@@ -620,7 +625,6 @@ class HeartFChatting:
|
||||
"""
|
||||
|
||||
try:
|
||||
|
||||
# --- Create Placeholder --- #
|
||||
placeholder_id = f"mid_pf_{int(time.time() * 1000)}"
|
||||
placeholder_user = UserInfo(
|
||||
|
||||
@@ -11,6 +11,7 @@ from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
|
||||
from ..utils.timer_calculater import Timer
|
||||
|
||||
from src.plugins.moods.moods import MoodManager
|
||||
|
||||
# 定义日志配置
|
||||
llm_config = LogConfig(
|
||||
# 使用消息发送专用样式
|
||||
@@ -78,7 +79,6 @@ class ResponseGenerator:
|
||||
|
||||
sender_name = f"<{message.chat_stream.user_info.platform}:{message.chat_stream.user_info.user_id}:{message.chat_stream.user_info.user_nickname}:{message.chat_stream.user_info.user_cardname}>"
|
||||
|
||||
|
||||
with Timer() as t_build_prompt:
|
||||
prompt = await prompt_builder.build_prompt(
|
||||
build_mode="focus",
|
||||
@@ -86,7 +86,7 @@ class ResponseGenerator:
|
||||
current_mind_info=current_mind_info,
|
||||
message_txt=message.processed_plain_text,
|
||||
sender_name=sender_name,
|
||||
chat_stream=message.chat_stream
|
||||
chat_stream=message.chat_stream,
|
||||
)
|
||||
logger.info(f"构建prompt时间: {t_build_prompt.human_readable}")
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ def init_prompt():
|
||||
涉及政治敏感以及违法违规的内容请规避。""",
|
||||
"moderation_prompt",
|
||||
)
|
||||
|
||||
|
||||
Prompt(
|
||||
"""
|
||||
{relation_prompt_all}
|
||||
@@ -77,23 +77,18 @@ class PromptBuilder:
|
||||
self.prompt_built = ""
|
||||
self.activate_messages = ""
|
||||
|
||||
|
||||
async def build_prompt(
|
||||
self, build_mode,reason,current_mind_info, message_txt: str, sender_name: str = "某人",chat_stream=None
|
||||
self, build_mode, reason, current_mind_info, message_txt: str, sender_name: str = "某人", chat_stream=None
|
||||
) -> tuple[str, str]:
|
||||
|
||||
if build_mode == "normal":
|
||||
return await self._build_prompt_normal(chat_stream, message_txt, sender_name)
|
||||
|
||||
|
||||
elif build_mode == "focus":
|
||||
return await self._build_prompt_focus(reason, current_mind_info, chat_stream, message_txt, sender_name)
|
||||
|
||||
|
||||
|
||||
async def _build_prompt_focus(
|
||||
self, reason, current_mind_info, chat_stream, message_txt: str, sender_name: str = "某人"
|
||||
) -> tuple[str, str]:
|
||||
|
||||
individuality = Individuality.get_instance()
|
||||
prompt_personality = individuality.get_prompt(type="personality", x_person=2, level=1)
|
||||
prompt_identity = individuality.get_prompt(type="identity", x_person=2, level=1)
|
||||
@@ -104,14 +99,14 @@ class PromptBuilder:
|
||||
if chat_stream.group_info:
|
||||
chat_in_group = True
|
||||
else:
|
||||
chat_in_group = False
|
||||
|
||||
chat_in_group = False
|
||||
|
||||
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
|
||||
chat_id =chat_stream.stream_id,
|
||||
timestamp = time.time(),
|
||||
chat_id=chat_stream.stream_id,
|
||||
timestamp=time.time(),
|
||||
limit=global_config.MAX_CONTEXT_SIZE,
|
||||
)
|
||||
|
||||
|
||||
chat_talking_prompt = await build_readable_messages(
|
||||
message_list_before_now,
|
||||
replace_bot_name=True,
|
||||
@@ -147,7 +142,6 @@ class PromptBuilder:
|
||||
if random.random() < 0.02:
|
||||
prompt_ger += "你喜欢用反问句"
|
||||
|
||||
|
||||
logger.debug("开始构建prompt")
|
||||
|
||||
prompt = await global_prompt_manager.format_prompt(
|
||||
@@ -176,11 +170,7 @@ class PromptBuilder:
|
||||
|
||||
return prompt
|
||||
|
||||
|
||||
|
||||
async def _build_prompt_normal(
|
||||
self, chat_stream, message_txt: str, sender_name: str = "某人"
|
||||
) -> tuple[str, str]:
|
||||
async def _build_prompt_normal(self, chat_stream, message_txt: str, sender_name: str = "某人") -> tuple[str, str]:
|
||||
# 开始构建prompt
|
||||
prompt_personality = "你"
|
||||
# person
|
||||
@@ -245,14 +235,14 @@ class PromptBuilder:
|
||||
if chat_stream.group_info:
|
||||
chat_in_group = True
|
||||
else:
|
||||
chat_in_group = False
|
||||
|
||||
chat_in_group = False
|
||||
|
||||
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
|
||||
chat_id =chat_stream.stream_id,
|
||||
timestamp = time.time(),
|
||||
chat_id=chat_stream.stream_id,
|
||||
timestamp=time.time(),
|
||||
limit=global_config.MAX_CONTEXT_SIZE,
|
||||
)
|
||||
|
||||
|
||||
chat_talking_prompt = await build_readable_messages(
|
||||
message_list_before_now,
|
||||
replace_bot_name=True,
|
||||
@@ -260,9 +250,7 @@ class PromptBuilder:
|
||||
timestamp_mode="relative",
|
||||
read_mark=0.0,
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
# 关键词检测与反应
|
||||
keywords_reaction_prompt = ""
|
||||
for rule in global_config.keywords_reaction_rules:
|
||||
@@ -303,11 +291,11 @@ class PromptBuilder:
|
||||
logger.debug(f"知识检索耗时: {(end_time - start_time):.3f}秒")
|
||||
|
||||
logger.debug("开始构建prompt")
|
||||
|
||||
schedule_prompt=await global_prompt_manager.format_prompt(
|
||||
|
||||
schedule_prompt = await global_prompt_manager.format_prompt(
|
||||
"schedule_prompt", schedule_info=bot_schedule.get_current_num_task(num=1, time_info=False)
|
||||
)
|
||||
|
||||
|
||||
prompt = await global_prompt_manager.format_prompt(
|
||||
"reasoning_prompt_main",
|
||||
relation_prompt_all=await global_prompt_manager.get_prompt_async("relationship_prompt"),
|
||||
@@ -558,6 +546,5 @@ class PromptBuilder:
|
||||
return "\n".join(str(result["content"]) for result in results)
|
||||
|
||||
|
||||
|
||||
init_prompt()
|
||||
prompt_builder = PromptBuilder()
|
||||
|
||||
@@ -22,6 +22,7 @@ from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
|
||||
from src.plugins.utils.timer_calculater import Timer
|
||||
from src.heart_flow.heartflow import heartflow
|
||||
from src.heart_flow.sub_heartflow import ChatState
|
||||
|
||||
# 定义日志配置
|
||||
chat_config = LogConfig(
|
||||
console_format=CHAT_STYLE_CONFIG["console_format"],
|
||||
@@ -129,7 +130,7 @@ class NormalChat:
|
||||
is_head=not mark_head,
|
||||
is_emoji=False,
|
||||
thinking_start_time=thinking_start_time,
|
||||
apply_set_reply_logic=True
|
||||
apply_set_reply_logic=True,
|
||||
)
|
||||
if not mark_head:
|
||||
mark_head = True
|
||||
@@ -165,7 +166,7 @@ class NormalChat:
|
||||
reply=message,
|
||||
is_head=False,
|
||||
is_emoji=True,
|
||||
apply_set_reply_logic=True
|
||||
apply_set_reply_logic=True,
|
||||
)
|
||||
await message_manager.add_message(bot_message)
|
||||
|
||||
@@ -212,13 +213,13 @@ class NormalChat:
|
||||
if removed_item:
|
||||
# logger.debug(f"[{stream_name}] 已从兴趣字典中移除消息 {msg_id} (因状态跳过)") # 减少日志
|
||||
pass
|
||||
continue # 处理下一条消息
|
||||
continue # 处理下一条消息
|
||||
# --- 结束状态检查 --- #
|
||||
|
||||
# --- 检查 HeartFChatting 是否活跃 (改为检查 SubHeartflow 状态) --- #
|
||||
is_focused = subheartflow.chat_state.chat_status == ChatState.FOCUSED
|
||||
|
||||
if is_focused: # New check: If the subflow is focused, NormalChat shouldn't process
|
||||
if is_focused: # New check: If the subflow is focused, NormalChat shouldn't process
|
||||
removed_item = interest_dict.pop(msg_id, None)
|
||||
if removed_item:
|
||||
# logger.debug(f"[{stream_name}] SubHeartflow 处于 FOCUSED 状态,已跳过并移除 NormalChat 兴趣消息 {msg_id}") # Reduce noise
|
||||
@@ -264,7 +265,7 @@ class NormalChat:
|
||||
)
|
||||
# 可以在这里添加 not_reply_handle 逻辑吗? 如果不回复,也需要清理意愿。
|
||||
# 注意:willing_manager.setup 尚未调用
|
||||
willing_manager.setup(message, chat, is_mentioned, interested_rate) # 先 setup
|
||||
willing_manager.setup(message, chat, is_mentioned, interested_rate) # 先 setup
|
||||
await willing_manager.not_reply_handle(message.message_info.message_id)
|
||||
willing_manager.delete(message.message_info.message_id)
|
||||
return
|
||||
@@ -313,7 +314,7 @@ class NormalChat:
|
||||
|
||||
# 生成回复
|
||||
sub_hf = heartflow.get_subheartflow(stream_id)
|
||||
|
||||
|
||||
try:
|
||||
with Timer("生成回复", timing_results):
|
||||
response_set = await self.gpt.generate_response(
|
||||
|
||||
@@ -9,6 +9,7 @@ from ..utils.timer_calculater import Timer
|
||||
from src.common.logger import get_module_logger, LogConfig, LLM_STYLE_CONFIG
|
||||
from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
|
||||
from src.heart_flow.sub_heartflow import SubHeartflow
|
||||
|
||||
# 定义日志配置
|
||||
llm_config = LogConfig(
|
||||
# 使用消息发送专用样式
|
||||
@@ -40,7 +41,9 @@ class ResponseGenerator:
|
||||
self.current_model_type = "r1" # 默认使用 R1
|
||||
self.current_model_name = "unknown model"
|
||||
|
||||
async def generate_response(self, sub_hf: SubHeartflow, message: MessageThinking, thinking_id: str) -> Optional[Union[str, List[str]]]:
|
||||
async def generate_response(
|
||||
self, sub_hf: SubHeartflow, message: MessageThinking, thinking_id: str
|
||||
) -> Optional[Union[str, List[str]]]:
|
||||
"""根据当前模型类型选择对应的生成函数"""
|
||||
# 从global_config中获取模型概率值并选择模型
|
||||
if random.random() < global_config.model_reasoning_probability:
|
||||
@@ -67,7 +70,9 @@ class ResponseGenerator:
|
||||
logger.info(f"{self.current_model_type}思考,失败")
|
||||
return None
|
||||
|
||||
async def _generate_response_with_model(self, sub_hf: SubHeartflow, message: MessageThinking, model: LLMRequest, thinking_id: str):
|
||||
async def _generate_response_with_model(
|
||||
self, sub_hf: SubHeartflow, message: MessageThinking, model: LLMRequest, thinking_id: str
|
||||
):
|
||||
info_catcher = info_catcher_manager.get_info_catcher(thinking_id)
|
||||
|
||||
if message.chat_stream.user_info.user_cardname and message.chat_stream.user_info.user_nickname:
|
||||
@@ -85,7 +90,7 @@ class ResponseGenerator:
|
||||
with Timer() as t_build_prompt:
|
||||
prompt = await prompt_builder.build_prompt(
|
||||
build_mode="normal",
|
||||
reason= "",
|
||||
reason="",
|
||||
current_mind_info="",
|
||||
message_txt=message.processed_plain_text,
|
||||
sender_name=sender_name,
|
||||
@@ -95,7 +100,7 @@ class ResponseGenerator:
|
||||
|
||||
try:
|
||||
content, reasoning_content, self.current_model_name = await model.generate_response(prompt)
|
||||
|
||||
|
||||
logger.info(f"prompt:{prompt}\n生成回复:{content}")
|
||||
|
||||
info_catcher.catch_after_llm_generated(
|
||||
@@ -108,7 +113,6 @@ class ResponseGenerator:
|
||||
|
||||
return content
|
||||
|
||||
|
||||
async def _get_emotion_tags(self, content: str, processed_plain_text: str):
|
||||
"""提取情感标签,结合立场和情绪"""
|
||||
try:
|
||||
|
||||
@@ -246,7 +246,7 @@ async def _build_readable_messages_internal(
|
||||
if stripped_line.endswith("。"):
|
||||
stripped_line = stripped_line[:-1]
|
||||
output_lines.append(f"{stripped_line};")
|
||||
output_lines.append("\n") # 在每个消息块后添加换行,保持可读性
|
||||
output_lines.append("\n") # 在每个消息块后添加换行,保持可读性
|
||||
|
||||
# 移除可能的多余换行,然后合并
|
||||
formatted_string = "".join(output_lines).strip()
|
||||
@@ -314,5 +314,4 @@ async def build_readable_messages(
|
||||
return f"{read_mark_line}{formatted_after}"
|
||||
else:
|
||||
# 理论上不应该发生,但作为保险
|
||||
return read_mark_line.strip() # 如果前后都无消息,只返回标记行
|
||||
|
||||
return read_mark_line.strip() # 如果前后都无消息,只返回标记行
|
||||
|
||||
Reference in New Issue
Block a user