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

This commit is contained in:
github-actions[bot]
2025-04-20 09:25:10 +00:00
parent ed21af9dba
commit 53abdabccd
5 changed files with 87 additions and 82 deletions

View File

@@ -184,9 +184,7 @@ class ChattingObservation(Observation):
try:
# 只需检查是否存在,不需要获取内容,使用 {"_id": 1} 提高效率
new_message = await asyncio.to_thread(
db.messages.find_one,
{"chat_id": self.chat_id, "time": {"$gt": timestamp}},
{"_id": 1}
db.messages.find_one, {"chat_id": self.chat_id, "time": {"$gt": timestamp}}, {"_id": 1}
)
# new_message = db.messages.find_one({"chat_id": self.chat_id, "time": {"$gt": timestamp}}, {"_id": 1}) # find_one 不是异步的
return new_message is not None

View File

@@ -43,13 +43,9 @@ def init_prompt():
prompt += "你现在{mood_info}\n"
# prompt += "你注意到{sender_name}刚刚说:{message_txt}\n"
prompt += "现在请你根据刚刚的想法继续思考,思考时可以想想如何对群聊内容进行回复,要不要对群里的话题进行回复,关注新话题,可以适当转换话题,大家正在说的话才是聊天的主题。\n"
prompt += (
"回复的要求是:平淡一些,简短一些,说中文,如果你要回复,最好只回复一个人的一个话题\n"
)
prompt += "回复的要求是:平淡一些,简短一些,说中文,如果你要回复,最好只回复一个人的一个话题\n"
prompt += "请注意不要输出多余内容(包括前后缀,冒号和引号,括号, 表情,等),不要带有括号和动作描写。不要回复自己的发言,尽量不要说你说过的话。"
prompt += (
"现在请你继续生成你在这个聊天中的想法,不要分点输出,生成内心想法,文字不要浮夸"
)
prompt += "现在请你继续生成你在这个聊天中的想法,不要分点输出,生成内心想法,文字不要浮夸"
Prompt(prompt, "sub_heartflow_prompt_before")

View File

@@ -64,6 +64,7 @@ class HeartFC_Controller:
# Optionally, initialize here if a strict singleton pattern is desired
# cls._instance = cls()
return cls._instance
# --- End Added Class Method ---
async def start(self):

View File

@@ -74,7 +74,6 @@ class MessageSender:
logger.error(f"发送消息 {message_preview} 失败: {str(e)}")
class MessageContainer:
"""单个聊天流的发送/思考消息容器"""
@@ -221,7 +220,6 @@ class MessageManager:
await asyncio.sleep(typing_time)
logger.debug(f"\n{message_earliest.processed_plain_text},{typing_time},等待输入时间结束\n")
await self.storage.store_message(message_earliest, message_earliest.chat_stream)
await MessageSender().send_message(message_earliest)

View File

