mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: 优化memory耗时
This commit is contained in:
parent
25e7587671
commit
61111c74a0
4 changed files with 265 additions and 40 deletions
|
|
@ -602,6 +602,10 @@ class ConnectionHandler:
|
|||
|
||||
def _initialize_asr(self):
|
||||
"""初始化ASR"""
|
||||
# 检查 _asr 是否为 None
|
||||
if self._asr is None:
|
||||
return initialize_asr(self.config)
|
||||
|
||||
if self._asr.interface_type == InterfaceType.LOCAL:
|
||||
# 如果公共ASR是本地服务,则直接返回
|
||||
# 因为本地一个实例ASR,可以被多个连接共享
|
||||
|
|
@ -892,6 +896,12 @@ class ConnectionHandler:
|
|||
depth: Recursive depth, for function calling
|
||||
"""
|
||||
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
|
||||
|
||||
# 检查 TTS 是否已初始化
|
||||
if self.tts is None:
|
||||
self.logger.bind(tag=TAG).error("TTS 未初始化,无法处理聊天请求")
|
||||
return False
|
||||
|
||||
self.llm_finish_task = False
|
||||
|
||||
# extract text content for memory query
|
||||
|
|
|
|||
|
|
@ -176,6 +176,127 @@ def _init_interrupt_state(conn):
|
|||
conn._continuous_voice_count = 0
|
||||
|
||||
|
||||
# 在用户开始说话时,提前预取 Memory,利用说话时间掩盖网络延迟
|
||||
|
||||
async def _trigger_memory_prefetch_on_voice_start(conn, have_voice: bool):
|
||||
"""
|
||||
检测语音开始边缘,触发 Memory 预取
|
||||
|
||||
策略:
|
||||
- 当检测到从"无声"到"有声"的边缘时,启动预取
|
||||
- 基于最近对话上下文构建查询
|
||||
- 预取结果缓存在 conn._prefetched_memory_task
|
||||
- ASR 完成后,ParallelChatHandler 使用预取结果
|
||||
|
||||
优势:
|
||||
- 用户说话时间(1~3秒)> Memory 查询时间(0.3~2秒)
|
||||
- 理想情况下,ASR 完成时 Memory 已就绪
|
||||
"""
|
||||
# 检查是否有 Memory 组件
|
||||
if not hasattr(conn, 'memory') or conn.memory is None:
|
||||
return
|
||||
|
||||
# 获取上一帧的语音状态
|
||||
prev_have_voice = getattr(conn, '_prev_have_voice_for_prefetch', False)
|
||||
conn._prev_have_voice_for_prefetch = have_voice
|
||||
|
||||
# 检测边缘:从无声到有声
|
||||
if have_voice and not prev_have_voice:
|
||||
# 如果已有正在进行的预取任务,不重复启动
|
||||
if hasattr(conn, '_prefetched_memory_task'):
|
||||
task = conn._prefetched_memory_task
|
||||
if task and not task.done():
|
||||
return
|
||||
|
||||
# 启动预取
|
||||
logger.bind(tag=TAG).debug("检测到语音开始,启动 Memory 预取")
|
||||
conn._prefetched_memory_task = asyncio.create_task(
|
||||
_prefetch_memory(conn)
|
||||
)
|
||||
|
||||
|
||||
async def _prefetch_memory(conn) -> None:
|
||||
"""
|
||||
预取 Memory(基于最近对话上下文)
|
||||
|
||||
查询策略:
|
||||
- 使用最近 2-3 轮用户发言作为查询上下文
|
||||
- 结果缓存到 conn._prefetched_memory_result
|
||||
- 设置 1.5 秒超时,避免阻塞过久
|
||||
"""
|
||||
try:
|
||||
import time
|
||||
start_time = time.time()
|
||||
|
||||
# 构建查询上下文:最近的用户发言
|
||||
context_query = _build_prefetch_query(conn)
|
||||
if not context_query:
|
||||
logger.bind(tag=TAG).debug("无有效对话上下文,跳过 Memory 预取")
|
||||
conn._prefetched_memory_result = None
|
||||
return
|
||||
|
||||
# 执行预取(带超时)
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
conn.memory.query_memory(context_query),
|
||||
timeout=1.5 # 预取超时 1.5 秒
|
||||
)
|
||||
conn._prefetched_memory_result = result
|
||||
elapsed_ms = (time.time() - start_time) * 1000
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Memory 预取完成: {elapsed_ms:.0f}ms, 结果长度: {len(result) if result else 0}"
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.bind(tag=TAG).debug("Memory 预取超时,将在 LLM 调用时重新查询")
|
||||
conn._prefetched_memory_result = None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"Memory 预取异常: {e}")
|
||||
conn._prefetched_memory_result = None
|
||||
|
||||
|
||||
def _build_prefetch_query(conn) -> str:
|
||||
"""
|
||||
构建预取查询字符串
|
||||
|
||||
策略:
|
||||
- 有历史对话:使用最近 2-3 轮用户发言拼接
|
||||
- 无历史对话(第一轮):使用通用查询,预取最近记忆
|
||||
"""
|
||||
try:
|
||||
if not hasattr(conn, 'dialogue') or conn.dialogue is None:
|
||||
# 第一轮:使用通用查询
|
||||
return "最近的对话记忆"
|
||||
|
||||
# 获取最近的对话消息
|
||||
messages = conn.dialogue.get_llm_dialogue()
|
||||
if not messages:
|
||||
# 第一轮:使用通用查询,预取最近记忆
|
||||
return "最近的对话记忆"
|
||||
|
||||
# 提取最近 3 条用户消息
|
||||
user_messages = []
|
||||
for msg in reversed(messages):
|
||||
if msg.get("role") == "user":
|
||||
content = msg.get("content", "")
|
||||
if content:
|
||||
user_messages.append(content)
|
||||
if len(user_messages) >= 3:
|
||||
break
|
||||
|
||||
if not user_messages:
|
||||
# 没有用户消息:使用通用查询
|
||||
return "最近的对话记忆"
|
||||
|
||||
# 反转回正序,拼接
|
||||
user_messages.reverse()
|
||||
return " ".join(user_messages)
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).debug(f"构建预取查询失败: {e}")
|
||||
return "最近的对话记忆"
|
||||
|
||||
|
||||
async def _parallel_interruption_check(conn, audio_chunk):
|
||||
"""
|
||||
并行打断检测(目标 <400ms)
|
||||
|
|
@ -306,6 +427,10 @@ async def handleAudioMessage(conn, audio):
|
|||
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
|
||||
return
|
||||
|
||||
# ============== Memory 预取(方案 A2)==============
|
||||
# 检测语音开始边缘(从无声到有声),提前预取 Memory
|
||||
await _trigger_memory_prefetch_on_voice_start(conn, have_voice)
|
||||
|
||||
# ============== 打断处理逻辑(业界最佳实践:持续语音检测) ==============
|
||||
# 只有 TTS 正在播放且非手动监听模式时才检测打断
|
||||
if conn.client_is_speaking and conn.client_listen_mode != "manual":
|
||||
|
|
|
|||
|
|
@ -133,6 +133,13 @@ class ParallelChatHandler:
|
|||
if hasattr(self.conn, 'clear_queues'):
|
||||
self.conn.clear_queues()
|
||||
|
||||
def _put_tts_message(self, message) -> bool:
|
||||
"""安全地向 TTS 队列发送消息,防止 conn.tts 为 None 时崩溃"""
|
||||
if hasattr(self.conn, 'tts') and self.conn.tts is not None:
|
||||
self.conn.tts.tts_text_queue.put(message)
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _request_user_confirmation(self, prompt: str) -> str:
|
||||
"""请求用户确认"""
|
||||
# 播放确认提示
|
||||
|
|
@ -246,6 +253,10 @@ class ParallelChatHandler:
|
|||
if self.degradation_manager.current_level >= DegradationLevel.MINIMAL:
|
||||
return False
|
||||
|
||||
# 检查 TTS 是否已初始化(必须在 TTS 就绪后才能使用并行优化)
|
||||
if not hasattr(self.conn, 'tts') or self.conn.tts is None:
|
||||
return False
|
||||
|
||||
# 检查必要组件
|
||||
if not hasattr(self.conn, 'func_handler') or not self.conn.func_handler:
|
||||
return False
|
||||
|
|
@ -256,23 +267,23 @@ class ParallelChatHandler:
|
|||
"""发送首条消息标记"""
|
||||
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
|
||||
|
||||
if hasattr(self.conn, 'tts') and self.conn.tts:
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.FIRST,
|
||||
content_type=ContentType.ACTION,
|
||||
)
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.FIRST,
|
||||
content_type=ContentType.ACTION,
|
||||
)
|
||||
)
|
||||
|
||||
async def _process_with_llm(self, query: str, depth: int) -> bool:
|
||||
"""
|
||||
使用 LLM 处理查询(流式)
|
||||
|
||||
优化策略:
|
||||
1. Memory 查询与 LLM 并行启动,减少串行等待
|
||||
2. 条件过渡响应:LLM 首 token 超时才发送,避免割裂感
|
||||
1. 优先使用 VAD 阶段预取的 Memory(方案 A2)
|
||||
2. 预取未命中时,短窗口等待查询
|
||||
3. depth > 0 时复用缓存的 memory,避免用工具结果查询 memory
|
||||
4. 条件过渡响应:LLM 首 token 超时才发送,避免割裂感
|
||||
"""
|
||||
from core.utils.dialogue import Message
|
||||
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
|
||||
|
|
@ -282,21 +293,14 @@ class ParallelChatHandler:
|
|||
if self.conn.intent_type == "function_call" and hasattr(self.conn, 'func_handler'):
|
||||
functions = self.conn.func_handler.get_functions()
|
||||
|
||||
# 优化: depth=0 时查询 Memory 并缓存;depth > 0 时复用缓存
|
||||
# 优化: 优先使用预取的 Memory,未命中再查询
|
||||
memory_str = None
|
||||
if self.conn.memory:
|
||||
if depth == 0:
|
||||
# 首次调用:使用原始用户查询进行 memory 查询
|
||||
memory_task = asyncio.create_task(
|
||||
self._query_memory_with_timeout(query)
|
||||
)
|
||||
try:
|
||||
memory_str = await memory_task
|
||||
# 缓存 memory 结果,供后续递归调用使用
|
||||
self._cached_memory_str = memory_str
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).warning(f"记忆查询失败: {e}")
|
||||
self._cached_memory_str = None
|
||||
# 首次调用:尝试使用 VAD 阶段预取的 Memory
|
||||
memory_str = await self._get_memory_with_prefetch(query)
|
||||
# 缓存 memory 结果,供后续递归调用使用
|
||||
self._cached_memory_str = memory_str
|
||||
else:
|
||||
# 递归调用:复用缓存的 memory,避免用工具结果做查询
|
||||
memory_str = getattr(self, '_cached_memory_str', None)
|
||||
|
|
@ -321,11 +325,92 @@ class ParallelChatHandler:
|
|||
query, dialogue_history, functions, depth
|
||||
)
|
||||
|
||||
async def _query_memory_with_timeout(self, query: str, timeout: float = 2.0) -> Optional[str]:
|
||||
async def _get_memory_with_prefetch(self, query: str) -> Optional[str]:
|
||||
"""
|
||||
获取 Memory(优先使用预取结果)
|
||||
|
||||
策略(方案 A2):
|
||||
1. 检查 VAD 阶段是否已预取 Memory
|
||||
2. 如果预取任务存在且已完成,直接使用结果
|
||||
3. 如果预取任务存在但未完成,短暂等待(300ms)
|
||||
4. 如果预取未命中或超时,用当前 query 重新查询
|
||||
|
||||
优势:
|
||||
- 用户说话时间(1~3秒)通常 > Memory 查询时间
|
||||
- 大部分情况下,ASR 完成时 Memory 已就绪
|
||||
- 最坏情况退化为短窗口等待
|
||||
"""
|
||||
import time
|
||||
start_time = time.time()
|
||||
|
||||
# 1. 尝试获取预取结果
|
||||
prefetch_result = await self._try_get_prefetched_memory()
|
||||
if prefetch_result is not None:
|
||||
elapsed_ms = (time.time() - start_time) * 1000
|
||||
self.logger.bind(tag=TAG).info(
|
||||
f"[{self.session_id}] 使用预取的 Memory, 等待耗时: {elapsed_ms:.0f}ms"
|
||||
)
|
||||
return prefetch_result
|
||||
|
||||
# 2. 预取未命中,用当前 query 查询(短窗口)
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"[{self.session_id}] 预取未命中,执行 Memory 查询"
|
||||
)
|
||||
return await self._query_memory_with_timeout(query, timeout=1.5)
|
||||
|
||||
async def _try_get_prefetched_memory(self) -> Optional[str]:
|
||||
"""
|
||||
尝试获取预取的 Memory 结果
|
||||
|
||||
Returns:
|
||||
str: Memory 结果,如果预取成功
|
||||
None: 如果预取未启动、未完成或失败
|
||||
"""
|
||||
# 检查是否有预取结果(已完成的结果)
|
||||
if hasattr(self.conn, '_prefetched_memory_result'):
|
||||
result = self.conn._prefetched_memory_result
|
||||
# 清理,避免下次复用旧结果
|
||||
delattr(self.conn, '_prefetched_memory_result')
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
# 检查是否有正在进行的预取任务
|
||||
if hasattr(self.conn, '_prefetched_memory_task'):
|
||||
task = self.conn._prefetched_memory_task
|
||||
if task and not task.done():
|
||||
# 预取任务还在进行,短暂等待
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(task),
|
||||
timeout=0.3 # 最多等 300ms
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"[{self.session_id}] 预取任务未完成,跳过等待"
|
||||
)
|
||||
return None
|
||||
|
||||
# 任务已完成,获取结果
|
||||
if task and task.done():
|
||||
# 清理任务引用
|
||||
delattr(self.conn, '_prefetched_memory_task')
|
||||
# 检查是否有结果
|
||||
if hasattr(self.conn, '_prefetched_memory_result'):
|
||||
result = self.conn._prefetched_memory_result
|
||||
delattr(self.conn, '_prefetched_memory_result')
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
async def _query_memory_with_timeout(self, query: str, timeout: float = 1.5) -> Optional[str]:
|
||||
"""
|
||||
带超时的 Memory 查询
|
||||
|
||||
避免 Memory 服务慢时阻塞整个流程
|
||||
|
||||
Args:
|
||||
query: 查询字符串
|
||||
timeout: 超时时间(秒),默认 1.5s(部署到 us-west-2 后足够)
|
||||
"""
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
|
|
@ -512,12 +597,14 @@ class ParallelChatHandler:
|
|||
|
||||
if tools_call:
|
||||
tool_call_flag = True
|
||||
if tools_call[0].id:
|
||||
function_id = tools_call[0].id
|
||||
if tools_call[0].function.name:
|
||||
function_name = tools_call[0].function.name
|
||||
if tools_call[0].function.arguments:
|
||||
function_arguments += tools_call[0].function.arguments
|
||||
tc = tools_call[0]
|
||||
if hasattr(tc, 'id') and tc.id:
|
||||
function_id = tc.id
|
||||
if hasattr(tc, 'function') and tc.function:
|
||||
if hasattr(tc.function, 'name') and tc.function.name:
|
||||
function_name = tc.function.name
|
||||
if hasattr(tc.function, 'arguments') and tc.function.arguments:
|
||||
function_arguments += tc.function.arguments
|
||||
else:
|
||||
content = response
|
||||
|
||||
|
|
@ -531,7 +618,7 @@ class ParallelChatHandler:
|
|||
first_content_sent = True
|
||||
|
||||
# 立即发送到 TTS 队列
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.MIDDLE,
|
||||
|
|
@ -559,7 +646,7 @@ class ParallelChatHandler:
|
|||
|
||||
# 发送结束标记
|
||||
if depth == 0:
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.LAST,
|
||||
|
|
@ -588,7 +675,7 @@ class ParallelChatHandler:
|
|||
transition = "嗯,"
|
||||
|
||||
# 发送到 TTS
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.MIDDLE,
|
||||
|
|
@ -643,12 +730,14 @@ class ParallelChatHandler:
|
|||
|
||||
if tools_call:
|
||||
tool_call_flag = True
|
||||
if tools_call[0].id:
|
||||
function_id = tools_call[0].id
|
||||
if tools_call[0].function.name:
|
||||
function_name = tools_call[0].function.name
|
||||
if tools_call[0].function.arguments:
|
||||
function_arguments += tools_call[0].function.arguments
|
||||
tc = tools_call[0]
|
||||
if hasattr(tc, 'id') and tc.id:
|
||||
function_id = tc.id
|
||||
if hasattr(tc, 'function') and tc.function:
|
||||
if hasattr(tc.function, 'name') and tc.function.name:
|
||||
function_name = tc.function.name
|
||||
if hasattr(tc.function, 'arguments') and tc.function.arguments:
|
||||
function_arguments += tc.function.arguments
|
||||
else:
|
||||
content = response
|
||||
|
||||
|
|
@ -660,7 +749,7 @@ class ParallelChatHandler:
|
|||
self.tracer.record_ttfr()
|
||||
first_content_sent = True
|
||||
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.MIDDLE,
|
||||
|
|
@ -684,7 +773,7 @@ class ParallelChatHandler:
|
|||
|
||||
# 发送结束标记
|
||||
if depth == 0:
|
||||
self.conn.tts.tts_text_queue.put(
|
||||
self._put_tts_message(
|
||||
TTSMessageDTO(
|
||||
sentence_id=self.conn.sentence_id,
|
||||
sentence_type=SentenceType.LAST,
|
||||
|
|
|
|||
|
|
@ -162,7 +162,8 @@ class PerformanceTracer:
|
|||
finally:
|
||||
span.finish()
|
||||
with self._lock:
|
||||
self._span_stack.pop()
|
||||
if self._span_stack:
|
||||
self._span_stack.pop()
|
||||
self._current_span = (
|
||||
self._span_stack[-1] if self._span_stack else None
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue