feat:修改表达方式衰减值

This commit is contained in:
SengokuCola
2025-06-05 16:50:35 +08:00
parent c584fe67cc
commit 3c779f9340
3 changed files with 60 additions and 32 deletions

View File

@@ -111,14 +111,43 @@ class ExpressionLearner:
async def learn_and_store_expression(self) -> List[Tuple[str, str, str]]: async def learn_and_store_expression(self) -> List[Tuple[str, str, str]]:
""" """
学习并存储表达方式,分别学习语言风格和句法特点 学习并存储表达方式,分别学习语言风格和句法特点
同时对所有已存储的表达方式进行全局衰减
""" """
current_time = time.time()
# 全局衰减所有已存储的表达方式
for type in ["style", "grammar"]:
base_dir = os.path.join("data", "expression", f"learnt_{type}")
if not os.path.exists(base_dir):
continue
for chat_id in os.listdir(base_dir):
file_path = os.path.join(base_dir, chat_id, "expressions.json")
if not os.path.exists(file_path):
continue
try:
with open(file_path, "r", encoding="utf-8") as f:
expressions = json.load(f)
# 应用全局衰减
decayed_expressions = self.apply_decay_to_expressions(expressions, current_time)
# 保存衰减后的结果
with open(file_path, "w", encoding="utf-8") as f:
json.dump(decayed_expressions, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"全局衰减{type}表达方式失败: {e}")
continue
# 学习新的表达方式(这里会进行局部衰减)
for i in range(3): for i in range(3):
learnt_style: Optional[List[Tuple[str, str, str]]] = await self.learn_and_store(type="style", num=15) learnt_style: Optional[List[Tuple[str, str, str]]] = await self.learn_and_store(type="style", num=25)
if not learnt_style: if not learnt_style:
return [] return []
for i in range(1): for j in range(1):
learnt_grammar: Optional[List[Tuple[str, str, str]]] = await self.learn_and_store(type="grammar", num=15) learnt_grammar: Optional[List[Tuple[str, str, str]]] = await self.learn_and_store(type="grammar", num=10)
if not learnt_grammar: if not learnt_grammar:
return [] return []
@@ -126,29 +155,29 @@ class ExpressionLearner:
def calculate_decay_factor(self, time_diff_days: float) -> float: def calculate_decay_factor(self, time_diff_days: float) -> float:
""" """
计算衰减因子 计算衰减
当时间差为0天或30天衰减值为0.01 当时间差为0天时衰减值为0.001
当时间差为7天时衰减值为1.0 当时间差为7天时衰减值为0
当时间差为30天时衰减值为0.001
使用二次函数进行曲线插值 使用二次函数进行曲线插值
""" """
if time_diff_days <= 0 or time_diff_days >= DECAY_DAYS: if time_diff_days <= 0 or time_diff_days >= DECAY_DAYS:
return DECAY_MIN return 0.001
# 使用二次函数进行插值 # 使用二次函数进行插值
# 将7天作为顶点0天和30天作为两个端点 # 将7天作为顶点0天和30天作为两个端点
# 使用顶点式y = a(x-h)^2 + k其中(h,k)为顶点 # 使用顶点式y = a(x-h)^2 + k其中(h,k)为顶点
h = 7.0 # 顶点x坐标 h = 7.0 # 顶点x坐标
k = 1.0 # 顶点y坐标 k = 0.001 # 顶点y坐标
# 计算a值使得x=0和x=30时y=0.01 # 计算a值使得x=0和x=30时y=0.001
# 0.01 = a(0-7)^2 + 1 # 0.001 = a(0-7)^2 + 0.001
# 0.01 = a(30-7)^2 + 1 # 解得a = 0
# 解得a = -0.99/49 a = 0
a = -0.99 / 49
# 计算衰减因子 # 计算衰减
decay = a * (time_diff_days - h) ** 2 + k decay = a * (time_diff_days - h) ** 2 + k
return max(DECAY_MIN, min(1.0, decay)) return min(0.001, decay)
def apply_decay_to_expressions(self, expressions: List[Dict[str, Any]], current_time: float) -> List[Dict[str, Any]]: def apply_decay_to_expressions(self, expressions: List[Dict[str, Any]], current_time: float) -> List[Dict[str, Any]]:
""" """
@@ -157,11 +186,15 @@ class ExpressionLearner:
""" """
result = [] result = []
for expr in expressions: for expr in expressions:
last_active = expr.get("last_active_time", current_time) # 确保last_active_time存在,如果不存在则使用current_time
if "last_active_time" not in expr:
expr["last_active_time"] = current_time
last_active = expr["last_active_time"]
time_diff_days = (current_time - last_active) / (24 * 3600) # 转换为天 time_diff_days = (current_time - last_active) / (24 * 3600) # 转换为天
decay_factor = self.calculate_decay_factor(time_diff_days) decay_value = self.calculate_decay_factor(time_diff_days)
expr["count"] = expr.get("count", 1) * decay_factor expr["count"] = max(0.01, expr.get("count", 1) - decay_value)
if expr["count"] > 0: if expr["count"] > 0:
result.append(expr) result.append(expr)
@@ -225,7 +258,7 @@ class ExpressionLearner:
old_data = [] old_data = []
# 应用衰减 # 应用衰减
old_data = self.apply_decay_to_expressions(old_data, current_time) # old_data = self.apply_decay_to_expressions(old_data, current_time)
# 合并逻辑 # 合并逻辑
for new_expr in expr_list: for new_expr in expr_list:

View File

@@ -27,9 +27,9 @@ def init_prompt():
{chat_observe_info} {chat_observe_info}
现在请你根据现有的信息,总结你和群里的人的关系 现在请你根据现有的信息,总结你和群里的人的关系
1. 聊天记录中提到你时,请输出你和这个人之间的关系 1. 根据聊天记录的需要,精简你和其他人的关系并输出
2. 聊天记录中提到其他人时,请输出你和这个人之间的关系 2. 根据聊天记录,如果需要提及你和某个人的关系,请输出你和这个人之间的关系
3. 如果没有特别需要提及的关系,就不用输出这个人 3. 如果没有特别需要提及的关系,就不用输出这个人的关系
输出内容平淡一些,说中文。 输出内容平淡一些,说中文。
请注意不要输出多余内容(包括前后缀,括号()表情包at或 @等 )。只输出关系内容,记得明确说明这是你的关系。 请注意不要输出多余内容(包括前后缀,括号()表情包at或 @等 )。只输出关系内容,记得明确说明这是你的关系。

View File

@@ -1,4 +1,6 @@
import random import random
from reportportal_client import current
from src.common.logger_manager import get_logger from src.common.logger_manager import get_logger
from src.llm_models.utils_model import LLMRequest from src.llm_models.utils_model import LLMRequest
from src.config.config import global_config from src.config.config import global_config
@@ -7,7 +9,6 @@ from typing import List, Tuple
import os import os
import json import json
from datetime import datetime from datetime import datetime
from src.individuality.individuality import individuality
logger = get_logger("expressor") logger = get_logger("expressor")
@@ -89,21 +90,18 @@ class PersonalityExpression:
os.makedirs(os.path.dirname(self.expressions_file_path), exist_ok=True) os.makedirs(os.path.dirname(self.expressions_file_path), exist_ok=True)
current_style_text = global_config.expression.expression_style current_style_text = global_config.expression.expression_style
current_personality = individuality.get_personality_prompt(x_person=2, level=2) current_personality = global_config.personality.personality_core
current_identity = individuality.get_identity_prompt(x_person=2, level=2)
meta_data = self._read_meta_data() meta_data = self._read_meta_data()
last_style_text = meta_data.get("last_style_text") last_style_text = meta_data.get("last_style_text")
last_personality = meta_data.get("last_personality") last_personality = meta_data.get("last_personality")
last_identity = meta_data.get("last_identity")
count = meta_data.get("count", 0) count = meta_data.get("count", 0)
# 检查是否有任何变化 # 检查是否有任何变化
if (current_style_text != last_style_text or if (current_style_text != last_style_text or
current_personality != last_personality or current_personality != last_personality):
current_identity != last_identity): logger.info(f"检测到变化:\n风格: '{last_style_text}' -> '{current_style_text}'\n人格: '{last_personality}' -> '{current_personality}'")
logger.info(f"检测到变化:\n风格: '{last_style_text}' -> '{current_style_text}'\n人格: '{last_personality}' -> '{current_personality}'\n身份: '{last_identity}' -> '{current_identity}'")
count = 0 count = 0
if os.path.exists(self.expressions_file_path): if os.path.exists(self.expressions_file_path):
try: try:
@@ -119,7 +117,6 @@ class PersonalityExpression:
{ {
"last_style_text": current_style_text, "last_style_text": current_style_text,
"last_personality": current_personality, "last_personality": current_personality,
"last_identity": current_identity,
"count": count, "count": count,
"last_update_time": meta_data.get("last_update_time"), "last_update_time": meta_data.get("last_update_time"),
} }
@@ -142,7 +139,6 @@ class PersonalityExpression:
{ {
"last_style_text": current_style_text, "last_style_text": current_style_text,
"last_personality": current_personality, "last_personality": current_personality,
"last_identity": current_identity,
"count": count, "count": count,
"last_update_time": meta_data.get("last_update_time"), "last_update_time": meta_data.get("last_update_time"),
} }
@@ -200,7 +196,6 @@ class PersonalityExpression:
{ {
"last_style_text": current_style_text, "last_style_text": current_style_text,
"last_personality": current_personality, "last_personality": current_personality,
"last_identity": current_identity,
"count": count, "count": count,
"last_update_time": current_time "last_update_time": current_time
} }