Merge pull request #16 from Plaud-AI/feat_agent_config

优化memory 并行计算 &  打断
This commit is contained in:
Leo 2025-12-01 16:36:49 +08:00 committed by GitHub
commit 26c46c654d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 336 additions and 41 deletions

View file

@ -602,6 +602,10 @@ class ConnectionHandler:
def _initialize_asr(self): def _initialize_asr(self):
"""初始化ASR""" """初始化ASR"""
# 检查 _asr 是否为 None
if self._asr is None:
return initialize_asr(self.config)
if self._asr.interface_type == InterfaceType.LOCAL: if self._asr.interface_type == InterfaceType.LOCAL:
# 如果公共ASR是本地服务,则直接返回 # 如果公共ASR是本地服务,则直接返回
# 因为本地一个实例ASR,可以被多个连接共享 # 因为本地一个实例ASR,可以被多个连接共享
@ -892,6 +896,12 @@ class ConnectionHandler:
depth: Recursive depth, for function calling depth: Recursive depth, for function calling
""" """
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") 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 self.llm_finish_task = False
# extract text content for memory query # extract text content for memory query

View file

@ -176,6 +176,184 @@ def _init_interrupt_state(conn):
conn._continuous_voice_count = 0 conn._continuous_voice_count = 0
# 伪流式预取配置
PSEUDO_STREAM_BUFFER_THRESHOLD = 8 # 触发预取的音频帧数阈值(约 500ms @ 60ms/帧)
PSEUDO_STREAM_ASR_TIMEOUT = 2.0 # 预取 ASR 超时时间(秒)
PSEUDO_STREAM_MEMORY_TIMEOUT = 1.5 # 预取 Memory 超时时间(秒)
def _init_pseudo_stream_state(conn):
"""初始化伪流式预取状态"""
if not hasattr(conn, '_pseudo_stream_buffer'):
conn._pseudo_stream_buffer = []
if not hasattr(conn, '_pseudo_stream_prefetch_triggered'):
conn._pseudo_stream_prefetch_triggered = False
if not hasattr(conn, '_prefetch_asr_text'):
conn._prefetch_asr_text = None
def _reset_pseudo_stream_state(conn):
"""重置伪流式预取状态(VAD 静默后调用)"""
conn._pseudo_stream_buffer = []
conn._pseudo_stream_prefetch_triggered = False
conn._prefetch_asr_text = None
async def _trigger_pseudo_streaming_prefetch(conn, audio: bytes, have_voice: bool):
"""
伪流式 ASR Memory 预取
策略:
- 检测语音开始时,开始累积音频 buffer
- buffer 累积到 ~500ms(约 8 帧)时,发送预取 ASR
- 用 ASR 部分结果预取 Memory
- 预取 query 来自用户当前说的话,天然与最终 query 相关
"""
# 检查是否有 Memory 组件
if not hasattr(conn, 'memory') or conn.memory is None:
return
_init_pseudo_stream_state(conn)
# 获取上一帧的语音状态
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:
_reset_pseudo_stream_state(conn)
logger.bind(tag=TAG).debug("检测到语音开始,开始累积音频 buffer")
# 检测边缘:从有声到无声 → 重置状态(静默后清理)
if not have_voice and prev_have_voice:
# 不立即重置,让 parallel_chat_handler 有机会使用预取结果
pass
# 累积音频到 buffer(仅在有声时)
if have_voice:
conn._pseudo_stream_buffer.append(audio)
# 检查是否达到预取阈值
if (len(conn._pseudo_stream_buffer) >= PSEUDO_STREAM_BUFFER_THRESHOLD
and not conn._pseudo_stream_prefetch_triggered):
conn._pseudo_stream_prefetch_triggered = True
# 复制当前 buffer 用于预取(不影响后续累积)
prefetch_buffer = conn._pseudo_stream_buffer.copy()
logger.bind(tag=TAG).info(
f"触发伪流式预取: buffer={len(prefetch_buffer)} 帧 "
f"(~{len(prefetch_buffer) * 60}ms)"
)
# 异步启动预取任务
conn._prefetched_memory_task = asyncio.create_task(
_pseudo_stream_prefetch_memory(conn, prefetch_buffer)
)
async def _pseudo_stream_prefetch_memory(conn, audio_buffer: List[bytes]) -> None:
"""
伪流式预取 Memory
"""
try:
start_time = time.time()
# Step 1: 预取 ASR(用部分音频获取部分文本)
partial_text = await _quick_asr_for_prefetch(conn, audio_buffer)
if not partial_text or len(partial_text.strip()) < 2:
logger.bind(tag=TAG).debug("预取 ASR 结果太短,跳过 Memory 预取")
conn._prefetched_memory_result = None
conn._prefetch_asr_text = None
return
# 保存预取的 ASR 文本(用于日志和调试)
conn._prefetch_asr_text = partial_text
asr_elapsed_ms = (time.time() - start_time) * 1000
logger.bind(tag=TAG).info(
f"预取 ASR 完成: {asr_elapsed_ms:.0f}ms, 部分文本: '{partial_text}'"
)
# Step 2: 用部分文本预取 Memory
memory_start = time.time()
try:
result = await asyncio.wait_for(
conn.memory.query_memory(partial_text),
timeout=PSEUDO_STREAM_MEMORY_TIMEOUT
)
conn._prefetched_memory_result = result
memory_elapsed_ms = (time.time() - memory_start) * 1000
total_elapsed_ms = (time.time() - start_time) * 1000
logger.bind(tag=TAG).info(
f"Memory 预取完成: ASR={asr_elapsed_ms:.0f}ms, "
f"Memory={memory_elapsed_ms:.0f}ms, 总计={total_elapsed_ms:.0f}ms, "
f"结果长度: {len(result) if result else 0}"
)
except asyncio.TimeoutError:
logger.bind(tag=TAG).debug("Memory 预取超时")
conn._prefetched_memory_result = None
except Exception as e:
logger.bind(tag=TAG).warning(f"伪流式预取异常: {e}")
conn._prefetched_memory_result = None
conn._prefetch_asr_text = None
async def _quick_asr_for_prefetch(conn, audio_buffer: List[bytes]) -> str:
"""
快速 ASR(用于伪流式预取)
复用现有 ASR 服务,对部分音频进行识别。
在线程池中执行,避免阻塞事件循环。
"""
try:
loop = asyncio.get_event_loop()
def run_asr():
"""在线程中执行 ASR"""
try:
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
try:
result = new_loop.run_until_complete(
conn.asr.speech_to_text(
audio_buffer,
conn.session_id + "_prefetch",
conn.audio_format
)
)
return result[0] if result else ""
finally:
new_loop.close()
except Exception as e:
logger.bind(tag=TAG).debug(f"预取 ASR 失败: {e}")
return ""
# 在线程池中执行,设置超时
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
try:
future = executor.submit(run_asr)
return future.result(timeout=PSEUDO_STREAM_ASR_TIMEOUT)
except concurrent.futures.TimeoutError:
logger.bind(tag=TAG).debug("预取 ASR 超时")
return ""
except Exception as e:
logger.bind(tag=TAG).warning(f"快速 ASR 异常: {e}")
return ""
async def _parallel_interruption_check(conn, audio_chunk): async def _parallel_interruption_check(conn, audio_chunk):
""" """
并行打断检测(目标 <400ms) 并行打断检测(目标 <400ms)
@ -306,7 +484,9 @@ async def handleAudioMessage(conn, audio):
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
return return
# ============== 打断处理逻辑(业界最佳实践:持续语音检测) ============== # 当音频 buffer 累积到 ~500ms 时,用部分 ASR 结果预取 Memory
await _trigger_pseudo_streaming_prefetch(conn, audio, have_voice)
# 只有 TTS 正在播放且非手动监听模式时才检测打断 # 只有 TTS 正在播放且非手动监听模式时才检测打断
if conn.client_is_speaking and conn.client_listen_mode != "manual": if conn.client_is_speaking and conn.client_listen_mode != "manual":
# 初始化打断检测状态 # 初始化打断检测状态

