fix:拯救大兵ruff 2

This commit is contained in:
SengokuCola
2025-04-23 00:43:33 +08:00
parent f2c50d2cd4
commit e2d882ec82
11 changed files with 235 additions and 193 deletions

View File

@@ -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(

View File

@@ -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}")

View File

@@ -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()

View File

@@ -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(

View File

@@ -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: