Merge branch 'dev' of https://github.com/MaiM-with-u/MaiBot into dev
This commit is contained in:
@@ -57,5 +57,3 @@ class GetCurrentTaskTool(BaseTool):
|
||||
task_info = f"在 {start_time} 到 {end_time} 之间没有找到日程信息"
|
||||
|
||||
return {"name": "get_current_task", "content": f"日程信息: {task_info}"}
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from datetime import datetime
|
||||
|
||||
logger = get_module_logger("get_time_date")
|
||||
|
||||
|
||||
class GetCurrentDateTimeTool(BaseTool):
|
||||
"""获取当前时间、日期、年份和星期的工具"""
|
||||
|
||||
@@ -33,7 +34,5 @@ class GetCurrentDateTimeTool(BaseTool):
|
||||
|
||||
return {
|
||||
"name": "get_current_date_time",
|
||||
"content": f"当前时间: {current_time}, 日期: {current_date}, 年份: {current_year}, 星期: {current_weekday}"
|
||||
"content": f"当前时间: {current_time}, 日期: {current_date}, 年份: {current_year}, 星期: {current_weekday}",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,9 @@ class ToolUser:
|
||||
model=global_config.llm_tool_use, temperature=0.2, max_tokens=1000, request_type="tool_use"
|
||||
)
|
||||
|
||||
async def _build_tool_prompt(self, message_txt: str, sender_name: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None):
|
||||
async def _build_tool_prompt(
|
||||
self, message_txt: str, sender_name: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None
|
||||
):
|
||||
"""构建工具使用的提示词
|
||||
|
||||
Args:
|
||||
@@ -38,7 +40,7 @@ class ToolUser:
|
||||
# print(f"intol111111111111111111111111111111111222222222222mid_memory_info:{mid_memory_info}")
|
||||
else:
|
||||
mid_memory_info = ""
|
||||
|
||||
|
||||
new_messages = list(
|
||||
db.messages.find({"chat_id": chat_stream.stream_id, "time": {"$gt": time.time()}}).sort("time", 1).limit(15)
|
||||
)
|
||||
@@ -104,7 +106,9 @@ class ToolUser:
|
||||
logger.error(f"执行工具调用时发生错误: {str(e)}")
|
||||
return None
|
||||
|
||||
async def use_tool(self, message_txt: str, sender_name: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None):
|
||||
async def use_tool(
|
||||
self, message_txt: str, sender_name: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None
|
||||
):
|
||||
"""使用工具辅助思考,判断是否需要额外信息
|
||||
|
||||
Args:
|
||||
@@ -117,12 +121,7 @@ class ToolUser:
|
||||
"""
|
||||
try:
|
||||
# 构建提示词
|
||||
prompt = await self._build_tool_prompt(
|
||||
message_txt,
|
||||
sender_name,
|
||||
chat_stream,
|
||||
subheartflow
|
||||
)
|
||||
prompt = await self._build_tool_prompt(message_txt, sender_name, chat_stream, subheartflow)
|
||||
|
||||
# 定义可用工具
|
||||
tools = self._define_tools()
|
||||
@@ -170,10 +169,7 @@ class ToolUser:
|
||||
tool_name = result["name"]
|
||||
if tool_name not in structured_info:
|
||||
structured_info[tool_name] = []
|
||||
structured_info[tool_name].append({
|
||||
"name": result["name"],
|
||||
"content": result["content"]
|
||||
})
|
||||
structured_info[tool_name].append({"name": result["name"], "content": result["content"]})
|
||||
|
||||
# 如果有工具结果,返回结构化的信息
|
||||
if structured_info:
|
||||
|
||||
@@ -6,8 +6,10 @@ from src.plugins.config.config import global_config
|
||||
from src.common.database import db
|
||||
from src.common.logger import get_module_logger
|
||||
import traceback
|
||||
|
||||
logger = get_module_logger("observation")
|
||||
|
||||
|
||||
# 所有观察的基类
|
||||
class Observation:
|
||||
def __init__(self, observe_type, observe_id):
|
||||
@@ -35,7 +37,7 @@ class ChattingObservation(Observation):
|
||||
self.max_mid_memory_len = global_config.compress_length_limit
|
||||
self.mid_memory_info = ""
|
||||
self.now_message_info = ""
|
||||
|
||||
|
||||
self.updating_old = False
|
||||
|
||||
self.llm_summary = LLM_request(
|
||||
@@ -43,43 +45,42 @@ class ChattingObservation(Observation):
|
||||
)
|
||||
|
||||
# 进行一次观察 返回观察结果observe_info
|
||||
def get_observe_info(self, ids = None):
|
||||
def get_observe_info(self, ids=None):
|
||||
if ids:
|
||||
mid_memory_str = ""
|
||||
for id in ids:
|
||||
print(f"id:{id}")
|
||||
try:
|
||||
for mid_memory in self.mid_memorys:
|
||||
if mid_memory['id'] == id:
|
||||
if mid_memory["id"] == id:
|
||||
mid_memory_by_id = mid_memory
|
||||
msg_str = ""
|
||||
for msg in mid_memory_by_id['messages']:
|
||||
for msg in mid_memory_by_id["messages"]:
|
||||
msg_str += f"{msg['detailed_plain_text']}"
|
||||
time_diff = int((datetime.now().timestamp() - mid_memory_by_id['created_at']) / 60)
|
||||
time_diff = int((datetime.now().timestamp() - mid_memory_by_id["created_at"]) / 60)
|
||||
mid_memory_str += f"距离现在{time_diff}分钟前:\n{msg_str}\n"
|
||||
except Exception as e:
|
||||
logger.error(f"获取mid_memory_id失败: {e}")
|
||||
traceback.print_exc()
|
||||
# print(f"获取mid_memory_id失败: {e}")
|
||||
return self.now_message_info
|
||||
|
||||
|
||||
return mid_memory_str + "现在群里正在聊:\n" + self.now_message_info
|
||||
|
||||
|
||||
else:
|
||||
return self.now_message_info
|
||||
|
||||
|
||||
async def observe(self):
|
||||
# 查找新消息
|
||||
new_messages = list(
|
||||
db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}})
|
||||
.sort("time", 1)
|
||||
db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}}).sort("time", 1)
|
||||
) # 按时间正序排列
|
||||
|
||||
|
||||
if not new_messages:
|
||||
return self.observe_info # 没有新消息,返回上次观察结果
|
||||
|
||||
self.last_observe_time = new_messages[-1]["time"]
|
||||
|
||||
|
||||
self.talking_message.extend(new_messages)
|
||||
|
||||
# 将新消息转换为字符串格式
|
||||
@@ -91,7 +92,7 @@ class ChattingObservation(Observation):
|
||||
# print(f"new_messages_str:{new_messages_str}")
|
||||
|
||||
# 将新消息添加到talking_message,同时保持列表长度不超过20条
|
||||
|
||||
|
||||
if len(self.talking_message) > self.max_now_obs_len and not self.updating_old:
|
||||
self.updating_old = True
|
||||
# 计算需要保留的消息数量
|
||||
@@ -116,37 +117,31 @@ class ChattingObservation(Observation):
|
||||
"messages": oldest_messages,
|
||||
"timestamps": oldest_timestamps,
|
||||
"chat_id": self.chat_id,
|
||||
"created_at": datetime.now().timestamp()
|
||||
"created_at": datetime.now().timestamp(),
|
||||
}
|
||||
# print(f"mid_memory:{mid_memory}")
|
||||
# 存入内存中的 mid_memorys
|
||||
self.mid_memorys.append(mid_memory)
|
||||
if len(self.mid_memorys) > self.max_mid_memory_len:
|
||||
self.mid_memorys.pop(0)
|
||||
|
||||
|
||||
mid_memory_str = "之前聊天的内容概括是:\n"
|
||||
for mid_memory in self.mid_memorys:
|
||||
time_diff = int((datetime.now().timestamp() - mid_memory['created_at']) / 60)
|
||||
time_diff = int((datetime.now().timestamp() - mid_memory["created_at"]) / 60)
|
||||
mid_memory_str += f"距离现在{time_diff}分钟前(聊天记录id:{mid_memory['id']}):{mid_memory['theme']}\n"
|
||||
self.mid_memory_info = mid_memory_str
|
||||
|
||||
|
||||
|
||||
self.updating_old = False
|
||||
|
||||
|
||||
# print(f"处理后self.talking_message:{self.talking_message}")
|
||||
|
||||
now_message_str = ""
|
||||
now_message_str += self.translate_message_list_to_str(talking_message=self.talking_message)
|
||||
self.now_message_info = now_message_str
|
||||
|
||||
|
||||
|
||||
|
||||
logger.debug(f"压缩早期记忆:{self.mid_memory_info}\n现在聊天内容:{self.now_message_info}")
|
||||
|
||||
|
||||
async def update_talking_summary(self, new_messages_str):
|
||||
|
||||
|
||||
prompt = ""
|
||||
# prompt += f"{personality_info}"
|
||||
prompt += f"你的名字叫:{self.name}\n,标识'{self.name}'的都是你自己说的话"
|
||||
|
||||
@@ -150,7 +150,9 @@ class SubHeartflow:
|
||||
observation = self.observations[0]
|
||||
await observation.observe()
|
||||
|
||||
async def do_thinking_before_reply(self, message_txt: str, sender_name: str, chat_stream: ChatStream, extra_info: str, obs_id: int = None):
|
||||
async def do_thinking_before_reply(
|
||||
self, message_txt: str, sender_name: str, chat_stream: ChatStream, extra_info: str, obs_id: int = None
|
||||
):
|
||||
current_thinking_info = self.current_mind
|
||||
mood_info = self.current_state.mood
|
||||
# mood_info = "你很生气,很愤怒"
|
||||
@@ -257,7 +259,7 @@ class SubHeartflow:
|
||||
|
||||
personality_core = individuality.personality.personality_core
|
||||
prompt_personality += personality_core
|
||||
|
||||
|
||||
extra_info_prompt = ""
|
||||
for tool_name, tool_data in extra_info.items():
|
||||
extra_info_prompt += f"{tool_name} 相关信息:\n"
|
||||
|
||||
@@ -234,7 +234,7 @@ class ThinkFlowChat:
|
||||
if random() < reply_probability:
|
||||
try:
|
||||
do_reply = True
|
||||
|
||||
|
||||
# 回复前处理
|
||||
await willing_manager.before_generate_reply_handle(message.message_info.message_id)
|
||||
|
||||
@@ -259,7 +259,6 @@ class ThinkFlowChat:
|
||||
traceback.print_exc()
|
||||
|
||||
info_catcher.catch_after_observe(timing_results["观察"])
|
||||
|
||||
|
||||
# 思考前使用工具
|
||||
update_relationship = ""
|
||||
@@ -271,7 +270,8 @@ class ThinkFlowChat:
|
||||
message.processed_plain_text,
|
||||
message.message_info.user_info.user_nickname,
|
||||
chat,
|
||||
heartflow.get_subheartflow(chat.stream_id))
|
||||
heartflow.get_subheartflow(chat.stream_id),
|
||||
)
|
||||
# 如果工具被使用且获得了结果,将收集到的信息合并到思考中
|
||||
# collected_info = ""
|
||||
if tool_result.get("used_tools", False):
|
||||
@@ -280,26 +280,25 @@ class ThinkFlowChat:
|
||||
# collected_info = ""
|
||||
get_mid_memory_id = []
|
||||
update_relationship = ""
|
||||
|
||||
|
||||
# 动态解析工具结果
|
||||
for tool_name, tool_data in tool_result_info.items():
|
||||
# tool_result_info += f"\n{tool_name} 相关信息:\n"
|
||||
# for item in tool_data:
|
||||
# tool_result_info += f"- {item['name']}: {item['content']}\n"
|
||||
|
||||
# tool_result_info += f"- {item['name']}: {item['content']}\n"
|
||||
|
||||
# 特殊判定:mid_chat_mem
|
||||
if tool_name == "mid_chat_mem":
|
||||
for mid_memory in tool_data:
|
||||
get_mid_memory_id.append(mid_memory['content'])
|
||||
|
||||
get_mid_memory_id.append(mid_memory["content"])
|
||||
|
||||
# 特殊判定:change_mood
|
||||
if tool_name == "change_mood":
|
||||
for mood in tool_data:
|
||||
self.mood_manager.update_mood_from_emotion(
|
||||
mood['content'],
|
||||
global_config.mood_intensity_factor
|
||||
mood["content"], global_config.mood_intensity_factor
|
||||
)
|
||||
|
||||
|
||||
# 特殊判定:change_relationship
|
||||
if tool_name == "change_relationship":
|
||||
update_relationship = tool_data[0]["content"]
|
||||
@@ -307,20 +306,16 @@ class ThinkFlowChat:
|
||||
except Exception as e:
|
||||
logger.error(f"思考前工具调用失败: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
# 处理关系更新
|
||||
if update_relationship:
|
||||
stance, emotion = await self.gpt._get_emotion_tags_with_reason(
|
||||
"你还没有回复",
|
||||
message.processed_plain_text,
|
||||
update_relationship
|
||||
"你还没有回复", message.processed_plain_text, update_relationship
|
||||
)
|
||||
await relationship_manager.calculate_update_relationship_value(
|
||||
chat_stream=message.chat_stream,
|
||||
label=emotion,
|
||||
stance=stance
|
||||
chat_stream=message.chat_stream, label=emotion, stance=stance
|
||||
)
|
||||
|
||||
|
||||
# 思考前脑内状态
|
||||
try:
|
||||
with Timer("思考前脑内状态", timing_results):
|
||||
@@ -330,8 +325,8 @@ class ThinkFlowChat:
|
||||
message_txt=message.processed_plain_text,
|
||||
sender_name=message.message_info.user_info.user_nickname,
|
||||
chat_stream=chat,
|
||||
obs_id = get_mid_memory_id,
|
||||
extra_info=tool_result_info
|
||||
obs_id=get_mid_memory_id,
|
||||
extra_info=tool_result_info,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"心流思考前脑内状态失败: {e}")
|
||||
@@ -366,7 +361,6 @@ class ThinkFlowChat:
|
||||
except Exception as e:
|
||||
logger.error(f"心流处理表情包失败: {e}")
|
||||
|
||||
|
||||
try:
|
||||
with Timer("思考后脑内状态更新", timing_results):
|
||||
stream_id = message.chat_stream.stream_id
|
||||
@@ -376,7 +370,9 @@ class ThinkFlowChat:
|
||||
stream_id, limit=global_config.MAX_CONTEXT_SIZE, combine=True
|
||||
)
|
||||
|
||||
await heartflow.get_subheartflow(stream_id).do_thinking_after_reply(response_set, chat_talking_prompt,tool_result_info)
|
||||
await heartflow.get_subheartflow(stream_id).do_thinking_after_reply(
|
||||
response_set, chat_talking_prompt, tool_result_info
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"心流思考后脑内状态更新失败: {e}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user