feat:更好的回复信息收集器

This commit is contained in:
SengokuCola
2025-04-09 19:27:23 +08:00
parent 84c79c43a8
commit a889d9d222
9 changed files with 349 additions and 82 deletions

View File

@@ -96,40 +96,39 @@ class ResponseGenerator:
return None
# 保存到数据库
self._save_to_db(
message=message,
sender_name=sender_name,
prompt=prompt,
content=content,
reasoning_content=reasoning_content,
# reasoning_content_check=reasoning_content_check if global_config.enable_kuuki_read else ""
)
# self._save_to_db(
# message=message,
# sender_name=sender_name,
# prompt=prompt,
# content=content,
# reasoning_content=reasoning_content,
# # reasoning_content_check=reasoning_content_check if global_config.enable_kuuki_read else ""
# )
return content
# def _save_to_db(self, message: Message, sender_name: str, prompt: str, prompt_check: str,
# content: str, content_check: str, reasoning_content: str, reasoning_content_check: str):
def _save_to_db(
self,
message: MessageRecv,
sender_name: str,
prompt: str,
content: str,
reasoning_content: str,
):
"""保存对话记录到数据库"""
db.reasoning_logs.insert_one(
{
"time": time.time(),
"chat_id": message.chat_stream.stream_id,
"user": sender_name,
"message": message.processed_plain_text,
"model": self.current_model_name,
"reasoning": reasoning_content,
"response": content,
"prompt": prompt,
}
)
# def _save_to_db(
# self,
# message: MessageRecv,
# sender_name: str,
# prompt: str,
# content: str,
# reasoning_content: str,
# ):
# """保存对话记录到数据库"""
# db.reasoning_logs.insert_one(
# {
# "time": time.time(),
# "chat_id": message.chat_stream.stream_id,
# "user": sender_name,
# "message": message.processed_plain_text,
# "model": self.current_model_name,
# "reasoning": reasoning_content,
# "response": content,
# "prompt": prompt,
# }
# )
async def _get_emotion_tags(self, content: str, processed_plain_text: str):
"""提取情感标签,结合立场和情绪"""

View File

