🤖 自动格式化代码 [skip ci]

This commit is contained in:
github-actions[bot]
2025-04-14 04:01:29 +00:00
parent 38d7d9e014
commit 9c82f1322e
7 changed files with 69 additions and 84 deletions

View File

@@ -11,20 +11,19 @@ logger = get_module_logger("change_mood_tool")
class ChangeMoodTool(BaseTool): class ChangeMoodTool(BaseTool):
"""改变心情的工具""" """改变心情的工具"""
name = "change_mood" name = "change_mood"
description = "根据收到的内容和自身回复的内容,改变心情,当你回复了别人的消息,你可以使用这个工具" description = "根据收到的内容和自身回复的内容,改变心情,当你回复了别人的消息,你可以使用这个工具"
parameters = { parameters = {
"type": "object", "type": "object",
"properties": { "properties": {
"text": {"type": "string", "description": "引起你改变心情的文本"}, "text": {"type": "string", "description": "引起你改变心情的文本"},
"response_set": {"type": "list", "description": "你对文本的回复"} "response_set": {"type": "list", "description": "你对文本的回复"},
}, },
"required": ["text", "response_set"], "required": ["text", "response_set"],
} }
async def execute(self, function_args: Dict[str, Any],message_txt:str) -> Dict[str, Any]: async def execute(self, function_args: Dict[str, Any], message_txt: str) -> Dict[str, Any]:
"""执行心情改变 """执行心情改变
Args: Args:
@@ -38,13 +37,13 @@ class ChangeMoodTool(BaseTool):
try: try:
response_set = function_args.get("response_set") response_set = function_args.get("response_set")
message_processed_plain_text = function_args.get("text") message_processed_plain_text = function_args.get("text")
mood_manager = MoodManager.get_instance() mood_manager = MoodManager.get_instance()
gpt = ResponseGenerator() gpt = ResponseGenerator()
if response_set is None: if response_set is None:
response_set = ["你还没有回复"] response_set = ["你还没有回复"]
ori_response = ",".join(response_set) ori_response = ",".join(response_set)
_stance, emotion = await gpt._get_emotion_tags(ori_response, message_processed_plain_text) _stance, emotion = await gpt._get_emotion_tags(ori_response, message_processed_plain_text)
mood_manager.update_mood_from_emotion(emotion, global_config.mood_intensity_factor) mood_manager.update_mood_from_emotion(emotion, global_config.mood_intensity_factor)

View File

@@ -6,38 +6,29 @@ from src.do_tool.tool_can_use.base_tool import BaseTool
logger = get_module_logger("relationship_tool") logger = get_module_logger("relationship_tool")
class RelationshipTool(BaseTool): class RelationshipTool(BaseTool):
name = "change_relationship" name = "change_relationship"
description = "根据收到的文本和回复内容,修改与特定用户的关系值,当你回复了别人的消息,你可以使用这个工具" description = "根据收到的文本和回复内容,修改与特定用户的关系值,当你回复了别人的消息,你可以使用这个工具"
parameters = { parameters = {
"type": "object", "type": "object",
"properties": { "properties": {
"text": { "text": {"type": "string", "description": "收到的文本"},
"type": "string", "changed_value": {"type": "number", "description": "变更值"},
"description": "收到的文本" "reason": {"type": "string", "description": "变更原因"},
},
"changed_value": {
"type": "number",
"description": "变更值"
},
"reason": {
"type": "string",
"description": "变更原因"
}
}, },
"required": ["text", "changed_value", "reason"] "required": ["text", "changed_value", "reason"],
} }
async def execute(self, args: dict,message_txt:str) -> dict: async def execute(self, args: dict, message_txt: str) -> dict:
"""执行工具功能 """执行工具功能
Args: Args:
args: 包含工具参数的字典 args: 包含工具参数的字典
text: 原始消息文本 text: 原始消息文本
changed_value: 变更值 changed_value: 变更值
reason: 变更原因 reason: 变更原因
Returns: Returns:
dict: 包含执行结果的字典 dict: 包含执行结果的字典
""" """
@@ -45,9 +36,9 @@ class RelationshipTool(BaseTool):
text = args.get("text") text = args.get("text")
changed_value = args.get("changed_value") changed_value = args.get("changed_value")
reason = args.get("reason") reason = args.get("reason")
return {"content": f"因为你刚刚因为{reason},所以你和发[{text}]这条消息的人的关系值变化为{changed_value}"} return {"content": f"因为你刚刚因为{reason},所以你和发[{text}]这条消息的人的关系值变化为{changed_value}"}
except Exception as e: except Exception as e:
logger.error(f"修改关系值时发生错误: {str(e)}") logger.error(f"修改关系值时发生错误: {str(e)}")
return {"content": f"修改关系值失败: {str(e)}"} return {"content": f"修改关系值失败: {str(e)}"}

View File

@@ -21,7 +21,9 @@ class ToolUser:
model=global_config.llm_heartflow, temperature=0.2, max_tokens=1000, request_type="tool_use" model=global_config.llm_heartflow, 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, reply_message:str = ""): async def _build_tool_prompt(
self, message_txt: str, sender_name: str, chat_stream: ChatStream, reply_message: str = ""
):
"""构建工具使用的提示词 """构建工具使用的提示词
Args: Args:
@@ -155,7 +157,7 @@ class ToolUser:
logger.debug("模型返回了空的tool_calls列表") logger.debug("模型返回了空的tool_calls列表")
return {"used_tools": False} return {"used_tools": False}
tool_calls_str = "" tool_calls_str = ""
for tool_call in tool_calls: for tool_call in tool_calls:
tool_calls_str += f"{tool_call['function']['name']}\n" tool_calls_str += f"{tool_call['function']['name']}\n"
logger.info(f"模型请求调用{len(tool_calls)}个工具: {tool_calls_str}") logger.info(f"模型请求调用{len(tool_calls)}个工具: {tool_calls_str}")
@@ -166,7 +168,7 @@ class ToolUser:
"knowledge": [], "knowledge": [],
"change_relationship": [], "change_relationship": [],
"change_mood": [], "change_mood": [],
"other": [] "other": [],
} }
# 执行所有工具调用 # 执行所有工具调用
@@ -175,18 +177,12 @@ class ToolUser:
if result: if result:
tool_results.append(result) tool_results.append(result)
# 将工具结果添加到对应类型的列表中 # 将工具结果添加到对应类型的列表中
structured_info[result["type"]].append({ structured_info[result["type"]].append({"name": result["name"], "content": result["content"]})
"name": result["name"],
"content": result["content"]
})
# 如果有工具结果,返回结构化的信息 # 如果有工具结果,返回结构化的信息
if any(structured_info.values()): if any(structured_info.values()):
logger.info(f"工具调用收集到结构化信息: {json.dumps(structured_info, ensure_ascii=False)}") logger.info(f"工具调用收集到结构化信息: {json.dumps(structured_info, ensure_ascii=False)}")
return { return {"used_tools": True, "structured_info": structured_info}
"used_tools": True,
"structured_info": structured_info
}
else: else:
# 没有工具调用 # 没有工具调用
content, reasoning_content = response content, reasoning_content = response

View File

@@ -97,8 +97,6 @@ class SubHeartflow:
self.bot_name = global_config.BOT_NICKNAME self.bot_name = global_config.BOT_NICKNAME
def add_observation(self, observation: Observation): def add_observation(self, observation: Observation):
"""添加一个新的observation对象到列表中如果已存在相同id的observation则不添加""" """添加一个新的observation对象到列表中如果已存在相同id的observation则不添加"""
# 查找是否存在相同id的observation # 查找是否存在相同id的observation
@@ -151,15 +149,15 @@ class SubHeartflow:
observation = self.observations[0] observation = self.observations[0]
await observation.observe() await observation.observe()
async def do_thinking_before_reply(self, message_txt: str, sender_name: str, chat_stream: ChatStream, extra_info: str): async def do_thinking_before_reply(
self, message_txt: str, sender_name: str, chat_stream: ChatStream, extra_info: str
):
current_thinking_info = self.current_mind current_thinking_info = self.current_mind
mood_info = self.current_state.mood mood_info = self.current_state.mood
# mood_info = "你很生气,很愤怒" # mood_info = "你很生气,很愤怒"
observation = self.observations[0] observation = self.observations[0]
chat_observe_info = observation.observe_info chat_observe_info = observation.observe_info
# 开始构建prompt # 开始构建prompt
prompt_personality = f"你的名字是{self.bot_name},你" prompt_personality = f"你的名字是{self.bot_name},你"
# person # person

View File

