Merge branch 'MaiM-with-u:dev' into dev

pull/998/head
2829798842 2025-05-29 08:26:49 +08:00 committed by GitHub
commit 89d76847ca
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
36 changed files with 278 additions and 236 deletions

1
.gitignore vendored
View File

@ -305,3 +305,4 @@ $RECYCLE.BIN/
src/chat/focus_chat/working_memory/test/test1.txt
src/chat/focus_chat/working_memory/test/test4.txt
run_maiserver.bat
src/plugins/test_plugin_pic/actions/pic_action_config.toml

View File

@ -198,8 +198,8 @@ class MongoToSQLiteMigrator:
"status": "status",
"timestamp": "timestamp",
},
enable_validation=False, # 禁用数据验证
unique_fields=["user_id", "timestamp"], # 组合唯一性
enable_validation=True, # 禁用数据验证"
unique_fields=["user_id", "prompt_tokens","completion_tokens","total_tokens","cost"], # 组合唯一性
),
# 消息迁移配置
MigrationConfig(

View File

@ -635,7 +635,7 @@ class EmojiManager:
"""获取所有表情包并初始化为MaiEmoji类对象更新 self.emoji_objects"""
try:
self._ensure_db()
logger.info("[数据库] 开始加载所有表情包记录 (Peewee)...")
logger.debug("[数据库] 开始加载所有表情包记录 (Peewee)...")
emoji_peewee_instances = Emoji.select()
emoji_objects, load_errors = _to_emoji_objects(emoji_peewee_instances)

View File

@ -234,9 +234,8 @@ class DefaultExpressor:
# logger.info(f"{self.log_prefix}\nPrompt:\n{prompt}\n---------------------------\n")
logger.info(f"想要表达:{in_mind_reply}")
logger.info(f"理由:{reason}")
logger.info(f"生成回复: {content}\n")
logger.info(f"想要表达:{in_mind_reply}||理由:{reason}")
logger.info(f"最终回复: {content}\n")
info_catcher.catch_after_llm_generated(
prompt=prompt, response=content, reasoning_content=reasoning_content, model_name=model_name

View File

@ -204,19 +204,21 @@ class ExpressionLearner:
random_msg: Optional[List[Dict[str, Any]]] = get_raw_msg_by_timestamp_random(
current_time - 3600 * 24, current_time, limit=num
)
if not random_msg:
# print(random_msg)
if not random_msg or random_msg == []:
return None
# 转化成str
chat_id: str = random_msg[0]["chat_id"]
# random_msg_str: str = await build_readable_messages(random_msg, timestamp_mode="normal")
random_msg_str: str = await build_anonymous_messages(random_msg)
# print(f"random_msg_str:{random_msg_str}")
prompt: str = await global_prompt_manager.format_prompt(
prompt,
chat_str=random_msg_str,
)
# logger.info(f"学习{type_str}的prompt: {prompt}")
logger.debug(f"学习{type_str}的prompt: {prompt}")
try:
response, _ = await self.express_learn_model.generate_response_async(prompt)
@ -224,7 +226,7 @@ class ExpressionLearner:
logger.error(f"学习{type_str}失败: {e}")
return None
logger.info(f"学习{type_str}的response: {response}")
logger.debug(f"学习{type_str}的response: {response}")
expressions: List[Tuple[str, str, str]] = self.parse_expression_response(response, chat_id)

View File

@ -54,7 +54,7 @@ CONSECUTIVE_NO_REPLY_THRESHOLD = 3 # 连续不回复的阈值
logger = get_logger("hfc") # Logger Name Changed
# 设定处理器超时时间(秒)
PROCESSOR_TIMEOUT = 20
PROCESSOR_TIMEOUT = 30
async def _handle_cycle_delay(action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str):
@ -329,11 +329,20 @@ class HeartFChatting:
formatted_time = f"{elapsed * 1000:.2f}毫秒" if elapsed < 1 else f"{elapsed:.2f}"
timer_strings.append(f"{name}: {formatted_time}")
# 新增:输出每个处理器的耗时
processor_time_costs = self._current_cycle.loop_processor_info.get("processor_time_costs", {})
processor_time_strings = []
for pname, ptime in processor_time_costs.items():
formatted_ptime = f"{ptime * 1000:.2f}毫秒" if ptime < 1 else f"{ptime:.2f}"
processor_time_strings.append(f"{pname}: {formatted_ptime}")
processor_time_log = ("\n各处理器耗时: " + "; ".join(processor_time_strings)) if processor_time_strings else ""
logger.info(
f"{self.log_prefix}{self._current_cycle.cycle_id}次思考,"
f"耗时: {self._current_cycle.end_time - self._current_cycle.start_time:.1f}秒, "
f"动作: {self._current_cycle.loop_plan_info['action_result']['action_type']}"
+ (f"\n详情: {'; '.join(timer_strings)}" if timer_strings else "")
+ processor_time_log
)
await asyncio.sleep(global_config.focus_chat.think_interval)
@ -369,18 +378,18 @@ class HeartFChatting:
async def _process_processors(
self, observations: List[Observation], running_memorys: List[Dict[str, Any]], cycle_timers: dict
) -> List[InfoBase]:
) -> tuple[List[InfoBase], Dict[str, float]]:
# 记录并行任务开始时间
parallel_start_time = time.time()
logger.debug(f"{self.log_prefix} 开始信息处理器并行任务")
processor_tasks = []
task_to_name_map = {}
processor_time_costs = {} # 新增: 记录每个处理器耗时
for processor in self.processors:
processor_name = processor.__class__.log_prefix
# 用lambda包裹便于传参
async def run_with_timeout(proc=processor):
return await asyncio.wait_for(
proc.process_info(observations=observations, running_memorys=running_memorys),
@ -404,24 +413,24 @@ class HeartFChatting:
duration_since_parallel_start = task_completed_time - parallel_start_time
try:
# 使用 await task 来获取结果或触发异常
result_list = await task
logger.info(
f"{self.log_prefix} 处理器 {processor_name} 已完成,信息已处理: {duration_since_parallel_start:.2f}"
)
logger.info(f"{self.log_prefix} 处理器 {processor_name} 已完成!")
if result_list is not None:
all_plan_info.extend(result_list)
else:
logger.warning(f"{self.log_prefix} 处理器 {processor_name} 返回了 None")
# 记录耗时
processor_time_costs[processor_name] = duration_since_parallel_start
except asyncio.TimeoutError:
logger.error(f"{self.log_prefix} 处理器 {processor_name} 超时(>{PROCESSOR_TIMEOUT}s已跳过")
logger.info(f"{self.log_prefix} 处理器 {processor_name} 超时(>{PROCESSOR_TIMEOUT}s已跳过")
processor_time_costs[processor_name] = PROCESSOR_TIMEOUT
except Exception as e:
logger.error(
f"{self.log_prefix} 处理器 {processor_name} 执行失败,耗时 (自并行开始): {duration_since_parallel_start:.2f}秒. 错误: {e}",
exc_info=True,
)
traceback.print_exc()
# 即使出错,也认为该任务结束了,已从 pending_tasks 中移除
processor_time_costs[processor_name] = duration_since_parallel_start
if pending_tasks:
current_progress_time = time.time()
@ -437,12 +446,11 @@ class HeartFChatting:
logger.info(f"{self.log_prefix} 所有处理器任务全部完成,总耗时: {total_duration:.2f}")
# logger.debug(f"{self.log_prefix} 所有信息处理器处理后的信息: {all_plan_info}")
return all_plan_info
return all_plan_info, processor_time_costs
async def _observe_process_plan_action_loop(self, cycle_timers: dict, thinking_id: str) -> dict:
try:
with Timer("观察", cycle_timers):
# await self.observations[0].observe()
await self.chatting_observation.observe()
await self.working_observation.observe()
await self.hfcloop_observation.observe()
@ -463,10 +471,11 @@ class HeartFChatting:
running_memorys = await self.memory_activator.activate_memory(observations)
with Timer("执行 信息处理器", cycle_timers):
all_plan_info = await self._process_processors(observations, running_memorys, cycle_timers)
all_plan_info, processor_time_costs = await self._process_processors(observations, running_memorys, cycle_timers)
loop_processor_info = {
"all_plan_info": all_plan_info,
"processor_time_costs": processor_time_costs,
}
with Timer("规划器", cycle_timers):
@ -485,7 +494,6 @@ class HeartFChatting:
plan_result.get("action_result", {}).get("reasoning", "未提供理由"),
)
# 在此处添加日志记录
if action_type == "reply":
action_str = "回复"
elif action_type == "no_reply":
@ -493,7 +501,7 @@ class HeartFChatting:
else:
action_str = action_type
logger.info(f"{self.log_prefix} 麦麦决定'{action_str}', 原因'{reasoning}'")
logger.debug(f"{self.log_prefix} 麦麦想要:'{action_str}', 原因'{reasoning}'")
success, reply_text, command = await self._handle_action(
action_type, reasoning, action_data, cycle_timers, thinking_id
@ -576,8 +584,8 @@ class HeartFChatting:
else:
success, reply_text = result
command = ""
logger.info(
f"{self.log_prefix} 麦麦决定'{action}', 原因'{reasoning}',返回结果'{success}', '{reply_text}', '{command}'"
logger.debug(
f"{self.log_prefix} 麦麦执行了'{action}', 原因'{reasoning}',返回结果'{success}', '{reply_text}', '{command}'"
)
return success, reply_text, command

View File

@ -1,18 +1,21 @@
import traceback
from ..memory_system.Hippocampus import HippocampusManager
from ...config.config import global_config
from ..message_receive.message import MessageRecv
from ..message_receive.storage import MessageStorage
from ..utils.utils import is_mentioned_bot_in_message
from src.chat.memory_system.Hippocampus import HippocampusManager
from src.config.config import global_config
from src.chat.message_receive.message import MessageRecv
from src.chat.message_receive.storage import MessageStorage
from src.chat.heart_flow.heartflow import heartflow
from src.chat.message_receive.chat_stream import chat_manager, ChatStream
from src.chat.utils.utils import is_mentioned_bot_in_message
from src.chat.utils.timer_calculator import Timer
from src.common.logger_manager import get_logger
from ..message_receive.chat_stream import chat_manager
from src.person_info.relationship_manager import relationship_manager
import math
import re
import traceback
from typing import Optional, Tuple, Dict, Any
from maim_message import UserInfo
# from ..message_receive.message_buffer import message_buffer
from ..utils.timer_calculator import Timer
from src.person_info.relationship_manager import relationship_manager
from typing import Optional, Tuple, Dict, Any
logger = get_logger("chat")
@ -109,7 +112,7 @@ async def _calculate_interest(message: MessageRecv) -> Tuple[float, bool]:
# return "seglist"
def _check_ban_words(text: str, chat, userinfo) -> bool:
def _check_ban_words(text: str, chat: ChatStream, userinfo: UserInfo) -> bool:
"""检查消息是否包含过滤词
Args:
@ -129,7 +132,7 @@ def _check_ban_words(text: str, chat, userinfo) -> bool:
return False
def _check_ban_regex(text: str, chat, userinfo) -> bool:
def _check_ban_regex(text: str, chat: ChatStream, userinfo: UserInfo) -> bool:
"""检查消息是否匹配过滤正则表达式
Args:
@ -141,7 +144,7 @@ def _check_ban_regex(text: str, chat, userinfo) -> bool:
bool: 是否匹配过滤正则
"""
for pattern in global_config.message_receive.ban_msgs_regex:
if pattern.search(text):
if re.search(pattern, text):
chat_name = chat.group_info.group_name if chat.group_info else "私聊"
logger.info(f"[{chat_name}]{userinfo.user_nickname}:{text}")
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")

View File

@ -96,6 +96,7 @@ class ChattingInfoProcessor(BaseProcessor):
async def chat_compress(self, obs: ChattingObservation):
if obs.compressor_prompt:
summary = ""
try:
summary_result, _, _ = await self.model_summary.generate_response(obs.compressor_prompt)
summary = "没有主题的闲聊" # 默认值

View File

@ -227,7 +227,7 @@ class MindProcessor(BaseProcessor):
# 记录初步思考结果
logger.debug(f"{self.log_prefix} 思考prompt: \n{prompt}\n")
logger.info(f"{self.log_prefix} 思考结果: {content}")
logger.info(f"{self.log_prefix} 聊天规划: {content}")
self.update_current_mind(content)
return content

View File

@ -185,8 +185,8 @@ class SelfProcessor(BaseProcessor):
if content == "None":
content = ""
# 记录初步思考结果
logger.debug(f"{self.log_prefix} 自我识别prompt: \n{prompt}\n")
logger.info(f"{self.log_prefix} 自我识别结果: {content}")
# logger.debug(f"{self.log_prefix} 自我识别prompt: \n{prompt}\n")
logger.info(f"{self.log_prefix} 自我认知: {content}")
return content

View File

@ -93,7 +93,7 @@ class WorkingMemoryProcessor(BaseProcessor):
# chat_info_truncate = observation.talking_message_str_truncate
if not working_memory:
logger.warning(f"{self.log_prefix} 没有找到工作记忆对象")
logger.debug(f"{self.log_prefix} 没有找到工作记忆对象")
mind_info = MindInfo()
return [mind_info]
except Exception as e:
@ -127,7 +127,7 @@ class WorkingMemoryProcessor(BaseProcessor):
# 调用LLM处理记忆
content = ""
try:
logger.debug(f"{self.log_prefix} 处理工作记忆的prompt: {prompt}")
# logger.debug(f"{self.log_prefix} 处理工作记忆的prompt: {prompt}")
content, _ = await self.llm_model.generate_response_async(prompt=prompt)
if not content:
@ -180,7 +180,7 @@ class WorkingMemoryProcessor(BaseProcessor):
working_memory_info.add_working_memory(memory_str)
logger.debug(f"{self.log_prefix} 取得工作记忆: {memory_str}")
else:
logger.warning(f"{self.log_prefix} 没有找到工作记忆")
logger.debug(f"{self.log_prefix} 没有找到工作记忆")
# 根据聊天内容添加新记忆
if new_memory:

View File

@ -107,11 +107,11 @@ class MemoryActivator:
cached_keywords=cached_keywords_str,
)
logger.debug(f"prompt: {prompt}")
# logger.debug(f"prompt: {prompt}")
response = await self.summary_model.generate_response(prompt)
logger.debug(f"response: {response}")
# logger.debug(f"response: {response}")
# 只取response的第一个元素字符串
response_str = response[0]
@ -127,7 +127,7 @@ class MemoryActivator:
# 添加新的关键词到缓存
self.cached_keywords.update(keywords)
logger.debug(f"更新关键词缓存: {self.cached_keywords}")
logger.debug(f"当前激活的记忆关键词: {self.cached_keywords}")
# 调用记忆系统获取相关记忆
related_memory = await HippocampusManager.get_instance().get_memory_from_topic(

View File

@ -100,6 +100,7 @@ class ReplyAction(BaseAction):
"emojis": "微笑" # 表情关键词列表(可选)
}
"""
logger.info(f"{self.log_prefix} 决定回复: {self.reasoning}")
# 从聊天观察获取锚定消息
chatting_observation: ChattingObservation = next(

View File

@ -130,6 +130,7 @@ class ActionPlanner:
current_mind = ""
cycle_info = ""
structured_info = ""
is_group_chat = True
for info in all_plan_info:
if isinstance(info, ObsInfo):
observed_messages = info.get_talking_message()

View File

@ -399,7 +399,7 @@ class MemoryManager:
try:
# 调用LLM修改总结、概括和要点
response, _ = await self.llm_summarizer.generate_response_async(prompt)
logger.info(f"精简记忆响应: {response}")
logger.debug(f"精简记忆响应: {response}")
# 使用repair_json处理响应
try:
# 修复JSON格式

View File

@ -87,8 +87,6 @@ class BackgroundTaskManager:
),
]
)
else:
logger.info("聊天模式为 normal跳过启动清理任务、私聊激活任务和专注评估任务")
# 统一启动所有任务
for task_func, log_level, log_msg, task_attr_name in task_configs:

View File

@ -179,7 +179,7 @@ class ChattingObservation(Observation):
"processed_plain_text": find_msg.get("processed_plain_text"),
}
find_rec_msg = MessageRecv(message_dict)
logger.debug(f"锚定消息处理后find_rec_msg: {find_rec_msg}")
# logger.debug(f"锚定消息处理后find_rec_msg: {find_rec_msg}")
return find_rec_msg
async def observe(self):

