mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Compare commits
117 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3219a28039 | ||
|
|
aa524af1d3 | ||
|
|
39d4905137 | ||
|
|
bc4bc661f5 | ||
|
|
a2f949c347 | ||
|
|
ad0e514666 | ||
|
|
74fd778601 | ||
|
|
e6d711e8fe | ||
|
|
d7751f468e | ||
|
|
285d47783c | ||
|
|
01f65ee5c4 | ||
|
|
4e898819dd | ||
|
|
c1906d5dff | ||
|
|
462b288bda | ||
|
|
7c5fe74410 | ||
|
|
cda17f4d6a | ||
|
|
4ae96c6e02 | ||
|
|
a1919f7db3 | ||
|
|
5b0c8c303b | ||
|
|
9100e7ecd2 | ||
|
|
4c04b9dd37 | ||
|
|
f441703e6c | ||
|
|
61a8c04477 | ||
|
|
b545623b38 | ||
|
|
63e2bcec8a | ||
|
|
c74a6aaa68 | ||
|
|
0d7180d898 | ||
|
|
2dfaf44269 | ||
|
|
e41bc98a25 | ||
|
|
4b1a54a41c | ||
|
|
579538478b | ||
|
|
4f6e9ec6b1 | ||
|
|
dd367c9e43 | ||
|
|
b4e144afef | ||
|
|
9f5f520576 | ||
|
|
70f1a7bfd8 | ||
|
|
e61f5aee28 | ||
|
|
c59b29c723 | ||
|
|
c8e60d1325 | ||
|
|
6589f7f481 | ||
|
|
7d9f47b0d1 | ||
|
|
5b0de039c9 | ||
|
|
398f0bd097 | ||
|
|
4e1405a6f6 | ||
|
|
e09df59c13 | ||
|
|
f9138e65b7 | ||
|
|
9b8a9b585d | ||
|
|
7f0d416e66 | ||
|
|
c282397cd2 | ||
|
|
7e450fca0d | ||
|
|
92337881a7 | ||
|
|
a93b71f9e7 | ||
|
|
325f52469a | ||
|
|
3230a69c99 | ||
|
|
1ac4c09946 | ||
|
|
42f7e55c72 | ||
|
|
5f6e191d11 | ||
|
|
27833f918c | ||
|
|
1a095d5bed | ||
|
|
01289b8fd4 | ||
|
|
ef2fcdbcb1 | ||
|
|
942ac2fe12 | ||
|
|
4dbed0ab1d | ||
|
|
15d9b0fba1 | ||
|
|
8c5330f742 | ||
|
|
549261fdff | ||
|
|
2cb0562ade | ||
|
|
3bf619e2dd | ||
|
|
ccc77799d9 | ||
|
|
d9c2e8c5d9 | ||
|
|
1a675e4d6b | ||
|
|
40a7ed0391 | ||
|
|
62e316f298 | ||
|
|
76cef92cb2 | ||
|
|
826c25d3e5 | ||
|
|
f1965167cc | ||
|
|
6c352e5978 | ||
|
|
032f6f1582 | ||
|
|
a377d89dcd | ||
|
|
d35b9f8b00 | ||
|
|
d687121e99 | ||
|
|
badf6fe3d0 | ||
|
|
adb4a15f2d | ||
|
|
a5f9a782d6 | ||
|
|
7ab4cc5c90 | ||
|
|
9c4790c8d0 | ||
|
|
4fd51c6f7f | ||
|
|
e7e0a886bf | ||
|
|
3ff080bb0d | ||
|
|
ca8ff121d4 | ||
|
|
9f63b255fb | ||
|
|
9d34360a2c | ||
|
|
2f18e2ee0a | ||
|
|
fd05dd5159 | ||
|
|
82d2acc78c | ||
|
|
77be288c8e | ||
|
|
ba22f5b765 | ||
|
|
0492dc5924 | ||
|
|
ffd4ab74d7 | ||
|
|
f0ebebfa85 | ||
|
|
61136b958b | ||
|
|
ee726f49e6 | ||
|
|
05f0da0639 | ||
|
|
af1982c424 | ||
|
|
1120be2f60 | ||
|
|
9880ce998f | ||
|
|
9bd668aebc | ||
|
|
d027432432 | ||
|
|
3972df6e4e | ||
|
|
855a64cbb9 | ||
|
|
37d4330224 | ||
|
|
7873984f9f | ||
|
|
4ed3197a6f | ||
|
|
4dd194ef8b | ||
|
|
8c41faac8b | ||
|
|
597ab5f415 | ||
|
|
4f1cb98503 |
111 changed files with 4314 additions and 728 deletions
57
.github/workflows/test.yml
vendored
57
.github/workflows/test.yml
vendored
|
|
@ -20,24 +20,58 @@ jobs:
|
|||
python-version: '3.10'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'main/xiaozhi-server/requirements.txt'
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# opuslib_next 是 ctypes 绑定,pip 装上的是纯 Python 包,真正的编解码
|
||||
# 靠系统里的 libopus.so。runner 上默认没有,import 会失败,音频相关的
|
||||
# 用例直接报错。正式镜像 Dockerfile-server-base 里也是装 libopus0 的
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends libopus0
|
||||
- name: Install dependencies
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
pip install -r requirements.txt
|
||||
pip install pytest pytest-asyncio freezegun
|
||||
- name: Run smoke test
|
||||
- name: Prepare test config
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
if [ -f tests/test_smoke.py ]; then
|
||||
pytest tests/test_smoke.py -x -q
|
||||
else
|
||||
echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing"
|
||||
exit 0
|
||||
fi
|
||||
# config/settings.py 在 import 期就要这个文件,缺了整套用例连收集都过不去。
|
||||
# data/ 在 .gitignore 里,只能由这一步现造
|
||||
mkdir -p data
|
||||
printf '{}\n' > data/.config.yaml
|
||||
- name: Run tests
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
# Edge TTS 那条要连微软公网,runner 的出口 IP 会被风控挡掉,先排除。
|
||||
# 根治办法是给它打 live 标记,让 mock 模式下自动不收(另开一条改)
|
||||
pytest tests/ -v -k "not test_tts_text_to_speak_writes_file"
|
||||
|
||||
java:
|
||||
name: Java (manager-api)
|
||||
runs-on: ubuntu-latest
|
||||
# 三个 @SpringBootTest 要真连 MySQL 和 Redis,空库即可,Liquibase 会自己建表
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
env:
|
||||
MYSQL_ROOT_PASSWORD: 123456
|
||||
MYSQL_DATABASE: xiaozhi_esp32_server
|
||||
ports:
|
||||
- 3306:3306
|
||||
options: >-
|
||||
--health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -p123456"
|
||||
--health-interval=10s
|
||||
--health-timeout=5s
|
||||
--health-retries=20
|
||||
redis:
|
||||
image: redis:8.0
|
||||
ports:
|
||||
- 6379:6379
|
||||
options: >-
|
||||
--health-cmd="redis-cli ping"
|
||||
--health-interval=10s
|
||||
--health-timeout=5s
|
||||
--health-retries=20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
|
|
@ -47,7 +81,12 @@ jobs:
|
|||
cache: 'maven'
|
||||
- name: Run tests
|
||||
working-directory: main/manager-api
|
||||
run: mvn -B -q test -DfailIfNoTests=false
|
||||
run: mvn -B test -DskipTests=false -DfailIfNoTests=false
|
||||
- name: Check the integration tests really ran
|
||||
working-directory: main/manager-api
|
||||
# 守卫在依赖不齐时会把整类集成测试跳过,这里盯一下它们有没有真跑,
|
||||
# 免得门禁被悄悄掏空
|
||||
run: bash scripts/check-integration-tests.sh
|
||||
|
||||
web:
|
||||
name: Vue (manager-web)
|
||||
|
|
@ -63,4 +102,6 @@ jobs:
|
|||
working-directory: main/manager-web
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm run test:contract
|
||||
npm run test:unit
|
||||
npm run build
|
||||
|
|
|
|||
42
README.md
42
README.md
|
|
@ -22,6 +22,7 @@
|
|||
<a href="./docs/readme/README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||
<a href="./docs/readme/README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||
<a href="./docs/readme/README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||
<a href="./docs/readme/README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
|
|
@ -169,12 +170,12 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
|
|||
#### 🚀 部署方式选择
|
||||
| 部署方式 | 特点 | 适用场景 | 部署文档 | 配置要求 | 视频教程 |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 如果使用`FunASR`要2核4G,如果全API,要2核2G | - |
|
||||
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 如果使用`FunASR`要4核8G,如果全API,要2核4G| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 本地跑 `FunASR` 较耗内存,全部走 API 时资源占用低 | - |
|
||||
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 本地跑 `FunASR` 较耗内存,另需数据库资源,全部走 API 时资源占用低| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
|
||||
|
||||
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据,
|
||||
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据。
|
||||
|
||||
```
|
||||
智控台地址: https://2662r3426b.vicp.fun
|
||||
|
|
@ -202,7 +203,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
| VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) |
|
||||
| TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) |
|
||||
| Intent(意图识别) | function_call(函数调用) | function_call(函数调用) |
|
||||
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) |
|
||||
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) |
|
||||
|
||||
如果您关心各组件的耗时,请查阅[小智各组件性能测试报告](https://github.com/xinnan-tech/xiaozhi-performance-research),可按报告中的测试方法在您的环境中实际测试。
|
||||
|
||||
|
|
@ -211,8 +212,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 执行 `python start.py` 后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
|
||||
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 |
|
||||
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 按其 README 装好依赖后执行 `python start.py`,然后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
|
||||
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)等核心模块的响应速度 |
|
||||
|
||||
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
|
||||
|
||||
|
|
@ -230,12 +231,12 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
|
||||
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 |
|
||||
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
|
||||
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
||||
| 工具调用 | 支持客户端IOT协议、客户端MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
||||
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
|
||||
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 |
|
||||
| 测试工具 | 提供性能测试工具、视觉模型测试工具和音频交互测试工具 |
|
||||
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文、德语、越南语、巴西葡萄牙语显示 |
|
||||
| 测试工具 | 提供模型响应性能测试工具和音频交互测试工具 |
|
||||
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 |
|
||||
| 插件系统 | 支持功能插件扩展、自定义插件开发和插件热加载 |
|
||||
| 插件系统 | 支持功能插件扩展、自定义插件开发;新增插件文件在下次设备连接时自动加载,改动已加载插件的代码需重启服务 |
|
||||
|
||||
### 正在开发 🚧
|
||||
|
||||
|
|
@ -255,7 +256,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 使用方式 | 支持平台 | 免费平台 |
|
||||
|:---:|:---:|:---:|
|
||||
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini |
|
||||
| OpenAI 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞、LM Studio | 智谱、Gemini |
|
||||
| ollama 接口调用 | Ollama | - |
|
||||
| dify 接口调用 | Dify | - |
|
||||
| fastgpt 接口调用 | Fastgpt | - |
|
||||
|
|
@ -263,7 +264,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
| xinference 接口调用 | Xinference | - |
|
||||
| homeassistant 接口调用 | HomeAssistant | - |
|
||||
|
||||
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
|
||||
实际上,任何支持 OpenAI 接口调用的 LLM 均可接入使用。
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -271,9 +272,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 使用方式 | 支持平台 | 免费平台 |
|
||||
|:---:|:---:|:---:|
|
||||
| openai 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM |
|
||||
| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM、科大讯飞 | 智谱ChatGLMVLLM |
|
||||
|
||||
实际上,任何支持 openai 接口调用的 VLLM 均可接入使用。
|
||||
实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -281,8 +282,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 使用方式 | 支持平台 | 免费平台 |
|
||||
|:---:|:---:|:---:|
|
||||
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) |
|
||||
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、Index-TTS、PaddleSpeech | Index-TTS、PaddleSpeech、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
|
||||
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、CustomTTS、OpenAITTS、MinimaxTTS | EdgeTTS、CosyVoiceSiliconflow(部分) |
|
||||
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、IndexStreamTTS、PaddleSpeechTTS | IndexStreamTTS、PaddleSpeechTTS、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -298,8 +299,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 使用方式 | 支持平台 | 免费平台 |
|
||||
|:---:|:---:|:---:|
|
||||
| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR |
|
||||
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer |
|
||||
| 本地使用 | FunASR、SherpaASR、SherpaParaformerASR、VoskASR | FunASR、SherpaASR、SherpaParaformerASR、VoskASR |
|
||||
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云及百炼、百度云、OpenAI ASR、GroqASR、Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -307,7 +308,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
|
||||
| 使用方式 | 支持平台 | 免费平台 |
|
||||
|:---:|:---:|:---:|
|
||||
| 本地使用 | 3D-Speaker | 3D-Speaker |
|
||||
| 接口调用 | 声纹识别服务(voiceprint-api) | - |
|
||||
|
||||
声纹识别需要单独部署 [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) 服务(基于 3D-Speaker),并依赖 MySQL,详见[声纹识别启用指南](./docs/voiceprint-integration.md)
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -319,6 +322,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
|
||||
| Memory | mem_local_short | 本地总结 | 免费 | |
|
||||
| Memory | nomem | 无记忆模式 | 免费 | |
|
||||
| Memory | mem_report_only | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||

|
||||
# 方式一:Docker只运行Server
|
||||
|
||||
`0.8.2`版本开始,本项目发行的docker镜像只支持`x86架构`,如果需要在`arm64架构`的CPU上部署,可按照[这个教程](docker-build.md)在本机编译`arm64的镜像`。
|
||||
本项目发行的docker镜像同时提供`amd64`和`arm64`两种架构,可以直接拉取使用;如需自定义镜像,可按照[这个教程](docker-build.md)在本机编译。
|
||||
|
||||
## 1. 安装docker
|
||||
|
||||
|
|
@ -36,9 +36,9 @@ xiaozhi-server
|
|||
|
||||
#### 1.1.3 下载配置文件
|
||||
|
||||
你需要下载两个配置文件:`docker-compose.yaml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
|
||||
你需要下载两个配置文件:`docker-compose.yml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
|
||||
|
||||
##### 1.1.3.1 下载 docker-compose.yaml
|
||||
##### 1.1.3.1 下载 docker-compose.yml
|
||||
|
||||
用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。
|
||||
|
||||
|
|
@ -91,25 +91,22 @@ docker logs -f xiaozhi-esp32-server
|
|||
|
||||
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
|
||||
|
||||
## 5. 版本升级操作
|
||||
## 4. 版本升级操作
|
||||
|
||||
如果后期想升级版本,可以这么操作
|
||||
|
||||
5.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
|
||||
4.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
|
||||
请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。
|
||||
|
||||
5.2、执行以下命令
|
||||
4.2、执行以下命令
|
||||
|
||||
```
|
||||
docker stop xiaozhi-esp32-server
|
||||
docker rm xiaozhi-esp32-server
|
||||
docker stop xiaozhi-esp32-server-web
|
||||
docker rm xiaozhi-esp32-server-web
|
||||
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest
|
||||
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
|
||||
```
|
||||
|
||||
5.3、重新按docker方式部署
|
||||
4.3、重新按docker方式部署
|
||||
|
||||
# 方式二:本地源码只运行Server
|
||||
|
||||
|
|
@ -213,14 +210,14 @@ prompt: |
|
|||
请你像一个人一样说话,请勿返回配置xml及其他特殊字符。
|
||||
|
||||
selected_module:
|
||||
LLM: DoubaoLLM
|
||||
LLM: ChatGLMLLM
|
||||
|
||||
LLM:
|
||||
ChatGLMLLM:
|
||||
api_key: xxxxxxxxxxxxxxx.xxxxxx
|
||||
```
|
||||
|
||||
建议先将最简单的配置运行起来,然后再去`xiaozhi/config.yaml`阅读配置的使用说明。
|
||||
建议先将最简单的配置运行起来,然后再去[`../main/xiaozhi-server/config.yaml`](../main/xiaozhi-server/config.yaml)阅读配置的使用说明。
|
||||
比如你要换更换模型,修改`selected_module`下的配置就行。
|
||||
|
||||
## 模型文件
|
||||
|
|
@ -238,11 +235,12 @@ LLM:
|
|||
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
||||
|
||||
```
|
||||
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
|
||||
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
|
||||
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
|
||||
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
|
||||
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======================================================
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-视觉分析接口是 http://192.168.4.123:8003/mcp/vision/explain
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
|
||||
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-=============================================================
|
||||
```
|
||||
|
||||
正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。
|
||||
|
|
|
|||
|
|
@ -144,5 +144,7 @@
|
|||
### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办?
|
||||
- 可以查阅你使用的asr服务的文档,确认是否支持热词识别。
|
||||
- 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。
|
||||
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置页面`,把`热词文件名称`配置在`火山引擎的tts`上去。
|
||||
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置`页面,在`语音识别`里找到模型名称为`豆包语音识别(流式)`的那一条,点`修改`,弹窗里的`供应器`是`火山引擎语音识别(流式)`,在弹窗的`调用信息`区域把`热词文件名称`填到对应的输入框,点`确认保存`。
|
||||
- `豆包语音识别2.0(流式)`(供应器是`火山引擎语音识别(流式)`)和`豆包语音识别`(供应器是`火山引擎语音识别`)这两条也都有`热词文件名称`这个字段,用法一样,配置时注意别选错行。
|
||||
- 改完要让设备重新连接才会生效:设备连上时才会把最新的私有配置拉下来,一直连着的设备不会自动变。
|
||||
|
||||
|
|
|
|||
|
|
@ -50,10 +50,11 @@ paddlespeech tts --input "你好,这是一次测试"
|
|||
|
||||
### 7.修改tts_online_application.yaml配置
|
||||
参考目录 ```"PaddleSpeech\demos\streaming_tts_server\conf\tts_online_application.yaml"```
|
||||
Linux / WSL 2 用正斜杠写法:```"PaddleSpeech/demos/streaming_tts_server/conf/tts_online_application.yaml"```
|
||||
选择```tts_online_application.yaml```文件用编辑器打开,设置```protocol```为```websocket```
|
||||
|
||||
### 8.启动服务
|
||||
```yaml
|
||||
```bash
|
||||
paddlespeech_server start --config_file ./demos/streaming_tts_server/conf/tts_online_application.yaml
|
||||
#官方默认启动命令:
|
||||
paddlespeech_server start --config_file ./conf/tts_online_application.yaml
|
||||
|
|
@ -68,10 +69,19 @@ INFO: Application startup complete.
|
|||
INFO: Uvicorn running on http://0.0.0.0:8092 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
## 三、修改小智的配置文件
|
||||
### 1.```main/xiaozhi-server/core/providers/tts/paddle_speech.py```
|
||||
## 三、配置小智服务
|
||||
### 1. 无需修改代码(provider 已内置于 main/xiaozhi-server/core/providers/tts/paddle_speech.py)
|
||||
|
||||
### 2.新建 `main/xiaozhi-server/data/.config.yaml`
|
||||
|
||||
`main/xiaozhi-server/data/` 目录不在仓库里,是被 `.gitignore` 忽略掉的,所以第一次用要先把它建出来,再在里面新建 `.config.yaml` 文件(在仓库根目录执行,上面的 `cd PaddleSpeech` 之后当前目录还停在 PaddleSpeech 源码目录里):
|
||||
|
||||
```bash
|
||||
mkdir -p main/xiaozhi-server/data
|
||||
```
|
||||
|
||||
这个文件是必需的,少了它小智服务起不来,会直接报错退出。
|
||||
|
||||
### 2.```main/xiaozhi-server/data/.config.yaml```
|
||||
使用单模块部署
|
||||
```yaml
|
||||
selected_module:
|
||||
|
|
@ -79,19 +89,41 @@ selected_module:
|
|||
TTS:
|
||||
PaddleSpeechTTS:
|
||||
type: paddle_speech
|
||||
protocol: websocket
|
||||
protocol: websocket # 当前仅支持 websocket
|
||||
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming]
|
||||
spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
|
||||
sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择]
|
||||
speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
|
||||
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
|
||||
save_path: # 保存路径
|
||||
```
|
||||
采样率固定 24000,provider 内部写死,配置里不用写这一项。
|
||||
|
||||
### 3.启动xiaozhi服务
|
||||
```py
|
||||
|
||||
小智服务用**另一个** Python 环境,不要用前面给 PaddleSpeech 建的 `paddle_env` —— 那个环境里装的是 PaddleSpeech 自己那套依赖,版本由它决定,跟本项目锁定的版本不一定一致(`paddlespeech` 对 numpy 没写版本上限,装进去的 numpy 未必是本项目要的那个)。本项目推荐的 Python 版本和依赖版本写在 `main/xiaozhi-server/requirements.txt` 里(文件开头写着推荐 python3.10,另外锁了 torch 2.2.2、numpy 1.26.4)。
|
||||
|
||||
先建环境、装依赖(在仓库根目录执行):
|
||||
```bash
|
||||
conda create -n xiaozhi-esp32-server python=3.10 -y
|
||||
conda activate xiaozhi-esp32-server
|
||||
cd main/xiaozhi-server
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
然后在 `main/xiaozhi-server` 目录下启动(目录不能换:provider 是按相对路径 `core/providers/tts/` 找的,见 `core/utils/tts.py:35`):
|
||||
```bash
|
||||
# 上一段已经 cd 到 main/xiaozhi-server 了,这段不用再 cd
|
||||
# 如果是另开的新终端,先 cd main/xiaozhi-server 再执行
|
||||
python app.py
|
||||
```
|
||||
启动`main/digital-human`下的`python start.py`后,打开`http://127.0.0.1:8006/index.html`,测试连接和发送消息时paddlespeech端是否有输出日志
|
||||
|
||||
要验证语音合成的实际输出,另开一个终端,在仓库根目录下跑数字人页面(这套代码另有一份依赖清单,在 `main/digital-human/wakeword_runtime/requirements.txt` 里,缺了会报缺包;唤醒词那部分还要 numpy —— `core/detector.py:7` 和 `core/microphone.py:4` 在模块顶层就 import numpy,用上面建的 `xiaozhi-esp32-server` 跑的话 numpy 已经在里面,不会有这个问题):
|
||||
```bash
|
||||
cd main/digital-human
|
||||
python start.py
|
||||
```
|
||||
|
||||
打开`http://127.0.0.1:8006/index.html`,测试连接和发送消息时paddlespeech端是否有输出日志
|
||||
|
||||
输出日志参考:
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1,8 +1,15 @@
|
|||
# 语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
|
||||
# 语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
|
||||
|
||||
0.先装依赖(在仓库根目录执行)
|
||||
```
|
||||
cd main/xiaozhi-server
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
测试脚本要 import `yaml`、`aiohttp`、`tabulate`,少一个都起不来。`tabulate` 不在 requirements.txt 里,是 `edge-tts` 间接带进来的。
|
||||
|
||||
1.在main/xiaozhi-server目录下创建data目录
|
||||
2.在data目录下创建.config.yaml文件
|
||||
3.在.data/config.yaml中,写入你的语音识别、大语言模型、流式语音合成、视觉模型的参数
|
||||
3.在data/.config.yaml中,写入你的语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的参数
|
||||
例如:
|
||||
```
|
||||
LLM:
|
||||
|
|
@ -16,12 +23,50 @@ LLM:
|
|||
api_key: 你的chat-glm web key
|
||||
|
||||
TTS:
|
||||
EdgeTTS:
|
||||
# 定义TTS API类型
|
||||
type: edge
|
||||
voice: zh-CN-XiaoxiaoNeural
|
||||
|
||||
VLLM:
|
||||
ChatGLMVLLM:
|
||||
# 定义视觉模型API类型
|
||||
type: openai
|
||||
# glm-4v-flash 是智谱的视觉模型,需要在智谱平台申请api_key
|
||||
model_name: glm-4v-flash
|
||||
url: https://open.bigmodel.cn/api/paas/v4/
|
||||
api_key: 你的api_key
|
||||
|
||||
ASR:
|
||||
FunASR:
|
||||
type: fun_local
|
||||
model_dir: models/SenseVoiceSmall
|
||||
language: auto
|
||||
```
|
||||
4.在main/xiaozhi-server目录下运行performance_tester.py:
|
||||
```
|
||||
python performance_tester.py
|
||||
```
|
||||
```
|
||||
|
||||
## 几点说明
|
||||
|
||||
- 脚本第一行提示的 `docs/performance_tester.md` 就是本文档,它在仓库根目录的 `docs/` 下;脚本本身在 `main/xiaozhi-server/` 目录里跑,两处不是一个目录。
|
||||
- LLM、VLLM、非流式语音合成这三项会把 `config.yaml` 和 `data/.config.yaml` 两份配置合并起来再遍历,所以实际会测**所有配好 api_key 的供应器**,不只是你在 `.config.yaml` 里写的那一个;api_key 还是占位符的会被跳过。
|
||||
- 非流式的语音识别这一项读配置的方式和别的不一样:它自己扫 `data/` 目录下的 `*.config.yaml`,只取其中的 `ASR` 段,**不会**用 `config.yaml` 里的默认值。想测语音识别,就得把供应器写进 `data/.config.yaml`。
|
||||
- 流式语音识别读的是合并后的配置,固定测 `DoubaoStreamASR`、`Qwen3ASRFlash`、`XunfeiStreamASR` 这三家。`config.yaml` 里这三项带的 key 是占位符,要在 `data/.config.yaml` 的 `ASR` 段里填上自己的 key 才会测出延迟。
|
||||
- 视觉模型的配置写在 `data/.config.yaml` 的 `VLLM:` 段里,这段**不能只写一个空键**:写空的话合并后整段是空的,这项测试会直接跳过、什么都不测。
|
||||
- 流式语音合成一次会跑这些供应器:
|
||||
|
||||
| 供应器 | 说明 |
|
||||
|---|---|
|
||||
| `AliyunStreamTTS` | 阿里云流式 TTS,无条件调用 |
|
||||
| `HuoshanDoubleStreamTTS` | 火山引擎流式 TTS,无条件调用 |
|
||||
| `PaddleSpeechTTS` | PaddleSpeech 流式 TTS,无条件调用 |
|
||||
| `IndexStreamTTS` | IndexStream 流式 TTS,无条件调用 |
|
||||
| `LinkeraiTTS` | `config.yaml` 的 TTS 段里没有这个供应器,默认不测、整项跳过;要测得自己在 `.config.yaml` 里补上 |
|
||||
| `AliBLTTS` | 阿里百炼流式 TTS,默认就会测:判断读的是合并后的配置,`config.yaml` 里本来就带着这一项 |
|
||||
| `XunFeiTTS` | 讯飞流式 TTS,同上,默认就会测 |
|
||||
|
||||
`AliBLTTS` 和 `XunFeiTTS` 这两项默认带的 key 是占位符,不在 `.config.yaml` 里换成自己的 key 就会报失败;想直接跳过,把这两项在 `.config.yaml` 里写成空的(键名下面不填内容)就行。
|
||||
|
||||
标了「无条件调用」的这几个(`AliyunStreamTTS`、`HuoshanDoubleStreamTTS`、`PaddleSpeechTTS`、`IndexStreamTTS`),供应器缺失或被清空时,那一项会报错,错误被测试方法内部的异常处理吃掉,这一项被记成失败 —— 结果表里会多出一行失败记录,但不影响其它项。带守卫的那几家(`AliBLTTS`、`XunFeiTTS`、`LinkeraiTTS`)是整项跳过:没配就不报错、结果表里也不会有这一行。
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme<br/>und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
|
||||
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||
Implementiert mit Python, Java und Vue gemäß dem <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi-Kommunikationsprotokoll</a><br/>
|
||||
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
|
||||
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Zugriffspunkte, Stimmabdruckerkennung und Wissensdatenbank
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -22,6 +22,7 @@ Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabd
|
|||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
|
||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
|
|
@ -54,31 +55,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||
<picture>
|
||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
||||
<img alt="Das Gefühl der Reaktionsgeschwindigkeit" src="../images/demo9.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||
<picture>
|
||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
||||
<img alt="Das Geheimnis der Geschwindigkeitsoptimierung" src="../images/demo6.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||
<picture>
|
||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
||||
<img alt="Xiaozhi-Digitalmensch mit Sprachaktivierung" src="../images/demo8.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||
<picture>
|
||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
||||
<img alt="Anruf von Gerät zu Gerät" src="../images/demo0.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||
<picture>
|
||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
||||
<img alt="Komplexes medizinisches Szenario" src="../images/demo1.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -86,31 +87,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||
<picture>
|
||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
||||
<img alt="Musik abspielen, Wetter abfragen und Nachrichten vorlesen" src="../images/demo7.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||
<picture>
|
||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
||||
<img alt="Unterbrechung in Echtzeit" src="../images/demo10.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||
<picture>
|
||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
||||
<img alt="Objekte per Foto erkennen" src="../images/demo12.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||
<picture>
|
||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
||||
<img alt="Haushaltsgeräte ein- und ausschalten" src="../images/demo5.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||
<picture>
|
||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
||||
<img alt="Aufgaben mit mehreren Befehlen" src="../images/demo11.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -118,31 +119,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||
<picture>
|
||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
||||
<img alt="MCP-Zugriffspunkt" src="../images/demo13.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||
<picture>
|
||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
||||
<img alt="MQTT-Befehlsübermittlung" src="../images/demo4.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||
<picture>
|
||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
||||
<img alt="Stimmabdruckerkennung" src="../images/demo14.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||
<picture>
|
||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
||||
<img alt="Eigene Stimmfarbe" src="../images/demo2.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||
<picture>
|
||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
||||
<img alt="Gespräch auf Kantonesisch" src="../images/demo3.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -167,8 +168,8 @@ Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend
|
|||
#### 🚀 Auswahl der Bereitstellungsmethode
|
||||
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 Kerne 4GB bei Verwendung von `FunASR`, 2 Kerne 2GB bei allen APIs | - |
|
||||
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | 4 Kerne 8GB bei Verwendung von `FunASR`, 2 Kerne 4GB bei allen APIs| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Lokales `FunASR` benötigt mehr Arbeitsspeicher; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering | - |
|
||||
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | Lokales `FunASR` benötigt mehr Arbeitsspeicher, zusätzlich werden Datenbankressourcen benötigt; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md)
|
||||
|
||||
|
|
@ -209,15 +210,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
|
|||
|
||||
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` `python start.py` ausführen und dann `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
|
||||
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) drei Kernmodulen |
|
||||
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` zuerst die Abhängigkeiten wie in der README installieren, dann `python start.py` ausführen und `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
|
||||
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von Kernmodulen wie ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) |
|
||||
|
||||
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
|
||||
|
||||
---
|
||||
## Funktionsliste ✨
|
||||
### Implementiert ✅
|
||||

|
||||