@@ -3,8 +3,7 @@ import time
import traceback
from typing import List, Optional, Dict, Any, TYPE_CHECKING
import json
from src.plugins.chat.message import (MessageRecv, BaseMessageInfo, MessageThinking,
MessageSending)
from src.plugins.chat.message import MessageRecv, BaseMessageInfo, MessageThinking, MessageSending
from src.plugins.chat.message import MessageSet, Seg # Local import needed after move
from src.plugins.chat.chat_stream import ChatStream
from src.plugins.chat.message import UserInfo
@@ -219,11 +218,12 @@ class PFChatting:
else:
logger.info(f"{log_prefix} PFChatting: 11111111111111111111111111111111麦麦不发消息了开始规划")
async with self._timer_lock:
current_timer = self._loop_timer
if current_timer <= 0:
logger.info(f"{log_prefix} PFChatting: 聊太久了,麦麦打算休息一下 (计时器为 {current_timer:.1f}s)。退出PFChatting。")
logger.info(
f"{log_prefix} PFChatting: 聊太久了,麦麦打算休息一下 (计时器为 {current_timer:.1f}s)。退出PFChatting。"
)
break
# 记录循环周期开始时间,用于计时和休眠计算
@@ -287,7 +287,7 @@ class PFChatting:
thinking_id=thinking_id,
anchor_message=anchor_message,
response_set=replier_result,
send_emoji=emoji_query
send_emoji=emoji_query,
)
# logger.info(f"{log_prefix} 循环: 发送器完成成功.")
except Exception as e_sender:
@@ -460,7 +460,9 @@ class PFChatting:
tool_result_info = tool_result.get("structured_info", {})
logger.debug(f"{log_prefix}[Planner] 规划前工具结果: {tool_result_info}")
# Extract memory IDs and potential emoji query from tools
get_mid_memory_id = [mem["content"] for mem in tool_result_info.get("mid_chat_mem", []) if "content" in mem]
get_mid_memory_id = [
mem["content"] for mem in tool_result_info.get("mid_chat_mem", []) if "content" in mem
]
# send_emoji_from_tools = next((item["content"] for item in tool_result_info.get("send_emoji", []) if "content" in item), "")
# if send_emoji_from_tools:
# logger.info(f"{log_prefix}[Planner] 工具建议表情: '{send_emoji_from_tools}'")
@@ -520,7 +522,9 @@ class PFChatting:
f"{log_prefix}[Planner] LLM 决策: {action}, 理由: {reasoning}, EmojiQuery: '{emoji_query}'"
)
except json.JSONDecodeError as json_e:
logger.error(f"{log_prefix}[Planner] 解析工具参数失败: {json_e}. Args: {tool_call['function'].get('arguments')}")
logger.error(
f"{log_prefix}[Planner] 解析工具参数失败: {json_e}. Args: {tool_call['function'].get('arguments')}"
)
action = "error"
reasoning = "工具参数解析失败"
llm_error = True
@@ -530,7 +534,9 @@ class PFChatting:
reasoning = "处理工具参数时出错"
llm_error = True
else:
logger.warning(f"{log_prefix}[Planner] LLM 未按预期调用 'decide_reply_action' 工具。Tool calls: {tool_calls}")
logger.warning(
f"{log_prefix}[Planner] LLM 未按预期调用 'decide_reply_action' 工具。Tool calls: {tool_calls}"
)
action = "error"
reasoning = "LLM未调用预期工具"
llm_error = True
@@ -589,7 +595,9 @@ class PFChatting:
# logger.debug(f"{self._get_log_prefix()} 重构的锚点消息: ID={anchor_message.message_info.message_id}")
return anchor_message
except Exception as e_reconstruct:
logger.warning(f"{self._get_log_prefix()} 从观察到的消息重构 MessageRecv 失败: {e_reconstruct}. 创建占位符.")
logger.warning(
f"{self._get_log_prefix()} 从观察到的消息重构 MessageRecv 失败: {e_reconstruct}. 创建占位符."
)
# else:
# logger.warning(f"{self._get_log_prefix()} observed_messages 为空. 创建占位符锚点消息.")
@@ -613,7 +621,9 @@ class PFChatting:
}
anchor_message = MessageRecv(placeholder_msg_dict)
anchor_message.update_chat_stream(self.chat_stream)
logger.info(f"{self._get_log_prefix()} Created placeholder anchor message: ID={anchor_message.message_info.message_id}")
logger.info(
f"{self._get_log_prefix()} Created placeholder anchor message: ID={anchor_message.message_info.message_id}"
)
return anchor_message
except Exception as e:
@@ -638,7 +648,7 @@ class PFChatting:
thinking_id: str,
anchor_message: MessageRecv,
response_set: List[str],
send_emoji: str # Emoji query decided by planner or tools
send_emoji: str, # Emoji query decided by planner or tools
):
"""
发送器 (Sender): 使用本类的方法发送生成的回复。
@@ -698,7 +708,9 @@ class PFChatting:
config = self.heartfc_controller.global_config
rel_manager = self.heartfc_controller.relationship_manager
prompt = f"你的名字是 {config.BOT_NICKNAME}。是一个女大二学生正在QQ聊天正在决定是否以及如何回应当前的聊天。\n"
prompt = (
f"你的名字是 {config.BOT_NICKNAME}。是一个女大二学生正在QQ聊天正在决定是否以及如何回应当前的聊天。\n"
)
if observed_messages:
context_texts = []
@@ -706,7 +718,7 @@ class PFChatting:
sender = msg.get("message_info", {}).get("user_info", {}).get("user_nickname", "未知用户")
text = msg.get("detailed_plain_text", "")
timestamp = msg.get("time", 0)
time_str = time.strftime('%H:%M:%S', time.localtime(timestamp)) if timestamp else ""
time_str = time.strftime("%H:%M:%S", time.localtime(timestamp)) if timestamp else ""
context_texts.append(f"{sender} ({time_str}): {text}")
context_text = "\n".join(context_texts)
prompt += "观察到的最新聊天内容如下 (最近的消息在最后)\n---\n"
@@ -759,7 +771,7 @@ class PFChatting:
# Ensure generate_response has access to current_mind if it's crucial context
response_set = await gpt_instance.generate_response(
anchor_message, # Pass anchor_message positionally (matches 'message' parameter)
thinking_id # Pass thinking_id positionally
thinking_id, # Pass thinking_id positionally
)
if not response_set:
@@ -857,7 +869,6 @@ class PFChatting:
first_bot_msg = bot_message
message_set.add_message(bot_message)
self.heartfc_controller.MessageManager().add_message(message_set)
return first_bot_msg
@@ -921,4 +932,5 @@ class PFChatting:
stance=stance,
)
mood_manager_instance.update_mood_from_emotion(emotion, config.mood_intensity_factor)
# --- Methods moved from HeartFC_Controller end ---