From e4a4fc4624af41983f0b98fcdd86c352a10692c4 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 26 Nov 2025 21:28:45 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=20=E5=B9=B6=E8=A1=8C=E4=BC=98?= =?UTF-8?q?=E5=8C=96+=20=E6=89=93=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/handle/receiveAudioHandle.py | 293 ++++++++++++- .../core/parallel/degradation_manager.py | 2 + .../core/parallel/feature_flags.py | 4 +- .../core/parallel/interruption_handler.py | 2 + .../parallel/llm_compiler_orchestrator.py | 2 + .../core/parallel/parallel_chat_handler.py | 389 +++++++++++++++--- .../core/parallel/performance_tracer.py | 2 + .../core/parallel/priority_queue.py | 2 + .../core/parallel/state_machine.py | 9 + .../core/parallel/tests/__init__.py | 2 + .../parallel/tests/test_parallel_modules.py | 2 + .../xiaozhi-server/core/providers/tts/base.py | 32 +- .../functions/get_news_from_newsnow.py | 77 ++++ main/xiaozhi-server/test/test_page.html | 6 +- 14 files changed, 756 insertions(+), 68 deletions(-) diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 71bfdeff0..e2367c0b3 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -1,6 +1,8 @@ import time import json import asyncio +import threading +import concurrent.futures from core.utils.util import audio_to_data from core.handle.abortHandle import handleAbortMessage from core.handle.intentHandler import handle_user_intent @@ -8,8 +10,67 @@ from core.utils.output_counter import check_device_output_limit from core.handle.sendAudioHandle import send_stt_message, SentenceType from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO from typing import List, Dict, Any +from config.logger import setup_logging TAG = __name__ +logger = setup_logging() + + +def _get_parallel_chat_handler(conn): + """ + 获取或创建 ParallelChatHandler 实例 + + 缓存在 conn 对象上,避免重复创建 + """ + if hasattr(conn, '_parallel_chat_handler') and conn._parallel_chat_handler is not None: + return conn._parallel_chat_handler + + try: + from core.parallel import ParallelChatHandler, FeatureFlag, get_feature_manager + + # 检查是否启用 LLMCompiler + if not get_feature_manager().is_enabled(FeatureFlag.LLM_COMPILER): + return None + + conn._parallel_chat_handler = ParallelChatHandler(conn) + conn.logger.bind(tag=TAG).info("ParallelChatHandler 已初始化") + return conn._parallel_chat_handler + except ImportError as e: + conn.logger.bind(tag=TAG).warning(f"并行优化模块未安装: {e}") + return None + except Exception as e: + conn.logger.bind(tag=TAG).error(f"ParallelChatHandler 初始化失败: {e}") + return None + + +def _is_parallel_enabled() -> bool: + """检查并行优化是否启用""" + try: + from core.parallel.feature_flags import FeatureFlag, get_feature_manager + return get_feature_manager().is_enabled(FeatureFlag.LLM_COMPILER) + except ImportError: + return False + +# ============== 打断检测配置 ============== +# 业界最佳实践:持续语音检测 + 分层打断 + +# 持续语音检测阈值(避免短暂噪音、回声、咳嗽等误触发) +# 需要连续检测到语音的帧数才触发打断 +CONTINUOUS_VOICE_THRESHOLD = 3 # 连续 3 帧(约 180ms @ 60ms/帧) + +# 智能打断配置(用于 ASR 意图识别) +INTERRUPT_BUFFER_SIZE = 5 # 累积 5 个音频包(约 300ms @ 60ms/包) +INTERRUPT_ASR_TIMEOUT = 0.8 # 快速 ASR 超时时间(秒) +INTERRUPT_DEBOUNCE_MS = 500 # 打断防抖时间(毫秒) + +# 打断意图关键词 +INTERRUPTION_KEYWORDS = [ + "停", "等等", "打住", "不对", "算了", "别说了", + "我想问", "我要", "帮我", "听我说", "等一下" +] + +# 强制停止关键词(即使 TTS 未播放也会取消当前任务) +FORCE_STOP_KEYWORDS = ["停止", "取消", "算了", "不要了", "停下"] async def _smart_interrupt_handler(conn, text: str) -> bool: @@ -58,6 +119,12 @@ async def _smart_interrupt_handler(conn, text: str) -> bool: # 需要打断 if decision == InterruptionDecision.INTERRUPT: + # 通知 ParallelChatHandler 处理打断(如果存在) + parallel_handler = _get_parallel_chat_handler(conn) + if parallel_handler is not None: + await parallel_handler.handle_user_interruption(text) + + # 同时执行传统的打断处理 await handleAbortMessage(conn) return True @@ -82,6 +149,151 @@ def _is_smart_interruption_enabled() -> bool: return False +def _is_interruption_intent(text: str) -> bool: + """检测是否是打断意图""" + if not text: + return False + return any(keyword in text for keyword in INTERRUPTION_KEYWORDS) + + +def _is_force_stop_intent(text: str) -> bool: + """检测是否是强制停止意图(即使 TTS 未播放也生效)""" + if not text: + return False + return any(keyword in text for keyword in FORCE_STOP_KEYWORDS) + + +def _init_interrupt_state(conn): + """初始化打断检测状态""" + if not hasattr(conn, '_interrupt_buffer'): + conn._interrupt_buffer = [] + if not hasattr(conn, '_interrupt_check_running'): + conn._interrupt_check_running = False + if not hasattr(conn, '_last_interrupt_time'): + conn._last_interrupt_time = 0 + # 持续语音检测计数器 + if not hasattr(conn, '_continuous_voice_count'): + conn._continuous_voice_count = 0 + + +async def _parallel_interruption_check(conn, audio_chunk): + """ + 并行打断检测(目标 <400ms) + + 流程: + 1. 累积音频到打断检测缓冲区 + 2. 累积足够音频后触发快速 ASR + 3. 检测打断意图 + 4. 如果是打断,立即停止 TTS + """ + _init_interrupt_state(conn) + + # 防抖检查 + current_time = time.time() * 1000 + if (current_time - conn._last_interrupt_time) < INTERRUPT_DEBOUNCE_MS: + return + + # 累积音频到缓冲区 + conn._interrupt_buffer.append(audio_chunk) + + # 检查是否已经有正在运行的检测任务 + if conn._interrupt_check_running: + return + + # 累积足够音频后触发快速识别 + if len(conn._interrupt_buffer) >= INTERRUPT_BUFFER_SIZE: + conn._interrupt_check_running = True + audio_to_check = conn._interrupt_buffer.copy() + conn._interrupt_buffer.clear() + + # 启动异步检测任务 + asyncio.create_task(_quick_asr_and_check(conn, audio_to_check)) + + +async def _quick_asr_and_check(conn, audio_chunks): + """ + 快速 ASR + 打断意图检测 + + 在独立线程中执行 ASR,不阻塞主流程 + 目标:<400ms 完成打断响应 + """ + try: + start_time = time.time() + + # 使用线程池执行 ASR(避免阻塞事件循环) + loop = asyncio.get_event_loop() + + def run_quick_asr(): + """在线程中执行快速 ASR""" + try: + # 创建新的事件循环 + new_loop = asyncio.new_event_loop() + asyncio.set_event_loop(new_loop) + try: + # 调用现有 ASR 接口 + result = new_loop.run_until_complete( + conn.asr.speech_to_text( + audio_chunks, + conn.session_id + "_interrupt", + 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_quick_asr) + text = future.result(timeout=INTERRUPT_ASR_TIMEOUT) + except concurrent.futures.TimeoutError: + logger.bind(tag=TAG).debug("快速 ASR 超时,跳过本次检测") + return + + elapsed_ms = (time.time() - start_time) * 1000 + + # 检测打断意图 + if text and _is_interruption_intent(text): + # 再次检查是否还在说话(可能在 ASR 期间已经停止了) + if conn.client_is_speaking: + logger.bind(tag=TAG).info( + f"智能打断触发: '{text}' (耗时 {elapsed_ms:.0f}ms)" + ) + conn._last_interrupt_time = time.time() * 1000 + + # 通知 ParallelChatHandler 处理打断 + parallel_handler = _get_parallel_chat_handler(conn) + if parallel_handler is not None: + await parallel_handler.handle_user_interruption(text) + + # 执行传统的打断处理 + await handleAbortMessage(conn) + + # 记录打断响应时间 + total_elapsed_ms = (time.time() - start_time) * 1000 + if total_elapsed_ms > 400: + logger.bind(tag=TAG).warning( + f"打断响应超时: {total_elapsed_ms:.0f}ms > 400ms" + ) + else: + logger.bind(tag=TAG).info( + f"打断响应完成: {total_elapsed_ms:.0f}ms (目标 <400ms)" + ) + elif text: + logger.bind(tag=TAG).debug( + f"快速 ASR 识别: '{text}',非打断意图 (耗时 {elapsed_ms:.0f}ms)" + ) + + except Exception as e: + logger.bind(tag=TAG).error(f"快速打断检测失败: {e}") + finally: + conn._interrupt_check_running = False + + async def handleAudioMessage(conn, audio): # 当前片段是否有人说话 have_voice = conn.vad.is_vad(conn, audio) @@ -94,12 +306,30 @@ async def handleAudioMessage(conn, audio): conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) return - # 打断处理逻辑 - if have_voice and conn.client_is_speaking and conn.client_listen_mode != "manual": - # 智能打断模式:延迟到 ASR 识别完成后再决定是否打断 - # 传统模式:VAD 检测到声音立即打断 - if not _is_smart_interruption_enabled(): - await handleAbortMessage(conn) + # ============== 打断处理逻辑(业界最佳实践:持续语音检测) ============== + # 只有 TTS 正在播放且非手动监听模式时才检测打断 + if conn.client_is_speaking and conn.client_listen_mode != "manual": + # 初始化打断检测状态 + _init_interrupt_state(conn) + + if have_voice: + # 检测到语音,增加连续语音帧计数 + conn._continuous_voice_count += 1 + + # 当连续语音帧达到阈值时,触发打断 + # 这样可以过滤短暂噪音、回声、咳嗽等误触发 + if conn._continuous_voice_count >= CONTINUOUS_VOICE_THRESHOLD: + logger.bind(tag=TAG).info( + f"持续语音检测触发打断: 连续 {conn._continuous_voice_count} 帧 " + f"(阈值 {CONTINUOUS_VOICE_THRESHOLD} 帧, 约 {CONTINUOUS_VOICE_THRESHOLD * 60}ms)" + ) + # 重置计数器 + conn._continuous_voice_count = 0 + # 触发打断 + await handleAbortMessage(conn) + else: + # 没有检测到语音,重置连续语音帧计数 + conn._continuous_voice_count = 0 # 设备长时间空闲检测,用于say goodbye await no_voice_close_connect(conn, have_voice) @@ -159,7 +389,31 @@ async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]] await max_out_size(conn) return - # 智能打断处理 + # 提取用于检测的纯文本(去除JSON包装) + check_text = actual_text + try: + if actual_text.strip().startswith("{"): + parsed = json.loads(actual_text) + if "content" in parsed: + check_text = parsed["content"] + except (json.JSONDecodeError, KeyError): + pass + + # 强制停止检测:即使 TTS 未播放,如果有正在进行的 LLM 任务也要停止 + if _is_force_stop_intent(check_text): + # 检查是否有正在进行的 LLM 任务 + if not conn.llm_finish_task: + conn.logger.bind(tag=TAG).info(f"强制停止意图检测到: '{check_text}',取消当前任务") + await handleAbortMessage(conn) + # 不继续处理,直接返回 + return + # 如果 TTS 正在播放也要停止 + if conn.client_is_speaking: + conn.logger.bind(tag=TAG).info(f"强制停止 TTS 播放: '{check_text}'") + await handleAbortMessage(conn) + return + + # 智能打断处理(TTS 正在播放时) if conn.client_is_speaking and conn.client_listen_mode != "manual": should_continue = await _smart_interrupt_handler(conn, actual_text) if not should_continue: @@ -180,7 +434,30 @@ async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]] # if multimodal content is provided, use it, otherwise use text # in multimodal content, text is included in the content list chat_content = multimodal_content if multimodal_content else actual_text - conn.executor.submit(conn.chat, chat_content) + + # 尝试使用并行优化的聊天处理器 + parallel_handler = _get_parallel_chat_handler(conn) + if parallel_handler is not None and not multimodal_content: + # 使用并行优化的异步 chat 方法(仅支持文本,不支持 multimodal_content) + conn.logger.bind(tag=TAG).debug("使用 ParallelChatHandler 处理消息") + asyncio.create_task(_run_parallel_chat(conn, parallel_handler, actual_text)) + else: + # 降级到原始的同步 chat 方法(支持 multimodal_content) + conn.executor.submit(conn.chat, chat_content) + + +async def _run_parallel_chat(conn, handler, text: str): + """ + 运行并行聊天处理 + + 包装 ParallelChatHandler.chat() 的异步调用,处理异常并降级 + """ + try: + await handler.chat(text) + except Exception as e: + conn.logger.bind(tag=TAG).error(f"并行聊天处理失败: {e},降级到原始方法") + # 降级到原始方法 + conn.executor.submit(conn.chat, text) async def no_voice_close_connect(conn, have_voice): diff --git a/main/xiaozhi-server/core/parallel/degradation_manager.py b/main/xiaozhi-server/core/parallel/degradation_manager.py index fb4450d6d..6969a21f7 100644 --- a/main/xiaozhi-server/core/parallel/degradation_manager.py +++ b/main/xiaozhi-server/core/parallel/degradation_manager.py @@ -424,3 +424,5 @@ def is_feature_enabled(feature: str) -> bool: return get_degradation_manager().is_feature_enabled(feature) + + diff --git a/main/xiaozhi-server/core/parallel/feature_flags.py b/main/xiaozhi-server/core/parallel/feature_flags.py index b20e29311..36354c686 100644 --- a/main/xiaozhi-server/core/parallel/feature_flags.py +++ b/main/xiaozhi-server/core/parallel/feature_flags.py @@ -62,7 +62,7 @@ class FeatureFlagManager: description="启用过渡响应", ), FeatureFlag.SMART_INTERRUPTION: FeatureConfig( - enabled=True, + enabled=True, # 已修复:VAD 检测到声音后立即启动并行打断检测 description="启用智能打断(<400ms)", requires=[FeatureFlag.STATE_MACHINE], ), @@ -332,3 +332,5 @@ def disable(flag: FeatureFlag) -> bool: return get_feature_manager().disable(flag) + + diff --git a/main/xiaozhi-server/core/parallel/interruption_handler.py b/main/xiaozhi-server/core/parallel/interruption_handler.py index 610f6d03f..4301e02b1 100644 --- a/main/xiaozhi-server/core/parallel/interruption_handler.py +++ b/main/xiaozhi-server/core/parallel/interruption_handler.py @@ -307,3 +307,5 @@ class InterruptionHandler: ] + + diff --git a/main/xiaozhi-server/core/parallel/llm_compiler_orchestrator.py b/main/xiaozhi-server/core/parallel/llm_compiler_orchestrator.py index 218bd7aa1..8a692fefd 100644 --- a/main/xiaozhi-server/core/parallel/llm_compiler_orchestrator.py +++ b/main/xiaozhi-server/core/parallel/llm_compiler_orchestrator.py @@ -595,3 +595,5 @@ class LLMCompilerOrchestrator: } + + diff --git a/main/xiaozhi-server/core/parallel/parallel_chat_handler.py b/main/xiaozhi-server/core/parallel/parallel_chat_handler.py index 0b8a85f16..ee33eb9e6 100644 --- a/main/xiaozhi-server/core/parallel/parallel_chat_handler.py +++ b/main/xiaozhi-server/core/parallel/parallel_chat_handler.py @@ -187,20 +187,24 @@ class ParallelChatHandler: if depth == 0: self.conn.sentence_id = str(uuid.uuid4().hex) self.conn.llm_finish_task = False - self.conn.dialogue.put_message("user", query) + # 保存原始用户查询,用于 memory 查询(递归调用时使用) + self._original_query = query + from core.utils.dialogue import Message + self.conn.dialogue.put(Message(role="user", content=query)) self._send_first_message() # 获取 LLM 响应 result = await self._process_with_llm(query, depth) - # 记录性能 - duration_ms = (time.time() - start_time) * 1000 - self.degradation_manager.record_request( - latency_ms=duration_ms, - success=result, - ) + # 只在顶层调用时记录性能和打印日志,避免递归调用重复记录 + if depth == 0: + duration_ms = (time.time() - start_time) * 1000 + self.degradation_manager.record_request( + latency_ms=duration_ms, + success=result, + ) - if self.tracer: + if self.tracer and depth == 0: metrics = self.tracer.finish_trace() self.logger.bind(tag=TAG).info( f"[{self.session_id}] 聊天完成: " @@ -262,71 +266,182 @@ class ParallelChatHandler: ) async def _process_with_llm(self, query: str, depth: int) -> bool: - """使用 LLM 处理查询""" + """ + 使用 LLM 处理查询(流式) + + 优化策略: + 1. Memory 查询与 LLM 并行启动,减少串行等待 + 2. 条件过渡响应:LLM 首 token 超时才发送,避免割裂感 + 3. depth > 0 时复用缓存的 memory,避免用工具结果查询 memory + """ from core.utils.dialogue import Message from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType - # 获取对话历史 - memory_str = None - if self.conn.memory: - try: - memory_str = await self.conn.memory.query_memory(query) - except Exception as e: - self.logger.bind(tag=TAG).warning(f"记忆查询失败: {e}") - - dialogue_history = self.conn.dialogue.get_llm_dialogue_with_memory( - memory_str, self.conn.config.get("voiceprint", {}) - ) - - # 获取可用函数 + # 获取可用函数(本地操作,很快) functions = None if self.conn.intent_type == "function_call" and hasattr(self.conn, 'func_handler'): functions = self.conn.func_handler.get_functions() - # 调用 LLM + # 优化: depth=0 时查询 Memory 并缓存;depth > 0 时复用缓存 + 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 + else: + # 递归调用:复用缓存的 memory,避免用工具结果做查询 + memory_str = getattr(self, '_cached_memory_str', None) + + # 构建对话历史 + dialogue_history = self.conn.dialogue.get_llm_dialogue_with_memory( + memory_str, self.conn.config.get("voiceprint", {}) + ) + + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] 准备调用 LLM, dialogue_len={len(dialogue_history)}, has_functions={functions is not None}" + ) + + # 流式处理响应(带条件过渡) if self.tracer: with self.tracer.trace(TracePhase.RESPONSE_GENERATION): - llm_responses = await self._call_llm(dialogue_history, functions) + return await self._process_llm_response_with_transition( + query, dialogue_history, functions, depth + ) else: - llm_responses = await self._call_llm(dialogue_history, functions) + return await self._process_llm_response_with_transition( + query, dialogue_history, functions, depth + ) - # 处理响应 - return await self._process_llm_response(query, llm_responses, functions, depth) + async def _query_memory_with_timeout(self, query: str, timeout: float = 2.0) -> Optional[str]: + """ + 带超时的 Memory 查询 + + 避免 Memory 服务慢时阻塞整个流程 + """ + try: + return await asyncio.wait_for( + self.conn.memory.query_memory(query), + timeout=timeout + ) + except asyncio.TimeoutError: + self.logger.bind(tag=TAG).warning( + f"Memory 查询超时 ({timeout}s),跳过记忆注入" + ) + return None + except Exception as e: + self.logger.bind(tag=TAG).warning(f"Memory 查询异常: {e}") + return None - async def _call_llm( + + async def _call_llm_streaming( self, dialogue_history: List[Dict], functions: Optional[List[Dict]], - ) -> Any: - """调用 LLM""" + ): + """ + 流式调用 LLM(异步生成器) + + 与原始 chat 方法保持一致,实现真正的流式处理 + """ loop = asyncio.get_event_loop() - - if self.conn.intent_type == "function_call" and functions: - return await loop.run_in_executor( - None, - lambda: list(self.conn.llm.response_with_functions( - self.conn.session_id, - dialogue_history, - functions=functions, - )) + + # 创建一个队列用于线程间通信 + response_queue = asyncio.Queue() + + def run_llm(): + """在线程中运行 LLM 并将结果放入队列""" + response_count = 0 + try: + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] LLM 调用开始, intent_type={self.conn.intent_type}" + ) + if self.conn.intent_type == "function_call" and functions: + llm_gen = self.conn.llm.response_with_functions( + self.conn.session_id, + dialogue_history, + functions=functions, + ) + else: + llm_gen = self.conn.llm.response( + self.conn.session_id, + dialogue_history, + ) + + for response in llm_gen: + response_count += 1 + # 检查是否被打断 + if self.conn.client_abort: + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] LLM 被打断,已收到 {response_count} 个响应" + ) + break + # 使用线程安全的方式放入队列 + asyncio.run_coroutine_threadsafe( + response_queue.put(response), loop + ).result(timeout=5.0) + + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] LLM 调用完成,共收到 {response_count} 个响应" + ) + except Exception as e: + self.logger.bind(tag=TAG).error( + f"[{self.session_id}] LLM 调用异常: {e}" + ) + asyncio.run_coroutine_threadsafe( + response_queue.put(e), loop + ).result(timeout=5.0) + finally: + # 发送结束标记 + asyncio.run_coroutine_threadsafe( + response_queue.put(None), loop + ).result(timeout=5.0) + + # 在线程池中启动 LLM 调用 + if not self.conn.executor: + # 连接已关闭,提前退出 + self.logger.bind(tag=TAG).warning( + f"[{self.session_id}] executor 为 None,跳过 LLM 调用" ) + await response_queue.put(None) else: - return await loop.run_in_executor( - None, - lambda: list(self.conn.llm.response( - self.conn.session_id, - dialogue_history, - )) + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] 提交 LLM 任务到线程池" ) + self.conn.executor.submit(run_llm) + + # 异步生成响应 + while True: + response = await response_queue.get() + if response is None: + break + if isinstance(response, Exception): + raise response + yield response - async def _process_llm_response( + async def _process_llm_response_with_transition( self, query: str, - llm_responses: List, + dialogue_history: List[Dict], functions: Optional[List[Dict]], depth: int, ) -> bool: - """处理 LLM 响应""" + """ + 流式处理 LLM 响应(带条件过渡响应) + + 策略: + - 首 token 在 300ms 内到达 → 直接播放(够快,无需过渡) + - 首 token 超过 300ms → 先发过渡响应,再播放 LLM 内容 + - 这样在 LLM 快时无割裂感,LLM 慢时也有反馈 + """ from core.utils.dialogue import Message from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType from core.utils.util import extract_json_from_string @@ -338,10 +453,180 @@ class ParallelChatHandler: function_id = None function_arguments = "" content_arguments = "" + first_content_sent = False + transition_sent = False + + # 首 token 超时阈值(秒)- 超过此时间才发送过渡响应 + FIRST_TOKEN_TIMEOUT = 0.35 - for response in llm_responses: + self.logger.bind(tag=TAG).info( + f"[{self.session_id}] 开始 LLM 流式处理, depth={depth}" + ) + + # 启动定时器:如果超时还没收到首 token,发送过渡响应 + start_time = time.time() + timer_task = None + if depth == 0 and self.transition_generator: + async def send_transition_after_delay(): + await asyncio.sleep(FIRST_TOKEN_TIMEOUT) + nonlocal transition_sent + if not first_content_sent and not transition_sent: + self._send_quick_transition(query) + transition_sent = True + if self.tracer: + self.tracer.record_ttfr() + timer_task = asyncio.create_task(send_transition_after_delay()) + + # 启动 LLM 流式生成器 + llm_gen = self._call_llm_streaming(dialogue_history, functions) + + try: + async for response in llm_gen: + # 首次收到响应时取消定时器 + if timer_task and not timer_task.done(): + timer_task.cancel() + try: + await timer_task + except asyncio.CancelledError: + pass + timer_task = None + + # 检查打断 + if self.conn.client_abort: + self.logger.bind(tag=TAG).info("LLM 响应被用户打断") + break + + # 解析 response + content = None + if self.conn.intent_type == "function_call" and functions: + content, tools_call = response + if "content" in response: + content = response["content"] + tools_call = None + + if content: + content_arguments += content + + if not tool_call_flag and content_arguments.startswith(""): + tool_call_flag = True + + 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 + else: + content = response + + # 发送文本到 TTS(非工具调用时) + if content and not tool_call_flag: + response_message.append(content) + + # 记录 TTFR(首次响应时间) + if self.tracer and not first_content_sent: + self.tracer.record_ttfr() + first_content_sent = True + + # 立即发送到 TTS 队列 + self.conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=self.conn.sentence_id, + sentence_type=SentenceType.MIDDLE, + content_type=ContentType.TEXT, + content_detail=content, + ) + ) + finally: + # 确保定时器被清理 + if timer_task and not timer_task.done(): + timer_task.cancel() + + # 处理工具调用 + if tool_call_flag: + return await self._handle_tool_call( + query, function_name, function_id, function_arguments, + content_arguments, response_message, depth + ) + + # 存储对话 + if response_message: + text_buff = "".join(response_message) + self.conn.tts_MessageText = text_buff + self.conn.dialogue.put(Message(role="assistant", content=text_buff)) + + # 发送结束标记 + if depth == 0: + self.conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=self.conn.sentence_id, + sentence_type=SentenceType.LAST, + content_type=ContentType.ACTION, + ) + ) + + return True + + def _send_quick_transition(self, query: str) -> None: + """ + 发送简短过渡响应 + + 仅在 LLM 首 token 超时时调用,保持简短自然 + """ + from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType + + # 根据问题类型选择过渡词(保持简短,易于衔接) + if any(kw in query for kw in ["天气", "新闻", "查询", "搜索", "帮我查", "帮我找"]): + transition = "好的," + elif any(kw in query for kw in ["什么是", "怎么", "如何", "为什么"]): + transition = "嗯," + elif any(kw in query for kw in ["音乐", "播放", "放首"]): + transition = "好嘞," + else: + transition = "嗯," + + # 发送到 TTS + self.conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=self.conn.sentence_id, + sentence_type=SentenceType.MIDDLE, + content_type=ContentType.TEXT, + content_detail=transition, + ) + ) + + self.logger.bind(tag=TAG).debug( + f"[{self.session_id}] LLM 首 token 超时,发送过渡: {transition}" + ) + + async def _process_llm_response_streaming( + self, + query: str, + dialogue_history: List[Dict], + functions: Optional[List[Dict]], + depth: int, + ) -> bool: + """流式处理 LLM 响应(无过渡版本,供工具结果处理使用)""" + from core.utils.dialogue import Message + from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType + from core.utils.util import extract_json_from_string + from plugins_func.register import Action + + response_message = [] + tool_call_flag = False + function_name = None + function_id = None + function_arguments = "" + content_arguments = "" + first_content_sent = False + + # 使用流式生成器 + async for response in self._call_llm_streaming(dialogue_history, functions): # 检查打断 if self.conn.client_abort: + self.logger.bind(tag=TAG).info("LLM 响应被用户打断") break if self.conn.intent_type == "function_call" and functions: @@ -371,9 +656,9 @@ class ParallelChatHandler: if content and not tool_call_flag: response_message.append(content) - # 记录 TTFR - if self.tracer and len(response_message) == 1: + if self.tracer and not first_content_sent: self.tracer.record_ttfr() + first_content_sent = True self.conn.tts.tts_text_queue.put( TTSMessageDTO( @@ -628,3 +913,5 @@ class ParallelChatHandler: return stats + + diff --git a/main/xiaozhi-server/core/parallel/performance_tracer.py b/main/xiaozhi-server/core/parallel/performance_tracer.py index a08c7b13e..c6150a401 100644 --- a/main/xiaozhi-server/core/parallel/performance_tracer.py +++ b/main/xiaozhi-server/core/parallel/performance_tracer.py @@ -326,3 +326,5 @@ class PerformanceTracerFactory: return all_stats + + diff --git a/main/xiaozhi-server/core/parallel/priority_queue.py b/main/xiaozhi-server/core/parallel/priority_queue.py index 5febf679a..c663e64f7 100644 --- a/main/xiaozhi-server/core/parallel/priority_queue.py +++ b/main/xiaozhi-server/core/parallel/priority_queue.py @@ -362,3 +362,5 @@ class Full(Exception): pass + + diff --git a/main/xiaozhi-server/core/parallel/state_machine.py b/main/xiaozhi-server/core/parallel/state_machine.py index d43c5b047..80200cbde 100644 --- a/main/xiaozhi-server/core/parallel/state_machine.py +++ b/main/xiaozhi-server/core/parallel/state_machine.py @@ -37,6 +37,7 @@ class ConversationState(Enum): # 合法的状态转换映射 +# 优化:支持并发场景下的状态转换(如工具调用触发新查询、用户打断等) VALID_TRANSITIONS: Dict[ConversationState, List[ConversationState]] = { ConversationState.IDLE: [ ConversationState.PROCESSING_INTENT, @@ -54,6 +55,7 @@ VALID_TRANSITIONS: Dict[ConversationState, List[ConversationState]] = { ConversationState.PLAYING_TRANSITION: [ ConversationState.EXECUTING_TOOLS, ConversationState.GENERATING_RESPONSE, + ConversationState.SPEAKING, # 过渡响应后可直接进入播放 ConversationState.IDLE, ConversationState.INTERRUPTED, ConversationState.ERROR, @@ -61,17 +63,22 @@ VALID_TRANSITIONS: Dict[ConversationState, List[ConversationState]] = { ConversationState.EXECUTING_TOOLS: [ ConversationState.GENERATING_RESPONSE, ConversationState.SPEAKING, + ConversationState.PROCESSING_INTENT, # 工具执行后可能触发新查询 ConversationState.IDLE, ConversationState.INTERRUPTED, ConversationState.ERROR, ], ConversationState.GENERATING_RESPONSE: [ ConversationState.SPEAKING, + ConversationState.PROCESSING_INTENT, # 工具调用后触发新查询(递归调用) + ConversationState.PLAYING_TRANSITION, # 并发场景:生成响应时播放过渡 + ConversationState.EXECUTING_TOOLS, # 并发场景:响应中触发工具调用 ConversationState.IDLE, ConversationState.INTERRUPTED, ConversationState.ERROR, ], ConversationState.SPEAKING: [ + ConversationState.PROCESSING_INTENT, # 播放时用户新查询 ConversationState.IDLE, ConversationState.INTERRUPTED, ConversationState.ERROR, @@ -83,12 +90,14 @@ VALID_TRANSITIONS: Dict[ConversationState, List[ConversationState]] = { ], ConversationState.BACKCHANNELING: [ ConversationState.SPEAKING, + ConversationState.PROCESSING_INTENT, ConversationState.IDLE, ConversationState.INTERRUPTED, ConversationState.ERROR, ], ConversationState.ERROR: [ ConversationState.IDLE, + ConversationState.PROCESSING_INTENT, # 错误恢复后可处理新查询 ], } diff --git a/main/xiaozhi-server/core/parallel/tests/__init__.py b/main/xiaozhi-server/core/parallel/tests/__init__.py index 1db5526da..a1be0c1f3 100644 --- a/main/xiaozhi-server/core/parallel/tests/__init__.py +++ b/main/xiaozhi-server/core/parallel/tests/__init__.py @@ -1,3 +1,5 @@ """并行优化模块测试""" + + diff --git a/main/xiaozhi-server/core/parallel/tests/test_parallel_modules.py b/main/xiaozhi-server/core/parallel/tests/test_parallel_modules.py index a54664d5a..86066c0dc 100644 --- a/main/xiaozhi-server/core/parallel/tests/test_parallel_modules.py +++ b/main/xiaozhi-server/core/parallel/tests/test_parallel_modules.py @@ -356,3 +356,5 @@ if __name__ == "__main__": unittest.main() + + diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 6836c6adb..b7c025400 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -6,6 +6,7 @@ import queue import asyncio import threading import traceback +from concurrent.futures import ThreadPoolExecutor from core.utils import p3 from datetime import datetime from core.utils import textUtils @@ -27,6 +28,9 @@ from core.providers.tts.dto.dto import ( TAG = __name__ logger = setup_logging() +# TTS 生成线程池(全局共享,避免频繁创建) +_tts_executor = ThreadPoolExecutor(max_workers=3, thread_name_prefix="tts_gen_") + class TTSProviderBase(ABC): def __init__(self, config, delete_audio_file): @@ -52,10 +56,10 @@ class TTSProviderBase(ABC): ":", ) self.first_sentence_punctuations = ( - # ",", + ",", # 启用逗号,让首段更快播放 "~", "、", - # ",", + ",", # 启用英文逗号 "。", "?", "?", @@ -312,6 +316,9 @@ class TTSProviderBase(ABC): # 需要上报的文本和音频列表 enqueue_text = None enqueue_audio = None + # 用于跟踪上一个发送任务,确保顺序但不阻塞 + last_send_future = None + while not self.conn.stop_event.is_set(): text = None try: @@ -327,6 +334,7 @@ class TTSProviderBase(ABC): if self.conn.client_abort: logger.bind(tag=TAG).debug("收到打断信号,跳过当前音频数据") enqueue_text, enqueue_audio = None, [] + last_send_future = None continue # 收到下一个文本开始或会话结束时进行上报 @@ -341,12 +349,18 @@ class TTSProviderBase(ABC): if isinstance(audio_datas, bytes) and enqueue_audio is not None: enqueue_audio.append(audio_datas) - # 发送音频 - future = asyncio.run_coroutine_threadsafe( + # 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞 + if last_send_future is not None: + try: + last_send_future.result(timeout=5.0) + except Exception as e: + logger.bind(tag=TAG).warning(f"上一个音频发送超时或失败: {e}") + + # 异步发送音频(不阻塞等待) + last_send_future = asyncio.run_coroutine_threadsafe( sendAudioMessage(self.conn, sentence_type, audio_datas, text), self.conn.loop, ) - future.result() # 记录输出和报告 if self.conn.max_output_size > 0 and text: @@ -371,6 +385,9 @@ class TTSProviderBase(ABC): full_text = "".join(self.tts_text_buff) current_text = full_text[self.processed_chars :] # 从未处理的位置开始 last_punct_pos = -1 + + # 首句最小字符数(避免首句太短如"好的,") + MIN_FIRST_SEGMENT_CHARS = 8 # 根据是否是第一句话选择不同的标点符号集合 punctuations_to_use = ( @@ -388,6 +405,11 @@ class TTSProviderBase(ABC): if last_punct_pos != -1: segment_text_raw = current_text[: last_punct_pos + 1] + + # 首句长度检查:如果太短,等待更多文本 + if self.is_first_sentence and len(segment_text_raw) < MIN_FIRST_SEGMENT_CHARS: + return None # 继续等待更多文本 + segment_text = textUtils.get_string_no_punctuation_or_emoji( segment_text_raw ) diff --git a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py index 1d60aefdc..28c2c3968 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py +++ b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py @@ -161,12 +161,89 @@ def fetch_news_detail(url): logger.bind(tag=TAG).warning(f"清理后的新闻内容为空: {url}") return "无法解析新闻详情内容,可能是网站结构特殊或内容受限。" + # 清理无用内容:移除页面导航、版权、下载链接等 + clean_text = _clean_news_content(clean_text) + return clean_text except Exception as e: logger.bind(tag=TAG).error(f"获取新闻详情失败: {e}") return "无法获取详细内容" +def _clean_news_content(text: str) -> str: + """清理新闻内容,移除页面垃圾信息""" + import re + + lines = text.split('\n') + cleaned_lines = [] + + # 需要过滤的关键词(页面元素、导航等) + skip_patterns = [ + r'^\s*$', # 空行 + r'下载客户端', + r'登录', + r'无障碍', + r'扫码下载', + r'Android版|iPhone版|iPad版', + r'关于澎湃|加入澎湃|联系我们|广告合作|法律声明|隐私政策', + r'澎湃新闻报料', + r'澎湃新闻,未经授权不得转载', + r'沪ICP备|沪公网安备|互联网新闻信息服务许可证|增值电信业务经营许可证', + r'©.*上海东方报业', + r'反馈', + r'收藏', + r'我要举报', + r'查看更多', + r'开始答题', + r'新闻报料', + r'报料热线|报料邮箱', + r'澎湃矩阵', + r'澎湃新闻微博|澎湃新闻公众号|澎湃新闻抖音号', + r'派生万物开放平台|IP SHANGHAI|SIXTH TONE', + r'^\*\s*\+\d+', # 点赞数 + r'^\[\!\[.*\]\(.*\)\]', # markdown 图片链接 + r'^\!\[.*\]\(data:image', # base64 图片 + r'^#\s*$', # 空标题 + r'字号', + ] + + skip_regex = re.compile('|'.join(skip_patterns), re.IGNORECASE) + + in_content = False + for line in lines: + stripped = line.strip() + + # 检测正文开始(通常在日期/来源之后) + if re.match(r'^\d{4}-\d{2}-\d{2}', stripped): + in_content = True + continue + + # 检测正文结束标志 + if '责任编辑' in stripped or '校对' in stripped: + break + + # 跳过匹配的垃圾内容 + if skip_regex.search(stripped): + continue + + # 跳过纯链接行 + if stripped.startswith('[') and stripped.endswith(')'): + continue + + # 保留有意义的内容 + if stripped and len(stripped) > 5: + cleaned_lines.append(stripped) + + result = '\n'.join(cleaned_lines) + + # 限制最大长度(避免 token 过多) + max_length = 2000 + if len(result) > max_length: + result = result[:max_length] + "...(内容已截断)" + + return result + + @register_function( "get_news_from_newsnow", GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC, diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index 6eaf24c08..a19a0d9d7 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -1653,8 +1653,8 @@ // 使用与服务端期望的listen消息格式 const listenMessage = { type: 'listen', - mode: 'manual', // 使用手动模式,由我们控制开始/停止 - state: 'start' // 表示开始录音 + mode: 'auto', // 使用自动模式,服务器VAD检测说话结束 + state: 'start' }; log(`发送录音开始消息: ${JSON.stringify(listenMessage)}`, 'info'); @@ -1739,7 +1739,7 @@ // 发送监听结束消息 const stopMessage = { type: 'listen', - mode: 'manual', + mode: 'auto', state: 'stop' };