|
||||
| Funktionsmodul | Beschreibung |
|
||||
|:---:|:---|
|
||||
| Kernarchitektur | Basierend auf [MQTT+UDP-Gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket und HTTP-Servern, bietet vollständiges Konsolenverwaltungs- und Authentifizierungssystem |
|
||||
|
|
@ -225,15 +226,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
|
|||
| Stimmabdruckerkennung | Unterstützt Mehrbenutzer-Stimmabdruckregistrierung, -verwaltung und -erkennung, verarbeitet parallel mit ASR, Echtzeit-Sprecheridentitätserkennung und Weitergabe an LLM für personalisierte Antworten |
|
||||
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
|
||||
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
|
||||
| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
||||
| Absichtserkennung | Unterstützt externe LLM-Absichtserkennung, autonome Funktionsaufrufe durch große Modelle, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
||||
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion |
|
||||
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
|
||||
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
||||
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Zugriffspunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
||||
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
|
||||
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch und englische Anzeige |
|
||||
| Testwerkzeuge | Bietet Leistungstestwerkzeuge, Vision-Modell-Testwerkzeuge und Audio-Interaktionstestwerkzeuge |
|
||||
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch, Englisch, Deutsch, Vietnamesisch und brasilianisches Portugiesisch an |
|
||||
| Testwerkzeuge | Bietet Leistungstestwerkzeuge für Modellantworten und Audio-Interaktionstestwerkzeuge |
|
||||
| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
|
||||
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen, benutzerdefinierte Plugin-Entwicklung und Plugin-Hot-Loading |
|
||||
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen und benutzerdefinierte Plugin-Entwicklung; neu hinzugefügte Plugin-Dateien werden bei der nächsten Geräteverbindung geladen, Änderungen an bereits geladenen Plugins erfordern einen Neustart des Dienstes |
|
||||
|
||||
### In Entwicklung 🚧
|
||||
|
||||
|
|
@ -253,7 +254,7 @@ Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich
|
|||
|
||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||
|:---:|:---:|:---:|
|
||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
|
||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, Volcano Engine AI Gateway, DeepSeek, Zhipu ChatGLM, Gemini, iFLYTEK, LM Studio | Zhipu ChatGLM, Gemini |
|
||||
| Ollama-Schnittstellenaufrufe | Ollama | - |
|
||||
| Dify-Schnittstellenaufrufe | Dify | - |
|
||||
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
|
||||
|
|
@ -269,7 +270,7 @@ Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, inte
|
|||
|
||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||
|:---:|:---:|:---:|
|
||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||
|
||||
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
|
||||
|
||||
|
|
@ -279,8 +280,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||
|
||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||
|:---:|:---:|:---:|
|
||||
| Schnittstellenaufrufe | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS, Volcano Dual-Stream TTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow (teilweise) |
|
||||
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
| Schnittstellenaufrufe | EdgeTTS, iFLYTEK, Volcano Engine Doubao TTS, Volcano Engine AI Gateway TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, Alibaba Bailian CosyVoice TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS, Volcano Dual-Stream TTS | EdgeTTS, CosyVoiceSiliconflow (teilweise) |
|
||||
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -296,8 +297,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||
|
||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||
|:---:|:---:|:---:|
|
||||
| Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
|
||||
| Lokale Verwendung | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, Doubao Streaming ASR V2, FunASRServer, iFLYTEK, TencentASR, AliyunASR, Aliyun Streaming ASR, Alibaba Bailian Streaming ASR, Baidu ASR, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -305,7 +306,9 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||
|
||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||
|:---:|:---:|:---:|
|
||||
| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
|
||||
| Schnittstellenaufrufe | Voiceprint-Dienst (voiceprint-api) | - |
|
||||
|
||||
Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)-Dienst (auf Basis von 3D-Speaker) sowie MySQL. Siehe [Anleitung zur Stimmabdruckerkennung](../voiceprint-integration.md).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -317,6 +320,7 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||
| Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage |
|
||||
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
|
||||
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
|
||||
| Memory | mem_report_only | Nur Meldung | Kostenlos | Meldet nur Chat-Verläufe, keine Gedächtniszusammenfassung |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -351,11 +355,10 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||
| <img src="../images/logo_contributors.png" width="160"> | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
|
||||
|
||||
|
||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||
|
||||
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
</picture>
|
||||
</a>
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint
|
|||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
|
|
@ -54,31 +55,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||
<picture>
|
||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
||||
<img alt="The feel of the response speed" src="../images/demo9.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||
<picture>
|
||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
||||
<img alt="The secret to speeding things up" src="../images/demo6.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||
<picture>
|
||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
||||
<img alt="Xiaozhi digital human with voice wake-up" src="../images/demo8.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||
<picture>
|
||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
||||
<img alt="Device-to-device calling" src="../images/demo0.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||
<picture>
|
||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
||||
<img alt="A complex medical scenario" src="../images/demo1.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -86,31 +87,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||
<picture>
|
||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
||||
<img alt="Play music, check the weather, and read the news" src="../images/demo7.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||
<picture>
|
||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
||||
<img alt="Real-time interruption" src="../images/demo10.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||
<picture>
|
||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
||||
<img alt="Take a photo to identify objects" src="../images/demo12.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||
<picture>
|
||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
||||
<img alt="Turn home appliances on and off" src="../images/demo5.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||
<picture>
|
||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
||||
<img alt="Multi-command tasks" src="../images/demo11.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -118,31 +119,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||
<picture>
|
||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
||||
<img alt="MCP access point" src="../images/demo13.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||
<picture>
|
||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
||||
<img alt="MQTT command delivery" src="../images/demo4.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||
<picture>
|
||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
||||
<img alt="Voiceprint recognition" src="../images/demo14.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||
<picture>
|
||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
||||
<img alt="Custom voice timbre" src="../images/demo2.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||
<picture>
|
||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
||||
<img alt="Talking in Cantonese" src="../images/demo3.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -167,8 +168,8 @@ This project provides two deployment methods. Please choose based on your specif
|
|||
#### 🚀 Deployment Method Selection
|
||||
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 cores 4GB if using `FunASR`, 2 cores 2GB if all APIs | - |
|
||||
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | 4 cores 8GB if using `FunASR`, 2 cores 4GB if all APIs| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Local `FunASR` needs more memory; using APIs for everything keeps resource usage low | - |
|
||||
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | Local `FunASR` needs more memory plus database resources; using APIs for everything keeps resource usage low| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md)
|
||||
|
||||
|
|
@ -209,15 +210,15 @@ This project provides the following testing tools to help you verify the system
|
|||
|
||||
| Tool Name | Location | Usage Method | Function Description |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| Audio Interaction Test Tool | main》digital-human》index.html | Run `python start.py` in `main/digital-human`, then open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
||||
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
|
||||
| Audio Interaction Test Tool | main》digital-human》index.html | In `main/digital-human`, install dependencies as its README says, then run `python start.py` and open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
||||
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of core modules such as ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
|
||||
|
||||
> 💡 Note: When testing model speed, only models with configured keys will be tested.
|
||||
|
||||
---
|
||||
## Feature List ✨
|
||||
### Implemented ✅
|
||||

|
||||

