diff --git a/docs/s2s-provider-integration.md b/docs/s2s-provider-integration.md new file mode 100644 index 000000000..a88fdae7c --- /dev/null +++ b/docs/s2s-provider-integration.md @@ -0,0 +1,102 @@ +# 语音进语音出(S2S)provider 使用教程 + +## 概述 + +原版链路是 VAD → ASR → 文字 LLM → TTS 的级联:一问一答,模型说话时不能插嘴。S2S(speech-to-speech)provider 把中间那一格换成一个 +自己判轮次、自己出声、能被打断的实时语音模型,比如 OpenAI Realtime。设备固件和协议完全不变,服务器的工具、记忆、OTA、 +白名单也照用。 + +目前自带的 provider: + +| 名称 | type | 传输 | 说明 | +|---|---|---|---| +| OpenAIRealtime | `openai_realtime` | WebSocket 直连 `wss://api.openai.com/v1/realtime` | 平台 API key;模型侧 server_vad / semantic_vad 判轮次;真机说完约 0.5~1.2 秒出声,可以开口打断 | + +## 工作原理 + +``` +设备 Opus ──▶ connection._route_message 解成 PCM ──▶ provider.on_pcm ──▶(残余回声门控)──▶ 16 k → 24 k ──▶ 模型 +模型音频 ──▶ provider ──▶ 24 kHz 60 ms Opus ──▶ 上游节拍器 sendAudio ──▶ 设备(tts start / sentence_start / stop 照发) +模型转写 ──▶ stt / tts sentence_start 给设备显示;写进 conn.dialogue,连接关闭时由记忆模块照常保存 +工具 ──▶ Intent=function_call 的统一工具处理器(服务端插件 / server_mcp / 设备 MCP / MCP 接入点) +打断 ──▶ 设备 abort、模型侧 VAD 检到用户开口、本地门控连续几帧判为人声 → handleAbortMessage → provider.cancel + (丢掉未发的帧、取消模型回复、把模型上下文截到设备实际播到的位置) +``` + +选中 S2S 的连接不再初始化 TTS 和 ASR;上游会话在握手时建立(限时 `connect_timeout_s`),建不成就自动回退到原版级联, +同一条连接、设备无感。模型最后一次出声回答之后 `idle_close_s` 秒没有新回答,连接关闭,设备回待机。 + +改动的上游文件只有 4 个、五处小钩子:`core/connection.py`(`self.s2s`、`_route_message` 入队前分流、`_initialize_components` 跳过 TTS / ASR、 +`close()` 关上游会话)、`core/handle/abortHandle.py`、`core/handle/receiveAudioHandle.py` 的 `startToChat`、 +`core/handle/textHandler/listenMessageHandler.py`(维护 `conn.client_is_listening`:`listen start` 之前的唤醒词音频不送模型)。 +其余都在 `core/providers/s2s/` 和 `core/utils/s2s.py`。 + +## 接口规范(写一个新 provider) + +目录与 LLM / TTS 相同:`core/providers/s2s//.py`,类名 `S2SProvider`,继承 `core/providers/s2s/base.py` 的 `S2SProviderBase`: + +| 方法 | 何时被调 | 要做什么 | +|---|---|---| +| `open()` | 连接初始化(执行器线程经 `attach_s2s` 调度到事件循环,限时) | 建上游会话;抛异常 = 失败,连接回退级联 | +| `after_components_ready()` | 原版把提示词增强、工具处理器建好之后(执行器线程) | 把 `conn.prompt` 与 `conn.func_handler.get_functions()` 同步给上游 | +| `on_pcm(pcm16k)` | 每收到一帧设备音频(16 kHz 单声道 PCM,60 ms) | 送给模型 | +| `on_text(text)` | 唤醒词 detect、文字消息、结束语 | 作为用户输入交给模型;唤醒词是固定的 `嘿,你好呀` | +| (读)`conn.client_is_listening` | 上游 listen 处理器在 start / stop 时维护 | `on_pcm` 据此决定送不送模型;provider 建成常晚于 listen start,所以状态记在连接上 | +| `cancel(reason)` | 打断(`device` 来自设备按键;模型侧 / 本地由 provider 自己发起) | 丢帧、取消、截断 | +| `close()` | 连接关闭 | 收尾 | + +下行请用基类里的 `DeviceSpeaker`:`begin()`(一条新回复)、`push(pcm)`(模型音频)、`end()`(回复结束,等设备播完再发 stop)、 +`interrupt()`、`played_ms()`(设备大约播到了哪,截断用)。它走上游现成的 `AudioRateController`,前 5 帧直接发当缓冲,之后 60 ms 一帧。 + +工具接线请用 `core/providers/s2s/tools.py`:`to_realtime_tools()` 把工具清单拍平,`ToolRunner.run(name, arguments)` 执行并翻成文字, +白名单、限频、request_id 日志都在里面。 + +## 配置指南 + +### 方式 1:配置文件(单模块部署) + +`data/.config.yaml`: + +```yaml +selected_module: + S2S: OpenAIRealtime # 不填或留空 = 原版级联 + Intent: function_call # 工具要走统一工具处理器 + # VAD / LLM / TTS / ASR 照常配置:S2S 握手失败会回退到它们 + +S2S: + OpenAIRealtime: + type: openai_realtime + api_key: 你的OpenAI平台密钥 + model_name: gpt-realtime + voice: marin + turn_detection: server_vad # 或 semantic_vad + vad_silence_ms: 400 + idle_close_s: 45 + echo_gate: true + local_barge: true +``` + +所有项的说明见 `config.yaml` 的 `S2S:` 块。 + +### 方式 2:智控台(全模块部署) + +暂不支持,智控台没有 S2S 这一类模块;全模块部署请在 `data/.config.yaml` 里按方式 1 配置,`selected_module.S2S` 会生效。 + +### 残余回声门控 + +设备端 AEC 之后,播放期间上行仍会漏一点与播放内容相关的回声;模型侧 VAD 会把它当成用户开口,模型播到半秒就被自己打断、 +再接着回答自己的回声。`echo_gate: true` 时 provider 用自己发出的音频当参考,按滞后与回传比把回声帧换成舒适噪声,人声放行。 +它复用 `selected_module.VAD` 的 silero onnx 模型;模型不在时只用能量判据。实测只有设备 AEC、不开门控的场景能不能稳, +建议先开着,再按日志里的 `gate` 统计决定。 + +## 附录:Mock 测试 + +`tests/core/providers/s2s/` 里有一个假的 Realtime WebSocket 服务端(`test_openai_realtime.py`),按脚本发事件、断言 provider +对上游和对设备分别发了什么;`tests/core/handle/test_s2s_slot.py` 用假 provider 验证四处钩子。都不出网、不用真 key: + +```bash +cd main/xiaozhi-server +pytest tests/core/providers/s2s tests/core/handle/test_s2s_slot.py -q +``` + +真机验收四项:唤醒后握手、语音控制工具(如 `hass_state` 开灯)、模型说话时插话、把 `api_key` 改错后设备无感回退到级联。 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 17329459a..c35fbbc36 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -249,6 +249,9 @@ selected_module: # 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令 # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-seed-2-0-lite-260215 Intent: function_call + # 语音进、语音出的全双工大脑(见下面的 S2S 配置块);不填或留空 = 原版 VAD→ASR→LLM→TTS 级联。 + # 选中后本连接不再初始化 TTS / ASR;上游会话握手失败会自动回退到级联,设备无感。 + # S2S: OpenAIRealtime # 意图识别,是用于理解用户意图的模块,例如:播放音乐 Intent: @@ -767,6 +770,47 @@ VLLM: base_url: https://ark.cn-beijing.volces.com/api/v3 model_name: lite api_key: 你的api_password +# ##################################################################################### +# ##########################以下是语音进语音出(S2S)模型配置################################# +# S2S(speech-to-speech)provider 把 VAD→ASR→LLM→TTS 中间那一格换成一个自己判轮次、自己出声、能被打断的实时语音模型。 +# 设备协议不变;工具(服务端插件 / server_mcp / 设备 MCP / MCP 接入点)照用 Intent=function_call 的统一工具处理器; +# 转写写进对话历史,记忆模块照常保存。详见 docs/s2s-provider-integration.md。 +S2S: + OpenAIRealtime: + type: openai_realtime + # OpenAI 平台的 API key(platform.openai.com),直连 wss://api.openai.com/v1/realtime + api_key: 你的OpenAI平台密钥 + url: wss://api.openai.com/v1/realtime + model_name: gpt-realtime + voice: marin + # 用户说话的转写模型(给设备显示、写进对话历史和记忆) + transcribe_model: gpt-4o-mini-transcribe + # 轮次检测:server_vad(静音满 vad_silence_ms 判停)或 semantic_vad(按语义判,vad_eagerness: low/medium/high/auto) + turn_detection: server_vad + vad_threshold: 0.5 + vad_silence_ms: 400 + vad_eagerness: auto + # 握手限时(秒):超时就回退到原版级联 + connect_timeout_s: 4 + # 模型最后一次真的出声回答之后多少秒没有新回答就关连接(设备回待机);0 = 不按空闲关闭 + idle_close_s: 45 + # 唤醒词的应答指令;留空则唤醒时不让模型开口 + wake_greeting: 用户刚叫醒你,只用两三个字回应,比如“我在”。 + # 残余回声门控:设备端 AEC 之后仍会漏一点播放回声,模型侧 VAD 会把它当成用户开口并打断自己。 + # 需要上游 VAD 的 silero onnx 模型(selected_module.VAD 的 model_dir);模型不在时只用能量判据。 + echo_gate: true + gate_lag_prior_ms: 200 + gate_lag_max_ms: 1200 + # 本地插话:门控连续 N 帧判为人声就本地停播(比等模型侧 VAD 快);0 = 关闭 + local_barge: true + local_barge_frames: 3 + # 工具白名单(空 = 全部)与每会话每分钟调用上限 + tools_allow: [] + tool_calls_per_minute: 12 + # 调试:日志里记转写正文(默认不记) + log_text: false + + TTS: # 当前支持的type为edge、doubao,可自行适配 EdgeTTS: diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 62d8fff80..35fe315af 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -22,6 +22,7 @@ from core.utils.util import ( ) from typing import Dict, Any from collections import deque +from core.utils.s2s import attach_s2s from core.utils.modules_initialize import ( initialize_modules, initialize_tts, @@ -117,6 +118,7 @@ class ConnectionHandler: self.client_is_speaking = False self.client_listen_mode = "auto" self.client_aec = False # 是否启用了服务端AEC + self.client_is_listening = False # 设备 listen start 到 stop 之间为 True(S2S provider 据此决定是否把音频送模型) # 线程任务相关 self.loop = None # 在 handle_connection 中获取运行中的事件循环 @@ -173,6 +175,7 @@ class ConnectionHandler: # iot相关变量 self.iot_descriptors = {} self.func_handler = None + self.s2s = None # 语音进语音出 provider(selected_module.S2S);None = 原版 VAD→ASR→LLM→TTS 级联 self.cmd_exit = self.config["exit_commands"] @@ -368,6 +371,12 @@ class ConnectionHandler: if isinstance(message, str): await handleTextMessage(self, message) elif isinstance(message, bytes): + if self.s2s is not None: + # S2S 模式:解完 Opus 直接交给 provider,不进 ASR 队列(没有 ASR 线程来取) + pcm_frame = self._decode_opus_packet(message) + if pcm_frame: + await self.s2s.on_pcm(pcm_frame) + return if self.vad is None or self.asr is None: return @@ -605,12 +614,15 @@ class ConnectionHandler: def _initialize_components(self): try: - if self.tts is None: + if self.s2s is None: + self.s2s = attach_s2s(self) # 选中 S2S 且上游会话建成则接管音频,不建 TTS / ASR;失败返回 None 走级联 + if self.tts is None and self.s2s is None: self.tts = self._initialize_tts() # 打开语音合成通道 - asyncio.run_coroutine_threadsafe( - self.tts.open_audio_channels(self), self.loop - ) + if self.s2s is None: + asyncio.run_coroutine_threadsafe( + self.tts.open_audio_channels(self), self.loop + ) if self.need_bind: self.bind_completed_event.set() return @@ -632,15 +644,16 @@ class ConnectionHandler: """初始化本地组件""" if self.vad is None: self.vad = self._vad - if self.asr is None: + if self.asr is None and self.s2s is None: self.asr = self._initialize_asr() # 初始化声纹识别 self._initialize_voiceprint() # 打开语音识别通道 - asyncio.run_coroutine_threadsafe( - self.asr.open_audio_channels(self), self.loop - ) + if self.s2s is None: + asyncio.run_coroutine_threadsafe( + self.asr.open_audio_channels(self), self.loop + ) """加载记忆""" self._initialize_memory() @@ -652,6 +665,8 @@ class ConnectionHandler: self._init_prompt_enhancement() """注入工具调用few-shot示例(仅function_call模式)""" self._inject_tool_call_fewshot() + if self.s2s is not None: + self.s2s.after_components_ready() # 把增强后的提示词与工具清单同步给上游会话 except Exception as e: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") @@ -1641,6 +1656,8 @@ class ConnectionHandler: await self.tts.close() if self.asr: await self.asr.close() + if self.s2s is not None: + await self.s2s.close() # 关掉上游语音会话,不然设备断开后会话还挂着计费 # 最后关闭线程池(避免阻塞) if self.executor: diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py index c4a2fa88b..b827dd4da 100644 --- a/main/xiaozhi-server/core/handle/abortHandle.py +++ b/main/xiaozhi-server/core/handle/abortHandle.py @@ -17,4 +17,6 @@ async def handleAbortMessage(conn: "ConnectionHandler"): json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}) ) conn.clearSpeakStatus() + if conn.s2s is not None: + await conn.s2s.cancel("device") # S2S 模式:丢掉未发的帧、取消上游回复、把上下文截到已播位置 conn.logger.bind(tag=TAG).info("Abort message received-end") diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 2e81a78b2..7e6e2e45d 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -7,6 +7,7 @@ if TYPE_CHECKING: from core.connection import ConnectionHandler from core.utils.util import audio_to_data from core.handle.abortHandle import handleAbortMessage +from core.utils.s2s import s2s_selected, s2s_on_text from core.handle.intentHandler import handle_user_intent from core.utils.output_counter import check_device_output_limit from core.handle.sendAudioHandle import send_stt_message, SentenceType @@ -41,6 +42,9 @@ async def resume_vad_detection(conn: "ConnectionHandler"): async def startToChat(conn: "ConnectionHandler", text): + if conn.s2s is not None or s2s_selected(conn): + await s2s_on_text(conn, text) # S2S 模式:文字(唤醒词 / 文字消息 / 结束语)交给语音模型;provider 还没建成就先排队 + return # 检查输入是否是JSON格式(包含说话人信息) speaker_name = None actual_text = text diff --git a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py index 545ccec4d..f3bb21e73 100644 --- a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py @@ -32,6 +32,9 @@ class ListenTextMessageHandler(TextMessageHandler): conn.logger.bind(tag=TAG).debug( f"客户端拾音模式:{conn.client_listen_mode}" ) + if msg_json["state"] in ("start", "stop"): + # 记在连接上而不是通知 provider:provider 常常在 listen start 之后才建成,建成时要能看到当前状态 + conn.client_is_listening = msg_json["state"] == "start" if msg_json["state"] == "start": # 设备从播放模式切回录音模式,清除所有音频状态和缓冲区 conn.reset_audio_states() diff --git a/main/xiaozhi-server/core/providers/s2s/__init__.py b/main/xiaozhi-server/core/providers/s2s/__init__.py new file mode 100644 index 000000000..a95c3152a --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/__init__.py @@ -0,0 +1,14 @@ +"""S2S(speech-to-speech,语音进、语音出)provider 插槽。 + +原版链路是 VAD → ASR → 文字 LLM → TTS 的级联,一问一答。S2S provider 把中间那一格换成一个自己判轮次、自己出声、 +能被打断的实时语音模型(OpenAI Realtime、GPT-Live 等),设备侧协议完全不变: + + 设备 Opus → connection._route_message 解成 PCM → provider.on_pcm → 上游模型 + 上游音频 → provider → 60 ms Opus → 上游现成的 sendAudio 节拍器 → 设备 + 工具 → conn.func_handler(服务端插件 / server_mcp / 设备 MCP / MCP 接入点) + 打断 → 设备 abort / 模型侧 VAD / 本地门控 → handleAbortMessage + provider.cancel + 记忆 → 转写写进 conn.dialogue,关闭时由原版保存 + +选中方式:selected_module.S2S 指向 S2S 配置块里的一个 provider;握手失败自动回退到原版级联(同一连接,设备无感)。 +目录约定与 LLM / TTS 一样:core/providers/s2s//.py 里的 S2SProvider 类,由 core/utils/s2s.py 创建。 +""" diff --git a/main/xiaozhi-server/core/providers/s2s/audio.py b/main/xiaozhi-server/core/providers/s2s/audio.py new file mode 100644 index 000000000..3ea6d6387 --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/audio.py @@ -0,0 +1,97 @@ +"""S2S 共用的音频工具:重采样、PCM → 60 ms Opus 帧。 + +设备侧:上行是 16 kHz 单声道 PCM(上游在 connection.py 里已经把 Opus 解开);下行按 hello 里的 audio_params 编 Opus +(默认 24 kHz,见 config.yaml 的 xiaozhi.audio_params)。 +模型侧:OpenAI Realtime 的 audio/pcm 只收发 24 kHz。所以上行要 16 k → 24 k,下行多数情况不用再采样。 + +重采样优先用标准库 audioop.ratecv(Python 3.10 / 3.11 有,3.13 移除);没有时退到 numpy 线性插值,音质够语音用。 +""" +from __future__ import annotations + +import warnings + +import numpy as np + +try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + import audioop # type: ignore +except ImportError: # Python >= 3.13 + audioop = None + +from core.utils.opus_encoder_utils import OpusEncoderUtils + + +class Resampler: + """16 位单声道 PCM 流式重采样,保留跨包状态,连续调用不产生接缝。""" + + def __init__(self, src_rate: int, dst_rate: int): + self.src_rate = int(src_rate) + self.dst_rate = int(dst_rate) + self.reset() + + def reset(self) -> None: + self._state = None + self._last = 0.0 # numpy 路径:上一包最后一个样本 + self._pos = 0.0 # numpy 路径:下一个输出样本在输入轴上的小数位置 + + def process(self, pcm: bytes) -> bytes: + if not pcm: + return b"" + if self.src_rate == self.dst_rate: + return bytes(pcm) + if audioop is not None: + out, self._state = audioop.ratecv(pcm, 2, 1, self.src_rate, self.dst_rate, self._state) + return out + return self._numpy_resample(pcm) + + def _numpy_resample(self, pcm: bytes) -> bytes: + x = np.frombuffer(pcm, dtype=np.int16).astype(np.float64) + # 把上一包的最后一个样本接在前面,位置轴:-1 是它,0..n-1 是本包 + src = np.concatenate(([self._last], x)) + ratio = self.src_rate / self.dst_rate + n = len(x) + positions = [] + p = self._pos + while p < n: + positions.append(p) + p += ratio + self._pos = p - n + self._last = float(x[-1]) + if not positions: + return b"" + pos = np.asarray(positions) + idx = np.floor(pos).astype(int) # -1 .. n-1 → src 下标 idx+1 + frac = pos - idx + a = src[idx + 1] + b = src[np.minimum(idx + 2, n)] + y = a + (b - a) * frac + return np.clip(np.rint(y), -32768, 32767).astype(np.int16).tobytes() + + +class OpusFramer: + """把任意长度的 PCM 攒成固定时长的 Opus 帧(默认 60 ms),用上游的 OpusEncoderUtils。""" + + def __init__(self, sample_rate: int, frame_ms: int = 60): + self.sample_rate = int(sample_rate) + self.frame_ms = int(frame_ms) + self.frame_bytes = self.sample_rate * self.frame_ms // 1000 * 2 + self._enc = OpusEncoderUtils(self.sample_rate, 1, self.frame_ms) + + def push(self, pcm: bytes) -> list[bytes]: + frames: list[bytes] = [] + if pcm: + self._enc.encode_pcm_to_opus_stream(pcm, False, frames.append) + return frames + + def flush(self) -> list[bytes]: + """把不足一帧的尾巴补零编出来(回复结束时调用)。""" + frames: list[bytes] = [] + self._enc.encode_pcm_to_opus_stream(b"", True, frames.append) + return frames + + def reset(self) -> None: + self._enc.reset_state() + + def close(self) -> None: + self._enc.close() diff --git a/main/xiaozhi-server/core/providers/s2s/base.py b/main/xiaozhi-server/core/providers/s2s/base.py new file mode 100644 index 000000000..1e427acfe --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/base.py @@ -0,0 +1,207 @@ +"""S2S provider 基类,以及所有 S2S provider 共用的"设备侧扬声器"(下行音频 → 设备)。 + +provider 的生命周期(都在连接的事件循环上,open() 除外由 core/utils/s2s.attach_s2s 从执行器线程里调度): + open() 建上游会话;抛异常 = 失败,连接回退到原版级联 + after_components_ready() 原版把 prompt 增强、工具处理器建好之后调用(执行器线程),把它们同步给上游 + on_pcm(pcm16k) 设备音频(已解 Opus,16 kHz 单声道,一帧 60 ms) + on_text(text) 文字入口:唤醒词 detect、文字消息、结束语 + conn.client_is_listening 设备 listen start 到 stop 之间为 True,由上游 listen 处理器维护;on_pcm 据此决定送不送模型 + cancel(reason) 打断:设备 abort(reason=device)由 handleAbortMessage 调过来;模型侧 / 本地插话由 provider 自己发起 + close() 连接关闭 + +下行走上游现成的节拍器(core/handle/sendAudioHandle.py 的 AudioRateController):前 5 帧直接发给设备当缓冲, +之后严格 60 ms 一帧。为了知道"设备实际播到哪了"(打断时要把模型上下文截到那个位置)和给回声门控当参考, +每个音频包后面跟一个 message 回调,在包真正发出的那一刻记一笔。 +""" +from __future__ import annotations + +import asyncio +import time +import uuid +from abc import ABC, abstractmethod +from typing import Optional + +from core.handle.sendAudioHandle import ( + PRE_BUFFER_COUNT, + AUDIO_FRAME_DURATION, + _do_send_audio, + _get_or_create_rate_controller, + send_display_message, + send_tts_message, +) +from core.providers.s2s.audio import OpusFramer, Resampler +from core.utils.dialogue import Message + +TAG = __name__ + + +class DeviceSpeaker: + """把模型的 PCM 变成设备的 Opus 帧并按节拍发出去;维护 tts start / stop 状态和已播位置。""" + + def __init__(self, conn, sample_rate: int, frame_ms: int = AUDIO_FRAME_DURATION, gate=None): + self.conn = conn + self.sample_rate = int(sample_rate) + self.frame_ms = int(frame_ms) + self.gate = gate + self.framer = OpusFramer(self.sample_rate, self.frame_ms) + # 回声门控的参考要 16 kHz:下行 PCM 另外重采样一份,按帧切给门控 + self._ref_rs = Resampler(self.sample_rate, 16000) if gate is not None else None + self._ref_buf = bytearray() + self._ref_frame_bytes = 16000 * self.frame_ms // 1000 * 2 + self.speaking = False # 设备在播放(从第一帧发出到设备播完),回声门控与打断判定都看它 + self.generation = 0 # begin() 自增;end() 等播完后只在没有新回复接上时才清 speaking + self.frames_sent = 0 # 本条回复里真正发给设备的帧数 + self.frames_queued = 0 + + async def begin(self) -> None: + """一条新回复开始:新的 sentence_id 让上游节拍器重置,清掉上一条的打断标记。""" + self.conn.sentence_id = uuid.uuid4().hex + self.conn.client_abort = False + self.generation += 1 + self.frames_sent = 0 + self.frames_queued = 0 + self.framer.reset() + self._ref_buf.clear() + if self._ref_rs is not None: + self._ref_rs.reset() + + async def push(self, pcm: bytes) -> None: + if not pcm: + return + if self._ref_rs is not None: + self._ref_buf.extend(self._ref_rs.process(pcm)) + await self._emit(self.framer.push(pcm)) + + async def end(self) -> None: + """回复结束(模型生成完):尾巴补零编出来,等设备真的播完再发 tts stop、再清 speaking。 + 模型生成比实时快得多,生成完时设备往往还要播好几秒;这几秒里回声门控必须仍当作"在播放", + 否则残余回声直接进模型,模型侧 VAD 把自己的声音当成用户开口(10-31 真机:连环 turn_detected)。""" + if self.speaking or self.frames_queued: + await self._emit(self.framer.flush()) + if not self.speaking: + return + gen = self.generation + await send_tts_message(self.conn, "stop") # 上游实现:等队列清空 + 预缓冲播放时间,再发 stop、清 client_is_speaking + if self.generation != gen: + return # 等待期间已经有新回复接上(begin 过了):播放状态由新回复接管 + self.speaking = False + if self.gate is not None: + self.gate.on_tts_stop(time.monotonic()) + if self.conn.close_after_chat: + await self.conn.close() + + async def interrupt(self) -> None: + """被打断:丢掉还没发的帧。tts stop 消息由 handleAbortMessage 负责。""" + self.speaking = False + self.framer.reset() + self._ref_buf.clear() + rc = getattr(self.conn, "audio_rate_controller", None) + if rc is not None: + rc.reset() + if self.gate is not None: + self.gate.on_tts_stop(time.monotonic()) + + def played_ms(self) -> int: + """设备大约播到了本条回复的第几毫秒:已发出的帧减去设备侧预缓冲(前 PRE_BUFFER_COUNT 帧一次性发出)。""" + return max(0, (self.frames_sent - PRE_BUFFER_COUNT) * self.frame_ms) + + async def _emit(self, frames: list[bytes]) -> None: + if not frames: + return + conn = self.conn + if not self.speaking: + self.speaking = True + if self.gate is not None: + self.gate.on_tts_start(time.monotonic()) + await send_tts_message(conn, "start") + conn.client_is_speaking = True + rc, fc = _get_or_create_rate_controller(conn, self.frame_ms, True, 0) + for opus in frames: + if conn.client_abort: + return + conn.last_activity_time = time.time() * 1000 + self.frames_queued += 1 + if fc["packet_count"] < PRE_BUFFER_COUNT: + await _do_send_audio(conn, opus, fc) + self._mark_sent() + else: + rc.add_audio(opus) + rc.add_message(self._mark_sent_async) + + def _mark_sent(self) -> None: + self.frames_sent += 1 + if self.gate is not None: + n = self._ref_frame_bytes + ref = bytes(self._ref_buf[:n]) + del self._ref_buf[:n] + if len(ref) < n: + ref = ref + b"\x00" * (n - len(ref)) + self.gate.on_downlink(ref, time.monotonic()) + + async def _mark_sent_async(self) -> None: + self._mark_sent() + + +class S2SProviderBase(ABC): + def __init__(self, config: dict, conn): + self.config = config or {} + self.conn = conn + self.logger = conn.logger + self._tasks: set[asyncio.Task] = set() + self.speaker: Optional[DeviceSpeaker] = None + + # ---------- 生命周期 ---------- + @abstractmethod + async def open(self) -> None: + """建上游会话。抛异常 = 失败,attach_s2s 会让连接回退到原版级联。""" + + def after_components_ready(self) -> None: + """原版组件(prompt 增强、工具处理器)就绪后被调用,注意在执行器线程里;要发消息请 run_coroutine_threadsafe。""" + + async def close(self) -> None: + for t in list(self._tasks): + t.cancel() + if self.speaker is not None: + await self.speaker.interrupt() + + # ---------- 设备侧事件 ---------- + @abstractmethod + async def on_pcm(self, pcm16k: bytes) -> None: + """设备上行 PCM(16 kHz 单声道,60 ms 一帧)。""" + + @abstractmethod + async def on_text(self, text: str) -> None: + """文字入口(唤醒词 detect、文字消息)。""" + + def on_listen(self, state: str | None, mode: str | None) -> None: + """保留给需要额外处理 listen 消息的 provider;聆听开关本身看 conn.client_is_listening(上游 listen 处理器维护)。""" + + @abstractmethod + async def cancel(self, reason: str) -> None: + """打断。reason:device(设备按键,经 handleAbortMessage)、server(模型侧判出有人开口)、local(本地门控)。""" + + # ---------- 公用小工具 ---------- + def spawn(self, coro) -> asyncio.Task: + t = asyncio.ensure_future(coro) + self._tasks.add(t) + t.add_done_callback(self._tasks.discard) + return t + + async def show_user_text(self, text: str) -> None: + """用户说了什么:设备屏幕显示 + 写进对话历史(记忆用)。""" + if not text: + return + self.conn.dialogue.put(Message(role="user", content=text)) + try: + await send_display_message(self.conn, text) + except Exception: # noqa: BLE001 + pass + + async def show_assistant_text(self, text: str) -> None: + if not text: + return + self.conn.dialogue.put(Message(role="assistant", content=text)) + try: + await send_tts_message(self.conn, "sentence_start", text) + except Exception: # noqa: BLE001 + pass diff --git a/main/xiaozhi-server/core/providers/s2s/echo_gate.py b/main/xiaozhi-server/core/providers/s2s/echo_gate.py new file mode 100644 index 000000000..3955970d6 --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/echo_gate.py @@ -0,0 +1,268 @@ +"""一级残余回声门控:S2S provider 在把设备上行送给模型之前,用它压掉设备端 AEC 剩下的回声。 + +为什么需要(2026-10-20 ESP32-S3 真机实测):设备端 AEC 之后,播放期间上行仍有与播放内容相关的残余:安静时 RMS 中位 25, +播放时峰值可到 1200,包络与下行相关、滞后稳定;模型侧 VAD 会把它当成用户开口,模型播到 0.5 秒就被自己打断、 +再接着回答自己的回声。门控打开后同样的场景 0 次误触发。 + +做法:provider 知道自己发了什么、什么时候发的: + 1. 参考 = 本段第一帧发送时刻起、按设备实际播放排列的下行 PCM(断流处补零); + 2. 滞后先验 200 ms,0~1200 ms 内按 50 ms 对数包络互相关复估(插话多时跳过); + 3. 回声回传比 g = 播放期间"上行功率 / 参考尾窗最大功率"的 90% 分位; + 4. 每 20 ms 子帧判:上行功率 > α·g·P_ref + (2×底噪)²,且 silero 判为人声 → 整帧放行并保持 300 ms; + 否则整帧换成底噪水平的舒适噪声。设备不在播放、或这一帧对应的时间窗里设备没放东西时直通。 +silero 直接用上游自带的 onnx 模型(models/snakers4_silero-vad),不装 torch;模型文件不在时只用能量判据并记一条警告。 +""" +from __future__ import annotations + +import collections +import math +import os +from pathlib import Path + +import numpy as np + +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +RATE = 16000 +SUB = RATE * 20 // 1000 # 20 ms 子帧 = 320 样本 +ENV_S = 0.02 +DEFAULT_VAD_MODEL = Path("models/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx") + +_SESSIONS: dict[str, object] = {} # 模型只加载一次,各会话各自保存状态 + + +class SileroVAD: + """silero VAD 的 onnx 推理(16 kHz、每次 512 样本 + 64 样本上下文),与上游 core/providers/vad/silero.py 同一模型。""" + + def __init__(self, path: Path): + key = str(path) + if key not in _SESSIONS: + import onnxruntime as ort + + opts = ort.SessionOptions() + opts.inter_op_num_threads = 1 + opts.intra_op_num_threads = 1 + _SESSIONS[key] = ort.InferenceSession(key, sess_options=opts, providers=["CPUExecutionProvider"]) + self.sess = _SESSIONS[key] + self.reset_states() + + def reset_states(self) -> None: + self.state = np.zeros((2, 1, 128), dtype=np.float32) + self.context = np.zeros((1, 64), dtype=np.float32) + + def __call__(self, chunk: np.ndarray) -> float: + """chunk:512 个 float32 样本(−1~1)。返回人声概率。""" + x = np.concatenate([self.context, chunk.reshape(1, -1).astype(np.float32)], axis=1) + out, self.state = self.sess.run(None, {"input": x, "state": self.state, "sr": np.array(16000, dtype=np.int64)}) + self.context = x[:, -64:] + return float(np.asarray(out).reshape(-1)[0]) + + +def load_vad(path: str | os.PathLike | None = None): + p = Path(path or DEFAULT_VAD_MODEL) + if not p.exists(): + logger.bind(tag=TAG).warning(f"silero VAD 模型不存在({p}),回声门控只用能量判据") + return None + return SileroVAD(p) + + +class EchoGate: + def __init__(self, alpha=2.0, floor_rms=25.0, g_quantile=0.90, g_prior=1e-2, lag_prior=0.20, + lag_min=0.0, lag_max=1.20, lag_step=0.02, lag_every=5.0, hold_s=0.30, + tail_back=0.12, tail_fwd=0.04, vad_threshold=0.5, vad=None, log_fn=None, seed=0, + start_window: tuple[float, float] | None = (0.08, 0.65)): + """默认值来自真机:公网入口下滞后 160~520 ms(相对本段第一帧发送时刻),残余回声相对参考 −8~−50 dB 起伏, + 上行到达抖动中位 31 ms、最大 143 ms(所以音频时钟按帧序号重建)。vad=None 表示只用能量判据。 + start_window=(最短, 最长) 秒:还没估出滞后之前,参考窗放宽到覆盖这段回声延迟(会话开头先验常常不准, + 窄窗盖不住,唤醒应答的回声漏给模型,模型去回答自己的回声)。""" + self.alpha = alpha + self.floor_rms = floor_rms + self.g_quantile = g_quantile + self.g_prior = g_prior + self.lag = lag_prior + self.lag_corr = None + self.lag_min, self.lag_max, self.lag_step, self.lag_every = lag_min, lag_max, lag_step, lag_every + self.hold_s = hold_s + self.tail_back, self.tail_fwd = tail_back, tail_fwd + self.start_window = start_window + self.vad_threshold = vad_threshold + self.vad = vad + self.t_audio = None + self.log = log_fn or (lambda m: logger.bind(tag=TAG).info(m)) + self.rng = np.random.default_rng(seed) + self.seg_t0 = None + self.seg_buf = bytearray() + self.seg_end = None + self.ratios = collections.deque(maxlen=250) + self.up_env = collections.deque(maxlen=400) + self.t_last_lag = -1e9 + self.g = None + self.hold_until = -1.0 + self.recent = collections.deque(maxlen=100) + self.stats = {"frames": 0, "bypass": 0, "pass": 0, "echo": 0, "lag_est": 0, "noref": 0, "lag_skip_barge": 0} + + # ---------- 事件 ---------- + @property + def seg(self) -> np.ndarray: + return np.frombuffer(self.seg_buf, dtype=np.int16) # 视图,不拷贝;别长期持有 + + def on_tts_start(self, t: float) -> None: + self.seg_t0 = None + self.seg_buf = bytearray() + self.seg_end = None + self.up_env.clear() + if self.vad is not None: + self.vad.reset_states() + + def on_downlink(self, pcm_bytes: bytes, t_send: float) -> None: + """设备收到一帧就排进播放队列:本帧开播时刻 = max(发送时刻, 上一帧播完)。断流时中间补零。pcm 是 16 kHz。""" + if self.seg_t0 is None: + self.seg_t0 = t_send + end_t = self.seg_t0 + len(self.seg_buf) / 2 / RATE + gap = t_send - end_t + if gap > 0.03: + self.seg_buf.extend(b"\x00\x00" * int(gap * RATE)) + self.seg_buf.extend(pcm_bytes) + + def on_tts_stop(self, t: float) -> None: + self.seg_end = t + + # ---------- 内部 ---------- + def _window(self) -> tuple[float, float]: + if self.lag_corr is None and self.start_window: + lo, hi = self.start_window + return max(self.tail_back, hi - self.lag), max(self.tail_fwd, self.lag - lo) + return self.tail_back, self.tail_fwd + + def _active(self, t: float, speaking: bool) -> bool: + if speaking and self.seg_t0 is not None: + return True + return self.seg_end is not None and self.seg_t0 is not None and t - self.seg_end < self.lag + self._window()[0] + 0.18 + + def _ref_sub(self, t_sub: float): + if self.seg_t0 is None: + return None + idx = int(round((t_sub - self.lag - self.seg_t0) * RATE)) + if idx < 0 or idx + SUB > len(self.seg_buf) // 2: + return None + return np.frombuffer(self.seg_buf, dtype=np.int16, count=SUB, offset=idx * 2) + + def _ref_power(self, t_sub: float): + best = None + tail_back, tail_fwd = self._window() + off = -tail_back + while off <= tail_fwd + 1e-9: + r = self._ref_sub(t_sub + off) + if r is not None: + p = float(np.mean(r.astype(np.float64) ** 2)) + best = p if best is None else max(best, p) + off += ENV_S + return best + + def _estimate_lag(self, t: float) -> None: + if len(self.up_env) < 100 or len(self.seg_buf) < 2 * RATE: + self.t_last_lag = t - self.lag_every + 0.5 + return + if self.recent and sum(self.recent) / len(self.recent) > 0.3: + self.stats["lag_skip_barge"] += 1 + self.t_last_lag = t - self.lag_every + 1.0 + return + self.t_last_lag = t + ups = np.array(self.up_env, dtype=np.float64) + W = 0.05 + seg = self.seg.astype(np.float64) + n_env = int(len(seg) / RATE / W) + wlen = int(RATE * W) + ref_env = np.sqrt(np.mean(seg[:n_env * wlen].reshape(n_env, wlen) ** 2, axis=1)) + del seg + quiet = ups[:, 1] <= np.median(ups[:, 1]) + up_log = np.log10(ups[:, 1] + 1.0) + ref_log = np.log10(ref_env + 1.0) + best_c, best_lag = -1.0, None + for lag in np.arange(self.lag_min, self.lag_max + 1e-9, self.lag_step): + k = np.floor((ups[:, 0] - lag - self.seg_t0) / W + 1e-6).astype(int) + m = (k >= 0) & (k < n_env) & quiet + if m.sum() < 30: + continue + x, y = up_log[m], ref_log[k[m]] + if x.std() < 1e-6 or y.std() < 1e-6: + continue + c = float(np.corrcoef(x, y)[0, 1]) + if c > best_c: + best_c, best_lag = c, float(lag) + self.stats["lag_est"] += 1 + accept = best_lag is not None and (best_c >= 0.5 or (best_c >= 0.25 and abs(best_lag - self.lag) <= 0.10)) + if accept: + old = self.lag + self.lag, self.lag_corr = best_lag, best_c + self.log(f"echo gate lag {old * 1000:.0f} -> {best_lag * 1000:.0f} ms (corr {best_c:.2f})") + else: + self.t_last_lag = t - self.lag_every + 1.0 + + def _vad_prob(self, a: np.ndarray) -> float: + if self.vad is None: + return 1.0 + x = a.astype(np.float32) / 32768.0 + probs = [] + for start in (0, max(0, len(x) - 512)): + chunk = x[start:start + 512] + if len(chunk) < 512: + chunk = np.pad(chunk, (0, 512 - len(chunk))) + probs.append(self.vad(chunk)) + return max(probs) + + # ---------- 主入口 ---------- + def process(self, pcm_bytes: bytes, t_recv: float, speaking: bool) -> tuple[bytes, str]: + """返回 (送给模型的 PCM, 判决)。判决首词:bypass / noref / pass / echo。t_recv 是这 60 ms 帧到达的时刻。""" + self.stats["frames"] += 1 + a = np.frombuffer(pcm_bytes, dtype=np.int16) + if self.t_audio is None: + self.t_audio = t_recv + else: + self.t_audio += 0.06 + if t_recv - self.t_audio > 0.2 or self.t_audio - t_recv > 0.1: + self.t_audio = t_recv + t_frame = self.t_audio + if not self._active(t_frame, speaking): + self.stats["bypass"] += 1 + return pcm_bytes, "bypass" + floor_p = (2.0 * self.floor_rms) ** 2 + g = self.g if self.g is not None else self.g_prior + any_pass = False + n_ref = 0 + for i in range(len(a) // SUB): + sub = a[i * SUB:(i + 1) * SUB].astype(np.float64) + t_sub = t_frame - 0.06 + i * ENV_S + 0.01 + p_up = float(np.mean(sub ** 2)) + self.up_env.append((t_sub, math.sqrt(p_up))) + p_ref = self._ref_power(t_sub) + if p_ref is None: + continue + n_ref += 1 + if p_ref > 1e3: + self.ratios.append(p_up / p_ref) + if p_up > self.alpha * g * p_ref + floor_p: + any_pass = True + if n_ref == 0: + self.stats["noref"] += 1 + self.recent.append(0) + return pcm_bytes, "noref" + if len(self.ratios) >= 50: + self.g = float(np.quantile(np.array(self.ratios), self.g_quantile)) + if (self.lag_corr is None and t_frame - self.t_last_lag >= 2.4) or t_frame - self.t_last_lag >= self.lag_every: + self._estimate_lag(t_frame) + vad_p = self._vad_prob(a) if any_pass or t_frame < self.hold_until else 0.0 + fresh = any_pass and vad_p >= self.vad_threshold + if fresh: + self.hold_until = t_frame + self.hold_s + if fresh or t_frame < self.hold_until: + self.stats["pass"] += 1 + self.recent.append(1) + return pcm_bytes, "pass" + self.stats["echo"] += 1 + self.recent.append(0) + noise = self.rng.normal(0.0, self.floor_rms, len(a)).astype(np.int16) + return noise.tobytes(), "echo" diff --git a/main/xiaozhi-server/core/providers/s2s/openai_realtime/__init__.py b/main/xiaozhi-server/core/providers/s2s/openai_realtime/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/core/providers/s2s/openai_realtime/openai_realtime.py b/main/xiaozhi-server/core/providers/s2s/openai_realtime/openai_realtime.py new file mode 100644 index 000000000..63686a9c0 --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/openai_realtime/openai_realtime.py @@ -0,0 +1,399 @@ +"""OpenAI Realtime 作为 S2S provider:WebSocket 直连平台(wss://api.openai.com/v1/realtime),平台 API key。 + +会话:握手时先建上游会话、等 session.created、发 session.update(指令 = 连接的系统提示词,工具 = func_handler 的清单); + 原版把提示词增强、工具处理器建好后(after_components_ready)再同步一次。 +上行:设备 16 kHz PCM → 残余回声门控(可关)→ 16 k → 24 k → input_audio_buffer.append;模型侧 server_vad 判轮次。 +下行:response.output_audio.delta(24 kHz PCM)→ 60 ms Opus → 上游节拍器 → 设备;转写用 tts sentence_start / stt 消息给设备显示, + 并写进 conn.dialogue 供记忆使用。 +打断:模型侧 speech_started、本地门控连续 N 帧判为人声、设备 abort 三条路都汇到 handleAbortMessage → cancel(): + 丢掉未发的帧、response.cancel(模型侧判的不用,它自己已取消)、conversation.item.truncate 截到设备实际播到的位置。 +工具:response.output_item.done 里的 function_call → core/providers/s2s/tools.py → function_call_output → response.create。 +结束:模型最后一次真的出声回答之后 idle_close_s 秒没有新回答就关连接(设备回待机);上游中途断开也关连接, + 设备重连时若上游仍不可用,attach_s2s 会让它回退到原版级联。 +日志只记事件、时长、字数,不记转写正文(log_text: true 才记);api_key 不打印。 +""" +from __future__ import annotations + +import asyncio +import base64 +import contextlib +import json +import os +import time + +from websockets.asyncio.client import connect +from websockets.exceptions import ConnectionClosed + +from core.handle.abortHandle import handleAbortMessage +from core.providers.s2s.audio import Resampler +from core.providers.s2s.base import DeviceSpeaker, S2SProviderBase +from core.providers.s2s.echo_gate import EchoGate, load_vad +from core.providers.s2s.tools import ToolRunner, to_realtime_tools + +TAG = __name__ + +RT_RATE = 24000 # Realtime 的 audio/pcm 只有 24 kHz +DEVICE_RATE = 16000 # 设备上行 +WAKE_TRIGGER = "嘿,你好呀" # 上游 listenMessageHandler 把唤醒词统一换成这句再进 startToChat +RESPONSE_START_WAIT_S = 10.0 # 我们发了 response.create 之后,最多等这么久算"回答进行中"(空闲关闭不打断它) +SPEECH_GRACE_S = 3.0 # 刚说完这么久内不按空闲关闭:留给模型起回复 +BENIGN_ERRORS = ("response_cancel_not_active", "conversation_already_has_active_response") + + +class S2SProvider(S2SProviderBase): + def __init__(self, config: dict, conn): + super().__init__(config, conn) + c = self.config + self.api_key = str(c.get("api_key") or "") + self.url = str(c.get("url") or "wss://api.openai.com/v1/realtime") + self.model = str(c.get("model_name") or "gpt-realtime") + self.voice = str(c.get("voice") or "marin") + self.transcribe_model = str(c.get("transcribe_model") or "gpt-4o-mini-transcribe") + self.turn_detection_type = str(c.get("turn_detection") or "server_vad") + self.vad_threshold = float(c.get("vad_threshold", 0.5)) + self.vad_silence_ms = int(c.get("vad_silence_ms", 400)) + self.vad_eagerness = str(c.get("vad_eagerness") or "auto") + self.connect_timeout_s = float(c.get("connect_timeout_s", 4)) + self.idle_close_s = float(c.get("idle_close_s", 45)) + self.wake_greeting = c.get("wake_greeting", "用户刚叫醒你,只用两三个字回应,比如“我在”。") + self.local_barge_frames = int(c.get("local_barge_frames", 3)) if c.get("local_barge", True) else 0 + self.log_text = bool(c.get("log_text", False)) + + gate = None + if c.get("echo_gate", True): + gate = EchoGate(vad=load_vad(self._vad_model_path()), + lag_prior=float(c.get("gate_lag_prior_ms", 200)) / 1000, + lag_max=float(c.get("gate_lag_max_ms", 1200)) / 1000) + self.gate = gate + self.speaker = DeviceSpeaker(conn, getattr(conn, "sample_rate", RT_RATE), gate=gate) + self.tools = ToolRunner(conn, conn.logger, per_minute=int(c.get("tool_calls_per_minute", 12)), + allow=c.get("tools_allow") or None) + self.up_rs = Resampler(DEVICE_RATE, RT_RATE) + + self.ws = None + self.rx_task = None + self.closing = False + self.resp_done = True + self.suppress = False # 被打断后丢掉本条回复剩下的音频,直到下一条 response.created + self.item_id = None # 当前助手消息(截断用) + self.want_response = False # 工具结果已交回、还没能发 response.create(当时有回复在进行) + self.in_speech = False + self.barge_run = 0 + self._pending_barge = None + self._tool_tasks: set[asyncio.Task] = set() + self._tools_sig = None + self._idle_handle = None + self.t_reply = time.monotonic() + self.t_speech_stopped = None + self.t_response_requested = None + self.stats = {"turns": 0, "cancelled": 0, "speech_started": 0, "barge_server": 0, "barge_local": 0, + "barge_device": 0, "up_frames": 0, "tools": 0, "first_audio_ms": []} + + # ---------- 会话 ---------- + def _vad_model_path(self): + try: + selected = (self.conn.config.get("selected_module") or {}).get("VAD") + model_dir = ((self.conn.config.get("VAD") or {}).get(selected) or {}).get("model_dir") + except AttributeError: + model_dir = None + if not model_dir: + return None + return os.path.join(model_dir, "src", "silero_vad", "data", "silero_vad.onnx") + + def _turn_detection(self) -> dict: + both = {"create_response": True, "interrupt_response": True} + if self.turn_detection_type == "semantic_vad": + return {"type": "semantic_vad", "eagerness": self.vad_eagerness, **both} + return {"type": "server_vad", "threshold": self.vad_threshold, "prefix_padding_ms": 300, + "silence_duration_ms": self.vad_silence_ms, **both} + + def _tool_list(self) -> list[dict]: + fh = getattr(self.conn, "func_handler", None) + funcs = [] + if fh is not None: + try: + funcs = fh.get_functions() or [] + except Exception: # noqa: BLE001 + funcs = [] + return to_realtime_tools(funcs, self.tools.allow or None) + + def _session(self) -> dict: + tools = self._tool_list() + self._tools_sig = tuple(sorted(t["name"] for t in tools)) + # 建成那一刻 conn.prompt 往往还是 None(快速提示词在之后才设置):先用配置里的原始 prompt,别让第一轮没有人设 + instructions = (getattr(self.conn, "prompt", None) or (self.conn.config.get("prompt") if isinstance(getattr(self.conn, "config", None), dict) else None) + or self.config.get("instructions") or "") + return { + "type": "realtime", + "instructions": instructions, + "tools": tools, + "tool_choice": "auto", + "output_modalities": ["audio"], + "audio": { + "input": {"format": {"type": "audio/pcm", "rate": RT_RATE}, + "transcription": {"model": self.transcribe_model}, + "turn_detection": self._turn_detection()}, + "output": {"format": {"type": "audio/pcm", "rate": RT_RATE}, "voice": self.voice}, + }, + } + + async def open(self) -> None: + if not self.api_key or self.api_key.startswith("你的"): + raise RuntimeError("api_key 未配置") + + async def _connect(): + ws = await connect(f"{self.url}?model={self.model}", + additional_headers={"Authorization": f"Bearer {self.api_key}"}, + max_size=None, open_timeout=None, ping_interval=20, ping_timeout=20) + try: + ev = json.loads(await ws.recv()) + if ev.get("type") != "session.created": + code = (ev.get("error") or {}).get("code") if ev.get("type") == "error" else "" + raise RuntimeError(f"first event {ev.get('type')} {code or ''}".strip()) + await ws.send(json.dumps({"type": "session.update", "session": self._session()}, ensure_ascii=False)) + return ws + except BaseException: + self.spawn(ws.close()) + raise + + t0 = time.monotonic() + self.ws = await asyncio.wait_for(_connect(), self.connect_timeout_s) + self.rx_task = self.spawn(self._rx_loop()) + self._arm_idle() + self.logger.bind(tag=TAG).info( + f"Realtime 会话已建立 model={self.model} turn={self.turn_detection_type} " + f"echo_gate={'on' if self.gate else 'off'} in {time.monotonic() - t0:.2f}s") + + def after_components_ready(self) -> None: + asyncio.run_coroutine_threadsafe(self._after_ready(), self.conn.loop) + + async def _after_ready(self) -> None: + await self._refresh_session() + from core.utils.s2s import drain_pending_texts + await drain_pending_texts(self.conn) # provider 建成前到的文字(唤醒词 detect 等)现在补送 + + async def _refresh_session(self) -> None: + session = self._session() + await self._send({"type": "session.update", "session": session}) + self.logger.bind(tag=TAG).info(f"会话配置已同步:指令 {len(session['instructions'])} 字、工具 {len(session['tools'])} 个") + + async def _maybe_refresh_tools(self) -> None: + tools = self._tool_list() + if tuple(sorted(t["name"] for t in tools)) != self._tools_sig: + await self._refresh_session() + + async def _send(self, obj: dict) -> None: + if self.ws is None: + return + with contextlib.suppress(ConnectionClosed): + await self.ws.send(json.dumps(obj, ensure_ascii=False)) + + async def close(self) -> None: + self.closing = True + if self._idle_handle is not None: + self._idle_handle.cancel() + for t in list(self._tool_tasks): + t.cancel() + await super().close() + if self.ws is not None: + with contextlib.suppress(Exception): + await self.ws.close() + if self.gate is not None: + self.stats["gate"] = dict(self.gate.stats, lag_ms=round(self.gate.lag * 1000)) + self.logger.bind(tag=TAG).info(f"Realtime 会话结束: {self.stats}") + + # ---------- 设备 → 模型 ---------- + async def on_pcm(self, pcm16k: bytes) -> None: + if self.closing or not pcm16k: + return + if self.gate is not None: + pcm16k, info = self.gate.process(pcm16k, time.monotonic(), self.speaker.speaking) + if self.local_barge_frames: + if self.speaker.speaking and info.startswith("pass"): + self.barge_run += 1 + if self.barge_run == self.local_barge_frames: + await self._barge("local") + else: + self.barge_run = 0 + # 设备 listen start 之前(唤醒词那几十帧)的音频不送模型:否则模型侧 VAD 把"你好小智"当一轮提问,唤醒后答两次。 + # 状态记在连接上(listenMessageHandler 维护):provider 建成常晚于 listen start,自己记会错过它 + if not getattr(self.conn, "client_is_listening", False): + return + pcm24 = self.up_rs.process(pcm16k) + await self._send({"type": "input_audio_buffer.append", "audio": base64.b64encode(pcm24).decode()}) + self.stats["up_frames"] += 1 + + async def on_text(self, text: str) -> None: + text = (text or "").strip() + if not text: + return + await self._maybe_refresh_tools() # 插件 / MCP 可能刚注册完:第一轮就要看得到 + if text == WAKE_TRIGGER: + if self.wake_greeting and self.resp_done and not self.speaker.speaking: + await self._create_response({"instructions": self.wake_greeting}) + return + await self.show_user_text(text) + await self._send({"type": "conversation.item.create", + "item": {"type": "message", "role": "user", + "content": [{"type": "input_text", "text": text}]}}) + await self._create_response() + + # ---------- 打断 ---------- + async def cancel(self, reason: str) -> None: + """reason=device 时来自 handleAbortMessage(它已发 tts stop、置 client_abort); + 模型侧 / 本地插话由 _barge 先调 handleAbortMessage,再经钩子到这里,真正的原因放在 _pending_barge。""" + if reason == "device" and self._pending_barge: + reason, self._pending_barge = self._pending_barge, None + had_audio = self.speaker.speaking or self.speaker.frames_sent > 0 + played = self.speaker.played_ms() + self.suppress = True + await self.speaker.interrupt() + if reason != "server" and not self.resp_done: + await self._send({"type": "response.cancel"}) # 模型侧自己判的插话(interrupt_response)已经取消过 + if had_audio and self.item_id: + await self._send({"type": "conversation.item.truncate", "item_id": self.item_id, + "content_index": 0, "audio_end_ms": played}) + self.stats[f"barge_{reason}"] = self.stats.get(f"barge_{reason}", 0) + 1 + self.logger.bind(tag=TAG).info(f"打断({reason}):截到 {played if had_audio else -1} ms") + + async def _barge(self, reason: str) -> None: + self._pending_barge = reason + await handleAbortMessage(self.conn) # 发 tts stop、置 client_abort,再经 abortHandle 的钩子调到 cancel() + + # ---------- 模型 → 设备 ---------- + async def _rx_loop(self) -> None: + try: + async for raw in self.ws: + try: + ev = json.loads(raw) + except ValueError: + continue + try: + await self._on_event(ev.get("type", ""), ev) + except Exception as e: # noqa: BLE001 + self.logger.bind(tag=TAG).error(f"处理 Realtime 事件 {ev.get('type')} 出错: {type(e).__name__}: {e}") + except ConnectionClosed: + pass + if not self.closing: + self.closing = True + self.logger.bind(tag=TAG).warning("Realtime 上游断开,关闭本连接(设备重连时若上游仍不可用会回退级联)") + self.spawn(self.conn.close()) + + async def _on_event(self, et: str, ev: dict) -> None: + conn = self.conn + if et == "input_audio_buffer.speech_started": + self.in_speech = True + conn.last_activity_time = time.time() * 1000 + self.stats["speech_started"] += 1 + if (self.speaker.speaking or self.speaker.frames_queued > self.speaker.frames_sent) and not self.suppress: + await self._barge("server") + await self._maybe_refresh_tools() # 用户开口到模型决定调工具之间还有几百毫秒,够把新注册的工具同步上去 + elif et == "input_audio_buffer.speech_stopped": + self.in_speech = False + self.t_speech_stopped = time.monotonic() + conn.last_activity_time = time.time() * 1000 + elif et == "response.created": + self.resp_done = False + self.suppress = False + self.t_response_requested = None + self.item_id = None + await self.speaker.begin() + elif et == "response.output_item.added": + item = ev.get("item") or {} + if item.get("type") == "message": + self.item_id = item.get("id") + elif et == "response.output_item.done": + item = ev.get("item") or {} + if item.get("type") == "function_call": + t = self.spawn(self._run_tool(item)) + self._tool_tasks.add(t) + t.add_done_callback(self._tool_tasks.discard) + elif et in ("response.output_audio.delta", "response.audio.delta"): + if self.suppress: + return + b = base64.b64decode(ev.get("delta") or "") + if b and self.t_speech_stopped is not None and not self.speaker.speaking: + ms = round(1000 * (time.monotonic() - self.t_speech_stopped)) + self.stats["first_audio_ms"].append(ms) + self.t_speech_stopped = None + self.logger.bind(tag=TAG).info(f"首个音频片段:说完后 {ms} ms") + await self.speaker.push(b) + elif et in ("response.output_audio_transcript.done", "response.audio_transcript.done"): + txt = ev.get("transcript") or "" + if self.log_text: + self.logger.bind(tag=TAG).info(f"assistant: {txt}") + if txt and not self.suppress: + await self.show_assistant_text(txt) + elif et == "conversation.item.input_audio_transcription.completed": + txt = ev.get("transcript") or "" + if self.log_text: + self.logger.bind(tag=TAG).info(f"user: {txt}") + if txt: + await self.show_user_text(txt) + elif et == "response.done": + r = ev.get("response") or {} + self.resp_done = True + self.stats["turns"] += 1 + if r.get("status") != "completed": + self.stats["cancelled"] += 1 + self.t_reply = time.monotonic() + if not self.suppress: + self.spawn(self.speaker.end()) # 等设备播完再发 tts stop;不阻塞事件循环,插话仍能及时处理 + self.logger.bind(tag=TAG).info( + f"回复 {r.get('status')} ({(r.get('status_details') or {}).get('reason') or '-'})") + if self.want_response: + await self._create_response() + await self._maybe_refresh_tools() + elif et == "error": + err = ev.get("error") or {} + code = err.get("code") + if code == "conversation_already_has_active_response" and not self.want_response: + self.want_response = True # 工具结果的 response.create 撞上了刚开始的新回复:等它结束再发 + msg = f"Realtime error type={err.get('type')} code={code}" + if code in BENIGN_ERRORS: + self.logger.bind(tag=TAG).info(msg) + else: + self.logger.bind(tag=TAG).warning(msg) + + # ---------- 工具 ---------- + async def _run_tool(self, item: dict) -> None: + self.stats["tools"] += 1 + output = await self.tools.run(item.get("name"), item.get("arguments") or "{}") + await self._send({"type": "conversation.item.create", + "item": {"type": "function_call_output", "call_id": item.get("call_id"), "output": output}}) + if self.resp_done: + await self._create_response() + else: + self.want_response = True # 当前还有回复在进行(例如函数调用所在的那条还没 done):done 时再发 + + async def _create_response(self, response: dict | None = None) -> None: + self.want_response = False + self.t_response_requested = time.monotonic() + await self._send({"type": "response.create", **({"response": response} if response else {})}) + + # ---------- 空闲关闭(call_later,不用 sleep 循环) ---------- + def _arm_idle(self) -> None: + if self.idle_close_s <= 0 or self.closing: + return + self._idle_handle = self.conn.loop.call_later(1.0, self._idle_tick) + + def _idle_due(self, now: float) -> bool: + if self.speaker.speaking or not self.resp_done or self.want_response or self._tool_tasks: + return False + if self.t_response_requested is not None and now - self.t_response_requested < RESPONSE_START_WAIT_S: + return False + if self.in_speech: + return False + if self.t_speech_stopped is not None and now - self.t_speech_stopped < SPEECH_GRACE_S: + return False + return now - self.t_reply > self.idle_close_s + + def _idle_tick(self) -> None: + if self.closing: + return + if self._idle_due(time.monotonic()): + self.logger.bind(tag=TAG).info(f"空闲超过 {self.idle_close_s:.0f} 秒,关闭连接") + self.closing = True + self.spawn(self.conn.close()) + return + self._arm_idle() diff --git a/main/xiaozhi-server/core/providers/s2s/tools.py b/main/xiaozhi-server/core/providers/s2s/tools.py new file mode 100644 index 000000000..b419a7a1b --- /dev/null +++ b/main/xiaozhi-server/core/providers/s2s/tools.py @@ -0,0 +1,107 @@ +"""把原版的统一工具处理器(UnifiedToolHandler)接给语音进语音出的模型。 + +模型拿到的工具清单来自 conn.func_handler.get_functions():服务端插件、server_mcp、设备 MCP、MCP 接入点在那里已经合成一份, +格式是 chat-completions 的 {"type": "function", "function": {name, description, parameters}};Realtime 要的是拍平的 +{"type": "function", "name", "description", "parameters"}。执行走 conn.func_handler.handle_llm_function_call,拿到 +ActionResponse 后翻成一段交给模型的文字(模型据此开口)。 + +接线层自己做、不改原版工具包:白名单(tools_allow,空 = 全部)、每会话每分钟调用次数上限、request_id 与耗时日志。 +""" +from __future__ import annotations + +import time +import uuid +from collections import deque +from typing import Any, Iterable + +from plugins_func.register import Action + +TAG = __name__ + + +def to_realtime_tools(functions: Iterable[dict[str, Any]] | None, allow: set[str] | None = None) -> list[dict[str, Any]]: + """chat-completions 工具描述 → Realtime 工具描述;allow 非空时只保留名单内的。""" + out: list[dict[str, Any]] = [] + for f in functions or []: + fn = f.get("function") if isinstance(f, dict) else None + if not isinstance(fn, dict) or not fn.get("name"): + continue + name = str(fn["name"]) + if allow and name not in allow: + continue + tool = {"type": "function", "name": name, + "description": str(fn.get("description") or ""), + "parameters": fn.get("parameters") or {"type": "object", "properties": {}}} + out.append(tool) + return out + + +class ToolRunner: + """给一条连接用的工具执行器。""" + + def __init__(self, conn, logger, per_minute: int = 12, allow: Iterable[str] | None = None): + self.conn = conn + self.logger = logger + self.per_minute = int(per_minute) + self.allow = {str(a) for a in allow} if allow else set() + self._recent: deque[float] = deque() + self.calls = 0 + + def allowed(self, name: str) -> bool: + return not self.allow or name in self.allow + + def _over_rate(self) -> bool: + now = time.monotonic() + while self._recent and now - self._recent[0] > 60: + self._recent.popleft() + if len(self._recent) >= self.per_minute: + return True + self._recent.append(now) + return False + + async def run(self, name: str, arguments: str | dict | None) -> str: + """执行一个工具调用,返回交给模型的文字。永不抛异常。""" + rid = uuid.uuid4().hex[:8] + t0 = time.monotonic() + self.calls += 1 + if not name: + return "工具名为空,无法执行。" + if not self.allowed(name): + self.logger.bind(tag=TAG).warning(f"tool {name} rid={rid} 不在白名单,拒绝") + return f"工具 {name} 不允许使用。" + if self._over_rate(): + self.logger.bind(tag=TAG).warning(f"tool {name} rid={rid} 超过每分钟 {self.per_minute} 次上限,拒绝") + return "工具调用太频繁,请稍后再试。" + handler = getattr(self.conn, "func_handler", None) + if handler is None: + return "服务器还没准备好工具,请稍后再试。" + try: + resp = await handler.handle_llm_function_call( + self.conn, {"name": name, "arguments": arguments if arguments is not None else "{}"} + ) + text, action = self._to_text(resp) + except Exception as e: # noqa: BLE001 + text, action = f"工具 {name} 执行出错:{type(e).__name__}", "EXCEPTION" + ms = round((time.monotonic() - t0) * 1000) + self.logger.bind(tag=TAG).info(f"tool {name} rid={rid} {action} {ms} ms, output {len(text)} chars") + return text + + @staticmethod + def _to_text(resp) -> tuple[str, str]: + if resp is None: + return "工具没有返回结果。", "NONE" + action = getattr(resp, "action", None) + result = getattr(resp, "result", None) + response = getattr(resp, "response", None) + name = getattr(action, "name", str(action)) + if action == Action.RESPONSE: + return str(response or result or "已完成。"), name + if action == Action.REQLLM: + return str(result or response or "已完成,请据此回答用户。"), name + if action in (Action.NONE, Action.RECORD): + return str(result or response or "已执行。"), name + if action == Action.NOTFOUND: + return "没有这个工具。", name + if action == Action.ERROR: + return f"工具出错:{response or result or '未知错误'}", name + return str(response or result or "已完成。"), name diff --git a/main/xiaozhi-server/core/utils/s2s.py b/main/xiaozhi-server/core/utils/s2s.py new file mode 100644 index 000000000..27fbef31f --- /dev/null +++ b/main/xiaozhi-server/core/utils/s2s.py @@ -0,0 +1,84 @@ +"""S2S provider 的创建与挂接(与 core/utils/llm.py 的 create_instance 同一套路)。""" +import asyncio +import importlib +import os +import sys + +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +def create_instance(class_name, *args, **kwargs): + """按 type 名加载 core/providers/s2s//.py 里的 S2SProvider。""" + if os.path.exists(os.path.join("core", "providers", "s2s", class_name, f"{class_name}.py")): + lib_name = f"core.providers.s2s.{class_name}.{class_name}" + if lib_name not in sys.modules: + sys.modules[lib_name] = importlib.import_module(f"{lib_name}") + return sys.modules[lib_name].S2SProvider(*args, **kwargs) + + raise ValueError(f"不支持的S2S类型: {class_name},请检查该配置的type是否设置正确") + + +def s2s_selected(conn) -> bool: + """这条连接是否选了 S2S(provider 可能还没建成)。""" + return bool((conn.config.get("selected_module") or {}).get("S2S")) + + +async def s2s_on_text(conn, text: str) -> None: + """文字入口:provider 建成了就直接给它;还没建成(唤醒词 detect 常比它早到一秒)就先记着,建成后回放。""" + if conn.s2s is not None: + await conn.s2s.on_text(text) + return + pending = getattr(conn, "_s2s_pending_texts", None) + if pending is None: + pending = conn._s2s_pending_texts = [] + pending.append(text) + + +async def drain_pending_texts(conn) -> None: + pending = getattr(conn, "_s2s_pending_texts", None) + if not pending or conn.s2s is None: + return + texts, pending[:] = list(pending), [] + for t in texts: + await conn.s2s.on_text(t) + + +def attach_s2s(conn): + """在 ConnectionHandler._initialize_components(执行器线程)里调用。 + + selected_module.S2S 没填 → None(原版级联)。填了就创建 provider 并在连接的事件循环上打开上游会话, + 整段限时 connect_timeout_s + 1 秒;任何失败都返回 None 并记一条警告,连接照常走级联,设备无感。 + """ + selected = (conn.config.get("selected_module") or {}).get("S2S") + if not selected: + return None + cfg = (conn.config.get("S2S") or {}).get(selected) + if not isinstance(cfg, dict): + conn.logger.bind(tag=TAG).warning(f"selected_module.S2S={selected} 但没有对应的 S2S 配置块,回退级联") + return None + s2s_type = cfg.get("type", selected) + timeout = float(cfg.get("connect_timeout_s", 4)) + 1.0 + provider = None + fut = None + try: + provider = create_instance(s2s_type, cfg, conn) + fut = asyncio.run_coroutine_threadsafe(provider.open(), conn.loop) + fut.result(timeout=timeout) + except Exception as e: # noqa: BLE001 + conn.logger.bind(tag=TAG).warning(f"S2S {selected} 打开失败,回退原版级联: {type(e).__name__}: {e}") + if fut is not None: + fut.cancel() # 超时的那次 open() 可能还在跑:取消掉,别让它事后建成一个没人管的会话 + if provider is not None: + try: + asyncio.run_coroutine_threadsafe(provider.close(), conn.loop) + except Exception: # noqa: BLE001 + pass + return None + conn.logger.bind(tag=TAG).info(f"S2S {selected} 已接管本连接(不建 TTS / ASR)") + # 兜底:组件初始化后面某步失败、after_components_ready 没被调到时,建成前排队的文字也要送出去 + # 这里在执行器线程:loop.call_later 不是线程安全的,要经 call_soon_threadsafe 排进事件循环再定时 + conn.loop.call_soon_threadsafe(conn.loop.call_later, 3.0, lambda: asyncio.ensure_future(drain_pending_texts(conn))) + return provider diff --git a/main/xiaozhi-server/tests/core/handle/__init__.py b/main/xiaozhi-server/tests/core/handle/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/tests/core/handle/test_s2s_slot.py b/main/xiaozhi-server/tests/core/handle/test_s2s_slot.py new file mode 100644 index 000000000..48f33dd97 --- /dev/null +++ b/main/xiaozhi-server/tests/core/handle/test_s2s_slot.py @@ -0,0 +1,151 @@ +"""S2S 插槽的四处钩子(connection._route_message / _initialize_components、abortHandle、startToChat、listen): +选中 S2S 时音频直接交给 provider、不建 TTS / ASR;没选中或打开失败时和原版完全一样。provider 用假的,不出网。""" +from __future__ import annotations + +import asyncio +import copy +import json + +import pytest + +from tests.conftest import CONFIG +from config.logger import setup_logging +from core.utils.cache.manager import CacheType, cache_manager + +# setup_logging() 没有配置缓存时会 asyncio.run(load_config()),在事件循环里会炸;生产由 app.py 填缓存,测试自己填 +cache_manager.set(CacheType.CONFIG, "main_config", CONFIG) +setup_logging() + +from core.connection import ConnectionHandler # noqa: E402 +from core.handle.abortHandle import handleAbortMessage +from core.handle.receiveAudioHandle import startToChat +from core.handle.textHandler.listenMessageHandler import ListenTextMessageHandler +import core.connection as connection_mod + + +class FakeWS: + def __init__(self): + self.sent = [] + + async def send(self, m): + self.sent.append(m) + + +class FakeProvider: + def __init__(self): + self.pcm, self.texts, self.cancels, self.listens, self.ready = [], [], [], [], 0 + + async def on_pcm(self, pcm): + self.pcm.append(pcm) + + async def on_text(self, text): + self.texts.append(text) + + async def cancel(self, reason): + self.cancels.append(reason) + + def on_listen(self, state, mode): + self.listens.append((state, mode)) + + def after_components_ready(self): + self.ready += 1 + + async def close(self): + self.closed = getattr(self, "closed", 0) + 1 + + +def _opus_silence_frame(): + try: + from core.utils.opus_encoder_utils import OpusEncoderUtils + frames = [] + OpusEncoderUtils(16000, 1, 60).encode_pcm_to_opus_stream(bytes(1920), False, frames.append) + return frames[0] + except Exception: # noqa: BLE001 + return None + + +def make_conn(loop): + conn = ConnectionHandler(copy.deepcopy(CONFIG), None, None, None, None, None) + conn.loop = loop + conn.websocket = FakeWS() + conn.need_bind = False + conn.bind_completed_event.set() + conn.session_id = "s" + return conn + + +def test_route_message_bytes_goes_to_provider_only_when_attached(): + frame = _opus_silence_frame() + if frame is None: + pytest.skip("Opus 编码器不可用") + + async def go(): + conn = make_conn(asyncio.get_running_loop()) + await conn._route_message(frame) # 没选 S2S、也没有 ASR:静默丢弃,不报错 + fake = FakeProvider() + conn.s2s = fake + await conn._route_message(frame) + assert len(fake.pcm) == 1 and len(fake.pcm[0]) == 1920 # 60 ms 16 kHz PCM + assert conn.asr_audio_queue.empty() # 不进 ASR 队列 + asyncio.run(go()) + + +def test_initialize_components_skips_tts_asr_when_s2s_attached(monkeypatch): + async def go(): + conn = make_conn(asyncio.get_running_loop()) + fake = FakeProvider() + monkeypatch.setattr(connection_mod, "attach_s2s", lambda c: fake) + monkeypatch.setattr(conn, "_initialize_tts", lambda: (_ for _ in ()).throw(AssertionError("不该建 TTS"))) + monkeypatch.setattr(conn, "_initialize_asr", lambda: (_ for _ in ()).throw(AssertionError("不该建 ASR"))) + monkeypatch.setattr(conn, "_init_prompt_enhancement", lambda: None) # 不查 IP 归属地 / 天气 + monkeypatch.setattr(conn, "_inject_tool_call_fewshot", lambda: None) + await asyncio.get_running_loop().run_in_executor(None, conn._initialize_components) + assert conn.s2s is fake and conn.tts is None and conn.asr is None + assert fake.ready == 1 + asyncio.run(go()) + + +def test_initialize_components_falls_back_to_cascade_when_attach_returns_none(monkeypatch): + class Dummy: + def __init__(self): + self.opened = 0 + + async def open_audio_channels(self, conn): + self.opened += 1 + + async def go(): + conn = make_conn(asyncio.get_running_loop()) + tts, asr = Dummy(), Dummy() + monkeypatch.setattr(connection_mod, "attach_s2s", lambda c: None) + monkeypatch.setattr(conn, "_initialize_tts", lambda: tts) + monkeypatch.setattr(conn, "_initialize_asr", lambda: asr) + monkeypatch.setattr(conn, "_init_prompt_enhancement", lambda: None) + monkeypatch.setattr(conn, "_inject_tool_call_fewshot", lambda: None) + await asyncio.get_running_loop().run_in_executor(None, conn._initialize_components) + await asyncio.sleep(0) + assert conn.s2s is None and conn.tts is tts and conn.asr is asr + assert tts.opened == 1 and asr.opened == 1 + asyncio.run(go()) + + +def test_text_abort_and_listen_hooks_reach_provider(): + async def go(): + conn = make_conn(asyncio.get_running_loop()) + fake = FakeProvider() + conn.s2s = fake + await startToChat(conn, "现在几点") + assert fake.texts == ["现在几点"] + conn.client_is_speaking = True + await handleAbortMessage(conn) + assert fake.cancels == ["device"] and conn.client_abort is True and conn.client_is_speaking is False + assert json.loads(conn.websocket.sent[-1]) == {"type": "tts", "state": "stop", "session_id": "s"} + assert conn.client_is_listening is False + await ListenTextMessageHandler().handle(conn, {"state": "start", "mode": "realtime"}) + assert conn.client_is_listening is True and conn.client_listen_mode == "realtime" + await ListenTextMessageHandler().handle(conn, {"state": "detect", "text": "你好小智"}) + assert conn.client_is_listening is True and fake.texts[-1] == "嘿,你好呀" # detect 不改聆听状态;唤醒词被上游换成固定问候句再进 startToChat + await ListenTextMessageHandler().handle(conn, {"state": "stop"}) + assert conn.client_is_listening is False + await conn.close() # 设备断开 → 上游会话跟着关 + assert fake.closed == 1 + asyncio.run(go()) diff --git a/main/xiaozhi-server/tests/core/providers/s2s/__init__.py b/main/xiaozhi-server/tests/core/providers/s2s/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/tests/core/providers/s2s/test_audio.py b/main/xiaozhi-server/tests/core/providers/s2s/test_audio.py new file mode 100644 index 000000000..162434298 --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/s2s/test_audio.py @@ -0,0 +1,51 @@ +"""S2S 音频工具:重采样(audioop 与 numpy 两条路径)、Opus 分帧。""" +from __future__ import annotations + +import numpy as np +import pytest + +from core.providers.s2s import audio as audio_mod +from core.providers.s2s.audio import OpusFramer, Resampler + + +def _tone(rate: int, ms: int, hz: float = 440.0, amp: int = 8000) -> bytes: + n = rate * ms // 1000 + t = np.arange(n) / rate + return (np.sin(2 * np.pi * hz * t) * amp).astype(np.int16).tobytes() + + +@pytest.mark.parametrize("use_audioop", [True, False]) +def test_resample_16k_to_24k_keeps_duration_and_tone(monkeypatch, use_audioop): + if use_audioop and audio_mod.audioop is None: + pytest.skip("本解释器没有 audioop") + if not use_audioop: + monkeypatch.setattr(audio_mod, "audioop", None) + rs = Resampler(16000, 24000) + out = b"".join(rs.process(_tone(16000, 60)) for _ in range(10)) # 10 帧 × 60 ms,分帧送进去 + n_in, n_out = 16000 * 600 // 1000, len(out) // 2 + assert abs(n_out - n_in * 3 // 2) <= 4 # 时长按 3:2 放大,允许边界差几样本 + y = np.frombuffer(out, np.int16).astype(np.float64) + spec = np.abs(np.fft.rfft(y[2400:])) # 去掉开头的过渡 + peak_hz = np.fft.rfftfreq(len(y[2400:]), 1 / 24000)[int(np.argmax(spec))] + assert abs(peak_hz - 440) < 10 + + +def test_resample_same_rate_is_identity_and_empty_is_empty(): + rs = Resampler(24000, 24000) + pcm = _tone(24000, 20) + assert rs.process(pcm) == pcm and rs.process(b"") == b"" + + +def test_opus_framer_cuts_60ms_frames_and_flushes_tail(): + try: + fr = OpusFramer(24000, 60) + except Exception as e: # noqa: BLE001 (conftest 可能把 opuslib_next 桩掉) + pytest.skip(f"Opus 编码器不可用: {type(e).__name__}") + pcm = _tone(24000, 150) # 2.5 帧 + frames = fr.push(pcm) + assert len(frames) == 2 and all(isinstance(f, bytes) and len(f) > 0 for f in frames) + tail = fr.flush() + assert len(tail) == 1 # 剩下半帧补零编出来 + assert fr.flush() == [] # 再 flush 没有东西 + fr.reset() + assert fr.push(_tone(24000, 60)) and len(fr.push(b"")) == 0 diff --git a/main/xiaozhi-server/tests/core/providers/s2s/test_echo_gate.py b/main/xiaozhi-server/tests/core/providers/s2s/test_echo_gate.py new file mode 100644 index 000000000..4938008a6 --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/s2s/test_echo_gate.py @@ -0,0 +1,139 @@ +"""残余回声门控:合成信号自检(参考延迟衰减 + 底噪 + 插话),以及上游自带的 silero onnx 推理能跑。""" +from __future__ import annotations + +import numpy as np +import pytest + +from core.providers.s2s.echo_gate import RATE, EchoGate, load_vad + +FR = 960 # 60 ms + + +def _speechlike(seconds: float, seed: int, amp: float = 6000.0) -> np.ndarray: + """有音节起伏的带限信号(4 Hz 调制的 200~3000 Hz 噪声),能量包络像说话。""" + rng = np.random.default_rng(seed) + n = int(seconds * RATE) + x = rng.normal(0, 1, n) + spec = np.fft.rfft(x) + f = np.fft.rfftfreq(n, 1 / RATE) + spec[(f < 200) | (f > 3000)] = 0 + x = np.fft.irfft(spec, n) + env = 0.55 + 0.45 * np.sin(2 * np.pi * 4.0 * np.arange(n) / RATE) * np.sin(2 * np.pi * 0.7 * np.arange(n) / RATE) + x = x / (np.abs(x).max() + 1e-9) * amp * env + return x + + +def _run(lag=0.10, echo_db=-28.0, barge_gain=0.8, barge_at=2.0, barge_len=1.5): + # 真机:TTS 下行 RMS 约 3000~5000,设备 AEC 后残余相对参考约 −28 dB(中位) + ref = _speechlike(5.0, seed=1, amp=20000.0).astype(np.int16) + spk = _speechlike(barge_len, seed=2, amp=9000.0) + att = 10 ** (echo_db / 20) + rng = np.random.default_rng(3) + n = len(ref) + RATE + up = rng.normal(0, 25, n) + d = int(lag * RATE) + up[d:d + len(ref)] += ref.astype(float) * att + b0 = int(barge_at * RATE) + up[b0:b0 + len(spk)] += spk * barge_gain + up = np.clip(up, -32768, 32767).astype(np.int16) + + gate = EchoGate(vad=None, lag_prior=0.08, lag_max=0.30, start_window=None) # 能量判据(合成信号不是真人声) + t = 100.0 + gate.on_tts_start(t) + nf = len(ref) // FR + for k in range(nf): # 段首 3 帧一次送出,之后每 60 ms 一帧(与节拍器一致) + gate.on_downlink(ref[k * FR:(k + 1) * FR].tobytes(), t + (0 if k < 3 else (k - 2) * 0.06)) + gate.on_tts_stop(t + nf * 0.06) + out, dec = [], [] + for k in range(n // FR): + o, info = gate.process(up[k * FR:(k + 1) * FR].tobytes(), t + (k + 1) * 0.06, speaking=k * 0.06 < nf * 0.06) + out.append(np.frombuffer(o, np.int16)) + dec.append(info) + return gate, up, np.concatenate(out), dec, b0, len(spk) + + +def _rms(x): + return float(np.sqrt(np.mean(x.astype(float) ** 2))) + + +def test_echo_suppressed_and_barge_passes(): + gate, up, out, dec, b0, nb = _run() + echo_only = slice(int(0.5 * RATE), int(1.9 * RATE)) + barge = slice(b0, b0 + nb) + assert _rms(up[echo_only]) > 100 # 原始残余回声明显高于底噪 + assert _rms(out[echo_only]) < 25 * 1.5 # 门控后压到底噪附近 + assert _rms(out[barge]) > 0.8 * _rms(up[barge]) # 插话基本原样放行 + first = next(k for k in range(b0 // FR, len(dec)) if dec[k] == "pass") + assert (first - b0 // FR) * 60 <= 120 # 插话判决延迟 ≤ 120 ms + + +def test_bypass_when_not_playing(): + gate = EchoGate(vad=None) + pcm = (np.ones(FR, np.int16) * 500).tobytes() + o, info = gate.process(pcm, 1.0, speaking=False) + assert info == "bypass" and o == pcm + + +def test_noref_passthrough_during_underrun(): + gate = EchoGate(vad=None) + gate.on_tts_start(10.0) + gate.on_downlink(bytes(FR * 2), 10.0) # 只播了 60 ms + pcm = (np.ones(FR, np.int16) * 3000).tobytes() + o, info = gate.process(pcm, 14.0, speaking=True) # 4 秒后设备什么都没在放 + assert info == "noref" and o == pcm + + +def test_lag_estimate_converges(): + gate, *_ = _run(lag=0.18, barge_gain=0.0) + assert abs(gate.lag - 0.18) <= 0.04 + + +def test_silero_onnx_runs_with_upstream_model(): + vad = load_vad() # 默认路径 = 上游自带的 models/snakers4_silero-vad + if vad is None: + pytest.skip("上游 silero onnx 模型不在当前目录下") + p_silence = vad(np.zeros(512, np.float32)) + assert 0.0 <= p_silence < 0.5 + vad.reset_states() + assert 0.0 <= vad(np.random.default_rng(0).normal(0, 0.3, 512).astype(np.float32)) <= 1.0 + + +def _short_echo_run(start_window, lag=0.5, echo_db=-24.0): + """像唤醒应答那样短(1.2 秒)的一段播放,残余回声晚 lag 秒到;返回 (原始回声 RMS, 门控后 RMS, 是否估出过滞后)。""" + ref = _speechlike(1.2, seed=5, amp=20000.0).astype(np.int16) + rng = np.random.default_rng(6) + n = len(ref) + RATE + up = rng.normal(0, 25, n) + d = int(lag * RATE) + up[d:d + len(ref)] += ref.astype(float) * 10 ** (echo_db / 20) + up = np.clip(up, -32768, 32767).astype(np.int16) + gate = EchoGate(vad=None, lag_prior=0.2, lag_max=1.2, start_window=start_window) + t = 100.0 + gate.on_tts_start(t) + nf = len(ref) // FR + for k in range(nf): + gate.on_downlink(ref[k * FR:(k + 1) * FR].tobytes(), t + (0 if k < 3 else (k - 2) * 0.06)) + gate.on_tts_stop(t + nf * 0.06) + out = [] + for k in range(n // FR): + o, _ = gate.process(up[k * FR:(k + 1) * FR].tobytes(), t + (k + 1) * 0.06, speaking=k * 0.06 < nf * 0.06) + out.append(np.frombuffer(o, np.int16)) + out = np.concatenate(out) + echo = slice(d, d + len(ref)) + return _rms(up[echo]), _rms(out[echo]), gate.lag_corr is not None + + +def test_start_window_suppresses_echo_before_first_lag_estimate(): + """会话开头先验 200 ms、实际滞后 500 ms 时,窄窗把唤醒应答的回声漏给模型;起始窗(80~650 ms)压得住。""" + raw, narrow, est1 = _short_echo_run(None) + _, wide, est2 = _short_echo_run((0.08, 0.65)) + assert not est1 and not est2 # 这么短还估不出滞后:全靠先验和窗口 + assert raw > 100 and narrow > 2 * 25 # 窄窗:回声明显漏过 + assert wide < 25 * 1.5 # 起始窗:压到底噪附近 + + +def test_start_window_only_applies_before_estimate(): + gate = EchoGate(vad=None, lag_prior=0.2, start_window=(0.08, 0.65)) + assert gate._window() == pytest.approx((0.45, 0.12)) + gate.lag_corr = 0.7 # 估出过滞后:回到正常窗口 + assert gate._window() == (gate.tail_back, gate.tail_fwd) diff --git a/main/xiaozhi-server/tests/core/providers/s2s/test_openai_realtime.py b/main/xiaozhi-server/tests/core/providers/s2s/test_openai_realtime.py new file mode 100644 index 000000000..203be51b0 --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/s2s/test_openai_realtime.py @@ -0,0 +1,345 @@ +"""OpenAI Realtime provider 的契约测试:起一个假的 Realtime WebSocket 服务端按脚本发事件,断言 provider 对上游发了什么、 +对设备发了什么。不出网、不用真 key、不碰 ConnectionHandler(连接对象用最小的假对象)。 + +运行:在 main/xiaozhi-server 目录下 `pytest tests/core/providers/s2s -q`。 +""" +from __future__ import annotations + +import asyncio +import base64 +import json +import time + +import numpy as np +import pytest +from websockets.asyncio.server import serve + +from config.logger import setup_logging +from core.handle.abortHandle import handleAbortMessage +from core.providers.s2s.openai_realtime.openai_realtime import WAKE_TRIGGER, S2SProvider +from core.utils.dialogue import Dialogue +from core.utils.s2s import attach_s2s +from plugins_func.register import Action, ActionResponse + +# conftest 在 mock 模式把 asyncio.sleep 换成了不让出事件循环的空函数;上游节拍器和本测试的等待都要真睡。 +_real_sleep = asyncio.tasks.sleep +# setup_logging() 没有配置缓存时会 asyncio.run(load_config()),在事件循环里会炸;生产由 app.py 的 load_config 填缓存,测试这里自己填 +from tests.conftest import CONFIG # noqa: E402 +from core.utils.cache.manager import CacheType, cache_manager # noqa: E402 + +cache_manager.set(CacheType.CONFIG, "main_config", CONFIG) +LOGGER = setup_logging() + + +@pytest.fixture(autouse=True) +def _restore_sleep(monkeypatch): + monkeypatch.setattr(asyncio, "sleep", _real_sleep) + + +def _opus_available() -> bool: + try: + from core.utils.opus_encoder_utils import OpusEncoderUtils + OpusEncoderUtils(24000, 1, 60) + return True + except Exception: # noqa: BLE001 + return False + + +pytestmark = pytest.mark.skipif(not _opus_available(), reason="Opus 编码器不可用(opuslib_next / libopus)") + + +class FakeDeviceWS: + def __init__(self): + self.sent = [] + + async def send(self, m): + self.sent.append(m) + + def texts(self): + return [json.loads(m) for m in self.sent if isinstance(m, str)] + + def frames(self): + return [m for m in self.sent if isinstance(m, bytes)] + + def states(self): + return [(t.get("type"), t.get("state")) for t in self.texts()] + + +class FakeFuncHandler: + def __init__(self): + self.calls = [] + + def get_functions(self): + return [{"type": "function", "function": { + "name": "hass_state", "description": "控制家里的设备", + "parameters": {"type": "object", "properties": {"entity_id": {"type": "string"}}, "required": ["entity_id"]}}}] + + async def handle_llm_function_call(self, conn, data): + self.calls.append(data) + return ActionResponse(Action.RESPONSE, None, "客厅灯已打开") + + +class FakeConn: + def __init__(self, loop): + self.loop = loop + self.logger = LOGGER + self.config = {"selected_module": {"VAD": "SileroVAD"}, "VAD": {"SileroVAD": {"model_dir": "/nonexistent"}}, + "tts_audio_send_delay": 0, "enable_stop_tts_notify": False, "end_prompt": {}} + self.sample_rate = 24000 + self.session_id = "sess" + self.websocket = FakeDeviceWS() + self.dialogue = Dialogue() + self.prompt = "你是测试助手" + self.func_handler = FakeFuncHandler() + self.client_abort = False + self.client_is_speaking = False + self.client_is_listening = False + self.close_after_chat = False + self.last_activity_time = 0.0 + self.conn_from_mqtt_gateway = False + self.tts = None + self.sentence_id = None + self.s2s = None + self.closed = False + + def clearSpeakStatus(self): + self.client_is_speaking = False + + def clear_queues(self): + pass + + async def close(self, ws=None): + self.closed = True + + +class FakeRealtime: + """假上游:握手回 session.created,之后记录收到的每条事件;测试用 emit() 往下发。""" + + def __init__(self, first_event=None): + self.received = [] + self.ws = None + self.first_event = first_event or {"type": "session.created", "session": {}} + + async def handler(self, ws): + self.ws = ws + self.closed = False + await ws.send(json.dumps(self.first_event)) + async for raw in ws: + self.received.append(json.loads(raw)) + self.closed = True + + async def emit(self, ev: dict): + await self.ws.send(json.dumps(ev)) + + def types(self): + return [m["type"] for m in self.received] + + def of(self, typ): + return [m for m in self.received if m["type"] == typ] + + async def wait_for(self, typ, n=1, timeout=3.0): + t0 = time.monotonic() + while len(self.of(typ)) < n: + if time.monotonic() - t0 > timeout: + raise AssertionError(f"上游 {timeout}s 内没收到 {n} 条 {typ},收到的是 {self.types()}") + await _real_sleep(0.01) + return self.of(typ) + + +async def wait_until(pred, timeout=5.0, what="condition"): + t0 = time.monotonic() + while not pred(): + if time.monotonic() - t0 > timeout: + raise AssertionError(f"{timeout}s 内没等到 {what}") + await _real_sleep(0.01) + + +def pcm(ms: int, rate: int = 16000, amp: int = 0) -> bytes: + return (np.ones(rate * ms // 1000, np.int16) * amp).tobytes() + + +def b64(ms: int, rate: int = 24000) -> str: + return base64.b64encode(pcm(ms, rate, 2000)).decode() + + +def make_provider(conn, url, **over): + cfg = {"api_key": "test-key", "url": url, "model_name": "gpt-realtime", "echo_gate": False, + "idle_close_s": 0, "connect_timeout_s": 2, **over} + return S2SProvider(cfg, conn) + + +def run_scenario(scenario, first_event=None): + async def go(): + rt = FakeRealtime(first_event) + async with serve(rt.handler, "127.0.0.1", 0) as srv: + url = f"ws://127.0.0.1:{srv.sockets[0].getsockname()[1]}/v1/realtime" + conn = FakeConn(asyncio.get_running_loop()) + await scenario(rt, conn, url) + asyncio.run(go()) + + +async def _stream_response(rt, frames=8, item_id="item_1"): + await rt.emit({"type": "response.created", "response": {"id": "resp_1"}}) + await rt.emit({"type": "response.output_item.added", "item": {"id": item_id, "type": "message"}}) + for _ in range(frames): + await rt.emit({"type": "response.output_audio.delta", "delta": b64(60)}) + await _real_sleep(0.005) + + +# ---------------------------------------------------------------- 测试 ---------------------------------------------------------------- + +def test_open_sends_session_update_then_forwards_resampled_audio(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + conn.s2s = p + await p.open() + (upd,) = await rt.wait_for("session.update") + s = upd["session"] + assert s["instructions"] == "你是测试助手" and s["type"] == "realtime" + assert [t["name"] for t in s["tools"]] == ["hass_state"] and s["tools"][0]["type"] == "function" + assert s["audio"]["input"]["format"]["rate"] == 24000 and s["audio"]["input"]["turn_detection"]["type"] == "server_vad" + await p.on_pcm(pcm(60)) # listen start 之前(唤醒词音频):不送 + await _real_sleep(0.05) + assert rt.of("input_audio_buffer.append") == [] + conn.client_is_listening = True # 上游 listen 处理器在 listen start 时置位 + await p.on_pcm(pcm(60)) + (app,) = await rt.wait_for("input_audio_buffer.append") + assert abs(len(base64.b64decode(app["audio"])) - 24000 * 60 // 1000 * 2) <= 4 # 16 k → 24 k(重采样器首包差 1 样本) + conn.client_is_listening = False + await p.on_pcm(pcm(60)) # 不在聆听:不送 + await _real_sleep(0.05) + assert len(rt.of("input_audio_buffer.append")) == 1 + conn.client_is_listening = True + await p.on_pcm(pcm(60)) + await rt.wait_for("input_audio_buffer.append", 2) + await p.close() # 连接关闭 → 上游会话也关 + await wait_until(lambda: rt.closed, what="上游看到客户端关闭") + assert p.stats["up_frames"] == 2 + run_scenario(sc) + + +def test_response_audio_reaches_device_with_tts_messages_and_dialogue(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + conn.s2s = p + await p.open() + await rt.wait_for("session.update") + await rt.emit({"type": "conversation.item.input_audio_transcription.completed", "transcript": "现在几点"}) + await _stream_response(rt, frames=8) + await rt.emit({"type": "response.output_audio_transcript.done", "transcript": "现在三点整。"}) + await rt.emit({"type": "response.done", "response": {"status": "completed"}}) + dev = conn.websocket + await wait_until(lambda: ("tts", "stop") in dev.states(), what="设备收到 tts stop") + states = dev.states() + assert states.index(("tts", "start")) < states.index(("tts", "stop")) + assert ("tts", "sentence_start") in states and ("stt", None) in states + assert [t["text"] for t in dev.texts() if t.get("type") == "stt"] == ["现在几点"] + assert [t["text"] for t in dev.texts() if t.get("state") == "sentence_start"] == ["现在三点整。"] + assert 8 <= len(dev.frames()) <= 9 # 8 帧 + 可能的补零尾帧 + assert [(m.role, m.content) for m in conn.dialogue.dialogue] == [("user", "现在几点"), ("assistant", "现在三点整。")] + assert p.stats["turns"] == 1 and p.stats["cancelled"] == 0 + assert conn.client_is_speaking is False + await p.close() + run_scenario(sc) + + +def test_server_detected_barge_in_truncates_without_cancel(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + conn.s2s = p + await p.open() + await rt.wait_for("session.update") + await _stream_response(rt, frames=20) + await wait_until(lambda: p.speaker.frames_sent >= 5, what="设备收到预缓冲帧") + await rt.emit({"type": "input_audio_buffer.speech_started", "item_id": "u1", "audio_start_ms": 1000}) + (tr,) = await rt.wait_for("conversation.item.truncate") + assert tr["item_id"] == "item_1" and tr["content_index"] == 0 and tr["audio_end_ms"] >= 0 + assert "response.cancel" not in rt.types() # 模型侧判的插话它自己已取消 + assert ("tts", "stop") in conn.websocket.states() # handleAbortMessage 发的 + n_frames = len(conn.websocket.frames()) + await rt.emit({"type": "response.output_audio.delta", "delta": b64(60)}) # 残余音频应被丢弃 + await rt.emit({"type": "response.done", "response": {"status": "cancelled", "status_details": {"reason": "turn_detected"}}}) + await _real_sleep(0.1) + assert len(conn.websocket.frames()) == n_frames + assert p.stats["barge_server"] == 1 and p.stats["cancelled"] == 1 + await p.close() + run_scenario(sc) + + +def test_device_abort_cancels_response_and_truncates(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + conn.s2s = p + await p.open() + await rt.wait_for("session.update") + await _stream_response(rt, frames=20) + await wait_until(lambda: p.speaker.frames_sent >= 5, what="设备收到预缓冲帧") + await handleAbortMessage(conn) # 设备按键 → abortHandle 钩子 → cancel("device") + await rt.wait_for("response.cancel") + await rt.wait_for("conversation.item.truncate") + assert conn.client_abort is True and p.stats["barge_device"] == 1 + await p.close() + run_scenario(sc) + + +def test_tool_call_roundtrip_and_text_entry(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + conn.s2s = p + await p.open() + await rt.wait_for("session.update") + await rt.emit({"type": "response.created", "response": {"id": "r"}}) + await rt.emit({"type": "response.output_item.done", + "item": {"type": "function_call", "call_id": "call_1", "name": "hass_state", + "arguments": '{"entity_id": "light.living"}'}}) + (out,) = await rt.wait_for("conversation.item.create") + assert out["item"] == {"type": "function_call_output", "call_id": "call_1", "output": "客厅灯已打开"} + assert conn.func_handler.calls[0]["name"] == "hass_state" + assert "response.create" not in rt.types() # 当前回复还没 done,先记下 + await rt.emit({"type": "response.done", "response": {"status": "completed"}}) + await rt.wait_for("response.create") # done 后补发 + # 文字入口 + await p.on_text("把卧室灯关掉") + items = await rt.wait_for("conversation.item.create", 2) + assert items[1]["item"]["role"] == "user" and items[1]["item"]["content"][0]["text"] == "把卧室灯关掉" + await rt.wait_for("response.create", 2) + assert conn.dialogue.dialogue[-1].content == "把卧室灯关掉" + # 唤醒词:只让模型短应答,不进对话历史 + await p.on_text(WAKE_TRIGGER) + creates = await rt.wait_for("response.create", 3) + assert creates[2]["response"]["instructions"].startswith("用户刚叫醒你") + assert len(conn.dialogue.dialogue) == 1 + await p.close() + run_scenario(sc) + + +def test_open_fails_on_error_first_event_and_attach_falls_back(): + async def sc(rt, conn, url): + p = make_provider(conn, url) + with pytest.raises(RuntimeError): + await p.open() + # attach_s2s 在执行器线程里调用,失败返回 None,连接走级联 + conn.config["selected_module"]["S2S"] = "OpenAIRealtime" + conn.config["S2S"] = {"OpenAIRealtime": {"type": "openai_realtime", "api_key": "k", "url": url, + "connect_timeout_s": 1, "echo_gate": False}} + got = await asyncio.get_running_loop().run_in_executor(None, attach_s2s, conn) + assert got is None + conn.config["selected_module"]["S2S"] = "" + assert await asyncio.get_running_loop().run_in_executor(None, attach_s2s, conn) is None + run_scenario(sc, first_event={"type": "error", "error": {"code": "invalid_api_key"}}) + + +def test_attach_succeeds_and_upstream_close_closes_connection(): + async def sc(rt, conn, url): + conn.config["selected_module"]["S2S"] = "OpenAIRealtime" + conn.config["S2S"] = {"OpenAIRealtime": {"type": "openai_realtime", "api_key": "k", "url": url, + "connect_timeout_s": 2, "echo_gate": False, "idle_close_s": 0}} + p = await asyncio.get_running_loop().run_in_executor(None, attach_s2s, conn) + assert isinstance(p, S2SProvider) + conn.s2s = p + await rt.wait_for("session.update") + p.after_components_ready() # 执行器线程里的那次同步 + await rt.wait_for("session.update", 2) + await rt.ws.close() # 上游断开 + await wait_until(lambda: conn.closed, what="连接被关闭") + run_scenario(sc) diff --git a/main/xiaozhi-server/tests/core/providers/s2s/test_tools.py b/main/xiaozhi-server/tests/core/providers/s2s/test_tools.py new file mode 100644 index 000000000..e416fed0a --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/s2s/test_tools.py @@ -0,0 +1,71 @@ +"""S2S 工具接线:chat-completions → Realtime 工具描述、ActionResponse → 文字、白名单、限频、异常不外泄。""" +from __future__ import annotations + +import asyncio + +from config.logger import setup_logging +from core.providers.s2s.tools import ToolRunner, to_realtime_tools +from plugins_func.register import Action, ActionResponse + +FUNCS = [ + {"type": "function", "function": {"name": "hass_state", "description": "控制设备", + "parameters": {"type": "object", "properties": {"entity_id": {"type": "string"}}}}}, + {"type": "function", "function": {"name": "get_weather", "description": "天气"}}, + {"type": "function", "function": {"description": "没有名字,应被丢掉"}}, + "不是字典", +] + + +def test_to_realtime_tools_flattens_and_filters(): + tools = to_realtime_tools(FUNCS) + assert [t["name"] for t in tools] == ["hass_state", "get_weather"] + assert tools[0] == {"type": "function", "name": "hass_state", "description": "控制设备", + "parameters": {"type": "object", "properties": {"entity_id": {"type": "string"}}}} + assert tools[1]["parameters"] == {"type": "object", "properties": {}} # 没给 parameters 的补一个空对象 + assert [t["name"] for t in to_realtime_tools(FUNCS, {"get_weather"})] == ["get_weather"] + assert to_realtime_tools(None) == [] + + +class _Handler: + def __init__(self, resp=None, raise_exc=False): + self.resp, self.raise_exc, self.calls = resp, raise_exc, [] + + async def handle_llm_function_call(self, conn, data): + self.calls.append(data) + if self.raise_exc: + raise RuntimeError("boom") + return self.resp + + +class _Conn: + def __init__(self, handler): + self.func_handler = handler + + +def _run(runner, name, args="{}"): + return asyncio.run(runner.run(name, args)) + + +def test_action_mapping_and_arguments_passthrough(): + log = setup_logging() + h = _Handler(ActionResponse(Action.RESPONSE, None, "客厅灯已打开")) + r = ToolRunner(_Conn(h), log) + assert _run(r, "hass_state", '{"entity_id": "light.living"}') == "客厅灯已打开" + assert h.calls[0] == {"name": "hass_state", "arguments": '{"entity_id": "light.living"}'} + assert _run(ToolRunner(_Conn(_Handler(ActionResponse(Action.REQLLM, "今天晴 20 度", None))), log), "get_weather") == "今天晴 20 度" + assert _run(ToolRunner(_Conn(_Handler(ActionResponse(Action.NOTFOUND))), log), "x") == "没有这个工具。" + assert _run(ToolRunner(_Conn(_Handler(ActionResponse(Action.ERROR, None, "连不上"))), log), "x") == "工具出错:连不上" + assert _run(ToolRunner(_Conn(_Handler(ActionResponse(Action.NONE))), log), "x") == "已执行。" + assert _run(ToolRunner(_Conn(_Handler(None)), log), "x") == "工具没有返回结果。" + + +def test_whitelist_rate_limit_and_exceptions(): + log = setup_logging() + h = _Handler(ActionResponse(Action.RESPONSE, None, "ok")) + r = ToolRunner(_Conn(h), log, per_minute=2, allow=["hass_state"]) + assert _run(r, "get_weather") == "工具 get_weather 不允许使用。" and h.calls == [] + assert _run(r, "hass_state") == "ok" and _run(r, "hass_state") == "ok" + assert _run(r, "hass_state") == "工具调用太频繁,请稍后再试。" and len(h.calls) == 2 + assert _run(ToolRunner(_Conn(_Handler(raise_exc=True)), log), "hass_state").startswith("工具 hass_state 执行出错") + assert _run(ToolRunner(_Conn(None), log), "hass_state") == "服务器还没准备好工具,请稍后再试。" + assert _run(r, "") == "工具名为空,无法执行。"