mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge 405de0c9e4 into fa91c97685
This commit is contained in:
commit
20f073d7b4
3 changed files with 137 additions and 92 deletions
|
|
@ -57,6 +57,9 @@ log:
|
||||||
|
|
||||||
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
|
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
|
||||||
delete_audio: true
|
delete_audio: true
|
||||||
|
# 对话历史最大保留轮数(每轮 = user + assistant/tool 相关消息)
|
||||||
|
# 默认 10 轮,可根据 LLM 上下文窗口大小调整
|
||||||
|
max_history_turns: 6
|
||||||
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
|
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
|
||||||
close_connection_no_voice_time: 120
|
close_connection_no_voice_time: 120
|
||||||
# TTS请求超时时间(秒)
|
# TTS请求超时时间(秒)
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@ class ConnectionHandler:
|
||||||
self.current_speaker = None # 存储当前说话人
|
self.current_speaker = None # 存储当前说话人
|
||||||
|
|
||||||
# llm相关变量
|
# llm相关变量
|
||||||
self.dialogue = Dialogue()
|
self.dialogue = Dialogue(config=self.config, logger=self.logger)
|
||||||
|
|
||||||
# 工具调用统计(用于监控和自动恢复)
|
# 工具调用统计(用于监控和自动恢复)
|
||||||
self.tool_call_stats = {
|
self.tool_call_stats = {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import uuid
|
import uuid
|
||||||
import re
|
import re
|
||||||
from typing import List, Dict
|
import logging
|
||||||
|
from typing import List, Dict, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -12,7 +13,7 @@ class Message:
|
||||||
uniq_id: str = None,
|
uniq_id: str = None,
|
||||||
tool_calls=None,
|
tool_calls=None,
|
||||||
tool_call_id=None,
|
tool_call_id=None,
|
||||||
is_temporary=False,
|
is_temporary: bool = False,
|
||||||
):
|
):
|
||||||
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
|
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
|
||||||
self.role = role
|
self.role = role
|
||||||
|
|
@ -23,10 +24,19 @@ class Message:
|
||||||
|
|
||||||
|
|
||||||
class Dialogue:
|
class Dialogue:
|
||||||
def __init__(self):
|
def __init__(self, config: dict = None, logger: logging.Logger = None):
|
||||||
self.dialogue: List[Message] = []
|
self.dialogue: List[Message] = []
|
||||||
# 获取当前时间
|
self.logger = logger
|
||||||
self.current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
|
# 从配置中读取最大历史轮数,默认为 10 轮
|
||||||
|
if config:
|
||||||
|
self.max_history_turns = config.get("max_history_turns", 6)
|
||||||
|
else:
|
||||||
|
self.max_history_turns = 6
|
||||||
|
|
||||||
|
def _log_debug(self, msg: str):
|
||||||
|
if self.logger:
|
||||||
|
self.logger.debug(msg)
|
||||||
|
|
||||||
def put(self, message: Message):
|
def put(self, message: Message):
|
||||||
self.dialogue.append(message)
|
self.dialogue.append(message)
|
||||||
|
|
@ -61,70 +71,66 @@ class Dialogue:
|
||||||
else:
|
else:
|
||||||
self.put(Message(role="system", content=new_content))
|
self.put(Message(role="system", content=new_content))
|
||||||
|
|
||||||
def trim_history(self, max_turns: int = 10) -> int:
|
def _group_messages_by_turns(self, messages: List[Message]) -> List[List[Message]]:
|
||||||
"""
|
"""
|
||||||
智能截断对话历史,保留工具调用的完整性
|
将消息按对话轮次分组
|
||||||
|
|
||||||
Args:
|
|
||||||
max_turns: 保留的最大对话轮数(每轮 = user + assistant/tool 相关消息)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: 被移除的消息数量
|
|
||||||
"""
|
"""
|
||||||
if len(self.dialogue) <= max_turns * 2 + 1: # +1 是系统消息
|
turns = []
|
||||||
return 0
|
current_turn = []
|
||||||
|
|
||||||
# 分离系统消息和对话消息
|
for msg in messages:
|
||||||
system_messages = [msg for msg in self.dialogue if msg.role == "system"]
|
|
||||||
conversation_messages = [msg for msg in self.dialogue if msg.role != "system"]
|
|
||||||
|
|
||||||
if len(conversation_messages) <= max_turns * 2:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
# 智能截断:保留完整的工具调用链路
|
|
||||||
keep_messages = []
|
|
||||||
i = len(conversation_messages) - 1
|
|
||||||
turn_count = 0
|
|
||||||
|
|
||||||
while i >= 0 and turn_count < max_turns:
|
|
||||||
msg = conversation_messages[i]
|
|
||||||
|
|
||||||
# 从后向前收集消息
|
|
||||||
if msg.role == "user":
|
if msg.role == "user":
|
||||||
# 遇到 user 消息,说明一轮对话开始
|
if current_turn:
|
||||||
keep_messages.insert(0, msg)
|
turns.append(current_turn)
|
||||||
turn_count += 1
|
current_turn = [msg]
|
||||||
i -= 1
|
|
||||||
elif msg.role == "assistant":
|
|
||||||
# 收集 assistant 消息
|
|
||||||
keep_messages.insert(0, msg)
|
|
||||||
|
|
||||||
# 如果这个 assistant 有 tool_calls,需要收集对应的 tool 响应
|
|
||||||
if msg.tool_calls is not None:
|
|
||||||
i -= 1
|
|
||||||
# 继续向后收集所有相关的 tool 消息
|
|
||||||
while i >= 0 and conversation_messages[i].role == "tool":
|
|
||||||
keep_messages.insert(0, conversation_messages[i])
|
|
||||||
i -= 1
|
|
||||||
else:
|
else:
|
||||||
i -= 1
|
current_turn.append(msg)
|
||||||
elif msg.role == "tool":
|
|
||||||
# tool 消息应该已经被上面的逻辑收集了
|
|
||||||
# 如果单独遇到,也要保留(防止边界情况)
|
|
||||||
keep_messages.insert(0, msg)
|
|
||||||
i -= 1
|
|
||||||
else:
|
|
||||||
i -= 1
|
|
||||||
|
|
||||||
removed_count = len(conversation_messages) - len(keep_messages)
|
if current_turn:
|
||||||
|
turns.append(current_turn)
|
||||||
|
|
||||||
# 重建对话列表
|
return turns
|
||||||
self.dialogue = system_messages + keep_messages
|
|
||||||
|
|
||||||
return removed_count
|
def _ensure_tool_calls_complete(self, messages: List[Message]) -> List[Message]:
|
||||||
|
"""
|
||||||
|
确保所有 tool_calls 都有对应的 tool 响应
|
||||||
|
|
||||||
|
修复被打断导致的悬空 tool_calls,防止大模型 API 报 400 错误
|
||||||
|
"""
|
||||||
|
pending_tool_calls = set()
|
||||||
|
result = []
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
result.append(msg)
|
||||||
|
|
||||||
|
# 记录 assistant 发出的 tool_calls ID
|
||||||
|
if msg.role == "assistant" and msg.tool_calls:
|
||||||
|
for tc in msg.tool_calls:
|
||||||
|
# 兼容字典和对象两种格式
|
||||||
|
tc_id = tc.get("id") if isinstance(tc, dict) else getattr(tc, "id", None)
|
||||||
|
if tc_id:
|
||||||
|
pending_tool_calls.add(tc_id)
|
||||||
|
|
||||||
|
# tool 响应核销对应的 ID
|
||||||
|
elif msg.role == "tool" and msg.tool_call_id:
|
||||||
|
pending_tool_calls.discard(msg.tool_call_id)
|
||||||
|
|
||||||
|
# 为悬空的 tool_calls 补齐占位响应
|
||||||
|
for missing_id in pending_tool_calls:
|
||||||
|
dummy_tool_msg = Message(
|
||||||
|
role="tool",
|
||||||
|
content='{"status": "interrupted", "message": "动作已取消/被打断"}',
|
||||||
|
tool_call_id=missing_id
|
||||||
|
)
|
||||||
|
result.append(dummy_tool_msg)
|
||||||
|
self._log_debug(f"已为悬空的 tool_call({missing_id}) 自动补齐占位响应")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
def get_llm_dialogue_with_memory(
|
def get_llm_dialogue_with_memory(
|
||||||
self, memory_str: str = None, voiceprint_config: dict = None
|
self,
|
||||||
|
memory_str: str = None,
|
||||||
|
voiceprint_config: dict = None
|
||||||
) -> List[Dict[str, str]]:
|
) -> List[Dict[str, str]]:
|
||||||
# 构建对话
|
# 构建对话
|
||||||
dialogue = []
|
dialogue = []
|
||||||
|
|
@ -143,6 +149,7 @@ class Dialogue:
|
||||||
)
|
)
|
||||||
|
|
||||||
# 添加说话人个性化描述
|
# 添加说话人个性化描述
|
||||||
|
if voiceprint_config:
|
||||||
try:
|
try:
|
||||||
speakers = voiceprint_config.get("speakers", [])
|
speakers = voiceprint_config.get("speakers", [])
|
||||||
if speakers:
|
if speakers:
|
||||||
|
|
@ -152,19 +159,15 @@ class Dialogue:
|
||||||
parts = speaker_str.split(",", 2)
|
parts = speaker_str.split(",", 2)
|
||||||
if len(parts) >= 2:
|
if len(parts) >= 2:
|
||||||
name = parts[1].strip()
|
name = parts[1].strip()
|
||||||
# 如果描述为空,则为""
|
description = parts[2].strip() if len(parts) >= 3 else ""
|
||||||
description = (
|
|
||||||
parts[2].strip() if len(parts) >= 3 else ""
|
|
||||||
)
|
|
||||||
enhanced_system_prompt += f"\n- {name}:{description}"
|
enhanced_system_prompt += f"\n- {name}:{description}"
|
||||||
except:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
enhanced_system_prompt += "\n\n</speakers_info>"
|
enhanced_system_prompt += "\n\n</speakers_info>"
|
||||||
except:
|
except Exception:
|
||||||
# 配置读取失败时忽略错误,不影响其他功能
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 使用正则表达式匹配 <memory> 标签,不管中间有什么内容
|
# 注入记忆内容
|
||||||
if memory_str is not None:
|
if memory_str is not None:
|
||||||
enhanced_system_prompt = re.sub(
|
enhanced_system_prompt = re.sub(
|
||||||
r"<memory>.*?</memory>",
|
r"<memory>.*?</memory>",
|
||||||
|
|
@ -172,11 +175,50 @@ class Dialogue:
|
||||||
enhanced_system_prompt,
|
enhanced_system_prompt,
|
||||||
flags=re.DOTALL,
|
flags=re.DOTALL,
|
||||||
)
|
)
|
||||||
|
|
||||||
dialogue.append({"role": "system", "content": enhanced_system_prompt})
|
dialogue.append({"role": "system", "content": enhanced_system_prompt})
|
||||||
|
|
||||||
# 添加用户和助手的对话
|
# 获取非系统消息
|
||||||
for m in self.dialogue:
|
non_system_messages = [m for m in self.dialogue if m.role != "system"]
|
||||||
if m.role != "system": # 跳过原始的系统消息
|
|
||||||
|
if not non_system_messages:
|
||||||
|
return dialogue
|
||||||
|
|
||||||
|
# 找到最后一个 user 的位置(当前轮次的起点)
|
||||||
|
last_user_idx = -1
|
||||||
|
for i in range(len(non_system_messages) - 1, -1, -1):
|
||||||
|
if non_system_messages[i].role == "user":
|
||||||
|
last_user_idx = i
|
||||||
|
break
|
||||||
|
|
||||||
|
# 如果没有 user 消息,直接返回
|
||||||
|
if last_user_idx == -1:
|
||||||
|
for m in non_system_messages:
|
||||||
|
self.getMessages(m, dialogue)
|
||||||
|
return dialogue
|
||||||
|
|
||||||
|
# 历史轮次:截断并确保完整性
|
||||||
|
history_messages = non_system_messages[:last_user_idx]
|
||||||
|
# 当前轮次:原封不动保留
|
||||||
|
current_turn_messages = non_system_messages[last_user_idx:]
|
||||||
|
|
||||||
|
# 处理历史轮次
|
||||||
|
if history_messages:
|
||||||
|
history_turns = self._group_messages_by_turns(history_messages)
|
||||||
|
max_history = self.max_history_turns - 1
|
||||||
|
if max_history < 1:
|
||||||
|
max_history = 1
|
||||||
|
|
||||||
|
if len(history_turns) > max_history:
|
||||||
|
history_turns = history_turns[-max_history:]
|
||||||
|
|
||||||
|
for turn in history_turns:
|
||||||
|
complete_turn = self._ensure_tool_calls_complete(turn)
|
||||||
|
for m in complete_turn:
|
||||||
|
self.getMessages(m, dialogue)
|
||||||
|
|
||||||
|
# 当前轮次原封不动保留
|
||||||
|
for m in current_turn_messages:
|
||||||
self.getMessages(m, dialogue)
|
self.getMessages(m, dialogue)
|
||||||
|
|
||||||
return dialogue
|
return dialogue
|
||||||
Loading…
Reference in a new issue