Merge remote-tracking branch 'upstream/dev' into dev

This commit is contained in:
meng_xi_pan
2025-04-11 14:04:03 +08:00
55 changed files with 3144 additions and 1794 deletions

View File

@@ -1,7 +1,7 @@
import time
from random import random
import re
from typing import List
from ...memory_system.Hippocampus import HippocampusManager
from ...moods.moods import MoodManager
from ...config.config import global_config
@@ -18,6 +18,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(
@@ -57,7 +58,7 @@ class ReasoningChat:
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
@@ -76,6 +77,7 @@ class ReasoningChat:
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(
@@ -95,9 +97,12 @@ class ReasoningChat:
)
if not mark_head:
mark_head = True
first_bot_msg = bot_message
message_set.add_message(bot_message)
message_manager.add_message(message_set)
return first_bot_msg
async def _handle_emoji(self, message, chat, response):
"""处理表情包"""
if random() < global_config.emoji_chance:
@@ -228,11 +233,22 @@ class ReasoningChat:
timer2 = time.time()
timing_results["创建思考消息"] = timer2 - timer1
logger.debug(f"创建捕捉器thinking_id:{thinking_id}")
info_catcher = info_catcher_manager.get_info_catcher(thinking_id)
info_catcher.catch_decide_to_response(message)
# 生成回复
timer1 = time.time()
response_set = await self.gpt.generate_response(message)
timer2 = time.time()
timing_results["生成回复"] = timer2 - timer1
try:
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["生成回复"])
except Exception as e:
logger.error(f"回复生成出现错误str{e}")
response_set = None
if not response_set:
logger.info("为什么生成回复失败?")
@@ -240,10 +256,14 @@ class ReasoningChat:
# 发送消息
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
info_catcher.catch_after_response(timing_results["发送消息"], response_set, first_bot_msg)
info_catcher.done_catch()
# 处理表情包
timer1 = time.time()
await self._handle_emoji(message, chat, response_set)
@@ -286,7 +306,7 @@ class ReasoningChat:
def _check_ban_regex(self, text: str, chat, userinfo) -> bool:
"""检查消息是否匹配过滤正则表达式"""
for pattern in global_config.ban_msgs_regex:
if re.search(pattern, text):
if pattern.search(text):
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]{userinfo.user_nickname}:{text}"
)

View File

@@ -2,13 +2,13 @@ import time
from typing import List, Optional, Tuple, Union
import random
from ....common.database import db
from ...models.utils_model import LLM_request
from ...config.config import global_config
from ...chat.message import MessageRecv, MessageThinking
from ...chat.message import MessageThinking
from .reasoning_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(
@@ -38,7 +38,7 @@ 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: MessageThinking,thinking_id:str) -> Optional[Union[str, List[str]]]:
"""根据当前模型类型选择对应的生成函数"""
# 从global_config中获取模型概率值并选择模型
if random.random() < global_config.MODEL_R1_PROBABILITY:
@@ -52,7 +52,7 @@ class ResponseGenerator:
f"{self.current_model_type}思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}"
) # noqa: E501
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}")
@@ -65,8 +65,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: MessageThinking, 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}]"
@@ -91,45 +94,52 @@ 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):
"""提取情感标签,结合立场和情绪"""

View File

@@ -115,6 +115,18 @@ class PromptBuilder:
f"检测到以下关键词之一:{rule.get('keywords', [])},触发反应:{rule.get('reaction', '')}"
)
keywords_reaction_prompt += rule.get("reaction", "") + ""
else:
for pattern in rule.get("regex", []):
result = pattern.search(message_txt)
if result:
reaction = rule.get('reaction', '')
for name, content in result.groupdict().items():
reaction = reaction.replace(f'[{name}]', content)
logger.info(
f"匹配到以下正则表达式:{pattern},触发反应:{reaction}"
)
keywords_reaction_prompt += reaction + ""
break
# 中文高手(新加的好玩功能)
prompt_ger = ""