diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index e82d15f08..189648785 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -57,6 +57,9 @@ log:
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
delete_audio: true
+# 对话历史最大保留轮数(每轮 = user + assistant/tool 相关消息)
+# 默认 10 轮,可根据 LLM 上下文窗口大小调整
+max_history_turns: 6
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120
# TTS请求超时时间(秒)
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index d1e6be73a..2f407ef94 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -169,7 +169,7 @@ class ConnectionHandler:
self.current_speaker = None # 存储当前说话人
# llm相关变量
- self.dialogue = Dialogue()
+ self.dialogue = Dialogue(config=self.config, logger=self.logger)
# 工具调用统计(用于监控和自动恢复)
self.tool_call_stats = {
diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py
index 630453ba5..420d5365a 100644
--- a/main/xiaozhi-server/core/utils/dialogue.py
+++ b/main/xiaozhi-server/core/utils/dialogue.py
@@ -1,18 +1,19 @@
import uuid
import re
-from typing import List, Dict
+import logging
+from typing import List, Dict, Optional
from datetime import datetime
class Message:
def __init__(
- self,
- role: str,
- content: str = None,
- uniq_id: str = None,
- tool_calls=None,
- tool_call_id=None,
- is_temporary=False,
+ self,
+ role: str,
+ content: str = None,
+ uniq_id: str = None,
+ tool_calls=None,
+ tool_call_id=None,
+ is_temporary: bool = False,
):
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
self.role = role
@@ -23,10 +24,19 @@ class Message:
class Dialogue:
- def __init__(self):
+ def __init__(self, config: dict = None, logger: logging.Logger = None):
self.dialogue: List[Message] = []
- # 获取当前时间
- self.current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ self.logger = logger
+
+ # 从配置中读取最大历史轮数,默认为 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):
self.dialogue.append(message)
@@ -61,70 +71,66 @@ class Dialogue:
else:
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 是系统消息
- return 0
+ turns = []
+ current_turn = []
- # 分离系统消息和对话消息
- 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]
-
- # 从后向前收集消息
+ for msg in messages:
if msg.role == "user":
- # 遇到 user 消息,说明一轮对话开始
- keep_messages.insert(0, msg)
- turn_count += 1
- 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:
- i -= 1
- elif msg.role == "tool":
- # tool 消息应该已经被上面的逻辑收集了
- # 如果单独遇到,也要保留(防止边界情况)
- keep_messages.insert(0, msg)
- i -= 1
+ if current_turn:
+ turns.append(current_turn)
+ current_turn = [msg]
else:
- i -= 1
+ current_turn.append(msg)
- removed_count = len(conversation_messages) - len(keep_messages)
+ if current_turn:
+ turns.append(current_turn)
- # 重建对话列表
- self.dialogue = system_messages + keep_messages
+ return turns
- 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(
- self, memory_str: str = None, voiceprint_config: dict = None
+ self,
+ memory_str: str = None,
+ voiceprint_config: dict = None
) -> List[Dict[str, str]]:
# 构建对话
dialogue = []
@@ -143,28 +149,25 @@ class Dialogue:
)
# 添加说话人个性化描述
- try:
- speakers = voiceprint_config.get("speakers", [])
- if speakers:
- enhanced_system_prompt += "\n\n"
- for speaker_str in speakers:
- try:
- parts = speaker_str.split(",", 2)
- if len(parts) >= 2:
- name = parts[1].strip()
- # 如果描述为空,则为""
- description = (
- parts[2].strip() if len(parts) >= 3 else ""
- )
- enhanced_system_prompt += f"\n- {name}:{description}"
- except:
- pass
- enhanced_system_prompt += "\n\n"
- except:
- # 配置读取失败时忽略错误,不影响其他功能
- pass
+ if voiceprint_config:
+ try:
+ speakers = voiceprint_config.get("speakers", [])
+ if speakers:
+ enhanced_system_prompt += "\n\n"
+ for speaker_str in speakers:
+ try:
+ parts = speaker_str.split(",", 2)
+ if len(parts) >= 2:
+ name = parts[1].strip()
+ description = parts[2].strip() if len(parts) >= 3 else ""
+ enhanced_system_prompt += f"\n- {name}:{description}"
+ except Exception:
+ pass
+ enhanced_system_prompt += "\n\n"
+ except Exception:
+ pass
- # 使用正则表达式匹配 标签,不管中间有什么内容
+ # 注入记忆内容
if memory_str is not None:
enhanced_system_prompt = re.sub(
r".*?",
@@ -172,11 +175,50 @@ class Dialogue:
enhanced_system_prompt,
flags=re.DOTALL,
)
+
dialogue.append({"role": "system", "content": enhanced_system_prompt})
- # 添加用户和助手的对话
- for m in self.dialogue:
- if m.role != "system": # 跳过原始的系统消息
- self.getMessages(m, dialogue)
+ # 获取非系统消息
+ non_system_messages = [m for m in self.dialogue if m.role != "system"]
- return dialogue
+ 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)
+
+ return dialogue
\ No newline at end of file