增加了event_handler修改内容的方法
This commit is contained in:
@@ -8,7 +8,6 @@ from typing import List, Dict, Optional, Any, Tuple
|
||||
|
||||
from src.common.logger import get_logger
|
||||
from src.common.database.database_model import Expression
|
||||
from src.common.data_models.database_data_model import DatabaseMessages
|
||||
from src.llm_models.utils_model import LLMRequest
|
||||
from src.config.config import model_config, global_config
|
||||
from src.chat.utils.chat_message_builder import get_raw_msg_by_timestamp_with_chat_inclusive, build_anonymous_messages
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import time
|
||||
from typing import Optional, Dict, List
|
||||
from typing import Optional, Dict
|
||||
from src.plugin_system.apis import message_api
|
||||
from src.chat.message_receive.chat_stream import ChatStream, get_chat_manager
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config
|
||||
from src.chat.frequency_control.talk_frequency_control import get_config_base_talk_frequency
|
||||
from src.chat.frequency_control.focus_value_control import get_config_base_focus_value
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import math
|
||||
import random
|
||||
from typing import List, Optional, Dict, Any, Tuple, TYPE_CHECKING
|
||||
from rich.traceback import install
|
||||
from collections import deque
|
||||
|
||||
from src.config.config import global_config
|
||||
from src.common.logger import get_logger
|
||||
@@ -101,7 +100,6 @@ class HeartFChatting:
|
||||
|
||||
self.last_read_time = time.time() - 10
|
||||
|
||||
|
||||
async def start(self):
|
||||
"""检查是否需要启动主循环,如果未激活则启动。"""
|
||||
|
||||
@@ -178,7 +176,7 @@ class HeartFChatting:
|
||||
f"耗时: {self._current_cycle_detail.end_time - self._current_cycle_detail.start_time:.1f}秒" # type: ignore
|
||||
+ (f"\n详情: {'; '.join(timer_strings)}" if timer_strings else "")
|
||||
)
|
||||
|
||||
|
||||
async def caculate_interest_value(self, recent_messages_list: List["DatabaseMessages"]) -> float:
|
||||
total_interest = 0.0
|
||||
for msg in recent_messages_list:
|
||||
@@ -197,10 +195,13 @@ class HeartFChatting:
|
||||
filter_mai=True,
|
||||
filter_command=True,
|
||||
)
|
||||
|
||||
|
||||
if recent_messages_list:
|
||||
self.last_read_time = time.time()
|
||||
await self._observe(interest_value=await self.caculate_interest_value(recent_messages_list),recent_messages_list=recent_messages_list)
|
||||
await self._observe(
|
||||
interest_value=await self.caculate_interest_value(recent_messages_list),
|
||||
recent_messages_list=recent_messages_list,
|
||||
)
|
||||
else:
|
||||
# Normal模式:消息数量不足,等待
|
||||
await asyncio.sleep(0.2)
|
||||
@@ -257,7 +258,7 @@ class HeartFChatting:
|
||||
|
||||
return loop_info, reply_text, cycle_timers
|
||||
|
||||
async def _observe(self, interest_value: float = 0.0,recent_messages_list: List["DatabaseMessages"] = []) -> bool:
|
||||
async def _observe(self, interest_value: float = 0.0, recent_messages_list: List["DatabaseMessages"] = []) -> bool:
|
||||
reply_text = "" # 初始化reply_text变量,避免UnboundLocalError
|
||||
|
||||
# 使用sigmoid函数将interest_value转换为概率
|
||||
@@ -274,12 +275,10 @@ class HeartFChatting:
|
||||
return 1.0 / (1.0 + math.exp(-k * (interest_val - x0)))
|
||||
|
||||
normal_mode_probability = (
|
||||
calculate_normal_mode_probability(interest_value)
|
||||
* 2
|
||||
* self.frequency_control.get_final_talk_frequency()
|
||||
calculate_normal_mode_probability(interest_value) * 2 * self.frequency_control.get_final_talk_frequency()
|
||||
)
|
||||
|
||||
#对呼唤名字进行增幅
|
||||
|
||||
# 对呼唤名字进行增幅
|
||||
for msg in recent_messages_list:
|
||||
if msg.reply_probability_boost is not None and msg.reply_probability_boost > 0.0:
|
||||
normal_mode_probability += msg.reply_probability_boost
|
||||
@@ -287,18 +286,15 @@ class HeartFChatting:
|
||||
normal_mode_probability += global_config.chat.mentioned_bot_reply
|
||||
if global_config.chat.at_bot_inevitable_reply and msg.is_at:
|
||||
normal_mode_probability += global_config.chat.at_bot_inevitable_reply
|
||||
|
||||
|
||||
# 根据概率决定使用直接回复
|
||||
interest_triggerd = False
|
||||
focus_triggerd = False
|
||||
|
||||
|
||||
if random.random() < normal_mode_probability:
|
||||
interest_triggerd = True
|
||||
|
||||
logger.info(
|
||||
f"{self.log_prefix} 有新消息,在{normal_mode_probability * 100:.0f}%概率下选择回复"
|
||||
)
|
||||
logger.info(f"{self.log_prefix} 有新消息,在{normal_mode_probability * 100:.0f}%概率下选择回复")
|
||||
|
||||
if s4u_config.enable_s4u:
|
||||
await send_typing()
|
||||
@@ -307,21 +303,20 @@ class HeartFChatting:
|
||||
await self.expression_learner.trigger_learning_for_chat()
|
||||
|
||||
available_actions: Dict[str, ActionInfo] = {}
|
||||
|
||||
#如果兴趣度不足以激活
|
||||
if not interest_triggerd:
|
||||
#看看专注值够不够
|
||||
if random.random() < self.frequency_control.get_final_focus_value():
|
||||
#专注值足够,仍然进入正式思考
|
||||
focus_triggerd = True #都没触发,路边
|
||||
|
||||
|
||||
# 如果兴趣度不足以激活
|
||||
if not interest_triggerd:
|
||||
# 看看专注值够不够
|
||||
if random.random() < self.frequency_control.get_final_focus_value():
|
||||
# 专注值足够,仍然进入正式思考
|
||||
focus_triggerd = True # 都没触发,路边
|
||||
|
||||
# 任意一种触发都行
|
||||
if interest_triggerd or focus_triggerd:
|
||||
# 进入正式思考模式
|
||||
cycle_timers, thinking_id = self.start_cycle()
|
||||
logger.info(f"{self.log_prefix} 开始第{self._cycle_counter}次思考")
|
||||
|
||||
|
||||
# 第一步:动作检查
|
||||
try:
|
||||
await self.action_modifier.modify_actions()
|
||||
@@ -353,17 +348,20 @@ class HeartFChatting:
|
||||
# actions_before_now_block=actions_before_now_block,
|
||||
message_id_list=message_id_list,
|
||||
)
|
||||
if not await events_manager.handle_mai_events(
|
||||
continue_flag, modified_message = await events_manager.handle_mai_events(
|
||||
EventType.ON_PLAN, None, prompt_info[0], None, self.chat_stream.stream_id
|
||||
):
|
||||
)
|
||||
if not continue_flag:
|
||||
return False
|
||||
if modified_message and modified_message._modify_flags.modify_llm_prompt:
|
||||
prompt_info = (modified_message.llm_prompt, prompt_info[1])
|
||||
with Timer("规划器", cycle_timers):
|
||||
# 根据不同触发,进入不同plan
|
||||
if focus_triggerd:
|
||||
mode = ChatMode.FOCUS
|
||||
else:
|
||||
mode = ChatMode.NORMAL
|
||||
|
||||
|
||||
action_to_use_info, _ = await self.action_planner.plan(
|
||||
mode=mode,
|
||||
loop_start_time=self.last_read_time,
|
||||
@@ -432,8 +430,7 @@ class HeartFChatting:
|
||||
},
|
||||
}
|
||||
reply_text = action_reply_text
|
||||
|
||||
|
||||
|
||||
self.end_cycle(loop_info, cycle_timers)
|
||||
self.print_cycle_info(cycle_timers)
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ from rich.progress import (
|
||||
SpinnerColumn,
|
||||
TextColumn,
|
||||
)
|
||||
from src.chat.utils.utils import get_embedding
|
||||
from src.config.config import global_config
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import re
|
||||
import jieba
|
||||
import networkx as nx
|
||||
import numpy as np
|
||||
from typing import List, Tuple, Set, Coroutine, Any, Dict
|
||||
from typing import List, Tuple, Set, Coroutine, Any
|
||||
from collections import Counter
|
||||
import traceback
|
||||
|
||||
@@ -21,7 +21,6 @@ from src.common.logger import get_logger
|
||||
from src.chat.utils.utils import cut_key_words
|
||||
from src.chat.utils.chat_message_builder import (
|
||||
build_readable_messages,
|
||||
get_raw_msg_by_timestamp_with_chat_inclusive,
|
||||
) # 导入 build_readable_messages
|
||||
|
||||
|
||||
@@ -1183,9 +1182,7 @@ class ParahippocampalGyrus:
|
||||
# 规范化输入为列表[str]
|
||||
if isinstance(keywords, str):
|
||||
# 支持中英文逗号、顿号、空格分隔
|
||||
parts = (
|
||||
keywords.replace(",", ",").replace("、", ",").replace(" ", ",").strip(", ")
|
||||
)
|
||||
parts = keywords.replace(",", ",").replace("、", ",").replace(" ", ",").strip(", ")
|
||||
keyword_list = [p.strip() for p in parts.split(",") if p.strip()]
|
||||
else:
|
||||
keyword_list = [k.strip() for k in keywords if isinstance(k, str) and k.strip()]
|
||||
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
import re
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from maim_message import UserInfo
|
||||
from maim_message import UserInfo, Seg
|
||||
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config
|
||||
@@ -169,8 +169,12 @@ class ChatBot:
|
||||
|
||||
# 处理消息内容
|
||||
await message.process()
|
||||
|
||||
_ = Person.register_person(platform=message.message_info.platform, user_id=message.message_info.user_info.user_id,nickname=user_info.user_nickname) # type: ignore
|
||||
|
||||
_ = Person.register_person(
|
||||
platform=message.message_info.platform,
|
||||
user_id=message.message_info.user_info.user_id,
|
||||
nickname=user_info.user_nickname,
|
||||
) # type: ignore
|
||||
|
||||
await self.s4u_message_processor.process_message(message)
|
||||
|
||||
@@ -220,10 +224,18 @@ class ChatBot:
|
||||
user_info = message.message_info.user_info
|
||||
if message.message_info.additional_config:
|
||||
sent_message = message.message_info.additional_config.get("echo", False)
|
||||
if sent_message: # 这一段只是为了在一切处理前劫持上报的自身消息,用于更新message_id,需要ada支持上报事件,实际测试中不会对正常使用造成任何问题
|
||||
if sent_message: # 处理上报的自身消息,更新message_id,需要ada支持上报事件
|
||||
await MessageStorage.update_message(message)
|
||||
return
|
||||
|
||||
continue_flag, modified_message = await events_manager.handle_mai_events(
|
||||
EventType.ON_MESSAGE_PRE_PROCESS, message
|
||||
)
|
||||
if not continue_flag:
|
||||
return
|
||||
if modified_message and modified_message._modify_flags.modify_message_segments:
|
||||
message.message_segment = Seg(type="seglist", data=modified_message.message_segments)
|
||||
|
||||
get_chat_manager().register_message(message)
|
||||
|
||||
chat = await get_chat_manager().get_or_create_stream(
|
||||
@@ -258,8 +270,11 @@ class ChatBot:
|
||||
logger.info(f"命令处理完成,跳过后续消息处理: {cmd_result}")
|
||||
return
|
||||
|
||||
if not await events_manager.handle_mai_events(EventType.ON_MESSAGE, message):
|
||||
continue_flag, modified_message = await events_manager.handle_mai_events(EventType.ON_MESSAGE, message)
|
||||
if not continue_flag:
|
||||
return
|
||||
if modified_message and modified_message._modify_flags.modify_plain_text:
|
||||
message.processed_plain_text = modified_message.plain_text
|
||||
|
||||
# 确认从接口发来的message是否有自定义的prompt模板信息
|
||||
if message.message_info.template_info and not message.message_info.template_info.template_default:
|
||||
|
||||
@@ -202,10 +202,14 @@ class DefaultReplyer:
|
||||
from src.plugin_system.core.events_manager import events_manager
|
||||
|
||||
if not from_plugin:
|
||||
if not await events_manager.handle_mai_events(
|
||||
continue_flag, modified_message = await events_manager.handle_mai_events(
|
||||
EventType.POST_LLM, None, prompt, None, stream_id=stream_id
|
||||
):
|
||||
)
|
||||
if not continue_flag:
|
||||
raise UserWarning("插件于请求前中断了内容生成")
|
||||
if modified_message and modified_message._modify_flags.modify_llm_prompt:
|
||||
llm_response.prompt = modified_message.llm_prompt
|
||||
prompt = str(modified_message.llm_prompt)
|
||||
|
||||
# 4. 调用 LLM 生成回复
|
||||
content = None
|
||||
@@ -219,10 +223,19 @@ class DefaultReplyer:
|
||||
llm_response.reasoning = reasoning_content
|
||||
llm_response.model = model_name
|
||||
llm_response.tool_calls = tool_call
|
||||
if not from_plugin and not await events_manager.handle_mai_events(
|
||||
continue_flag, modified_message = await events_manager.handle_mai_events(
|
||||
EventType.AFTER_LLM, None, prompt, llm_response, stream_id=stream_id
|
||||
):
|
||||
)
|
||||
if not from_plugin and not continue_flag:
|
||||
raise UserWarning("插件于请求后取消了内容生成")
|
||||
if modified_message:
|
||||
if modified_message._modify_flags.modify_llm_prompt:
|
||||
logger.warning("警告:插件在内容生成后才修改了prompt,此修改不会生效")
|
||||
llm_response.prompt = modified_message.llm_prompt # 虽然我不知道为什么在这里需要改prompt
|
||||
if modified_message._modify_flags.modify_llm_response_content:
|
||||
llm_response.content = modified_message.llm_response_content
|
||||
if modified_message._modify_flags.modify_llm_response_reasoning:
|
||||
llm_response.reasoning = modified_message.llm_response_reasoning
|
||||
except UserWarning as e:
|
||||
raise e
|
||||
except Exception as llm_e:
|
||||
@@ -634,7 +647,7 @@ class DefaultReplyer:
|
||||
"""构建动作提示"""
|
||||
|
||||
action_descriptions = ""
|
||||
skip_names = ["emoji","build_memory","build_relation","reply"]
|
||||
skip_names = ["emoji", "build_memory", "build_relation", "reply"]
|
||||
if available_actions:
|
||||
action_descriptions = "除了进行回复之外,你可以做以下这些动作,不过这些动作由另一个模型决定,:\n"
|
||||
for action_name, action_info in available_actions.items():
|
||||
@@ -671,9 +684,7 @@ class DefaultReplyer:
|
||||
else:
|
||||
bot_nickname = ""
|
||||
|
||||
prompt_personality = (
|
||||
f"{global_config.personality.personality};"
|
||||
)
|
||||
prompt_personality = f"{global_config.personality.personality};"
|
||||
return f"你的名字是{bot_name}{bot_nickname},你{prompt_personality}"
|
||||
|
||||
async def build_prompt_reply_context(
|
||||
@@ -809,11 +820,6 @@ class DefaultReplyer:
|
||||
|
||||
moderation_prompt_block = "请不要输出违法违规内容,不要输出色情,暴力,政治相关内容,如有敏感内容,请规避。"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if sender:
|
||||
if is_group_chat:
|
||||
reply_target_block = (
|
||||
@@ -1016,7 +1022,7 @@ class DefaultReplyer:
|
||||
logger.info(f"使用模型集生成回复: {', '.join(map(str, self.express_model.model_for_task.model_list))}")
|
||||
|
||||
logger.info(f"\n{prompt}\n")
|
||||
|
||||
|
||||
if global_config.debug.show_prompt:
|
||||
logger.info(f"\n{prompt}\n")
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user