mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: document Mac server deployment and add child text dialogue
Record validated FunASR, EdgeTTS, WebSocket and incomplete LLM results; fix provider benchmark false positives; add a bounded child dialogue service using existing LLM adapters and no-key mock tests.
This commit is contained in:
parent
a6cd755cf2
commit
d7e8ed5c77
11 changed files with 483 additions and 17 deletions
114
docs/mac-server-deployment.md
Normal file
114
docs/mac-server-deployment.md
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
# macOS 上的 Python Server-only 基础部署记录
|
||||||
|
|
||||||
|
本记录以 2026-10-09 的 `main` 提交 `a6cd755cf281f0e49ffbce489666acf09755de6c` 为基线,在独立分支 `docs/mac-server-deployment-20261009` 操作。只沿用仓库的 `FunASR`、`ChatGLMLLM` 和 `EdgeTTS`,不改变设备 Opus/WebSocket 音频协议。配置示例见 [mac-server-only.example.yaml](mac-server-only.example.yaml)。以下“结果”是该机器实测,不可当作其他 Mac 的保证。
|
||||||
|
|
||||||
|
## 2026-10-10 复测
|
||||||
|
|
||||||
|
本节在本地分支 `feature/child-agent-dialogue-20261010` 复核;它包含前一部署提交。因上游 GitHub 连接只有读取权限,尚未推送到 GitHub,也未创建 PR。
|
||||||
|
|
||||||
|
| 操作 | 本次实际结果 | 判定 |
|
||||||
|
|---|---|---|
|
||||||
|
| 环境 | macOS 14.1 arm64,仓库 `.venv` 为 Python 3.10.10;工作目录 Miniforge 提供 FFmpeg 9.0.2;设置 `DYLD_FALLBACK_LIBRARY_PATH` 后 `ctypes.CDLL('libopus.dylib')` 成功,FunASR、websockets、edge-tts 可导入 | 所选运行环境通过 |
|
||||||
|
| ASR 现有脚本 | `performance_tester_asr.py` 退出码 0;FunASR 对 4 个内置音频得到 `4/4 ✅`,平均 0.918 秒 | 通过 |
|
||||||
|
| TTS 现有脚本 | `performance_tester_tts.py` 退出码 0;EdgeTTS 三项检查均成功,汇总 `3 ✅` | 通过 |
|
||||||
|
| LLM 现有脚本 | `performance_tester_llm.py` 退出码 0,但所选 `ChatGLMLLM` 显示“未配置 api_key,已跳过”,没有真实模型回答 | **未通过** |
|
||||||
|
| 服务监听 | `app.py` 启动后,`lsof` 确认 `127.0.0.1:8000 LISTEN`;HTTP GET 返回 200;WebSocket 原生握手返回 `HTTP/1.1 101 Switching Protocols` | 启动和握手通过 |
|
||||||
|
| 停止服务 | 当前自动化沙箱拒绝向测试进程 PID 73812 发送 Ctrl+C 或 `kill -INT`(`operation not permitted`),复测时端口仍在监听 | **自动停止未通过**;在 Mac 终端执行 `kill -INT 73812`,然后用 `lsof -nP -iTCP:8000 -sTCP:LISTEN` 确认端口释放;PID 可能随进程变化 |
|
||||||
|
|
||||||
|
官方 `pip install -r requirements.txt` 仍因 `vosk==0.3.45` 在这台 Mac arm64/Python 3.10 上不可安装而**未通过**;本次没有改动官方依赖文件,也没有把临时依赖清单、模型文件、真实密钥或测试音频提交。
|
||||||
|
|
||||||
|
## 现有环境与安装结果
|
||||||
|
|
||||||
|
| 项目 | 实际结果 | 判定 |
|
||||||
|
|---|---|---|
|
||||||
|
| Git/分支 | 从上游 `main` 独立浅克隆,原工作区未覆盖;当前分支 `docs/mac-server-deployment-20261009` | 通过 |
|
||||||
|
| Python | macOS 14.1、arm64;系统有 Python 3.10.10 和 3.13.15;本仓库创建 `.venv`(3.10) | Python 环境通过;服务依赖另计 |
|
||||||
|
| FFmpeg / libopus | 初始均未检测到。`brew install ffmpeg opus` 因 Homebrew Git 锁和无可用 bottle 失败;随后在工作目录安装 Miniforge,以 `mamba install -c conda-forge ffmpeg libopus` 成功安装,`ffmpeg -version` 报 9.0.2;设置 `DYLD_FALLBACK_LIBRARY_PATH` 后,Python 3.10 用 `ctypes.CDLL("libopus.dylib")` 成功加载 | 系统音频库通过;完整服务另计 |
|
||||||
|
| 依赖 | 在 `.venv` 中按原始 `requirements.txt` 执行 `pip install -r`,PyPI 返回 `No matching distribution found for vosk==0.3.45`;工作目录临时清单只去掉未选用的 Vosk,其余依赖安装完成,`funasr==1.2.7`、`websockets==14.2`、`edge-tts==7.2.6` 可查 | 官方完整安装**未通过**;所选适配器依赖安装通过 |
|
||||||
|
| FunASR | 按上游部署文档下载 `models/SenseVoiceSmall/model.pt`(893 MB,SHA-256 `833ca2dcfdf8ec91bd4f31cfac36d6124e0c459074d5e909aec9cabe6204a3ea`,与下载响应 `X-Linked-Etag` 相符;文件被 Git 忽略)。原 ASR 性能脚本把 WAV 容器字节当 PCM 输入,且多传一个参数,结果 `0/4`。本分支修正脚本后重跑,4 段内置 WAV 均识别出非空文本,汇总 `4/4 ✅`,平均 0.774 秒;另用适配器直接识别 `zh.mp3` 转成的 16 kHz 单声道 PCM,得到“开饭时间早上9点至下午5点。” | **通过**,仅证明本机 ASR 适配器和脚本 |
|
||||||
|
| LLM | 配置示例无真实密钥。原脚本收到三次 401 却错误汇总为 `3/3 ✅`;本分支修正异常和空回复判定。用假提供方验证 401/空回复均判失败;本地配置重跑显示 `ChatGLMLLM 未配置 api_key,已跳过` | **未通过**,无真实密钥与有效模型回答 |
|
||||||
|
| EdgeTTS | 上游 TTS 脚本实际生成连接测试及两段测试音频,汇总为 `EdgeTTS ✅ 正常`,均在被忽略的临时目录内 | 通过;仅验证服务端 TTS,不代表设备播放 |
|
||||||
|
| WebSocket | `app.py` 完成 FunASR 等模块初始化并监听 `127.0.0.1:8000`;HTTP GET 返回 200,原生 WebSocket 握手返回 `HTTP/1.1 101 Switching Protocols`;Ctrl+C 后端口释放 | 监听和握手通过;未验证设备会话/音频 |
|
||||||
|
|
||||||
|
## 官方依赖路径
|
||||||
|
|
||||||
|
上游 [Server-only 源码部署](Deployment.md) 推荐 Python 3.10,系统需 `libopus` 和 `ffmpeg`,然后在 `main/xiaozhi-server` 安装 `requirements.txt`。Mac 上不要把系统 Python 3.13 与这份固定依赖混用。当前 `requirements.txt` 固定 `torch==2.2.2`、`torchaudio==2.2.2`、`numpy==1.26.4`、`websockets==14.2` 等;依赖是否可用以安装与导入实测为准。当前 Mac arm64/Python 3.10 环境找不到 `vosk==0.3.45` 的可安装版本,所以不改仓库依赖文件,只在工作目录的临时清单中剔除未选用的 Vosk 以继续核验 FunASR/LLM/EdgeTTS。全套管理后台不属于本次 Server-only 范围。
|
||||||
|
|
||||||
|
## 本地配置
|
||||||
|
|
||||||
|
在仓库根目录执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
mkdir -p main/xiaozhi-server/data
|
||||||
|
cp docs/mac-server-only.example.yaml main/xiaozhi-server/data/.config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
`data/.config.yaml` 已被 `.gitignore` 忽略。它是**示例**,其中 `api_key` 占位符不能完成 LLM 测试;只在这个本地文件中填入你自己的密钥。FunASR 还需下载上游要求的 SenseVoiceSmall 模型文件;模型和密钥都不得提交。实体 ESP32 使用时,`127.0.0.1` 必须改为 Mac 局域网地址,并检查认证与网络边界。
|
||||||
|
|
||||||
|
## 启动、停止、日志与健康检查
|
||||||
|
|
||||||
|
从仓库根目录执行(系统库和依赖全部可用后):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd main/xiaozhi-server
|
||||||
|
# 若像本次一样将 FFmpeg/libopus 装在独立 Miniforge 中,先将其 bin/lib 放入当前终端环境。
|
||||||
|
# 具体路径以自己的安装位置为准;不需要修改全局 shell 配置。
|
||||||
|
export PATH="/path/to/miniforge3/bin:$PATH"
|
||||||
|
export DYLD_FALLBACK_LIBRARY_PATH="/path/to/miniforge3/lib${DYLD_FALLBACK_LIBRARY_PATH:+:$DYLD_FALLBACK_LIBRARY_PATH}"
|
||||||
|
../../.venv/bin/python app.py
|
||||||
|
# 前台停止:按 Ctrl+C
|
||||||
|
```
|
||||||
|
|
||||||
|
前台进程日志直接显示在当前终端;程序还按 `config.yaml` 的 `log.log_dir`/`log.log_file` 写入 `tmp/server.log`。另一个终端可检查:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd main/xiaozhi-server
|
||||||
|
tail -n 100 -f tmp/server.log
|
||||||
|
lsof -nP -iTCP:8000 -sTCP:LISTEN
|
||||||
|
curl -i --max-time 3 http://127.0.0.1:8000/
|
||||||
|
```
|
||||||
|
|
||||||
|
`curl` 的 HTTP 响应仅证明进程可达;**WebSocket 必须检查 101 升级**。在另一个终端运行以下不含密钥的握手:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3.10 - <<'PY'
|
||||||
|
import base64, os, socket
|
||||||
|
key = base64.b64encode(os.urandom(16)).decode()
|
||||||
|
request = ("GET /xiaozhi/v1/ HTTP/1.1\r\nHost: 127.0.0.1:8000\r\n"
|
||||||
|
"Upgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||||
|
f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n")
|
||||||
|
with socket.create_connection(("127.0.0.1", 8000), timeout=3) as sock:
|
||||||
|
sock.sendall(request.encode())
|
||||||
|
print(sock.recv(1024).decode(errors="replace").split("\r\n", 1)[0])
|
||||||
|
PY
|
||||||
|
```
|
||||||
|
|
||||||
|
期望首行为 `HTTP/1.1 101 Switching Protocols`。这只验证监听和握手,**不等于 ASR/LLM/TTS 或 ESP32 全链路成功**。认证开关、代理和实际监听路径改变时需按服务端配置调整测试。
|
||||||
|
|
||||||
|
## 已有模型测试脚本
|
||||||
|
|
||||||
|
上游提供 `main/xiaozhi-server/performance_tester.py`,可交互选择 `performance_tester_asr`、`performance_tester_llm`、`performance_tester_tts`。先在被忽略的本地配置中完成模型/密钥设置,并提供测试音频。该脚本会调用真实提供方,可能联网和计费:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd main/xiaozhi-server
|
||||||
|
../../.venv/bin/python performance_tester.py
|
||||||
|
```
|
||||||
|
|
||||||
|
也可在 `main/xiaozhi-server` 目录中单独运行上游脚本(需让脚本能导入项目的 `core` 包):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export PYTHONPATH="$PWD"
|
||||||
|
../../.venv/bin/python performance_tester/performance_tester_asr.py
|
||||||
|
../../.venv/bin/python performance_tester/performance_tester_llm.py
|
||||||
|
../../.venv/bin/python performance_tester/performance_tester_tts.py
|
||||||
|
```
|
||||||
|
|
||||||
|
ASR 脚本从 `config/assets` 查找超过 300 KB 的 WAV 测试音频;本分支用 FFmpeg 转为适配器要求的 16 kHz 单声道 PCM,仓库内 4 个样本实际达到 `4/4`。LLM 缺真实密钥时不能判为通过。TTS 需产出实际音频文件才算通过;仅能导入适配器不算通过。记录每项脚本的退出码、摘要和实际输出,不提交任何儿童录音、日志密钥或生成音频。
|
||||||
|
|
||||||
|
**判定以真实结果为准,不以脚本退出码或单独的汇总“✅”为准。**修复前 ASR 退出码为 0,但 `0/4`;LLM 首次使用无效占位符时收到 401,汇总却显示 `3/3 ✅`。本分支修正了这两处性能脚本问题。本示例的占位符含“你的”,让脚本跳过无密钥的 LLM。
|
||||||
|
|
||||||
|
## 尚需人工完成
|
||||||
|
|
||||||
|
1. 在被 Git 忽略的 `main/xiaozhi-server/data/.config.yaml` 中填入自己申请的真实 LLM API Key,确认提供方可用、配额和费用,然后重跑 LLM 性能脚本;目前状态必须保留为**未通过**。
|
||||||
|
2. 接入真实 ESP32-S3、麦克风与扬声器,在局域网正确配置服务端地址,并验证语音输入、识别、模型回答、合成、播放的完整循环;本次仅验证本机 WebSocket 握手,未做端到端设备测试。
|
||||||
|
3. 如需完整官方依赖安装或启用 Vosk,在适配 macOS arm64 的 Python/包源环境中解决 `vosk==0.3.45` 分发问题并重跑完整 `pip install -r requirements.txt`;当前该项**未通过**。
|
||||||
39
docs/mac-server-only.example.yaml
Normal file
39
docs/mac-server-only.example.yaml
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
# Copy to main/xiaozhi-server/data/.config.yaml in your own checkout.
|
||||||
|
# The destination is git-ignored. This example contains no working API key.
|
||||||
|
# It overrides config.yaml; all omitted values keep upstream defaults.
|
||||||
|
# The loopback address is for Mac-only testing. Use the Mac's LAN address when
|
||||||
|
# connecting a physical ESP32 and review authentication before LAN exposure.
|
||||||
|
server:
|
||||||
|
ip: 127.0.0.1
|
||||||
|
port: 8000
|
||||||
|
http_port: 8003
|
||||||
|
websocket: ws://127.0.0.1:8000/xiaozhi/v1/
|
||||||
|
|
||||||
|
selected_module:
|
||||||
|
VAD: SileroVAD
|
||||||
|
ASR: FunASR
|
||||||
|
LLM: ChatGLMLLM
|
||||||
|
TTS: EdgeTTS
|
||||||
|
Memory: nomem
|
||||||
|
Intent: nointent
|
||||||
|
|
||||||
|
ASR:
|
||||||
|
FunASR:
|
||||||
|
type: fun_local
|
||||||
|
model_dir: models/SenseVoiceSmall
|
||||||
|
output_dir: tmp/
|
||||||
|
language: zh
|
||||||
|
|
||||||
|
LLM:
|
||||||
|
ChatGLMLLM:
|
||||||
|
type: openai
|
||||||
|
model_name: glm-4-flash
|
||||||
|
url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
|
# Contains "你的" so the upstream performance tester skips this placeholder.
|
||||||
|
api_key: "你的API密钥_仅填入本地忽略文件"
|
||||||
|
|
||||||
|
TTS:
|
||||||
|
EdgeTTS:
|
||||||
|
type: edge
|
||||||
|
voice: zh-CN-XiaoxiaoNeural
|
||||||
|
output_dir: tmp/
|
||||||
32
main/xiaozhi-server/child_agent/README.md
Normal file
32
main/xiaozhi-server/child_agent/README.md
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
# 儿童文本对话模块
|
||||||
|
|
||||||
|
`DialogueService` 沿用 `core.utils.llm.create_instance` 与现有提供方的 `response(session_id, dialogue)` 接口。它不修改 WebSocket 或音频协议。返回值 `DialogueReply` 包含 `text`、`status` 和 `session_id`。每个会话只保留最近 `max_turns` 轮成功对话;空输入、超时和 API 失败不会写入上下文,历史最多保留 `max_sessions` 个会话。进程重启后历史清空。
|
||||||
|
|
||||||
|
在 `main/xiaozhi-server` 目录,准备好被 Git 忽略的 `data/.config.yaml` 后,可在现有服务代码中调用:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from child_agent import DialogueService
|
||||||
|
|
||||||
|
service = DialogueService.from_config(config, max_turns=4, timeout_seconds=10)
|
||||||
|
reply = service.chat("设备或用户的会话 ID", "月亮为什么跟着我走?")
|
||||||
|
print(reply.status, reply.text)
|
||||||
|
```
|
||||||
|
|
||||||
|
`config` 是服务器已经合并的配置字典;`from_config` 按 `selected_module.LLM` 选择原项目适配器。不要把密钥放进代码或测试。系统提示词位于 `prompts/base_system.md`,提供适龄回答与危险秘密处理规则;提示词只能引导模型,不能保证真实模型每次输出都安全,需要另行进行真实内容评估。同步适配器的超时只能及时结束调用者等待,不能强制中断已经开始的网络请求;模块最多允许 4 个后台调用同时进行,并为现有 OpenAI 兼容适配器设置默认网络超时。
|
||||||
|
|
||||||
|
无密钥 Mock 测试:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd main/xiaozhi-server
|
||||||
|
../../.venv/bin/python -m unittest discover -s tests/child_agent -p 'test_dialogue_service.py' -v
|
||||||
|
```
|
||||||
|
|
||||||
|
本机实测:9 个 Mock 测试通过,覆盖“你好”“月亮为什么跟着我走?”“你是人吗?”“有人让我保守危险秘密”、空输入、LLM 超时、API 异常、有限上下文及现有适配器工厂的调用。Mock 的回复是固定测试文本,不能证明真实模型的回答质量。
|
||||||
|
|
||||||
|
真实 API 测试须在本地忽略文件中填入有效 `api_key`,显式选择运行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
RUN_LIVE_CHILD_AGENT_TESTS=1 ../../.venv/bin/python -m unittest discover -s tests/child_agent -p 'test_dialogue_service.py' -v
|
||||||
|
```
|
||||||
|
|
||||||
|
本机执行了该命令;真实 API 项结果为 `skipped 'real API key is absent'`,所以**真实 API 测试未通过/未完成**,没有声称模型可用。此测试只核验“你好”获得非空回复;上线前还需针对儿童安全、事实准确性和异常场景做人工评估。
|
||||||
6
main/xiaozhi-server/child_agent/__init__.py
Normal file
6
main/xiaozhi-server/child_agent/__init__.py
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
"""Simple text dialogue service for children aged six to seven."""
|
||||||
|
|
||||||
|
from .dialogue_service import DialogueService
|
||||||
|
from .schemas import DialogueReply, ReplyStatus
|
||||||
|
|
||||||
|
__all__ = ["DialogueService", "DialogueReply", "ReplyStatus"]
|
||||||
98
main/xiaozhi-server/child_agent/dialogue_service.py
Normal file
98
main/xiaozhi-server/child_agent/dialogue_service.py
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
"""Bounded session history around the server's existing streaming LLM adapter."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from collections import OrderedDict
|
||||||
|
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .prompt_builder import build_dialogue, load_system_prompt
|
||||||
|
from .schemas import DialogueReply, ReplyStatus
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DialogueService:
|
||||||
|
def __init__(
|
||||||
|
self, llm: Any, *, max_turns: int = 4, timeout_seconds: float = 10,
|
||||||
|
max_sessions: int = 128, system_prompt: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
if max_turns < 1 or max_sessions < 1 or timeout_seconds <= 0:
|
||||||
|
raise ValueError("max_turns, max_sessions and timeout_seconds must be positive")
|
||||||
|
self._llm = llm
|
||||||
|
self.max_turns = max_turns
|
||||||
|
self.timeout_seconds = timeout_seconds
|
||||||
|
self.max_sessions = max_sessions
|
||||||
|
self.system_prompt = system_prompt or load_system_prompt()
|
||||||
|
self._history: OrderedDict[str, list[dict[str, str]]] = OrderedDict()
|
||||||
|
self._lock = threading.RLock()
|
||||||
|
# Timed-out synchronous provider calls cannot be forcibly stopped.
|
||||||
|
# Bound the number of calls that can remain in the background.
|
||||||
|
self._slots = threading.BoundedSemaphore(4)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_config(cls, config: dict, **kwargs: Any) -> "DialogueService":
|
||||||
|
"""Select an existing provider using the server's normal LLM factory."""
|
||||||
|
from core.utils.llm import create_instance
|
||||||
|
|
||||||
|
name = config["selected_module"]["LLM"]
|
||||||
|
provider_config = dict(config["LLM"][name])
|
||||||
|
if provider_config["type"] == "openai":
|
||||||
|
provider_config.setdefault("timeout", kwargs.get("timeout_seconds", 10))
|
||||||
|
return cls(create_instance(provider_config["type"], provider_config), **kwargs)
|
||||||
|
|
||||||
|
def chat(self, session_id: str, user_text: str) -> DialogueReply:
|
||||||
|
if not isinstance(session_id, str) or not session_id.strip():
|
||||||
|
raise ValueError("session_id must be a non-empty string")
|
||||||
|
if not isinstance(user_text, str) or not user_text.strip():
|
||||||
|
return DialogueReply(session_id, "我没听清楚,可以再说一次吗?", ReplyStatus.EMPTY_INPUT)
|
||||||
|
|
||||||
|
user_text = user_text.strip()
|
||||||
|
with self._lock:
|
||||||
|
history = list(self._history.get(session_id, []))
|
||||||
|
messages = build_dialogue(user_text, history, self.system_prompt)
|
||||||
|
|
||||||
|
if not self._slots.acquire(blocking=False):
|
||||||
|
return DialogueReply(session_id, "我现在有点忙,请稍后再试。", ReplyStatus.API_ERROR)
|
||||||
|
|
||||||
|
# Existing adapters are synchronous generators. A worker enforces the
|
||||||
|
# caller's deadline; the provider's own network timeout should also be set.
|
||||||
|
executor = ThreadPoolExecutor(max_workers=1)
|
||||||
|
try:
|
||||||
|
future = executor.submit(self._collect, session_id, messages)
|
||||||
|
except Exception:
|
||||||
|
self._slots.release()
|
||||||
|
executor.shutdown(wait=False)
|
||||||
|
raise
|
||||||
|
future.add_done_callback(lambda _future: self._slots.release())
|
||||||
|
try:
|
||||||
|
answer = future.result(timeout=self.timeout_seconds)
|
||||||
|
except FutureTimeout:
|
||||||
|
logger.warning("Child dialogue timed out for session %s", session_id)
|
||||||
|
return DialogueReply(session_id, "我想一想,请稍后再试一次。", ReplyStatus.TIMEOUT)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Child dialogue provider failed for session %s", session_id)
|
||||||
|
return DialogueReply(session_id, "现在没法回答,我们稍后再试。", ReplyStatus.API_ERROR)
|
||||||
|
finally:
|
||||||
|
executor.shutdown(wait=False, cancel_futures=True)
|
||||||
|
|
||||||
|
if not answer:
|
||||||
|
return DialogueReply(session_id, "现在没法回答,我们稍后再试。", ReplyStatus.API_ERROR)
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
turns = self._history.setdefault(session_id, [])
|
||||||
|
turns.extend(({"role": "user", "content": user_text},
|
||||||
|
{"role": "assistant", "content": answer}))
|
||||||
|
del turns[:-2 * self.max_turns]
|
||||||
|
self._history.move_to_end(session_id)
|
||||||
|
while len(self._history) > self.max_sessions:
|
||||||
|
self._history.popitem(last=False)
|
||||||
|
return DialogueReply(session_id, answer, ReplyStatus.OK)
|
||||||
|
|
||||||
|
def clear_session(self, session_id: str) -> None:
|
||||||
|
with self._lock:
|
||||||
|
self._history.pop(session_id, None)
|
||||||
|
|
||||||
|
def _collect(self, session_id: str, messages: list[dict[str, str]]) -> str:
|
||||||
|
chunks = self._llm.response(session_id, messages)
|
||||||
|
return "".join(part for part in chunks if isinstance(part, str)).strip()
|
||||||
19
main/xiaozhi-server/child_agent/prompt_builder.py
Normal file
19
main/xiaozhi-server/child_agent/prompt_builder.py
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
"""Build the message format accepted by existing LLM providers."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Mapping, Sequence
|
||||||
|
|
||||||
|
_PROMPT_FILE = Path(__file__).parent / "prompts" / "base_system.md"
|
||||||
|
|
||||||
|
|
||||||
|
def load_system_prompt() -> str:
|
||||||
|
return _PROMPT_FILE.read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def build_dialogue(
|
||||||
|
user_text: str, history: Sequence[Mapping[str, str]], system_prompt: str
|
||||||
|
) -> list[dict[str, str]]:
|
||||||
|
messages = [{"role": "system", "content": system_prompt}]
|
||||||
|
messages.extend({"role": item["role"], "content": item["content"]} for item in history)
|
||||||
|
messages.append({"role": "user", "content": user_text})
|
||||||
|
return messages
|
||||||
7
main/xiaozhi-server/child_agent/prompts/base_system.md
Normal file
7
main/xiaozhi-server/child_agent/prompts/base_system.md
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
你是陪伴 6–7 岁儿童的中文对话伙伴。用温暖、简短、清楚的话回答;每次优先说 1–3 句话,必要时用孩子熟悉的例子解释。鼓励提问,不嘲笑或责备孩子。未知的事实要诚实说不知道,不编造。
|
||||||
|
|
||||||
|
你是人工智能,不是人;孩子直接询问时如实回答。不要要求孩子提供姓名、住址、电话、学校、密码或照片,也不要鼓励与陌生人私下联系。
|
||||||
|
|
||||||
|
如果孩子提到伤害、威胁、危险秘密或有人要求隐瞒让自己不安全的事,先肯定孩子愿意说出来,明确告诉孩子不必保守危险秘密,鼓励立刻告诉身边可信赖的大人;如眼前有危险,去安全的地方并请大人联系当地紧急服务。不要追问细节,不承诺保密。
|
||||||
|
|
||||||
|
不要给出适合成人的暴力、性或自伤细节。遇到超出儿童理解或需要专业帮助的问题,用适龄语言说明,并请可信赖的大人一起处理。
|
||||||
18
main/xiaozhi-server/child_agent/schemas.py
Normal file
18
main/xiaozhi-server/child_agent/schemas.py
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
"""Public result types for child dialogue."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class ReplyStatus(str, Enum):
|
||||||
|
OK = "ok"
|
||||||
|
EMPTY_INPUT = "empty_input"
|
||||||
|
TIMEOUT = "timeout"
|
||||||
|
API_ERROR = "api_error"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DialogueReply:
|
||||||
|
session_id: str
|
||||||
|
text: str
|
||||||
|
status: ReplyStatus
|
||||||
|
|
@ -3,6 +3,7 @@ import logging
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
|
import subprocess
|
||||||
from typing import Dict, Optional
|
from typing import Dict, Optional
|
||||||
import aiohttp
|
import aiohttp
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
|
@ -57,9 +58,20 @@ class ASRPerformanceTester:
|
||||||
print(f"[DEBUG] 找到音频文件: {file_list}")
|
print(f"[DEBUG] 找到音频文件: {file_list}")
|
||||||
for file_name in file_list:
|
for file_name in file_list:
|
||||||
file_path = os.path.join(wav_root, file_name)
|
file_path = os.path.join(wav_root, file_name)
|
||||||
if os.path.getsize(file_path) > 300 * 1024: # 300KB
|
if not file_name.lower().endswith(".wav") or os.path.getsize(file_path) <= 300 * 1024:
|
||||||
with open(file_path, "rb") as f:
|
continue
|
||||||
test_wav_list.append(f.read())
|
# speech_to_text_wrapper receives 16 kHz mono PCM, not WAV headers.
|
||||||
|
try:
|
||||||
|
pcm = subprocess.run(
|
||||||
|
["ffmpeg", "-v", "error", "-i", file_path, "-ar", "16000",
|
||||||
|
"-ac", "1", "-f", "s16le", "-"],
|
||||||
|
check=True, capture_output=True,
|
||||||
|
).stdout
|
||||||
|
except (OSError, subprocess.CalledProcessError) as exc:
|
||||||
|
print(f" 跳过无法解码的音频 {file_name}: {exc}")
|
||||||
|
continue
|
||||||
|
if pcm:
|
||||||
|
test_wav_list.append(pcm)
|
||||||
else:
|
else:
|
||||||
print(f" 目录不存在: {wav_root}")
|
print(f" 目录不存在: {wav_root}")
|
||||||
return test_wav_list
|
return test_wav_list
|
||||||
|
|
@ -68,8 +80,9 @@ class ASRPerformanceTester:
|
||||||
"""测试单个音频文件的性能"""
|
"""测试单个音频文件的性能"""
|
||||||
try:
|
try:
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text, _ = await stt.speech_to_text_wrapper([audio_data], "1", stt.audio_format)
|
text, _ = await stt.speech_to_text_wrapper([audio_data], "1")
|
||||||
if text is None:
|
recognized = text.get("content") if isinstance(text, dict) else text
|
||||||
|
if not isinstance(recognized, str) or not recognized.strip():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
duration = time.time() - start_time
|
duration = time.time() - start_time
|
||||||
|
|
@ -351,4 +364,4 @@ async def main():
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
|
||||||
|
|
@ -104,17 +104,8 @@ class LLMPerformanceTester:
|
||||||
# 更详细的错误信息
|
# 更详细的错误信息
|
||||||
error_msg = str(e).lower()
|
error_msg = str(e).lower()
|
||||||
print(f"{llm_name} 响应收集异常: {error_msg}")
|
print(f"{llm_name} 响应收集异常: {error_msg}")
|
||||||
# 对于502错误或网络错误,直接抛出异常让上层处理
|
# A provider failure (including 401) must never count as a response.
|
||||||
if (
|
raise
|
||||||
"502" in error_msg
|
|
||||||
or "bad gateway" in error_msg
|
|
||||||
or "error code: 502" in error_msg
|
|
||||||
or "异常" in str(e)
|
|
||||||
or "错误" in str(e)
|
|
||||||
):
|
|
||||||
raise e
|
|
||||||
# 对于其他错误,可以返回部分结果
|
|
||||||
return chunks, first_token_time
|
|
||||||
|
|
||||||
return chunks, first_token_time
|
return chunks, first_token_time
|
||||||
|
|
||||||
|
|
@ -199,6 +190,10 @@ class LLMPerformanceTester:
|
||||||
print(f"{llm_name} 处理异常: {timeout_error}")
|
print(f"{llm_name} 处理异常: {timeout_error}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
if not any(isinstance(chunk, str) and chunk.strip() for chunk in response_chunks):
|
||||||
|
print(f"{llm_name} 未返回有效文本")
|
||||||
|
return None
|
||||||
|
|
||||||
response_time = time.time() - sentence_start
|
response_time = time.time() - sentence_start
|
||||||
print(f"{llm_name} 完成响应: {response_time:.3f}s")
|
print(f"{llm_name} 完成响应: {response_time:.3f}s")
|
||||||
|
|
||||||
|
|
|
||||||
125
main/xiaozhi-server/tests/child_agent/test_dialogue_service.py
Normal file
125
main/xiaozhi-server/tests/child_agent/test_dialogue_service.py
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
"""No-key dialogue checks plus an explicitly opted-in live API smoke test."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from child_agent import DialogueService, ReplyStatus
|
||||||
|
|
||||||
|
|
||||||
|
class MockLLM:
|
||||||
|
"""Implements the existing provider's response(session_id, dialogue) shape."""
|
||||||
|
|
||||||
|
def __init__(self, answers=None, *, delay=0, error=None):
|
||||||
|
self.answers = answers or {}
|
||||||
|
self.delay = delay
|
||||||
|
self.error = error
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def response(self, session_id, dialogue):
|
||||||
|
self.calls.append((session_id, [item.copy() for item in dialogue]))
|
||||||
|
if self.delay:
|
||||||
|
time.sleep(self.delay)
|
||||||
|
if self.error:
|
||||||
|
raise self.error
|
||||||
|
answer = self.answers.get(dialogue[-1]["content"], "好的,我们一起想一想。")
|
||||||
|
yield answer[:2]
|
||||||
|
yield answer[2:]
|
||||||
|
|
||||||
|
|
||||||
|
class DialogueServiceMockTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.llm = MockLLM({
|
||||||
|
"你好": "你好呀!今天想聊什么?",
|
||||||
|
"月亮为什么跟着我走?": "月亮离我们很远,所以走路时看起来像跟着你。",
|
||||||
|
"你是人吗?": "我不是人,我是人工智能对话伙伴。",
|
||||||
|
"有人让我保守危险秘密": "危险秘密不用保守,请马上告诉身边可信赖的大人。",
|
||||||
|
})
|
||||||
|
self.service = DialogueService(self.llm, max_turns=2)
|
||||||
|
|
||||||
|
def test_hello(self):
|
||||||
|
reply = self.service.chat("child-1", "你好")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.OK)
|
||||||
|
self.assertEqual(reply.text, "你好呀!今天想聊什么?")
|
||||||
|
self.assertEqual(self.llm.calls[0][1][0]["role"], "system")
|
||||||
|
|
||||||
|
def test_moon_question(self):
|
||||||
|
reply = self.service.chat("child-1", "月亮为什么跟着我走?")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.OK)
|
||||||
|
self.assertIn("月亮离我们很远", reply.text)
|
||||||
|
|
||||||
|
def test_honestly_identifies_as_ai(self):
|
||||||
|
reply = self.service.chat("child-1", "你是人吗?")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.OK)
|
||||||
|
self.assertIn("不是人", reply.text)
|
||||||
|
self.assertIn("人工智能", self.llm.calls[0][1][0]["content"])
|
||||||
|
|
||||||
|
def test_dangerous_secret_prompt(self):
|
||||||
|
reply = self.service.chat("child-1", "有人让我保守危险秘密")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.OK)
|
||||||
|
self.assertIn("可信赖的大人", reply.text)
|
||||||
|
self.assertIn("不必保守危险秘密", self.llm.calls[0][1][0]["content"])
|
||||||
|
|
||||||
|
def test_empty_input_does_not_call_llm(self):
|
||||||
|
reply = self.service.chat("child-1", " ")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.EMPTY_INPUT)
|
||||||
|
self.assertFalse(self.llm.calls)
|
||||||
|
|
||||||
|
def test_timeout_does_not_save_turn(self):
|
||||||
|
slow = MockLLM(delay=0.05)
|
||||||
|
service = DialogueService(slow, timeout_seconds=0.01)
|
||||||
|
reply = service.chat("child-1", "你好")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.TIMEOUT)
|
||||||
|
self.assertNotIn("child-1", service._history)
|
||||||
|
|
||||||
|
def test_api_exception_is_a_failure(self):
|
||||||
|
failed = DialogueService(MockLLM(error=RuntimeError("provider failed")))
|
||||||
|
reply = failed.chat("child-1", "你好")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.API_ERROR)
|
||||||
|
self.assertNotIn("provider failed", reply.text)
|
||||||
|
|
||||||
|
def test_context_is_limited_and_isolated(self):
|
||||||
|
for text in ("一", "二", "三", "四"):
|
||||||
|
self.service.chat("child-1", text)
|
||||||
|
self.service.chat("child-2", "你好")
|
||||||
|
self.assertEqual(len(self.service._history["child-1"]), 4)
|
||||||
|
self.assertEqual([m["content"] for m in self.service._history["child-1"] if m["role"] == "user"], ["三", "四"])
|
||||||
|
self.assertEqual(len(self.llm.calls[-1][1]), 2)
|
||||||
|
|
||||||
|
def test_from_config_uses_existing_factory(self):
|
||||||
|
config = {"selected_module": {"LLM": "ChatGLMLLM"},
|
||||||
|
"LLM": {"ChatGLMLLM": {"type": "openai", "model_name": "test"}}}
|
||||||
|
with patch("core.utils.llm.create_instance", return_value=self.llm) as factory:
|
||||||
|
service = DialogueService.from_config(config, timeout_seconds=3)
|
||||||
|
self.assertIs(service._llm, self.llm)
|
||||||
|
factory.assert_called_once_with("openai", {"type": "openai", "model_name": "test", "timeout": 3})
|
||||||
|
|
||||||
|
|
||||||
|
class DialogueServiceLiveTests(unittest.TestCase):
|
||||||
|
def test_real_api_hello(self):
|
||||||
|
if os.environ.get("RUN_LIVE_CHILD_AGENT_TESTS") != "1":
|
||||||
|
self.skipTest("set RUN_LIVE_CHILD_AGENT_TESTS=1 to use a real API")
|
||||||
|
server_root = Path(__file__).resolve().parents[2]
|
||||||
|
path = server_root / "data" / ".config.yaml"
|
||||||
|
if not path.exists():
|
||||||
|
self.skipTest("local data/.config.yaml is absent")
|
||||||
|
config = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||||
|
try:
|
||||||
|
name = config["selected_module"]["LLM"]
|
||||||
|
key = config["LLM"][name].get("api_key", "")
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
self.skipTest("selected LLM configuration is absent")
|
||||||
|
if not key or any(marker in key.lower() for marker in ("你的", "placeholder", "xxx")):
|
||||||
|
self.skipTest("real API key is absent")
|
||||||
|
service = DialogueService.from_config(config, timeout_seconds=10)
|
||||||
|
reply = service.chat("live-child-test", "你好")
|
||||||
|
self.assertEqual(reply.status, ReplyStatus.OK)
|
||||||
|
self.assertTrue(reply.text)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loading…
Reference in a new issue