@@ -136,8 +136,6 @@ class ThinkFlowChat:
message_manager.add_message(bot_message) message_manager.add_message(bot_message)
async def _update_relationship(self, message: MessageRecv, response_set): async def _update_relationship(self, message: MessageRecv, response_set):
"""更新关系情绪""" """更新关系情绪"""
ori_response = ",".join(response_set) ori_response = ",".join(response_set)
@@ -260,16 +258,17 @@ class ThinkFlowChat:
logger.error(f"心流观察失败: {e}") logger.error(f"心流观察失败: {e}")
info_catcher.catch_after_observe(timing_results["观察"]) info_catcher.catch_after_observe(timing_results["观察"])
# 思考前使用工具 # 思考前使用工具
update_relationship = "" update_relationship = ""
try: try:
with Timer("思考前使用工具", timing_results): with Timer("思考前使用工具", timing_results):
tool_result = await self.tool_user.use_tool(message.processed_plain_text, message.message_info.user_info.user_nickname, chat) tool_result = await self.tool_user.use_tool(
message.processed_plain_text, message.message_info.user_info.user_nickname, chat
)
# 如果工具被使用且获得了结果,将收集到的信息合并到思考中 # 如果工具被使用且获得了结果,将收集到的信息合并到思考中
collected_info = "" collected_info = ""
if tool_result.get("used_tools", False): if tool_result.get("used_tools", False):
# 如果有收集到的结构化信息,将其格式化后添加到当前思考中 # 如果有收集到的结构化信息,将其格式化后添加到当前思考中
if "structured_info" in tool_result: if "structured_info" in tool_result:
info = tool_result["structured_info"] info = tool_result["structured_info"]
@@ -278,19 +277,19 @@ class ThinkFlowChat:
collected_info += "\n记忆相关信息:\n" collected_info += "\n记忆相关信息:\n"
for mem in info["memory"]: for mem in info["memory"]:
collected_info += f"- {mem['name']}: {mem['content']}\n" collected_info += f"- {mem['name']}: {mem['content']}\n"
# 处理日程信息 # 处理日程信息
if info["schedule"]: if info["schedule"]:
collected_info += "\n日程相关信息:\n" collected_info += "\n日程相关信息:\n"
for sch in info["schedule"]: for sch in info["schedule"]:
collected_info += f"- {sch['name']}: {sch['content']}\n" collected_info += f"- {sch['name']}: {sch['content']}\n"
# 处理知识信息 # 处理知识信息
if info["knowledge"]: if info["knowledge"]:
collected_info += "\n知识相关信息:\n" collected_info += "\n知识相关信息:\n"
for know in info["knowledge"]: for know in info["knowledge"]:
collected_info += f"- {know['name']}: {know['content']}\n" collected_info += f"- {know['name']}: {know['content']}\n"
# 处理关系信息 # 处理关系信息
if info["change_relationship"]: if info["change_relationship"]:
collected_info += "\n关系相关信息:\n" collected_info += "\n关系相关信息:\n"
@@ -305,7 +304,7 @@ class ThinkFlowChat:
collected_info += "\n心情相关信息:\n" collected_info += "\n心情相关信息:\n"
for mood in info["change_mood"]: for mood in info["change_mood"]:
collected_info += f"- {mood['name']}: {mood['content']}\n" collected_info += f"- {mood['name']}: {mood['content']}\n"
# 处理其他信息 # 处理其他信息
if info["other"]: if info["other"]:
collected_info += "\n其他相关信息:\n" collected_info += "\n其他相关信息:\n"
@@ -314,18 +313,18 @@ class ThinkFlowChat:
except Exception as e: except Exception as e:
logger.error(f"思考前工具调用失败: {e}") logger.error(f"思考前工具调用失败: {e}")
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
if update_relationship: if update_relationship:
# ori_response = ",".join(response_set) # ori_response = ",".join(response_set)
# print("22222222222222222222222222222") # print("22222222222222222222222222222")
stance, emotion = await self.gpt._get_emotion_tags_with_reason("你还没有回复", message.processed_plain_text,update_relationship) stance, emotion = await self.gpt._get_emotion_tags_with_reason(
"你还没有回复", message.processed_plain_text, update_relationship
)
await relationship_manager.calculate_update_relationship_value( 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
) )
print("33333333333333333333333333333") print("33333333333333333333333333333")
# 思考前脑内状态 # 思考前脑内状态
try: try:
with Timer("思考前脑内状态", timing_results): with Timer("思考前脑内状态", timing_results):
@@ -335,7 +334,7 @@ class ThinkFlowChat:
message_txt=message.processed_plain_text, message_txt=message.processed_plain_text,
sender_name=message.message_info.user_info.user_nickname, sender_name=message.message_info.user_info.user_nickname,
chat_stream=chat, chat_stream=chat,
extra_info=collected_info extra_info=collected_info,
) )
except Exception as e: except Exception as e:
logger.error(f"心流思考前脑内状态失败: {e}") logger.error(f"心流思考前脑内状态失败: {e}")
@@ -370,15 +369,15 @@ class ThinkFlowChat:
except Exception as e: except Exception as e:
logger.error(f"心流处理表情包失败: {e}") logger.error(f"心流处理表情包失败: {e}")
# 思考后使用工具 # 思考后使用工具
try: try:
with Timer("思考后使用工具", timing_results): with Timer("思考后使用工具", timing_results):
tool_result = await self.tool_user.use_tool(message.processed_plain_text, message.message_info.user_info.user_nickname, chat) tool_result = await self.tool_user.use_tool(
message.processed_plain_text, message.message_info.user_info.user_nickname, chat
)
# 如果工具被使用且获得了结果,将收集到的信息合并到思考中 # 如果工具被使用且获得了结果,将收集到的信息合并到思考中
collected_info = "" collected_info = ""
if tool_result.get("used_tools", False): if tool_result.get("used_tools", False):
# 如果有收集到的结构化信息,将其格式化后添加到当前思考中 # 如果有收集到的结构化信息,将其格式化后添加到当前思考中
if "structured_info" in tool_result: if "structured_info" in tool_result:
info = tool_result["structured_info"] info = tool_result["structured_info"]
@@ -387,31 +386,31 @@ class ThinkFlowChat:
collected_info += "\n记忆相关信息:\n" collected_info += "\n记忆相关信息:\n"
for mem in info["memory"]: for mem in info["memory"]:
collected_info += f"- {mem['name']}: {mem['content']}\n" collected_info += f"- {mem['name']}: {mem['content']}\n"
# 处理日程信息 # 处理日程信息
if info["schedule"]: if info["schedule"]:
collected_info += "\n日程相关信息:\n" collected_info += "\n日程相关信息:\n"
for sch in info["schedule"]: for sch in info["schedule"]:
collected_info += f"- {sch['name']}: {sch['content']}\n" collected_info += f"- {sch['name']}: {sch['content']}\n"
# 处理知识信息 # 处理知识信息
if info["knowledge"]: if info["knowledge"]:
collected_info += "\n知识相关信息:\n" collected_info += "\n知识相关信息:\n"
for know in info["knowledge"]: for know in info["knowledge"]:
collected_info += f"- {know['name']}: {know['content']}\n" collected_info += f"- {know['name']}: {know['content']}\n"
# 处理关系信息 # 处理关系信息
if info["change_relationship"]: if info["change_relationship"]:
collected_info += "\n关系相关信息:\n" collected_info += "\n关系相关信息:\n"
for rel in info["change_relationship"]: for rel in info["change_relationship"]:
collected_info += f"- {rel['name']}: {rel['content']}\n" collected_info += f"- {rel['name']}: {rel['content']}\n"
# 处理心情信息 # 处理心情信息
if info["change_mood"]: if info["change_mood"]:
collected_info += "\n心情相关信息:\n" collected_info += "\n心情相关信息:\n"
for mood in info["change_mood"]: for mood in info["change_mood"]:
collected_info += f"- {mood['name']}: {mood['content']}\n" collected_info += f"- {mood['name']}: {mood['content']}\n"
# 处理其他信息 # 处理其他信息
if info["other"]: if info["other"]:
collected_info += "\n其他相关信息:\n" collected_info += "\n其他相关信息:\n"
@@ -424,13 +423,13 @@ class ThinkFlowChat:
# 更新关系 # 更新关系
if info["change_relationship"]: if info["change_relationship"]:
ori_response = ",".join(response_set) ori_response = ",".join(response_set)
stance, emotion = await self.gpt._get_emotion_tags(ori_response, message.processed_plain_text,info["change_relationship"]["content"]) stance, emotion = await self.gpt._get_emotion_tags(
ori_response, message.processed_plain_text, info["change_relationship"]["content"]
)
await relationship_manager.calculate_update_relationship_value( 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: try:
with Timer("思考后脑内状态更新", timing_results): with Timer("思考后脑内状态更新", timing_results):
stream_id = message.chat_stream.stream_id stream_id = message.chat_stream.stream_id
@@ -440,11 +439,12 @@ class ThinkFlowChat:
stream_id, limit=global_config.MAX_CONTEXT_SIZE, combine=True 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,collected_info) await heartflow.get_subheartflow(stream_id).do_thinking_after_reply(
response_set, chat_talking_prompt, collected_info
)
except Exception as e: except Exception as e:
logger.error(f"心流思考后脑内状态更新失败: {e}") logger.error(f"心流思考后脑内状态更新失败: {e}")
# 回复后处理 # 回复后处理
await willing_manager.after_generate_reply_handle(message.message_info.message_id) await willing_manager.after_generate_reply_handle(message.message_info.message_id)