@@ -1,7 +1,8 @@
import time
from random import random
import re
import traceback
from typing import List
from ...memory_system.Hippocampus import HippocampusManager
from ...moods.moods import MoodManager
from ...config.config import global_config
@@ -19,6 +20,7 @@ from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
from ...chat.chat_stream import chat_manager
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
# 定义日志配置
chat_config = LogConfig(
@@ -59,7 +61,11 @@ class ThinkFlowChat:
return thinking_id
async def _send_response_messages(self, message, chat, response_set, thinking_id):
async def _send_response_messages(self,
message,
chat,
response_set:List[str],
thinking_id) -> MessageSending:
"""发送回复消息"""
container = message_manager.get_container(chat.stream_id)
thinking_message = None
@@ -72,12 +78,13 @@ class ThinkFlowChat:
if not thinking_message:
logger.warning("未找到对应的思考消息,可能已超时被移除")
return
return None
thinking_start_time = thinking_message.thinking_start_time
message_set = MessageSet(chat, thinking_id)
mark_head = False
first_bot_msg = None
for msg in response_set:
message_segment = Seg(type="text", data=msg)
bot_message = MessageSending(
@@ -97,10 +104,12 @@ class ThinkFlowChat:
)
if not mark_head:
mark_head = True
first_bot_msg = bot_message
# print(f"thinking_start_time:{bot_message.thinking_start_time}")
message_set.add_message(bot_message)
message_manager.add_message(message_set)
return first_bot_msg
async def _handle_emoji(self, message, chat, response):
"""处理表情包"""
@@ -257,6 +266,8 @@ class ThinkFlowChat:
if random() < reply_probability:
try:
do_reply = True
# 创建思考消息
try:
@@ -266,6 +277,11 @@ class ThinkFlowChat:
timing_results["创建思考消息"] = timer2 - timer1
except Exception as e:
logger.error(f"心流创建思考消息失败: {e}")
logger.debug(f"创建捕捉器thinking_id:{thinking_id}")
info_catcher = info_catcher_manager.get_info_catcher(thinking_id)
info_catcher.catch_decide_to_response(message)
try:
# 观察
@@ -275,36 +291,48 @@ class ThinkFlowChat:
timing_results["观察"] = timer2 - timer1
except Exception as e:
logger.error(f"心流观察失败: {e}")
info_catcher.catch_after_observe(timing_results["观察"])
# 思考前脑内状态
try:
timer1 = time.time()
await heartflow.get_subheartflow(chat.stream_id).do_thinking_before_reply(
current_mind,past_mind = await heartflow.get_subheartflow(chat.stream_id).do_thinking_before_reply(
message.processed_plain_text
)
timer2 = time.time()
timing_results["思考前脑内状态"] = timer2 - timer1
except Exception as e:
logger.error(f"心流思考前脑内状态失败: {e}")
info_catcher.catch_afer_shf_step(timing_results["思考前脑内状态"],past_mind,current_mind)
# 生成回复
timer1 = time.time()
response_set = await self.gpt.generate_response(message)
response_set = await self.gpt.generate_response(message,thinking_id)
timer2 = time.time()
timing_results["生成回复"] = timer2 - timer1
info_catcher.catch_after_generate_response(timing_results["生成回复"])
if not response_set:
logger.info("为什么生成回复失败?")
logger.info("回复生成失败,返回为空")
return
# 发送消息
try:
timer1 = time.time()
await self._send_response_messages(message, chat, response_set, thinking_id)
first_bot_msg = await self._send_response_messages(message, chat, response_set, thinking_id)
timer2 = time.time()
timing_results["发送消息"] = timer2 - timer1
except Exception as e:
logger.error(f"心流发送消息失败: {e}")
info_catcher.catch_after_response(timing_results["发送消息"],response_set,first_bot_msg)
info_catcher.done_catch()
# 处理表情包
try:
@@ -335,6 +363,7 @@ class ThinkFlowChat:
except Exception as e:
logger.error(f"心流处理消息失败: {e}")
logger.error(traceback.format_exc())
# 输出性能计时结果
if do_reply:

View File

@@ -9,6 +9,7 @@ from ...chat.message import MessageRecv, MessageThinking
from .think_flow_prompt_builder import prompt_builder
from ...chat.utils import process_llm_response
from src.common.logger import get_module_logger, LogConfig, LLM_STYLE_CONFIG
from src.plugins.respon_info_catcher.info_catcher import info_catcher_manager
# 定义日志配置
llm_config = LogConfig(
@@ -32,15 +33,16 @@ class ResponseGenerator:
self.current_model_type = "r1" # 默认使用 R1
self.current_model_name = "unknown model"
async def generate_response(self, message: MessageThinking) -> Optional[Union[str, List[str]]]:
async def generate_response(self, message: MessageRecv,thinking_id:str) -> Optional[List[str]]:
"""根据当前模型类型选择对应的生成函数"""
logger.info(
f"思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}"
)
current_model = self.model_normal
model_response = await self._generate_response_with_model(message, current_model)
model_response = await self._generate_response_with_model(message, current_model,thinking_id)
# print(f"raw_content: {model_response}")
@@ -53,8 +55,11 @@ class ResponseGenerator:
logger.info(f"{self.current_model_type}思考,失败")
return None
async def _generate_response_with_model(self, message: MessageThinking, model: LLM_request):
async def _generate_response_with_model(self, message: MessageRecv, model: LLM_request,thinking_id:str):
sender_name = ""
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:
sender_name = (
f"[({message.chat_stream.user_info.user_id}){message.chat_stream.user_info.user_nickname}]"
@@ -79,45 +84,51 @@ class ResponseGenerator:
try:
content, reasoning_content, self.current_model_name = await model.generate_response(prompt)
info_catcher.catch_after_llm_generated(
prompt=prompt,
response=content,
reasoning_content=reasoning_content,
model_name=self.current_model_name)
except Exception:
logger.exception("生成回复时出错")
return None
# 保存到数据库
self._save_to_db(
message=message,
sender_name=sender_name,
prompt=prompt,
content=content,
reasoning_content=reasoning_content,
# reasoning_content_check=reasoning_content_check if global_config.enable_kuuki_read else ""
)
# self._save_to_db(
# message=message,
# sender_name=sender_name,
# prompt=prompt,
# content=content,
# reasoning_content=reasoning_content,
# # reasoning_content_check=reasoning_content_check if global_config.enable_kuuki_read else ""
# )
return content
# def _save_to_db(self, message: Message, sender_name: str, prompt: str, prompt_check: str,
# content: str, content_check: str, reasoning_content: str, reasoning_content_check: str):
def _save_to_db(
self,
message: MessageRecv,
sender_name: str,
prompt: str,
content: str,
reasoning_content: str,
):
"""保存对话记录到数据库"""
db.reasoning_logs.insert_one(
{
"time": time.time(),
"chat_id": message.chat_stream.stream_id,
"user": sender_name,
"message": message.processed_plain_text,
"model": self.current_model_name,
"reasoning": reasoning_content,
"response": content,
"prompt": prompt,
}
)
# def _save_to_db(
# self,
# message: MessageRecv,
# sender_name: str,
# prompt: str,
# content: str,
# reasoning_content: str,
# ):
# """保存对话记录到数据库"""
# db.reasoning_logs.insert_one(
# {
# "time": time.time(),
# "chat_id": message.chat_stream.stream_id,
# "user": sender_name,
# "message": message.processed_plain_text,
# "model": self.current_model_name,
# "reasoning": reasoning_content,
# "response": content,
# "prompt": prompt,
# }
# )
async def _get_emotion_tags(self, content: str, processed_plain_text: str):
"""提取情感标签,结合立场和情绪"""
@@ -167,10 +178,10 @@ class ResponseGenerator:
logger.debug(f"获取情感标签时出错: {e}")
return "中立", "平静" # 出错时返回默认值
async def _process_response(self, content: str) -> Tuple[List[str], List[str]]:
async def _process_response(self, content: str) -> List[str]:
"""处理响应内容,返回处理后的内容和情感标签"""
if not content:
return None, []
return None
processed_response = process_llm_response(content)