View file

@ -426,3 +426,4 @@ def is_feature_enabled(feature: str) -> bool:

View file

@ -309,3 +309,4 @@ class InterruptionHandler:

View file

@ -597,3 +597,4 @@ class LLMCompilerOrchestrator:

View file

@ -133,6 +133,13 @@ class ParallelChatHandler:
if hasattr(self.conn, 'clear_queues'): if hasattr(self.conn, 'clear_queues'):
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: async def _request_user_confirmation(self, prompt: str) -> str:
"""请求用户确认""" """请求用户确认"""
# 播放确认提示 # 播放确认提示
@ -246,6 +253,10 @@ class ParallelChatHandler:
if self.degradation_manager.current_level >= DegradationLevel.MINIMAL: if self.degradation_manager.current_level >= DegradationLevel.MINIMAL:
return False 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: if not hasattr(self.conn, 'func_handler') or not self.conn.func_handler:
return False return False
@ -256,8 +267,7 @@ class ParallelChatHandler:
"""发送首条消息标记""" """发送首条消息标记"""
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
if hasattr(self.conn, 'tts') and self.conn.tts: self._put_tts_message(
self.conn.tts.tts_text_queue.put(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.FIRST, sentence_type=SentenceType.FIRST,
@ -270,9 +280,10 @@ class ParallelChatHandler:
使用 LLM 处理查询(流式) 使用 LLM 处理查询(流式)
优化策略: 优化策略:
1. Memory 查询与 LLM 并行启动,减少串行等待 1. 优先使用 VAD 阶段预取的 Memory
2. 条件过渡响应:LLM 首 token 超时才发送,避免割裂感 2. 预取未命中时,短窗口等待查询
3. depth > 0 时复用缓存的 memory,避免用工具结果查询 memory 3. depth > 0 时复用缓存的 memory,避免用工具结果查询 memory
4. 条件过渡响应:LLM 首 token 超时才发送,避免割裂感
""" """
from core.utils.dialogue import Message from core.utils.dialogue import Message
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType 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'): if self.conn.intent_type == "function_call" and hasattr(self.conn, 'func_handler'):
functions = self.conn.func_handler.get_functions() functions = self.conn.func_handler.get_functions()
# 优化: depth=0 时查询 Memory 并缓存;depth > 0 时复用缓存 # 优化: 优先使用预取的 Memory,未命中再查询
memory_str = None memory_str = None
if self.conn.memory: if self.conn.memory:
if depth == 0: if depth == 0:
# 首次调用:使用原始用户查询进行 memory 查询 # 首次调用:尝试使用 VAD 阶段预取的 Memory
memory_task = asyncio.create_task( memory_str = await self._get_memory_with_prefetch(query)
self._query_memory_with_timeout(query)
)
try:
memory_str = await memory_task
# 缓存 memory 结果,供后续递归调用使用 # 缓存 memory 结果,供后续递归调用使用
self._cached_memory_str = memory_str self._cached_memory_str = memory_str
except Exception as e:
self.logger.bind(tag=TAG).warning(f"记忆查询失败: {e}")
self._cached_memory_str = None
else: else:
# 递归调用:复用缓存的 memory,避免用工具结果做查询 # 递归调用:复用缓存的 memory,避免用工具结果做查询
memory_str = getattr(self, '_cached_memory_str', None) memory_str = getattr(self, '_cached_memory_str', None)
@ -321,11 +325,101 @@ class ParallelChatHandler:
query, dialogue_history, functions, depth 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(优先使用预取结果)
策略:
1. 检查 VAD 阶段是否已预取 Memory
2. 如果预取任务存在且已完成,直接使用结果
3. 如果预取任务存在但未完成,短暂等待(300ms)
4. 如果预取未命中或超时,用当前 query 重新查询
"""
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: 如果预取未启动、未完成或失败
"""
# 获取预取的 ASR 文本
prefetch_asr_text = getattr(self.conn, '_prefetch_asr_text', 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:
if prefetch_asr_text:
self.logger.bind(tag=TAG).debug(
f"[{self.session_id}] 使用预取 Memory, "
f"预取 query: '{prefetch_asr_text}'"
)
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')
if result is not None and prefetch_asr_text:
self.logger.bind(tag=TAG).debug(
f"[{self.session_id}] 使用预取 Memory, "
f"预取 query: '{prefetch_asr_text}'"
)
return result
return None
async def _query_memory_with_timeout(self, query: str, timeout: float = 1.5) -> Optional[str]:
""" """
带超时的 Memory 查询 带超时的 Memory 查询
避免 Memory 服务慢时阻塞整个流程 避免 Memory 服务慢时阻塞整个流程
Args:
query: 查询字符串
timeout: 超时时间(秒),默认 1.5s(部署到 us-west-2 后足够)
""" """
try: try:
return await asyncio.wait_for( return await asyncio.wait_for(
@ -512,12 +606,14 @@ class ParallelChatHandler:
if tools_call: if tools_call:
tool_call_flag = True tool_call_flag = True
if tools_call[0].id: tc = tools_call[0]
function_id = tools_call[0].id if hasattr(tc, 'id') and tc.id:
if tools_call[0].function.name: function_id = tc.id
function_name = tools_call[0].function.name if hasattr(tc, 'function') and tc.function:
if tools_call[0].function.arguments: if hasattr(tc.function, 'name') and tc.function.name:
function_arguments += tools_call[0].function.arguments function_name = tc.function.name
if hasattr(tc.function, 'arguments') and tc.function.arguments:
function_arguments += tc.function.arguments
else: else:
content = response content = response
@ -531,7 +627,7 @@ class ParallelChatHandler:
first_content_sent = True first_content_sent = True
# 立即发送到 TTS 队列 # 立即发送到 TTS 队列
self.conn.tts.tts_text_queue.put( self._put_tts_message(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.MIDDLE, sentence_type=SentenceType.MIDDLE,
@ -559,7 +655,7 @@ class ParallelChatHandler:
# 发送结束标记 # 发送结束标记
if depth == 0: if depth == 0:
self.conn.tts.tts_text_queue.put( self._put_tts_message(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.LAST, sentence_type=SentenceType.LAST,
@ -588,7 +684,7 @@ class ParallelChatHandler:
transition = "嗯," transition = "嗯,"
# 发送到 TTS # 发送到 TTS
self.conn.tts.tts_text_queue.put( self._put_tts_message(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.MIDDLE, sentence_type=SentenceType.MIDDLE,
@ -643,12 +739,14 @@ class ParallelChatHandler:
if tools_call: if tools_call:
tool_call_flag = True tool_call_flag = True
if tools_call[0].id: tc = tools_call[0]
function_id = tools_call[0].id if hasattr(tc, 'id') and tc.id:
if tools_call[0].function.name: function_id = tc.id
function_name = tools_call[0].function.name if hasattr(tc, 'function') and tc.function:
if tools_call[0].function.arguments: if hasattr(tc.function, 'name') and tc.function.name:
function_arguments += tools_call[0].function.arguments function_name = tc.function.name
if hasattr(tc.function, 'arguments') and tc.function.arguments:
function_arguments += tc.function.arguments
else: else:
content = response content = response
@ -660,7 +758,7 @@ class ParallelChatHandler:
self.tracer.record_ttfr() self.tracer.record_ttfr()
first_content_sent = True first_content_sent = True
self.conn.tts.tts_text_queue.put( self._put_tts_message(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.MIDDLE, sentence_type=SentenceType.MIDDLE,
@ -684,7 +782,7 @@ class ParallelChatHandler:
# 发送结束标记 # 发送结束标记
if depth == 0: if depth == 0:
self.conn.tts.tts_text_queue.put( self._put_tts_message(
TTSMessageDTO( TTSMessageDTO(
sentence_id=self.conn.sentence_id, sentence_id=self.conn.sentence_id,
sentence_type=SentenceType.LAST, sentence_type=SentenceType.LAST,

View file

@ -162,6 +162,7 @@ class PerformanceTracer:
finally: finally:
span.finish() span.finish()
with self._lock: with self._lock:
if self._span_stack:
self._span_stack.pop() self._span_stack.pop()
self._current_span = ( self._current_span = (
self._span_stack[-1] if self._span_stack else None self._span_stack[-1] if self._span_stack else None

View file

@ -364,3 +364,4 @@ class Full(Exception):

View file

@ -358,3 +358,4 @@ if __name__ == "__main__":