View File

@ -78,18 +78,13 @@ class SubHeartflow:
logger.debug(
f"SubHeartflow {self.chat_id} initialized: is_group={self.is_group_chat}, target_info={self.chat_target_info}"
)
# --- End using utility function ---
# Initialize interest system (existing logic)
# await self.interest_chatting.initialize()
# logger.debug(f"{self.log_prefix} InterestChatting 实例已初始化。")
# 根据配置决定初始状态
if global_config.chat.chat_mode == "focus":
logger.info(f"{self.log_prefix} 配置为 focus 模式,将直接尝试进入 FOCUSED 状态。")
logger.debug(f"{self.log_prefix} 配置为 focus 模式,将直接尝试进入 FOCUSED 状态。")
await self.change_chat_state(ChatState.FOCUSED)
else: # "auto" 或其他模式保持原有逻辑或默认为 NORMAL
logger.info(f"{self.log_prefix} 配置为 auto 或其他模式,将尝试进入 NORMAL 状态。")
logger.debug(f"{self.log_prefix} 配置为 auto 或其他模式,将尝试进入 NORMAL 状态。")
await self.change_chat_state(ChatState.NORMAL)
def update_last_chat_state_time(self):
@ -116,6 +111,8 @@ class SubHeartflow:
"""
await self._stop_heart_fc_chat() # 确保 专注聊天已停止
self.interest_dict.clear()
log_prefix = self.log_prefix
try:
# 获取聊天流并创建 NormalChat 实例 (同步部分)
@ -281,9 +278,9 @@ class SubHeartflow:
self.update_last_chat_state_time()
self.history_chat_state.append((current_state, self.chat_state_last_time))
logger.info(
f"{log_prefix} 麦麦的聊天状态从 {current_state.value} (持续了 {int(self.chat_state_last_time)} 秒) 变更为 {new_state.value}"
)
# logger.info(
# f"{log_prefix} 麦麦的聊天状态从 {current_state.value} (持续了 {int(self.chat_state_last_time)} 秒) 变更为 {new_state.value}"
# )
self.chat_state.chat_status = new_state
self.chat_state_last_time = 0

View File

@ -223,8 +223,9 @@ class MessageManager:
# f"[message.apply_set_reply_logic:{message.apply_set_reply_logic},message.is_head:{message.is_head},thinking_messages_count:{thinking_messages_count},thinking_messages_length:{thinking_messages_length},message.is_private_message():{message.is_private_message()}]"
# )
if (
message.apply_set_reply_logic # 检查标记
and message.is_head
# message.apply_set_reply_logic # 检查标记
# and message.is_head
message.is_head
and (thinking_messages_count > 3 or thinking_messages_length > 200)
and not message.is_private_message()
):

View File

@ -39,6 +39,7 @@ class NormalChat:
self.chat_target_info: Optional[dict] = None
self.willing_amplifier = 1
self.start_time = time.time()
# Other sync initializations
self.gpt = NormalChatGenerator()
@ -64,7 +65,7 @@ class NormalChat:
self.is_group_chat, self.chat_target_info = await get_chat_type_and_target_info(self.stream_id)
self.stream_name = chat_manager.get_stream_name(self.stream_id) or self.stream_id
self._initialized = True
logger.info(f"[{self.stream_name}] NormalChat 实例 initialize 完成 (异步部分)。")
logger.debug(f"[{self.stream_name}] NormalChat 初始化完成 (异步部分)。")
# 改为实例方法
async def _create_thinking_message(self, message: MessageRecv, timestamp: Optional[float] = None) -> str:
@ -208,7 +209,10 @@ class NormalChat:
for msg_id, (message, interest_value, is_mentioned) in items_to_process:
try:
# 处理消息
self.adjust_reply_frequency()
if time.time() - self.start_time > 600:
self.adjust_reply_frequency(duration=600 / 60)
else:
self.adjust_reply_frequency(duration=(time.time() - self.start_time) / 60)
await self.normal_response(
message=message,
@ -256,7 +260,7 @@ class NormalChat:
logger.info(
f"[{mes_name}]"
f"{message.message_info.user_info.user_nickname}:" # 使用 self.chat_stream
f"{message.processed_plain_text}[回复概率:{reply_probability * 100:.1f}%]"
f"{message.processed_plain_text}[兴趣:{interested_rate:.2f}][回复概率:{reply_probability * 100:.1f}%]"
)
do_reply = False
response_set = None # 初始化 response_set
@ -304,7 +308,7 @@ class NormalChat:
willing_manager.delete(message.message_info.message_id)
return # 不执行后续步骤
logger.info(f"[{self.stream_name}] 回复内容: {response_set}")
# logger.info(f"[{self.stream_name}] 回复内容: {response_set}")
if self._disabled:
logger.info(f"[{self.stream_name}] 已停用,忽略 normal_response。")
@ -357,7 +361,7 @@ class NormalChat:
trigger_msg = message.processed_plain_text
response_msg = " ".join(response_set)
logger.info(
f"[{self.stream_name}] 触发消息: {trigger_msg[:20]}... | 推理消息: {response_msg[:20]}... | 性能计时: {timing_str}"
f"[{self.stream_name}]回复消息: {trigger_msg[:30]}... | 回复内容: {response_msg[:30]}... | 计时: {timing_str}"
)
elif not do_reply:
# 不回复处理
@ -376,7 +380,7 @@ class NormalChat:
self._disabled = False # 启动时重置停用标志
if self._chat_task is None or self._chat_task.done():
logger.info(f"[{self.stream_name}] 开始处理兴趣消息...")
# logger.info(f"[{self.stream_name}] 开始处理兴趣消息...")
polling_task = asyncio.create_task(self._reply_interested_message())
polling_task.add_done_callback(lambda t: self._handle_task_completion(t))
self._chat_task = polling_task
@ -483,21 +487,39 @@ class NormalChat:
调整回复频率
"""
# 获取最近30分钟内的消息统计
print(f"willing_amplifier: {self.willing_amplifier}")
stats = get_recent_message_stats(minutes=duration, chat_id=self.stream_id)
bot_reply_count = stats["bot_reply_count"]
print(f"[{self.stream_name}] 最近{duration}分钟内回复数量: {bot_reply_count}")
total_message_count = stats["total_message_count"]
print(f"[{self.stream_name}] 最近{duration}分钟内消息总数: {total_message_count}")
if total_message_count == 0:
return
logger.debug(
f"[{self.stream_name}]({self.willing_amplifier}) 最近{duration}分钟 回复数量: {bot_reply_count},消息总数: {total_message_count}"
)
# 计算回复频率
_reply_frequency = bot_reply_count / total_message_count
differ = global_config.normal_chat.talk_frequency - (bot_reply_count / duration)
# 如果回复频率低于0.5,增加回复概率
if bot_reply_count / duration < global_config.normal_chat.talk_frequency:
# differ = global_config.normal_chat.talk_frequency - reply_frequency
logger.info(f"[{self.stream_name}] 回复频率低于{global_config.normal_chat.talk_frequency},增加回复概率")
self.willing_amplifier += 0.1
else:
logger.info(f"[{self.stream_name}] 回复频率高于{global_config.normal_chat.talk_frequency},减少回复概率")
self.willing_amplifier -= 0.1
if differ > 0.1:
mapped = 1 + (differ - 0.1) * 4 / 0.9
mapped = max(1, min(5, mapped))
logger.info(
f"[{self.stream_name}] 回复频率低于{global_config.normal_chat.talk_frequency}增加回复概率differ={differ:.3f},映射值={mapped:.2f}"
)
self.willing_amplifier += mapped * 0.1 # 你可以根据实际需要调整系数
elif differ < -0.1:
mapped = 1 - (differ + 0.1) * 4 / 0.9
mapped = max(1, min(5, mapped))
logger.info(
f"[{self.stream_name}] 回复频率高于{global_config.normal_chat.talk_frequency}减少回复概率differ={differ:.3f},映射值={mapped:.2f}"
)
self.willing_amplifier -= mapped * 0.1
if self.willing_amplifier > 5:
self.willing_amplifier = 5
elif self.willing_amplifier < 0.1:
self.willing_amplifier = 0.1

View File

@ -11,7 +11,7 @@ from src.chat.utils.info_catcher import info_catcher_manager
from src.person_info.person_info import person_info_manager
logger = get_logger("llm")
logger = get_logger("normal_chat_response")
class NormalChatGenerator:
@ -40,25 +40,25 @@ class NormalChatGenerator:
"""根据当前模型类型选择对应的生成函数"""
# 从global_config中获取模型概率值并选择模型
if random.random() < global_config.normal_chat.normal_chat_first_probability:
self.current_model_type = "深深地"
current_model = self.model_reasoning
self.current_model_name = current_model.model_name
else:
self.current_model_type = "浅浅的"
current_model = self.model_normal
self.current_model_name = current_model.model_name
logger.info(
f"{self.current_model_type}思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}"
f"{self.current_model_name}思考:{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, thinking_id)
if model_response:
logger.info(f"{global_config.bot.nickname}回复是:{model_response}")
logger.debug(f"{global_config.bot.nickname}原始回复是:{model_response}")
model_response = await self._process_response(model_response)
return model_response
else:
logger.info(f"{self.current_model_type}思考,失败")
logger.info(f"{self.current_model_name}思考,失败")
return None
async def _generate_response_with_model(self, message: MessageThinking, model: LLMRequest, thinking_id: str):

View File

@ -441,6 +441,7 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
处理 回复<aaa:bbb> @<aaa:bbb> 字段将bbb映射为匿名占位符
"""
if not messages:
print("111111111111没有消息无法构建匿名消息")
return ""
person_map = {}
@ -448,9 +449,18 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
output_lines = []
def get_anon_name(platform, user_id):
# print(f"get_anon_name: platform:{platform}, user_id:{user_id}")
# print(f"global_config.bot.qq_account:{global_config.bot.qq_account}")
if user_id == global_config.bot.qq_account:
# print("SELF11111111111111")
return "SELF"
person_id = person_info_manager.get_person_id(platform, user_id)
try:
person_id = person_info_manager.get_person_id(platform, user_id)
except Exception as e:
person_id = None
if not person_id:
return "?"
if person_id not in person_map:
nonlocal current_char
person_map[person_id] = chr(current_char)
@ -458,56 +468,76 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
return person_map[person_id]
for msg in messages:
user_info = msg.get("user_info", {})
platform = user_info.get("platform")
user_id = user_info.get("user_id")
timestamp = msg.get("time")
if msg.get("display_message"):
content = msg.get("display_message")
else:
content = msg.get("processed_plain_text", "")
try:
# user_info = msg.get("user_info", {})
platform = msg.get("chat_info_platform")
user_id = msg.get("user_id")
timestamp = msg.get("time")
# print(f"msg:{msg}")
# print(f"platform:{platform}")
# print(f"user_id:{user_id}")
# print(f"timestamp:{timestamp}")
if msg.get("display_message"):
content = msg.get("display_message")
else:
content = msg.get("processed_plain_text", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if "" in content:
content = content.replace("", "")
if not all([platform, user_id, timestamp is not None]):
# if not all([platform, user_id, timestamp is not None]):
# continue
anon_name = get_anon_name(platform, user_id)
# print(f"anon_name:{anon_name}")
# 处理 回复<aaa:bbb>
reply_pattern = r"回复<([^:<>]+):([^:<>]+)>"
match = re.search(reply_pattern, content)
if match:
# print(f"发现回复match:{match}")
bbb = match.group(2)
try:
anon_reply = get_anon_name(platform, bbb)
# print(f"anon_reply:{anon_reply}")
except Exception:
anon_reply = "?"
content = re.sub(reply_pattern, f"回复 {anon_reply}", content, count=1)
# 处理 @<aaa:bbb>无嵌套def
at_pattern = r"@<([^:<>]+):([^:<>]+)>"
at_matches = list(re.finditer(at_pattern, content))
if at_matches:
# print(f"发现@match:{at_matches}")
new_content = ""
last_end = 0
for m in at_matches:
new_content += content[last_end:m.start()]
bbb = m.group(2)
try:
anon_at = get_anon_name(platform, bbb)
# print(f"anon_at:{anon_at}")
except Exception:
anon_at = "?"
new_content += f"@{anon_at}"
last_end = m.end()
new_content += content[last_end:]
content = new_content
header = f"{anon_name}"
output_lines.append(header)
stripped_line = content.strip()
if stripped_line:
if stripped_line.endswith(""):
stripped_line = stripped_line[:-1]
output_lines.append(f"{stripped_line}")
# print(f"output_lines:{output_lines}")
output_lines.append("\n")
except Exception:
continue
anon_name = get_anon_name(platform, user_id)
# 处理 回复<aaa:bbb>
reply_pattern = r"回复<([^:<>]+):([^:<>]+)>"
def reply_replacer(match, platform=platform):
# aaa = match.group(1)
bbb = match.group(2)
anon_reply = get_anon_name(platform, bbb) # noqa
return f"回复 {anon_reply}"
content = re.sub(reply_pattern, reply_replacer, content, count=1)
# 处理 @<aaa:bbb>
at_pattern = r"@<([^:<>]+):([^:<>]+)>"
def at_replacer(match, platform=platform):
# aaa = match.group(1)
bbb = match.group(2)
anon_at = get_anon_name(platform, bbb) # noqa
return f"@{anon_at}"
content = re.sub(at_pattern, at_replacer, content)
header = f"{anon_name}"
output_lines.append(header)
stripped_line = content.strip()
if stripped_line:
if stripped_line.endswith(""):
stripped_line = stripped_line[:-1]
output_lines.append(f"{stripped_line}")
output_lines.append("\n")
formatted_string = "".join(output_lines).strip()
return formatted_string

View File

@ -100,7 +100,7 @@ class InfoCatcher:
time_end = message_end.message_info.time
chat_id = message_start.chat_stream.stream_id
print(f"查询参数: time_start={time_start}, time_end={time_end}, chat_id={chat_id}")
# print(f"查询参数: time_start={time_start}, time_end={time_end}, chat_id={chat_id}")
messages_between_query = (
Messages.select()
@ -109,10 +109,10 @@ class InfoCatcher:
)
result = list(messages_between_query)
print(f"查询结果数量: {len(result)}")
if result:
print(f"第一条消息时间: {result[0].time}")
print(f"最后一条消息时间: {result[-1].time}")
# print(f"查询结果数量: {len(result)}")
# if result:
# print(f"第一条消息时间: {result[0].time}")
# print(f"最后一条消息时间: {result[-1].time}")
return result
except Exception as e:
print(f"获取消息时出错: {str(e)}")

View File

@ -225,22 +225,37 @@ SCHEDULE_STYLE_CONFIG = {
},
}
LLM_STYLE_CONFIG = {
NORMAL_CHAT_RESPONSE_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<light-yellow>麦麦组织语言</light-yellow> | "
"<light-yellow>普通水群回复</light-yellow> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦组织语言 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群回复 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <light-green>麦麦组织语言</light-green> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦组织语言 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <light-green>普通水群回复</light-green> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群回复 | {message}",
},
}
EXPRESS_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<light-yellow>麦麦表达</light-yellow> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦表达 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #E595FF>麦麦表达</fg #E595FF> | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦表达 | {message}",
},
}
# Topic日志样式配置
TOPIC_STYLE_CONFIG = {
@ -282,14 +297,14 @@ NORMAL_CHAT_STYLE_CONFIG = {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<green>一般水群</green> | "
"<green>普通水群</green> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 一般水群 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #00B741>一般水群</fg #00B741> | <fg #00B741>{message}</fg #00B741>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 一般水群 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #00B741>普通水群</fg #00B741> | <fg #00B741>{message}</fg #00B741>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 普通水群 | {message}",
},
}
@ -310,6 +325,7 @@ FOCUS_CHAT_STYLE_CONFIG = {
},
}
REMOTE_STYLE_CONFIG = {
"advanced": {
"console_format": (
@ -530,19 +546,19 @@ EMOJI_STYLE_CONFIG = {
},
}
MAI_STATE_CONFIG = {
STATISTIC_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<white>{time:YYYY-MM-DD HH:mm:ss}</white> | "
"<level>{level: <8}</level> | "
"<light-blue>麦麦状态</light-blue> | "
"<light-blue>麦麦统计</light-blue> | "
"<level>{message}</level>"
),
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦状态 | {message}",
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦统计 | {message}",
},
"simple": {
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #66CCFF>麦麦状态 | {message} </fg #66CCFF>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦状态 | {message}",
"console_format": "<level>{time:HH:mm:ss}</level> | <fg #66CCFF>麦麦统计 | {message} </fg #66CCFF>", # noqa: E501
"file_format": "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 麦麦统计 | {message}",
},
}
@ -906,7 +922,9 @@ MEMORY_STYLE_CONFIG = MEMORY_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else MEMORY
CHAT_STREAM_STYLE_CONFIG = CHAT_STREAM_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CHAT_STREAM_STYLE_CONFIG["advanced"]
TOPIC_STYLE_CONFIG = TOPIC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else TOPIC_STYLE_CONFIG["advanced"]
SENDER_STYLE_CONFIG = SENDER_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SENDER_STYLE_CONFIG["advanced"]
LLM_STYLE_CONFIG = LLM_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else LLM_STYLE_CONFIG["advanced"]
NORMAL_CHAT_RESPONSE_STYLE_CONFIG = (
NORMAL_CHAT_RESPONSE_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else NORMAL_CHAT_RESPONSE_STYLE_CONFIG["advanced"]
)
CHAT_STYLE_CONFIG = CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CHAT_STYLE_CONFIG["advanced"]
MOOD_STYLE_CONFIG = MOOD_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else MOOD_STYLE_CONFIG["advanced"]
RELATION_STYLE_CONFIG = RELATION_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else RELATION_STYLE_CONFIG["advanced"]
@ -919,7 +937,7 @@ SUB_HEARTFLOW_MIND_STYLE_CONFIG = (
SUB_HEARTFLOW_MIND_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SUB_HEARTFLOW_MIND_STYLE_CONFIG["advanced"]
)
WILLING_STYLE_CONFIG = WILLING_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else WILLING_STYLE_CONFIG["advanced"]
MAI_STATE_CONFIG = MAI_STATE_CONFIG["simple"] if SIMPLE_OUTPUT else MAI_STATE_CONFIG["advanced"]
STATISTIC_STYLE_CONFIG = STATISTIC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else STATISTIC_STYLE_CONFIG["advanced"]
CONFIG_STYLE_CONFIG = CONFIG_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else CONFIG_STYLE_CONFIG["advanced"]
TOOL_USE_STYLE_CONFIG = TOOL_USE_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else TOOL_USE_STYLE_CONFIG["advanced"]
PFC_STYLE_CONFIG = PFC_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else PFC_STYLE_CONFIG["advanced"]
@ -971,6 +989,7 @@ INTEREST_CHAT_STYLE_CONFIG = (
)
NORMAL_CHAT_STYLE_CONFIG = NORMAL_CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else NORMAL_CHAT_STYLE_CONFIG["advanced"]
FOCUS_CHAT_STYLE_CONFIG = FOCUS_CHAT_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else FOCUS_CHAT_STYLE_CONFIG["advanced"]
EXPRESS_STYLE_CONFIG = EXPRESS_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else EXPRESS_STYLE_CONFIG["advanced"]
def is_registered_module(record: dict) -> bool:

View File

@ -9,7 +9,6 @@ from src.common.logger import (
RELATION_STYLE_CONFIG,
CONFIG_STYLE_CONFIG,
HEARTFLOW_STYLE_CONFIG,
LLM_STYLE_CONFIG,
CHAT_STYLE_CONFIG,
EMOJI_STYLE_CONFIG,
SUB_HEARTFLOW_STYLE_CONFIG,
@ -20,7 +19,7 @@ from src.common.logger import (
PERSON_INFO_STYLE_CONFIG,
WILLING_STYLE_CONFIG,
PFC_ACTION_PLANNER_STYLE_CONFIG,
MAI_STATE_CONFIG,
STATISTIC_STYLE_CONFIG,
NORMAL_CHAT_STYLE_CONFIG,
FOCUS_CHAT_STYLE_CONFIG,
LPMM_STYLE_CONFIG,
@ -47,6 +46,8 @@ from src.common.logger import (
INIT_STYLE_CONFIG,
INTEREST_CHAT_STYLE_CONFIG,
API_SERVER_STYLE_CONFIG,
NORMAL_CHAT_RESPONSE_STYLE_CONFIG,
EXPRESS_STYLE_CONFIG,
)
# 可根据实际需要补充更多模块配置
@ -60,7 +61,7 @@ MODULE_LOGGER_CONFIGS = {
"relation": RELATION_STYLE_CONFIG, # 关系
"config": CONFIG_STYLE_CONFIG, # 配置
"heartflow": HEARTFLOW_STYLE_CONFIG, # 麦麦大脑袋
"llm": LLM_STYLE_CONFIG, # 麦麦组织语言
"normal_chat_response": NORMAL_CHAT_RESPONSE_STYLE_CONFIG, # 麦麦组织语言
"chat": CHAT_STYLE_CONFIG, # 见闻
"emoji": EMOJI_STYLE_CONFIG, # 表情包
"sub_heartflow": SUB_HEARTFLOW_STYLE_CONFIG, # 麦麦水群
@ -71,7 +72,7 @@ MODULE_LOGGER_CONFIGS = {
"person_info": PERSON_INFO_STYLE_CONFIG, # 人物信息
"willing": WILLING_STYLE_CONFIG, # 意愿
"pfc_action_planner": PFC_ACTION_PLANNER_STYLE_CONFIG, # PFC私聊规划
"mai_state": MAI_STATE_CONFIG, # 麦麦状态
"statistic": STATISTIC_STYLE_CONFIG, # 麦麦统计
"lpmm": LPMM_STYLE_CONFIG, # LPMM
"hfc": HFC_STYLE_CONFIG, # HFC
"observation": OBSERVATION_STYLE_CONFIG, # 聊天观察
@ -98,6 +99,7 @@ MODULE_LOGGER_CONFIGS = {
"api": API_SERVER_STYLE_CONFIG, # API服务器
"normal_chat": NORMAL_CHAT_STYLE_CONFIG, # 一般水群
"focus_chat": FOCUS_CHAT_STYLE_CONFIG, # 专注水群
"expressor": EXPRESS_STYLE_CONFIG, # 麦麦表达
# ...如有更多模块,继续添加...
}

View File

@ -16,7 +16,7 @@ class MessageProcessor:
@staticmethod
def _check_ban_words(text: str, chat, userinfo) -> bool:
"""检查消息中是否包含过滤词"""
for word in global_config.chat.ban_words:
for word in global_config.message_receive.ban_words:
if word in text:
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]{userinfo.user_nickname}:{text}"

View File

@ -45,7 +45,7 @@ class MainSystem:
# 其他初始化任务
await asyncio.gather(self._init_components())
logger.success("系统初始化完成")
logger.debug("系统初始化完成")
async def _init_components(self):
"""初始化其他组件"""
@ -73,7 +73,7 @@ class MainSystem:
await async_task_manager.add_task(MoodPrintTask())
# 检查并清除person_info冗余字段启动个人习惯推断
await person_info_manager.del_all_undefined_field()
# await person_info_manager.del_all_undefined_field()
asyncio.create_task(person_info_manager.personal_habit_deduction())
# 启动愿望管理器
@ -142,29 +142,30 @@ class MainSystem:
"""记忆遗忘任务"""
while True:
await asyncio.sleep(global_config.memory.forget_memory_interval)
print("\033[1;32m[记忆遗忘]\033[0m 开始遗忘记忆...")
logger.info("[记忆遗忘] 开始遗忘记忆...")
await HippocampusManager.get_instance().forget_memory(
percentage=global_config.memory.memory_forget_percentage
)
print("\033[1;32m[记忆遗忘]\033[0m 记忆遗忘完成")
logger.info("[记忆遗忘] 记忆遗忘完成")
@staticmethod
async def consolidate_memory_task():
"""记忆整合任务"""
while True:
await asyncio.sleep(global_config.memory.consolidate_memory_interval)
print("\033[1;32m[记忆整合]\033[0m 开始整合记忆...")
logger.info("[记忆整合] 开始整合记忆...")
await HippocampusManager.get_instance().consolidate_memory()
print("\033[1;32m[记忆整合]\033[0m 记忆整合完成")
logger.info("[记忆整合] 记忆整合完成")
@staticmethod
async def learn_and_store_expression_task():
"""学习并存储表达方式任务"""
while True:
await asyncio.sleep(global_config.expression.learning_interval)
print("\033[1;32m[表达方式学习]\033[0m 开始学习表达方式...")
await expression_learner.learn_and_store_expression()
print("\033[1;32m[表达方式学习]\033[0m 表达方式学习完成")
if global_config.expression.enable_expression_learning:
logger.info("[表达方式学习] 开始学习表达方式...")
await expression_learner.learn_and_store_expression()
logger.info("[表达方式学习] 表达方式学习完成")
# async def print_mood_task(self):
# """打印情绪状态"""

View File

@ -103,7 +103,7 @@ class AsyncTaskManager:
) # 添加完成回调函数-用户自定义或默认的FallBack
self.tasks[task.task_name] = task_inst # 将任务添加到任务列表
logger.info(f"已启动任务 '{task.task_name}'")
logger.debug(f"已启动任务 '{task.task_name}'")
def get_tasks_status(self) -> Dict[str, Dict[str, str]]:
"""

View File

@ -425,13 +425,13 @@ class PersonInfoManager:
return result
@staticmethod
async def del_all_undefined_field():
"""删除所有项里的未定义字段 - 对于Peewee (SQL),此操作通常不适用,因为模式是固定的。"""
logger.info(
"del_all_undefined_field: 对于使用Peewee的SQL数据库此操作通常不适用或不需要因为表结构是预定义的。"
)
return
# @staticmethod
# async def del_all_undefined_field():
# """删除所有项里的未定义字段 - 对于Peewee (SQL),此操作通常不适用,因为模式是固定的。"""
# logger.info(
# "del_all_undefined_field: 对于使用Peewee的SQL数据库此操作通常不适用或不需要因为表结构是预定义的。"
# )
# return
@staticmethod
async def get_specific_value_list(

View File

@ -56,14 +56,14 @@ class RelationshipManager:
self.positive_feedback_value = 0
if abs(self.positive_feedback_value) > 1:
logger.info(f"触发mood变更增益当前增益系数{self.gain_coefficient[abs(self.positive_feedback_value)]}")
logger.debug(f"触发mood变更增益当前增益系数{self.gain_coefficient[abs(self.positive_feedback_value)]}")
def mood_feedback(self, value):
"""情绪反馈"""
mood_manager = self.mood_manager
mood_gain = mood_manager.current_mood.valence**2 * math.copysign(1, value * mood_manager.current_mood.valence)
value += value * mood_gain
logger.info(f"当前relationship增益系数{mood_gain:.3f}")
logger.debug(f"当前relationship增益系数{mood_gain:.3f}")
return value
def feedback_to_mood(self, mood_value):

View File

@ -12,8 +12,8 @@ class MuteAction(PluginAction):
action_name = "mute_action"
action_description = "如果某人违反了公序良俗,或者别人戳你太多,或者某人刷屏,一定要禁言某人,如果你很生气,可以禁言某人,可以自选禁言时长,视严重程度而定。"
action_parameters = {
"target": "禁言对象,输入你要禁言的对象的名字,必填",
"duration": "禁言时长,输入你要禁言的时长(秒),单位为秒,必填,必须为数字",
"target": "禁言对象,必填,输入你要禁言的对象的名字",
"duration": "禁言时长,必填,输入你要禁言的时长(秒),单位为秒,必须为数字",
"reason": "禁言理由,可选",
}
action_require = [
@ -24,8 +24,8 @@ class MuteAction(PluginAction):
"当你想回避某个话题时使用",
]
default = True # 默认动作,是否手动添加到使用集
# associated_types = ["command", "text"]
associated_types = ["text"]
associated_types = ["command", "text"]
# associated_types = ["text"]
async def process(self) -> Tuple[bool, str]:
"""处理群聊禁言动作"""

View File

@ -1,20 +1,15 @@
import os
CONFIG_CONTENT = """\
# 请替换为您的火山引擎 Access Key ID
volcano_ak = "YOUR_VOLCANO_ENGINE_ACCESS_KEY_ID_HERE"
# 请替换为您的火山引擎 Secret Access Key
volcano_sk = "YOUR_VOLCANO_ENGINE_SECRET_ACCESS_KEY_HERE"
# 火山方舟 API 的基础 URL
base_url = "https://ark.cn-beijing.volces.com/api/v3"
# 用于图片生成的API密钥
volcano_generate_api_key = "YOUR_VOLCANO_GENERATE_API_KEY_HERE"
# 默认图片生成模型
default_model = "doubao-seedream-3-0-t2i-250415"
# 默认图片尺寸
default_size = "1024x1024"
# 用于图片生成的API密钥
# PicAction 当前配置为在HTTP请求体和Authorization头中使用此密钥。
# 如果您的API认证方式不同请相应调整或移除。
volcano_generate_api_key = "YOUR_VOLCANO_GENERATE_API_KEY_HERE"
# 是否默认开启水印
default_watermark = true
@ -38,7 +33,7 @@ def generate_config():
with open(config_file_path, "w", encoding="utf-8") as f:
f.write(CONFIG_CONTENT)
print(f"配置文件已生成: {config_file_path}")
print("请记得编辑该文件,填入您的火山引擎 AK/SK 和 API 密钥。")
print("请记得编辑该文件,填入您的火山引擎API 密钥。")
except IOError as e:
print(f"错误:无法写入配置文件 {config_file_path}。原因: {e}")
else:

View File

@ -22,7 +22,7 @@ class PicAction(PluginAction):
"""根据描述使用火山引擎HTTP API生成图片的动作处理类"""
action_name = "pic_action"
action_description = "可以根据特定的描述,使用火山引擎模型生成并发送一张图片 (通过HTTP API)"
action_description = "可以根据特定的描述,生成并发送一张图片,如果没提供描述,就根据聊天内容生成"
action_parameters = {
"description": "图片描述,输入你想要生成并发送的图片的描述,必填",
"size": "图片尺寸,例如 '1024x1024' (可选, 默认从配置或 '1024x1024')",
@ -31,7 +31,7 @@ class PicAction(PluginAction):
"当有人要求你生成并发送一张图片时使用",
"当有人让你画一张图时使用",
]
default = False
default = True
action_config_file_name = "pic_action_config.toml"
def __init__(

View File

@ -1,24 +0,0 @@
# 请替换为您的火山引擎 Access Key ID
volcano_ak = "YOUR_VOLCANO_ENGINE_ACCESS_KEY_ID_HERE"
# 请替换为您的火山引擎 Secret Access Key
volcano_sk = "YOUR_VOLCANO_ENGINE_SECRET_ACCESS_KEY_HERE"
# 火山方舟 API 的基础 URL
base_url = "https://ark.cn-beijing.volces.com/api/v3"
# 默认图片生成模型
default_model = "doubao-seedream-3-0-t2i-250415"
# 默认图片尺寸
default_size = "1024x1024"
# 用于图片生成的API密钥
# PicAction 当前配置为在HTTP请求体和Authorization头中使用此密钥。
# 如果您的API认证方式不同请相应调整或移除。
volcano_generate_api_key = "YOUR_VOLCANO_GENERATE_API_KEY_HERE"
# 是否默认开启水印
default_watermark = true
# 默认引导强度
default_guidance_scale = 2.5
# 默认随机种子
default_seed = 42
# 更多插件特定配置可以在此添加...
# custom_parameter = "some_value"

View File

@ -15,7 +15,7 @@ version = "2.6.0"
[bot]
qq_account = 1145141919810
nickname = "麦麦"
alias_names = ["麦叠", "牢麦"] #仅在 专注聊天 有效
alias_names = ["麦叠", "牢麦"]
[personality]
personality_core = "是一个积极向上的女大学生" # 建议50字以内
@ -65,10 +65,9 @@ ban_words = [
]
ban_msgs_regex = [
# 需要过滤的消息(原始消息)匹配的正则表达式,匹配到的消息将被过滤支持CQ码,若不了解正则表达式请勿修改
# 需要过滤的消息(原始消息)匹配的正则表达式,匹配到的消息将被过滤,若不了解正则表达式请勿修改
#"https?://[^\\s]+", # 匹配https链接
#"\\d{4}-\\d{2}-\\d{2}", # 匹配日期
# "\\[CQ:at,qq=\\d+\\]" # 匹配@
]
[normal_chat] #普通聊天
@ -95,7 +94,7 @@ talk_frequency_down_groups = [] #降低回复频率的群号码
think_interval = 3 # 思考间隔 单位秒,可以有效减少消耗
observation_context_size = 15 # 观察到的最长上下文大小,建议15太短太长都会导致脑袋尖尖
compressed_length = 5 # 不能大于chat.observation_context_size,心流上下文压缩的最短压缩长度超过心流观察到的上下文长度会压缩最短压缩长度为5
compressed_length = 5 # 不能大于observation_context_size,心流上下文压缩的最短压缩长度超过心流观察到的上下文长度会压缩最短压缩长度为5
compress_length_limit = 5 #最多压缩份数,超过该数值的压缩上下文会被删除
[focus_chat_processor] # 专注聊天处理器打开可以实现更多功能但是会增加token消耗
@ -215,7 +214,7 @@ pri_out = 0.35
#嵌入模型
[model.embedding]
name = "BAAI/bge-m3"
provider = "DEV"
provider = "SILICONFLOW"
pri_in = 0
pri_out = 0

View File

@ -1,20 +1,6 @@
HOST=127.0.0.1
PORT=8000
# 默认配置
# 如果工作在Docker下请改成 MONGODB_HOST=mongodb
MONGODB_HOST=127.0.0.1
MONGODB_PORT=27017
DATABASE_NAME=MegBot
# 也可以使用 URI 连接数据库(优先级比上面的高)
# MONGODB_URI=mongodb://127.0.0.1:27017/MegBot
# MongoDB 认证信息,若需要认证,请取消注释以下三行并填写正确的信息
# MONGODB_USERNAME=user
# MONGODB_PASSWORD=password
# MONGODB_AUTH_SOURCE=admin
#key and url
CHAT_ANY_WHERE_BASE_URL=https://api.chatanywhere.tech/v1
SILICONFLOW_BASE_URL=https://api.siliconflow.cn/v1/