🤖 自动格式化代码 [skip ci]
This commit is contained in:
@@ -184,9 +184,7 @@ class ChattingObservation(Observation):
|
|||||||
try:
|
try:
|
||||||
# 只需检查是否存在,不需要获取内容,使用 {"_id": 1} 提高效率
|
# 只需检查是否存在,不需要获取内容,使用 {"_id": 1} 提高效率
|
||||||
new_message = await asyncio.to_thread(
|
new_message = await asyncio.to_thread(
|
||||||
db.messages.find_one,
|
db.messages.find_one, {"chat_id": self.chat_id, "time": {"$gt": timestamp}}, {"_id": 1}
|
||||||
{"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 不是异步的
|
# new_message = db.messages.find_one({"chat_id": self.chat_id, "time": {"$gt": timestamp}}, {"_id": 1}) # find_one 不是异步的
|
||||||
return new_message is not None
|
return new_message is not None
|
||||||
|
|||||||
@@ -43,13 +43,9 @@ def init_prompt():
|
|||||||
prompt += "你现在{mood_info}\n"
|
prompt += "你现在{mood_info}\n"
|
||||||
# prompt += "你注意到{sender_name}刚刚说:{message_txt}\n"
|
# prompt += "你注意到{sender_name}刚刚说:{message_txt}\n"
|
||||||
prompt += "现在请你根据刚刚的想法继续思考,思考时可以想想如何对群聊内容进行回复,要不要对群里的话题进行回复,关注新话题,可以适当转换话题,大家正在说的话才是聊天的主题。\n"
|
prompt += "现在请你根据刚刚的想法继续思考,思考时可以想想如何对群聊内容进行回复,要不要对群里的话题进行回复,关注新话题,可以适当转换话题,大家正在说的话才是聊天的主题。\n"
|
||||||
prompt += (
|
prompt += "回复的要求是:平淡一些,简短一些,说中文,如果你要回复,最好只回复一个人的一个话题\n"
|
||||||
"回复的要求是:平淡一些,简短一些,说中文,如果你要回复,最好只回复一个人的一个话题\n"
|
|
||||||
)
|
|
||||||
prompt += "请注意不要输出多余内容(包括前后缀,冒号和引号,括号, 表情,等),不要带有括号和动作描写。不要回复自己的发言,尽量不要说你说过的话。"
|
prompt += "请注意不要输出多余内容(包括前后缀,冒号和引号,括号, 表情,等),不要带有括号和动作描写。不要回复自己的发言,尽量不要说你说过的话。"
|
||||||
prompt += (
|
prompt += "现在请你继续生成你在这个聊天中的想法,不要分点输出,生成内心想法,文字不要浮夸"
|
||||||
"现在请你继续生成你在这个聊天中的想法,不要分点输出,生成内心想法,文字不要浮夸"
|
|
||||||
)
|
|
||||||
|
|
||||||
Prompt(prompt, "sub_heartflow_prompt_before")
|
Prompt(prompt, "sub_heartflow_prompt_before")
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ class HeartFC_Controller:
|
|||||||
# Optionally, initialize here if a strict singleton pattern is desired
|
# Optionally, initialize here if a strict singleton pattern is desired
|
||||||
# cls._instance = cls()
|
# cls._instance = cls()
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
# --- End Added Class Method ---
|
# --- End Added Class Method ---
|
||||||
|
|
||||||
async def start(self):
|
async def start(self):
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ class MessageSender:
|
|||||||
logger.error(f"发送消息 {message_preview} 失败: {str(e)}")
|
logger.error(f"发送消息 {message_preview} 失败: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class MessageContainer:
|
class MessageContainer:
|
||||||
"""单个聊天流的发送/思考消息容器"""
|
"""单个聊天流的发送/思考消息容器"""
|
||||||
|
|
||||||
@@ -221,7 +220,6 @@ class MessageManager:
|
|||||||
await asyncio.sleep(typing_time)
|
await asyncio.sleep(typing_time)
|
||||||
logger.debug(f"\n{message_earliest.processed_plain_text},{typing_time},等待输入时间结束\n")
|
logger.debug(f"\n{message_earliest.processed_plain_text},{typing_time},等待输入时间结束\n")
|
||||||
|
|
||||||
|
|
||||||
await self.storage.store_message(message_earliest, message_earliest.chat_stream)
|
await self.storage.store_message(message_earliest, message_earliest.chat_stream)
|
||||||
|
|
||||||
await MessageSender().send_message(message_earliest)
|
await MessageSender().send_message(message_earliest)
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ import time
|
|||||||
import traceback
|
import traceback
|
||||||
from typing import List, Optional, Dict, Any, TYPE_CHECKING
|
from typing import List, Optional, Dict, Any, TYPE_CHECKING
|
||||||
import json
|
import json
|
||||||
from src.plugins.chat.message import (MessageRecv, BaseMessageInfo, MessageThinking,
|
from src.plugins.chat.message import MessageRecv, BaseMessageInfo, MessageThinking, MessageSending
|
||||||
MessageSending)
|
|
||||||
from src.plugins.chat.message import MessageSet, Seg # Local import needed after move
|
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.chat_stream import ChatStream
|
||||||
from src.plugins.chat.message import UserInfo
|
from src.plugins.chat.message import UserInfo
|
||||||
@@ -219,11 +218,12 @@ class PFChatting:
|
|||||||
else:
|
else:
|
||||||
logger.info(f"{log_prefix} PFChatting: 11111111111111111111111111111111麦麦不发消息了,开始规划")
|
logger.info(f"{log_prefix} PFChatting: 11111111111111111111111111111111麦麦不发消息了,开始规划")
|
||||||
|
|
||||||
|
|
||||||
async with self._timer_lock:
|
async with self._timer_lock:
|
||||||
current_timer = self._loop_timer
|
current_timer = self._loop_timer
|
||||||
if current_timer <= 0:
|
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
|
break
|
||||||
|
|
||||||
# 记录循环周期开始时间,用于计时和休眠计算
|
# 记录循环周期开始时间,用于计时和休眠计算
|
||||||
@@ -287,7 +287,7 @@ class PFChatting:
|
|||||||
thinking_id=thinking_id,
|
thinking_id=thinking_id,
|
||||||
anchor_message=anchor_message,
|
anchor_message=anchor_message,
|
||||||
response_set=replier_result,
|
response_set=replier_result,
|
||||||
send_emoji=emoji_query
|
send_emoji=emoji_query,
|
||||||
)
|
)
|
||||||
# logger.info(f"{log_prefix} 循环: 发送器完成成功.")
|
# logger.info(f"{log_prefix} 循环: 发送器完成成功.")
|
||||||
except Exception as e_sender:
|
except Exception as e_sender:
|
||||||
@@ -460,7 +460,9 @@ class PFChatting:
|
|||||||
tool_result_info = tool_result.get("structured_info", {})
|
tool_result_info = tool_result.get("structured_info", {})
|
||||||
logger.debug(f"{log_prefix}[Planner] 规划前工具结果: {tool_result_info}")
|
logger.debug(f"{log_prefix}[Planner] 规划前工具结果: {tool_result_info}")
|
||||||
# Extract memory IDs and potential emoji query from tools
|
# 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), "")
|
# 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:
|
# if send_emoji_from_tools:
|
||||||
# logger.info(f"{log_prefix}[Planner] 工具建议表情: '{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}'"
|
f"{log_prefix}[Planner] LLM 决策: {action}, 理由: {reasoning}, EmojiQuery: '{emoji_query}'"
|
||||||
)
|
)
|
||||||
except json.JSONDecodeError as json_e:
|
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"
|
action = "error"
|
||||||
reasoning = "工具参数解析失败"
|
reasoning = "工具参数解析失败"
|
||||||
llm_error = True
|
llm_error = True
|
||||||
@@ -530,7 +534,9 @@ class PFChatting:
|
|||||||
reasoning = "处理工具参数时出错"
|
reasoning = "处理工具参数时出错"
|
||||||
llm_error = True
|
llm_error = True
|
||||||
else:
|
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"
|
action = "error"
|
||||||
reasoning = "LLM未调用预期工具"
|
reasoning = "LLM未调用预期工具"
|
||||||
llm_error = True
|
llm_error = True
|
||||||
@@ -589,7 +595,9 @@ class PFChatting:
|
|||||||
# logger.debug(f"{self._get_log_prefix()} 重构的锚点消息: ID={anchor_message.message_info.message_id}")
|
# logger.debug(f"{self._get_log_prefix()} 重构的锚点消息: ID={anchor_message.message_info.message_id}")
|
||||||
return anchor_message
|
return anchor_message
|
||||||
except Exception as e_reconstruct:
|
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:
|
# else:
|
||||||
# logger.warning(f"{self._get_log_prefix()} observed_messages 为空. 创建占位符锚点消息.")
|
# logger.warning(f"{self._get_log_prefix()} observed_messages 为空. 创建占位符锚点消息.")
|
||||||
|
|
||||||
@@ -613,7 +621,9 @@ class PFChatting:
|
|||||||
}
|
}
|
||||||
anchor_message = MessageRecv(placeholder_msg_dict)
|
anchor_message = MessageRecv(placeholder_msg_dict)
|
||||||
anchor_message.update_chat_stream(self.chat_stream)
|
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
|
return anchor_message
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -638,7 +648,7 @@ class PFChatting:
|
|||||||
thinking_id: str,
|
thinking_id: str,
|
||||||
anchor_message: MessageRecv,
|
anchor_message: MessageRecv,
|
||||||
response_set: List[str],
|
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): 使用本类的方法发送生成的回复。
|
发送器 (Sender): 使用本类的方法发送生成的回复。
|
||||||
@@ -698,7 +708,9 @@ class PFChatting:
|
|||||||
config = self.heartfc_controller.global_config
|
config = self.heartfc_controller.global_config
|
||||||
rel_manager = self.heartfc_controller.relationship_manager
|
rel_manager = self.heartfc_controller.relationship_manager
|
||||||
|
|
||||||
prompt = f"你的名字是 {config.BOT_NICKNAME}。是一个女大二学生,正在QQ聊天,正在决定是否以及如何回应当前的聊天。\n"
|
prompt = (
|
||||||
|
f"你的名字是 {config.BOT_NICKNAME}。是一个女大二学生,正在QQ聊天,正在决定是否以及如何回应当前的聊天。\n"
|
||||||
|
)
|
||||||
|
|
||||||
if observed_messages:
|
if observed_messages:
|
||||||
context_texts = []
|
context_texts = []
|
||||||
@@ -706,7 +718,7 @@ class PFChatting:
|
|||||||
sender = msg.get("message_info", {}).get("user_info", {}).get("user_nickname", "未知用户")
|
sender = msg.get("message_info", {}).get("user_info", {}).get("user_nickname", "未知用户")
|
||||||
text = msg.get("detailed_plain_text", "")
|
text = msg.get("detailed_plain_text", "")
|
||||||
timestamp = msg.get("time", 0)
|
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_texts.append(f"{sender} ({time_str}): {text}")
|
||||||
context_text = "\n".join(context_texts)
|
context_text = "\n".join(context_texts)
|
||||||
prompt += "观察到的最新聊天内容如下 (最近的消息在最后):\n---\n"
|
prompt += "观察到的最新聊天内容如下 (最近的消息在最后):\n---\n"
|
||||||
@@ -759,7 +771,7 @@ class PFChatting:
|
|||||||
# Ensure generate_response has access to current_mind if it's crucial context
|
# Ensure generate_response has access to current_mind if it's crucial context
|
||||||
response_set = await gpt_instance.generate_response(
|
response_set = await gpt_instance.generate_response(
|
||||||
anchor_message, # Pass anchor_message positionally (matches 'message' parameter)
|
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:
|
if not response_set:
|
||||||
@@ -857,7 +869,6 @@ class PFChatting:
|
|||||||
first_bot_msg = bot_message
|
first_bot_msg = bot_message
|
||||||
message_set.add_message(bot_message)
|
message_set.add_message(bot_message)
|
||||||
|
|
||||||
|
|
||||||
self.heartfc_controller.MessageManager().add_message(message_set)
|
self.heartfc_controller.MessageManager().add_message(message_set)
|
||||||
return first_bot_msg
|
return first_bot_msg
|
||||||
|
|
||||||
@@ -921,4 +932,5 @@ class PFChatting:
|
|||||||
stance=stance,
|
stance=stance,
|
||||||
)
|
)
|
||||||
mood_manager_instance.update_mood_from_emotion(emotion, config.mood_intensity_factor)
|
mood_manager_instance.update_mood_from_emotion(emotion, config.mood_intensity_factor)
|
||||||
|
|
||||||
# --- Methods moved from HeartFC_Controller end ---
|
# --- Methods moved from HeartFC_Controller end ---
|
||||||
|
|||||||
Reference in New Issue
Block a user