|
||||
| Feature Module | Description |
|
||||
|:---:|:---|
|
||||
| Core Architecture | Based on [MQTT+UDP gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket and HTTP servers, provides complete console management and authentication system |
|
||||
|
|
@ -225,15 +226,15 @@ This project provides the following testing tools to help you verify the system
|
|||
| Voiceprint Recognition | Supports multi-user voiceprint registration, management, and recognition, processes in parallel with ASR, real-time speaker identity recognition and passes to LLM for personalized responses |
|
||||
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
|
||||
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
|
||||
| Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
|
||||
| Intent Recognition | Supports pluggable external LLM intent recognition and autonomous LLM function calling, provides plugin-based intent processing mechanism |
|
||||
| Memory System | Supports local short-term memory, mem0ai interface memory, PowerMem intelligent memory, with memory summarization functionality |
|
||||
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
|
||||
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
|
||||
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP access point protocol, custom tool functions |
|
||||
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
|
||||
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
|
||||
| Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
|
||||
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese, English, German, Vietnamese and Brazilian Portuguese display |
|
||||
| Testing Tools | Provides model response performance testing tools and audio interaction testing tools |
|
||||
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
|
||||
| Plugin System | Supports functional plugin extensions, custom plugin development, and plugin hot-loading |
|
||||
| Plugin System | Supports functional plugin extensions and custom plugin development; newly added plugin files are loaded on the next device connection, code changes to already loaded plugins require a service restart |
|
||||
|
||||
### Under Development 🚧
|
||||
|
||||
|
|
@ -253,7 +254,7 @@ Xiaozhi is an ecosystem. When using this product, you can also check out other [
|
|||
|
||||
| Usage Method | Supported Platforms | Free Platforms |
|
||||
|:---:|:---:|:---:|
|
||||
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
|
||||
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||
| Ollama interface calls | Ollama | - |
|
||||
| Dify interface calls | Dify | - |
|
||||
| FastGPT interface calls | FastGPT | - |
|
||||
|
|
@ -269,7 +270,7 @@ In fact, any LLM that supports OpenAI interface calls can be integrated and used
|
|||
|
||||
| Usage Method | Supported Platforms | Free Platforms |
|
||||
|:---:|:---:|:---:|
|
||||
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||
|
||||
In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
|
||||
|
||||
|
|
@ -279,8 +280,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||
|
||||
| Usage Method | Supported Platforms | Free Platforms |
|
||||
|:---:|:---:|:---:|
|
||||
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
|
||||
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(partial) |
|
||||
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -296,8 +297,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||
|
||||
| Usage Method | Supported Platforms | Free Platforms |
|
||||
|:---:|:---:|:---:|
|
||||
| Local use | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
||||
| Local use | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud and Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -305,7 +306,9 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||
|
||||
| Usage Method | Supported Platforms | Free Platforms |
|
||||
|:---:|:---:|:---:|
|
||||
| Local use | 3D-Speaker | 3D-Speaker |
|
||||
| Interface calls | Voiceprint service (voiceprint-api) | - |
|
||||
|
||||
Voiceprint recognition requires a separately deployed [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) service (based on 3D-Speaker) and MySQL. See the [voiceprint integration guide](../voiceprint-integration.md).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -317,6 +320,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||
| Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval |
|
||||
| Memory | mem_local_short | Local summarization | Free | |
|
||||
| Memory | nomem | No memory mode | Free | |
|
||||
| Memory | mem_report_only | Report only | Free | Only reports chat records, no memory summarization |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -351,11 +355,10 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||
| <img src="../images/logo_contributors.png" width="160"> | [Code Contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Thanks to [all code contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), your efforts have made the project more robust and powerful. |
|
||||
|
||||
|
||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||
|
||||
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
</picture>
|
||||
</a>
|
||||
|
|
|
|||
364
docs/readme/README_es.md
Normal file
364
docs/readme/README_es.md
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
||||
|
||||
<h1 align="center">Servicio backend Xiaozhi xiaozhi-esp32-server</h1>
|
||||
|
||||
<p align="center">
|
||||
Este proyecto desarrolla sistemas de hardware y software para terminales inteligentes a partir de la teoría y la tecnología de la inteligencia simbiótica humano-máquina<br/>y ofrece el servicio backend del proyecto de hardware inteligente de código abierto
|
||||
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||
Implementado en Python, Java y Vue según el <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">protocolo de comunicación Xiaozhi</a><br/>
|
||||
Compatible con el protocolo MQTT+UDP, el protocolo WebSocket, puntos de acceso MCP, reconocimiento de huella de voz y bases de conocimiento
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="../FAQ.md">Preguntas frecuentes</a>
|
||||
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Informar de problemas</a>
|
||||
· <a href="../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Documentación de despliegue</a>
|
||||
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Notas de la versión</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="../../README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
|
||||
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
|
||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DBEDFA"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
|
||||
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
|
||||
</a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
|
||||
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Liderado por el equipo del profesor Siyuan Liu (Universidad Tecnológica del Sur de China)
|
||||
</br>
|
||||
刘思源教授团队主导研发(华南理工大学)
|
||||
</br>
|
||||
<img src="../images/hnlg.jpg" alt="Universidad Tecnológica del Sur de China (华南理工大学)" width="50%">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## A quién va dirigido 👥
|
||||
|
||||
Este proyecto debe usarse junto con hardware ESP32. Si ya ha comprado hardware relacionado con ESP32, se ha conectado con éxito al servicio backend desplegado por Brother Xia (虾哥) y quiere montar por su cuenta su propio servicio backend `xiaozhi-esp32`, este proyecto encaja con lo que busca.
|
||||
|
||||
¿Quiere ver cómo se usa? Pulse los vídeos 🎥
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||
<picture>
|
||||
<img alt="Sensación de la velocidad de respuesta" src="../images/demo9.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||
<picture>
|
||||
<img alt="El secreto para optimizar la velocidad" src="../images/demo6.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||
<picture>
|
||||
<img alt="Humano digital Xiaozhi con activación por voz" src="../images/demo8.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||
<picture>
|
||||
<img alt="Llamadas de dispositivo a dispositivo" src="../images/demo0.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||
<picture>
|
||||
<img alt="Escenario médico complejo" src="../images/demo1.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||
<picture>
|
||||
<img alt="Reproducir música, consultar el tiempo y leer noticias" src="../images/demo7.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||
<picture>
|
||||
<img alt="Interrupción en tiempo real" src="../images/demo10.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||
<picture>
|
||||
<img alt="Reconocer objetos con una foto" src="../images/demo12.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||
<picture>
|
||||
<img alt="Controlar el encendido de electrodomésticos" src="../images/demo5.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||
<picture>
|
||||
<img alt="Tareas con varias instrucciones" src="../images/demo11.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||
<picture>
|
||||
<img alt="Punto de acceso MCP" src="../images/demo13.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||
<picture>
|
||||
<img alt="Envío de instrucciones MQTT" src="../images/demo4.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||
<picture>
|
||||
<img alt="Reconocimiento de huella de voz" src="../images/demo14.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||
<picture>
|
||||
<img alt="Tono de voz personalizado" src="../images/demo2.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||
<picture>
|
||||
<img alt="Conversación en cantonés" src="../images/demo3.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
## Advertencias ⚠️
|
||||
|
||||
1. Este proyecto es software de código abierto. Este software no mantiene relación comercial alguna con los proveedores de API de terceros a los que se conecta (incluidos, entre otros, plataformas de reconocimiento de voz, modelos de lenguaje y síntesis de voz), y no ofrece ninguna garantía sobre la calidad del servicio de dichos proveedores ni sobre la seguridad de sus fondos. Se recomienda elegir de forma preferente proveedores que cuenten con las licencias de actividad correspondientes y leer con atención sus condiciones de servicio y su política de privacidad. Este software no custodia ninguna clave de cuenta, no interviene en el movimiento de fondos y no asume el riesgo de pérdida del saldo recargado.
|
||||
|
||||
2. Las funciones de este proyecto no están completas y no ha superado una evaluación de seguridad de red. No lo utilice en entornos de producción. Si despliega este proyecto en una red pública con fines de aprendizaje, aplique las protecciones necesarias.
|
||||
|
||||
---
|
||||
|
||||
## Documentación de despliegue
|
||||
|
||||

|
||||
|
||||
Este proyecto ofrece dos formas de despliegue. Elija según lo que necesite:
|
||||
|
||||
#### 🚀 Elección del método de despliegue
|
||||
| Método de despliegue | Características | Escenarios | Documentación de despliegue | Requisitos | Tutoriales en vídeo |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **Instalación simplificada** | Diálogo inteligente, gestión de un solo agente | Entornos con pocos recursos; los datos se guardan en archivos de configuración y no hace falta base de datos | [①Versión Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Despliegue desde el código fuente](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Ejecutar `FunASR` en local consume bastante memoria; si todo va por API, el consumo de recursos es bajo | - |
|
||||
| **Instalación de todos los módulos** | Diálogo inteligente, gestión multiusuario, gestión de varios agentes, uso de la interfaz de la consola inteligente | Experiencia con todas las funciones; los datos se guardan en una base de datos |[①Versión Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Despliegue desde el código fuente](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de actualización automática desde el código fuente](../dev-ops-integration.md) | Ejecutar `FunASR` en local consume bastante memoria, y además requiere recursos de base de datos; si todo va por API, el consumo de recursos es bajo | [Tutorial en vídeo para arrancar el código fuente en local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
|
||||
|
||||
> 💡 Nota: a continuación hay una plataforma de prueba desplegada con el código más reciente. Si lo necesita, puede grabar el firmware y probarla. La concurrencia es de 6 usuarios y los datos se borran cada día.
|
||||
|
||||
```
|
||||
Dirección de la consola inteligente: https://2662r3426b.vicp.fun
|
||||
Consola inteligente (versión H5): https://2662r3426b.vicp.fun/h5/index.html
|
||||
|
||||
Herramienta de prueba del servicio: https://2662r3426b.vicp.fun/test/
|
||||
Dirección de la interfaz OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
|
||||
Dirección de la interfaz WebSocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||
```
|
||||
|
||||
#### 🚩 Descripción y recomendaciones de configuración
|
||||
> [!Note]
|
||||
> Este proyecto ofrece dos esquemas de configuración:
|
||||
>
|
||||
> 1. `Configuración básica y totalmente gratuita`: adecuada para uso personal y doméstico. Todos los componentes usan opciones gratuitas y no hay que pagar nada más.
|
||||
>
|
||||
> 2. `Configuración en streaming`: adecuada para demostraciones, formación y escenarios con más de 2 usuarios concurrentes. Usa procesamiento en streaming, responde antes y se siente mejor.
|
||||
>
|
||||
> Desde la versión `0.5.2`, el proyecto admite la configuración en streaming. Frente a las versiones anteriores, el tiempo de respuesta mejora unos `2,5 segundos` y la experiencia de uso mejora de forma notable.
|
||||
|
||||
| Módulo | Configuración básica y totalmente gratuita | Configuración en streaming |
|
||||
|:---:|:---:|:---:|
|
||||
| ASR (reconocimiento de voz) | FunASR (local) | 👍XunfeiStreamASR (iFLYTEK en streaming) |
|
||||
| LLM (modelo de lenguaje) | glm-4-flash (Zhipu) | 👍qwen-flash (Alibaba Bailian) |
|
||||
| VLLM (modelo de visión) | glm-4v-flash (Zhipu) | 👍qwen3.5-flash (Alibaba Bailian) |
|
||||
| TTS (síntesis de voz) | EdgeTTS (Microsoft) | 👍HuoshanDoubleStreamTTS (Volcano en streaming) |
|
||||
| Intent (reconocimiento de intención) | function_call (llamada a funciones) | function_call (llamada a funciones) |
|
||||
| Memory (memoria) | mem_local_short (memoria local a corto plazo) | mem_local_short (memoria local a corto plazo) |
|
||||
|
||||
Si le importa el tiempo que tarda cada componente, consulte el [informe de rendimiento de los componentes de Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research) y pruebe en su propio entorno con el método que describe el informe.
|
||||
|
||||
#### 🔧 Herramientas de prueba
|
||||
Este proyecto incluye las siguientes herramientas para comprobar el sistema y elegir un modelo adecuado:
|
||||
|
||||
| Herramienta | Ubicación | Uso | Qué hace |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| Prueba de interacción de audio | main》digital-human》index.html | En `main/digital-human`, instale las dependencias como indica su README, después ejecute `python start.py` y abra `http://127.0.0.1:8006/index.html` | Prueba la reproducción y la recepción de audio, y comprueba que el procesamiento de audio en Python funciona |
|
||||
| Prueba de respuesta de los modelos | main》xiaozhi-server》performance_tester.py | Ejecute `python performance_tester.py` | Mide la velocidad de respuesta de los principales módulos: ASR (reconocimiento de voz), LLM (modelo de lenguaje), VLLM (modelo de visión) y TTS (síntesis de voz) |
|
||||
|
||||
> 💡 Nota: al medir la velocidad de los modelos, solo se prueban los modelos que tienen una clave configurada.
|
||||
|
||||
---
|
||||
## Lista de funciones ✨
|
||||
### Implementado ✅
|
||||

|
||||
| Módulo | Descripción |
|
||||
|:---:|:---|
|
||||
| Arquitectura principal | Basada en la [pasarela MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md) y en servidores WebSocket y HTTP; ofrece un sistema completo de gestión de consola y de autenticación |
|
||||
| Interacción por voz | Admite ASR en streaming (reconocimiento de voz), TTS en streaming (síntesis de voz) y VAD (detección de actividad de voz), además de reconocimiento multilingüe y procesamiento de voz |
|
||||
| Huella de voz | Admite el registro, la gestión y el reconocimiento de la huella de voz de varios usuarios; se procesa en paralelo con el ASR, identifica en tiempo real quién habla y se lo pasa al LLM para una respuesta personalizada |
|
||||
| Diálogo inteligente | Admite varios LLM (modelos de lenguaje) para mantener un diálogo inteligente |
|
||||
| Percepción visual | Admite varios VLLM (modelos de visión) para una interacción multimodal |
|
||||
| Reconocimiento de intención | Admite el reconocimiento de intención con un modelo de lenguaje (LLM) externo y conectable, y la llamada autónoma a funciones del modelo, y ofrece un mecanismo de procesamiento de intenciones mediante plugins |
|
||||
| Sistema de memoria | Admite memoria local a corto plazo, memoria por la interfaz mem0ai y memoria inteligente PowerMem, con resumen de la memoria |
|
||||
| Base de conocimiento | Admite la base de conocimiento RAGFlow, para que el modelo decida si debe consultarla antes de responder |
|
||||
| Llamada a herramientas | Admite el protocolo IOT del cliente, el protocolo MCP del cliente, el protocolo MCP del servidor, el protocolo de punto de acceso MCP y funciones de herramientas personalizadas |
|
||||
| Envío de instrucciones | Apoyado en el protocolo MQTT, permite enviar instrucciones MCP desde la consola inteligente a los dispositivos ESP32 |
|
||||
| Backend de administración | Ofrece una interfaz web de administración, con gestión de usuarios, configuración del sistema y gestión de dispositivos. La interfaz se muestra en chino simplificado, chino tradicional, inglés, alemán, vietnamita y portugués de Brasil |
|
||||
| Herramientas de prueba | Incluye herramientas de prueba de rendimiento y de interacción de audio |
|
||||
| Soporte de despliegue | Admite el despliegue con Docker y el despliegue local, y ofrece una gestión completa de los archivos de configuración |
|
||||
| Sistema de plugins | Admite extensiones de plugins funcionales y el desarrollo de plugins propios; los nuevos archivos de plugin se cargan automáticamente en la siguiente conexión del dispositivo, y los cambios en el código de un plugin ya cargado requieren reiniciar el servicio |
|
||||
|
||||
### En desarrollo 🚧
|
||||
|
||||
Para ver el avance concreto del plan de desarrollo, [pulse aquí](https://github.com/users/xinnan-tech/projects/3). Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
|
||||
|
||||
Si desarrolla software, aquí tiene una [carta abierta a quienes desarrollan](../contributor_open_letter.md). La invitación está hecha.
|
||||
|
||||
---
|
||||
|
||||
## Ecosistema del producto 👬
|
||||
Xiaozhi es un ecosistema. Al usar este producto, también puede ver otros [proyectos destacados](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) de este ecosistema
|
||||
|
||||
---
|
||||
|
||||
## Plataformas y componentes compatibles 📋
|
||||
### LLM, modelos de lenguaje
|
||||
|
||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||
| Llamadas por la interfaz Ollama | Ollama | - |
|
||||
| Llamadas por la interfaz Dify | Dify | - |
|
||||
| Llamadas por la interfaz FastGPT | FastGPT | - |
|
||||
| Llamadas por la interfaz Coze | Coze | - |
|
||||
| Llamadas por la interfaz Xinference | Xinference | - |
|
||||
| Llamadas por la interfaz HomeAssistant | HomeAssistant | - |
|
||||
|
||||
En la práctica, se puede integrar cualquier LLM que admita llamadas por la interfaz OpenAI.
|
||||
|
||||
---
|
||||
|
||||
### VLLM, modelos de visión
|
||||
|
||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||
|
||||
En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI.
|
||||
|
||||
---
|
||||
|
||||
### TTS, síntesis de voz
|
||||
|
||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Llamadas por interfaz | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud y Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow (parcial) |
|
||||
| Servicio local | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
### VAD, detección de actividad de voz
|
||||
|
||||
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||
|:---:|:---------:|:----:|:----:|:--:|
|
||||
| VAD | SileroVAD | Uso local | Gratuito | |
|
||||
|
||||
---
|
||||
|
||||
### ASR, reconocimiento de voz
|
||||
|
||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||
| Llamadas por interfaz | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud y Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
### Voiceprint, huella de voz
|
||||
|
||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Llamadas por interfaz | Servicio de reconocimiento de huella de voz (voiceprint-api) | - |
|
||||
|
||||
El reconocimiento de huella de voz requiere desplegar por separado el servicio [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) (basado en 3D-Speaker), que depende de MySQL; consulte la [guía de integración de la huella de voz](../voiceprint-integration.md)
|
||||
|
||||
---
|
||||
|
||||
### Memory, almacenamiento de memoria
|
||||
|
||||
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||
| Memory | mem0ai | Llamadas por interfaz | Cuota de 1000 veces al mes | |
|
||||
| Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente |
|
||||
| Memory | mem_local_short | Resumen local | Gratuito | |
|
||||
| Memory | nomem | Modo sin memoria | Gratuito | |
|
||||
| Memory | mem_report_only | Solo informe | Gratuito | Solo informa el historial de chat, sin resumen de memoria |
|
||||
|
||||
---
|
||||
|
||||
### Intent, reconocimiento de intención
|
||||
|
||||
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||
| Intent | intent_llm | Llamadas por interfaz | Según el precio del LLM | Reconoce la intención mediante el modelo de lenguaje (LLM); gran capacidad de generalización |
|
||||
| Intent | function_call | Llamadas por interfaz | Según el precio del LLM | Completa la intención con llamadas a funciones del modelo; rápido y con buen resultado |
|
||||
| Intent | nointent | Modo sin intención | Gratuito | No reconoce la intención y devuelve directamente el resultado del diálogo |
|
||||
|
||||
---
|
||||
|
||||
### Rag, generación aumentada por recuperación
|
||||
|
||||
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||
| Rag | ragflow | Llamadas por interfaz | Cobrado según los tokens consumidos en el troceado y la segmentación | Usa la generación aumentada por recuperación de RagFlow para dar respuestas más precisas |
|
||||
|
||||
---
|
||||
|
||||
## Agradecimientos 🙏
|
||||
|
||||
| Logo | Proyecto o empresa | Descripción |
|
||||
|:---:|:---:|:---|
|
||||
| <img src="../images/logo_bailing.png" width="160"> | [Robot de diálogo por voz Bailing (百聆语音对话机器人)](https://github.com/wwbin2017/bailing) | Este proyecto parte del [robot de diálogo por voz Bailing](https://github.com/wwbin2017/bailing) y se construye sobre esa base |
|
||||
| <img src="../images/logo_tenclass.png" width="160"> | [Tenclass (十方融海)](https://www.tenclass.com/) | Gracias a [Tenclass](https://www.tenclass.com/) por definir el protocolo de comunicación estándar del ecosistema Xiaozhi, las soluciones de compatibilidad con varios dispositivos y los ejemplos prácticos de alta concurrencia, y por el apoyo de documentación técnica de todo el recorrido de este proyecto |
|
||||
| <img src="../images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology (玄凤科技)](https://github.com/Eric0308) | Gracias a [Xuanfeng Technology](https://github.com/Eric0308) por el código del marco de llamada a funciones, del protocolo de comunicación MCP y del mecanismo de llamadas basado en plugins. Con un sistema estandarizado de despacho de instrucciones y capacidad de ampliación dinámica, mejora de forma clara la eficiencia de interacción y la extensibilidad de los dispositivos de frontend (IoT) |
|
||||
| <img src="../images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Gracias a [huangjunsen](https://github.com/huangjunsen0406) por el módulo `consola inteligente móvil`, que permite controlar con eficacia dispositivos móviles de varias plataformas e interactuar en tiempo real, y mejora mucho la comodidad de uso y la eficiencia de gestión en escenarios móviles |
|
||||
| <img src="../images/logo_huiyuan.png" width="160"> | [Huiyuan Design (汇远设计)](http://ui.kwd988.net/) | Gracias a [Huiyuan Design](http://ui.kwd988.net/) por la solución visual de este proyecto, y por poner al servicio de la experiencia de uso la práctica de diseño acumulada con más de mil empresas |
|
||||
| <img src="../images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology (西安勤人信息科技)](https://www.029app.com/) | Gracias a [Xi'an Qinren Information Technology](https://www.029app.com/) por profundizar el sistema visual de este proyecto y mantener un estilo coherente y ampliable en distintos escenarios |
|
||||
| <img src="../images/logo_contributors.png" width="160"> | [Quienes contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Gracias a [todas las personas que contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors). Su trabajo hace el proyecto más sólido y más capaz. |
|
||||
|
||||
|
||||
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
</picture>
|
||||
</a>
|
||||
|
|
@ -22,6 +22,7 @@ Suporte ao protocolo MQTT+UDP, protocolo WebSocket, ponto de acesso MCP, reconhe
|
|||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DBEDFA"></a>
|
||||
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
|
|
@ -54,31 +55,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||
<picture>
|
||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
||||
<img alt="A sensação da velocidade de resposta" src="../images/demo9.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||
<picture>
|
||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
||||
<img alt="O segredo para otimizar a velocidade" src="../images/demo6.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||
<picture>
|
||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
||||
<img alt="Humano digital Xiaozhi com ativação por voz" src="../images/demo8.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||
<picture>
|
||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
||||
<img alt="Chamadas de dispositivo para dispositivo" src="../images/demo0.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||
<picture>
|
||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
||||
<img alt="Cenário médico complexo" src="../images/demo1.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -86,31 +87,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||
<picture>
|
||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
||||
<img alt="Reproduzir música, consultar o tempo e ler as notícias" src="../images/demo7.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||
<picture>
|
||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
||||
<img alt="Interrupção em tempo real" src="../images/demo10.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||
<picture>
|
||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
||||
<img alt="Reconhecer objetos com uma foto" src="../images/demo12.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||
<picture>
|
||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
||||
<img alt="Controlar o acionamento de eletrodomésticos" src="../images/demo5.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||
<picture>
|
||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
||||
<img alt="Tarefas com vários comandos" src="../images/demo11.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -118,31 +119,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||
<picture>
|
||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
||||
<img alt="Ponto de acesso MCP" src="../images/demo13.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||
<picture>
|
||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
||||
<img alt="Envio de comandos MQTT" src="../images/demo4.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||
<picture>
|
||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
||||
<img alt="Reconhecimento de impressão vocal" src="../images/demo14.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||
<picture>
|
||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
||||
<img alt="Tom de voz personalizado" src="../images/demo2.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||
<picture>
|
||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
||||
<img alt="Conversa em cantonês" src="../images/demo3.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -167,8 +168,8 @@ Este projeto oferece dois métodos de implantação. Por favor, escolha de acord
|
|||
#### 🚀 Seleção do Método de Implantação
|
||||
| Método de Implantação | Funcionalidades | Cenários Aplicáveis | Documentação de Implantação | Requisitos de Configuração | Tutoriais em Vídeo |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 núcleos 4GB se usar `FunASR`, 2 núcleos 2GB se todas APIs | - |
|
||||
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | 4 núcleos 8GB se usar `FunASR`, 2 núcleos 4GB se todas APIs| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` local exige mais memória; usar apenas APIs mantém o consumo de recursos baixo | - |
|
||||
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | `FunASR` local exige mais memória e recursos de banco de dados; usar apenas APIs mantém o consumo de recursos baixo| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md)
|
||||
|
||||
|
|
@ -209,15 +210,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
|
|||
|
||||
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Execute `python start.py` em `main/digital-human` e depois abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
|
||||
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta dos três módulos principais: ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
|
||||
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Em `main/digital-human`, instale as dependências como indica o README, depois execute `python start.py` e abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
|
||||
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta de módulos principais como ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
|
||||
|
||||
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
|
||||
|
||||
---
|
||||
## Lista de Funcionalidades ✨
|
||||
### Implementado ✅
|
||||

|
||||

|
||||
| Módulo de Funcionalidade | Descrição |
|
||||
|:---:|:---|
|
||||
| Arquitetura Principal | Baseado em [gateway MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), servidores WebSocket e HTTP, fornece sistema completo de gerenciamento de console e autenticação |
|
||||
|
|
@ -225,15 +226,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
|
|||
| Reconhecimento de Impressão Vocal | Suporta registro, gerenciamento e reconhecimento de impressão vocal de múltiplos usuários, processa em paralelo com o ASR, reconhecimento de identidade do falante em tempo real e repassa ao LLM para respostas personalizadas |
|
||||
| Diálogo Inteligente | Suporta múltiplos LLM (modelos de linguagem de grande porte), implementa diálogo inteligente |
|
||||
| Percepção Visual | Suporta múltiplos VLLM (modelos de visão de grande porte), implementa interação multimodal |
|
||||
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM, Function Call (chamada de função), fornece mecanismo de processamento de intenção baseado em plugins |
|
||||
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM externo e conectável, chamada de função autônoma do modelo de linguagem, fornece mecanismo de processamento de intenção baseado em plugins |
|
||||
| Sistema de Memória | Suporta memória local de curto prazo, memória via interface mem0ai, memória inteligente PowerMem, com funcionalidade de resumo de memória |
|
||||
| Base de Conhecimento | Suporta base de conhecimento RAGFlow, permitindo que o LLM julgue se deve acionar a base de conhecimento após receber a pergunta do usuário, e então responda à pergunta |
|
||||
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de endpoint MCP, funções de ferramentas personalizadas |
|
||||
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de ponto de acesso MCP, funções de ferramentas personalizadas |
|
||||
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente |
|
||||
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional e Inglês |
|
||||
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho, ferramentas de teste de modelo de visão e ferramentas de teste de interação por áudio |
|
||||
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional, Inglês, Alemão, Vietnamita e Português do Brasil |
|
||||
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho de resposta de modelo e ferramentas de teste de interação por áudio |
|
||||
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração |
|
||||
| Sistema de Plugins | Suporta extensões de plugins funcionais, desenvolvimento de plugins personalizados e carregamento dinâmico de plugins |
|
||||
| Sistema de Plugins | Suporta extensões de plugins funcionais e desenvolvimento de plugins personalizados; novos arquivos de plugin são carregados na próxima conexão do dispositivo e alterações em plugins já carregados exigem reiniciar o serviço |
|
||||
|
||||
### Em Desenvolvimento 🚧
|
||||
|
||||
|
|
@ -253,7 +254,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
|
|||
|
||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
|
||||
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||
| Chamadas via interface Ollama | Ollama | - |
|
||||
| Chamadas via interface Dify | Dify | - |
|
||||
| Chamadas via interface FastGPT | FastGPT | - |
|
||||
|
|
@ -261,7 +262,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
|
|||
| Chamadas via interface Xinference | Xinference | - |
|
||||
| Chamadas via interface HomeAssistant | HomeAssistant | - |
|
||||
|
||||
Na verdade, qualquer LLM que suporte chamadas via interface openai pode ser integrado e utilizado.
|
||||
Na verdade, qualquer LLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -269,7 +270,7 @@ Na verdade, qualquer LLM que suporte chamadas via interface openai pode ser inte
|
|||
|
||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||
|
||||
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
|
||||
|
||||
|
|
@ -279,8 +280,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||
|
||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(parcial) |
|
||||
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(parcial) |
|
||||
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -296,8 +297,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||
|
||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Uso local | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
||||
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud e Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -305,7 +306,9 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||
|
||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||
|:---:|:---:|:---:|
|
||||
| Uso local | 3D-Speaker | 3D-Speaker |
|
||||
| Chamadas via interface | Serviço de voiceprint (voiceprint-api) | - |
|
||||
|
||||
O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) implantado separadamente (baseado em 3D-Speaker) e MySQL. Veja o [guia de integração de voiceprint](../voiceprint-integration.md).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -317,6 +320,7 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||
| Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente |
|
||||
| Memória | mem_local_short | Resumo local | Gratuito | |
|
||||
| Memória | nomem | Modo sem memória | Gratuito | |
|
||||
| Memória | mem_report_only | Apenas relatório | Gratuito | Apenas reporta o histórico de chat, sem resumo de memória |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -351,11 +355,10 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||
| <img src="../images/logo_contributors.png" width="160"> | [Contribuidores de Código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Agradecimentos a [todos os contribuidores de código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), seus esforços tornaram o projeto mais robusto e poderoso. |
|
||||
|
||||
|
||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||
|
||||
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
</picture>
|
||||
</a>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh<br/>Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
|
||||
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||
Được triển khai bằng Python, Java, Vue theo <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">giao thức truyền thông Xiaozhi</a><br/>
|
||||
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng giọng nói và kho tri thức
|
||||
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng vân giọng và kho tri thức
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -22,6 +22,7 @@ Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP,
|
|||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
|
||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||
</a>
|
||||
|
|
@ -38,7 +39,7 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
|
|||
</br>
|
||||
Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
|
||||
</br>
|
||||
<img src="../images/hnlg.jpg" alt="华南理工大学" width="50%">
|
||||
<img src="../images/hnlg.jpg" alt="Đại học Bách khoa Nam Trung Quốc" width="50%">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
|
@ -54,31 +55,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||
<picture>
|
||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
||||
<img alt="Cảm giác tốc độ phản hồi" src="../images/demo9.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||
<picture>
|
||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
||||
<img alt="Bí quyết tối ưu tốc độ" src="../images/demo6.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||
<picture>
|
||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
||||
<img alt="Người ảo số Xiaozhi có đánh thức bằng giọng nói" src="../images/demo8.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||
<picture>
|
||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
||||
<img alt="Gọi giữa các thiết bị" src="../images/demo0.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||
<picture>
|
||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
||||
<img alt="Tình huống y tế phức tạp" src="../images/demo1.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -86,31 +87,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||
<picture>
|
||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
||||
<img alt="Phát nhạc, tra cứu thời tiết và đọc tin tức" src="../images/demo7.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||
<picture>
|
||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
||||
<img alt="Ngắt giữa chừng theo thời gian thực" src="../images/demo10.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||
<picture>
|
||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
||||
<img alt="Nhận dạng vật thể qua ảnh chụp" src="../images/demo12.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||
<picture>
|
||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
||||
<img alt="Bật tắt thiết bị gia dụng" src="../images/demo5.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||
<picture>
|
||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
||||
<img alt="Nhiệm vụ nhiều lệnh" src="../images/demo11.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -118,31 +119,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||
<picture>
|
||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
||||
<img alt="Điểm truy cập MCP" src="../images/demo13.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||
<picture>
|
||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
||||
<img alt="Gửi lệnh MQTT" src="../images/demo4.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||
<picture>
|
||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
||||
<img alt="Nhận dạng vân giọng" src="../images/demo14.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||
<picture>
|
||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
||||
<img alt="Giọng nói tùy chỉnh" src="../images/demo2.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||
<picture>
|
||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
||||
<img alt="Trò chuyện bằng tiếng Quảng Đông" src="../images/demo3.png" /></picture>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
@ -168,12 +169,12 @@ Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo
|
|||
#### 🚀 Lựa chọn phương pháp triển khai
|
||||
| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
|
||||
|---------|------|---------|---------|---------|---------|
|
||||
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 nhân 4GB nếu dùng `FunASR`, 2 nhân 2GB nếu toàn API | - |
|
||||
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | 4 nhân 8GB nếu dùng `FunASR`, 2 nhân 4GB nếu toàn API| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` cục bộ cần nhiều bộ nhớ; dùng toàn API thì mức dùng tài nguyên thấp | - |
|
||||
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, thao tác qua bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | `FunASR` cục bộ cần nhiều bộ nhớ, thêm tài nguyên cơ sở dữ liệu; dùng toàn API thì mức dùng tài nguyên thấp| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||
|
||||
Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](../FAQ.md)
|
||||
|
||||
> 💡 Gợi ý: Dưới đây là nền tảng thử nghiệm được triển khai theo mã mới nhất, có thể flash để thử nghiệm nếu cần, đồng thời là 6, dữ liệu sẽ được xóa mỗi ngày,
|
||||
> 💡 Gợi ý: Dưới đây là nền tảng thử nghiệm được triển khai theo mã mới nhất, có thể flash để thử nghiệm nếu cần, đồng thời là 6, dữ liệu sẽ được xóa mỗi ngày.
|
||||
|
||||
```
|
||||
Địa chỉ bảng điều khiển thông minh: https://2662r3426b.vicp.fun
|
||||
|
|
@ -192,7 +193,7 @@ Công cụ kiểm tra dịch vụ: https://2662r3426b.vicp.fun/test/
|
|||
>
|
||||
> 2. `Cấu hình streaming`: Phù hợp với demo, đào tạo, hơn 2 đồng thời, v.v., sử dụng công nghệ xử lý streaming, tốc độ phản hồi nhanh hơn, trải nghiệm tốt hơn.
|
||||
>
|
||||
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với phiên bản đầu, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
|
||||
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với các phiên bản trước đó, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
|
||||
|
||||
| Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|
||||
|:---:|:---:|:---:|
|
||||
|
|
@ -210,15 +211,15 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
|
|||
|
||||
| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
|
||||
|:---:|:---|:---:|:---:|
|
||||
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Chạy `python start.py` trong `main/digital-human`, sau đó mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
|
||||
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của ba module cốt lõi ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
|
||||
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Trong `main/digital-human`, cài đặt các phụ thuộc theo README, rồi chạy `python start.py` và mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
|
||||
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của các module cốt lõi như ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
|
||||
|
||||
> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
|
||||
|
||||
---
|
||||
## Danh sách tính năng ✨
|
||||
### Đã thực hiện ✅
|
||||

|
||||

|
||||
| Module chức năng | Mô tả |
|
||||
|:---:|:---|
|
||||
| Kiến trúc cốt lõi | Dựa trên [cổng MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket, máy chủ HTTP, cung cấp hệ thống quản lý bảng điều khiển và xác thực hoàn chỉnh |
|
||||
|
|
@ -231,10 +232,10 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
|
|||
| Kho tri thức | Hỗ trợ kho tri thức RAGFlow, cho phép mô hình lớn đánh giá cần gọi kho tri thức trước khi trả lời |
|
||||
| Gọi công cụ | Hỗ trợ giao thức IOT phía client, giao thức MCP phía client, giao thức MCP phía server, giao thức điểm truy cập MCP, hàm công cụ tùy chỉnh |
|
||||
| Gửi lệnh | Dựa vào giao thức MQTT, hỗ trợ gửi lệnh MCP từ bảng điều khiển thông minh xuống thiết bị ESP32 |
|
||||
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh |
|
||||
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất, công cụ kiểm tra mô hình thị giác và công cụ kiểm tra tương tác âm thanh |
|
||||
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh, tiếng Đức, tiếng Việt và tiếng Bồ Đào Nha Brazil |
|
||||
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất phản hồi mô hình và công cụ kiểm tra tương tác âm thanh |
|
||||
| Hỗ trợ triển khai | Hỗ trợ triển khai Docker và triển khai cục bộ, cung cấp quản lý tệp cấu hình hoàn chỉnh |
|
||||
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng, phát triển plugin tùy chỉnh và hot loading plugin |
|
||||
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng và phát triển plugin tùy chỉnh; file plugin mới được tải ở lần kết nối thiết bị tiếp theo, thay đổi mã của plugin đã tải cần khởi động lại dịch vụ |
|
||||
|
||||
### Đang phát triển 🚧
|
||||
|
||||
|
|
@ -254,7 +255,7 @@ Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạ
|
|||
|
||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||
|:---:|:---:|:---:|
|
||||
| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
|
||||
| Gọi giao diện OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||
| Gọi giao diện ollama | Ollama | - |
|
||||
| Gọi giao diện dify | Dify | - |
|
||||
| Gọi giao diện fastgpt | Fastgpt | - |
|
||||
|
|
@ -262,7 +263,7 @@ Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạ
|
|||
| Gọi giao diện xinference | Xinference | - |
|
||||
| Gọi giao diện homeassistant | HomeAssistant | - |
|
||||
|
||||
Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
|
||||
Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -270,9 +271,9 @@ Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đề
|
|||
|
||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||
|:---:|:---:|:---:|
|
||||
| Gọi giao diện openai | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||
| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||
|
||||
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
|
||||
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -280,8 +281,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||
|
||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||
|:---:|:---:|:---:|
|
||||
| Gọi giao diện | EdgeTTS, iFlytek, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi streaming TTS, MinimaxTTS | Lingxi streaming TTS, EdgeTTS, CosyVoiceSiliconflow(một phần) |
|
||||
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
| Gọi giao diện | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(một phần) |
|
||||
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -297,8 +298,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||
|
||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||
|:---:|:---:|:---:|
|
||||
| Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||
| Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
||||
| Sử dụng cục bộ | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||
| Gọi giao diện | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud và Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -306,7 +307,9 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||
|
||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||
|:---:|:---:|:---:|
|
||||
| Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
|
||||
| Gọi giao diện | Dịch vụ nhận dạng vân giọng (voiceprint-api) | - |
|
||||
|
||||
Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) được triển khai riêng (dựa trên 3D-Speaker) và MySQL. Xem [hướng dẫn tích hợp voiceprint](../voiceprint-integration.md).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -318,6 +321,7 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||
| Memory | [powermem](../powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh |
|
||||
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
|
||||
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
|
||||
| Memory | mem_report_only | Chỉ báo cáo | Miễn phí | Chỉ báo cáo lịch sử trò chuyện, không tóm tắt bộ nhớ |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -352,11 +356,10 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||
| <img src="../images/logo_contributors.png" width="160"> | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
|
||||
|
||||
|
||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||
|
||||
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||
</picture>
|
||||
</a>
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@
|
|||
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`voiceprint-api-main`
|
||||
你需要把它重命名成`voiceprint-api`。
|
||||
|
||||
## 第二步, 创建数据库和表
|
||||
## 第二步, 确认 MySQL 能访问
|
||||
|
||||
声纹识别需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
|
||||
|
||||
|
|
@ -39,7 +39,7 @@ telnet 127.0.0.1 3306
|
|||
networks:
|
||||
- default
|
||||
expose:
|
||||
- "3306:3306"
|
||||
- 3306
|
||||
```
|
||||
|
||||
修改后
|
||||
|
|
@ -58,8 +58,9 @@ telnet 127.0.0.1 3306
|
|||
# 进入你docker-compose_all.yml所在的文件夹,例如我的是xiaozhi-server
|
||||
cd xiaozhi-server
|
||||
docker compose -f docker-compose_all.yml down
|
||||
docker compose -f docker-compose.yml up -d
|
||||
docker compose -f docker-compose_all.yml up -d
|
||||
```
|
||||
数据库服务`xiaozhi-esp32-server-db`在`docker-compose_all.yml`里,最小化的`docker-compose.yml`只有服务本身,所以两条命令都用`docker-compose_all.yml`。
|
||||
|
||||
启动完后,在宿主机再使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
|
||||
```
|
||||
|
|
@ -171,6 +172,8 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
|
|||
然后搜索参数`server.voice_print`,此时,它的值应该是`null`值。
|
||||
点击修改按钮,把上一步得来的`声纹接口地址`粘贴到`参数值`里。然后保存。
|
||||
|
||||
声纹识别的相似度阈值是另一个系统参数`server.voiceprint_similarity_threshold`(默认0.4,范围0.0-1.0,数值越高越严格),要调整就在同一个`参数管理`页面里改。
|
||||
|
||||
如果能保存成功,说明一切顺利,你可以去智能体查看效果了。如果不成功,说明智控台无法访问声纹识别,很大概率是网络防火墙,或者没有填写正确的局域网ip。
|
||||
|
||||
## 第二步 设置智能体记忆模式
|
||||
|
|
@ -186,7 +189,7 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
|
|||
在智控台,`智能体管理`页面,在智能体的面板里,有一个`声纹识别`按钮,点击它。在底部有一个`新增按钮`。就可以对某个人说的话进行声纹注册。
|
||||
在弹出的框里,`描述`这个属性建议填写上,可以是这个人的职业、性格、爱好。方便智能体对说话人进行分析和了解。
|
||||
|
||||
## 第三步 和你的智能体聊天
|
||||
## 第五步 验证效果
|
||||
|
||||
将你的设备通电,问它,你知道我是谁吗?如果他能回答得出,说明声纹识别功能正常。
|
||||
|
||||
|
|
@ -205,6 +208,9 @@ voiceprint:
|
|||
- "test1,张三,张三是一个程序员"
|
||||
- "test2,李四,李四是一个产品经理"
|
||||
- "test3,王五,王五是一个设计师"
|
||||
# 声纹识别相似度阈值,范围0.0-1.0,默认0.4
|
||||
# 数值越高越严格,减少误识别但可能增加拒识率
|
||||
similarity_threshold: 0.4
|
||||
```
|
||||
|
||||
把上一步得来的 `声纹接口地址` 粘贴到 `url` 里。然后保存。
|
||||
|
|
|
|||
|
|
@ -2,14 +2,16 @@
|
|||
|
||||
## 功能简介
|
||||
|
||||
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。
|
||||
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持五个搜索源:秘塔(Metaso)、Tavily、Serply、Outcrawl和SpecStream,用户可根据需要选择其中一个。
|
||||
|
||||
## API Key申请指南
|
||||
|
||||
目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。
|
||||
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`、`Outcrawl搜索`和`SpecStream搜索`。
|
||||
- Tavily搜索:每个月1000次免费额度。
|
||||
- 秘塔搜索:拥有较为优质的国内数据源。
|
||||
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
|
||||
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
|
||||
- SpecStream搜索:注册赠送10美元,每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
|
||||
|
||||
## API Key申请指南
|
||||
|
||||
|
|
@ -32,6 +34,20 @@
|
|||
- 复制生成的API Key,这是配置所需的关键信息
|
||||
- 接口说明见 [Serply文档](https://serply.io/docs)
|
||||
|
||||
### 方式四:使用Outcrawl搜索
|
||||
|
||||
- 访问 [Outcrawl](https://outcrawl.ai),注册并登录账号
|
||||
- 在控制台中创建API Key
|
||||
- 复制生成的API Key,这是配置所需的关键信息
|
||||
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
|
||||
|
||||
### 方式五:使用SpecStream搜索
|
||||
|
||||
- 访问 [SpecStream](https://specstream.ai/signup?src=xiaozhi-esp32-server),注册并登录账号
|
||||
- 在工作区的 Agents & API 页面创建API Key
|
||||
- 复制生成的API Key,这是配置所需的关键信息
|
||||
- 接口说明见 [SpecStream文档](https://specstream.ai/search-api)
|
||||
|
||||
## 配置方式
|
||||
|
||||
### 方式1. 使用智控台部署(推荐)
|
||||
|
|
@ -40,14 +56,14 @@
|
|||
- 进入"配置角色"页面,选择要配置的智能体
|
||||
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
|
||||
- 勾选"联网搜索"
|
||||
- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项
|
||||
- 填入搜索源(`metaso`、`tavily`、`serply`、`outcrawl`或`specstream`),并将对应的`API Key`填入配置项
|
||||
- 保存配置,再保存智能体配置
|
||||
|
||||
### 方式2. 单模块xiaozhi-server部署
|
||||
|
||||
在 `data/.config.yaml` 中配置:
|
||||
|
||||
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply`
|
||||
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply`、`outcrawl` 或 `specstream`
|
||||
- 将申请到的API Key填入 `api_key`
|
||||
|
||||
```yaml
|
||||
|
|
|
|||
|
|
@ -16,3 +16,28 @@ Vue 3.x
|
|||
# 接口文档
|
||||
启动后打开:http://localhost:8002/xiaozhi/doc.html
|
||||
|
||||
# 跑测试
|
||||
测试分两种:纯单元测试,和要真连 MySQL、Redis 的集成测试(`DeviceTest`、`loginControllerTest`、`ModelConfigPersistenceTest`)。
|
||||
|
||||
集成测试需要先起好 MySQL 8 和 Redis 8。没起的时候这类测试整类跳过,不会让构建变红,日志里会写明缺的是哪个依赖。CI 上不一样:依赖连不上就直接让构建失败,不许跳过,免得门禁被悄悄掏空。
|
||||
|
||||
本地用 Docker 起这两个依赖:
|
||||
|
||||
```bash
|
||||
docker run -d --name xiaozhi-mysql -p 3306:3306 \
|
||||
-e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=xiaozhi_esp32_server mysql:8.0
|
||||
docker run -d --name xiaozhi-redis -p 6379:6379 redis:8.0
|
||||
```
|
||||
|
||||
跑全部测试:
|
||||
|
||||
```bash
|
||||
mvn -B test -DskipTests=false
|
||||
```
|
||||
|
||||
只想编译、不跑测试:
|
||||
|
||||
```bash
|
||||
mvn -B package -DskipTests=true
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@
|
|||
<liquibase-core.version>4.20.0</liquibase-core.version>
|
||||
<aliyun-sms-version>4.1.0</aliyun-sms-version>
|
||||
<okio-version>3.4.0</okio-version>
|
||||
<skipTests>true</skipTests>
|
||||
<skipTests>false</skipTests>
|
||||
<argLine></argLine>
|
||||
</properties>
|
||||
|
||||
|
|
|
|||
44
main/manager-api/scripts/check-integration-tests.sh
Executable file
44
main/manager-api/scripts/check-integration-tests.sh
Executable file
|
|
@ -0,0 +1,44 @@
|
|||
#!/usr/bin/env bash
|
||||
# 检查那几个要连 MySQL 和 Redis 的集成测试是不是真的跑了。
|
||||
# 守卫要是哪天手滑把它们全跳过了,CI 必须红,不能安安静静少跑一半门禁。
|
||||
set -uo pipefail
|
||||
|
||||
REPORT_DIR="${1:-target/surefire-reports}"
|
||||
|
||||
WATCHED=(
|
||||
"xiaozhi.modules.device.DeviceTest"
|
||||
"xiaozhi.modules.model.service.impl.ModelConfigPersistenceTest"
|
||||
"xiaozhi.modules.sys.loginControllerTest"
|
||||
)
|
||||
|
||||
if [ ! -d "$REPORT_DIR" ]; then
|
||||
echo "找不到测试报告目录:$REPORT_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
missing=()
|
||||
for class in "${WATCHED[@]}"; do
|
||||
count=0
|
||||
for report in "$REPORT_DIR"/TEST-*.xml; do
|
||||
[ -e "$report" ] || continue
|
||||
name=$(sed -n 's/.*<testsuite[^>]*name="\([^"]*\)".*/\1/p' "$report" | head -1)
|
||||
if [ "$name" = "$class" ]; then
|
||||
count=$(sed -n 's/.*<testsuite[^>]*tests="\([0-9]*\)".*/\1/p' "$report" | head -1)
|
||||
count=${count:-0}
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ "$count" -eq 0 ]; then
|
||||
missing+=("$class")
|
||||
else
|
||||
echo "OK $class 跑了 $count 条"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ${#missing[@]} -ne 0 ]; then
|
||||
echo "这几个集成测试一条都没跑:${missing[*]}"
|
||||
echo "守卫把门禁掏空了,构建必须失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "集成测试都跑过了"
|
||||
|
|
@ -95,6 +95,10 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||
callerNickname = targetBook.get(bookKey(callerMac));
|
||||
}
|
||||
if (StringUtils.isBlank(callerNickname)) {
|
||||
// 主叫显示名取的是主叫方自己那台设备在设备表里的名字,不是对方的。
|
||||
// 对方那边给主叫方起的称呼在上面的 targetBook 里已经查过。
|
||||
// 产品上按「来电显示」的口径处理,所以这里不套通讯录那套「不抄对方私产」的限制
|
||||
// 这个接口没有登录用户上下文,归属校验那个查法在这里会返回空,只能用不校验归属的查法
|
||||
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(callerMac);
|
||||
if (callerDevice != null) {
|
||||
callerNickname = callerDevice.getAlias();
|
||||
|
|
@ -212,11 +216,18 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
|
||||
entity.setMacAddress(macAddress);
|
||||
entity.setTargetMac(targetMac);
|
||||
// 如果 alias 为空,就默认使用设备名称;对方设备尚未登记时退回尾号称呼
|
||||
// 调用方没起名就退回尾号称呼。对方设备在智控台上起的名字是对方的私产,
|
||||
// 抄进调用方的通讯录等于把别人的昵称漏出去,所以别人的设备一律不去设备表取名
|
||||
if (StringUtils.isBlank(alias)) {
|
||||
DeviceEntity targetDevice = deviceService.getDeviceByMacAddress(targetMac);
|
||||
if (targetDevice != null) {
|
||||
alias = targetDevice.getAlias();
|
||||
// 只有给自己那台设备起名时才用设备表里的名字,那本来就是调用方自己的
|
||||
if (isOwnDevice(macAddress, targetMac)) {
|
||||
// 用带归属校验的那个查法。设备表里同一个 MAC 可能有两行只差大小写,
|
||||
// 一次只准取一条的那种查法撞上这种数据会抛 TooManyResultsException,
|
||||
// 整个保存接口带崩;按 id 取第一条,撞行也不报错
|
||||
DeviceEntity ownDevice = deviceService.getOwnedDeviceByMacAddress(macAddress);
|
||||
if (ownDevice != null && StringUtils.isNotBlank(ownDevice.getAlias())) {
|
||||
alias = ownDevice.getAlias();
|
||||
}
|
||||
}
|
||||
// 设备登记了但用户没起过名,alias 建表就是 null,这是默认状态
|
||||
// 不是异常。这时候落个 null 进去,缓存刷新会把整条跳过,
|
||||
|
|
@ -304,6 +315,16 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||
return macAddress == null ? null : macAddress.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标设备是不是调用方自己那台
|
||||
*
|
||||
* <p>
|
||||
* MAC 不区分大小写,比较前先按通讯录的键归一化,跟别处的比较口径保持一致
|
||||
*/
|
||||
private static boolean isOwnDevice(String macAddress, String targetMac) {
|
||||
return bookKey(macAddress) != null && bookKey(macAddress).equals(bookKey(targetMac));
|
||||
}
|
||||
|
||||
private String formatMacAsDeviceName(String mac) {
|
||||
if (StringUtils.isBlank(mac) || mac.length() < 2) {
|
||||
return mac;
|
||||
|
|
|
|||
|
|
@ -64,6 +64,37 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
|
||||
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
|
||||
|
||||
/**
|
||||
* Ollama的OpenAI兼容端点位于{base_url}/v1下,与xiaozhi-server侧ollama provider逻辑保持一致:
|
||||
* 先去尾斜杠、再剥离用户误填的完整端点后缀,仅对不含路径的纯主机地址补/v1。
|
||||
* 空串返回null,交由上层"配置不完整"必填校验拦截
|
||||
*/
|
||||
private static String normalizeOllamaBaseUrl(String baseUrl) {
|
||||
if (baseUrl == null) {
|
||||
return null;
|
||||
}
|
||||
String url = baseUrl.trim();
|
||||
if (url.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
while (url.endsWith("/")) {
|
||||
url = url.substring(0, url.length() - 1);
|
||||
}
|
||||
if (url.endsWith("/chat/completions")) {
|
||||
url = url.substring(0, url.length() - "/chat/completions".length());
|
||||
while (url.endsWith("/")) {
|
||||
url = url.substring(0, url.length() - 1);
|
||||
}
|
||||
}
|
||||
if (url.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (url.replaceFirst("^https?://[^/]+", "").isEmpty()) {
|
||||
url = url + "/v1";
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateSummary(String conversation) {
|
||||
return generateSummary(conversation, null, null);
|
||||
|
|
@ -101,6 +132,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
Double temperature = configJson.getDouble("temperature");
|
||||
Integer maxTokens = configJson.getInt("max_tokens");
|
||||
|
||||
|
|
@ -196,6 +234,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
||||
log.error("LLM配置不完整,baseUrl或apiKey为空");
|
||||
|
|
@ -271,8 +316,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
|
||||
// Ollama免鉴权:不要求api_key
|
||||
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
|
||||
return baseUrl != null && !baseUrl.trim().isEmpty() &&
|
||||
apiKey != null && !apiKey.trim().isEmpty();
|
||||
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
|
||||
} catch (Exception e) {
|
||||
log.error("检查LLM服务可用性时发生异常:", e);
|
||||
return false;
|
||||
|
|
@ -297,8 +344,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
|
||||
// Ollama免鉴权:不要求api_key
|
||||
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
|
||||
return baseUrl != null && !baseUrl.trim().isEmpty() &&
|
||||
apiKey != null && !apiKey.trim().isEmpty();
|
||||
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
|
||||
} catch (Exception e) {
|
||||
log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e);
|
||||
return false;
|
||||
|
|
@ -354,6 +403,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
||||
log.error("LLM配置不完整,baseUrl或apiKey为空");
|
||||
|
|
|
|||
|
|
@ -110,8 +110,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||
// 1. 参数验证
|
||||
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
|
||||
|
||||
// 2. 验证模型提供者
|
||||
validateModelProvider(modelType, provideCode);
|
||||
// 2. 验证模型提供者,使用注册类型的大小写
|
||||
String registeredModelType = resolveModelType(modelType, provideCode);
|
||||
|
||||
// 3. 获取原始配置(不经过敏感数据处理)
|
||||
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
|
||||
|
|
@ -120,7 +120,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||
validateLlmConfiguration(modelConfigBodyDTO);
|
||||
|
||||
// 5. 准备更新实体并处理敏感数据
|
||||
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id);
|
||||
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, registeredModelType, id);
|
||||
|
||||
// 6. 执行数据库更新
|
||||
modelConfigDao.updateById(modelConfigEntity);
|
||||
|
|
@ -136,9 +136,9 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||
validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
|
||||
|
||||
validateModelProvider(modelType, provideCode);
|
||||
String registeredModelType = resolveModelType(modelType, provideCode);
|
||||
|
||||
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, modelType);
|
||||
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, registeredModelType);
|
||||
|
||||
modelConfigDao.insert(modelConfigEntity);
|
||||
|
||||
|
|
@ -283,13 +283,14 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||
}
|
||||
|
||||
/**
|
||||
* 验证模型提供者
|
||||
* 验证模型提供者并获取注册类型,保留 TTS、Memory、Intent 等类型的大小写
|
||||
*/
|
||||
private void validateModelProvider(String modelType, String provideCode) {
|
||||
private String resolveModelType(String modelType, String provideCode) {
|
||||
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
||||
if (CollectionUtil.isEmpty(providerList)) {
|
||||
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
|
||||
}
|
||||
return providerList.get(0).getModelType();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -0,0 +1,4 @@
|
|||
-- 添加MCP接入点附带说话人身份的开关参数配置
|
||||
delete from `sys_params` where param_code = 'mcp_forward_speaker';
|
||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (313, 'mcp_forward_speaker', 'true', 'boolean', 1, '是否随MCP调用附带说话人身份');
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
-- Ollama LLM配置补充api_key占位值,走鉴权网关/Ollama Cloud时使用
|
||||
UPDATE `ai_model_config`
|
||||
SET `config_json` = JSON_SET(`config_json`, '$.api_key', 'ollama')
|
||||
WHERE `id` = 'LLM_OllamaLLM' AND JSON_EXTRACT(`config_json`, '$.api_key') IS NULL;
|
||||
|
||||
-- Ollama供应商追加api_key字段定义,password类型
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_ARRAY_APPEND(COALESCE(`fields`, JSON_ARRAY()), '$',
|
||||
JSON_OBJECT('key', 'api_key', 'label', 'API密钥', 'type', 'password'))
|
||||
WHERE `id` = 'SYSTEM_LLM_ollama'
|
||||
AND JSON_SEARCH(`fields`, 'one', 'api_key', NULL, '$[*].key') IS NULL;
|
||||
|
||||
-- 配置说明补充api_key条目
|
||||
UPDATE `ai_model_config`
|
||||
SET `remark` = CONCAT(`remark`, '\n4. 走鉴权网关或使用Ollama Cloud时,需填写api_key')
|
||||
WHERE `id` = 'LLM_OllamaLLM'
|
||||
AND `remark` IS NOT NULL AND `remark` NOT LIKE '%api_key%';
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
-- PaddleSpeechTTS:智控台协议收敛为仅 websocket(与 xiaozhi-server 实现一致)
|
||||
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_ARRAY(
|
||||
JSON_OBJECT('key', 'protocol', 'label', '协议类型', 'type', 'string', 'options', JSON_ARRAY('websocket')),
|
||||
JSON_OBJECT('key', 'url', 'label', '服务地址', 'type', 'string'),
|
||||
JSON_OBJECT('key', 'spk_id', 'label', '音色', 'type', 'int'),
|
||||
JSON_OBJECT('key', 'sample_rate', 'label', '采样率', 'type', 'float'),
|
||||
JSON_OBJECT('key', 'speed', 'label', '语速', 'type', 'float'),
|
||||
JSON_OBJECT('key', 'volume', 'label', '音量', 'type', 'float'),
|
||||
JSON_OBJECT('key', 'save_path', 'label', '保存路径', 'type', 'string')
|
||||
)
|
||||
WHERE `id` = 'SYSTEM_TTS_PaddleSpeechTTS';
|
||||
|
||||
UPDATE `ai_model_config`
|
||||
SET `remark` = 'PaddleSpeechTTS 配置说明:
|
||||
1. PaddleSpeech 是百度飞桨开源的语音合成工具,支持本地离线部署和模型训练。paddlepaddle百度飞浆框架地址:https://www.paddlepaddle.org.cn/
|
||||
2. 当前仅支持 WebSocket 协议进行流式传输(参考部署文档:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/paddlespeech-deploy.md)。
|
||||
3. 使用前要在本地部署 paddlespeech 服务,服务默认运行在 ws://127.0.0.1:8092/paddlespeech/tts/streaming
|
||||
4. 支持自定义发音人、语速、音量和采样率。
|
||||
'
|
||||
WHERE `id` = 'TTS_PaddleSpeechTTS';
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
-- 联网搜索插件新增Outcrawl搜索源
|
||||
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_SET(
|
||||
`fields`,
|
||||
'$[0].label',
|
||||
'搜索源:metaso / tavily / serply / outcrawl'
|
||||
)
|
||||
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
-- 联网搜索插件新增SpecStream搜索源
|
||||
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_SET(
|
||||
`fields`,
|
||||
'$[0].label',
|
||||
'搜索源:metaso / tavily / serply / outcrawl / specstream'
|
||||
)
|
||||
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
-- 为 LLM 的 OpenAI 接口配置表单新增 chat_template_kwargs 字段(dict, 前端映射为 JSON 文本框)
|
||||
-- 用于向 vLLM/SGLang 等自托管 OpenAI 兼容后端透传 chat template 控制参数(如 enable_thinking)
|
||||
-- 注意: DashScope 等云服务不识别此字段, 仅供自托管后端使用
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = '[{"key":"base_url","label":"基础URL","type":"string"},{"key":"model_name","label":"模型名称","type":"string"},{"key":"api_key","label":"API密钥","type":"string"},{"key":"temperature","label":"温度","type":"number"},{"key":"max_tokens","label":"最大令牌数","type":"number"},{"key":"top_p","label":"top_p值","type":"number"},{"key":"top_k","label":"top_k值","type":"number"},{"key":"frequency_penalty","label":"频率惩罚","type":"number"},{"key":"chat_template_kwargs","label":"模板变量(JSON)","type":"dict"}]'
|
||||
WHERE `id` = 'SYSTEM_LLM_openai';
|
||||
|
|
@ -753,3 +753,45 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202609172100.sql
|
||||
- changeSet:
|
||||
id: 202610261030
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202610261030.sql
|
||||
- changeSet:
|
||||
id: 202610291451
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202610291451.sql
|
||||
- changeSet:
|
||||
id: 202610302051
|
||||
author: shinjiyu
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202610302051.sql
|
||||
- changeSet:
|
||||
id: 202611021200
|
||||
author: heydryft
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202611021200.sql
|
||||
- changeSet:
|
||||
id: 202611101200
|
||||
author: Specstreamai
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202611101200.sql
|
||||
- changeSet:
|
||||
id: 202611181622
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202611181622.sql
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ class SensitiveDataUtilsTest {
|
|||
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
|
||||
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
|
||||
assertTrue(masked.startsWith("very"));
|
||||
assertTrue(masked.endsWith("3123"));
|
||||
assertTrue(masked.endsWith("e123"));
|
||||
assertTrue(masked.contains("****"));
|
||||
assertEquals("verylongapikeyvalue123".length(), masked.length());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,9 +14,14 @@ import java.util.Collections;
|
|||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
|
||||
import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao;
|
||||
import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity;
|
||||
import xiaozhi.modules.correctword.dao.CorrectWordFileDao;
|
||||
|
|
@ -37,6 +42,20 @@ class CorrectWordFileServiceImplTest {
|
|||
private final CorrectWordFileServiceImpl service =
|
||||
new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao);
|
||||
|
||||
@BeforeAll
|
||||
static void registerEntityMetadata() {
|
||||
// 这条用例不起 Spring 上下文,MyBatis-Plus 的实体元数据没人注册,
|
||||
// LambdaQueryWrapper 拼条件时找不到 lambda 缓存就抛异常。
|
||||
// 全量跑的时候是前面的上下文测试顺带注册好的,单独跑就露馅。
|
||||
// 这里自己补上,单独跑和跟着全量跑结果一样。
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
CorrectWordItemEntity.class);
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
CorrectWordFileEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_empty_list_when_no_mappings() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package xiaozhi.modules.device;
|
|||
import java.util.HashMap;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
|
@ -15,6 +16,7 @@ import xiaozhi.common.exception.RenException;
|
|||
import xiaozhi.common.redis.RedisUtils;
|
||||
import xiaozhi.modules.sys.dto.SysUserDTO;
|
||||
import xiaozhi.modules.sys.service.SysUserService;
|
||||
import xiaozhi.testsupport.IntegrationTestEnvironment;
|
||||
|
||||
@Slf4j
|
||||
@SpringBootTest
|
||||
|
|
@ -22,6 +24,11 @@ import xiaozhi.modules.sys.service.SysUserService;
|
|||
@DisplayName("设备测试")
|
||||
public class DeviceTest {
|
||||
|
||||
@BeforeAll
|
||||
static void checkDependencies() {
|
||||
IntegrationTestEnvironment.requireDatabaseAndRedis();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private RedisUtils redisUtils;
|
||||
@Autowired
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package xiaozhi.modules.device.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
|
@ -21,6 +22,7 @@ import java.util.List;
|
|||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.apache.ibatis.exceptions.TooManyResultsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
|
|
@ -75,7 +77,7 @@ class DeviceAddressBookServiceImplTest {
|
|||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
|
||||
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
|
||||
|
||||
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
|
||||
|
||||
|
|
@ -85,10 +87,11 @@ class DeviceAddressBookServiceImplTest {
|
|||
assertNotNull(entity.getAlias());
|
||||
assertEquals("尾号为66的设备", entity.getAlias());
|
||||
assertTrue(entity.getHasPermission());
|
||||
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAliasOnRegisteredTargetWithoutNicknameFallsBackToMacSuffix() {
|
||||
void blankAliasOnAnotherDeviceFallsBackToMacSuffixWithoutAskingTheDeviceTable() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
|
|
@ -101,6 +104,7 @@ class DeviceAddressBookServiceImplTest {
|
|||
registered.setMacAddress(OTHER_MAC);
|
||||
registered.setAlias(null);
|
||||
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
|
||||
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
|
||||
|
||||
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
|
||||
|
||||
|
|
@ -108,6 +112,171 @@ class DeviceAddressBookServiceImplTest {
|
|||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
|
||||
"登记了但没起名的设备落个空名,缓存刷新会跳过这条,对方永远呼不过来");
|
||||
verify(deviceService, never()).getDeviceByMacAddress(anyString());
|
||||
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAliasOnRegisteredTargetDoesNotTakeOverTheirNickname() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
DeviceEntity theirs = new DeviceEntity();
|
||||
theirs.setMacAddress(OTHER_MAC);
|
||||
theirs.setAlias("老王的音响");
|
||||
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
|
||||
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
|
||||
|
||||
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
|
||||
"对方在智控台上给这台设备起的名字被抄进了调用方的通讯录");
|
||||
verify(deviceService, never()).getDeviceByMacAddress(anyString());
|
||||
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAliasOnOwnDeviceUsesTheNameFromItsOwnDeviceRow() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
DeviceEntity mine = new DeviceEntity();
|
||||
mine.setMacAddress(MAC);
|
||||
mine.setAlias("我的书房");
|
||||
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
|
||||
|
||||
service.saveOrUpdate(MAC, MAC, null, true);
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
|
||||
"给自己那台设备起名,用的就是自己设备表里的名字");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownDeviceWithoutAliasInDeviceTableFallsBackToMacSuffix() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
DeviceEntity mine = new DeviceEntity();
|
||||
mine.setMacAddress(MAC);
|
||||
mine.setAlias(null);
|
||||
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
|
||||
|
||||
service.saveOrUpdate(MAC, MAC, null, true);
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("尾号为55的设备", entityCaptor.getValue().getAlias(),
|
||||
"自己的设备在设备表里也没起名,落个空名的话缓存刷新会跳过这条");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateDeviceRowsDifferingOnlyInCaseDoNotBreakNaming() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
// 设备表里同一个 MAC 有两行只差大小写,一次只准取一条的那种查法会直接抛异常
|
||||
when(deviceService.getDeviceByMacAddress(anyString()))
|
||||
.thenThrow(new TooManyResultsException("selectOne 撞上两行只差大小写的数据"));
|
||||
DeviceEntity first = new DeviceEntity();
|
||||
first.setMacAddress(MAC);
|
||||
first.setAlias("我的书房");
|
||||
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(first);
|
||||
|
||||
assertDoesNotThrow(() -> service.saveOrUpdate(MAC, MAC, null, true),
|
||||
"同 MAC 有两行只差大小写时,取名不能把整个接口带崩");
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
|
||||
"撞行时按 id 取第一条那条的名字");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownDeviceIsRecognizedWhateverCaseTheAddressIsWrittenIn() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
DeviceEntity mine = new DeviceEntity();
|
||||
mine.setMacAddress(HEX_MAC);
|
||||
mine.setAlias("我的书房");
|
||||
when(deviceService.getOwnedDeviceByMacAddress(HEX_MAC)).thenReturn(mine);
|
||||
|
||||
service.saveOrUpdate(HEX_MAC, HEX_MAC.toUpperCase(), null, true);
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
|
||||
"同一个地址写成大小写两种样子,就被当成别人的设备了");
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitAliasIsKeptAsIs() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
|
||||
service.saveOrUpdate(MAC, OTHER_MAC, "客厅", true);
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("客厅", entityCaptor.getValue().getAlias(),
|
||||
"自己给别人的设备起名是通讯录的本意,不能被兜底逻辑改掉");
|
||||
verify(deviceService, never()).getDeviceByMacAddress(anyString());
|
||||
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAliasOnUnregisteredTargetDoesNotBlowUp() {
|
||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||
DeviceService deviceService = mock(DeviceService.class);
|
||||
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
|
||||
|
||||
assertDoesNotThrow(() -> service.saveOrUpdate(MAC, OTHER_MAC, null, true),
|
||||
"目标设备没登记时接口得正常返回,不能抛异常");
|
||||
|
||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
@ -325,7 +494,7 @@ class DeviceAddressBookServiceImplTest {
|
|||
DeviceService deviceService = mock(DeviceService.class);
|
||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||
when(deviceService.getDeviceByMacAddress(anyString())).thenReturn(null);
|
||||
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
|
||||
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||
addressBookDao, redisUtils, deviceService, mock(SysParamsService.class));
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,82 @@
|
|||
package xiaozhi.modules.model.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import cn.hutool.json.JSONObject;
|
||||
import xiaozhi.common.redis.RedisKeys;
|
||||
import xiaozhi.common.redis.RedisUtils;
|
||||
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||
import xiaozhi.modules.model.service.ModelConfigService;
|
||||
import xiaozhi.testsupport.IntegrationTestEnvironment;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
@Transactional
|
||||
class ModelConfigPersistenceTest {
|
||||
|
||||
@BeforeAll
|
||||
static void checkDependencies() {
|
||||
IntegrationTestEnvironment.requireDatabaseAndRedis();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private ModelConfigService service;
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbc;
|
||||
|
||||
@Autowired
|
||||
private RedisUtils redis;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"tts,TTS", "memory,Memory", "intent,Intent"})
|
||||
void preservesRegisteredTypeWhenAddingAndEditing(String requestedType, String registeredType) {
|
||||
String id = UUID.randomUUID().toString().replace("-", "");
|
||||
String providerCode = "test-" + id;
|
||||
jdbc.update("INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields) VALUES (?, ?, ?, ?, ?)",
|
||||
id, registeredType, providerCode, "Persistence test provider", "[]");
|
||||
|
||||
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
|
||||
body.setId(id);
|
||||
body.setModelCode(providerCode);
|
||||
body.setModelName("Persistence test model");
|
||||
body.setIsDefault(0);
|
||||
body.setIsEnabled(1);
|
||||
body.setSort(1);
|
||||
body.setConfigJson(new JSONObject().set("type", providerCode));
|
||||
|
||||
ModelConfigDTO added = service.add(requestedType, providerCode, body);
|
||||
assertEquals(registeredType, added.getModelType());
|
||||
assertEquals(registeredType,
|
||||
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
|
||||
|
||||
String cacheKey = RedisKeys.getModelConfigById(id);
|
||||
try {
|
||||
redis.set(cacheKey, "cached model");
|
||||
body.setModelName("Updated persistence test model");
|
||||
ModelConfigDTO edited = service.edit(requestedType, providerCode, id, body);
|
||||
|
||||
assertEquals(registeredType, edited.getModelType());
|
||||
assertEquals(registeredType,
|
||||
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
|
||||
assertEquals(body.getModelName(),
|
||||
jdbc.queryForObject("SELECT model_name FROM ai_model_config WHERE id = ?", String.class, id));
|
||||
assertNull(redis.get(cacheKey));
|
||||
} finally {
|
||||
redis.delete(cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
package xiaozhi.modules.model.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
import xiaozhi.common.exception.ErrorCode;
|
||||
import xiaozhi.common.exception.RenException;
|
||||
import xiaozhi.common.redis.RedisUtils;
|
||||
import xiaozhi.common.utils.MessageUtils;
|
||||
import xiaozhi.modules.agent.dao.AgentDao;
|
||||
import xiaozhi.modules.model.dao.ModelConfigDao;
|
||||
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||
import xiaozhi.modules.model.dto.ModelProviderDTO;
|
||||
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
||||
import xiaozhi.modules.model.service.ModelProviderService;
|
||||
|
||||
class ModelConfigServiceImplTest {
|
||||
|
||||
private ModelConfigDao modelConfigDao;
|
||||
private ModelProviderService modelProviderService;
|
||||
private ModelConfigServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
modelConfigDao = mock(ModelConfigDao.class);
|
||||
modelProviderService = mock(ModelProviderService.class);
|
||||
service = new ModelConfigServiceImpl(
|
||||
modelConfigDao, modelProviderService, mock(RedisUtils.class), mock(AgentDao.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
|
||||
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
|
||||
})
|
||||
void addPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
|
||||
registerProvider(requestedType, registeredType);
|
||||
|
||||
ModelConfigDTO result = service.add(requestedType, "test-provider", modelBody());
|
||||
|
||||
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
|
||||
verify(modelConfigDao).insert(saved.capture());
|
||||
assertEquals(registeredType, saved.getValue().getModelType());
|
||||
assertEquals(registeredType, result.getModelType());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
|
||||
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
|
||||
})
|
||||
void editPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
|
||||
registerProvider(requestedType, registeredType);
|
||||
ModelConfigEntity original = new ModelConfigEntity();
|
||||
original.setId("test-model");
|
||||
original.setModelType(registeredType);
|
||||
when(modelConfigDao.selectById("test-model")).thenReturn(original);
|
||||
|
||||
ModelConfigDTO result = service.edit(requestedType, "test-provider", "test-model", modelBody());
|
||||
|
||||
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
|
||||
verify(modelConfigDao).updateById(saved.capture());
|
||||
assertEquals(registeredType, saved.getValue().getModelType());
|
||||
assertEquals(registeredType, result.getModelType());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void rejectsUnknownProviderBeforeWriting(boolean editing) {
|
||||
when(modelProviderService.getList("tts", "missing")).thenReturn(List.of());
|
||||
|
||||
try (MockedStatic<MessageUtils> messages = mockStatic(MessageUtils.class)) {
|
||||
messages.when(() -> MessageUtils.getMessage(ErrorCode.MODEL_PROVIDER_NOT_EXIST))
|
||||
.thenReturn("Model provider does not exist");
|
||||
RenException error = assertThrows(RenException.class, () -> {
|
||||
if (editing) {
|
||||
service.edit("tts", "missing", "test-model", modelBody());
|
||||
} else {
|
||||
service.add("tts", "missing", modelBody());
|
||||
}
|
||||
});
|
||||
assertEquals(ErrorCode.MODEL_PROVIDER_NOT_EXIST, error.getCode());
|
||||
}
|
||||
|
||||
verify(modelConfigDao, never()).insert(any(ModelConfigEntity.class));
|
||||
verify(modelConfigDao, never()).updateById(any(ModelConfigEntity.class));
|
||||
}
|
||||
|
||||
private void registerProvider(String requestedType, String registeredType) {
|
||||
ModelProviderDTO provider = new ModelProviderDTO();
|
||||
provider.setModelType(registeredType);
|
||||
provider.setProviderCode("test-provider");
|
||||
when(modelProviderService.getList(requestedType, "test-provider")).thenReturn(List.of(provider));
|
||||
}
|
||||
|
||||
private ModelConfigBodyDTO modelBody() {
|
||||
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
|
||||
body.setId("test-model");
|
||||
body.setModelName("Test model");
|
||||
body.setIsEnabled(1);
|
||||
body.setSort(1);
|
||||
return body;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
|||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
|
@ -18,12 +19,18 @@ import xiaozhi.modules.security.dto.LoginDTO;
|
|||
import xiaozhi.modules.security.dto.SmsVerificationDTO;
|
||||
import xiaozhi.modules.sys.dto.RetrievePasswordDTO;
|
||||
import xiaozhi.modules.sys.service.SysUserService;
|
||||
import xiaozhi.testsupport.IntegrationTestEnvironment;
|
||||
|
||||
@Slf4j
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
class loginControllerTest {
|
||||
|
||||
@BeforeAll
|
||||
static void checkDependencies() {
|
||||
IntegrationTestEnvironment.requireDatabaseAndRedis();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
LoginController loginController;
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,149 @@
|
|||
package xiaozhi.testsupport;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.springframework.boot.env.YamlPropertySourceLoader;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.env.PropertySourcesPropertyResolver;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.RedisURI;
|
||||
import io.lettuce.core.api.StatefulRedisConnection;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 几个 @SpringBootTest 要真连 MySQL 和 Redis。本地没起这两个依赖时,
|
||||
* 整类测试跳过,别让 Spring 上下文起不来变成一堆看不懂的报错;
|
||||
* CI 里依赖必须真的在,探不通就直接让构建红。
|
||||
*/
|
||||
@Slf4j
|
||||
public final class IntegrationTestEnvironment {
|
||||
|
||||
/** 集成测试用的配置文件,跟应用本身读的是同一套 */
|
||||
private static final String[] CONFIG_FILES = {"application.yml", "application-dev.yml"};
|
||||
|
||||
private static Boolean available;
|
||||
private static String problem;
|
||||
|
||||
private IntegrationTestEnvironment() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 放在要连库的测试类的 @BeforeAll 里。
|
||||
* 本地依赖不齐就整类跳过,CI 里依赖不齐就直接失败。
|
||||
*/
|
||||
public static void requireDatabaseAndRedis() {
|
||||
String issue = probe();
|
||||
if (issue == null) {
|
||||
return;
|
||||
}
|
||||
if (isCi()) {
|
||||
throw new IllegalStateException(
|
||||
"CI 环境里" + issue + ",这几个集成测试必须真的跑起来,不能跳过");
|
||||
}
|
||||
log.warn("跳过依赖 MySQL 和 Redis 的集成测试:{}", issue);
|
||||
Assumptions.assumeTrue(false, issue);
|
||||
}
|
||||
|
||||
/** GitHub Actions 上会带 CI=true */
|
||||
public static boolean isCi() {
|
||||
String value = System.getenv("CI");
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return !trimmed.isEmpty() && !"false".equalsIgnoreCase(trimmed);
|
||||
}
|
||||
|
||||
/** 依赖都齐返回 null,不齐返回缺什么 */
|
||||
static synchronized String probe() {
|
||||
if (available != null) {
|
||||
return problem;
|
||||
}
|
||||
PropertySourcesPropertyResolver resolver = resolver();
|
||||
StringBuilder issues = new StringBuilder();
|
||||
|
||||
String url = firstNonBlank(resolver.getProperty("spring.datasource.druid.url", ""),
|
||||
resolver.getProperty("spring.datasource.url", ""));
|
||||
String username = firstNonBlank(resolver.getProperty("spring.datasource.druid.username", ""),
|
||||
resolver.getProperty("spring.datasource.username", ""));
|
||||
String password = firstNonBlank(resolver.getProperty("spring.datasource.druid.password", ""),
|
||||
resolver.getProperty("spring.datasource.password", ""));
|
||||
if (url.isBlank()) {
|
||||
issues.append("配置里找不到数据源地址;");
|
||||
} else {
|
||||
try {
|
||||
DriverManager.setLoginTimeout(5);
|
||||
try (Connection connection = DriverManager.getConnection(url, username, password)) {
|
||||
connection.isValid(3);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
issues.append("连不上 MySQL(").append(e.getMessage()).append(");");
|
||||
}
|
||||
}
|
||||
|
||||
String redisHost = resolver.getProperty("spring.data.redis.host", "localhost");
|
||||
int redisPort = resolver.getProperty("spring.data.redis.port", Integer.class, 6379);
|
||||
String redisPassword = resolver.getProperty("spring.data.redis.password", "");
|
||||
try {
|
||||
RedisURI.Builder builder = RedisURI.builder()
|
||||
.withHost(redisHost)
|
||||
.withPort(redisPort)
|
||||
.withTimeout(Duration.ofSeconds(3));
|
||||
if (redisPassword != null && !redisPassword.isBlank()) {
|
||||
builder.withPassword(redisPassword.toCharArray());
|
||||
}
|
||||
RedisClient client = RedisClient.create(builder.build());
|
||||
try {
|
||||
StatefulRedisConnection<String, String> connection = client.connect();
|
||||
connection.sync().ping();
|
||||
connection.close();
|
||||
} finally {
|
||||
client.shutdown();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
issues.append("连不上 Redis(").append(e.getMessage()).append(");");
|
||||
}
|
||||
|
||||
if (issues.length() == 0) {
|
||||
available = Boolean.TRUE;
|
||||
problem = null;
|
||||
} else {
|
||||
available = Boolean.FALSE;
|
||||
problem = issues.toString();
|
||||
}
|
||||
return problem;
|
||||
}
|
||||
|
||||
/** 读应用自己那份配置,命令行上的 -D 参数优先级更高,跟应用保持一致 */
|
||||
private static PropertySourcesPropertyResolver resolver() {
|
||||
ConfigurableEnvironment environment = new StandardEnvironment();
|
||||
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
|
||||
for (String name : CONFIG_FILES) {
|
||||
Resource resource = new ClassPathResource(name);
|
||||
if (!resource.exists()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
for (PropertySource<?> source : loader.load(name, resource)) {
|
||||
environment.getPropertySources().addLast(source);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("读配置 {} 失败:{}", name, e.getMessage());
|
||||
}
|
||||
}
|
||||
return new PropertySourcesPropertyResolver(environment.getPropertySources());
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String first, String second) {
|
||||
return first != null && !first.isBlank() ? first : (second == null ? "" : second);
|
||||
}
|
||||
}
|
||||
|
|
@ -120,6 +120,11 @@ export default defineManifestConfig({
|
|||
/* 小程序特有相关 */
|
||||
'mp-weixin': {
|
||||
appid: VITE_WX_APPID,
|
||||
// 仅供开发者工具选择调试基础库版本;线上客户端的最低基础库门槛需在
|
||||
// 微信公众平台「开发管理 → 基础库最低版本设置」中配置(代码里改不动)。
|
||||
// 功能硬性要求:wx.getRandomValues 需基础库 >= 2.17.3,低于该版本的
|
||||
// 线上客户端登录时将收到 fail-closed 报错
|
||||
libVersion: '2.19.4',
|
||||
setting: {
|
||||
urlCheck: false,
|
||||
// 是否启用 ES6 转 ES5
|
||||
|
|
|
|||
|
|
@ -101,7 +101,7 @@
|
|||
"js-cookie": "^3.0.5",
|
||||
"pinia": "2.0.36",
|
||||
"pinia-plugin-persistedstate": "3.2.1",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "0.5.8",
|
||||
"vue": "^3.4.21",
|
||||
"wot-design-uni": "^1.9.1",
|
||||
"z-paging": "2.8.7"
|
||||
|
|
|
|||
29
main/manager-mobile/patches/sm-crypto@0.5.8.patch
Normal file
29
main/manager-mobile/patches/sm-crypto@0.5.8.patch
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
diff --git a/src/sm2/rng.js b/src/sm2/rng.js
|
||||
index c6572c1756579fb100c0d7bdf0cec323971ec211..cdb1f1fcc7d58c52138f6f9fd76240bae5dde5d4 100644
|
||||
--- a/src/sm2/rng.js
|
||||
+++ b/src/sm2/rng.js
|
||||
@@ -54,8 +54,14 @@ function rngSeedTime() {
|
||||
rngSeedInt(new Date().getTime())
|
||||
}
|
||||
|
||||
-// Initialize the pool with junk if needed.
|
||||
-if (rngPool == null) {
|
||||
+// [xiaozhi patch] 熵池初始化从模块加载时推迟到首次取随机字节时(见 rngGetByte)。
|
||||
+// 原因:微信小程序等环境没有同步的 crypto.getRandomValues,模块加载即取熵会直接抛异常;
|
||||
+// 推迟后,调用方可在首次使用前异步准备好真随机源(见 manager-mobile/src/utils/secure-random.ts)。
|
||||
+// fail-closed 语义保持不变:首次取熵时仍要求存在可用的 crypto.getRandomValues,否则抛出异常。
|
||||
+function ensureRngPool() {
|
||||
+ if (rngPool != null)
|
||||
+ return
|
||||
+
|
||||
rngPool = []
|
||||
rngPptr = 0
|
||||
let t
|
||||
@@ -82,6 +88,7 @@ if (rngPool == null) {
|
||||
|
||||
function rngGetByte() {
|
||||
if (rngState == null) {
|
||||
+ ensureRngPool()
|
||||
rngSeedTime()
|
||||
rngState = new Arcfour()
|
||||
rngState.init(rngPool)
|
||||
|
|
@ -11,6 +11,9 @@ patchedDependencies:
|
|||
'@dcloudio/uni-h5':
|
||||
hash: 5763725268e9a493075be3c82d91b590b9ae30e997a04a418494dd7d6d327b9d
|
||||
path: patches/@dcloudio__uni-h5.patch
|
||||
sm-crypto@0.5.8:
|
||||
hash: 62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352
|
||||
path: patches/sm-crypto@0.5.8.patch
|
||||
|
||||
importers:
|
||||
|
||||
|
|
@ -92,8 +95,8 @@ importers:
|
|||
specifier: 3.2.1
|
||||
version: 3.2.1(pinia@2.0.36(typescript@5.7.2)(vue@3.5.15(typescript@5.7.2)))
|
||||
sm-crypto:
|
||||
specifier: ^0.3.13
|
||||
version: 0.3.14
|
||||
specifier: 0.5.8
|
||||
version: 0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352)
|
||||
vue:
|
||||
specifier: ^3.4.21
|
||||
version: 3.5.15(typescript@5.7.2)
|
||||
|
|
@ -6026,8 +6029,8 @@ packages:
|
|||
resolution: {integrity: sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
sm-crypto@0.3.14:
|
||||
resolution: {integrity: sha512-sR7NuGAJH93Om8keAF2/rj1EqFzEiUey4aKGyDo3nQ2BiVqhgq8UkiIoIp5qhV9w4pG7qArhfqyewcG8AbhXbg==}
|
||||
sm-crypto@0.5.8:
|
||||
resolution: {integrity: sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==}
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
|
|
@ -14156,7 +14159,7 @@ snapshots:
|
|||
ansi-styles: 6.2.1
|
||||
is-fullwidth-code-point: 5.0.0
|
||||
|
||||
sm-crypto@0.3.14:
|
||||
sm-crypto@0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352):
|
||||
dependencies:
|
||||
jsbn: 1.1.0
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
packages:
|
||||
- '**'
|
||||
- '!node_modules'
|
||||
|
||||
patchedDependencies:
|
||||
'@dcloudio/uni-h5': patches/@dcloudio__uni-h5.patch
|
||||
sm-crypto@0.5.8: patches/sm-crypto@0.5.8.patch
|
||||
|
|
|
|||
|
|
@ -0,0 +1,136 @@
|
|||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
// #ifdef APP-PLUS
|
||||
import { ensureSecureRandomReady, registerRandomBridge, unregisterRandomBridge } from '@/utils/secure-random'
|
||||
// #endif
|
||||
|
||||
interface BridgeItem {
|
||||
length: number
|
||||
resolve: (bytes: number[]) => void
|
||||
reject: (err: Error) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* App 端专用(页面中 #ifdef APP-PLUS 条件挂载):
|
||||
* 逻辑层无 Web Crypto,经 renderjs 在视图层 WebView 取
|
||||
* crypto.getRandomValues 后 callMethod 回传,注册为 secure-random 的随机源。
|
||||
*/
|
||||
export default defineComponent({
|
||||
data() {
|
||||
return {
|
||||
/** 变化后触发 renderjs 取随机(每次新对象引用确保 prop 变更被感知) */
|
||||
bridgeRequest: null as { id: number, length: number } | null,
|
||||
// 仅类型检查用:renderjs 模块绑定由 uni-app 编译期处理,运行时不读取
|
||||
secureRandomRenderer: { onPropChange: () => {} } as { onPropChange: (...args: any[]) => void },
|
||||
seq: 0,
|
||||
queue: [] as BridgeItem[],
|
||||
sending: false,
|
||||
currentId: 0,
|
||||
timeoutTimer: undefined as ReturnType<typeof setTimeout> | undefined,
|
||||
provider: undefined as ((length: number) => Promise<Uint8Array>) | undefined,
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
// #ifdef APP-PLUS
|
||||
this.provider = (length: number) =>
|
||||
this.requestBytes(length).then(bytes => new Uint8Array(bytes))
|
||||
registerRandomBridge(this.provider)
|
||||
ensureSecureRandomReady().catch((e: Error) => {
|
||||
console.warn('[secure-random] App 端随机源预热失败', e)
|
||||
})
|
||||
// #endif
|
||||
},
|
||||
beforeUnmount() {
|
||||
// #ifdef APP-PLUS
|
||||
// 拒绝队列项并注销,否则销毁后 pending 的 Promise 永不 settle,readyPromise 死锁
|
||||
if (this.provider)
|
||||
unregisterRandomBridge(this.provider)
|
||||
for (const item of this.queue)
|
||||
item.reject(new Error('secure-random-bridge 组件已卸载,随机数请求中止'))
|
||||
this.queue = []
|
||||
this.sending = false
|
||||
// #endif
|
||||
clearTimeout(this.timeoutTimer)
|
||||
},
|
||||
methods: {
|
||||
requestBytes(length: number): Promise<number[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.queue.push({ length, resolve, reject })
|
||||
this.pump()
|
||||
})
|
||||
},
|
||||
/** 串行发送:prop 变更过快时视图层可能丢失中间状态,故一次只发一个请求 */
|
||||
pump() {
|
||||
if (this.sending || this.queue.length === 0)
|
||||
return
|
||||
this.sending = true
|
||||
const item = this.queue[0]
|
||||
this.currentId = ++this.seq
|
||||
this.bridgeRequest = { id: this.currentId, length: item.length }
|
||||
// 超时保护:视图层无响应时按 fail-closed 报错,避免登录流程永久挂起
|
||||
clearTimeout(this.timeoutTimer)
|
||||
this.timeoutTimer = setTimeout(() => {
|
||||
this.onRandomResult({ id: this.currentId, error: 'renderjs 随机数请求超时' })
|
||||
}, 5000)
|
||||
},
|
||||
/** renderjs 通过 callMethod 回传结果(或错误) */
|
||||
onRandomResult(res: { id: number, bytes?: number[], error?: string }) {
|
||||
if (res.id !== this.currentId)
|
||||
return
|
||||
clearTimeout(this.timeoutTimer)
|
||||
const item = this.queue.shift()
|
||||
this.sending = false
|
||||
if (item) {
|
||||
if (res.error)
|
||||
item.reject(new Error(res.error))
|
||||
else
|
||||
item.resolve(res.bytes || [])
|
||||
}
|
||||
this.pump()
|
||||
},
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<script module="secureRandomRenderer" lang="renderjs">
|
||||
// 视图层(WebView):可访问 crypto.getRandomValues
|
||||
export default {
|
||||
methods: {
|
||||
onPropChange(newVal, oldVal, ownerInstance, instance) {
|
||||
if (!newVal || !newVal.id || !newVal.length)
|
||||
return
|
||||
try {
|
||||
const cryptoObj = (typeof crypto !== 'undefined' && crypto)
|
||||
|| (typeof window !== 'undefined' && window.crypto)
|
||||
if (!cryptoObj || typeof cryptoObj.getRandomValues !== 'function')
|
||||
throw new Error('视图层缺少 crypto.getRandomValues')
|
||||
const bytes = new Uint8Array(newVal.length)
|
||||
cryptoObj.getRandomValues(bytes)
|
||||
ownerInstance.callMethod('onRandomResult', { id: newVal.id, bytes: Array.from(bytes) })
|
||||
}
|
||||
catch (e) {
|
||||
ownerInstance.callMethod('onRandomResult', {
|
||||
id: newVal.id,
|
||||
error: String((e && e.message) || e),
|
||||
})
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<view
|
||||
class="secure-random-bridge"
|
||||
:prop="bridgeRequest"
|
||||
:change:prop="secureRandomRenderer.onPropChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.secure-random-bridge {
|
||||
width: 0;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -92,6 +92,7 @@
|
|||
"minified": true
|
||||
},
|
||||
"usingComponents": true,
|
||||
"libVersion": "2.19.4",
|
||||
"optimization": {
|
||||
"subPackages": true
|
||||
},
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import { onLoad } from '@dcloudio/uni-app'
|
|||
import { computed, onMounted, ref } from 'vue'
|
||||
// 导入API接口
|
||||
import { retrievePassword, sendSmsCode } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { initI18n, t } from '@/i18n'
|
||||
import { useConfigStore } from '@/store'
|
||||
|
|
@ -235,7 +239,7 @@ async function handleResetPassword() {
|
|||
try {
|
||||
// 拼接图形验证码和新密码进行加密
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.newPassword
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -305,6 +309,9 @@ onMounted(async () => {
|
|||
class="app-container box-border h-screen w-full"
|
||||
:style="{ paddingTop: `${safeAreaInsets?.top}px` }"
|
||||
>
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="back-button" @click="goBack">
|
||||
<wd-icon name="arrow-left" custom-class="back-icon" />
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import type { LoginData } from '@/api/auth'
|
|||
import type { Language } from '@/store/lang'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { login } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { changeLanguage, getCurrentLanguage, getSupportedLanguages, initI18n, t } from '@/i18n'
|
||||
import { useConfigStore, useUserStore } from '@/store'
|
||||
|
|
@ -202,7 +206,7 @@ async function handleLogin() {
|
|||
try {
|
||||
// 拼接验证码和密码
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.password
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -281,6 +285,9 @@ onMounted(async () => {
|
|||
|
||||
<template>
|
||||
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="logo-section">
|
||||
<wd-img :width="80" :height="80" round src="/static/logo.png" class="logo" />
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@
|
|||
<script lang="ts" setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { register, sendSmsCode } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { initI18n, t } from '@/i18n'
|
||||
import { useConfigStore } from '@/store'
|
||||
|
|
@ -251,7 +255,7 @@ async function handleRegister() {
|
|||
try {
|
||||
// 拼接验证码和密码
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.password
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -325,6 +329,9 @@ onMounted(async () => {
|
|||
|
||||
<template>
|
||||
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="back-button" @click="goBack">
|
||||
<wd-icon name="arrow-left" custom-class="back-icon" />
|
||||
|
|
|
|||
|
|
@ -2,6 +2,21 @@ import smCrypto from 'sm-crypto'
|
|||
import { pages, subPackages } from '@/pages.json'
|
||||
|
||||
import { isMpWeixin } from './platform'
|
||||
import { ensureSecureRandomReady } from './secure-random'
|
||||
|
||||
/**
|
||||
* 获取 sm2 模块(确保密码学安全随机源已就绪)。
|
||||
*
|
||||
* sm-crypto >= 0.5.0(CVE-2026-73567 修复)强制要求 crypto.getRandomValues。
|
||||
* 小程序等环境没有该 API,项目中通过 pnpm patch(patches/sm-crypto@0.5.8.patch)
|
||||
* 将 sm-crypto 的熵池初始化推迟到首次取随机字节时,并由 secure-random.ts 提供
|
||||
* 垫片。因此小程序端首次调用 sm2 前必须 await 本方法,用 wx.getRandomValues
|
||||
* 预热真随机缓冲池;浏览器 / Node 等原生支持 globalThis.crypto 的环境立即就绪。
|
||||
*/
|
||||
async function getSm2(): Promise<typeof smCrypto.sm2> {
|
||||
await ensureSecureRandomReady()
|
||||
return smCrypto.sm2
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行时服务端地址覆盖存储键
|
||||
|
|
@ -201,11 +216,11 @@ export function getEnvBaseUploadUrl() {
|
|||
|
||||
/**
|
||||
* 生成SM2密钥对(十六进制格式)
|
||||
* @returns {object} 包含公钥和私钥的对象
|
||||
* @returns {Promise<object>} 包含公钥和私钥的对象
|
||||
*/
|
||||
export function generateSm2KeyPairHex() {
|
||||
export async function generateSm2KeyPairHex() {
|
||||
// 使用sm-crypto库生成SM2密钥对
|
||||
const sm2 = smCrypto.sm2
|
||||
const sm2 = await getSm2()
|
||||
const keypair = sm2.generateKeyPairHex()
|
||||
|
||||
return {
|
||||
|
|
@ -220,9 +235,9 @@ export function generateSm2KeyPairHex() {
|
|||
* SM2公钥加密
|
||||
* @param {string} publicKey 公钥(十六进制格式)
|
||||
* @param {string} plainText 明文
|
||||
* @returns {string} 加密后的密文(十六进制格式)
|
||||
* @returns {Promise<string>} 加密后的密文(十六进制格式)
|
||||
*/
|
||||
export function sm2Encrypt(publicKey: string, plainText: string): string {
|
||||
export async function sm2Encrypt(publicKey: string, plainText: string): Promise<string> {
|
||||
if (!publicKey) {
|
||||
throw new Error('公钥不能为null或undefined')
|
||||
}
|
||||
|
|
@ -231,7 +246,7 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
|
|||
throw new Error('明文不能为空')
|
||||
}
|
||||
|
||||
const sm2 = smCrypto.sm2
|
||||
const sm2 = await getSm2()
|
||||
// SM2加密,添加04前缀表示未压缩公钥
|
||||
const encrypted = sm2.doEncrypt(plainText, publicKey, 1)
|
||||
// 转换为十六进制格式(与后端保持一致,添加04前缀)
|
||||
|
|
@ -244,10 +259,10 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
|
|||
* SM2私钥解密
|
||||
* @param {string} privateKey 私钥(十六进制格式)
|
||||
* @param {string} cipherText 密文(十六进制格式)
|
||||
* @returns {string} 解密后的明文
|
||||
* @returns {Promise<string>} 解密后的明文(当前项目内暂无调用点,保留备用)
|
||||
*/
|
||||
export function sm2Decrypt(privateKey: string, cipherText: string): string {
|
||||
const sm2 = smCrypto.sm2
|
||||
export async function sm2Decrypt(privateKey: string, cipherText: string): Promise<string> {
|
||||
const sm2 = await getSm2()
|
||||
// 移除04前缀(与后端保持一致)
|
||||
const dataWithoutPrefix = cipherText.startsWith('04') ? cipherText.substring(2) : cipherText
|
||||
// SM2解密
|
||||
|
|
|
|||
206
main/manager-mobile/src/utils/secure-random.ts
Normal file
206
main/manager-mobile/src/utils/secure-random.ts
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
/**
|
||||
* 为 sm-crypto >= 0.5.0 提供 crypto.getRandomValues 兼容层
|
||||
* (0.5.0 起强制要求 CSPRNG,不支持时模块加载即抛异常,见 CVE-2026-73567)。
|
||||
*
|
||||
* 策略:
|
||||
* 1. 经平台异步 CSPRNG API 分块并行取真随机字节,填入同步缓冲池。
|
||||
* 探测顺序 wx → uni → my → tt → swan → ks → qq → jd → lark → xhs;
|
||||
* App 端逻辑层无 CSPRNG,
|
||||
* 由 secure-random-bridge 组件经 renderjs 回传(registerRandomBridge 兜底)。
|
||||
* 2. 垫片同步从缓冲池取字节,池不足即抛错,不回退弱随机(fail-closed)。
|
||||
* 3. sm-crypto 熵池初始化已通过 pnpm patch 推迟到首次取随机
|
||||
* (patches/sm-crypto@0.5.8.patch),首次 sm2 调用前 await
|
||||
* ensureSecureRandomReady() 即可。
|
||||
*
|
||||
* 无任何 CSPRNG 的平台(如支付宝/百度小程序)会 reject,属预期行为。
|
||||
*/
|
||||
const CHUNK_SIZE = 64
|
||||
const CHUNK_COUNT = 8
|
||||
const LOW_WATER_MARK = 128
|
||||
|
||||
// 标记垫片自身,探测时与原生实现区分,避免失败重试被短路成假成功
|
||||
const SHIM_MARKER = Symbol('secureRandomShim')
|
||||
|
||||
// App 端桥接通道,由 secure-random-bridge 组件挂载时注册
|
||||
let bridgeProvider: ((length: number) => Promise<Uint8Array>) | null = null
|
||||
|
||||
export function registerRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
|
||||
bridgeProvider = provider
|
||||
}
|
||||
|
||||
/** 仅当当前注册者仍是该实例时注销,避免多页栈下误清后挂载实例的注册 */
|
||||
export function unregisterRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
|
||||
if (bridgeProvider === provider)
|
||||
bridgeProvider = null
|
||||
}
|
||||
|
||||
let pool: number[] = []
|
||||
let readyPromise: Promise<void> | null = null
|
||||
let refillInFlight = false
|
||||
|
||||
function getGlobalObj(): Record<string, any> | null {
|
||||
// sm-crypto 读取的是 globalThis.crypto,垫片必须装在同一对象上
|
||||
if (typeof globalThis !== 'undefined')
|
||||
return globalThis as unknown as Record<string, any>
|
||||
return null
|
||||
}
|
||||
|
||||
function hasNativeGetRandomValues(): boolean {
|
||||
try {
|
||||
// 探测 globalThis.crypto:Node、h5:ssr 等环境有原生 CSPRNG 但无 window
|
||||
const fn = getGlobalObj()?.crypto?.getRandomValues
|
||||
// 排除垫片自身,否则失败重试会被短路成假成功
|
||||
return typeof fn === 'function' && !(fn as any)[SHIM_MARKER]
|
||||
}
|
||||
catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按优先级探测提供异步 CSPRNG 的平台全局对象。
|
||||
* uni.getRandomValues 仅有声明无实现,故排在 wx 之后兜底;
|
||||
* 其余平台对象未在 TS 类型中声明,经 globalThis 探测,
|
||||
* 对应平台未来实现同名 API 时自动生效。
|
||||
*/
|
||||
function findRandomApi(): { name: string, api: any } | null {
|
||||
const globalObj = getGlobalObj()
|
||||
const candidates: Array<[string, any]> = [
|
||||
['wx', typeof wx !== 'undefined' ? wx : null],
|
||||
['uni', typeof uni !== 'undefined' ? uni : null],
|
||||
['my', globalObj ? globalObj.my : null],
|
||||
['tt', globalObj ? globalObj.tt : null],
|
||||
['swan', globalObj ? globalObj.swan : null],
|
||||
['ks', globalObj ? globalObj.ks : null],
|
||||
['qq', globalObj ? globalObj.qq : null],
|
||||
['jd', globalObj ? globalObj.jd : null],
|
||||
['lark', globalObj ? globalObj.lark : null],
|
||||
['xhs', globalObj ? globalObj.xhs : null],
|
||||
]
|
||||
for (const [name, api] of candidates) {
|
||||
if (api && typeof api.getRandomValues === 'function')
|
||||
return { name, api }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function fetchRandomChunk(length: number): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const found = findRandomApi()
|
||||
if (!found && !bridgeProvider) {
|
||||
reject(new Error(
|
||||
'当前平台不支持获取密码学安全随机数(getRandomValues),无法安全执行 SM2 加密。'
|
||||
+ '当前已适配:微信小程序(wx.getRandomValues)、浏览器、Node 环境、'
|
||||
+ 'App 端(renderjs 桥接,需页面挂载 secure-random-bridge 组件);'
|
||||
+ '其余小程序平台因缺少 CSPRNG API 被按 fail-closed 原则拒绝,'
|
||||
+ '如需支持请扩展 secure-random.ts 的 findRandomApi 适配链。',
|
||||
))
|
||||
return
|
||||
}
|
||||
if (found) {
|
||||
// 平台 API 异常时可能 success/fail 均不回调,超时兜底防止 readyPromise 死锁
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error(`${found.name}.getRandomValues 超时(5s 无响应)`))
|
||||
}, 5000)
|
||||
found.api.getRandomValues({
|
||||
length,
|
||||
success: (res: { randomValues: ArrayBuffer | Uint8Array | number[] }) => {
|
||||
clearTimeout(timer)
|
||||
resolve(new Uint8Array(res.randomValues))
|
||||
},
|
||||
fail: (err: unknown) => {
|
||||
clearTimeout(timer)
|
||||
reject(err instanceof Error ? err : new Error(`getRandomValues 调用失败: ${JSON.stringify(err)}`))
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
bridgeProvider!(length).then(resolve, (err: unknown) => {
|
||||
reject(err instanceof Error ? err : new Error(`renderjs 桥接取随机失败: ${String(err)}`))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function refillPool(totalLength: number): Promise<void> {
|
||||
const chunks = await Promise.all(
|
||||
Array.from({ length: Math.ceil(totalLength / CHUNK_SIZE) }, () => fetchRandomChunk(CHUNK_SIZE)),
|
||||
)
|
||||
for (const chunk of chunks) {
|
||||
for (let i = 0; i < chunk.length; i++)
|
||||
pool.push(chunk[i])
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRefill() {
|
||||
if (refillInFlight)
|
||||
return
|
||||
refillInFlight = true
|
||||
refillPool(256)
|
||||
.catch((err) => {
|
||||
// 补充失败仅告警:池仍够用则无感,耗尽时由 getRandomValues 抛错兜底
|
||||
console.warn('[secure-random] 补充随机数缓冲池失败', err)
|
||||
})
|
||||
.finally(() => {
|
||||
refillInFlight = false
|
||||
})
|
||||
}
|
||||
|
||||
function createGetRandomValues<T extends ArrayBufferView>(array: T): T {
|
||||
// 按字节拷贝,兼容 Uint16Array/Uint32Array 等视图
|
||||
const view = array as unknown as ArrayBufferView
|
||||
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength)
|
||||
if (pool.length < bytes.length) {
|
||||
scheduleRefill()
|
||||
throw new Error('安全随机数缓冲池未就绪或已耗尽,请先等待 ensureSecureRandomReady() 完成')
|
||||
}
|
||||
for (let i = 0; i < bytes.length; i++)
|
||||
bytes[i] = pool[i]
|
||||
pool = pool.slice(bytes.length)
|
||||
if (pool.length < LOW_WATER_MARK)
|
||||
scheduleRefill()
|
||||
return array
|
||||
}
|
||||
|
||||
;(createGetRandomValues as any)[SHIM_MARKER] = true
|
||||
|
||||
function installShim() {
|
||||
const globalObj = getGlobalObj()
|
||||
if (!globalObj)
|
||||
throw new Error('无法获取全局对象,无法安装 crypto.getRandomValues 垫片')
|
||||
|
||||
if (globalObj.crypto && typeof globalObj.crypto.getRandomValues === 'function')
|
||||
return
|
||||
|
||||
if (globalObj.crypto) {
|
||||
// 只补缺的方法,保留宿主 crypto 其他成员;defineProperty 规避只读访问器赋值失败
|
||||
Object.defineProperty(globalObj.crypto, 'getRandomValues', {
|
||||
value: createGetRandomValues,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
else {
|
||||
globalObj.crypto = { getRandomValues: createGetRandomValues }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保密码学安全随机源可用(首次 sm2 调用前必须 await)。
|
||||
* 原生支持的环境直接就绪;缺失环境安装垫片并预热缓冲池;
|
||||
* 无 CSPRNG 的环境 reject,由调用方 fail-closed 处理。
|
||||
*/
|
||||
export function ensureSecureRandomReady(): Promise<void> {
|
||||
if (hasNativeGetRandomValues())
|
||||
return Promise.resolve()
|
||||
if (!readyPromise) {
|
||||
readyPromise = (async () => {
|
||||
installShim()
|
||||
await refillPool(CHUNK_SIZE * CHUNK_COUNT)
|
||||
})().catch((err) => {
|
||||
// 失败后重置,允许后续重试
|
||||
readyPromise = null
|
||||
throw err
|
||||
})
|
||||
}
|
||||
return readyPromise
|
||||
}
|
||||
8
main/manager-web/package-lock.json
generated
8
main/manager-web/package-lock.json
generated
|
|
@ -17,7 +17,7 @@
|
|||
"normalize.css": "^8.0.1",
|
||||
"opus-decoder": "^0.7.7",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "^0.5.8",
|
||||
"v-code-diff": "^1.16.0",
|
||||
"vue": "^2.6.14",
|
||||
"vue-axios": "^3.5.2",
|
||||
|
|
@ -12485,9 +12485,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/sm-crypto": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.3.13.tgz",
|
||||
"integrity": "sha512-ztNF+pZq6viCPMA1A6KKu3bgpkmYti5avykRHbcFIdSipFdkVmfUw2CnpM2kBJyppIalqvczLNM3wR8OQ0pT5w==",
|
||||
"version": "0.5.8",
|
||||
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.5.8.tgz",
|
||||
"integrity": "sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jsbn": "^1.1.0"
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@
|
|||
"normalize.css": "^8.0.1",
|
||||
"opus-decoder": "^0.7.7",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "^0.5.8",
|
||||
"v-code-diff": "^1.16.0",
|
||||
"vue": "^2.6.14",
|
||||
"vue-axios": "^3.5.2",
|
||||
|
|
|
|||
|
|
@ -77,7 +77,11 @@
|
|||
<el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form">
|
||||
<div v-for="(row, rowIndex) in chunkedCallInfoFields" :key="rowIndex" class="form-row">
|
||||
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" style="flex: 1;">
|
||||
<el-input v-if="field.type === 'json-textarea'" v-model="formData.configJson[field.prop]" type="textarea"
|
||||
<el-select v-if="field.type === 'select'" v-model="formData.configJson[field.prop]"
|
||||
:placeholder="field.placeholder" class="custom-input-bg" style="width: 100%">
|
||||
<el-option v-for="opt in field.options" :key="opt" :label="opt" :value="opt"></el-option>
|
||||
</el-select>
|
||||
<el-input v-else-if="field.type === 'json-textarea'" v-model="formData.configJson[field.prop]" type="textarea"
|
||||
:rows="3" :placeholder="field.placeholder" class="custom-input-bg">
|
||||
</el-input>
|
||||
<el-input v-else v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
|
||||
|
|
@ -164,7 +168,8 @@ export default {
|
|||
fields: JSON.parse(item.fields || '[]').map(f => ({
|
||||
label: f.label,
|
||||
prop: f.key,
|
||||
type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : 'text',
|
||||
type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : (f.type === 'select' ? 'select' : 'text'),
|
||||
options: f.options || [],
|
||||
placeholder: `请输入${f.key}`
|
||||
}))
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -81,6 +81,11 @@
|
|||
"></el-input>
|
||||
</template>
|
||||
|
||||
<el-select v-else-if="field.type === 'select'" v-model="form.configJson[field.prop]"
|
||||
:placeholder="field.placeholder" style="width: 100%">
|
||||
<el-option v-for="opt in field.options" :key="opt" :label="opt" :value="opt"></el-option>
|
||||
</el-select>
|
||||
|
||||
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
|
||||
:show-password="field.type === 'password'" @focus="
|
||||
isSensitiveField(field.prop)
|
||||
|
|
@ -312,7 +317,10 @@ export default {
|
|||
? "json-textarea"
|
||||
: f.type === "password"
|
||||
? "password"
|
||||
: "text",
|
||||
: f.type === "select"
|
||||
? "select"
|
||||
: "text",
|
||||
options: f.options || [],
|
||||
placeholder: `请输入${f.key}`,
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -613,6 +613,8 @@ export default {
|
|||
.nav-panel {
|
||||
min-width: 242px;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #ebeef5;
|
||||
background: linear-gradient(
|
||||
120deg,
|
||||
|
|
@ -629,6 +631,7 @@ export default {
|
|||
|
||||
.nav-panel .el-menu-item {
|
||||
height: 50px;
|
||||
flex-shrink: 0;
|
||||
background: #e9f0ff;
|
||||
line-height: 50px;
|
||||
border-radius: 4px 0 0 4px !important;
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ const functionDialogSource = await readFile(
|
|||
new URL('../src/components/FunctionDialog.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const modelConfigSource = await readFile(
|
||||
new URL('../src/views/ModelConfig.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
test('address-book permission state consistently uses the target device MAC', () => {
|
||||
assert.match(
|
||||
|
|
@ -66,6 +70,74 @@ test('correct-word pagination maps the UI page size to the backend limit query',
|
|||
assert.doesNotMatch(correctWordApiSource, /pageSize: params\.pageSize/);
|
||||
});
|
||||
|
||||
test('model navigation keeps its scrollable layout declarations', () => {
|
||||
const navStyles = modelConfigSource.match(/\.nav-panel\s*\{([^}]*)\}/)?.[1];
|
||||
const itemStyles = modelConfigSource.match(
|
||||
/\.nav-panel\s+\.el-menu-item\s*\{([^}]*)\}/,
|
||||
)?.[1];
|
||||
|
||||
assert.ok(navStyles, 'model navigation should define its layout');
|
||||
assert.ok(itemStyles, 'model menu items should define their layout');
|
||||
const wrapperStyles = modelConfigSource.match(/\.main-wrapper\s*\{([^}]*)\}/)?.[1];
|
||||
assert.ok(wrapperStyles, 'model page wrapper should define its height');
|
||||
|
||||
assert.match(navStyles, /box-sizing:\s*border-box;/);
|
||||
assert.match(navStyles, /overflow-y:\s*auto;/);
|
||||
assert.match(navStyles, /display:\s*flex;/);
|
||||
assert.match(navStyles, /flex-direction:\s*column;/);
|
||||
assert.match(itemStyles, /flex-shrink:\s*0;/);
|
||||
assert.match(wrapperStyles, /height:\s*calc\([^)]*vh[^)]*\)/);
|
||||
|
||||
// 断言只取第一条同名规则,后面再补一条就能盖掉上面三条,必须挡住
|
||||
assert.equal(
|
||||
(modelConfigSource.match(/\.nav-panel\s*\{/g) || []).length,
|
||||
1,
|
||||
'model navigation should keep a single rule',
|
||||
);
|
||||
assert.equal(
|
||||
(modelConfigSource.match(/\.nav-panel\s+\.el-menu-item\s*\{/g) || []).length,
|
||||
1,
|
||||
'model menu items should keep a single rule',
|
||||
);
|
||||
// 复合选择器特异性更高,能直接盖掉可滚属性
|
||||
assert.equal(
|
||||
(modelConfigSource.match(/\.nav-panel[.:\[#][^{}]*\{/g) || []).length,
|
||||
0,
|
||||
'model navigation should not use composite selectors',
|
||||
);
|
||||
|
||||
const styleSource = modelConfigSource.match(/<style[^>]*>([\s\S]*?)<\/style>/)?.[1];
|
||||
assert.ok(styleSource, 'model config should define its styles');
|
||||
const ruleSelectors = styleSource
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/\/\/[^\n]*/g, '')
|
||||
.split('}')
|
||||
.map((chunk) => {
|
||||
const open = chunk.indexOf('{');
|
||||
return open < 0 ? null : chunk.slice(0, open).trim();
|
||||
})
|
||||
.filter((selector) => selector && !selector.startsWith('@'));
|
||||
|
||||
// 上面几条挡不住带伪类的后代选择器(.nav-panel .el-menu-item:hover),
|
||||
// 它特异性一样更高,照样能盖掉可滚属性,所以把 nav 相关的选择器逐条列出来核对
|
||||
assert.deepEqual(
|
||||
ruleSelectors.filter((selector) => selector.includes('.nav-panel')).sort(),
|
||||
[
|
||||
'.nav-panel',
|
||||
'.nav-panel .el-menu-item',
|
||||
'.nav-panel .el-menu-item.is-active',
|
||||
'.nav-panel .el-menu-item.is-active::before',
|
||||
'::v-deep .nav-panel .el-menu-item.is-active .menu-text',
|
||||
].sort(),
|
||||
'model navigation should keep its declared rules',
|
||||
);
|
||||
assert.deepEqual(
|
||||
ruleSelectors.filter((selector) => selector.includes('.main-wrapper')),
|
||||
['.main-wrapper'],
|
||||
'model page wrapper should keep a single rule',
|
||||
);
|
||||
});
|
||||
|
||||
test('function dialog footer stays above the expanding MCP tools section', () => {
|
||||
const mcpLayer = functionDialogSource.match(
|
||||
/\.mcp-access-point\s*\{[^}]*z-index:\s*(\d+);/s,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ from core.http_server import SimpleHttpServer
|
|||
from core.websocket_server import WebSocketServer
|
||||
from core.utils.util import check_ffmpeg_installed
|
||||
from core.utils.gc_manager import get_gc_manager
|
||||
from core.handle.helloHandle import preheat_wakeup_audio_cache
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
|
@ -64,6 +65,9 @@ async def main():
|
|||
# 添加 stdin 监控任务
|
||||
stdin_task = asyncio.create_task(monitor_stdin())
|
||||
|
||||
# 预热唤醒词音频编码缓存,让首条连接就命中
|
||||
asyncio.create_task(preheat_wakeup_audio_cache())
|
||||
|
||||
# 启动全局GC管理器(5分钟清理一次)
|
||||
gc_manager = get_gc_manager(interval_seconds=300)
|
||||
await gc_manager.start()
|
||||
|
|
|
|||
|
|
@ -119,6 +119,10 @@ wakeup_words:
|
|||
# MCP接入点地址,地址格式为:ws://你的mcp接入点ip或者域名:端口号/mcp/?token=你的token
|
||||
# 详细教程 https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md
|
||||
mcp_endpoint: 你的接入点 websocket地址
|
||||
# 声纹识别到说话人后,是否把身份附在 MCP 接入点 tools/call 的 params._meta 上。
|
||||
# true:写入 speakerId、speakerName。未识别到说话人时不附带,请求与原来一致。
|
||||
# 工具参数本身不改。false:完全不附带。
|
||||
mcp_forward_speaker: true
|
||||
|
||||
# 上下文源配置
|
||||
# 用于在系统提示词中注入动态数据,如健康数据、股票信息等
|
||||
|
|
@ -172,18 +176,20 @@ plugins:
|
|||
# ragflow知识库id
|
||||
dataset_ids: ["123456789"]
|
||||
# 联网搜索插件配置
|
||||
# 支持秘塔(metaso)、Tavily和Serply三个搜索源
|
||||
# 支持秘塔(metaso)、Tavily、Serply、Outcrawl和SpecStream五个搜索源
|
||||
# 秘塔API Key申请:https://metaso.cn/search-api/api-keys
|
||||
# Tavily API Key申请:https://app.tavily.com/home
|
||||
# Serply API Key申请:https://serply.io
|
||||
# Outcrawl API Key申请:https://outcrawl.ai
|
||||
# SpecStream API Key申请:https://specstream.ai/signup?src=xiaozhi-esp32-server
|
||||
web_search:
|
||||
# 搜索源:metaso / tavily / serply
|
||||
# 搜索源:metaso / tavily / serply / outcrawl / specstream
|
||||
provider: "metaso"
|
||||
# 工具描述,用于告知LLM何时调用此工具,可根据需要自定义
|
||||
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
|
||||
# 返回结果数量(默认5)
|
||||
max_results: 5
|
||||
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key
|
||||
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key / SpecStream API Key
|
||||
api_key: "mk-xxx"
|
||||
# 声纹识别配置
|
||||
voiceprint:
|
||||
|
|
@ -398,8 +404,8 @@ ASR:
|
|||
# DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
|
||||
# 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
|
||||
type: doubao
|
||||
appid: 你的火山引擎语音合成服务appid
|
||||
access_token: 你的火山引擎语音合成服务access_token
|
||||
appid: 你的火山引擎语音识别服务appid
|
||||
access_token: 你的火山引擎语音识别服务access_token
|
||||
cluster: volcengine_input_common
|
||||
# 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
|
||||
boosting_table_name: (选填)你的热词文件名称
|
||||
|
|
@ -412,8 +418,8 @@ ASR:
|
|||
# 开通地址https://console.volcengine.com/speech/service/10011
|
||||
# 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
|
||||
type: doubao_stream
|
||||
appid: 你的火山引擎语音合成服务appid
|
||||
access_token: 你的火山引擎语音合成服务access_token
|
||||
appid: 你的火山引擎语音识别服务appid
|
||||
access_token: 你的火山引擎语音识别服务access_token
|
||||
# 资源ID:小时版 volc.bigasr.sauc.duration,并发版 volc.bigasr.sauc.concurrent
|
||||
resource_id: volc.bigasr.sauc.duration
|
||||
# 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
|
||||
|
|
@ -432,8 +438,8 @@ ASR:
|
|||
# 开通地址:https://console.volcengine.com/speech/service/10038
|
||||
# 价格更为便宜,建议在高并发场景下使用
|
||||
type: doubao_stream
|
||||
appid: 你的火山引擎语音合成服务appid
|
||||
access_token: 你的火山引擎语音合成服务access_token
|
||||
appid: 你的火山引擎语音识别服务appid
|
||||
access_token: 你的火山引擎语音识别服务access_token
|
||||
# 资源ID:小时版 volc.seedasr.sauc.duration,并发版 volc.seedasr.sauc.concurrent
|
||||
resource_id: volc.seedasr.sauc.duration
|
||||
# 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
|
||||
|
|
@ -451,9 +457,9 @@ ASR:
|
|||
# token申请地址:https://console.cloud.tencent.com/cam/capi
|
||||
# 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle
|
||||
type: tencent
|
||||
appid: 你的腾讯语音合成服务appid
|
||||
secret_id: 你的腾讯语音合成服务secret_id
|
||||
secret_key: 你的腾讯语音合成服务secret_key
|
||||
appid: 你的腾讯语音识别服务appid
|
||||
secret_id: 你的腾讯语音识别服务secret_id
|
||||
secret_key: 你的腾讯语音识别服务secret_key
|
||||
output_dir: tmp/
|
||||
AliyunASR:
|
||||
# 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
|
||||
|
|
@ -619,11 +625,15 @@ LLM:
|
|||
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
||||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||
model_name: qwen-flash
|
||||
api_key: 你的deepseek web key
|
||||
api_key: 你的阿里云百炼API密钥
|
||||
temperature: 0.7 # 温度值
|
||||
max_tokens: 500 # 最大生成token数
|
||||
top_p: 1
|
||||
frequency_penalty: 0 # 频率惩罚
|
||||
# 可选: chat_template_kwargs 仅供 vLLM/SGLang 等自托管 OpenAI 兼容后端使用(请求级控制 chat template, 例如思考开关)
|
||||
# 注意: DashScope 等云服务不支持此字段, 请勿在 AliLLM 等云服务配置段启用; 此处示例仅作参数格式参考
|
||||
# chat_template_kwargs:
|
||||
# enable_thinking: true
|
||||
AliAppLLM:
|
||||
# 定义LLM API类型
|
||||
type: AliBL
|
||||
|
|
@ -666,6 +676,7 @@ LLM:
|
|||
type: ollama
|
||||
model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
|
||||
base_url: http://localhost:11434 # Ollama服务地址
|
||||
api_key: ollama # 本地部署无需真实密钥,占位即可;走鉴权网关或Ollama Cloud时修改为真实key
|
||||
DifyLLM:
|
||||
# 定义LLM API类型
|
||||
type: dify
|
||||
|
|
@ -763,10 +774,14 @@ VLLM:
|
|||
# 先新建应用,在下面的地址
|
||||
# 开通应用地址:https://console.xfyun.cn/app/myapp
|
||||
# 有免费额度,但也要开通服务,才能获取api_key
|
||||
# 每一个模型都需要单独开通,每一个模型的api_password都不同,例如Lite模型在https://console.xfyun.cn/services/cbm 开通
|
||||
base_url: https://ark.cn-beijing.volces.com/api/v3
|
||||
# 每一个模型都需要单独开通,每一个模型的 api_key 都不同,例如 Lite 模型在 https://console.xfyun.cn/services/cbm 开通
|
||||
# 讯飞星火的 OpenAI 兼容端点,可用模型名(lite / 4.0Ultra 等)见
|
||||
# https://www.xfyun.cn/doc/spark/HTTP调用文档.html
|
||||
# 注意 base_url 必须指向讯飞自己的域名。这里曾误填成火山方舟的
|
||||
# ark.cn-beijing.volces.com,会把讯飞的 api_key 发给火山引擎。
|
||||
base_url: https://spark-api-open.xf-yun.com/v1
|
||||
model_name: lite
|
||||
api_key: 你的api_password
|
||||
api_key: 你的api_key
|
||||
TTS:
|
||||
# 当前支持的type为edge、doubao,可自行适配
|
||||
EdgeTTS:
|
||||
|
|
@ -1117,8 +1132,8 @@ TTS:
|
|||
#SpeechServerDemo https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/demos/speech_server
|
||||
#流式传输请参考 https://github.com/PaddlePaddle/PaddleSpeech/wiki/PaddleSpeech-Server-WebSocket-API
|
||||
type: paddle_speech
|
||||
protocol: websocket # protocol choices = ['websocket', 'http']
|
||||
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming,http默认http://127.0.0.1:8090/paddlespeech/tts]
|
||||
protocol: websocket # 当前仅实现 websocket;填其他值会在启动时报错
|
||||
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务地址(未配置时代码兜底同此本机地址)
|
||||
spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
|
||||
speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
|
||||
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
|||
from config.logger import setup_logging, build_module_string, create_connection_logger
|
||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException, generate_and_save_chat_title
|
||||
from core.utils.prompt_manager import PromptManager
|
||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||
from core.utils.voiceprint_provider import VoiceprintProvider, UNKNOWN_SPEAKER_NAME
|
||||
from core.utils.util import get_system_error_response
|
||||
from core.utils import textUtils
|
||||
|
||||
|
|
@ -158,7 +158,7 @@ class ConnectionHandler:
|
|||
# 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
|
||||
self.asr_audio = [] # 存储PCM帧列表,供VAD和ASR共享
|
||||
self.asr_audio_queue = queue.Queue()
|
||||
self.current_speaker = None # 存储当前说话人
|
||||
self.current_speaker = None # 当前说话人展示名
|
||||
self.introduced_speakers = set() # 已"首次引入"的说话人,控制只在首轮带名字
|
||||
self.system_introduced_speakers = set() # 已在 system 注入过身份的说话人,控制 system 身份只首轮出现
|
||||
|
||||
|
|
@ -781,7 +781,7 @@ class ConnectionHandler:
|
|||
self.voiceprint_provider = voiceprint_provider
|
||||
self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整")
|
||||
self.logger.bind(tag=TAG).debug("声纹识别功能启用但配置不完整")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).info("声纹识别功能未启用")
|
||||
except Exception as e:
|
||||
|
|
@ -916,6 +916,8 @@ class ConnectionHandler:
|
|||
self.chat_history_conf = int(private_config["chat_history_conf"])
|
||||
if private_config.get("mcp_endpoint", None) is not None:
|
||||
self.config["mcp_endpoint"] = private_config["mcp_endpoint"]
|
||||
if private_config.get("mcp_forward_speaker", None) is not None:
|
||||
self.config["mcp_forward_speaker"] = private_config["mcp_forward_speaker"]
|
||||
if private_config.get("context_providers", None) is not None:
|
||||
self.config["context_providers"] = private_config["context_providers"]
|
||||
|
||||
|
|
@ -1052,7 +1054,8 @@ class ConnectionHandler:
|
|||
# 更新系统prompt至上下文
|
||||
self.dialogue.update_system_message(self.prompt)
|
||||
|
||||
def chat(self, query, depth=0):
|
||||
def chat(self, query, depth=0, speaker=None):
|
||||
# speaker: 本轮声纹身份快照,随工具调用下传
|
||||
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
|
||||
current_sentence_id = None
|
||||
|
||||
|
|
@ -1121,8 +1124,20 @@ class ConnectionHandler:
|
|||
# 仅在该说话人首次出现时把身份注入 system,之后靠对话历史首轮保留,
|
||||
# 避免每轮在 system 重复出现名字诱导模型反复称呼
|
||||
speaker_for_system = None
|
||||
cs = (self.current_speaker or "").strip()
|
||||
if cs and cs != "未知说话人" and cs not in self.system_introduced_speakers:
|
||||
# 展示名只取本轮数据(声纹快照 → query JSON),不读并发下会被覆盖的连接态
|
||||
cs = ""
|
||||
if speaker is not None:
|
||||
cs = (speaker.name or "").strip()
|
||||
if not cs and depth == 0 and query:
|
||||
q = query.strip()
|
||||
if q.startswith("{") and q.endswith("}"):
|
||||
try:
|
||||
parsed = json.loads(q)
|
||||
if isinstance(parsed, dict):
|
||||
cs = str(parsed.get("speaker") or "").strip()
|
||||
except (json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
if cs and cs != UNKNOWN_SPEAKER_NAME and cs not in self.system_introduced_speakers:
|
||||
self.system_introduced_speakers.add(cs)
|
||||
speaker_for_system = cs
|
||||
|
||||
|
|
@ -1337,7 +1352,7 @@ class ConnectionHandler:
|
|||
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.func_handler.handle_llm_function_call(
|
||||
self, tool_call_data
|
||||
self, tool_call_data, speaker=speaker
|
||||
),
|
||||
self.loop,
|
||||
)
|
||||
|
|
@ -1369,7 +1384,7 @@ class ConnectionHandler:
|
|||
|
||||
# 统一处理工具调用结果
|
||||
if tool_results:
|
||||
self._handle_function_result(tool_results, depth=depth, streamed_text=streamed_text)
|
||||
self._handle_function_result(tool_results, depth=depth, streamed_text=streamed_text, speaker=speaker)
|
||||
|
||||
# 存储对话内容
|
||||
if len(response_message) > 0:
|
||||
|
|
@ -1394,7 +1409,7 @@ class ConnectionHandler:
|
|||
|
||||
return True
|
||||
|
||||
def _handle_function_result(self, tool_results, depth, streamed_text=""):
|
||||
def _handle_function_result(self, tool_results, depth, streamed_text="", speaker=None):
|
||||
need_llm_tools = []
|
||||
record_tools = []
|
||||
|
||||
|
|
@ -1500,7 +1515,7 @@ class ConnectionHandler:
|
|||
)
|
||||
)
|
||||
|
||||
self.chat(None, depth=depth + 1)
|
||||
self.chat(None, depth=depth + 1, speaker=speaker)
|
||||
|
||||
def _report_worker(self):
|
||||
"""聊天记录上报工作线程"""
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import uuid
|
|||
import random
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
from config.logger import setup_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
|
|
@ -13,9 +14,14 @@ from core.providers.tts.dto.dto import SentenceType
|
|||
from core.utils.wakeup_word import WakeupWordsConfig
|
||||
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
||||
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
||||
from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
|
||||
from core.providers.tools.device_mcp import (
|
||||
MCPClient,
|
||||
send_mcp_initialize_message,
|
||||
send_mcp_tools_list_request,
|
||||
)
|
||||
|
||||
TAG = __name__
|
||||
_wakeup_logger = setup_logging()
|
||||
|
||||
WAKEUP_CONFIG = {
|
||||
"refresh_time": 10,
|
||||
|
|
@ -63,6 +69,8 @@ async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
|
|||
# The device waits for the server hello before processing MCP messages.
|
||||
if features and features.get("mcp"):
|
||||
asyncio.create_task(send_mcp_initialize_message(conn))
|
||||
# 并发预发 tools/list,让帧排在 audio 流之前到达 client
|
||||
asyncio.create_task(send_mcp_tools_list_request(conn))
|
||||
|
||||
|
||||
async def checkWakeupWords(conn: "ConnectionHandler", text):
|
||||
|
|
@ -105,19 +113,19 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
|
|||
}
|
||||
|
||||
# 获取音频数据
|
||||
opus_packets = await audio_to_data(response.get("file_path"), use_cache=False)
|
||||
opus_packets = await audio_to_data(response.get("file_path"), use_cache=True)
|
||||
# 播放唤醒词回复
|
||||
conn.client_abort = False
|
||||
|
||||
# 将唤醒词回复视为新会话,生成新的 sentence_id,确保流控器重置
|
||||
conn.sentence_id = str(uuid.uuid4().hex)
|
||||
|
||||
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
|
||||
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
|
||||
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
||||
|
||||
# 补充对话
|
||||
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
|
||||
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
|
||||
|
||||
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
|
||||
asyncio.create_task(_finish_wakeup_reply(conn))
|
||||
|
||||
# 检查是否需要更新唤醒词回复
|
||||
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
||||
|
|
@ -126,6 +134,16 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
|
|||
return True
|
||||
|
||||
|
||||
async def _finish_wakeup_reply(conn: "ConnectionHandler"):
|
||||
"""等音频队列清空后再发 stop(时序:全部音频帧→stop),期间不阻塞接收循环"""
|
||||
try:
|
||||
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"唤醒词回复收尾失败: {e}")
|
||||
|
||||
|
||||
async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
||||
if not conn.tts:
|
||||
return
|
||||
|
|
@ -160,7 +178,32 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
|||
f.write(wav_bytes)
|
||||
# 更新配置
|
||||
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
||||
# 覆写文件后 mtime 变化使旧缓存失效,此处立刻预编码新文件,
|
||||
# 下次唤醒直接命中缓存,编码成本不占用唤醒响应路径
|
||||
await audio_to_data(file_path, use_cache=True)
|
||||
finally:
|
||||
# 确保在任何情况下都释放锁
|
||||
if _wakeup_response_lock.locked():
|
||||
_wakeup_response_lock.release()
|
||||
|
||||
|
||||
async def preheat_wakeup_audio_cache():
|
||||
"""进程启动时预热唤醒词音频编码缓存
|
||||
|
||||
把 wakeup_words/{voice}.wav 在 Opus 编码结果一次性算好塞进全局 cache,
|
||||
后续每条连接上来就能直接命中,省掉 wav→PCM→Opus 的数百毫秒开销。
|
||||
"""
|
||||
# 进程启动时 tts 还未初始化,无法拿到 conn.tts.voice,按常见 fallback 列表预热
|
||||
preheat_voices = ["default", "female-shaonv", "male-qn-jingying"]
|
||||
fallback_path = "config/assets/wakeup_words_short.wav"
|
||||
for voice in preheat_voices:
|
||||
file_path = fallback_path
|
||||
try:
|
||||
response = wakeup_words_config.get_wakeup_response(voice)
|
||||
if response and response.get("file_path"):
|
||||
file_path = response["file_path"]
|
||||
await audio_to_data(file_path, use_cache=True)
|
||||
except Exception as e:
|
||||
_wakeup_logger.bind(tag=TAG).warning(
|
||||
f"预热 voice={voice} 失败: {e}"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
|
|||
TAG = __name__
|
||||
|
||||
|
||||
async def handle_user_intent(conn: "ConnectionHandler", text):
|
||||
async def handle_user_intent(conn: "ConnectionHandler", text, speaker=None):
|
||||
# 预处理输入文本,处理可能的JSON格式
|
||||
try:
|
||||
if text.strip().startswith("{") and text.strip().endswith("}"):
|
||||
|
|
@ -47,7 +47,7 @@ async def handle_user_intent(conn: "ConnectionHandler", text):
|
|||
# 会话开始时生成sentence_id
|
||||
conn.sentence_id = str(uuid.uuid4().hex)
|
||||
# 处理各种意图
|
||||
return await process_intent_result(conn, intent_result, text)
|
||||
return await process_intent_result(conn, intent_result, text, speaker=speaker)
|
||||
|
||||
|
||||
async def check_direct_exit(conn: "ConnectionHandler", text):
|
||||
|
|
@ -81,7 +81,7 @@ async def analyze_intent_with_llm(conn: "ConnectionHandler", text):
|
|||
|
||||
|
||||
async def process_intent_result(
|
||||
conn: "ConnectionHandler", intent_result, original_text
|
||||
conn: "ConnectionHandler", intent_result, original_text, speaker=None
|
||||
):
|
||||
"""处理意图识别结果"""
|
||||
try:
|
||||
|
|
@ -172,7 +172,7 @@ async def process_intent_result(
|
|||
try:
|
||||
result = asyncio.run_coroutine_threadsafe(
|
||||
conn.func_handler.handle_llm_function_call(
|
||||
conn, function_call_data
|
||||
conn, function_call_data, speaker=speaker
|
||||
),
|
||||
conn.loop,
|
||||
).result(timeout=tool_call_timeout)
|
||||
|
|
|
|||
|
|
@ -40,7 +40,8 @@ async def resume_vad_detection(conn: "ConnectionHandler"):
|
|||
conn.just_woken_up = False
|
||||
|
||||
|
||||
async def startToChat(conn: "ConnectionHandler", text):
|
||||
async def startToChat(conn: "ConnectionHandler", text, speaker=None):
|
||||
"""speaker: 本轮声纹身份快照,随调用链传递。"""
|
||||
# 检查输入是否是JSON格式(包含说话人信息)
|
||||
speaker_name = None
|
||||
actual_text = text
|
||||
|
|
@ -69,11 +70,8 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
# 如果解析失败,继续使用原始文本
|
||||
pass
|
||||
|
||||
# 保存说话人信息到连接对象
|
||||
if speaker_name:
|
||||
conn.current_speaker = speaker_name
|
||||
else:
|
||||
conn.current_speaker = None
|
||||
# 说话人名供提示词注入;声纹身份走 speaker 快照,不挂连接
|
||||
conn.current_speaker = speaker_name
|
||||
|
||||
if conn.need_bind:
|
||||
await check_bind_device(conn)
|
||||
|
|
@ -92,7 +90,7 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
await handleAbortMessage(conn)
|
||||
|
||||
# 首先进行意图分析,使用实际文本内容
|
||||
intent_handled = await handle_user_intent(conn, actual_text)
|
||||
intent_handled = await handle_user_intent(conn, actual_text, speaker=speaker)
|
||||
|
||||
if intent_handled:
|
||||
# 如果意图已被处理,不再进行聊天
|
||||
|
|
@ -104,7 +102,7 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
# 准备开始新会话
|
||||
conn.client_abort = False
|
||||
|
||||
conn.executor.submit(conn.chat, actual_text)
|
||||
conn.executor.submit(conn.chat, actual_text, depth=0, speaker=speaker)
|
||||
|
||||
|
||||
async def no_voice_close_connect(conn: "ConnectionHandler", have_voice):
|
||||
|
|
|
|||
|
|
@ -12,10 +12,8 @@ from core.providers.tts.dto.dto import SentenceType
|
|||
from core.utils.audioRateController import AudioRateController
|
||||
|
||||
TAG = __name__
|
||||
# 音频帧时长(毫秒)
|
||||
AUDIO_FRAME_DURATION = 60
|
||||
# 预缓冲包数量,直接发送以减少延迟
|
||||
PRE_BUFFER_COUNT = 5
|
||||
AUDIO_FRAME_DURATION = 60 # 音频帧时长(毫秒),与 Opus 编码 60ms/帧对齐
|
||||
PRE_BUFFER_COUNT = 2 # 首段发送时不入队的帧数,避免流控延迟拉高首帧到达时间
|
||||
|
||||
|
||||
async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text, sentence_id=None):
|
||||
|
|
|
|||
|
|
@ -106,8 +106,8 @@ class ListenTextMessageHandler(TextMessageHandler):
|
|||
elif is_wakeup_words:
|
||||
conn.just_woken_up = True
|
||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||
enqueue_asr_report(conn, "嘿,你好呀", [])
|
||||
await startToChat(conn, "嘿,你好呀")
|
||||
enqueue_asr_report(conn, filtered_text, [])
|
||||
await startToChat(conn, filtered_text)
|
||||
else:
|
||||
conn.just_woken_up = True
|
||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ from core.providers.asr.dto.dto import InterfaceType
|
|||
from core.handle.receiveAudioHandle import startToChat
|
||||
from core.handle.reportHandle import enqueue_asr_report
|
||||
from core.utils.util import remove_punctuation_and_length
|
||||
from core.utils.voiceprint_provider import SpeakerIdentification
|
||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||
from typing import Optional, Tuple, List, NamedTuple, TYPE_CHECKING
|
||||
|
||||
|
|
@ -101,7 +102,7 @@ class ASRProviderBase(ABC):
|
|||
)
|
||||
|
||||
if conn.voiceprint_provider and wav_data:
|
||||
voiceprint_task = conn.voiceprint_provider.identify_speaker(
|
||||
voiceprint_task = conn.voiceprint_provider.identify_speaker_detail(
|
||||
wav_data, conn.session_id
|
||||
)
|
||||
# 并发等待两个结果
|
||||
|
|
@ -119,11 +120,11 @@ class ASRProviderBase(ABC):
|
|||
else:
|
||||
raw_text, _ = asr_result
|
||||
|
||||
speaker_name = ""
|
||||
if isinstance(voiceprint_result, Exception):
|
||||
logger.bind(tag=TAG).error(f"声纹识别失败: {voiceprint_result}")
|
||||
speaker_name = ""
|
||||
else:
|
||||
speaker_name = voiceprint_result
|
||||
elif voiceprint_result is not None:
|
||||
speaker_name = voiceprint_result.name or ""
|
||||
|
||||
# 判断 ASR 结果类型
|
||||
if isinstance(raw_text, dict):
|
||||
|
|
@ -164,10 +165,16 @@ class ASRProviderBase(ABC):
|
|||
self.stop_ws_connection()
|
||||
|
||||
if text_len > 0:
|
||||
# 本轮声纹身份快照,随调用链供 MCP 接入点工具使用
|
||||
speaker = (
|
||||
voiceprint_result
|
||||
if isinstance(voiceprint_result, SpeakerIdentification)
|
||||
else None
|
||||
)
|
||||
audio_snapshot = asr_audio_task.copy()
|
||||
enqueue_asr_report(conn, enhanced_text, audio_snapshot)
|
||||
# 使用自定义模块进行上报
|
||||
await startToChat(conn, enhanced_text)
|
||||
await startToChat(conn, enhanced_text, speaker=speaker)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||
import traceback
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ if TYPE_CHECKING:
|
|||
from core.connection import ConnectionHandler
|
||||
from ..base import IntentProviderBase
|
||||
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 core.utils.util import get_system_error_response
|
||||
import re
|
||||
|
|
@ -181,16 +182,11 @@ class IntentProvider(IntentProviderBase):
|
|||
music_file_names = music_config["music_file_names"]
|
||||
prompt_music = f"{self.promot}\n<musicNames>{music_file_names}\n</musicNames>"
|
||||
|
||||
home_assistant_cfg = conn.config["plugins"].get("home_assistant")
|
||||
if home_assistant_cfg:
|
||||
devices = home_assistant_cfg.get("devices", [])
|
||||
else:
|
||||
devices = []
|
||||
if len(devices) > 0:
|
||||
plugin_config = _hass_plugin_config(conn.config.get("plugins", {}))
|
||||
devices_text = _devices_text(plugin_config.get("devices", ""))
|
||||
if devices_text:
|
||||
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
|
||||
for device in devices:
|
||||
hass_prompt += device + "\n"
|
||||
prompt_music += hass_prompt
|
||||
prompt_music += hass_prompt + devices_text + "\n"
|
||||
|
||||
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
from config.logger import setup_logging
|
||||
from openai import OpenAI
|
||||
from urllib.parse import urlsplit
|
||||
import json
|
||||
from core.providers.llm.base import LLMProviderBase
|
||||
|
||||
|
|
@ -10,15 +11,20 @@ logger = setup_logging()
|
|||
class LLMProvider(LLMProviderBase):
|
||||
def __init__(self, config):
|
||||
self.model_name = config.get("model_name")
|
||||
self.base_url = config.get("base_url", "http://localhost:11434")
|
||||
self.base_url = (
|
||||
str(config.get("base_url") or "").strip() or "http://localhost:11434"
|
||||
).rstrip("/")
|
||||
# 兼容处理用户输入完整端点的情况
|
||||
if self.base_url.endswith("/chat/completions"):
|
||||
self.base_url = self.base_url[:-len("/chat/completions")].rstrip("/")
|
||||
# Initialize OpenAI client with Ollama base URL
|
||||
# 如果没有v1,增加v1
|
||||
if not self.base_url.endswith("/v1"):
|
||||
# 纯主机地址补/v1(Ollama默认约定);带路径的地址尊重用户输入,不再改写
|
||||
if not urlsplit(self.base_url).path.strip("/"):
|
||||
self.base_url = f"{self.base_url}/v1"
|
||||
|
||||
self.client = OpenAI(
|
||||
base_url=self.base_url,
|
||||
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
|
||||
api_key=config.get("api_key") or "ollama",
|
||||
)
|
||||
|
||||
# 检查是否是qwen3模型
|
||||
|
|
|
|||
|
|
@ -16,13 +16,28 @@ THINKING_DISABLED_DOMAINS = {
|
|||
"bigmodel.cn": {"thinking": {"type": "disabled"}},
|
||||
"moonshot.cn": {"thinking": {"type": "disabled"}},
|
||||
"volces.com": {"thinking": {"type": "disabled"}},
|
||||
"modelarts-maas.com": {"thinking": {"type": "disabled"}},
|
||||
}
|
||||
|
||||
# 域名规则的模型名豁免表: 强制思考模型不接受该参数注入(如 MaaS glm-5.3 传 thinking 必 400)
|
||||
THINKING_DISABLED_MODEL_EXCLUSIONS = {
|
||||
"modelarts-maas.com": ("glm-5.3",),
|
||||
}
|
||||
|
||||
|
||||
class LLMProvider(LLMProviderBase):
|
||||
def __init__(self, config):
|
||||
self.model_name = config.get("model_name")
|
||||
# 可选实例级思考强度: off/disabled/none/disable | low/medium/high | 空/其他=按域名默认
|
||||
self.thinking_mode = str(config.get("thinking") or "").strip().lower()
|
||||
self.api_key = config.get("api_key")
|
||||
# 可选: 透传给后端的 chat_template_kwargs(供 vLLM/SGLang 等自托管 OpenAI 兼容后端使用)
|
||||
chat_template_kwargs = config.get("chat_template_kwargs")
|
||||
if chat_template_kwargs and not isinstance(chat_template_kwargs, dict):
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"chat_template_kwargs 配置格式错误, 应为键值对象, 已忽略: {chat_template_kwargs!r}")
|
||||
chat_template_kwargs = None
|
||||
self.chat_template_kwargs = chat_template_kwargs or {}
|
||||
if "base_url" in config:
|
||||
self.base_url = config.get("base_url")
|
||||
else:
|
||||
|
|
@ -80,14 +95,39 @@ class LLMProvider(LLMProviderBase):
|
|||
return dialogue
|
||||
|
||||
def _apply_thinking_disabled(self, request_params: dict):
|
||||
"""根据域名自动禁用思考模式"""
|
||||
"""思考模式控制: 实例配置(thinking)优先, 否则按域名默认表"""
|
||||
mode = getattr(self, "thinking_mode", "")
|
||||
if mode in ("keep", "passthrough", "default"):
|
||||
# 不干预: 既不发 thinking 参数也不查域名表(适用于强制思考/拒绝该参数的模型, 如 MaaS glm-5.3)
|
||||
return
|
||||
if mode in ("off", "disabled", "none", "disable"):
|
||||
request_params.setdefault("extra_body", {}).update({"thinking": {"type": "disabled"}})
|
||||
logger.bind(tag=TAG).info("思考强度=off: 已禁用思考模式(实例配置)")
|
||||
return
|
||||
if mode in ("low", "medium", "high"):
|
||||
request_params.setdefault("extra_body", {}).update(
|
||||
{"reasoning_effort": mode, "thinking": {"type": "enabled"}})
|
||||
logger.bind(tag=TAG).info(f"思考强度={mode}: reasoning_effort 已设置(实例配置)")
|
||||
return
|
||||
parsed_url = urlparse(self.base_url)
|
||||
domain = parsed_url.netloc
|
||||
model_name = (self.model_name or "").lower()
|
||||
for disabled_domain, params in THINKING_DISABLED_DOMAINS.items():
|
||||
if disabled_domain in domain:
|
||||
request_params.setdefault("extra_body", {}).update(params)
|
||||
logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
|
||||
if disabled_domain not in domain:
|
||||
continue
|
||||
exclusions = THINKING_DISABLED_MODEL_EXCLUSIONS.get(disabled_domain, ())
|
||||
if any(ex in model_name for ex in exclusions):
|
||||
logger.bind(tag=TAG).info(
|
||||
f"域名 {domain} 命中禁思考规则, 但模型 {self.model_name} 强制思考且拒绝该参数, 跳过注入")
|
||||
break
|
||||
request_params.setdefault("extra_body", {}).update(params)
|
||||
logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
|
||||
break
|
||||
|
||||
def _apply_chat_template_kwargs(self, request_params: dict):
|
||||
"""透传 chat_template_kwargs 到 extra_body(仅 vLLM/SGLang 等自托管 OpenAI 兼容后端识别, 云服务会忽略)"""
|
||||
if self.chat_template_kwargs:
|
||||
request_params.setdefault("extra_body", {})["chat_template_kwargs"] = self.chat_template_kwargs
|
||||
|
||||
def response(self, session_id, dialogue, **kwargs):
|
||||
dialogue = self.normalize_dialogue(dialogue)
|
||||
|
|
@ -112,6 +152,7 @@ class LLMProvider(LLMProviderBase):
|
|||
|
||||
# 禁用思考模式
|
||||
self._apply_thinking_disabled(request_params)
|
||||
self._apply_chat_template_kwargs(request_params)
|
||||
|
||||
responses = self.client.chat.completions.create(**request_params)
|
||||
|
||||
|
|
@ -158,6 +199,7 @@ class LLMProvider(LLMProviderBase):
|
|||
|
||||
# 禁用思考模式
|
||||
self._apply_thinking_disabled(request_params)
|
||||
self._apply_chat_template_kwargs(request_params)
|
||||
|
||||
stream = self.client.chat.completions.create(**request_params)
|
||||
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ class ToolExecutor(ABC):
|
|||
|
||||
@abstractmethod
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行工具调用"""
|
||||
"""执行工具调用。speaker: 可选的说话人身份快照。"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class DeviceIoTExecutor(ToolExecutor):
|
|||
self.iot_tools: Dict[str, ToolDefinition] = {}
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行设备端IoT工具"""
|
||||
if not self.has_tool(tool_name):
|
||||
|
|
|
|||
|
|
@ -17,7 +17,11 @@ class MCPClient:
|
|||
self.name_mapping = {}
|
||||
self.ready = False
|
||||
self.call_results = {} # To store Futures for tool call responses
|
||||
self.next_id = 1
|
||||
# Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in mcp_handler.
|
||||
# JSON-RPC 2.0 forbids reusing request ids on the same connection, and
|
||||
# compliant device MCP servers reject tools/call with id 1/2 (see #3461).
|
||||
# Official protocol sequence expects the first tools/call to use id=3.
|
||||
self.next_id = 3
|
||||
self.lock = asyncio.Lock()
|
||||
self._cached_available_tools = None # Cache for get_available_tools
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
|||
self.conn = conn
|
||||
|
||||
async def execute(
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行设备端MCP工具"""
|
||||
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@
|
|||
import json
|
||||
import asyncio
|
||||
import re
|
||||
from concurrent.futures import Future
|
||||
from core.utils.util import get_vision_url, sanitize_tool_name
|
||||
from core.utils.util import get_vision_url
|
||||
from core.utils.auth import AuthToken
|
||||
from config.logger import setup_logging
|
||||
from .mcp_client import MCPClient
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -15,91 +15,6 @@ if TYPE_CHECKING:
|
|||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class MCPClient:
|
||||
"""设备端MCP客户端,用于管理MCP状态和工具"""
|
||||
|
||||
def __init__(self):
|
||||
self.tools = {} # sanitized_name -> tool_data
|
||||
self.name_mapping = {}
|
||||
self.ready = False
|
||||
self.call_results = {} # To store Futures for tool call responses
|
||||
self.next_id = 1
|
||||
self.lock = asyncio.Lock()
|
||||
self._cached_available_tools = None # Cache for get_available_tools
|
||||
|
||||
def has_tool(self, name: str) -> bool:
|
||||
return name in self.tools
|
||||
|
||||
def get_available_tools(self) -> list:
|
||||
# Check if the cache is valid
|
||||
if self._cached_available_tools is not None:
|
||||
return self._cached_available_tools
|
||||
|
||||
# If cache is not valid, regenerate the list
|
||||
result = []
|
||||
for tool_name, tool_data in self.tools.items():
|
||||
function_def = {
|
||||
"name": tool_name,
|
||||
"description": tool_data["description"],
|
||||
"parameters": {
|
||||
"type": tool_data["inputSchema"].get("type", "object"),
|
||||
"properties": tool_data["inputSchema"].get("properties", {}),
|
||||
"required": tool_data["inputSchema"].get("required", []),
|
||||
},
|
||||
}
|
||||
result.append({"type": "function", "function": function_def})
|
||||
|
||||
self._cached_available_tools = result # Store the generated list in cache
|
||||
return result
|
||||
|
||||
async def is_ready(self) -> bool:
|
||||
async with self.lock:
|
||||
return self.ready
|
||||
|
||||
async def set_ready(self, status: bool):
|
||||
async with self.lock:
|
||||
self.ready = status
|
||||
|
||||
async def add_tool(self, tool_data: dict):
|
||||
async with self.lock:
|
||||
sanitized_name = sanitize_tool_name(tool_data["name"])
|
||||
self.tools[sanitized_name] = tool_data
|
||||
self.name_mapping[sanitized_name] = tool_data["name"]
|
||||
self._cached_available_tools = (
|
||||
None # Invalidate the cache when a tool is added
|
||||
)
|
||||
|
||||
async def get_next_id(self) -> int:
|
||||
async with self.lock:
|
||||
current_id = self.next_id
|
||||
self.next_id += 1
|
||||
return current_id
|
||||
|
||||
async def register_call_result_future(self, id: int, future: Future):
|
||||
async with self.lock:
|
||||
self.call_results[id] = future
|
||||
|
||||
async def resolve_call_result(self, id: int, result: any):
|
||||
async with self.lock:
|
||||
if id in self.call_results:
|
||||
future = self.call_results.pop(id)
|
||||
if not future.done():
|
||||
future.set_result(result)
|
||||
|
||||
async def reject_call_result(self, id: int, exception: Exception):
|
||||
async with self.lock:
|
||||
if id in self.call_results:
|
||||
future = self.call_results.pop(id)
|
||||
if not future.done():
|
||||
future.set_exception(exception)
|
||||
|
||||
async def cleanup_call_result(self, id: int):
|
||||
async with self.lock:
|
||||
if id in self.call_results:
|
||||
self.call_results.pop(id)
|
||||
|
||||
|
||||
async def send_mcp_message(conn: "ConnectionHandler", payload: dict):
|
||||
"""Helper to send MCP messages, encapsulating common logic."""
|
||||
if not conn.features.get("mcp"):
|
||||
|
|
@ -147,11 +62,6 @@ async def handle_mcp_message(
|
|||
logger.bind(tag=TAG).debug(
|
||||
f"客户端MCP服务器信息: name={name}, version={version}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(1)
|
||||
logger.bind(tag=TAG).debug("初始化完成,开始请求MCP工具列表")
|
||||
await send_mcp_tools_list_request(conn)
|
||||
|
||||
return
|
||||
|
||||
elif msg_id == 2: # mcpToolsListID
|
||||
|
|
|
|||
|
|
@ -18,7 +18,9 @@ class MCPEndpointClient:
|
|||
self.name_mapping = {}
|
||||
self.ready = False
|
||||
self.call_results = {} # To store Futures for tool call responses
|
||||
self.next_id = 1
|
||||
# Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in
|
||||
# mcp_endpoint_handler; tools/call must start at 3 to avoid id reuse.
|
||||
self.next_id = 3
|
||||
self.lock = asyncio.Lock()
|
||||
self._cached_available_tools = None # Cache for get_available_tools
|
||||
self.websocket = None # WebSocket连接
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
"""MCP接入点工具执行器"""
|
||||
|
||||
from typing import Dict, Any
|
||||
from typing import Dict, Any, Optional
|
||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||
from plugins_func.register import Action, ActionResponse
|
||||
from core.utils.voiceprint_provider import SpeakerIdentification
|
||||
from .mcp_endpoint_handler import call_mcp_endpoint_tool
|
||||
from .mcp_speaker import should_forward_speaker, speaker_call_meta
|
||||
|
||||
|
||||
class MCPEndpointExecutor(ToolExecutor):
|
||||
|
|
@ -13,9 +15,9 @@ class MCPEndpointExecutor(ToolExecutor):
|
|||
self.conn = conn
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker: Optional[SpeakerIdentification] = None
|
||||
) -> ActionResponse:
|
||||
"""执行MCP接入点工具"""
|
||||
"""执行MCP接入点工具。speaker: 本轮说话人快照。"""
|
||||
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
|
||||
return ActionResponse(
|
||||
action=Action.ERROR,
|
||||
|
|
@ -29,14 +31,20 @@ class MCPEndpointExecutor(ToolExecutor):
|
|||
)
|
||||
|
||||
try:
|
||||
# 转换参数为JSON字符串
|
||||
# 转换参数为JSON字符串。说话人身份不写入参数,只放在 _meta。
|
||||
import json
|
||||
|
||||
meta = None
|
||||
if speaker is not None and should_forward_speaker(
|
||||
getattr(conn, "config", None)
|
||||
):
|
||||
meta = speaker_call_meta(speaker.speaker_id, speaker.name)
|
||||
|
||||
args_str = json.dumps(arguments) if arguments else "{}"
|
||||
|
||||
# 调用MCP接入点工具
|
||||
result = await call_mcp_endpoint_tool(
|
||||
conn.mcp_endpoint_client, tool_name, args_str
|
||||
conn.mcp_endpoint_client, tool_name, args_str, meta=meta
|
||||
)
|
||||
|
||||
resultJson = None
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import re
|
|||
import websockets
|
||||
from config.logger import setup_logging
|
||||
from .mcp_endpoint_client import MCPEndpointClient
|
||||
from .mcp_speaker import build_mcp_endpoint_tool_payload
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
|
@ -284,7 +285,11 @@ async def send_mcp_endpoint_tools_list_continue(
|
|||
|
||||
|
||||
async def call_mcp_endpoint_tool(
|
||||
mcp_client: MCPEndpointClient, tool_name: str, args: str = "{}", timeout: int = 30
|
||||
mcp_client: MCPEndpointClient,
|
||||
tool_name: str,
|
||||
args: str = "{}",
|
||||
timeout: int = 30,
|
||||
meta: dict = None,
|
||||
):
|
||||
"""
|
||||
调用指定的MCP接入点工具,并等待响应
|
||||
|
|
@ -350,16 +355,17 @@ async def call_mcp_endpoint_tool(
|
|||
raise e
|
||||
|
||||
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
||||
payload = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": tool_call_id,
|
||||
"method": "tools/call",
|
||||
"params": {"name": actual_name, "arguments": arguments},
|
||||
}
|
||||
payload = build_mcp_endpoint_tool_payload(
|
||||
tool_call_id, actual_name, arguments, meta
|
||||
)
|
||||
|
||||
message = json.dumps(payload)
|
||||
log_suffix = ""
|
||||
if meta:
|
||||
# 只记是否附带身份及字段名,不输出 speakerId/speakerName 明文
|
||||
log_suffix = f",_meta: 附带身份字段 {list(meta.keys())}"
|
||||
logger.bind(tag=TAG).info(
|
||||
f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}"
|
||||
f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}{log_suffix}"
|
||||
)
|
||||
await mcp_client.send_message(message)
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
"""把已识别的说话人附到 MCP 接入点 tools/call 上。
|
||||
|
||||
工具参数保持模型给出的原样。身份放在 MCP 的 params._meta 里,
|
||||
接入点上的服务可以读取,不读的服务按协议忽略。
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from core.utils.voiceprint_provider import UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
def should_forward_speaker(config: Optional[dict]) -> bool:
|
||||
"""mcp_forward_speaker 缺省为开启。显式 false 时不附带身份。"""
|
||||
if not isinstance(config, dict):
|
||||
return True
|
||||
value = config.get("mcp_forward_speaker", True)
|
||||
if value is None:
|
||||
return True
|
||||
return str(value).strip().lower() in ("true", "1", "yes")
|
||||
|
||||
|
||||
def speaker_call_meta(speaker_id: Any, speaker_name: Any) -> Optional[Dict[str, str]]:
|
||||
"""有真实身份时返回 _meta;没有则返回 None,调用方不写这个字段。"""
|
||||
meta: Dict[str, str] = {}
|
||||
if isinstance(speaker_id, str):
|
||||
speaker_id = speaker_id.strip()
|
||||
if speaker_id:
|
||||
meta["speakerId"] = speaker_id
|
||||
if isinstance(speaker_name, str):
|
||||
speaker_name = speaker_name.strip()
|
||||
if speaker_name and speaker_name != UNKNOWN_SPEAKER_NAME:
|
||||
meta["speakerName"] = speaker_name
|
||||
return meta or None
|
||||
|
||||
|
||||
def build_mcp_endpoint_tool_payload(
|
||||
tool_call_id: int,
|
||||
name: str,
|
||||
arguments: Dict[str, Any],
|
||||
meta: Optional[Dict[str, str]] = None,
|
||||
) -> dict:
|
||||
"""组装 tools/call。meta 为空时不出现 _meta,参数字典原样放进 arguments。"""
|
||||
params: Dict[str, Any] = {"name": name, "arguments": arguments}
|
||||
if meta:
|
||||
params["_meta"] = meta
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": tool_call_id,
|
||||
"method": "tools/call",
|
||||
"params": params,
|
||||
}
|
||||
|
|
@ -107,7 +107,7 @@ class ServerMCPClient:
|
|||
"function": {
|
||||
"name": name,
|
||||
"description": tool.description,
|
||||
"parameters": tool.inputSchema,
|
||||
"parameters": tool.input_schema,
|
||||
},
|
||||
}
|
||||
for name, tool in self.tools_dict.items()
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class ServerMCPExecutor(ToolExecutor):
|
|||
await self.mcp_manager.initialize_servers()
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行服务端MCP工具"""
|
||||
if not self._initialized or not self.mcp_manager:
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ class ServerMCPManager:
|
|||
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
|
||||
if not os.path.exists(self.config_path):
|
||||
self.config_path = ""
|
||||
logger.bind(tag=TAG).warning(
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
|
||||
)
|
||||
self.clients: Dict[str, ServerMCPClient] = {}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
"""服务端插件工具执行器"""
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Dict, Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -8,6 +10,10 @@ if TYPE_CHECKING:
|
|||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||
from plugins_func.register import all_function_registry, module_func_map, Action, ActionResponse
|
||||
|
||||
# 插件专用线程池:不用 asyncio 默认池(DNS 解析、ASR、initialize_modules 等都在用),
|
||||
# 避免慢插件打满默认池后拖垮所有协程的 DNS 解析和连接建立。
|
||||
_PLUGIN_POOL = ThreadPoolExecutor(max_workers=8, thread_name_prefix="plugin")
|
||||
|
||||
|
||||
class ServerPluginExecutor(ToolExecutor):
|
||||
"""服务端插件工具执行器"""
|
||||
|
|
@ -17,7 +23,7 @@ class ServerPluginExecutor(ToolExecutor):
|
|||
self.config = conn.config
|
||||
|
||||
async def execute(
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行服务端插件工具"""
|
||||
func_item = all_function_registry.get(tool_name)
|
||||
|
|
@ -28,23 +34,21 @@ class ServerPluginExecutor(ToolExecutor):
|
|||
|
||||
try:
|
||||
# 根据工具类型决定如何调用
|
||||
if hasattr(func_item, "type"):
|
||||
func_type = func_item.type
|
||||
if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (需要conn参数)
|
||||
result = func_item.func(conn, **arguments)
|
||||
elif func_type.code == 2: # WAIT
|
||||
result = func_item.func(**arguments)
|
||||
elif func_type.code == 3: # CHANGE_SYS_PROMPT
|
||||
result = func_item.func(conn, **arguments)
|
||||
else:
|
||||
result = func_item.func(**arguments)
|
||||
else:
|
||||
# 默认不传conn参数
|
||||
result = func_item.func(**arguments)
|
||||
func_type = getattr(func_item, "type", None)
|
||||
if func_type is not None and func_type.code in [3, 4, 5]:
|
||||
# CHANGE_SYS_PROMPT, SYSTEM_CTL, IOT_CTL (需要conn参数)
|
||||
call = functools.partial(func_item.func, conn, **arguments)
|
||||
else: # WAIT 等不传conn(含 type 未指定的插件)
|
||||
call = functools.partial(func_item.func, **arguments)
|
||||
|
||||
# 兼容 async def 工具函数
|
||||
if asyncio.iscoroutine(result):
|
||||
result = await result
|
||||
if asyncio.iscoroutinefunction(func_item.func):
|
||||
result = await call()
|
||||
else:
|
||||
# 同步函数在 loop 线程上直接执行会卡住整个事件循环,放专用线程池。
|
||||
result = await asyncio.get_running_loop().run_in_executor(_PLUGIN_POOL, call)
|
||||
# 兼容同步函数返回协程的写法
|
||||
if asyncio.iscoroutine(result):
|
||||
result = await result
|
||||
|
||||
return result
|
||||
|
||||
|
|
|
|||
|
|
@ -137,16 +137,16 @@ class UnifiedToolHandler:
|
|||
return self.tool_manager.has_tool(tool_name)
|
||||
|
||||
async def handle_llm_function_call(
|
||||
self, conn, function_call_data: Dict[str, Any]
|
||||
self, conn, function_call_data: Dict[str, Any], speaker=None
|
||||
) -> Optional[ActionResponse]:
|
||||
"""处理LLM函数调用"""
|
||||
"""处理LLM函数调用。speaker: 本轮说话人快照。"""
|
||||
try:
|
||||
# 处理多函数调用
|
||||
if "function_calls" in function_call_data:
|
||||
responses = []
|
||||
for call in function_call_data["function_calls"]:
|
||||
result = await self.tool_manager.execute_tool(
|
||||
call["name"], call.get("arguments", {})
|
||||
call["name"], call.get("arguments", {}), speaker=speaker
|
||||
)
|
||||
responses.append(result)
|
||||
return self._combine_responses(responses)
|
||||
|
|
@ -175,7 +175,9 @@ class UnifiedToolHandler:
|
|||
self.logger.warning(f"发送工具调用显示消息失败: {e}")
|
||||
|
||||
# 执行工具调用
|
||||
result = await self.tool_manager.execute_tool(function_name, arguments)
|
||||
result = await self.tool_manager.execute_tool(
|
||||
function_name, arguments, speaker=speaker
|
||||
)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
|
|
|||
|
|
@ -47,9 +47,12 @@ class ToolManager:
|
|||
return all_tools
|
||||
|
||||
def get_function_descriptions(self) -> List[Dict[str, Any]]:
|
||||
"""获取所有工具的函数描述(OpenAI格式)"""
|
||||
"""获取所有工具的函数描述(OpenAI格式)
|
||||
|
||||
返回缓存的浅拷贝,防止调用方就地修改污染缓存。
|
||||
"""
|
||||
if self._cached_function_descriptions is not None:
|
||||
return self._cached_function_descriptions
|
||||
return list(self._cached_function_descriptions)
|
||||
|
||||
descriptions = []
|
||||
tools = self.get_all_tools()
|
||||
|
|
@ -57,7 +60,7 @@ class ToolManager:
|
|||
descriptions.append(tool_definition.description)
|
||||
|
||||
self._cached_function_descriptions = descriptions
|
||||
return descriptions
|
||||
return list(descriptions)
|
||||
|
||||
def has_tool(self, tool_name: str) -> bool:
|
||||
"""检查是否存在指定工具"""
|
||||
|
|
@ -71,9 +74,9 @@ class ToolManager:
|
|||
return tool_def.tool_type if tool_def else None
|
||||
|
||||
async def execute_tool(
|
||||
self, tool_name: str, arguments: Dict[str, Any]
|
||||
self, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行工具调用"""
|
||||
"""执行工具调用。speaker: 本轮说话人快照。"""
|
||||
try:
|
||||
# 查找工具类型
|
||||
tool_type = self.get_tool_type(tool_name)
|
||||
|
|
@ -93,7 +96,7 @@ class ToolManager:
|
|||
|
||||
# 执行工具
|
||||
self.logger.info(f"执行工具: {tool_name},参数: {arguments}")
|
||||
result = await executor.execute(self.conn, tool_name, arguments)
|
||||
result = await executor.execute(self.conn, tool_name, arguments, speaker=speaker)
|
||||
self.logger.debug(f"工具执行结果: {result}")
|
||||
return result
|
||||
|
||||
|
|
|
|||
|
|
@ -74,7 +74,11 @@ class TTSProvider(TTSProviderBase):
|
|||
"""确保WebSocket连接可用,支持60秒内连接复用"""
|
||||
try:
|
||||
current_time = time.time()
|
||||
if self.ws and current_time - self.last_active_time < 60:
|
||||
if (
|
||||
self.ws
|
||||
and self.ws.close_code is None
|
||||
and current_time - self.last_active_time < 60
|
||||
):
|
||||
# 一分钟内才可以复用链接进行连续对话
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||
return self.ws
|
||||
|
|
@ -110,10 +114,11 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.conn.client_abort:
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||
|
|
@ -132,21 +137,27 @@ class TTSProvider(TTSProviderBase):
|
|||
self.reset_stream_state()
|
||||
# 初始化会话
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -174,6 +185,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -194,20 +216,23 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务进行合成"""
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning("WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
# 过滤Markdown
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
continue_task_message = {
|
||||
"header": {
|
||||
"action": "continue-task",
|
||||
|
|
@ -237,9 +262,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 确保连接可用
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -248,6 +270,9 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
# 发送run-task消息启动会话
|
||||
run_task_message = {
|
||||
"header": {
|
||||
|
|
@ -350,9 +375,6 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
# 只处理当前活跃会话的响应
|
||||
if task_id and self.conn.sentence_id != task_id:
|
||||
if event in ["task-finished", "task-failed"]:
|
||||
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
|
||||
self.activate_session = False
|
||||
continue
|
||||
|
||||
if event == "task-started":
|
||||
|
|
@ -376,6 +398,7 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).error(
|
||||
f"TTS任务失败: {error_code} - {error_message}"
|
||||
)
|
||||
self.activate_session = False
|
||||
break
|
||||
except json.JSONDecodeError:
|
||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
||||
|
|
@ -392,16 +415,14 @@ class TTSProvider(TTSProviderBase):
|
|||
)
|
||||
break
|
||||
|
||||
# 连接异常时关闭WebSocket
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def audio_to_opus_data_stream(
|
||||
|
|
|
|||
|
|
@ -186,7 +186,11 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
||||
self._refresh_token()
|
||||
current_time = time.time()
|
||||
if self.ws and current_time - self.last_active_time < 10:
|
||||
if (
|
||||
self.ws
|
||||
and self.ws.close_code is None
|
||||
and current_time - self.last_active_time < 10
|
||||
):
|
||||
# 10秒内才可以复用链接进行连续对话
|
||||
self.task_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接..., task_id: {self.task_id}")
|
||||
|
|
@ -220,12 +224,17 @@ class TTSProvider(TTSProviderBase):
|
|||
message = self.tts_text_queue.get(timeout=1)
|
||||
|
||||
if self.conn.client_abort:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.task_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||
continue
|
||||
|
||||
# 过滤旧消息:检查sentence_id是否匹配
|
||||
if message.sentence_id != self.conn.sentence_id:
|
||||
|
|
@ -240,18 +249,24 @@ class TTSProvider(TTSProviderBase):
|
|||
self.reset_stream_state()
|
||||
# 初始化参数
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.task_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -278,6 +293,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.task_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -296,18 +322,22 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
async def text_to_speak(self, text, _):
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.task_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
run_request = {
|
||||
"header": {
|
||||
"message_id": uuid.uuid4().hex,
|
||||
|
|
@ -339,9 +369,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 建立新连接
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -350,6 +377,9 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
start_request = {
|
||||
"header": {
|
||||
"message_id": uuid.uuid4().hex,
|
||||
|
|
@ -431,9 +461,6 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
# 只处理当前活跃会话的响应
|
||||
if task_id and self.task_id != task_id:
|
||||
if event_name in ["SynthesisCompleted", "TaskFailed"]:
|
||||
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
|
||||
self.activate_session = False
|
||||
continue
|
||||
|
||||
if event_name == "SynthesisStarted":
|
||||
|
|
@ -469,16 +496,15 @@ class TTSProvider(TTSProviderBase):
|
|||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
||||
)
|
||||
break
|
||||
# 连接异常时关闭WebSocket
|
||||
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def audio_to_opus_data_stream(
|
||||
|
|
|
|||
|
|
@ -704,3 +704,6 @@ class TTSProviderBase(ABC):
|
|||
def reset_stream_state(self):
|
||||
"""重置流式处理状态,用于会话开始时清理残留状态"""
|
||||
self._pending_prefix = ""
|
||||
# 清理编码器中未满一帧的PCM残留
|
||||
if getattr(self, "opus_encoder", None):
|
||||
self.opus_encoder.reset_state()
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@ class TTSProvider(TTSProviderBase):
|
|||
async def _ensure_connection(self):
|
||||
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
|
||||
try:
|
||||
if self.ws:
|
||||
if self.ws and self.ws.close_code is None:
|
||||
if self.enable_ws_reuse:
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||
return self.ws
|
||||
|
|
@ -281,12 +281,12 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.conn.client_abort:
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
if self.enable_ws_reuse:
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.cancel_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
else:
|
||||
if not self.enable_ws_reuse:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_connection(),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -307,26 +307,29 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.FIRST:
|
||||
# 重置流式处理状态
|
||||
self.reset_stream_state()
|
||||
# 重置 opus 流式编码器跨轮残留
|
||||
if hasattr(self, "opus_encoder") and self.opus_encoder:
|
||||
self.opus_encoder.reset_state()
|
||||
# 初始化参数
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -353,11 +356,29 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if self.activate_session:
|
||||
# 结束会话;LAST 与连接释放由监听任务在 SessionFinished 后处理
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
else:
|
||||
# 未开启会话,没有 SessionFinished 事件,需自行收尾
|
||||
self._process_before_stop_play_files()
|
||||
if not self.enable_ws_reuse:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
||||
continue
|
||||
|
|
@ -373,21 +394,23 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务"""
|
||||
try:
|
||||
# 建立新连接
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
# 过滤Markdown
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
await self.send_text(self.voice, txt, self.conn.sentence_id)
|
||||
|
||||
return
|
||||
|
|
@ -407,12 +430,11 @@ class TTSProvider(TTSProviderBase):
|
|||
# 上个会话处于激活状态时关闭上个连接新建链接
|
||||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
|
||||
# 确保连接建立
|
||||
await self._ensure_connection()
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
header = Header(
|
||||
message_type=FULL_CLIENT_REQUEST,
|
||||
|
|
@ -437,9 +459,6 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
|
||||
try:
|
||||
if self.ws:
|
||||
# 句尾替换词滑动窗口残留先发出去
|
||||
if self._pending_prefix:
|
||||
await self.text_to_speak(self._pending_prefix, None)
|
||||
header = Header(
|
||||
message_type=FULL_CLIENT_REQUEST,
|
||||
message_type_specific_flags=MsgTypeFlagWithEvent,
|
||||
|
|
|
|||
|
|
@ -23,9 +23,11 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__(config, delete_audio_file)
|
||||
self.url = config.get("url", "ws://192.168.1.10:8092/paddlespeech/tts/streaming")
|
||||
self.url = config.get("url", "ws://127.0.0.1:8092/paddlespeech/tts/streaming")
|
||||
self.protocol = config.get("protocol", "websocket")
|
||||
|
||||
if self.protocol != "websocket":
|
||||
raise ValueError("Unsupported protocol. Please use 'websocket'.")
|
||||
|
||||
if config.get("private_voice"):
|
||||
self.spk_id = int(config.get("private_voice"))
|
||||
else:
|
||||
|
|
@ -82,7 +84,7 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.protocol == "websocket":
|
||||
return await self.text_streaming(text, output_file)
|
||||
else:
|
||||
raise ValueError("Unsupported protocol. Please use 'websocket' or 'http'.")
|
||||
raise ValueError("Unsupported protocol. Please use 'websocket'.")
|
||||
|
||||
async def text_streaming(self, text, output_file):
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -127,7 +127,7 @@ class TTSProvider(TTSProviderBase):
|
|||
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
|
||||
|
||||
async def _ensure_connection(self):
|
||||
"""确保WebSocket连接可用"""
|
||||
"""建立新的WebSocket连接"""
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始建立新连接...")
|
||||
|
||||
|
|
@ -176,24 +176,14 @@ class TTSProvider(TTSProviderBase):
|
|||
self.text_seq += 1
|
||||
|
||||
if message.sentence_type == SentenceType.FIRST:
|
||||
# 初始化参数
|
||||
# 初始化参数,连接在文本到达时建立
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS状态失败: {str(e)}")
|
||||
|
||||
# 处理文本内容
|
||||
if ContentType.TEXT == message.content_type:
|
||||
|
|
@ -224,6 +214,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -242,19 +243,22 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务进行合成"""
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
# 发送文本合成请求
|
||||
run_request = self._build_base_request(status=1, text=txt)
|
||||
await self.ws.send(json.dumps(run_request))
|
||||
|
|
@ -277,9 +281,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 建立新连接
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -288,10 +289,15 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 发送会话启动请求
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
# 启动帧序号从1开始,避免与后续文本帧重复
|
||||
self.text_seq = 1
|
||||
start_request = self._build_base_request(status=0)
|
||||
|
||||
await self.ws.send(json.dumps(start_request))
|
||||
self.text_seq += 1
|
||||
logger.bind(tag=TAG).debug("会话启动请求已发送")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
||||
|
|
@ -412,16 +418,14 @@ class TTSProvider(TTSProviderBase):
|
|||
)
|
||||
break
|
||||
|
||||
# 链接不可复用
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def to_tts(self, text: str) -> list:
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import re
|
|||
from typing import List, Dict
|
||||
from datetime import datetime
|
||||
|
||||
from core.utils.voiceprint_provider import UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
class Message:
|
||||
def __init__(
|
||||
|
|
@ -125,7 +127,7 @@ class Dialogue:
|
|||
current_speaker_name = (current_speaker or "").strip()
|
||||
# 仅在本轮注入了有效身份时才输出 speakers_info,避免列表里的名字每轮
|
||||
# 重复出现诱导模型反复称呼;后续轮不再注入身份,靠对话历史首轮保留
|
||||
if current_speaker_name and current_speaker_name != "未知说话人":
|
||||
if current_speaker_name and current_speaker_name != UNKNOWN_SPEAKER_NAME:
|
||||
speakers = voiceprint_config.get("speakers", [])
|
||||
speakers_info = "\n<speakers_info>"
|
||||
speakers_info += f"\n当前说话人:{current_speaker_name}"
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
|
||||
import os
|
||||
import asyncio
|
||||
import hashlib
|
||||
import threading
|
||||
from typing import Dict, Any, TYPE_CHECKING
|
||||
|
||||
|
|
@ -120,8 +121,9 @@ class PromptManager:
|
|||
|
||||
# 使用传入的提示词并缓存(如果有设备ID)
|
||||
if device_id:
|
||||
device_cache_key = f"device_prompt:{device_id}"
|
||||
self.cache_manager.set(self.CacheType.DEVICE_PROMPT, device_cache_key, user_prompt)
|
||||
self.cache_manager.set(
|
||||
self.CacheType.DEVICE_PROMPT, device_cache_key, user_prompt
|
||||
)
|
||||
self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存")
|
||||
|
||||
self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...")
|
||||
|
|
@ -253,6 +255,18 @@ class PromptManager:
|
|||
if not self.base_prompt_template:
|
||||
return user_prompt
|
||||
|
||||
# 缓存键须覆盖所有渲染输入:emoji 开关、设备 prompt 变更否则会命中过期提示词
|
||||
emoji_enabled = kwargs.get("emoji_enabled", True)
|
||||
prompt_hash = hashlib.md5(user_prompt.encode("utf-8")).hexdigest()[:8]
|
||||
enhanced_cache_key = (
|
||||
f"enhanced_prompt:{device_id}:{emoji_enabled}:{prompt_hash}"
|
||||
)
|
||||
cached_prompt = self.cache_manager.get(
|
||||
self.CacheType.DEVICE_PROMPT, enhanced_cache_key
|
||||
)
|
||||
if cached_prompt is not None:
|
||||
return cached_prompt
|
||||
|
||||
try:
|
||||
# 获取最新的时间信息(不缓存)
|
||||
today_date, today_weekday, lunar_date = self._get_current_time_info()
|
||||
|
|
@ -301,11 +315,13 @@ class PromptManager:
|
|||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
device_cache_key = f"device_prompt:{device_id}"
|
||||
self.cache_manager.set(
|
||||
self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt
|
||||
self.CacheType.DEVICE_PROMPT,
|
||||
enhanced_cache_key,
|
||||
enhanced_prompt,
|
||||
ttl=300,
|
||||
)
|
||||
self.logger.bind(tag=TAG).info(
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"构建增强提示词成功,长度: {len(enhanced_prompt)}"
|
||||
)
|
||||
return enhanced_prompt
|
||||
|
|
|
|||
|
|
@ -135,7 +135,7 @@ def get_ip_info(ip_addr, logger):
|
|||
if is_private_ip(ip_addr):
|
||||
ip_addr = ""
|
||||
url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}"
|
||||
resp = requests.get(url).json()
|
||||
resp = requests.get(url, timeout=5).json()
|
||||
ip_info = {"city": resp.get("city")}
|
||||
|
||||
# 存入缓存
|
||||
|
|
@ -179,6 +179,14 @@ def remove_punctuation_and_length(text):
|
|||
|
||||
|
||||
def check_model_key(modelType, modelKey):
|
||||
"""检查 API key 是不是还停留在出厂占位符上。
|
||||
|
||||
modelKey 允许是 None / 空串:智控台下发的配置里未必带 api_key 字段
|
||||
(本地 LLM 场景也常把它留空),而 ``"你" in None`` 会直接抛
|
||||
TypeError,把「配置没填」这种业务错误变成了 provider 构造期的崩溃。
|
||||
"""
|
||||
if not modelKey:
|
||||
return f"配置错误: {modelType} 的 API key 未设置"
|
||||
if "你" in modelKey:
|
||||
return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}"
|
||||
return None
|
||||
|
|
@ -310,8 +318,12 @@ async def audio_to_data(
|
|||
from core.utils.cache.manager import cache_manager
|
||||
from core.utils.cache.config import CacheType
|
||||
|
||||
# 生成缓存键,包含文件路径和编码类型
|
||||
cache_key = f"{audio_file_path}:{is_opus}"
|
||||
# 缓存键含 mtime:文件被原地覆写时旧缓存自动失效(如唤醒词回复重新 TTS),避免播到过期音频
|
||||
try:
|
||||
mtime = os.path.getmtime(audio_file_path)
|
||||
cache_key = f"{audio_file_path}:{mtime}:{is_opus}"
|
||||
except OSError:
|
||||
cache_key = f"{audio_file_path}:{is_opus}"
|
||||
|
||||
# 尝试从缓存获取结果
|
||||
if use_cache:
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import time
|
|||
import aiohttp
|
||||
import requests
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from typing import Optional, Dict
|
||||
from typing import Optional, Dict, NamedTuple
|
||||
from config.logger import setup_logging
|
||||
from core.utils.cache.manager import cache_manager
|
||||
from core.utils.cache.config import CacheType
|
||||
|
|
@ -11,6 +11,30 @@ from core.utils.cache.config import CacheType
|
|||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
# 未命中声纹时沿用的展示名。下游只把这个名字交给 LLM,不把它当成真实身份。
|
||||
UNKNOWN_SPEAKER_NAME = "未知说话人"
|
||||
|
||||
|
||||
class SpeakerIdentification(NamedTuple):
|
||||
"""一次声纹识别结果。speaker_id 仅在命中已配置说话人时有值。"""
|
||||
|
||||
speaker_id: Optional[str]
|
||||
name: str
|
||||
|
||||
|
||||
def resolve_speaker_identification(
|
||||
speaker_id: Optional[str],
|
||||
score: float,
|
||||
speaker_map: Dict[str, Dict[str, str]],
|
||||
similarity_threshold: float,
|
||||
) -> SpeakerIdentification:
|
||||
"""把声纹接口返回的 speaker_id / score 解析成展示名,并保留命中的 id。"""
|
||||
if score < similarity_threshold:
|
||||
return SpeakerIdentification(None, UNKNOWN_SPEAKER_NAME)
|
||||
if speaker_id and speaker_id in speaker_map:
|
||||
return SpeakerIdentification(speaker_id, speaker_map[speaker_id]["name"])
|
||||
return SpeakerIdentification(None, UNKNOWN_SPEAKER_NAME)
|
||||
|
||||
|
||||
class VoiceprintProvider:
|
||||
"""声纹识别服务提供者"""
|
||||
|
|
@ -138,7 +162,16 @@ class VoiceprintProvider:
|
|||
return is_healthy
|
||||
|
||||
async def identify_speaker(self, audio_data: bytes, session_id: str) -> Optional[str]:
|
||||
"""识别说话人"""
|
||||
"""识别说话人,返回展示名。需要 speaker_id 时用 identify_speaker_detail。"""
|
||||
identified = await self.identify_speaker_detail(audio_data, session_id)
|
||||
if identified is None:
|
||||
return None
|
||||
return identified.name
|
||||
|
||||
async def identify_speaker_detail(
|
||||
self, audio_data: bytes, session_id: str
|
||||
) -> Optional[SpeakerIdentification]:
|
||||
"""识别说话人,同时返回声纹 id 和展示名。"""
|
||||
if not self.enabled or not self.api_url or not self.api_key:
|
||||
logger.bind(tag=TAG).debug("声纹识别功能已禁用或未配置,跳过识别")
|
||||
return None
|
||||
|
|
@ -171,18 +204,19 @@ class VoiceprintProvider:
|
|||
|
||||
logger.bind(tag=TAG).info(f"声纹识别耗时: {total_elapsed_time:.3f}s")
|
||||
|
||||
# 相似度阈值检查
|
||||
if score < self.similarity_threshold:
|
||||
identified = resolve_speaker_identification(
|
||||
speaker_id, score, self.speaker_map, self.similarity_threshold
|
||||
)
|
||||
# 三种结果:命中 / 低于阈值 / id不在配置中
|
||||
if identified.speaker_id:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"声纹识别成功: {identified.name} (id: {identified.speaker_id}, 相似度: {score:.3f})"
|
||||
)
|
||||
elif score < self.similarity_threshold:
|
||||
logger.bind(tag=TAG).warning(f"声纹识别相似度{score:.3f}低于阈值{self.similarity_threshold}")
|
||||
return "未知说话人"
|
||||
|
||||
if speaker_id and speaker_id in self.speaker_map:
|
||||
result_name = self.speaker_map[speaker_id]["name"]
|
||||
logger.bind(tag=TAG).info(f"声纹识别成功: {result_name} (相似度: {score:.3f})")
|
||||
return result_name
|
||||
else:
|
||||
logger.bind(tag=TAG).warning(f"未识别的说话人ID: {speaker_id}")
|
||||
return "未知说话人"
|
||||
return identified
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"声纹识别API错误: HTTP {response.status}")
|
||||
return None
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import os
|
|||
import importlib.util
|
||||
import asyncio
|
||||
|
||||
print("使用前请根据doc/performance_testerer.md的说明准备配置。")
|
||||
print("使用前请根据仓库根目录下 docs/performance_tester.md 的说明准备配置。")
|
||||
|
||||
|
||||
def list_performance_tester_modules():
|
||||
|
|
|
|||
|
|
@ -119,7 +119,12 @@ class LLMPerformanceTester:
|
|||
return chunks, first_token_time
|
||||
|
||||
async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
|
||||
"""异步检查 Ollama 服务状态"""
|
||||
"""异步检查 Ollama 服务状态(兼容带/v1或完整端点的base_url写法)"""
|
||||
base_url = base_url.strip().rstrip("/")
|
||||
if base_url.endswith("/chat/completions"):
|
||||
base_url = base_url[: -len("/chat/completions")].rstrip("/")
|
||||
if base_url.endswith("/v1"):
|
||||
base_url = base_url[: -len("/v1")].rstrip("/")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.get(f"{base_url}/api/version") as response:
|
||||
|
|
@ -230,7 +235,7 @@ class LLMPerformanceTester:
|
|||
"""异步测试单个 LLM 性能"""
|
||||
try:
|
||||
# 对于 Ollama,跳过 api_key 检查并进行特殊处理
|
||||
if llm_name == "Ollama":
|
||||
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
|
||||
base_url = config.get("base_url", "http://localhost:11434")
|
||||
model_name = config.get("model_name")
|
||||
if not model_name:
|
||||
|
|
@ -474,7 +479,7 @@ class LLMPerformanceTester:
|
|||
continue
|
||||
|
||||
# 对于 Ollama,先检查服务状态
|
||||
if llm_name == "Ollama":
|
||||
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
|
||||
base_url = config.get("base_url", "http://localhost:11434")
|
||||
model_name = config.get("model_name")
|
||||
if not model_name:
|
||||
|
|
|
|||
|
|
@ -647,8 +647,9 @@ class StreamTTSPerformanceTester:
|
|||
self.results.append(result)
|
||||
|
||||
# 测试Linkerai TTS
|
||||
result = await self.test_linkerai_tts(test_text, test_count)
|
||||
self.results.append(result)
|
||||
if self.config.get("TTS", {}).get("LinkeraiTTS"):
|
||||
result = await self.test_linkerai_tts(test_text, test_count)
|
||||
self.results.append(result)
|
||||
|
||||
# 测试IndexStreamTTS
|
||||
result = await self.test_indexstream_tts(test_text, test_count)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import random
|
||||
import httpx
|
||||
from io import BytesIO
|
||||
from urllib.parse import quote, urlsplit, urlunsplit, parse_qsl
|
||||
from markitdown import MarkItDown, StreamInfo
|
||||
from config.logger import setup_logging
|
||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||
|
|
@ -54,6 +55,27 @@ CHANNEL_MAP = {
|
|||
# 默认新闻来源字典,当配置中没有指定时使用
|
||||
DEFAULT_NEWS_SOURCES = "澎湃新闻;百度热搜;财联社"
|
||||
|
||||
DEFAULT_NEWS_API_URL = "https://newsnow.busiyi.world/api/s?id="
|
||||
|
||||
|
||||
def _build_news_api_url(source, configured_url=None):
|
||||
"""拼出新闻接口的请求地址和查询参数。
|
||||
|
||||
配置里带 {source} 占位符就替换占位符;否则把 id 设成新闻源 id,
|
||||
这样配置里已经写了 id 时也不会拼出脏串。
|
||||
"""
|
||||
api_url = str(configured_url).strip() if configured_url else DEFAULT_NEWS_API_URL
|
||||
if "{source}" in api_url:
|
||||
return api_url.replace("{source}", quote(source, safe="")), None
|
||||
parts = urlsplit(api_url)
|
||||
query = dict(parse_qsl(parts.query, keep_blank_values=True))
|
||||
query["id"] = source
|
||||
return (
|
||||
urlunsplit((parts.scheme, parts.netloc, parts.path, "", parts.fragment)),
|
||||
query,
|
||||
)
|
||||
|
||||
|
||||
def _get_newsnow_config(conn):
|
||||
# 从连接配置获取
|
||||
plugins = conn.config.get("plugins", {})
|
||||
|
|
@ -61,6 +83,8 @@ def _get_newsnow_config(conn):
|
|||
sources = newsnow.get("news_sources", "")
|
||||
if isinstance(sources, str) and sources.strip():
|
||||
return sources
|
||||
if isinstance(sources, (list, tuple)):
|
||||
return ";".join(str(item).strip() for item in sources if str(item).strip())
|
||||
|
||||
return ""
|
||||
|
||||
|
|
@ -113,23 +137,26 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = {
|
|||
async def fetch_news_from_api(conn: "ConnectionHandler", source="thepaper"):
|
||||
"""从API获取新闻列表"""
|
||||
try:
|
||||
api_url = f"https://newsnow.busiyi.world/api/s?id={source}"
|
||||
|
||||
news_config = conn.config.get("plugins", {}).get("get_news_from_newsnow", {})
|
||||
if news_config.get("url"):
|
||||
api_url = news_config["url"] + source
|
||||
configured_url = news_config.get("url") if isinstance(news_config, dict) else None
|
||||
api_url, request_params = _build_news_api_url(source, configured_url)
|
||||
|
||||
headers = {"User-Agent": "Mozilla/5.0"}
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
|
||||
response = await client.get(api_url, headers=headers)
|
||||
response = await client.get(api_url, params=request_params, headers=headers)
|
||||
|
||||
if response.status_code != 200:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"获取新闻API失败:HTTP {response.status_code},source={source}"
|
||||
)
|
||||
return []
|
||||
data = response.json()
|
||||
|
||||
if "items" in data:
|
||||
return data["items"]
|
||||
else:
|
||||
items = data.get("items") if isinstance(data, dict) else None
|
||||
if not isinstance(items, list):
|
||||
logger.bind(tag=TAG).error(f"获取新闻API响应格式错误: {data}")
|
||||
return []
|
||||
return [item for item in items if isinstance(item, dict) and item.get("title")]
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"获取新闻API失败: {e}")
|
||||
|
|
@ -239,18 +266,24 @@ async def get_news_from_newsnow(
|
|||
english_source_id = None
|
||||
|
||||
# 检查输入的中文名称是否在配置的新闻源中
|
||||
news_sources_list = [
|
||||
name.strip() for name in news_sources.split(";") if name.strip()
|
||||
]
|
||||
news_sources_list = [name.strip() for name in news_sources.split(";") if name.strip()]
|
||||
if source in news_sources_list:
|
||||
# 如果输入的中文名称在配置的新闻源中,在 CHANNEL_MAP 中查找对应的英文ID
|
||||
english_source_id = CHANNEL_MAP.get(source)
|
||||
elif not source and news_sources_list:
|
||||
source = news_sources_list[0]
|
||||
english_source_id = CHANNEL_MAP.get(source)
|
||||
|
||||
# 如果找不到对应的英文ID,使用默认源
|
||||
if not english_source_id:
|
||||
logger.bind(tag=TAG).warning(f"无效的新闻源: {source},使用默认源澎湃新闻")
|
||||
english_source_id = "thepaper"
|
||||
source = "澎湃新闻"
|
||||
fallback_source = next(
|
||||
(name for name in news_sources_list if CHANNEL_MAP.get(name)),
|
||||
"澎湃新闻",
|
||||
)
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"无效的新闻源: {source},使用配置中的默认源{fallback_source}"
|
||||
)
|
||||
english_source_id = CHANNEL_MAP[fallback_source]
|
||||
source = fallback_source
|
||||
|
||||
logger.bind(tag=TAG).info(f"获取新闻: 新闻源={source}({english_source_id})")
|
||||
|
||||
|
|
@ -266,20 +299,21 @@ async def get_news_from_newsnow(
|
|||
|
||||
# 随机选择一条新闻
|
||||
selected_news = random.choice(news_items)
|
||||
title = selected_news.get("title", "未知标题")
|
||||
|
||||
# 保存当前新闻链接到连接对象,以便后续查询详情
|
||||
if not hasattr(conn, "last_newsnow_link"):
|
||||
conn.last_newsnow_link = {}
|
||||
conn.last_newsnow_link = {
|
||||
"url": selected_news.get("url", "#"),
|
||||
"title": selected_news.get("title", "未知标题"),
|
||||
"title": title,
|
||||
"source_id": english_source_id,
|
||||
}
|
||||
|
||||
# 构建新闻报告
|
||||
news_report = (
|
||||
f"根据下列数据,用{lang}回应用户的新闻查询请求:\n\n"
|
||||
f"新闻标题: {selected_news['title']}\n"
|
||||
f"新闻标题: {title}\n"
|
||||
# f"新闻来源: {source}\n"
|
||||
f"(请以自然、流畅的方式向用户播报这条新闻标题,"
|
||||
f"提示用户可以要求获取详细内容,此时会获取新闻的详细内容。)"
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import asyncio
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from config.logger import setup_logging
|
||||
|
|
@ -112,20 +113,106 @@ WEATHER_CODE_MAP = {
|
|||
|
||||
|
||||
async def fetch_city_info(location, api_key, api_host):
|
||||
url = f"https://{api_host}/geo/v2/city/lookup?key={api_key}&location={location}&lang=zh"
|
||||
url = f"https://{api_host}/geo/v2/city/lookup"
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0, connect=3.0)) as client:
|
||||
response = await client.get(url, headers=HEADERS)
|
||||
data = response.json()
|
||||
if data.get("error") is not None:
|
||||
response = await client.get(
|
||||
url,
|
||||
params={
|
||||
"key": api_key,
|
||||
"location": location,
|
||||
"lang": "zh",
|
||||
"number": 1,
|
||||
},
|
||||
headers=HEADERS,
|
||||
)
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"获取天气失败,原因:{data.get('error', {}).get('detail')}"
|
||||
f"获取天气城市失败:HTTP {response.status_code} 返回了非 JSON 内容"
|
||||
)
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
logger.bind(tag=TAG).error("获取天气城市失败:响应不是 JSON 对象")
|
||||
return None
|
||||
if response.status_code != 200 or data.get("code") != "200":
|
||||
logger.bind(tag=TAG).error(
|
||||
f"获取天气城市失败:HTTP {response.status_code},代码 {data.get('code')}"
|
||||
)
|
||||
return None
|
||||
return data.get("location", [])[0] if data.get("location") else None
|
||||
|
||||
|
||||
async def fetch_weather_data(city_info, api_key, api_host):
|
||||
location_id = city_info.get("id")
|
||||
if not location_id:
|
||||
return None
|
||||
|
||||
base_url = f"https://{api_host}/v7/weather"
|
||||
params = {"key": api_key, "location": location_id, "lang": "zh"}
|
||||
|
||||
async def request(client, endpoint):
|
||||
response = await client.get(f"{base_url}/{endpoint}", params=params, headers=HEADERS)
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
return None
|
||||
if response.status_code != 200 or data.get("code") != "200":
|
||||
logger.bind(tag=TAG).error(
|
||||
f"获取天气数据失败:接口={endpoint} HTTP {response.status_code},代码 {data.get('code')}"
|
||||
)
|
||||
return None
|
||||
return data
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
|
||||
now, daily = await asyncio.gather(
|
||||
request(client, "now"), request(client, "7d")
|
||||
)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"获取天气 JSON 接口失败,将尝试网页接口: {e}")
|
||||
return None
|
||||
if now is None or daily is None:
|
||||
return None
|
||||
return now, daily
|
||||
|
||||
|
||||
def build_weather_report(city_info, now_data, daily_data):
|
||||
city_name = city_info.get("name") or city_info.get("adm2") or "未知位置"
|
||||
now = now_data.get("now", {})
|
||||
weather_report = f"您查询的位置是:{city_name}\n\n"
|
||||
weather_report += f"当前天气: {now.get('text', '未知')}\n"
|
||||
|
||||
current_basic = {
|
||||
"温度": f"{now['temp']}℃" if now.get("temp") is not None else None,
|
||||
"体感温度": f"{now['feelsLike']}℃" if now.get("feelsLike") is not None else None,
|
||||
"湿度": f"{now['humidity']}%" if now.get("humidity") is not None else None,
|
||||
"风向": now.get("windDir"),
|
||||
"风力": now.get("windScale"),
|
||||
"能见度": f"{now['vis']}公里" if now.get("vis") is not None else None,
|
||||
"气压": f"{now['pressure']}百帕" if now.get("pressure") is not None else None,
|
||||
"降水量": f"{now['precip']}毫米" if now.get("precip") is not None else None,
|
||||
}
|
||||
current_basic = {key: value for key, value in current_basic.items() if value}
|
||||
if current_basic:
|
||||
weather_report += "详细参数:\n"
|
||||
weather_report += "".join(f" · {key}: {value}\n" for key, value in current_basic.items())
|
||||
|
||||
weather_report += "\n未来7天预报:\n"
|
||||
for item in daily_data.get("daily", [])[:7]:
|
||||
date = item.get("fxDate", "未知日期")
|
||||
weather = item.get("textDay") or WEATHER_CODE_MAP.get(item.get("iconDay"), "未知")
|
||||
high = item.get("tempMax", "未知")
|
||||
low = item.get("tempMin", "未知")
|
||||
weather_report += f"{date}: {weather},气温 {low}~{high}℃\n"
|
||||
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
||||
return weather_report
|
||||
|
||||
|
||||
async def fetch_weather_page(url):
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(10.0, connect=3.0), follow_redirects=True
|
||||
) as client:
|
||||
response = await client.get(url, headers=HEADERS)
|
||||
return BeautifulSoup(response.text, "html.parser") if response.status_code == 200 else None
|
||||
|
||||
|
|
@ -181,7 +268,8 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str
|
|||
location = cached_ip_info.get("city")
|
||||
else:
|
||||
# 缓存未命中,调用API获取
|
||||
ip_info = get_ip_info(client_ip, logger)
|
||||
# get_ip_info 是同步 requests 调用,放线程池,避免卡住主事件循环
|
||||
ip_info = await asyncio.to_thread(get_ip_info, client_ip, logger)
|
||||
if ip_info:
|
||||
cache_manager.set(CacheType.IP_INFO, client_ip, ip_info)
|
||||
location = ip_info.get("city")
|
||||
|
|
@ -201,29 +289,31 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str
|
|||
city_info = await fetch_city_info(location, api_key, api_host)
|
||||
if not city_info:
|
||||
return ActionResponse(
|
||||
Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None
|
||||
Action.REQLLM,
|
||||
f"暂时查不到 {location} 的天气(城市未找到或天气服务不可用),请稍后再试",
|
||||
None,
|
||||
)
|
||||
soup = await fetch_weather_page(city_info["fxLink"])
|
||||
if not soup:
|
||||
return ActionResponse(Action.REQLLM, None, "请求失败")
|
||||
city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
|
||||
|
||||
weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n"
|
||||
|
||||
# 添加有效的当前天气参数
|
||||
if current_basic:
|
||||
weather_report += "详细参数:\n"
|
||||
for key, value in current_basic.items():
|
||||
if value != "0": # 过滤无效值
|
||||
weather_report += f" · {key}: {value}\n"
|
||||
|
||||
# 添加7天预报
|
||||
weather_report += "\n未来7天预报:\n"
|
||||
for date, weather, high, low in temps_list:
|
||||
weather_report += f"{date}: {weather},气温 {low}~{high}\n"
|
||||
|
||||
# 提示语
|
||||
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
||||
weather_data = await fetch_weather_data(city_info, api_key, api_host)
|
||||
if weather_data:
|
||||
weather_report = build_weather_report(city_info, *weather_data)
|
||||
else:
|
||||
fx_link = city_info.get("fxLink")
|
||||
soup = await fetch_weather_page(fx_link) if fx_link else None
|
||||
if not soup:
|
||||
return ActionResponse(Action.REQLLM, None, "请求天气数据失败")
|
||||
city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
|
||||
weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n"
|
||||
if current_basic:
|
||||
weather_report += "详细参数:\n"
|
||||
weather_report += "".join(
|
||||
f" · {key}: {value}\n" for key, value in current_basic.items() if value != "0"
|
||||
)
|
||||
weather_report += "\n未来7天预报:\n"
|
||||
weather_report += "".join(
|
||||
f"{date}: {weather},气温 {low}~{high}\n"
|
||||
for date, weather, high, low in temps_list
|
||||
)
|
||||
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
||||
|
||||
# 缓存完整的天气报告
|
||||
cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report)
|
||||
|
|
|
|||
|
|
@ -1,27 +1,53 @@
|
|||
from config.logger import setup_logging
|
||||
from core.utils.util import check_model_key
|
||||
from plugins_func.register import module_func_map
|
||||
|
||||
TAG = __name__
|
||||
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):
|
||||
if conn.intent_type == "function_call":
|
||||
funcs = 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"
|
||||
funcs = _expand_module_names(
|
||||
conn.config["Intent"][conn.config["selected_module"]["Intent"]].get(
|
||||
"functions", []
|
||||
)
|
||||
)
|
||||
|
||||
if "hass_get_state" in funcs or "hass_set_state" in funcs:
|
||||
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.dialogue.update_system_message(conn.prompt)
|
||||
|
|
@ -32,17 +58,10 @@ def initialize_hass_handler(conn):
|
|||
if not conn.load_function_plugin:
|
||||
return ha_config
|
||||
|
||||
# 安全地获取插件配置
|
||||
plugins_config = conn.config.get("plugins", {})
|
||||
# 确定配置来源
|
||||
config_source = (
|
||||
"home_assistant" if plugins_config.get("home_assistant") else "hass_state"
|
||||
)
|
||||
if not plugins_config.get(config_source):
|
||||
plugin_config = _hass_plugin_config(conn.config.get("plugins", {}))
|
||||
if not plugin_config:
|
||||
return ha_config
|
||||
|
||||
# 统一获取配置
|
||||
plugin_config = plugins_config[config_source]
|
||||
ha_config["base_url"] = plugin_config.get("base_url")
|
||||
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"])
|
||||
+ " "
|
||||
)
|
||||
if "volume_level" in response.json()["attributes"]:
|
||||
responsetext = (
|
||||
responsetext
|
||||
+ "音量是:"
|
||||
+ str(response.json()["attributes"]["volume_level"])
|
||||
+ " "
|
||||
)
|
||||
volume_level = response.json()["attributes"].get("volume_level")
|
||||
if isinstance(volume_level, (int, float)):
|
||||
# volume_level 量程 0~1,换算成百分比(同 volume_set 的 1~100)
|
||||
responsetext = responsetext + "音量是:" + f"{round(volume_level * 100)}%" + " "
|
||||
if "color_temp_kelvin" in response.json()["attributes"]:
|
||||
responsetext = (
|
||||
responsetext
|
||||
|
|
@ -142,13 +139,11 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id):
|
|||
+ str(response.json()["attributes"]["rgb_color"])
|
||||
+ " "
|
||||
)
|
||||
if "brightness" in response.json()["attributes"]:
|
||||
responsetext = (
|
||||
responsetext
|
||||
+ "亮度是:"
|
||||
+ str(response.json()["attributes"]["brightness"])
|
||||
+ " "
|
||||
)
|
||||
brightness = response.json()["attributes"].get("brightness")
|
||||
if isinstance(brightness, (int, float)):
|
||||
# brightness 量程 0~255,换算成百分比(同 brightness_pct 的 1~100),开灯最低报 1%
|
||||
percent = max(1, round(brightness * 100 / 255)) if brightness > 0 else 0
|
||||
responsetext = responsetext + "亮度是:" + f"{percent}%" + " "
|
||||
logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}")
|
||||
return responsetext
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -149,6 +149,106 @@ async def _search_serply(api_key: str, query: str, max_results: int) -> str:
|
|||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def _search_outcrawl(api_key: str, query: str, max_results: int) -> str:
|
||||
"""调用Outcrawl搜索API"""
|
||||
url = "https://api.outcrawl.ai/v1/search"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "xiaozhi-esp32-server",
|
||||
}
|
||||
# Outcrawl单次最多返回20条
|
||||
payload = {"query": query, "limit": max(1, min(max_results, 20))}
|
||||
logger.bind(tag=TAG).debug(f"Outcrawl搜索请求 | URL: {url} | payload: {payload}")
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||
response = await client.post(url, json=payload, headers=headers)
|
||||
data = response.json()
|
||||
logger.bind(tag=TAG).debug(f"Outcrawl搜索响应 | status: {response.status_code}")
|
||||
|
||||
if response.status_code != 200:
|
||||
# 错误信封为 {"code": "...", "message": "...", "details": {}},
|
||||
# code 是官方承诺的封闭枚举
|
||||
code = data.get("code", "") if isinstance(data, dict) else ""
|
||||
detail = data.get("message", "") if isinstance(data, dict) else ""
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Outcrawl搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}"
|
||||
)
|
||||
if code == "quota_exceeded":
|
||||
# 该code覆盖两种情况:每分钟请求数限流,或月度credits用尽
|
||||
return "联网搜索被限流或额度已用完,请稍后重试或检查Outcrawl账户余额。"
|
||||
if code == "unauthorized":
|
||||
return "联网搜索请求失败,请检查API Key是否正确。"
|
||||
# 其余code(bad_request、no_capacity、search_refused、internal等)
|
||||
# 多为输入问题或服务端暂时性故障,统一引导重试
|
||||
return "联网搜索请求失败,请稍后重试。"
|
||||
|
||||
hits = data.get("hits", [])
|
||||
if not hits:
|
||||
return "未找到相关搜索结果。"
|
||||
|
||||
lines = ["【联网搜索结果】"]
|
||||
for i, item in enumerate(hits[:max_results], 1):
|
||||
title = item.get("title") or "无标题"
|
||||
snippet = item.get("snippet", "")
|
||||
lines.append(f"{i}. 标题:{title}")
|
||||
if snippet:
|
||||
lines.append(f" 摘要:{snippet}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def _search_specstream(api_key: str, query: str, max_results: int) -> str:
|
||||
"""调用SpecStream搜索API"""
|
||||
url = "https://api.specstream.ai/v1/web-search"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"User-Agent": "xiaozhi-esp32-server",
|
||||
}
|
||||
# 单次10条以内按基础价计费,所以num按1到10截取
|
||||
params = {"q": query, "num": max(1, min(max_results, 10))}
|
||||
logger.bind(tag=TAG).debug(f"SpecStream搜索请求 | URL: {url} | params: {params}")
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||
response = await client.get(url, params=params, headers=headers)
|
||||
data = response.json()
|
||||
logger.bind(tag=TAG).debug(f"SpecStream搜索响应 | status: {response.status_code}")
|
||||
|
||||
if response.status_code != 200:
|
||||
# 错误信封为 {"error": {"code": "...", "message": "...", "details": {}}}
|
||||
error = data.get("error", {}) if isinstance(data, dict) else {}
|
||||
code = error.get("code", "") if isinstance(error, dict) else ""
|
||||
detail = error.get("message", "") if isinstance(error, dict) else ""
|
||||
logger.bind(tag=TAG).error(
|
||||
f"SpecStream搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}"
|
||||
)
|
||||
if code in ("missing_api_key", "invalid_token"):
|
||||
return "联网搜索请求失败,请检查API Key是否正确。"
|
||||
if code in ("insufficient_balance", "payment_required"):
|
||||
return "联网搜索额度已用完,请检查SpecStream账户余额。"
|
||||
# 其余code(rate_limited、capacity、bad_request等)统一引导重试
|
||||
return "联网搜索请求失败,请稍后重试。"
|
||||
|
||||
page = data.get("data") or {}
|
||||
sources = page.get("sources", [])
|
||||
if not sources:
|
||||
return "未找到相关搜索结果。"
|
||||
|
||||
lines = ["【联网搜索结果】"]
|
||||
answer = (page.get("answer") or {}).get("value", "")
|
||||
if answer:
|
||||
lines.append(f"总结:{answer}")
|
||||
for i, item in enumerate(sources[:max_results], 1):
|
||||
title = item.get("title") or "无标题"
|
||||
snippet = item.get("snippet", "")
|
||||
date = item.get("published") or ""
|
||||
lines.append(f"{i}. 标题:{title}")
|
||||
if date:
|
||||
lines.append(f" 日期:{date}")
|
||||
if snippet:
|
||||
lines.append(f" 摘要:{snippet}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@register_function("web_search", WEB_SEARCH_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
||||
async def web_search(conn: "ConnectionHandler", query: str = None):
|
||||
logger.bind(tag=TAG).info(f"web_search 被调用 | query={query}")
|
||||
|
|
@ -175,6 +275,10 @@ async def web_search(conn: "ConnectionHandler", query: str = None):
|
|||
result_text = await _search_tavily(api_key, query, max_results)
|
||||
elif provider == "serply":
|
||||
result_text = await _search_serply(api_key, query, max_results)
|
||||
elif provider == "outcrawl":
|
||||
result_text = await _search_outcrawl(api_key, query, max_results)
|
||||
elif provider == "specstream":
|
||||
result_text = await _search_specstream(api_key, query, max_results)
|
||||
else:
|
||||
return ActionResponse(
|
||||
Action.REQLLM,
|
||||
|
|
|
|||
|
|
@ -83,7 +83,11 @@ module_func_map = {}
|
|||
|
||||
|
||||
def register_function(name, desc, type=None):
|
||||
"""注册函数到函数注册字典的装饰器"""
|
||||
"""注册函数到函数注册字典的装饰器
|
||||
|
||||
同步函数在工作线程中执行,函数体内不可调用 asyncio 事件循环 API;
|
||||
需要异步(httpx、await)请定义为 async def。
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
all_function_registry[name] = FunctionItem(name, desc, func, type)
|
||||
|
|
|
|||
81
main/xiaozhi-server/tests/config/test_provider_endpoints.py
Normal file
81
main/xiaozhi-server/tests/config/test_provider_endpoints.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
"""供应器默认端点自检:防止不同 provider 的 base_url 被复制粘贴串台。
|
||||
|
||||
背景:``config.yaml`` 里每个 provider 的 ``base_url`` / ``url`` 都是照抄对应
|
||||
厂商文档填的,很容易从相邻的 provider 直接复制粘贴。真实案例:``VLLM``
|
||||
段的 ``XunfeiSparkLLM`` 抄了上面 ``LLM.DoubaoLLM`` 的火山方舟地址
|
||||
(ark.cn-beijing.volces.com),选它做视觉模型时会把讯飞的 api_key 发给
|
||||
火山引擎,而 ``model_name: lite`` 在那个端点上并不存在。
|
||||
|
||||
这里用一张「配置块 -> 端点主机名」的对照表把这类串台钉死。新增 provider
|
||||
时顺手往表里加一行即可。
|
||||
|
||||
注意:本用例读的是仓库里**出厂的** ``config.yaml``,不是用户
|
||||
``data/.config.yaml`` 合并后的结果 —— 要守的就是这份出厂默认值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from config.config_loader import get_project_dir, read_config
|
||||
|
||||
|
||||
# (模块段, provider 名, 端点主机名里必须出现的片段)
|
||||
PROVIDER_ENDPOINT_HOSTS = [
|
||||
("LLM", "AliLLM", "dashscope.aliyuncs.com"),
|
||||
("LLM", "AliAppLLM", "dashscope.aliyuncs.com"),
|
||||
("LLM", "ChatGLMLLM", "bigmodel.cn"),
|
||||
("LLM", "DeepSeekLLM", "deepseek.com"),
|
||||
("LLM", "DifyLLM", "dify.ai"),
|
||||
("LLM", "DoubaoLLM", "volces.com"),
|
||||
("LLM", "VolcesAiGatewayLLM", "volces.com"),
|
||||
("VLLM", "ChatGLMVLLM", "bigmodel.cn"),
|
||||
("VLLM", "QwenVLVLLM", "dashscope.aliyuncs.com"),
|
||||
("VLLM", "XunfeiSparkLLM", "xf-yun.com"),
|
||||
("ASR", "OpenaiASR", "api.openai.com"),
|
||||
("ASR", "GroqASR", "api.groq.com"),
|
||||
("ASR", "Qwen3ASRFlash", "dashscope.aliyuncs.com"),
|
||||
("TTS", "OpenAITTS", "api.openai.com"),
|
||||
("TTS", "DoubaoTTS", "bytedance.com"),
|
||||
("TTS", "TTS302AI", "302ai.cn"),
|
||||
("TTS", "VolcesAiGatewayTTS", "volces.com"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def default_config():
|
||||
"""仓库里出厂的默认配置(未经用户 data/.config.yaml 覆盖)。"""
|
||||
return read_config(get_project_dir() + "config.yaml")
|
||||
|
||||
|
||||
def _endpoint_of(block: dict) -> str:
|
||||
"""取 provider 配置块里生效的端点。
|
||||
|
||||
顺序与运行时一致:``core/providers/vllm/openai.py`` 和
|
||||
``core/providers/llm/openai/openai.py`` 都是 ``base_url`` 优先、
|
||||
``url`` 兜底;部分 TTS 用 ``api_url``。
|
||||
"""
|
||||
return block.get("base_url") or block.get("url") or block.get("api_url") or ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module,provider,expected_host",
|
||||
PROVIDER_ENDPOINT_HOSTS,
|
||||
ids=[f"{m}.{p}" for m, p, _ in PROVIDER_ENDPOINT_HOSTS],
|
||||
)
|
||||
def test_provider_endpoint_matches_platform(
|
||||
default_config, module, provider, expected_host
|
||||
):
|
||||
"""provider 的端点必须落在它自己那家厂商的域名下。"""
|
||||
block = default_config.get(module, {}).get(provider)
|
||||
assert block is not None, f"config.yaml 里找不到 {module}.{provider} 配置块"
|
||||
|
||||
endpoint = _endpoint_of(block)
|
||||
assert endpoint, f"{module}.{provider} 没有配置 base_url / url / api_url"
|
||||
|
||||
host = urlparse(endpoint).netloc
|
||||
assert expected_host in host, (
|
||||
f"{module}.{provider} 的端点 {endpoint!r} 解析出的主机是 {host!r},"
|
||||
f"与平台不符(期望包含 {expected_host!r})—— 疑似从别的 provider 复制粘贴时带串了"
|
||||
)
|
||||
|
|
@ -47,10 +47,29 @@ if str(_PROJECT_ROOT) not in sys.path:
|
|||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import opuslib_next # noqa: F401
|
||||
except Exception:
|
||||
except Exception as _opus_import_error:
|
||||
# opuslib_next 是 ctypes 绑定,pip 装上的是纯 Python 包,真正的编解码靠系统里的
|
||||
# libopus.so。runner 上没装 libopus 时 import 会失败,这里换桩顶上。
|
||||
# 桩只能撑住 import 链路,真要编解码得先把 libopus 装上
|
||||
# (apt-get install libopus0,正式镜像 Dockerfile-server-base 里也是这么装的)。
|
||||
print(
|
||||
f"[conftest] opuslib_next 不可用,改用桩:{_opus_import_error}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
def _opus_unavailable(_self, *_args, **_kwargs):
|
||||
raise RuntimeError(
|
||||
"libopus 没装,Opus 编解码跑不了。"
|
||||
"装法:apt-get install libopus0(正式镜像 Dockerfile-server-base 里也是这么装的)"
|
||||
)
|
||||
|
||||
_stub = types.ModuleType("opuslib_next")
|
||||
_stub.Encoder = type("Encoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.Decoder = type("Decoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.Encoder = type(
|
||||
"Encoder", (), {"__init__": lambda *a, **kw: None, "encode": _opus_unavailable}
|
||||
)
|
||||
_stub.Decoder = type(
|
||||
"Decoder", (), {"__init__": lambda *a, **kw: None, "decode": _opus_unavailable}
|
||||
)
|
||||
_stub.APPLICATION_AUDIO = 0
|
||||
_stub.OpusError = type("OpusError", (Exception,), {})
|
||||
_stub.constants = types.SimpleNamespace()
|
||||
|
|
@ -184,7 +203,8 @@ def get_provider_type(module: str, provider_name: str | None = None) -> str | No
|
|||
def has_real_key(config: dict, *keys: str) -> bool:
|
||||
"""任一候选 key 名下值不是占位符就算有真密钥。
|
||||
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none" / "ollama"
|
||||
(Ollama本地服务无需鉴权,config.yaml默认占位值即为"ollama")。
|
||||
"""
|
||||
if not config:
|
||||
return False
|
||||
|
|
@ -193,7 +213,7 @@ def has_real_key(config: dict, *keys: str) -> bool:
|
|||
if val is None:
|
||||
continue
|
||||
s = str(val).strip().lower()
|
||||
if not s or s == "none":
|
||||
if not s or s == "none" or s == "ollama":
|
||||
continue
|
||||
if s.startswith("你的") or "placeholder" in s:
|
||||
continue
|
||||
|
|
@ -323,35 +343,25 @@ def _install_mock_layer() -> None:
|
|||
|
||||
asyncio.sleep = _fast_sleep # type: ignore[assignment]
|
||||
|
||||
# 网络层 mock:如果真实 httpx 已加载,把它的 AsyncClient.send 替换成
|
||||
# 网络层 mock:如果真实 httpx 已加载,把它的 send 替换成
|
||||
# 立即抛 ConnectError 的桩,触发 ``_should_retry`` 走到 ``raise``,
|
||||
# 但避免真发请求。Live 模式完全不安装这层。
|
||||
if not LIVE_API_TESTS:
|
||||
try:
|
||||
import httpx as _httpx # noqa: F401
|
||||
import httpx as _httpx
|
||||
|
||||
class _FakeAsyncClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
async def _fake_async_send(self, request, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
|
||||
async def send(self, *args, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
def _fake_send(self, request, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
class _FakeClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def send(self, *args, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
_httpx.AsyncClient = _FakeAsyncClient # type: ignore[misc]
|
||||
_httpx.Client = _FakeClient # type: ignore[misc]
|
||||
# 只换 send 这一个方法,不换整个类。有些库(openai 2.x 的
|
||||
# SyncHttpxClientWrapper)继承 httpx.Client 再自己拼请求,
|
||||
# 整个类被换掉的话它们继承到的是假类,拼请求时直接
|
||||
# AttributeError,报错还完全看不出是 mock 层的问题
|
||||
_httpx.AsyncClient.send = _fake_async_send # type: ignore[assignment]
|
||||
_httpx.Client.send = _fake_send # type: ignore[assignment]
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
|
@ -390,6 +400,9 @@ def _check_modules_ready() -> None:
|
|||
f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)"
|
||||
)
|
||||
continue
|
||||
# Ollama免鉴权供应器无需真实key,跳过占位符检查
|
||||
if str(cfg.get("type", "")).lower() == "ollama":
|
||||
continue
|
||||
secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg]
|
||||
if secret_keys_present and not any(
|
||||
has_real_key(cfg, k) for k in secret_keys_present
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue