mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Merge cef2540dc4 into cda17f4d6a
This commit is contained in:
commit
9f0176641a
5 changed files with 231 additions and 0 deletions
43
docs/device-overrides.md
Normal file
43
docs/device-overrides.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# 按设备覆盖配置(单模块部署)
|
||||
|
||||
## 概述
|
||||
|
||||
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时,配置是全局的,所有设备一样。
|
||||
`data/devices.yaml` 补上这一块:连接初始化时按 `device-id` 读这台设备的覆盖项,合并进这条连接的配置。
|
||||
|
||||
## 工作原理
|
||||
|
||||
`core/utils/device_overrides.py` 在 `ConnectionHandler._initialize_components` 最开头被调用(每条连接的 config 都是深拷贝,互不影响)。
|
||||
每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启服务器。文件不存在、格式错、设备没登记、`enabled: false`、
|
||||
名字在对应配置块里不存在,都只记日志、不改配置、不抛异常。
|
||||
|
||||
## 配置
|
||||
|
||||
`data/.config.yaml`:
|
||||
|
||||
```yaml
|
||||
device_overrides_file: data/devices.yaml # 默认值,可不写
|
||||
```
|
||||
|
||||
`data/devices.yaml`(schema v1):
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
devices:
|
||||
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写;大小写不敏感)
|
||||
name: 书房
|
||||
enabled: true
|
||||
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字 = 这台设备用语音进语音出模型
|
||||
prompt: 你是书房的语音助手。 # 非空则替换全局 prompt
|
||||
llm: null # 非空且在 LLM 配置块里存在 → 这台设备用它
|
||||
tts: null # 同上
|
||||
```
|
||||
|
||||
同一份文件也可以给前置的准入网关当白名单(`client_id` 字段给网关用,服务器不读)。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
cd main/xiaozhi-server
|
||||
pytest tests/core/utils/test_device_overrides.py -q
|
||||
```
|
||||
|
|
@ -81,6 +81,10 @@ enable_websocket_ping: false
|
|||
# > 0: 使用固定延迟(毫秒)发送,例如: 60
|
||||
tts_audio_send_delay: 0
|
||||
|
||||
# 按设备覆盖配置(单模块部署没有智控台时的差异化配置):按 device-id 从这个文件读该设备的大脑 / 提示词 / LLM / TTS,
|
||||
# 每次连接都重读,改完表设备重连即生效;文件不存在就全部用全局配置。格式见 docs/device-overrides.md
|
||||
device_overrides_file: data/devices.yaml
|
||||
|
||||
exit_commands:
|
||||
- "退出"
|
||||
- "关闭"
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ from core.utils.util import (
|
|||
)
|
||||
from typing import Dict, Any
|
||||
from collections import deque
|
||||
from core.utils.device_overrides import apply_device_overrides
|
||||
from core.utils.modules_initialize import (
|
||||
initialize_modules,
|
||||
initialize_tts,
|
||||
|
|
@ -219,6 +220,9 @@ class ConnectionHandler:
|
|||
)
|
||||
|
||||
self.device_id = self.headers.get("device-id", None)
|
||||
# 按设备覆盖(data/devices.yaml):选大脑 / 提示词 / LLM / TTS,见 docs/device-overrides.md。
|
||||
# 放在拿到 device-id 的第一时间,后面的消息处理(唤醒词、组件初始化)都能看到覆盖后的配置
|
||||
apply_device_overrides(self)
|
||||
|
||||
# 认证通过,继续处理
|
||||
self.websocket = ws
|
||||
|
|
|
|||
106
main/xiaozhi-server/core/utils/device_overrides.py
Normal file
106
main/xiaozhi-server/core/utils/device_overrides.py
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
"""按设备覆盖配置:单模块部署(没有智控台)时的"差异化配置"。
|
||||
|
||||
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时配置是全局的。这个模块补上这一块:
|
||||
连接初始化时按请求头里的 device-id 读本地 YAML,把这台设备的覆盖项合并进这条连接的 config(connection.py 每条连接都是
|
||||
深拷贝,互不影响)。每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启。
|
||||
|
||||
文件路径:config["device_overrides_file"],默认 data/devices.yaml;文件不存在 = 不覆盖。schema v1:
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
devices:
|
||||
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写)
|
||||
name: 书房
|
||||
enabled: true # false 时这里不处理(准入由 server.auth 或前置网关负责)
|
||||
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字(OpenAIRealtime)或它的 type(openai_realtime)= 用该语音模型
|
||||
prompt: null # 非空则替换 config["prompt"]
|
||||
llm: null # 非空且在 LLM 配置块里存在 → selected_module.LLM
|
||||
tts: null # 同上,TTS
|
||||
```
|
||||
|
||||
任何错误都只记日志、不抛出:配置文件坏了不能让设备连不上。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import yaml
|
||||
|
||||
TAG = __name__
|
||||
DEFAULT_FILE = "data/devices.yaml"
|
||||
|
||||
|
||||
def load_device_overrides(path: str, device_id: str | None) -> dict | None:
|
||||
"""返回这台设备的覆盖项字典;文件不存在、格式错、没登记、被停用都返回 None。"""
|
||||
if not device_id or not path or not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
except (OSError, yaml.YAMLError):
|
||||
return None
|
||||
devices = data.get("devices") if isinstance(data, dict) else None
|
||||
if not isinstance(devices, dict):
|
||||
return None
|
||||
for key, info in devices.items():
|
||||
if str(key).lower() == str(device_id).lower():
|
||||
if not isinstance(info, dict) or info.get("enabled", True) is False:
|
||||
return None
|
||||
return info
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_s2s_name(s2s_block: dict, brain: str) -> str | None:
|
||||
"""brain 既可以写 S2S 配置块里的名字(OpenAIRealtime),也可以写它的 type(openai_realtime)。"""
|
||||
if brain in s2s_block:
|
||||
return brain
|
||||
for name, cfg in s2s_block.items():
|
||||
if isinstance(cfg, dict) and str(cfg.get("type", name)) == brain:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def apply_device_overrides(conn) -> dict:
|
||||
"""把这台设备的覆盖项合并进 conn.config;返回实际应用了哪些(给日志 / 测试用)。"""
|
||||
applied: dict = {}
|
||||
try:
|
||||
config = conn.config
|
||||
path = config.get("device_overrides_file", DEFAULT_FILE)
|
||||
info = load_device_overrides(path, getattr(conn, "device_id", None))
|
||||
if not info:
|
||||
return applied
|
||||
selected = config.setdefault("selected_module", {})
|
||||
|
||||
brain = info.get("brain")
|
||||
if brain is not None:
|
||||
brain = str(brain).strip()
|
||||
if brain in ("", "cascade"):
|
||||
selected["S2S"] = ""
|
||||
applied["S2S"] = ""
|
||||
else:
|
||||
name = _resolve_s2s_name(config.get("S2S") or {}, brain)
|
||||
if name:
|
||||
selected["S2S"] = name
|
||||
applied["S2S"] = name
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 brain={brain} 既不是 S2S 配置块的名字也不是其中某项的 type,忽略")
|
||||
|
||||
prompt = info.get("prompt")
|
||||
if isinstance(prompt, str) and prompt.strip():
|
||||
config["prompt"] = prompt
|
||||
applied["prompt"] = True
|
||||
|
||||
for key, section in (("llm", "LLM"), ("tts", "TTS")):
|
||||
name = info.get(key)
|
||||
if isinstance(name, str) and name.strip():
|
||||
if name in (config.get(section) or {}):
|
||||
selected[section] = name
|
||||
applied[section] = name
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 {key}={name} 不在 {section} 配置块里,忽略")
|
||||
|
||||
if applied:
|
||||
conn.logger.bind(tag=TAG).info(f"已应用设备覆盖: {applied}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
conn.logger.bind(tag=TAG).warning(f"应用设备覆盖失败,按全局配置继续: {type(e).__name__}: {e}")
|
||||
return applied
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
"""按设备覆盖(data/devices.yaml):选大脑、提示词、LLM / TTS;没登记 / 停用 / 文件坏 / 名字不存在都不改配置、不抛异常。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
from config.logger import setup_logging
|
||||
from core.utils.device_overrides import apply_device_overrides, load_device_overrides
|
||||
|
||||
LOGGER = setup_logging()
|
||||
|
||||
REG = """
|
||||
version: 1
|
||||
devices:
|
||||
"AA:BB:CC:DD:EE:01": {name: s3, client_id: "x", brain: OpenAIRealtime, prompt: "你是书房助手"}
|
||||
"aa:bb:cc:dd:ee:02": {name: p, brain: cascade, llm: OtherLLM, tts: NoSuchTTS}
|
||||
"aa:bb:cc:dd:ee:03": {name: paused, enabled: false, brain: OpenAIRealtime}
|
||||
"aa:bb:cc:dd:ee:04": {name: bad-brain, brain: Nope}
|
||||
"aa:bb:cc:dd:ee:05": {name: by-type, brain: openai_realtime}
|
||||
"""
|
||||
|
||||
|
||||
class Conn:
|
||||
def __init__(self, device_id, path):
|
||||
self.device_id = device_id
|
||||
self.logger = LOGGER
|
||||
self.config = {
|
||||
"device_overrides_file": path,
|
||||
"prompt": "全局提示词",
|
||||
"selected_module": {"LLM": "MainLLM", "TTS": "EdgeTTS", "S2S": ""},
|
||||
"S2S": {"OpenAIRealtime": {"type": "openai_realtime"}},
|
||||
"LLM": {"MainLLM": {}, "OtherLLM": {}},
|
||||
"TTS": {"EdgeTTS": {}},
|
||||
}
|
||||
|
||||
|
||||
def test_brain_prompt_and_case_insensitive_mac(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:01", str(p))
|
||||
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime", "prompt": True}
|
||||
assert c.config["selected_module"]["S2S"] == "OpenAIRealtime" and c.config["prompt"] == "你是书房助手"
|
||||
|
||||
|
||||
def test_brain_accepts_provider_type_name(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:05", str(p))
|
||||
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime"} # 写 type 也能解析到配置块的名字
|
||||
|
||||
|
||||
def test_cascade_and_llm_override_with_unknown_tts_ignored(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:02", str(p))
|
||||
c.config["selected_module"]["S2S"] = "OpenAIRealtime" # 全局选了 S2S,这台设备要级联
|
||||
assert apply_device_overrides(c) == {"S2S": "", "LLM": "OtherLLM"}
|
||||
assert c.config["selected_module"] == {"LLM": "OtherLLM", "TTS": "EdgeTTS", "S2S": ""}
|
||||
assert c.config["prompt"] == "全局提示词"
|
||||
|
||||
|
||||
def test_no_change_cases(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
for dev in ("aa:bb:cc:dd:ee:03", "aa:bb:cc:dd:ee:04", "ff:ff:ff:ff:ff:ff", None):
|
||||
c = Conn(dev, str(p))
|
||||
before = copy.deepcopy(c.config)
|
||||
assert apply_device_overrides(c) == {}
|
||||
assert c.config == before
|
||||
c = Conn("aa:bb:cc:dd:ee:01", str(tmp_path / "missing.yaml"))
|
||||
assert apply_device_overrides(c) == {}
|
||||
p.write_text("{broken", encoding="utf-8")
|
||||
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None
|
||||
p.write_text("devices: [1, 2]\n", encoding="utf-8")
|
||||
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None
|
||||
Loading…
Reference in a new issue