mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Compare commits
8 commits
f5c9d51870
...
d1ba851b82
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1ba851b82 | ||
|
|
4b1a54a41c | ||
|
|
4f6e9ec6b1 | ||
|
|
dd367c9e43 | ||
|
|
b4e144afef | ||
|
|
9f5f520576 | ||
|
|
70f1a7bfd8 | ||
|
|
cef2540dc4 |
9 changed files with 368 additions and 43 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
|
# > 0: 使用固定延迟(毫秒)发送,例如: 60
|
||||||
tts_audio_send_delay: 0
|
tts_audio_send_delay: 0
|
||||||
|
|
||||||
|
# 按设备覆盖配置(单模块部署没有智控台时的差异化配置):按 device-id 从这个文件读该设备的大脑 / 提示词 / LLM / TTS,
|
||||||
|
# 每次连接都重读,改完表设备重连即生效;文件不存在就全部用全局配置。格式见 docs/device-overrides.md
|
||||||
|
device_overrides_file: data/devices.yaml
|
||||||
|
|
||||||
exit_commands:
|
exit_commands:
|
||||||
- "退出"
|
- "退出"
|
||||||
- "关闭"
|
- "关闭"
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ from core.utils.util import (
|
||||||
)
|
)
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from collections import deque
|
from collections import deque
|
||||||
|
from core.utils.device_overrides import apply_device_overrides
|
||||||
from core.utils.modules_initialize import (
|
from core.utils.modules_initialize import (
|
||||||
initialize_modules,
|
initialize_modules,
|
||||||
initialize_tts,
|
initialize_tts,
|
||||||
|
|
@ -219,6 +220,9 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
|
|
||||||
self.device_id = self.headers.get("device-id", None)
|
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
|
self.websocket = ws
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ if TYPE_CHECKING:
|
||||||
from core.connection import ConnectionHandler
|
from core.connection import ConnectionHandler
|
||||||
from ..base import IntentProviderBase
|
from ..base import IntentProviderBase
|
||||||
from plugins_func.functions.play_music import initialize_music_handler
|
from plugins_func.functions.play_music import initialize_music_handler
|
||||||
|
from plugins_func.functions.hass_init import _devices_text, _hass_plugin_config
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils.util import get_system_error_response
|
from core.utils.util import get_system_error_response
|
||||||
import re
|
import re
|
||||||
|
|
@ -181,16 +182,11 @@ class IntentProvider(IntentProviderBase):
|
||||||
music_file_names = music_config["music_file_names"]
|
music_file_names = music_config["music_file_names"]
|
||||||
prompt_music = f"{self.promot}\n<musicNames>{music_file_names}\n</musicNames>"
|
prompt_music = f"{self.promot}\n<musicNames>{music_file_names}\n</musicNames>"
|
||||||
|
|
||||||
home_assistant_cfg = conn.config["plugins"].get("home_assistant")
|
plugin_config = _hass_plugin_config(conn.config.get("plugins", {}))
|
||||||
if home_assistant_cfg:
|
devices_text = _devices_text(plugin_config.get("devices", ""))
|
||||||
devices = home_assistant_cfg.get("devices", [])
|
if devices_text:
|
||||||
else:
|
|
||||||
devices = []
|
|
||||||
if len(devices) > 0:
|
|
||||||
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
||||||
for device in devices:
|
prompt_music += hass_prompt + devices_text + "\n"
|
||||||
hass_prompt += device + "\n"
|
|
||||||
prompt_music += hass_prompt
|
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
||||||
|
|
||||||
|
|
|
||||||
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
|
||||||
|
|
@ -1,27 +1,53 @@
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
from plugins_func.register import module_func_map
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
def _expand_module_names(funcs):
|
||||||
|
"""把 functions 列表里的模块名(如 hass_state)展开成具体函数名,与工具加载口径一致。"""
|
||||||
|
expanded = []
|
||||||
|
for name in funcs:
|
||||||
|
expanded.extend(module_func_map.get(name, [name]))
|
||||||
|
return expanded
|
||||||
|
|
||||||
|
|
||||||
|
def _devices_text(devices) -> str:
|
||||||
|
"""把 devices 配置转成拼进提示词的文字。
|
||||||
|
|
||||||
|
config.yaml 示例和手机端智控台给的是列表,每项一条"位置,设备名,entity_id",这里拼成每行一条;
|
||||||
|
网页端智控台和 HA 集成文档是一段字符串,原样用;其它(如 None)当空。
|
||||||
|
"""
|
||||||
|
if isinstance(devices, (list, tuple)):
|
||||||
|
return "\n".join(
|
||||||
|
str(d).strip() for d in devices if d is not None and str(d).strip()
|
||||||
|
)
|
||||||
|
return devices if isinstance(devices, str) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _hass_plugin_config(plugins_config: dict) -> dict:
|
||||||
|
"""取 HA 插件配置:优先本地 config.yaml 的 home_assistant,其次智控台下发的 hass_state。"""
|
||||||
|
for key in ("home_assistant", "hass_state"):
|
||||||
|
cfg = plugins_config.get(key)
|
||||||
|
if cfg:
|
||||||
|
return cfg
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def append_devices_to_prompt(conn):
|
def append_devices_to_prompt(conn):
|
||||||
if conn.intent_type == "function_call":
|
if conn.intent_type == "function_call":
|
||||||
funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get(
|
funcs = _expand_module_names(
|
||||||
"functions", []
|
conn.config["Intent"][conn.config["selected_module"]["Intent"]].get(
|
||||||
)
|
"functions", []
|
||||||
|
)
|
||||||
# 安全地获取插件配置
|
|
||||||
plugins_config = conn.config.get("plugins", {})
|
|
||||||
config_source = (
|
|
||||||
"home_assistant"
|
|
||||||
if plugins_config.get("home_assistant")
|
|
||||||
else "hass_state"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if "hass_get_state" in funcs or "hass_set_state" in funcs:
|
if "hass_get_state" in funcs or "hass_set_state" in funcs:
|
||||||
prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
||||||
deviceStr = plugins_config.get(config_source, {}).get("devices", "")
|
plugin_config = _hass_plugin_config(conn.config.get("plugins", {}))
|
||||||
|
deviceStr = _devices_text(plugin_config.get("devices", ""))
|
||||||
conn.prompt += prompt + deviceStr + "\n"
|
conn.prompt += prompt + deviceStr + "\n"
|
||||||
# 更新提示词
|
# 更新提示词
|
||||||
conn.dialogue.update_system_message(conn.prompt)
|
conn.dialogue.update_system_message(conn.prompt)
|
||||||
|
|
@ -32,17 +58,10 @@ def initialize_hass_handler(conn):
|
||||||
if not conn.load_function_plugin:
|
if not conn.load_function_plugin:
|
||||||
return ha_config
|
return ha_config
|
||||||
|
|
||||||
# 安全地获取插件配置
|
plugin_config = _hass_plugin_config(conn.config.get("plugins", {}))
|
||||||
plugins_config = conn.config.get("plugins", {})
|
if not plugin_config:
|
||||||
# 确定配置来源
|
|
||||||
config_source = (
|
|
||||||
"home_assistant" if plugins_config.get("home_assistant") else "hass_state"
|
|
||||||
)
|
|
||||||
if not plugins_config.get(config_source):
|
|
||||||
return ha_config
|
return ha_config
|
||||||
|
|
||||||
# 统一获取配置
|
|
||||||
plugin_config = plugins_config[config_source]
|
|
||||||
ha_config["base_url"] = plugin_config.get("base_url")
|
ha_config["base_url"] = plugin_config.get("base_url")
|
||||||
ha_config["api_key"] = plugin_config.get("api_key")
|
ha_config["api_key"] = plugin_config.get("api_key")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -121,13 +121,10 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id):
|
||||||
+ str(response.json()["attributes"]["media_title"])
|
+ str(response.json()["attributes"]["media_title"])
|
||||||
+ " "
|
+ " "
|
||||||
)
|
)
|
||||||
if "volume_level" in response.json()["attributes"]:
|
volume_level = response.json()["attributes"].get("volume_level")
|
||||||
responsetext = (
|
if isinstance(volume_level, (int, float)):
|
||||||
responsetext
|
# volume_level 量程 0~1,换算成百分比(同 volume_set 的 1~100)
|
||||||
+ "音量是:"
|
responsetext = responsetext + "音量是:" + f"{round(volume_level * 100)}%" + " "
|
||||||
+ str(response.json()["attributes"]["volume_level"])
|
|
||||||
+ " "
|
|
||||||
)
|
|
||||||
if "color_temp_kelvin" in response.json()["attributes"]:
|
if "color_temp_kelvin" in response.json()["attributes"]:
|
||||||
responsetext = (
|
responsetext = (
|
||||||
responsetext
|
responsetext
|
||||||
|
|
@ -142,13 +139,11 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id):
|
||||||
+ str(response.json()["attributes"]["rgb_color"])
|
+ str(response.json()["attributes"]["rgb_color"])
|
||||||
+ " "
|
+ " "
|
||||||
)
|
)
|
||||||
if "brightness" in response.json()["attributes"]:
|
brightness = response.json()["attributes"].get("brightness")
|
||||||
responsetext = (
|
if isinstance(brightness, (int, float)):
|
||||||
responsetext
|
# brightness 量程 0~255,换算成百分比(同 brightness_pct 的 1~100),开灯最低报 1%
|
||||||
+ "亮度是:"
|
percent = max(1, round(brightness * 100 / 255)) if brightness > 0 else 0
|
||||||
+ str(response.json()["attributes"]["brightness"])
|
responsetext = responsetext + "亮度是:" + f"{percent}%" + " "
|
||||||
+ " "
|
|
||||||
)
|
|
||||||
logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}")
|
logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}")
|
||||||
return responsetext
|
return responsetext
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
84
main/xiaozhi-server/tests/plugins_func/test_hass_init.py
Normal file
84
main/xiaozhi-server/tests/plugins_func/test_hass_init.py
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
"""append_devices_to_prompt:devices 写成列表或一段字符串都能拼进提示词。
|
||||||
|
|
||||||
|
config.yaml 示例和手机端智控台给的是列表,以前会报
|
||||||
|
can only concatenate str (not "list") to str,设备清单进不了提示词,模型只能猜 entity_id。
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import plugins_func.functions.hass_state # noqa: F401 注册 hass_state 模块,填充 module_func_map
|
||||||
|
from plugins_func.functions.hass_init import append_devices_to_prompt
|
||||||
|
|
||||||
|
HEADER = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
||||||
|
BASE_PROMPT = "你是小智。"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeDialogue:
|
||||||
|
def __init__(self):
|
||||||
|
self.system_messages = []
|
||||||
|
|
||||||
|
def update_system_message(self, prompt):
|
||||||
|
self.system_messages.append(prompt)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def __init__(self, plugin, source="home_assistant", functions=("hass_get_state", "hass_set_state")):
|
||||||
|
self.intent_type = "function_call"
|
||||||
|
self.config = {
|
||||||
|
"selected_module": {"Intent": "function_call"},
|
||||||
|
"Intent": {"function_call": {"functions": list(functions)}},
|
||||||
|
"plugins": {source: plugin},
|
||||||
|
}
|
||||||
|
self.prompt = BASE_PROMPT
|
||||||
|
self.dialogue = FakeDialogue()
|
||||||
|
|
||||||
|
|
||||||
|
def _plugin(**extra):
|
||||||
|
return {"base_url": "http://homeassistant.local:8123", "api_key": "test-token", **extra}
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_devices_one_per_line():
|
||||||
|
conn = FakeConn(_plugin(devices=[
|
||||||
|
"客厅,玩具灯,switch.toy_lamp",
|
||||||
|
" 卧室,台灯,switch.desk_lamp ",
|
||||||
|
"",
|
||||||
|
]))
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
expected = BASE_PROMPT + HEADER + "客厅,玩具灯,switch.toy_lamp\n卧室,台灯,switch.desk_lamp\n"
|
||||||
|
assert conn.prompt == expected
|
||||||
|
assert conn.dialogue.system_messages == [expected]
|
||||||
|
|
||||||
|
|
||||||
|
def test_string_devices_kept_as_is():
|
||||||
|
# 网页端智控台和 HA 集成文档给的是一段字符串
|
||||||
|
devices = "客厅,玩具灯,switch.toy_lamp;\n卧室,台灯,switch.desk_lamp;"
|
||||||
|
conn = FakeConn(_plugin(devices=devices))
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
assert conn.prompt == BASE_PROMPT + HEADER + devices + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_mobile_console_hass_state_list():
|
||||||
|
# 智控台下发的插件配置键是 hass_state;手机端把 array 字段按行切成了列表
|
||||||
|
conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), source="hass_state")
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
assert conn.prompt.endswith(HEADER + "客厅,玩具灯,switch.toy_lamp\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_module_name_in_functions():
|
||||||
|
# functions 里写模块名 hass_state(config.yaml 注释的写法),展开后应能匹配
|
||||||
|
conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), functions=("hass_state",))
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
assert conn.prompt.endswith(HEADER + "客厅,玩具灯,switch.toy_lamp\n")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("plugin", [_plugin(), _plugin(devices=None), _plugin(devices=[])])
|
||||||
|
def test_missing_or_empty_devices_does_not_raise(plugin):
|
||||||
|
conn = FakeConn(plugin)
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
assert conn.prompt == BASE_PROMPT + HEADER + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_hass_functions_prompt_unchanged():
|
||||||
|
conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), functions=("get_weather",))
|
||||||
|
append_devices_to_prompt(conn)
|
||||||
|
assert conn.prompt == BASE_PROMPT
|
||||||
|
assert conn.dialogue.system_messages == []
|
||||||
Loading…
Reference in a new issue