feat: 增强聊天回复生成器,添加参与者信息和聊天历史处理逻辑
This commit is contained in:
@@ -548,18 +548,56 @@ class DefaultReplyer:
|
|||||||
if user_info_obj:
|
if user_info_obj:
|
||||||
sender_name = getattr(user_info_obj, "user_nickname", "") or getattr(user_info_obj, "user_cardname", "")
|
sender_name = getattr(user_info_obj, "user_nickname", "") or getattr(user_info_obj, "user_cardname", "")
|
||||||
|
|
||||||
|
# 获取参与者信息
|
||||||
|
participants = []
|
||||||
|
try:
|
||||||
|
# 尝试从聊天流中获取参与者信息
|
||||||
|
if hasattr(stream, 'chat_history_manager'):
|
||||||
|
history_manager = stream.chat_history_manager
|
||||||
|
# 获取最近的参与者列表
|
||||||
|
recent_records = history_manager.get_memory_chat_history(
|
||||||
|
user_id=getattr(stream, "user_id", ""),
|
||||||
|
count=10,
|
||||||
|
memory_types=["chat_message", "system_message"]
|
||||||
|
)
|
||||||
|
# 提取唯一的参与者名称
|
||||||
|
for record in recent_records[:5]: # 最近5条记录
|
||||||
|
content = record.get("content", {})
|
||||||
|
participant = content.get("participant_name")
|
||||||
|
if participant and participant not in participants:
|
||||||
|
participants.append(participant)
|
||||||
|
|
||||||
|
# 如果消息包含发送者信息,也添加到参与者列表
|
||||||
|
if content.get("sender_name") and content.get("sender_name") not in participants:
|
||||||
|
participants.append(content.get("sender_name"))
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"获取参与者信息失败: {e}")
|
||||||
|
|
||||||
|
# 如果发送者不在参与者列表中,添加进去
|
||||||
|
if sender_name and sender_name not in participants:
|
||||||
|
participants.insert(0, sender_name)
|
||||||
|
|
||||||
|
# 格式化聊天历史为更友好的格式
|
||||||
|
formatted_history = ""
|
||||||
|
if chat_history:
|
||||||
|
# 移除过长的历史记录,只保留最近部分
|
||||||
|
lines = chat_history.strip().split('\n')
|
||||||
|
recent_lines = lines[-10:] if len(lines) > 10 else lines
|
||||||
|
formatted_history = '\n'.join(recent_lines)
|
||||||
|
|
||||||
query_context = {
|
query_context = {
|
||||||
"chat_history": chat_history if chat_history else "",
|
"chat_history": formatted_history,
|
||||||
"sender": sender_name,
|
"sender": sender_name,
|
||||||
|
"participants": participants,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 使用记忆管理器的智能检索(自动优化查询)
|
# 使用记忆管理器的智能检索(多查询策略)
|
||||||
memories = await manager.search_memories(
|
memories = await manager.search_memories(
|
||||||
query=target,
|
query=target,
|
||||||
top_k=10,
|
top_k=10,
|
||||||
min_importance=0.3,
|
min_importance=0.3,
|
||||||
include_forgotten=False,
|
include_forgotten=False,
|
||||||
optimize_query=True,
|
use_multi_query=True,
|
||||||
context=query_context,
|
context=query_context,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -432,7 +432,6 @@ class MemoryManager:
|
|||||||
time_range: Optional[Tuple[datetime, datetime]] = None,
|
time_range: Optional[Tuple[datetime, datetime]] = None,
|
||||||
min_importance: float = 0.0,
|
min_importance: float = 0.0,
|
||||||
include_forgotten: bool = False,
|
include_forgotten: bool = False,
|
||||||
optimize_query: bool = True,
|
|
||||||
use_multi_query: bool = True,
|
use_multi_query: bool = True,
|
||||||
expand_depth: int = 1,
|
expand_depth: int = 1,
|
||||||
context: Optional[Dict[str, Any]] = None,
|
context: Optional[Dict[str, Any]] = None,
|
||||||
@@ -453,7 +452,6 @@ class MemoryManager:
|
|||||||
time_range: 时间范围过滤 (start, end)
|
time_range: 时间范围过滤 (start, end)
|
||||||
min_importance: 最小重要性
|
min_importance: 最小重要性
|
||||||
include_forgotten: 是否包含已遗忘的记忆
|
include_forgotten: 是否包含已遗忘的记忆
|
||||||
optimize_query: 是否使用小模型优化查询(已弃用,被 use_multi_query 替代)
|
|
||||||
use_multi_query: 是否使用多查询策略(推荐,默认True)
|
use_multi_query: 是否使用多查询策略(推荐,默认True)
|
||||||
expand_depth: 图扩展深度(0=禁用, 1=推荐, 2-3=深度探索)
|
expand_depth: 图扩展深度(0=禁用, 1=推荐, 2-3=深度探索)
|
||||||
context: 查询上下文(用于优化)
|
context: 查询上下文(用于优化)
|
||||||
|
|||||||
@@ -635,21 +635,49 @@ class MemoryTools:
|
|||||||
request_type="memory.multi_query"
|
request_type="memory.multi_query"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 获取上下文信息
|
||||||
participants = context.get("participants", []) if context else []
|
participants = context.get("participants", []) if context else []
|
||||||
prompt = f"""为查询生成3-5个不同角度的搜索语句(JSON格式)。
|
chat_history = context.get("chat_history", "") if context else ""
|
||||||
|
sender = context.get("sender", "") if context else ""
|
||||||
|
|
||||||
**查询:** {query}
|
# 处理聊天历史,提取最近5条左右的对话
|
||||||
|
recent_chat = ""
|
||||||
|
if chat_history:
|
||||||
|
lines = chat_history.strip().split('\n')
|
||||||
|
# 取最近5条消息
|
||||||
|
recent_lines = lines[-5:] if len(lines) > 5 else lines
|
||||||
|
recent_chat = '\n'.join(recent_lines)
|
||||||
|
|
||||||
|
prompt = f"""基于聊天上下文为查询生成3-5个不同角度的搜索语句(JSON格式)。
|
||||||
|
|
||||||
|
**当前查询:** {query}
|
||||||
|
**发送者:** {sender if sender else '未知'}
|
||||||
**参与者:** {', '.join(participants) if participants else '无'}
|
**参与者:** {', '.join(participants) if participants else '无'}
|
||||||
|
|
||||||
**原则:** 对复杂查询(如"杰瑞喵如何评价新的记忆系统"),应生成:
|
**最近聊天记录(最近5条):**
|
||||||
1. 完整查询(权重1.0)
|
{recent_chat if recent_chat else '无聊天历史'}
|
||||||
2. 每个关键概念独立查询(权重0.8)- 重要!
|
|
||||||
3. 主体+动作(权重0.6)
|
|
||||||
|
|
||||||
**输出JSON:**
|
**分析原则:**
|
||||||
|
1. **上下文理解**:根据聊天历史理解查询的真实意图
|
||||||
|
2. **指代消解**:识别并代换"他"、"她"、"它"、"那个"等指代词
|
||||||
|
3. **话题关联**:结合最近讨论的话题生成更精准的查询
|
||||||
|
4. **查询分解**:对复杂查询分解为多个子查询
|
||||||
|
|
||||||
|
**生成策略:**
|
||||||
|
1. **完整查询**(权重1.0):结合上下文的完整查询,包含指代消解
|
||||||
|
2. **关键概念查询**(权重0.8):查询中的核心概念,特别是聊天中提到的实体
|
||||||
|
3. **话题扩展查询**(权重0.7):基于最近聊天话题的相关查询
|
||||||
|
4. **动作/情感查询**(权重0.6):如果涉及情感或动作,生成相关查询
|
||||||
|
|
||||||
|
**输出JSON格式:**
|
||||||
```json
|
```json
|
||||||
{{"queries": [{{"text": "查询1", "weight": 1.0}}, {{"text": "查询2", "weight": 0.8}}]}}
|
{{"queries": [{{"text": "查询语句", "weight": 1.0}}, {{"text": "查询语句", "weight": 0.8}}]}}
|
||||||
```"""
|
```
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
- 查询:"他怎么样了?" + 聊天中提到"小明生病了" → "小明身体恢复情况"
|
||||||
|
- 查询:"那个项目" + 聊天中讨论"记忆系统开发" → "记忆系统项目进展"
|
||||||
|
"""
|
||||||
|
|
||||||
response, _ = await llm.generate_response_async(prompt, temperature=0.3, max_tokens=250)
|
response, _ = await llm.generate_response_async(prompt, temperature=0.3, max_tokens=250)
|
||||||
|
|
||||||
|
|||||||
@@ -661,7 +661,7 @@ class ChatterPlanFilter:
|
|||||||
enhanced_memories = await memory_manager.search_memories(
|
enhanced_memories = await memory_manager.search_memories(
|
||||||
query=query,
|
query=query,
|
||||||
top_k=5,
|
top_k=5,
|
||||||
optimize_query=False, # 直接使用关键词查询
|
use_multi_query=False, # 直接使用关键词查询
|
||||||
)
|
)
|
||||||
|
|
||||||
if not enhanced_memories:
|
if not enhanced_memories:
|
||||||
|
|||||||
Reference in New Issue
Block a user