View File

@@ -225,8 +225,7 @@ class ResponseGenerator:
except Exception as e: except Exception as e:
logger.debug(f"获取情感标签时出错: {e}") logger.debug(f"获取情感标签时出错: {e}")
return "中立", "平静" # 出错时返回默认值 return "中立", "平静" # 出错时返回默认值
async def _get_emotion_tags_with_reason(self, content: str, processed_plain_text: str, reason: str): async def _get_emotion_tags_with_reason(self, content: str, processed_plain_text: str, reason: str):
"""提取情感标签,结合立场和情绪""" """提取情感标签,结合立场和情绪"""
try: try:

View File

@@ -84,10 +84,10 @@ class RelationshipManager:
2.关系越差,改善越难,关系越好,恶化越容易 2.关系越差,改善越难,关系越好,恶化越容易
3.人维护关系的精力往往有限,所以当高关系值用户越多,对于中高关系值用户增长越慢 3.人维护关系的精力往往有限,所以当高关系值用户越多,对于中高关系值用户增长越慢
4.连续正面或负面情感会正反馈 4.连续正面或负面情感会正反馈
返回: 返回:
用户昵称,变更值,变更后关系等级 用户昵称,变更值,变更后关系等级
""" """
stancedict = { stancedict = {
"支持": 0, "支持": 0,
@@ -159,10 +159,12 @@ class RelationshipManager:
) )
await person_info_manager.update_one_field(person_id, "relationship_value", old_value + value, data) await person_info_manager.update_one_field(person_id, "relationship_value", old_value + value, data)
return chat_stream.user_info.user_nickname,value,relationship_level[level_num] return chat_stream.user_info.user_nickname, value, relationship_level[level_num]
async def calculate_update_relationship_value_with_reason(self, chat_stream: ChatStream, label: str, stance: str, reason: str) -> tuple: async def calculate_update_relationship_value_with_reason(
self, chat_stream: ChatStream, label: str, stance: str, reason: str
) -> tuple:
"""计算并变更关系值 """计算并变更关系值
新的关系值变更计算方式: 新的关系值变更计算方式:
将关系值限定在-1000到1000 将关系值限定在-1000到1000
@@ -171,10 +173,10 @@ class RelationshipManager:
2.关系越差,改善越难,关系越好,恶化越容易 2.关系越差,改善越难,关系越好,恶化越容易
3.人维护关系的精力往往有限,所以当高关系值用户越多,对于中高关系值用户增长越慢 3.人维护关系的精力往往有限,所以当高关系值用户越多,对于中高关系值用户增长越慢
4.连续正面或负面情感会正反馈 4.连续正面或负面情感会正反馈
返回: 返回:
用户昵称,变更值,变更后关系等级 用户昵称,变更值,变更后关系等级
""" """
stancedict = { stancedict = {
"支持": 0, "支持": 0,
@@ -246,8 +248,8 @@ class RelationshipManager:
) )
await person_info_manager.update_one_field(person_id, "relationship_value", old_value + value, data) await person_info_manager.update_one_field(person_id, "relationship_value", old_value + value, data)
return chat_stream.user_info.user_nickname,value,relationship_level[level_num] return chat_stream.user_info.user_nickname, value, relationship_level[level_num]
async def build_relationship_info(self, person) -> str: async def build_relationship_info(self, person) -> str:
person_id = person_info_manager.get_person_id(person[0], person[1]) person_id = person_info_manager.get_person_id(person[0], person[1])