Compare commits

..

No commits in common. "main" and "v0.9.5" have entirely different histories.
main ... v0.9.5

411 changed files with 4676 additions and 32331 deletions

View file

@ -3,40 +3,4 @@ updates:
- package-ecosystem: pip - package-ecosystem: pip
directory: /main/xiaozhi-server directory: /main/xiaozhi-server
schedule: schedule:
interval: monthly interval: weekly
open-pull-requests-limit: 5
groups:
ai-services:
patterns:
- "openai*"
- "google-generativeai"
- "dashscope"
- "baidu-aip"
- "cozepy"
- "markitdown"
- "mem0ai"
- "powermem"
ai-models:
patterns:
- "funasr"
- "vosk"
- "silero_vad"
- "opuslib_next"
- "sherpa_onnx"
- "modelscope"
web-stack:
patterns:
- "httpx"
- "aiohttp"
- "aiohttp_cors"
- "requests"
- "pysocks"
everything-else:
patterns:
- "*"
ignore:
- dependency-name: "torch"
- dependency-name: "torchaudio"
- dependency-name: "numpy"
- dependency-name: "portalocker"
- dependency-name: "websockets"

View file

@ -1,107 +0,0 @@
name: Tests
on:
push:
branches: [main]
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
python:
name: Python (xiaozhi-server)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
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: Prepare test config
working-directory: main/xiaozhi-server
run: |
# 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
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- name: Run tests
working-directory: main/manager-api
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)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: main/manager-web/package-lock.json
- name: Run tests
working-directory: main/manager-web
run: |
npm ci --no-audit --no-fund
npm run test:contract
npm run test:unit
npm run build

5
.gitignore vendored
View file

@ -112,17 +112,12 @@ celerybeat.pid
# Environments # Environments
.env .env
.venv .venv
/.venv-*/
env/ env/
venv/ venv/
ENV/ ENV/
env.bak/ env.bak/
venv.bak/ venv.bak/
# Repository-local runtimes and package-manager caches
/.runtime/
/main/manager-web/.npm-cache/
# Spyder project settings # Spyder project settings
.spyderproject .spyderproject
.spyproject .spyproject

View file

@ -29,5 +29,4 @@ COPY main/xiaozhi-server/requirements.txt .
# 安装Python依赖 # 安装Python依赖
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \
# 阿里云 PyPI 镜像偶有元数据 404,加官方源作 fallback pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5
pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 --extra-index-url https://pypi.org/simple

View file

@ -1,21 +0,0 @@
.PHONY: test test-fast test-python test-java test-web help
help:
@echo "make test-fast - run all fast unit tests (default)"
@echo "make test - alias for test-fast"
@echo "make test-python - pytest in main/xiaozhi-server"
@echo "make test-java - mvn test in main/manager-api"
@echo "make test-web - npm run test:unit in main/manager-web"
test: test-fast
test-fast: test-python test-java test-web
test-python:
cd main/xiaozhi-server && python -m pytest -x -q
test-java:
cd main/manager-api && mvn -B -q test -DfailIfNoTests=false
test-web:
cd main/manager-web && npm ci --no-audit --no-fund && npm test

View file

@ -22,7 +22,6 @@
<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_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_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_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"> <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" /> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a> </a>
@ -170,12 +169,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` 较耗内存,全部走 API 时资源占用低 | - | | **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①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` 较耗内存,另需数据库资源,全部走 API 时资源占用低| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) | | **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①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) |
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md) 常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据。 > 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据,
``` ```
智控台地址: https://2662r3426b.vicp.fun 智控台地址: https://2662r3426b.vicp.fun
@ -203,7 +202,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) | | VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) |
| TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) | | TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) |
| Intent(意图识别) | function_call(函数调用) | function_call(函数调用) | | 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),可按报告中的测试方法在您的环境中实际测试。 如果您关心各组件的耗时,请查阅[小智各组件性能测试报告](https://github.com/xinnan-tech/xiaozhi-performance-research),可按报告中的测试方法在您的环境中实际测试。
@ -212,8 +211,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 工具名称 | 位置 | 使用方法 | 功能说明 | | 工具名称 | 位置 | 使用方法 | 功能说明 |
|:---:|:---|:---:|:---:| |:---:|:---|:---:|:---:|
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 按其 README 装好依赖后执行 `python start.py`,然后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 | | 音频交互测试工具 | 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》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 |
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。 > 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
@ -231,12 +230,12 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 | | 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 | | 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 |
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 | | 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
| 工具调用 | 支持客户端IOT协议、客户端MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 | | 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 | | 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文、德语、越南语、巴西葡萄牙语显示 | | 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 |
| 测试工具 | 提供模型响应性能测试工具和音频交互测试工具 | | 测试工具 | 提供性能测试工具、视觉模型测试工具和音频交互测试工具 |
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 | | 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 |
| 插件系统 | 支持功能插件扩展、自定义插件开发;新增插件文件在下次设备连接时自动加载,改动已加载插件的代码需重启服务 | | 插件系统 | 支持功能插件扩展、自定义插件开发和插件热加载 |
### 正在开发 🚧 ### 正在开发 🚧
@ -256,7 +255,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 | | 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞、LM Studio | 智谱、Gemini | | openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini |
| ollama 接口调用 | Ollama | - | | ollama 接口调用 | Ollama | - |
| dify 接口调用 | Dify | - | | dify 接口调用 | Dify | - |
| fastgpt 接口调用 | Fastgpt | - | | fastgpt 接口调用 | Fastgpt | - |
@ -264,7 +263,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| xinference 接口调用 | Xinference | - | | xinference 接口调用 | Xinference | - |
| homeassistant 接口调用 | HomeAssistant | - | | homeassistant 接口调用 | HomeAssistant | - |
实际上,任何支持 OpenAI 接口调用的 LLM 均可接入使用。 实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
--- ---
@ -272,9 +271,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 | | 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM、科大讯飞 | 智谱ChatGLMVLLM | | openai 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM |
实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。 实际上,任何支持 openai 接口调用的 VLLM 均可接入使用。
--- ---
@ -282,8 +281,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 | | 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、CustomTTS、OpenAITTS、MinimaxTTS | EdgeTTS、CosyVoiceSiliconflow(部分) | | 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) |
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、IndexStreamTTS、PaddleSpeechTTS | IndexStreamTTS、PaddleSpeechTTS、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 | | 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、Index-TTS、PaddleSpeech | Index-TTS、PaddleSpeech、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
--- ---
@ -299,8 +298,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 | | 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 本地使用 | FunASR、SherpaASR、SherpaParaformerASR、VoskASR | FunASR、SherpaASR、SherpaParaformerASR、VoskASR | | 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR |
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云及百炼、百度云、OpenAI ASR、GroqASR、Qwen3ASRFlash | FunASRServer | | 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer |
--- ---
@ -308,9 +307,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 | | 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 接口调用 | 声纹识别服务(voiceprint-api) | - | | 本地使用 | 3D-Speaker | 3D-Speaker |
声纹识别需要单独部署 [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) 服务(基于 3D-Speaker),并依赖 MySQL,详见[声纹识别启用指南](./docs/voiceprint-integration.md)
--- ---
@ -322,7 +319,6 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 | | Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
| Memory | mem_local_short | 本地总结 | 免费 | | | Memory | mem_local_short | 本地总结 | 免费 | |
| Memory | nomem | 无记忆模式 | 免费 | | | Memory | nomem | 无记忆模式 | 免费 | |
| Memory | mem_report_only | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 |
--- ---
@ -357,10 +353,11 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| <img src="./docs/images/logo_contributors.png" width="160"> | [代码贡献者](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | 感谢[所有代码贡献者](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors)贡献者,你们的付出让项目更加健壮和强大。 | | <img src="./docs/images/logo_contributors.png" width="160"> | [代码贡献者](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | 感谢[所有代码贡献者](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors)贡献者,你们的付出让项目更加健壮和强大。 |
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left"> <a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture> <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: 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/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" /> <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/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/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -2,7 +2,7 @@
![请参考-最简化架构图](../docs/images/deploy1.png) ![请参考-最简化架构图](../docs/images/deploy1.png)
# 方式一:Docker只运行Server # 方式一:Docker只运行Server
本项目发行的docker镜像同时提供`amd64`和`arm64`两种架构,可以直接拉取使用;如需自定义镜像,可按照[这个教程](docker-build.md)在本机编译。 `0.8.2`版本开始,本项目发行的docker镜像只支持`x86架构`,如果需要在`arm64架构`的CPU上部署,可按照[这个教程](docker-build.md)在本机编译`arm64的镜像`。
## 1. 安装docker ## 1. 安装docker
@ -36,9 +36,9 @@ xiaozhi-server
#### 1.1.3 下载配置文件 #### 1.1.3 下载配置文件
你需要下载两个配置文件:`docker-compose.yml` 和 `config.yaml`。需要从项目仓库下载这两个文件。 你需要下载两个配置文件:`docker-compose.yaml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
##### 1.1.3.1 下载 docker-compose.yml ##### 1.1.3.1 下载 docker-compose.yaml
用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。 用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。
@ -70,7 +70,7 @@ xiaozhi-server
## 2. 配置项目文件 ## 2. 配置项目文件
接下来,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程: 接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
[跳转到配置项目文件](#配置项目) [跳转到配置项目文件](#配置项目)
配置完项目文件后,回到本教程继续往下。 配置完项目文件后,回到本教程继续往下。
@ -91,22 +91,25 @@ docker logs -f xiaozhi-esp32-server
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认) 这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
## 4. 版本升级操作 ## 5. 版本升级操作
如果后期想升级版本,可以这么操作 如果后期想升级版本,可以这么操作
4.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。 5.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。 请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。
4.2、执行以下命令 5.2、执行以下命令
``` ```
docker stop xiaozhi-esp32-server docker stop xiaozhi-esp32-server
docker rm 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:server_latest
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
``` ```
4.3、重新按docker方式部署 5.3、重新按docker方式部署
# 方式二:本地源码只运行Server # 方式二:本地源码只运行Server
@ -116,7 +119,7 @@ docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest
如果确定使用`conda`,则安装好后,开始执行以下命令。 如果确定使用`conda`,则安装好后,开始执行以下命令。
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词, 重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
找到`Anaconda Prompt`,使用管理员身份运行它。如下图。 找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
![conda_prompt](./images/conda_env_1.png) ![conda_prompt](./images/conda_env_1.png)
@ -210,14 +213,14 @@ prompt: |
请你像一个人一样说话,请勿返回配置xml及其他特殊字符。 请你像一个人一样说话,请勿返回配置xml及其他特殊字符。
selected_module: selected_module:
LLM: ChatGLMLLM LLM: DoubaoLLM
LLM: LLM:
ChatGLMLLM: ChatGLMLLM:
api_key: xxxxxxxxxxxxxxx.xxxxxx api_key: xxxxxxxxxxxxxxx.xxxxxx
``` ```
建议先将最简单的配置运行起来,然后再去[`../main/xiaozhi-server/config.yaml`](../main/xiaozhi-server/config.yaml)阅读配置的使用说明。 建议先将最简单的配置运行起来,然后再去`xiaozhi/config.yaml`阅读配置的使用说明。
比如你要换更换模型,修改`selected_module`下的配置就行。 比如你要换更换模型,修改`selected_module`下的配置就行。
## 模型文件 ## 模型文件
@ -235,12 +238,11 @@ LLM:
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。 如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
``` ```
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/ 250427 13:04:20[0.3.11_SiFuChTTnofu][__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.3.11_SiFuChTTnofu][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
250427 13:04:20[0.9.8_00000000000000][__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.9.8_00000000000000][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问======= 250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250427 13:04:20[0.9.8_00000000000000][__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-=============================================================
``` ```
正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。 正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。

View file

@ -335,7 +335,7 @@ npm run serve
如果确定使用`conda`,则安装好后,开始执行以下命令。 如果确定使用`conda`,则安装好后,开始执行以下命令。
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词, 重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
找到`Anaconda Prompt`,使用管理员身份运行它。如下图。 找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
![conda_prompt](./images/conda_env_1.png) ![conda_prompt](./images/conda_env_1.png)

View file

@ -7,7 +7,7 @@
`上下文源` 在小智在唤醒那一刻,获取外部系统的数据,并将其动态注入到大模型的系统提示词(System Prompt)中。 `上下文源` 在小智在唤醒那一刻,获取外部系统的数据,并将其动态注入到大模型的系统提示词(System Prompt)中。
让其做到唤醒时感知世界某个事物的状态。 让其做到唤醒时感知世界某个事物的状态。
它和MCP、记忆有本质的区别:`上下文源`是强制让小智感知世界的数据;`记忆(Mem)`是让他知道之前聊了什么内容;`MCP(function_call)`是当需要调用某项能力/知识的时候使用调用。 它和MCP、记忆有本质的区别:`上下文源`是强制让小智感知世界的数据;`记忆(Mem)`是让他知道之前聊了什么内容;`MCP(functionc all)`是当需要调用某项能力/知识的时候使用调用。
通过这个功能,在小智唤醒的一刹那,“感知”到: 通过这个功能,在小智唤醒的一刹那,“感知”到:
- 人体健康传感器状态(体温、血压、血氧状态等) - 人体健康传感器状态(体温、血压、血氧状态等)

View file

@ -51,7 +51,7 @@ cp 你原来的model.pt完整路径 /home/system/xiaozhi/xiaozhi-esp32-server/ma
# 第四步 建立三个自动编译文件 # 第四步 建立三个自动编译文件
## 4.1 自动编译manager-web模块 ## 4.1 自动编译mananger-web模块
在`/home/system/xiaozhi/`目录下,创建名字为`update_8001.sh`的文件,内容如下 在`/home/system/xiaozhi/`目录下,创建名字为`update_8001.sh`的文件,内容如下
``` ```
@ -106,7 +106,7 @@ fi
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev & nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev &
tail -f nohup.out tail tail -f nohup.out
``` ```
保存好后执行赋权命令 保存好后执行赋权命令

View file

@ -144,7 +144,5 @@
### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办? ### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办?
- 可以查阅你使用的asr服务的文档,确认是否支持热词识别。 - 可以查阅你使用的asr服务的文档,确认是否支持热词识别。
- 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。 - 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置`页面,在`语音识别`里找到模型名称为`豆包语音识别(流式)`的那一条,点`修改`,弹窗里的`供应器`是`火山引擎语音识别(流式)`,在弹窗的`调用信息`区域把`热词文件名称`填到对应的输入框,点`确认保存`。 - 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置页面`,把`热词文件名称`配置在`火山引擎的tts`上去。
- `豆包语音识别2.0(流式)`(供应器是`火山引擎语音识别(流式)`)和`豆包语音识别`(供应器是`火山引擎语音识别`)这两条也都有`热词文件名称`这个字段,用法一样,配置时注意别选错行。
- 改完要让设备重新连接才会生效:设备连上时才会把最新的私有配置拉下来,一直连着的设备不会自动变。

View file

@ -45,7 +45,7 @@ python download_models.py
python -m tools.api_server --listen 0.0.0.0:6006 python -m tools.api_server --listen 0.0.0.0:6006
``` ```
然后用浏览器去到autodl实例页面 然后用浏览器去到aotodl实例页面
``` ```
https://autodl.com/console/instance/list https://autodl.com/console/instance/list
``` ```

View file

@ -68,7 +68,7 @@ http://homeassistant.local:8123
然后在实体中搜索你相关控制的开关,结果出来后,在列表中,点击其中一个结果,这是会出现一个开关的界面。 然后在实体中搜索你相关控制的开关,结果出来后,在列表中,点击其中一个结果,这是会出现一个开关的界面。
在开关的界面,我们尝试点击开关,看看是否会随着我们的点击开/关。如果能操作,说明是正常联网的。 在开关的界面,我们尝试点击开关,看看是开发会随着我们的点击开/关。如果能操作,说明是正常联网的。
接着在开关面板找到设置按钮,点击后,可以查看这个开关的`实体标识符`。 接着在开关面板找到设置按钮,点击后,可以查看这个开关的`实体标识符`。
@ -107,7 +107,7 @@ http://homeassistant.local:8123
保存成功后,即可唤醒设备操作。 保存成功后,即可唤醒设备操作。
#### 3. 唤醒设备进行控制 #### 3. 唤醒设别进行控制
尝试和esp32说,“打开XXX灯” 尝试和esp32说,“打开XXX灯”

View file

@ -3,7 +3,7 @@
本教程分为4个阶段:准备阶段、配置阶段、克隆阶段、使用阶段。主要是介绍通过智控台配置火山双流式语音合成+音色克隆的过程。 本教程分为4个阶段:准备阶段、配置阶段、克隆阶段、使用阶段。主要是介绍通过智控台配置火山双流式语音合成+音色克隆的过程。
## 第一阶段:准备阶段 ## 第一阶段:准备阶段
超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火山引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。 超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火上引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。
如果你想克隆多个音色,需要购买开通多个音色资源。只要把每个音色资源的声音ID(S_xxxxx)复制到本项目。然后分配给系统的账号使用即可。以下是详细步骤: 如果你想克隆多个音色,需要购买开通多个音色资源。只要把每个音色资源的声音ID(S_xxxxx)复制到本项目。然后分配给系统的账号使用即可。以下是详细步骤:

View file

@ -37,7 +37,7 @@
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。 打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-calculator-main` 点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-calculatorr-main`
你需要把它重命名成`mcp-calculator`。接下来,我们用命令行进入项目目录即安装依赖 你需要把它重命名成`mcp-calculator`。接下来,我们用命令行进入项目目录即安装依赖

View file

@ -113,7 +113,7 @@ server:
那我们需要先登录[智谱AI](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)网站,申请密钥。如果你之前已经申请过了密钥,可以复用这个密钥。 那我们需要先登录[智谱AI](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)网站,申请密钥。如果你之前已经申请过了密钥,可以复用这个密钥。
登录`智控台`,顶部菜单点击`模型配置`,在左侧栏点击`视觉大语言模型`,找到`VLLM_ChatGLMVLLM`,点击修改按钮,在弹框中,在`API密钥`输入你密钥,点击保存。 登录`智控台`,顶部菜单点击`模型配置`,在左侧栏点击`视觉打语言模型`,找到`VLLM_ChatGLMVLLM`,点击修改按钮,在弹框中,在`API密钥`输入你密钥,点击保存。
保存成功后,去到你需要测试的智能体哪里,点击`配置角色`,在打开的内容里,查看`视觉大语言模型(VLLM)`是否选择了刚才的视觉模型。点击保存。 保存成功后,去到你需要测试的智能体哪里,点击`配置角色`,在打开的内容里,查看`视觉大语言模型(VLLM)`是否选择了刚才的视觉模型。点击保存。

View file

@ -86,7 +86,7 @@ SERVER_SECRET=Te1st12134 # 服务器密钥,请保持和智控台(server.sec
- 注意不要用简单的密码,比如`123456`、`test`等。 - 注意不要用简单的密码,比如`123456`、`test`等。
- 注意不要用简单的密码,比如`123456`、`test`等。 - 注意不要用简单的密码,比如`123456`、`test`等。
`SERVER_SECRET` 是用于生成websocket连接的认证信息。 `SERVER_SECRET` 是用生成websocket连接的认证信息。
1、如果你是全模块部署,且你的智控台的参数管理里`server.auth.enabled`设置成了`true`,那么,`SERVER_SECRET`需要和智控台(`server.secret`)保持一致。 1、如果你是全模块部署,且你的智控台的参数管理里`server.auth.enabled`设置成了`true`,那么,`SERVER_SECRET`需要和智控台(`server.secret`)保持一致。

View file

@ -50,11 +50,10 @@ paddlespeech tts --input "你好,这是一次测试"
### 7.修改tts_online_application.yaml配置 ### 7.修改tts_online_application.yaml配置
参考目录 ```"PaddleSpeech\demos\streaming_tts_server\conf\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``` 选择```tts_online_application.yaml```文件用编辑器打开,设置```protocol```为```websocket```
### 8.启动服务 ### 8.启动服务
```bash ```yaml
paddlespeech_server start --config_file ./demos/streaming_tts_server/conf/tts_online_application.yaml paddlespeech_server start --config_file ./demos/streaming_tts_server/conf/tts_online_application.yaml
#官方默认启动命令: #官方默认启动命令:
paddlespeech_server start --config_file ./conf/tts_online_application.yaml paddlespeech_server start --config_file ./conf/tts_online_application.yaml
@ -69,19 +68,10 @@ INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8092 (Press CTRL+C to quit) INFO: Uvicorn running on http://0.0.0.0:8092 (Press CTRL+C to quit)
``` ```
## 三、配置小智服务 ## 三、修改小智的配置文件
### 1. 无需修改代码(provider 已内置于 main/xiaozhi-server/core/providers/tts/paddle_speech.py) ### 1.```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 ```yaml
selected_module: selected_module:
@ -89,41 +79,19 @@ selected_module:
TTS: TTS:
PaddleSpeechTTS: PaddleSpeechTTS:
type: paddle_speech type: paddle_speech
protocol: websocket # 当前仅支持 websocket protocol: websocket
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming] 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 通常表示默认的发音人 spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择]
speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢 speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小 volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
save_path: # 保存路径 save_path: # 保存路径
``` ```
采样率固定 24000,provider 内部写死,配置里不用写这一项。
### 3.启动xiaozhi服务 ### 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 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端是否有输出日志
输出日志参考: 输出日志参考:
``` ```

View file

@ -1,15 +1,8 @@
# 语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南 # 语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
0.先装依赖(在仓库根目录执行)
```
cd main/xiaozhi-server
pip install -r requirements.txt
```
测试脚本要 import `yaml`、`aiohttp`、`tabulate`,少一个都起不来。`tabulate` 不在 requirements.txt 里,是 `edge-tts` 间接带进来的。
1.在main/xiaozhi-server目录下创建data目录 1.在main/xiaozhi-server目录下创建data目录
2.在data目录下创建.config.yaml文件 2.在data目录下创建.config.yaml文件
3.在data/.config.yaml中,写入你的语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的参数 3.在.data/config.yaml中,写入你的语音识别、大语言模型、流式语音合成、视觉模型的参数
例如: 例如:
``` ```
LLM: LLM:
@ -23,50 +16,12 @@ LLM:
api_key: 你的chat-glm web key api_key: 你的chat-glm web key
TTS: TTS:
EdgeTTS:
# 定义TTS API类型
type: edge
voice: zh-CN-XiaoxiaoNeural
VLLM: 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: ASR:
FunASR:
type: fun_local
model_dir: models/SenseVoiceSmall
language: auto
``` ```
4.在main/xiaozhi-server目录下运行performance_tester.py: 4.在main/xiaozhi-server目录下运行performance_tester.py:
``` ```
python 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`)是整项跳过:没配就不报错、结果表里也不会有这一行。

View file

@ -1,6 +1,6 @@
# ragflow 集成指南 # ragflow 集成指南
本教程主要是两部分 本教程主要是是两部分
- 一、如何部署ragflow - 一、如何部署ragflow
- 二、如何在智控台配置ragflow接口 - 二、如何在智控台配置ragflow接口
@ -12,7 +12,7 @@
ragflow需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。 ragflow需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
你可以试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。 你可以你试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
``` shell ``` shell
telnet 127.0.0.1 3306 telnet 127.0.0.1 3306

View file

@ -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 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/> <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/> 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-Zugriffspunkte, Stimmabdruckerkennung und Wissensdatenbank Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
</p> </p>
<p align="center"> <p align="center">
@ -22,7 +22,6 @@ Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Zugriffspunkte, Stimma
<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_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_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_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"> <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" /> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a> </a>
@ -55,31 +54,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank"> <a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture> <picture>
<img alt="Das Gefühl der Reaktionsgeschwindigkeit" src="../images/demo9.png" /></picture> <img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank"> <a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture> <picture>
<img alt="Das Geheimnis der Geschwindigkeitsoptimierung" src="../images/demo6.png" /></picture> <img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank"> <a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture> <picture>
<img alt="Xiaozhi-Digitalmensch mit Sprachaktivierung" src="../images/demo8.png" /></picture> <img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank"> <a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture> <picture>
<img alt="Anruf von Gerät zu Gerät" src="../images/demo0.png" /></picture> <img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank"> <a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture> <picture>
<img alt="Komplexes medizinisches Szenario" src="../images/demo1.png" /></picture> <img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -87,31 +86,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank"> <a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture> <picture>
<img alt="Musik abspielen, Wetter abfragen und Nachrichten vorlesen" src="../images/demo7.png" /></picture> <img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank"> <a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture> <picture>
<img alt="Unterbrechung in Echtzeit" src="../images/demo10.png" /></picture> <img alt="实时打断" src="docs/images/demo10.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank"> <a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture> <picture>
<img alt="Objekte per Foto erkennen" src="../images/demo12.png" /></picture> <img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank"> <a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture> <picture>
<img alt="Haushaltsgeräte ein- und ausschalten" src="../images/demo5.png" /></picture> <img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank"> <a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture> <picture>
<img alt="Aufgaben mit mehreren Befehlen" src="../images/demo11.png" /></picture> <img alt="多指令任务" src="docs/images/demo11.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -119,31 +118,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank"> <a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture> <picture>
<img alt="MCP-Zugriffspunkt" src="../images/demo13.png" /></picture> <img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank"> <a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture> <picture>
<img alt="MQTT-Befehlsübermittlung" src="../images/demo4.png" /></picture> <img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank"> <a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture> <picture>
<img alt="Stimmabdruckerkennung" src="../images/demo14.png" /></picture> <img alt="声纹识别" src="docs/images/demo14.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank"> <a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture> <picture>
<img alt="Eigene Stimmfarbe" src="../images/demo2.png" /></picture> <img alt="自定义音色" src="docs/images/demo2.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank"> <a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture> <picture>
<img alt="Gespräch auf Kantonesisch" src="../images/demo3.png" /></picture> <img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -168,8 +167,8 @@ Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend
#### 🚀 Auswahl der Bereitstellungsmethode #### 🚀 Auswahl der Bereitstellungsmethode
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials | | 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)| Lokales `FunASR` benötigt mehr Arbeitsspeicher; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering | - | | **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) | 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) | | **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) |
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md) Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md)
@ -210,15 +209,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung | | Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|:---:|:---|:---:|:---:| |:---:|:---|:---:|:---:|
| 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 | | 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 Kernmodulen wie ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) | | 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 |
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet. > 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
--- ---
## Funktionsliste ✨ ## Funktionsliste ✨
### Implementiert ✅ ### Implementiert ✅
![Architekturdiagramm der Installation aller Module](../images/deploy2.png) ![请参考-全模块安装架构图](../images/deploy2.png)
| Funktionsmodul | Beschreibung | | 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 | | 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 |
@ -226,15 +225,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 | | 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 | | Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion | | Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
| Absichtserkennung | Unterstützt externe LLM-Absichtserkennung, autonome Funktionsaufrufe durch große Modelle, bietet plugin-basierten Absichtsverarbeitungsmechanismus | | Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion | | 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 | | 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-Zugriffspunktprotokoll, benutzerdefinierte Werkzeugfunktionen | | Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte | | 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, Englisch, Deutsch, Vietnamesisch und brasilianisches Portugiesisch an | | 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 für Modellantworten und Audio-Interaktionstestwerkzeuge | | Testwerkzeuge | Bietet Leistungstestwerkzeuge, Vision-Modell-Testwerkzeuge und Audio-Interaktionstestwerkzeuge |
| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung | | Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
| 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 | | Plugin-System | Unterstützt funktionale Plugin-Erweiterungen, benutzerdefinierte Plugin-Entwicklung und Plugin-Hot-Loading |
### In Entwicklung 🚧 ### In Entwicklung 🚧
@ -254,7 +253,7 @@ Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, Volcano Engine AI Gateway, DeepSeek, Zhipu ChatGLM, Gemini, iFLYTEK, LM Studio | Zhipu ChatGLM, Gemini | | OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
| Ollama-Schnittstellenaufrufe | Ollama | - | | Ollama-Schnittstellenaufrufe | Ollama | - |
| Dify-Schnittstellenaufrufe | Dify | - | | Dify-Schnittstellenaufrufe | Dify | - |
| FastGPT-Schnittstellenaufrufe | FastGPT | - | | FastGPT-Schnittstellenaufrufe | FastGPT | - |
@ -270,7 +269,7 @@ Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, inte
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | | OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden. Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
@ -280,8 +279,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 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) | | 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, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 | | Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
--- ---
@ -297,8 +296,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Lokale Verwendung | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | | Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
| 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 | | Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
--- ---
@ -306,9 +305,7 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Schnittstellenaufrufe | Voiceprint-Dienst (voiceprint-api) | - | | Lokale Verwendung | 3D-Speaker | 3D-Speaker |
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).
--- ---
@ -320,7 +317,6 @@ Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-a
| Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage | | 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 | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | | | Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
| Memory | mem_report_only | Nur Meldung | Kostenlos | Meldet nur Chat-Verläufe, keine Gedächtniszusammenfassung |
--- ---
@ -355,10 +351,11 @@ Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-a
| <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. | | <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://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left"> <a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture> <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: 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/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" /> <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/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/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -22,7 +22,6 @@ 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_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_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_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"> <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" /> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a> </a>
@ -55,31 +54,31 @@ Want to see the usage effects? Click the videos below 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank"> <a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture> <picture>
<img alt="The feel of the response speed" src="../images/demo9.png" /></picture> <img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank"> <a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture> <picture>
<img alt="The secret to speeding things up" src="../images/demo6.png" /></picture> <img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank"> <a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture> <picture>
<img alt="Xiaozhi digital human with voice wake-up" src="../images/demo8.png" /></picture> <img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank"> <a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture> <picture>
<img alt="Device-to-device calling" src="../images/demo0.png" /></picture> <img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank"> <a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture> <picture>
<img alt="A complex medical scenario" src="../images/demo1.png" /></picture> <img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -87,31 +86,31 @@ Want to see the usage effects? Click the videos below 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank"> <a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture> <picture>
<img alt="Play music, check the weather, and read the news" src="../images/demo7.png" /></picture> <img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank"> <a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture> <picture>
<img alt="Real-time interruption" src="../images/demo10.png" /></picture> <img alt="实时打断" src="docs/images/demo10.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank"> <a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture> <picture>
<img alt="Take a photo to identify objects" src="../images/demo12.png" /></picture> <img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank"> <a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture> <picture>
<img alt="Turn home appliances on and off" src="../images/demo5.png" /></picture> <img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank"> <a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture> <picture>
<img alt="Multi-command tasks" src="../images/demo11.png" /></picture> <img alt="多指令任务" src="docs/images/demo11.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -119,31 +118,31 @@ Want to see the usage effects? Click the videos below 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank"> <a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture> <picture>
<img alt="MCP access point" src="../images/demo13.png" /></picture> <img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank"> <a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture> <picture>
<img alt="MQTT command delivery" src="../images/demo4.png" /></picture> <img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank"> <a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture> <picture>
<img alt="Voiceprint recognition" src="../images/demo14.png" /></picture> <img alt="声纹识别" src="docs/images/demo14.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank"> <a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture> <picture>
<img alt="Custom voice timbre" src="../images/demo2.png" /></picture> <img alt="自定义音色" src="docs/images/demo2.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank"> <a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture> <picture>
<img alt="Talking in Cantonese" src="../images/demo3.png" /></picture> <img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -168,8 +167,8 @@ This project provides two deployment methods. Please choose based on your specif
#### 🚀 Deployment Method Selection #### 🚀 Deployment Method Selection
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials | | 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)| Local `FunASR` needs more memory; using APIs for everything keeps resource usage low | - | | **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) | 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) | | **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) |
For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md) For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md)
@ -210,15 +209,15 @@ This project provides the following testing tools to help you verify the system
| Tool Name | Location | Usage Method | Function Description | | Tool Name | Location | Usage Method | Function Description |
|:---:|:---|:---:|:---:| |:---:|:---|:---:|:---:|
| 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 | | 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 core modules such as ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) | | 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) |
> 💡 Note: When testing model speed, only models with configured keys will be tested. > 💡 Note: When testing model speed, only models with configured keys will be tested.
--- ---
## Feature List ✨ ## Feature List ✨
### Implemented ✅ ### Implemented ✅
![Full-module installation architecture diagram](../images/deploy2.png) ![请参考-全模块安装架构图](../images/deploy2.png)
| Feature Module | Description | | 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 | | 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 |
@ -226,15 +225,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 | | 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 | | Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction | | Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
| Intent Recognition | Supports pluggable external LLM intent recognition and autonomous LLM function calling, provides plugin-based intent processing mechanism | | Intent Recognition | Supports LLM intent recognition, Function Call 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 | | 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 | | 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 access point protocol, custom tool functions | | Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console | | 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, English, German, Vietnamese and Brazilian Portuguese display | | 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 model response performance testing tools and audio interaction testing tools | | Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management | | Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
| 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 | | Plugin System | Supports functional plugin extensions, custom plugin development, and plugin hot-loading |
### Under Development 🚧 ### Under Development 🚧
@ -254,7 +253,7 @@ Xiaozhi is an ecosystem. When using this product, you can also check out other [
| Usage Method | Supported Platforms | Free Platforms | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini | | OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
| Ollama interface calls | Ollama | - | | Ollama interface calls | Ollama | - |
| Dify interface calls | Dify | - | | Dify interface calls | Dify | - |
| FastGPT interface calls | FastGPT | - | | FastGPT interface calls | FastGPT | - |
@ -270,7 +269,7 @@ In fact, any LLM that supports OpenAI interface calls can be integrated and used
| Usage Method | Supported Platforms | Free Platforms | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | | OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
In fact, any VLLM that supports OpenAI interface calls can be integrated and used. In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
@ -280,8 +279,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(partial) | | 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, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 | | Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
--- ---
@ -297,8 +296,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Local use | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | | Local use | FunASR, SherpaASR | FunASR, SherpaASR |
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud and Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer | | Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
--- ---
@ -306,9 +305,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Interface calls | Voiceprint service (voiceprint-api) | - | | Local use | 3D-Speaker | 3D-Speaker |
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).
--- ---
@ -320,7 +317,6 @@ Voiceprint recognition requires a separately deployed [voiceprint-api](https://g
| Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval | | 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 | mem_local_short | Local summarization | Free | |
| Memory | nomem | No memory mode | Free | | | Memory | nomem | No memory mode | Free | |
| Memory | mem_report_only | Report only | Free | Only reports chat records, no memory summarization |
--- ---
@ -355,10 +351,11 @@ Voiceprint recognition requires a separately deployed [voiceprint-api](https://g
| <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. | | <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://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left"> <a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture> <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: 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/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" /> <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/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/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -1,364 +0,0 @@
[![Banners](../images/banner1.png)](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
![Banners](../images/banner2.png)
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 ✅
![Diagrama de arquitectura de la instalación de todos los módulos](../images/deploy2.png)
| 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>

View file

@ -22,7 +22,6 @@ 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_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_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_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"> <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" /> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a> </a>
@ -55,31 +54,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank"> <a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture> <picture>
<img alt="A sensação da velocidade de resposta" src="../images/demo9.png" /></picture> <img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank"> <a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture> <picture>
<img alt="O segredo para otimizar a velocidade" src="../images/demo6.png" /></picture> <img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank"> <a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture> <picture>
<img alt="Humano digital Xiaozhi com ativação por voz" src="../images/demo8.png" /></picture> <img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank"> <a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture> <picture>
<img alt="Chamadas de dispositivo para dispositivo" src="../images/demo0.png" /></picture> <img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank"> <a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture> <picture>
<img alt="Cenário médico complexo" src="../images/demo1.png" /></picture> <img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -87,31 +86,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank"> <a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture> <picture>
<img alt="Reproduzir música, consultar o tempo e ler as notícias" src="../images/demo7.png" /></picture> <img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank"> <a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture> <picture>
<img alt="Interrupção em tempo real" src="../images/demo10.png" /></picture> <img alt="实时打断" src="docs/images/demo10.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank"> <a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture> <picture>
<img alt="Reconhecer objetos com uma foto" src="../images/demo12.png" /></picture> <img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank"> <a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture> <picture>
<img alt="Controlar o acionamento de eletrodomésticos" src="../images/demo5.png" /></picture> <img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank"> <a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture> <picture>
<img alt="Tarefas com vários comandos" src="../images/demo11.png" /></picture> <img alt="多指令任务" src="docs/images/demo11.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -119,31 +118,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank"> <a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture> <picture>
<img alt="Ponto de acesso MCP" src="../images/demo13.png" /></picture> <img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank"> <a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture> <picture>
<img alt="Envio de comandos MQTT" src="../images/demo4.png" /></picture> <img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank"> <a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture> <picture>
<img alt="Reconhecimento de impressão vocal" src="../images/demo14.png" /></picture> <img alt="声纹识别" src="docs/images/demo14.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank"> <a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture> <picture>
<img alt="Tom de voz personalizado" src="../images/demo2.png" /></picture> <img alt="自定义音色" src="docs/images/demo2.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank"> <a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture> <picture>
<img alt="Conversa em cantonês" src="../images/demo3.png" /></picture> <img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -168,8 +167,8 @@ Este projeto oferece dois métodos de implantação. Por favor, escolha de acord
#### 🚀 Seleção do Método de Implantação #### 🚀 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 | | 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)| `FunASR` local exige mais memória; usar apenas APIs mantém o consumo de recursos baixo | - | | **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) | `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) | | **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) |
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md) Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md)
@ -210,15 +209,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 | | 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 | 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 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 de módulos principais como ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) | | 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) |
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados. > 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
--- ---
## Lista de Funcionalidades ✨ ## Lista de Funcionalidades ✨
### Implementado ✅ ### Implementado ✅
![Diagrama de arquitetura da instalação de todos os módulos](../images/deploy2.png) ![请参考-全模块安装架构图](../images/deploy2.png)
| Módulo de Funcionalidade | Descrição | | 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 | | 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 |
@ -226,15 +225,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 | | 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 | | 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 | | 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 externo e conectável, chamada de função autônoma do modelo de linguagem, fornece mecanismo de processamento de intenção baseado em plugins | | 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 |
| 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 | | 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 | | 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 ponto de acesso MCP, funções de ferramentas personalizadas | | 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 |
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente | | 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, Inglês, Alemão, Vietnamita e Português do Brasil | | 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 de resposta de modelo e ferramentas de teste de interação por áudio | | 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 |
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração | | 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 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 | | Sistema de Plugins | Suporta extensões de plugins funcionais, desenvolvimento de plugins personalizados e carregamento dinâmico de plugins |
### Em Desenvolvimento 🚧 ### Em Desenvolvimento 🚧
@ -254,7 +253,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini | | Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
| Chamadas via interface Ollama | Ollama | - | | Chamadas via interface Ollama | Ollama | - |
| Chamadas via interface Dify | Dify | - | | Chamadas via interface Dify | Dify | - |
| Chamadas via interface FastGPT | FastGPT | - | | Chamadas via interface FastGPT | FastGPT | - |
@ -262,7 +261,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
| Chamadas via interface Xinference | Xinference | - | | Chamadas via interface Xinference | Xinference | - |
| Chamadas via interface HomeAssistant | HomeAssistant | - | | 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.
--- ---
@ -270,7 +269,7 @@ Na verdade, qualquer LLM que suporte chamadas via interface OpenAI pode ser inte
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | | Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado. Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
@ -280,8 +279,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(parcial) | | 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, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 | | Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
--- ---
@ -297,8 +296,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | | Uso local | FunASR, SherpaASR | FunASR, SherpaASR |
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud e Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer | | Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
--- ---
@ -306,9 +305,7 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| Chamadas via interface | Serviço de voiceprint (voiceprint-api) | - | | Uso local | 3D-Speaker | 3D-Speaker |
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).
--- ---
@ -320,7 +317,6 @@ O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://
| Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente | | 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 | mem_local_short | Resumo local | Gratuito | |
| Memória | nomem | Modo sem memória | 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 |
--- ---
@ -355,10 +351,11 @@ O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://
| <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. | | <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://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left"> <a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture> <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: 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/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" /> <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/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/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -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ở 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/> <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/> Đượ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 vân giọng 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 giọng nói và kho tri thức
</p> </p>
<p align="center"> <p align="center">
@ -22,7 +22,6 @@ 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_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_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_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"> <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" /> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a> </a>
@ -39,7 +38,7 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
</br> </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) Đượ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> </br>
<img src="../images/hnlg.jpg" alt="Đại học Bách khoa Nam Trung Quốc" width="50%"> <img src="../images/hnlg.jpg" alt="华南理工大学" width="50%">
</p> </p>
--- ---
@ -55,31 +54,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank"> <a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture> <picture>
<img alt="Cảm giác tốc độ phản hồi" src="../images/demo9.png" /></picture> <img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank"> <a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture> <picture>
<img alt="Bí quyết tối ưu tốc độ" src="../images/demo6.png" /></picture> <img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank"> <a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture> <picture>
<img alt="Người ảo số Xiaozhi có đánh thức bằng giọng nói" src="../images/demo8.png" /></picture> <img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank"> <a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture> <picture>
<img alt="Gọi giữa các thiết bị" src="../images/demo0.png" /></picture> <img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank"> <a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture> <picture>
<img alt="Tình huống y tế phức tạp" src="../images/demo1.png" /></picture> <img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -87,31 +86,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank"> <a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture> <picture>
<img alt="Phát nhạc, tra cứu thời tiết và đọc tin tức" src="../images/demo7.png" /></picture> <img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank"> <a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture> <picture>
<img alt="Ngắt giữa chừng theo thời gian thực" src="../images/demo10.png" /></picture> <img alt="实时打断" src="docs/images/demo10.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank"> <a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture> <picture>
<img alt="Nhận dạng vật thể qua ảnh chụp" src="../images/demo12.png" /></picture> <img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank"> <a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture> <picture>
<img alt="Bật tắt thiết bị gia dụng" src="../images/demo5.png" /></picture> <img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank"> <a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture> <picture>
<img alt="Nhiệm vụ nhiều lệnh" src="../images/demo11.png" /></picture> <img alt="多指令任务" src="docs/images/demo11.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -119,31 +118,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td> <td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank"> <a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture> <picture>
<img alt="Điểm truy cập MCP" src="../images/demo13.png" /></picture> <img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank"> <a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture> <picture>
<img alt="Gửi lệnh MQTT" src="../images/demo4.png" /></picture> <img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank"> <a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture> <picture>
<img alt="Nhận dạng vân giọng" src="../images/demo14.png" /></picture> <img alt="声纹识别" src="docs/images/demo14.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank"> <a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture> <picture>
<img alt="Giọng nói tùy chỉnh" src="../images/demo2.png" /></picture> <img alt="自定义音色" src="docs/images/demo2.png" /></picture>
</a> </a>
</td> </td>
<td> <td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank"> <a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture> <picture>
<img alt="Trò chuyện bằng tiếng Quảng Đông" src="../images/demo3.png" /></picture> <img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
</a> </a>
</td> </td>
</tr> </tr>
@ -169,12 +168,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 #### 🚀 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 | | 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)| `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 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, 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à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â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) 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 Địa chỉ bảng điều khiển thông minh: https://2662r3426b.vicp.fun
@ -193,7 +192,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. > 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 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ừ 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ên module | Cài đặt miễn phí cho người mới | Cấu hình streaming | | Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|:---:|:---:|:---:| |:---:|:---:|:---:|
@ -211,15 +210,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 | | 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 | 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 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 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) | | 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) |
> 💡 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. > 💡 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 ✨ ## Danh sách tính năng ✨
### Đã thực hiện ✅ ### Đã thực hiện ✅
![Sơ đồ kiến trúc cài đặt đầy đủ các module](../images/deploy2.png) ![请参考-全模块安装架构图](../images/deploy2.png)
| Module chức năng | Mô tả | | 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 | | 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 |
@ -232,10 +231,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 | | 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 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 | | 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, tiếng Đức, tiếng Việt và tiếng Bồ Đào Nha Brazil | | 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 phản hồi mô hình và công cụ kiểm tra tương tác âm thanh | | 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 |
| 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ỗ 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 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ụ | | 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 |
### Đang phát triển 🚧 ### Đang phát triển 🚧
@ -255,7 +254,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í | | 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, LM Studio | Zhipu, Gemini | | Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
| Gọi giao diện ollama | Ollama | - | | Gọi giao diện ollama | Ollama | - |
| Gọi giao diện dify | Dify | - | | Gọi giao diện dify | Dify | - |
| Gọi giao diện fastgpt | Fastgpt | - | | Gọi giao diện fastgpt | Fastgpt | - |
@ -263,7 +262,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 xinference | Xinference | - |
| Gọi giao diện homeassistant | HomeAssistant | - | | 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.
--- ---
@ -271,9 +270,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í | | 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, iFLYTEK | Zhipu ChatGLMVLLM | | Gọi giao diện openai | Alibaba Bailian, Zhipu ChatGLMVLLM | 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.
--- ---
@ -281,8 +280,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í | | 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, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(một phần) | | 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, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 | | 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 |
--- ---
@ -298,8 +297,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í | | 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, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | | Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
| Gọi giao diện | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud và Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer | | Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
--- ---
@ -307,9 +306,7 @@ 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í | | 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 | Dịch vụ nhận dạng vân giọng (voiceprint-api) | - | | Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
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).
--- ---
@ -321,7 +318,6 @@ Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com
| 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 | [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 | 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 | 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ớ |
--- ---
@ -356,10 +352,11 @@ Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com
| <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. | | <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://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left"> <a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture> <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: 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/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" /> <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/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/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -16,11 +16,11 @@
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`voiceprint-api-main` 点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`voiceprint-api-main`
你需要把它重命名成`voiceprint-api`。 你需要把它重命名成`voiceprint-api`。
## 第二步, 确认 MySQL 能访问 ## 第二步, 创建数据库和表
声纹识别需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。 声纹识别需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
你可以试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。 你可以你试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
``` ```
telnet 127.0.0.1 3306 telnet 127.0.0.1 3306
``` ```
@ -39,7 +39,7 @@ telnet 127.0.0.1 3306
networks: networks:
- default - default
expose: expose:
- 3306 - "3306:3306"
``` ```
修改后 修改后
@ -58,9 +58,8 @@ telnet 127.0.0.1 3306
# 进入你docker-compose_all.yml所在的文件夹,例如我的是xiaozhi-server # 进入你docker-compose_all.yml所在的文件夹,例如我的是xiaozhi-server
cd xiaozhi-server cd xiaozhi-server
docker compose -f docker-compose_all.yml down docker compose -f docker-compose_all.yml down
docker compose -f docker-compose_all.yml up -d docker compose -f docker-compose.yml up -d
``` ```
数据库服务`xiaozhi-esp32-server-db`在`docker-compose_all.yml`里,最小化的`docker-compose.yml`只有服务本身,所以两条命令都用`docker-compose_all.yml`。
启动完后,在宿主机再使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。 启动完后,在宿主机再使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
``` ```
@ -172,8 +171,6 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
然后搜索参数`server.voice_print`,此时,它的值应该是`null`值。 然后搜索参数`server.voice_print`,此时,它的值应该是`null`值。
点击修改按钮,把上一步得来的`声纹接口地址`粘贴到`参数值`里。然后保存。 点击修改按钮,把上一步得来的`声纹接口地址`粘贴到`参数值`里。然后保存。
声纹识别的相似度阈值是另一个系统参数`server.voiceprint_similarity_threshold`(默认0.4,范围0.0-1.0,数值越高越严格),要调整就在同一个`参数管理`页面里改。
如果能保存成功,说明一切顺利,你可以去智能体查看效果了。如果不成功,说明智控台无法访问声纹识别,很大概率是网络防火墙,或者没有填写正确的局域网ip。 如果能保存成功,说明一切顺利,你可以去智能体查看效果了。如果不成功,说明智控台无法访问声纹识别,很大概率是网络防火墙,或者没有填写正确的局域网ip。
## 第二步 设置智能体记忆模式 ## 第二步 设置智能体记忆模式
@ -189,7 +186,7 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
在智控台,`智能体管理`页面,在智能体的面板里,有一个`声纹识别`按钮,点击它。在底部有一个`新增按钮`。就可以对某个人说的话进行声纹注册。 在智控台,`智能体管理`页面,在智能体的面板里,有一个`声纹识别`按钮,点击它。在底部有一个`新增按钮`。就可以对某个人说的话进行声纹注册。
在弹出的框里,`描述`这个属性建议填写上,可以是这个人的职业、性格、爱好。方便智能体对说话人进行分析和了解。 在弹出的框里,`描述`这个属性建议填写上,可以是这个人的职业、性格、爱好。方便智能体对说话人进行分析和了解。
## 第五步 验证效果 ## 第三步 和你的智能体聊天
将你的设备通电,问它,你知道我是谁吗?如果他能回答得出,说明声纹识别功能正常。 将你的设备通电,问它,你知道我是谁吗?如果他能回答得出,说明声纹识别功能正常。
@ -208,9 +205,6 @@ voiceprint:
- "test1,张三,张三是一个程序员" - "test1,张三,张三是一个程序员"
- "test2,李四,李四是一个产品经理" - "test2,李四,李四是一个产品经理"
- "test3,王五,王五是一个设计师" - "test3,王五,王五是一个设计师"
# 声纹识别相似度阈值,范围0.0-1.0,默认0.4
# 数值越高越严格,减少误识别但可能增加拒识率
similarity_threshold: 0.4
``` ```
把上一步得来的 `声纹接口地址` 粘贴到 `url` 里。然后保存。 把上一步得来的 `声纹接口地址` 粘贴到 `url` 里。然后保存。

View file

@ -2,16 +2,13 @@
## 功能简介 ## 功能简介
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持五个搜索源:秘塔(Metaso)、Tavily、Serply、Outcrawl和SpecStream,用户可根据需要选择其中一个。 联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持两个搜索源:秘塔(Metaso)和Tavily,用户可根据需要选择其中一个。
## API Key申请指南 ## API Key申请指南
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`、`Outcrawl搜索`和`SpecStream搜索`。 目前我们适配了`秘塔搜索`和`Tavily搜索`。
- Tavily搜索:每个月1000次免费额度。 - Tavily搜索:每个月1000次免费额度。
- 秘塔搜索:拥有较为优质的国内数据源。 - 秘塔搜索:拥有较为优质的国内数据源。
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
- SpecStream搜索:注册赠送10美元,每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
## API Key申请指南 ## API Key申请指南
@ -27,27 +24,6 @@
- 在控制台中创建API Key - 在控制台中创建API Key
- 复制生成的API Key(以 `tvly-` 为前缀),这是配置所需的关键信息 - 复制生成的API Key(以 `tvly-` 为前缀),这是配置所需的关键信息
### 方式三:使用Serply搜索
- 访问 [Serply](https://serply.io),注册并登录账号
- 在控制台中创建API Key
- 复制生成的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. 使用智控台部署(推荐) ### 方式1. 使用智控台部署(推荐)
@ -56,14 +32,14 @@
- 进入"配置角色"页面,选择要配置的智能体 - 进入"配置角色"页面,选择要配置的智能体
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件 - 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
- 勾选"联网搜索" - 勾选"联网搜索"
- 填入搜索源(`metaso`、`tavily`、`serply`、`outcrawl`或`specstream`),并将对应的`API Key`填入配置项 - 填入搜索源(`metaso`或`tavily`),并将对应的`API Key`填入配置项
- 保存配置,再保存智能体配置 - 保存配置,再保存智能体配置
### 方式2. 单模块xiaozhi-server部署 ### 方式2. 单模块xiaozhi-server部署
在 `data/.config.yaml` 中配置: 在 `data/.config.yaml` 中配置:
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply`、`outcrawl` 或 `specstream` - 将搜索源填入 `provider`,可选值为 `metaso` 或 `tavily`
- 将申请到的API Key填入 `api_key` - 将申请到的API Key填入 `api_key`
```yaml ```yaml

View file

@ -16,28 +16,3 @@ Vue 3.x
# 接口文档 # 接口文档
启动后打开:http://localhost:8002/xiaozhi/doc.html 启动后打开: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
```

View file

@ -20,20 +20,18 @@
<java.version>21</java.version> <java.version>21</java.version>
<junit.version>5.10.1</junit.version> <junit.version>5.10.1</junit.version>
<druid.version>1.2.20</druid.version> <druid.version>1.2.20</druid.version>
<mybatisplus.version>3.5.17</mybatisplus.version> <mybatisplus.version>3.5.5</mybatisplus.version>
<hutool.version>5.8.46</hutool.version> <hutool.version>5.8.24</hutool.version>
<jsoup.version>1.22.2</jsoup.version> <jsoup.version>1.19.1</jsoup.version>
<knife4j.version>4.6.0</knife4j.version> <knife4j.version>4.6.0</knife4j.version>
<springdoc.version>2.8.8</springdoc.version> <springdoc.version>2.8.8</springdoc.version>
<commons-lang3.version>3.20.0</commons-lang3.version> <commons-lang3.version>3.18.0</commons-lang3.version>
<shiro.version>2.0.2</shiro.version> <shiro.version>2.0.2</shiro.version>
<captcha.version>1.6.2</captcha.version> <captcha.version>1.6.2</captcha.version>
<guava.version>33.6.0-jre</guava.version> <guava.version>33.0.0-jre</guava.version>
<liquibase-core.version>4.20.0</liquibase-core.version> <liquibase-core.version>4.20.0</liquibase-core.version>
<aliyun-sms-version>4.1.0</aliyun-sms-version> <aliyun-sms-version>4.1.0</aliyun-sms-version>
<okio-version>3.4.0</okio-version> <okio-version>3.4.0</okio-version>
<skipTests>false</skipTests>
<argLine></argLine>
</properties> </properties>
<dependencies> <dependencies>
@ -177,13 +175,13 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version> <version>${mybatisplus.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis-plus-jsqlparser-4.9</artifactId> <artifactId>mybatis-spring</artifactId>
<version>${mybatisplus.version}</version> <version>3.0.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
@ -273,22 +271,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<proc>full</proc>
<compilerArgs>
<arg>-Xlint:deprecation,unchecked</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<configuration> <configuration>
<skipTests>${skipTests}</skipTests> <skipTests>true</skipTests>
<argLine>@{argLine} -Xshare:off -javaagent:"${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar"</argLine>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View file

@ -1,44 +0,0 @@
#!/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 "集成测试都跑过了"

View file

@ -324,7 +324,7 @@ public interface Constant {
/** /**
* 版本号 * 版本号
*/ */
public static final String VERSION = "0.9.8"; public static final String VERSION = "0.9.5";
/** /**
* 无效固件URL * 无效固件URL

View file

@ -67,7 +67,7 @@ public class DataFilterInterceptor implements InnerInterceptor {
private String getSelect(String buildSql, DataScope scope) { private String getSelect(String buildSql, DataScope scope) {
try { try {
Select select = (Select) CCJSqlParserUtil.parse(buildSql); Select select = (Select) CCJSqlParserUtil.parse(buildSql);
PlainSelect plainSelect = select.getPlainSelect(); PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
Expression expression = plainSelect.getWhere(); Expression expression = plainSelect.getWhere();
if (expression == null) { if (expression == null) {
@ -82,4 +82,4 @@ public class DataFilterInterceptor implements InnerInterceptor {
return buildSql; return buildSql;
} }
} }
} }

View file

@ -5,7 +5,7 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.BiFunction; import java.util.function.BiConsumer;
import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.Log;
@ -81,8 +81,8 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
// 处理排序字段 // 处理排序字段
if (orderField instanceof String) { if (orderField instanceof String) {
orderFields.add((String) orderField); orderFields.add((String) orderField);
} else if (orderField instanceof List<?> fields) { } else if (orderField instanceof List) {
fields.forEach(field -> orderFields.add(String.class.cast(field))); orderFields.addAll((List<String>) orderField);
} }
// 有排序字段则排序 // 有排序字段则排序
@ -142,12 +142,11 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
return SqlHelper.retBool(result); return SqlHelper.retBool(result);
} }
protected Class<?> currentMapperClass() { protected Class<M> currentMapperClass() {
return ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0); return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0);
} }
@Override @Override
@SuppressWarnings("unchecked")
public Class<T> currentModelClass() { public Class<T> currentModelClass() {
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1); return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1);
} }
@ -182,9 +181,8 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
* 执行批量操作 * 执行批量操作
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiFunction<SqlSession, E, Integer> operation) { protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
return SqlHelper.executeBatch(SqlHelper.sqlSessionFactory(this.currentModelClass()), this.log, list, batchSize, return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer);
operation);
} }
@Override @Override
@ -211,7 +209,7 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
return executeBatch(entityList, batchSize, (sqlSession, entity) -> { return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>(); MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity); param.put(Constants.ENTITY, entity);
return sqlSession.update(sqlStatement, param); sqlSession.update(sqlStatement, param);
}); });
} }
@ -227,6 +225,6 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
@Override @Override
public boolean deleteBatchIds(Collection<? extends Serializable> idList) { public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
return SqlHelper.retBool(baseDao.deleteByIds(idList)); return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
} }
} }

View file

@ -24,7 +24,6 @@ import xiaozhi.common.utils.ConvertUtils;
public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T> public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T>
implements CrudService<T, D> { implements CrudService<T, D> {
@SuppressWarnings("unchecked")
protected Class<D> currentDtoClass() { protected Class<D> currentDtoClass() {
return (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2); return (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2);
} }
@ -71,6 +70,6 @@ public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends Bas
@Override @Override
public void delete(Serializable[] ids) { public void delete(Serializable[] ids) {
baseDao.deleteByIds(Arrays.asList(ids)); baseDao.deleteBatchIds(Arrays.asList(ids));
} }
} }

View file

@ -0,0 +1,52 @@
package xiaozhi.common.utils;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 哈希加密算法的工具类
* @author zjy
*/
@Slf4j
public class HashEncryptionUtil {
/**
* 使用md5进行加密
* @param context 被加密的内容
* @return 哈希值
*/
public static String Md5hexDigest(String context){
return hexDigest(context,"MD5");
}
/**
* 指定哈希算法进行加密
* @param context 被加密的内容
* @param algorithm 哈希算法
* @return 哈希值
*/
public static String hexDigest(String context,String algorithm ){
// 获取MD5算法实例
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
log.error("加密失败的算法:{}",algorithm);
throw new RuntimeException("加密失败,"+ algorithm +"哈希算法系统不支持");
}
// 计算智能体id的MD5值
byte[] messageDigest = md.digest(context.getBytes());
// 将字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}

View file

@ -1,9 +1,7 @@
package xiaozhi.common.utils; package xiaozhi.common.utils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -18,10 +16,6 @@ import cn.hutool.core.util.StrUtil;
*/ */
public class JsonUtils { public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper(); private static final ObjectMapper objectMapper = new ObjectMapper();
private static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<>() {
};
private static final TypeReference<List<Map<String, Object>>> STRING_OBJECT_MAP_LIST = new TypeReference<>() {
};
public static String toJsonString(Object object) { public static String toJsonString(Object object) {
try { try {
@ -73,59 +67,4 @@ public class JsonUtils {
} }
} }
public static Map<String, Object> parseMap(String text) {
if (StrUtil.isEmpty(text)) {
return null;
}
return parseObject(text, STRING_OBJECT_MAP);
}
public static List<Map<String, Object>> parseMapList(String text) {
if (StrUtil.isEmpty(text)) {
return null;
}
return parseObject(text, STRING_OBJECT_MAP_LIST);
}
public static Map<String, Object> toStringObjectMap(Object value) {
if (value == null) {
return null;
}
if (!(value instanceof Map<?, ?> map)) {
throw new ClassCastException("Expected Map but got " + value.getClass().getName());
}
Map<String, Object> result = new LinkedHashMap<>(map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
result.put(String.class.cast(entry.getKey()), entry.getValue());
}
return result;
}
public static List<Map<String, Object>> toStringObjectMapList(Object value) {
if (value == null) {
return null;
}
List<?> list = List.class.cast(value);
List<Map<String, Object>> result = new ArrayList<>(list.size());
for (Object item : list) {
result.add(toStringObjectMap(item));
}
return result;
}
public static <T> List<T> toList(Object value, Class<T> elementType) {
if (value == null) {
return null;
}
List<?> list = List.class.cast(value);
List<T> result = new ArrayList<>(list.size());
for (Object item : list) {
result.add(elementType.cast(item));
}
return result;
}
} }

View file

@ -75,11 +75,11 @@ public class SensitiveDataUtils {
Object value = jsonObject.get(key); Object value = jsonObject.get(key);
if (SENSITIVE_FIELDS.contains(key.toLowerCase()) && value instanceof String) { if (SENSITIVE_FIELDS.contains(key.toLowerCase()) && value instanceof String) {
result.set(key, maskMiddle((String) value)); result.put(key, maskMiddle((String) value));
} else if (value instanceof JSONObject) { } else if (value instanceof JSONObject) {
result.set(key, maskSensitiveFields((JSONObject) value)); result.put(key, maskSensitiveFields((JSONObject) value));
} else { } else {
result.set(key, value); result.put(key, value);
} }
} }
@ -162,4 +162,4 @@ public class SensitiveDataUtils {
} }
} }
} }
} }

View file

@ -0,0 +1,89 @@
package xiaozhi.common.utils;
import cn.hutool.core.util.ReUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 通用工具类
*/
public class ToolUtil {
private static final Logger logger = LoggerFactory.getLogger(ToolUtil.class);
/**
* 对象是否不为空(新增)
*/
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
/**
* 对象是否为空
*/
public static boolean isEmpty(Object o) {
if (o == null) {
return true;
}
if (o instanceof String) {
if (o.toString().trim().equals("")) {
return true;
}
} else if (o instanceof List) {
if (((List) o).size() == 0) {
return true;
}
} else if (o instanceof Map) {
if (((Map) o).size() == 0) {
return true;
}
} else if (o instanceof Set) {
if (((Set) o).size() == 0) {
return true;
}
} else if (o instanceof Object[]) {
if (((Object[]) o).length == 0) {
return true;
}
} else if (o instanceof int[]) {
if (((int[]) o).length == 0) {
return true;
}
} else if (o instanceof long[]) {
if (((long[]) o).length == 0) {
return true;
}
}
return false;
}
/**
* 对象组中是否存在空对象
*/
public static boolean isOneEmpty(Object... os) {
for (Object o : os) {
if (isEmpty(o)) {
return true;
}
}
return false;
}
/**
* 对象组中是否全是空对象
*/
public static boolean isAllEmpty(Object... os) {
for (Object o : os) {
if (!isEmpty(o)) {
return false;
}
}
return true;
}
}

View file

@ -22,10 +22,10 @@ public class SqlFilter {
return null; return null;
} }
// 去掉'|"|;|\字符 // 去掉'|"|;|\字符
str = str.replace("'", ""); str = StringUtils.replace(str, "'", "");
str = str.replace("\"", ""); str = StringUtils.replace(str, "\"", "");
str = str.replace(";", ""); str = StringUtils.replace(str, ";", "");
str = str.replace("\\", ""); str = StringUtils.replace(str, "\\", "");
// 转换成小写 // 转换成小写
str = str.toLowerCase(); str = str.toLowerCase();

View file

@ -1,103 +0,0 @@
package xiaozhi.modules.agent.Enums;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import lombok.Getter;
import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO;
import xiaozhi.modules.agent.dto.AgentUpdateDTO;
import xiaozhi.modules.agent.entity.AgentEntity;
@Getter
public enum AgentSnapshotField {
AGENT_CODE("agentCode", AgentSnapshotDataDTO::getAgentCode, AgentUpdateDTO::getAgentCode,
(agent, data) -> agent.setAgentCode(data.getAgentCode())),
AGENT_NAME("agentName", AgentSnapshotDataDTO::getAgentName, AgentUpdateDTO::getAgentName,
(agent, data) -> agent.setAgentName(data.getAgentName())),
ASR_MODEL_ID("asrModelId", AgentSnapshotDataDTO::getAsrModelId, AgentUpdateDTO::getAsrModelId,
(agent, data) -> agent.setAsrModelId(data.getAsrModelId())),
VAD_MODEL_ID("vadModelId", AgentSnapshotDataDTO::getVadModelId, AgentUpdateDTO::getVadModelId,
(agent, data) -> agent.setVadModelId(data.getVadModelId())),
LLM_MODEL_ID("llmModelId", AgentSnapshotDataDTO::getLlmModelId, AgentUpdateDTO::getLlmModelId,
(agent, data) -> agent.setLlmModelId(data.getLlmModelId())),
SLM_MODEL_ID("slmModelId", AgentSnapshotDataDTO::getSlmModelId, AgentUpdateDTO::getSlmModelId,
(agent, data) -> agent.setSlmModelId(data.getSlmModelId())),
VLLM_MODEL_ID("vllmModelId", AgentSnapshotDataDTO::getVllmModelId, AgentUpdateDTO::getVllmModelId,
(agent, data) -> agent.setVllmModelId(data.getVllmModelId())),
TTS_MODEL_ID("ttsModelId", AgentSnapshotDataDTO::getTtsModelId, AgentUpdateDTO::getTtsModelId,
(agent, data) -> agent.setTtsModelId(data.getTtsModelId())),
TTS_VOICE_ID("ttsVoiceId", AgentSnapshotDataDTO::getTtsVoiceId, AgentUpdateDTO::getTtsVoiceId,
(agent, data) -> agent.setTtsVoiceId(data.getTtsVoiceId())),
TTS_LANGUAGE("ttsLanguage", AgentSnapshotDataDTO::getTtsLanguage, AgentUpdateDTO::getTtsLanguage,
(agent, data) -> agent.setTtsLanguage(data.getTtsLanguage())),
TTS_VOLUME("ttsVolume", AgentSnapshotDataDTO::getTtsVolume, AgentUpdateDTO::getTtsVolume,
(agent, data) -> agent.setTtsVolume(data.getTtsVolume())),
TTS_RATE("ttsRate", AgentSnapshotDataDTO::getTtsRate, AgentUpdateDTO::getTtsRate,
(agent, data) -> agent.setTtsRate(data.getTtsRate())),
TTS_PITCH("ttsPitch", AgentSnapshotDataDTO::getTtsPitch, AgentUpdateDTO::getTtsPitch,
(agent, data) -> agent.setTtsPitch(data.getTtsPitch())),
MEM_MODEL_ID("memModelId", AgentSnapshotDataDTO::getMemModelId, AgentUpdateDTO::getMemModelId,
(agent, data) -> agent.setMemModelId(data.getMemModelId())),
INTENT_MODEL_ID("intentModelId", AgentSnapshotDataDTO::getIntentModelId, AgentUpdateDTO::getIntentModelId,
(agent, data) -> agent.setIntentModelId(data.getIntentModelId())),
CHAT_HISTORY_CONF("chatHistoryConf", AgentSnapshotDataDTO::getChatHistoryConf, AgentUpdateDTO::getChatHistoryConf,
(agent, data) -> agent.setChatHistoryConf(data.getChatHistoryConf())),
SYSTEM_PROMPT("systemPrompt", AgentSnapshotDataDTO::getSystemPrompt, AgentUpdateDTO::getSystemPrompt,
(agent, data) -> agent.setSystemPrompt(data.getSystemPrompt())),
SUMMARY_MEMORY("summaryMemory", AgentSnapshotDataDTO::getSummaryMemory, AgentUpdateDTO::getSummaryMemory,
(agent, data) -> agent.setSummaryMemory(data.getSummaryMemory())),
LANG_CODE("langCode", AgentSnapshotDataDTO::getLangCode, AgentUpdateDTO::getLangCode,
(agent, data) -> agent.setLangCode(data.getLangCode())),
LANGUAGE("language", AgentSnapshotDataDTO::getLanguage, AgentUpdateDTO::getLanguage,
(agent, data) -> agent.setLanguage(data.getLanguage())),
SORT("sort", AgentSnapshotDataDTO::getSort, AgentUpdateDTO::getSort,
(agent, data) -> agent.setSort(data.getSort())),
FUNCTIONS("functions", AgentSnapshotDataDTO::getFunctions, AgentUpdateDTO::getFunctions, null),
CONTEXT_PROVIDERS("contextProviders", AgentSnapshotDataDTO::getContextProviders,
AgentUpdateDTO::getContextProviders, null),
CORRECT_WORD_FILE_IDS("correctWordFileIds", AgentSnapshotDataDTO::getCorrectWordFileIds,
AgentUpdateDTO::getCorrectWordFileIds, null),
TAG_NAMES("tagNames", AgentSnapshotDataDTO::getTagNames, AgentUpdateDTO::getTagNames, null);
private final String fieldName;
private final Function<AgentSnapshotDataDTO, Object> snapshotGetter;
private final Function<AgentUpdateDTO, Object> updateGetter;
private final BiConsumer<AgentEntity, AgentSnapshotDataDTO> restoreApplier;
AgentSnapshotField(String fieldName, Function<AgentSnapshotDataDTO, Object> snapshotGetter,
Function<AgentUpdateDTO, Object> updateGetter,
BiConsumer<AgentEntity, AgentSnapshotDataDTO> restoreApplier) {
this.fieldName = fieldName;
this.snapshotGetter = snapshotGetter;
this.updateGetter = updateGetter;
this.restoreApplier = restoreApplier;
}
public static List<String> names() {
return Arrays.stream(values()).map(AgentSnapshotField::getFieldName).toList();
}
public static String canonicalName(String fieldName) {
return "tags".equals(fieldName) ? TAG_NAMES.getFieldName() : fieldName;
}
public Object snapshotValue(AgentSnapshotDataDTO data) {
return data == null ? null : snapshotGetter.apply(data);
}
public Object updateValue(AgentUpdateDTO data) {
return data == null ? null : updateGetter.apply(data);
}
public boolean isRestorableAgentField() {
return restoreApplier != null;
}
public void applyTo(AgentEntity agent, AgentSnapshotDataDTO data) {
if (restoreApplier != null) {
restoreApplier.accept(agent, data);
}
}
}

View file

@ -19,6 +19,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
@ -26,13 +28,10 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.user.UserDetail; import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.common.utils.ResultUtils; import xiaozhi.common.utils.ResultUtils;
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
@ -42,15 +41,22 @@ import xiaozhi.modules.agent.dto.AgentDTO;
import xiaozhi.modules.agent.dto.AgentMemoryDTO; import xiaozhi.modules.agent.dto.AgentMemoryDTO;
import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO;
import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.entity.AgentEntity;
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.dto.AgentTagDTO; import xiaozhi.modules.agent.dto.AgentTagDTO;
import xiaozhi.modules.agent.entity.AgentTagEntity; import xiaozhi.modules.agent.entity.AgentTagEntity;
import xiaozhi.modules.agent.service.AgentTagService; import xiaozhi.modules.agent.service.AgentTagService;
import xiaozhi.modules.agent.service.AgentChatAudioService; import xiaozhi.modules.agent.service.AgentChatAudioService;
import xiaozhi.modules.agent.service.AgentChatHistoryService; import xiaozhi.modules.agent.service.AgentChatHistoryService;
import xiaozhi.modules.agent.service.AgentChatSummaryService; import xiaozhi.modules.agent.service.AgentChatSummaryService;
import xiaozhi.modules.agent.service.AgentContextProviderService;
import xiaozhi.modules.agent.service.AgentPluginMappingService;
import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.agent.service.AgentTemplateService;
import xiaozhi.modules.correctword.service.CorrectWordFileService;
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.agent.vo.AgentInfoVO;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体管理") @Tag(name = "智能体管理")
@ -58,38 +64,17 @@ import xiaozhi.modules.security.user.SecurityUser;
@RestController @RestController
@RequestMapping("/agent") @RequestMapping("/agent")
public class AgentController { public class AgentController {
private static final long AUDIO_PLAY_TOKEN_EXPIRE_SECONDS = 300L;
private final AgentService agentService; private final AgentService agentService;
private final AgentTemplateService agentTemplateService;
private final DeviceService deviceService;
private final AgentChatHistoryService agentChatHistoryService; private final AgentChatHistoryService agentChatHistoryService;
private final AgentChatAudioService agentChatAudioService; private final AgentChatAudioService agentChatAudioService;
private final AgentPluginMappingService agentPluginMappingService;
private final AgentContextProviderService agentContextProviderService;
private final AgentChatSummaryService agentChatSummaryService; private final AgentChatSummaryService agentChatSummaryService;
private final RedisUtils redisUtils; private final RedisUtils redisUtils;
private final AgentTagService agentTagService; private final AgentTagService agentTagService;
private final CorrectWordFileService correctWordFileService;
private void requireAgentPermission(String agentId) {
if (!agentService.checkAgentPermission(agentId, SecurityUser.getUserId())) {
throw new RenException(ErrorCode.NO_PERMISSION);
}
}
private String requireSessionAgent(String sessionId) {
String agentId = agentChatHistoryService.getAgentIdBySessionId(sessionId);
if (StringUtils.isBlank(agentId)) {
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
}
agentService.getAgentById(agentId);
return agentId;
}
private String requireAudioPermission(String audioId) {
String agentId = agentChatHistoryService.getAgentIdByAudioId(audioId);
if (StringUtils.isBlank(agentId)) {
throw new RenException(ErrorCode.NO_PERMISSION);
}
requireAgentPermission(agentId);
return agentId;
}
@GetMapping("/list") @GetMapping("/list")
@Operation(summary = "获取用户智能体列表") @Operation(summary = "获取用户智能体列表")
@ -121,7 +106,7 @@ public class AgentController {
@Operation(summary = "获取智能体详情") @Operation(summary = "获取智能体详情")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) { public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) {
AgentInfoVO agent = agentService.getAgentById(id, SecurityUser.getUserId()); AgentInfoVO agent = agentService.getAgentById(id);
return ResultUtils.success(agent); return ResultUtils.success(agent);
} }
@ -135,16 +120,20 @@ public class AgentController {
@PutMapping("/saveMemory/{macAddress}") @PutMapping("/saveMemory/{macAddress}")
@Operation(summary = "根据设备id更新智能体") @Operation(summary = "根据设备id更新智能体")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) { public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) {
agentService.updateAgentMemoryByDeviceMacAddress(macAddress, dto, SecurityUser.getUserId()); DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
return new Result<Void>().ok(null); if (device == null) {
return new Result<>();
}
AgentUpdateDTO agentUpdateDTO = new AgentUpdateDTO();
agentUpdateDTO.setSummaryMemory(dto.getSummaryMemory());
agentService.updateAgentById(device.getAgentId(), agentUpdateDTO);
return new Result<>();
} }
@PostMapping("/chat-summary/{sessionId}/save") @PostMapping("/chat-summary/{sessionId}/save")
@Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)") @Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)")
public Result<Void> generateAndSaveChatSummary(@PathVariable String sessionId) { public Result<Void> generateAndSaveChatSummary(@PathVariable String sessionId) {
requireSessionAgent(sessionId);
try { try {
// 异步执行总结生成任务,立即返回成功响应 // 异步执行总结生成任务,立即返回成功响应
new Thread(() -> { new Thread(() -> {
@ -166,7 +155,6 @@ public class AgentController {
@PostMapping("/chat-title/{sessionId}/generate") @PostMapping("/chat-title/{sessionId}/generate")
@Operation(summary = "根据会话ID生成聊天标题") @Operation(summary = "根据会话ID生成聊天标题")
public Result<Void> generateAndSaveChatTitle(@PathVariable String sessionId) { public Result<Void> generateAndSaveChatTitle(@PathVariable String sessionId) {
requireSessionAgent(sessionId);
agentChatSummaryService.generateAndSaveChatTitle(sessionId); agentChatSummaryService.generateAndSaveChatTitle(sessionId);
return new Result<Void>().ok(null); return new Result<Void>().ok(null);
} }
@ -175,7 +163,7 @@ public class AgentController {
@Operation(summary = "更新智能体") @Operation(summary = "更新智能体")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) { public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) {
agentService.updateAgentById(id, dto, SecurityUser.getUserId()); agentService.updateAgentById(id, dto);
return new Result<>(); return new Result<>();
} }
@ -183,10 +171,30 @@ public class AgentController {
@Operation(summary = "删除智能体") @Operation(summary = "删除智能体")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable String id) { public Result<Void> delete(@PathVariable String id) {
agentService.deleteAgentById(id, SecurityUser.getUserId()); // 先删除关联的设备
deviceService.deleteByAgentId(id);
// 删除关联的聊天记录
agentChatHistoryService.deleteByAgentId(id, true, true);
// 删除关联的插件
agentPluginMappingService.deleteByAgentId(id);
// 删除关联的上下文源配置
agentContextProviderService.deleteByAgentId(id);
// 删除关联的替换词文件关联记录
correctWordFileService.deleteMappingsByAgentId(id);
// 再删除智能体
agentService.deleteById(id);
return new Result<>(); return new Result<>();
} }
@GetMapping("/template")
@Operation(summary = "智能体模板模板列表")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list);
}
@GetMapping("/{id}/sessions") @GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表") @Operation(summary = "获取智能体会话列表")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
@ -197,7 +205,6 @@ public class AgentController {
public Result<PageData<AgentChatSessionDTO>> getAgentSessions( public Result<PageData<AgentChatSessionDTO>> getAgentSessions(
@PathVariable("id") String id, @PathVariable("id") String id,
@Parameter(hidden = true) @RequestParam Map<String, Object> params) { @Parameter(hidden = true) @RequestParam Map<String, Object> params) {
requireAgentPermission(id);
params.put("agentId", id); params.put("agentId", id);
PageData<AgentChatSessionDTO> page = agentChatHistoryService.getSessionListByAgentId(params); PageData<AgentChatSessionDTO> page = agentChatHistoryService.getSessionListByAgentId(params);
return new Result<PageData<AgentChatSessionDTO>>().ok(page); return new Result<PageData<AgentChatSessionDTO>>().ok(page);
@ -245,7 +252,6 @@ public class AgentController {
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<String> getContentByAudioId( public Result<String> getContentByAudioId(
@PathVariable("id") String id) { @PathVariable("id") String id) {
requireAudioPermission(id);
// 查询聊天记录 // 查询聊天记录
String data = agentChatHistoryService.getContentByAudioId(id); String data = agentChatHistoryService.getContentByAudioId(id);
return new Result<String>().ok(data); return new Result<String>().ok(data);
@ -255,13 +261,12 @@ public class AgentController {
@Operation(summary = "获取音频下载ID") @Operation(summary = "获取音频下载ID")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<String> getAudioId(@PathVariable("audioId") String audioId) { public Result<String> getAudioId(@PathVariable("audioId") String audioId) {
requireAudioPermission(audioId);
byte[] audioData = agentChatAudioService.getAudio(audioId); byte[] audioData = agentChatAudioService.getAudio(audioId);
if (audioData == null) { if (audioData == null) {
return new Result<String>().error("音频不存在"); return new Result<String>().error("音频不存在");
} }
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId, AUDIO_PLAY_TOKEN_EXPIRE_SECONDS); redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId);
return new Result<String>().ok(uuid); return new Result<String>().ok(uuid);
} }
@ -317,7 +322,6 @@ public class AgentController {
@Operation(summary = "获取智能体的标签") @Operation(summary = "获取智能体的标签")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<List<AgentTagDTO>> getAgentTags(@PathVariable String id) { public Result<List<AgentTagDTO>> getAgentTags(@PathVariable String id) {
requireAgentPermission(id);
List<AgentTagDTO> tags = agentTagService.getTagsByAgentId(id); List<AgentTagDTO> tags = agentTagService.getTagsByAgentId(id);
return new Result<List<AgentTagDTO>>().ok(tags); return new Result<List<AgentTagDTO>>().ok(tags);
} }
@ -326,14 +330,10 @@ public class AgentController {
@Operation(summary = "保存智能体的标签") @Operation(summary = "保存智能体的标签")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Void> saveAgentTags(@PathVariable String id, @RequestBody Map<String, Object> params) { public Result<Void> saveAgentTags(@PathVariable String id, @RequestBody Map<String, Object> params) {
requireAgentPermission(id); List<String> tagIds = (List<String>) params.get("tagIds");
List<String> tagIds = JsonUtils.toList(params.get("tagIds"), String.class); List<String> tagNames = (List<String>) params.get("tagNames");
List<String> tagNames = JsonUtils.toList(params.get("tagNames"), String.class); agentTagService.saveAgentTags(id, tagIds, tagNames);
AgentUpdateDTO dto = new AgentUpdateDTO();
dto.setTagIds(tagIds);
dto.setTagNames(tagNames);
agentService.updateAgentById(id, dto);
return new Result<Void>().ok(null); return new Result<Void>().ok(null);
} }
} }

View file

@ -1,79 +0,0 @@
package xiaozhi.modules.agent.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import xiaozhi.common.exception.RenException;
import xiaozhi.common.page.PageData;
import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO;
import xiaozhi.modules.agent.dto.AgentSnapshotRestoreDTO;
import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.agent.service.AgentSnapshotService;
import xiaozhi.modules.agent.vo.AgentSnapshotVO;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体快照")
@AllArgsConstructor
@RestController
@RequestMapping("/agent/{agentId}/snapshots")
public class AgentSnapshotController {
private final AgentSnapshotService agentSnapshotService;
private final AgentService agentService;
@GetMapping
@Operation(summary = "获取智能体快照列表")
@RequiresPermissions("sys:role:normal")
public Result<PageData<AgentSnapshotVO>> page(
@PathVariable String agentId,
@ParameterObject AgentSnapshotPageDTO params) {
checkPermission(agentId);
return new Result<PageData<AgentSnapshotVO>>().ok(agentSnapshotService.page(agentId, params));
}
@GetMapping("/{snapshotId}")
@Operation(summary = "获取智能体快照详情")
@RequiresPermissions("sys:role:normal")
public Result<AgentSnapshotVO> getSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) {
checkPermission(agentId);
return new Result<AgentSnapshotVO>().ok(agentSnapshotService.getSnapshot(agentId, snapshotId));
}
@PostMapping("/{snapshotId}/restore")
@Operation(summary = "恢复智能体快照")
@RequiresPermissions("sys:role:normal")
public Result<Void> restore(@PathVariable String agentId, @PathVariable String snapshotId,
@RequestBody @Valid AgentSnapshotRestoreDTO request) {
checkPermission(agentId);
agentSnapshotService.restoreSnapshot(agentId, snapshotId, request.getCurrentStateToken());
return new Result<>();
}
@DeleteMapping("/{snapshotId}")
@Operation(summary = "删除智能体历史快照")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) {
checkPermission(agentId);
agentSnapshotService.deleteSnapshot(agentId, snapshotId);
return new Result<>();
}
private void checkPermission(String agentId) {
UserDetail user = SecurityUser.getUser();
if (user == null || !agentService.checkAgentPermission(agentId, user.getId())) {
throw new RenException("没有权限访问该智能体快照");
}
}
}

View file

@ -41,17 +41,6 @@ public class AgentTemplateController {
private final AgentTemplateService agentTemplateService; private final AgentTemplateService agentTemplateService;
// 单独用 normal 权限(而非类级 superAdmin)是有意保留:
// 普通用户也需查询可用模板,与 /page 的管理入口分离,保持原行为契约。
@GetMapping
@Operation(summary = "智能体模板列表")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> getAgentTemplates() {
List<AgentTemplateEntity> list = agentTemplateService
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list);
}
@GetMapping("/page") @GetMapping("/page")
@Operation(summary = "获取模板分页列表") @Operation(summary = "获取模板分页列表")
@RequiresPermissions("sys:role:superAdmin") @RequiresPermissions("sys:role:superAdmin")

View file

@ -36,20 +36,4 @@ public interface AgentDao extends BaseDao<AgentEntity> {
* @param agentId 智能体ID * @param agentId 智能体ID
*/ */
AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId); AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId);
/**
* 锁定智能体主记录,用于串行化同一智能体的配置写入
*
* @param agentId 智能体ID
*/
AgentEntity selectByIdForUpdate(@Param("agentId") String agentId);
/**
* 精确写入快照覆盖的智能体字段,包括目标快照中的 null 值。
* 不更新所属用户、创建信息等不属于快照的字段。
*
* @param agent 已应用目标快照的智能体
* @return 受影响行数
*/
int updateSnapshotFields(@Param("agent") AgentEntity agent);
} }

View file

@ -1,29 +0,0 @@
package xiaozhi.modules.agent.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import xiaozhi.common.dao.BaseDao;
import xiaozhi.modules.agent.entity.AgentSnapshotEntity;
@Mapper
public interface AgentSnapshotDao extends BaseDao<AgentSnapshotEntity> {
Integer selectMaxVersionNo(@Param("agentId") String agentId);
AgentSnapshotEntity selectLatestSnapshot(@Param("agentId") String agentId);
AgentSnapshotEntity selectNextSnapshot(@Param("agentId") String agentId, @Param("versionNo") Integer versionNo);
int insertWithNextVersion(@Param("snapshot") AgentSnapshotEntity snapshot);
int deleteOlderThanKeepLimit(@Param("agentId") String agentId, @Param("keepLimit") int keepLimit);
List<AgentSnapshotEntity> selectLegacyRedactionBatch(@Param("afterId") String afterId,
@Param("limit") int limit,
@Param("targetRedactionVersion") int targetRedactionVersion);
int updateRedactedSnapshots(@Param("snapshots") List<AgentSnapshotEntity> snapshots,
@Param("redactionVersion") int redactionVersion);
}

View file

@ -39,7 +39,7 @@ public class AgentDTO {
private String systemPrompt; private String systemPrompt;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" + @Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", requiredMode = Schema.RequiredMode.NOT_REQUIRED) "根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
private String summaryMemory; private String summaryMemory;
@Schema(description = "最后连接时间", example = "2024-03-20 10:00:00") @Schema(description = "最后连接时间", example = "2024-03-20 10:00:00")
@ -50,4 +50,4 @@ public class AgentDTO {
@Schema(description = "标签列表") @Schema(description = "标签列表")
private List<AgentTagDTO> tags; private List<AgentTagDTO> tags;
} }

View file

@ -14,6 +14,6 @@ public class AgentMemoryDTO implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" + @Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", requiredMode = Schema.RequiredMode.NOT_REQUIRED) "根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
private String summaryMemory; private String summaryMemory;
} }

View file

@ -1,40 +0,0 @@
package xiaozhi.modules.agent.dto;
import java.io.Serializable;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照数据")
public class AgentSnapshotDataDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String agentCode;
private String agentName;
private String asrModelId;
private String vadModelId;
private String llmModelId;
private String slmModelId;
private String vllmModelId;
private String ttsModelId;
private String ttsVoiceId;
private String ttsLanguage;
private Integer ttsVolume;
private Integer ttsRate;
private Integer ttsPitch;
private String memModelId;
private String intentModelId;
private Integer chatHistoryConf;
private String systemPrompt;
private String summaryMemory;
private String langCode;
private String language;
private Integer sort;
private List<AgentUpdateDTO.FunctionInfo> functions;
private List<ContextProviderDTO> contextProviders;
private List<String> correctWordFileIds;
private List<String> tagNames;
private List<AgentSnapshotTagDTO> tags;
}

View file

@ -1,28 +0,0 @@
package xiaozhi.modules.agent.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照分页查询参数")
public class AgentSnapshotPageDTO {
@Schema(description = "当前页码,从1开始", example = "1")
private Integer page = 1;
@Schema(description = "每页数量", example = "10")
private Integer limit = 10;
@Schema(description = "版本锚点,只查询小于等于该版本号的历史快照", example = "20")
private Integer maxVersionNo;
public int pageOrDefault() {
return page == null || page < 1 ? 1 : page;
}
public int limitOrDefault() {
if (limit == null || limit < 1) {
return 10;
}
return limit;
}
}

View file

@ -1,13 +0,0 @@
package xiaozhi.modules.agent.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "智能体快照恢复请求")
public class AgentSnapshotRestoreDTO {
@NotBlank
@Schema(description = "预览时由服务端生成的当前配置状态指纹")
private String currentStateToken;
}

View file

@ -1,16 +0,0 @@
package xiaozhi.modules.agent.dto;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照标签")
public class AgentSnapshotTagDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String tagName;
private Integer sort;
}

View file

@ -4,12 +4,9 @@ import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import xiaozhi.common.utils.JsonUtils;
/** /**
* 智能体更新DTO * 智能体更新DTO
@ -39,10 +36,10 @@ public class AgentUpdateDTO implements Serializable {
@Schema(description = "小模型标识", example = "slm_model_02", nullable = true) @Schema(description = "小模型标识", example = "slm_model_02", nullable = true)
private String slmModelId; private String slmModelId;
@Schema(description = "VLLM模型标识", example = "vllm_model_02", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Schema(description = "VLLM模型标识", example = "vllm_model_02", required = false)
private String vllmModelId; private String vllmModelId;
@Schema(description = "语音合成模型标识", example = "tts_model_02", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Schema(description = "语音合成模型标识", example = "tts_model_02", required = false)
private String ttsModelId; private String ttsModelId;
@Schema(description = "音色标识", example = "voice_02", nullable = true) @Schema(description = "音色标识", example = "voice_02", nullable = true)
@ -94,50 +91,15 @@ public class AgentUpdateDTO implements Serializable {
@Schema(description = "替换词文件ID列表", nullable = true) @Schema(description = "替换词文件ID列表", nullable = true)
private List<String> correctWordFileIds; private List<String> correctWordFileIds;
@Schema(description = "标签名称列表", nullable = true)
private List<String> tagNames;
@Schema(description = "标签ID列表", nullable = true)
private List<String> tagIds;
@Data @Data
@Schema(description = "插件函数信息") @Schema(description = "插件函数信息")
public static class FunctionInfo implements Serializable { public static class FunctionInfo implements Serializable {
private static final TypeReference<HashMap<String, Object>> PARAM_INFO_TYPE = new TypeReference<>() {
};
@Schema(description = "插件ID", example = "plugin_01") @Schema(description = "插件ID", example = "plugin_01")
private String pluginId; private String pluginId;
@Schema(description = "函数参数信息", nullable = true) @Schema(description = "函数参数信息", nullable = true)
private HashMap<String, Object> paramInfo = new HashMap<>(); private HashMap<String, Object> paramInfo;
public void setParamInfo(Object paramInfo) {
this.paramInfo = normalizeParamInfo(paramInfo);
}
private static HashMap<String, Object> normalizeParamInfo(Object paramInfo) {
if (paramInfo == null) {
return new HashMap<>();
}
if (paramInfo instanceof String value) {
if (value.trim().isEmpty()) {
return new HashMap<>();
}
return JsonUtils.parseObject(value, PARAM_INFO_TYPE);
}
if (paramInfo instanceof Map<?, ?> value) {
HashMap<String, Object> normalized = new HashMap<>();
value.forEach((key, val) -> {
if (key != null) {
normalized.put(String.valueOf(key), val);
}
});
return normalized;
}
return JsonUtils.parseObject(JsonUtils.toJsonString(paramInfo), PARAM_INFO_TYPE);
}
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
} }
} }

View file

@ -7,11 +7,11 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import xiaozhi.modules.agent.dto.ContextProviderDTO; import xiaozhi.modules.agent.dto.ContextProviderDTO;
import xiaozhi.modules.agent.typehandler.ContextProviderListTypeHandler;
@Data @Data
@TableName(value = "ai_agent_context_provider", autoResultMap = true) @TableName(value = "ai_agent_context_provider", autoResultMap = true)
@ -26,7 +26,7 @@ public class AgentContextProviderEntity {
private String agentId; private String agentId;
@Schema(description = "上下文源配置") @Schema(description = "上下文源配置")
@TableField(typeHandler = ContextProviderListTypeHandler.class) @TableField(typeHandler = JacksonTypeHandler.class)
private List<ContextProviderDTO> contextProviders; private List<ContextProviderDTO> contextProviders;
@Schema(description = "创建者") @Schema(description = "创建者")

View file

@ -74,7 +74,7 @@ public class AgentEntity {
private String systemPrompt; private String systemPrompt;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" + @Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", requiredMode = Schema.RequiredMode.NOT_REQUIRED) "根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
private String summaryMemory; private String summaryMemory;
@Schema(description = "语言编码") @Schema(description = "语言编码")
@ -97,4 +97,4 @@ public class AgentEntity {
@Schema(description = "更新时间") @Schema(description = "更新时间")
private Date updatedAt; private Date updatedAt;
} }

View file

@ -1,53 +0,0 @@
package xiaozhi.modules.agent.entity;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@TableName("ai_agent_snapshot")
@Schema(description = "智能体配置快照")
public class AgentSnapshotEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "快照ID")
private String id;
@Schema(description = "智能体ID")
private String agentId;
@Schema(description = "所属用户ID")
private Long userId;
@Schema(description = "版本号")
private Integer versionNo;
@Schema(description = "快照数据JSON")
private String snapshotData;
@Schema(description = "变更字段JSON")
private String changedFields;
@Schema(description = "快照来源")
private String source;
@Schema(description = "恢复来源快照ID")
private String restoreFromSnapshotId;
@Schema(description = "恢复来源版本号")
private Integer restoreFromVersionNo;
@Schema(description = "创建者")
private Long creator;
@Schema(description = "创建时间")
private Date createdAt;
@Schema(description = "快照数据脱敏规则版本")
private Integer redactionVersion;
}

View file

@ -1,6 +1,6 @@
package xiaozhi.modules.agent.service; package xiaozhi.modules.agent.service;
import com.baomidou.mybatisplus.extension.repository.IRepository; import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity; import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
@ -11,7 +11,7 @@ import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
* @version 1.0, 2025/5/8 * @version 1.0, 2025/5/8
* @since 1.0.0 * @since 1.0.0
*/ */
public interface AgentChatAudioService extends IRepository<AgentChatAudioEntity> { public interface AgentChatAudioService extends IService<AgentChatAudioEntity> {
/** /**
* 保存音频数据 * 保存音频数据
* *

View file

@ -3,9 +3,9 @@ package xiaozhi.modules.agent.service;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.baomidou.mybatisplus.extension.repository.IRepository; import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
import xiaozhi.modules.agent.dto.AgentChatSessionDTO; import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity; import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
@ -18,7 +18,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
* @version 1.0, 2025/4/30 * @version 1.0, 2025/4/30
* @since 1.0.0 * @since 1.0.0
*/ */
public interface AgentChatHistoryService extends IRepository<AgentChatHistoryEntity> { public interface AgentChatHistoryService extends IService<AgentChatHistoryEntity> {
/** /**
* 根据智能体ID获取会话列表 * 根据智能体ID获取会话列表
@ -37,14 +37,6 @@ public interface AgentChatHistoryService extends IRepository<AgentChatHistoryEnt
*/ */
List<AgentChatHistoryDTO> getChatHistoryBySessionId(String agentId, String sessionId); List<AgentChatHistoryDTO> getChatHistoryBySessionId(String agentId, String sessionId);
/**
* 根据会话ID获取智能体ID
*
* @param sessionId 会话ID
* @return 智能体ID
*/
String getAgentIdBySessionId(String sessionId);
/** /**
* 根据智能体ID删除聊天记录 * 根据智能体ID删除聊天记录
* *
@ -70,14 +62,6 @@ public interface AgentChatHistoryService extends IRepository<AgentChatHistoryEnt
*/ */
String getContentByAudioId(String audioId); String getContentByAudioId(String audioId);
/**
* 根据音频ID获取智能体ID
*
* @param audioId 音频ID
* @return 智能体ID
*/
String getAgentIdByAudioId(String audioId);
/** /**
* 查询此音频id是否属于此智能体 * 查询此音频id是否属于此智能体

View file

@ -2,7 +2,7 @@ package xiaozhi.modules.agent.service;
import java.util.List; import java.util.List;
import com.baomidou.mybatisplus.extension.repository.IRepository; import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.modules.agent.entity.AgentPluginMapping; import xiaozhi.modules.agent.entity.AgentPluginMapping;
@ -10,7 +10,7 @@ import xiaozhi.modules.agent.entity.AgentPluginMapping;
* @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service * @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service
* @createDate 2025-05-25 22:33:17 * @createDate 2025-05-25 22:33:17
*/ */
public interface AgentPluginMappingService extends IRepository<AgentPluginMapping> { public interface AgentPluginMappingService extends IService<AgentPluginMapping> {
/** /**
* 根据智能体id获取插件参数 * 根据智能体id获取插件参数

View file

@ -7,7 +7,6 @@ import xiaozhi.common.page.PageData;
import xiaozhi.common.service.BaseService; import xiaozhi.common.service.BaseService;
import xiaozhi.modules.agent.dto.AgentCreateDTO; import xiaozhi.modules.agent.dto.AgentCreateDTO;
import xiaozhi.modules.agent.dto.AgentDTO; import xiaozhi.modules.agent.dto.AgentDTO;
import xiaozhi.modules.agent.dto.AgentMemoryDTO;
import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO;
import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.entity.AgentEntity;
import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.agent.vo.AgentInfoVO;
@ -36,15 +35,6 @@ public interface AgentService extends BaseService<AgentEntity> {
*/ */
AgentInfoVO getAgentById(String id); AgentInfoVO getAgentById(String id);
/**
* 根据ID获取当前用户有权访问的智能体
*
* @param id 智能体ID
* @param userId 当前用户ID
* @return 智能体实体
*/
AgentInfoVO getAgentById(String id, Long userId);
/** /**
* 插入智能体 * 插入智能体
* *
@ -60,13 +50,6 @@ public interface AgentService extends BaseService<AgentEntity> {
*/ */
void deleteAgentByUserId(Long userId); void deleteAgentByUserId(Long userId);
/**
* 删除智能体及其关联数据
*
* @param agentId 智能体ID
*/
void deleteAgent(String agentId);
/** /**
* 获取用户智能体列表 * 获取用户智能体列表
* *
@ -110,41 +93,6 @@ public interface AgentService extends BaseService<AgentEntity> {
*/ */
void updateAgentById(String agentId, AgentUpdateDTO dto); void updateAgentById(String agentId, AgentUpdateDTO dto);
/**
* 更新当前用户有权访问的智能体
*
* @param agentId 智能体ID
* @param dto 更新智能体所需的信息
* @param userId 当前用户ID
*/
void updateAgentById(String agentId, AgentUpdateDTO dto, Long userId);
/**
* 根据设备MAC地址更新当前用户有权访问的智能体记忆
*
* @param macAddress 设备MAC地址
* @param dto 智能体记忆
* @param userId 当前用户ID
*/
void updateAgentMemoryByDeviceMacAddress(String macAddress, AgentMemoryDTO dto, Long userId);
/**
* 删除当前用户有权访问的智能体
*
* @param agentId 智能体ID
* @param userId 当前用户ID
*/
void deleteAgentById(String agentId, Long userId);
/**
* 更新智能体
*
* @param agentId 智能体ID
* @param dto 更新智能体所需的信息
* @param createSnapshot 是否创建配置快照
*/
void updateAgentById(String agentId, AgentUpdateDTO dto, boolean createSnapshot);
/** /**
* 创建智能体 * 创建智能体
* *

View file

@ -1,25 +0,0 @@
package xiaozhi.modules.agent.service;
import xiaozhi.common.page.PageData;
import xiaozhi.common.service.BaseService;
import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO;
import xiaozhi.modules.agent.entity.AgentSnapshotEntity;
import xiaozhi.modules.agent.vo.AgentSnapshotVO;
public interface AgentSnapshotService extends BaseService<AgentSnapshotEntity> {
void createSnapshot(String agentId, String source);
PageData<AgentSnapshotVO> page(String agentId, AgentSnapshotPageDTO params);
AgentSnapshotVO getSnapshot(String agentId, String snapshotId);
void restoreSnapshot(String agentId, String snapshotId, String currentStateToken);
void deleteSnapshot(String agentId, String snapshotId);
Integer getCurrentVersionNo(String agentId);
void deleteByAgentId(String agentId);
long redactLegacySnapshots();
}

View file

@ -1,7 +1,7 @@
package xiaozhi.modules.agent.service; package xiaozhi.modules.agent.service;
import com.baomidou.mybatisplus.extension.repository.IRepository; import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.entity.AgentTemplateEntity;
/** /**
@ -9,7 +9,7 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity;
* @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service * @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service
* @createDate 2025-03-22 11:48:18 * @createDate 2025-03-22 11:48:18
*/ */
public interface AgentTemplateService extends IRepository<AgentTemplateEntity> { public interface AgentTemplateService extends IService<AgentTemplateEntity> {
/** /**
* 获取默认模板 * 获取默认模板

View file

@ -2,7 +2,7 @@ package xiaozhi.modules.agent.service.impl;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.spring.repository.CrudRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.modules.agent.dao.AiAgentChatAudioDao; import xiaozhi.modules.agent.dao.AiAgentChatAudioDao;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity; import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
@ -16,7 +16,7 @@ import xiaozhi.modules.agent.service.AgentChatAudioService;
* @since 1.0.0 * @since 1.0.0
*/ */
@Service @Service
public class AgentChatAudioServiceImpl extends CrudRepository<AiAgentChatAudioDao, AgentChatAudioEntity> public class AgentChatAudioServiceImpl extends ServiceImpl<AiAgentChatAudioDao, AgentChatAudioEntity>
implements AgentChatAudioService { implements AgentChatAudioService {
@Override @Override
public String saveAudio(byte[] audioData) { public String saveAudio(byte[] audioData) {

View file

@ -5,7 +5,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.collection.ListUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -15,12 +14,13 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.spring.repository.CrudRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.JsonUtils;
import xiaozhi.common.utils.ToolUtil;
import xiaozhi.modules.agent.Enums.AgentChatHistoryType; import xiaozhi.modules.agent.Enums.AgentChatHistoryType;
import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao; import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao;
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
@ -39,7 +39,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class AgentChatHistoryServiceImpl extends CrudRepository<AiAgentChatHistoryDao, AgentChatHistoryEntity> public class AgentChatHistoryServiceImpl extends ServiceImpl<AiAgentChatHistoryDao, AgentChatHistoryEntity>
implements AgentChatHistoryService { implements AgentChatHistoryService {
private final AgentChatTitleService agentChatTitleService; private final AgentChatTitleService agentChatTitleService;
@ -88,26 +88,13 @@ public class AgentChatHistoryServiceImpl extends CrudRepository<AiAgentChatHisto
return ConvertUtils.sourceToTarget(historyList, AgentChatHistoryDTO.class); return ConvertUtils.sourceToTarget(historyList, AgentChatHistoryDTO.class);
} }
@Override
public String getAgentIdBySessionId(String sessionId) {
if (sessionId == null || sessionId.isBlank()) {
return null;
}
AgentChatHistoryEntity entity = baseMapper.selectOne(
new LambdaQueryWrapper<AgentChatHistoryEntity>()
.select(AgentChatHistoryEntity::getAgentId)
.eq(AgentChatHistoryEntity::getSessionId, sessionId)
.last("LIMIT 1"));
return entity == null ? null : entity.getAgentId();
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText) { public void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText) {
if (deleteAudio) { if (deleteAudio) {
// 分批删除音频,避免超时 // 分批删除音频,避免超时
List<String> audioIds = baseMapper.getAudioIdsByAgentId(agentId); List<String> audioIds = baseMapper.getAudioIdsByAgentId(agentId);
if (CollUtil.isNotEmpty(audioIds)) { if (ToolUtil.isNotEmpty(audioIds)) {
// 每批删除1000条 // 每批删除1000条
List<List<String>> batch = ListUtil.split(audioIds, 1000); List<List<String>> batch = ListUtil.split(audioIds, 1000);
batch.forEach(dataList -> { batch.forEach(dataList -> {
@ -167,7 +154,7 @@ public class AgentChatHistoryServiceImpl extends CrudRepository<AiAgentChatHisto
// 尝试解析为 JSON // 尝试解析为 JSON
try { try {
Map<String, Object> jsonMap = JsonUtils.parseMap(content); Map<String, Object> jsonMap = JsonUtils.parseObject(content, Map.class);
if (jsonMap != null && jsonMap.containsKey("content")) { if (jsonMap != null && jsonMap.containsKey("content")) {
Object contentObj = jsonMap.get("content"); Object contentObj = jsonMap.get("content");
return contentObj != null ? contentObj.toString() : content; return contentObj != null ? contentObj.toString() : content;
@ -189,19 +176,6 @@ public class AgentChatHistoryServiceImpl extends CrudRepository<AiAgentChatHisto
return agentChatHistoryEntity == null ? null : agentChatHistoryEntity.getContent(); return agentChatHistoryEntity == null ? null : agentChatHistoryEntity.getContent();
} }
@Override
public String getAgentIdByAudioId(String audioId) {
if (audioId == null || audioId.isBlank()) {
return null;
}
AgentChatHistoryEntity entity = baseMapper.selectOne(
new LambdaQueryWrapper<AgentChatHistoryEntity>()
.select(AgentChatHistoryEntity::getAgentId)
.eq(AgentChatHistoryEntity::getAudioId, audioId)
.last("LIMIT 1"));
return entity == null ? null : entity.getAgentId();
}
@Override @Override
public boolean isAudioOwnedByAgent(String audioId, String agentId) { public boolean isAudioOwnedByAgent(String audioId, String agentId) {
// 查询是否有指定音频id和智能体id的数据,如果有且只有一条说明此数据属性此智能体 // 查询是否有指定音频id和智能体id的数据,如果有且只有一条说明此数据属性此智能体

View file

@ -118,7 +118,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
{ {
setSummaryMemory(summaryDTO.getSummary()); setSummaryMemory(summaryDTO.getSummary());
} }
}, false); });
log.info("成功保存会话 {} 的聊天记录总结到智能体 {}", sessionId, agentId); log.info("成功保存会话 {} 的聊天记录总结到智能体 {}", sessionId, agentId);
} else { } else {
log.info("生成总结失败: {}", summaryDTO.getErrorMessage()); log.info("生成总结失败: {}", summaryDTO.getErrorMessage());
@ -518,4 +518,4 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
return null; return null;
} }
} }
} }

View file

@ -12,11 +12,11 @@ import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.utils.AESUtils; import xiaozhi.common.utils.AESUtils;
import xiaozhi.common.utils.HashEncryptionUtil;
import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.Enums.XiaoZhiMcpJsonRpcJson; import xiaozhi.modules.agent.Enums.XiaoZhiMcpJsonRpcJson;
import xiaozhi.modules.agent.service.AgentMcpAccessPointService; import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
@ -76,7 +76,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
// 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动 // 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动
List<String> initResponses = client.listenerWithoutClose(response -> { List<String> initResponses = client.listenerWithoutClose(response -> {
try { try {
Map<String, Object> jsonMap = JsonUtils.parseMap(response); Map<String, Object> jsonMap = JsonUtils.parseObject(response, Map.class);
if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) {
// 检查是否有result字段,表示初始化成功 // 检查是否有result字段,表示初始化成功
return jsonMap.containsKey("result") && !jsonMap.containsKey("error"); return jsonMap.containsKey("result") && !jsonMap.containsKey("error");
@ -92,7 +92,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
boolean initSucceeded = false; boolean initSucceeded = false;
for (String response : initResponses) { for (String response : initResponses) {
try { try {
Map<String, Object> jsonMap = JsonUtils.parseMap(response); Map<String, Object> jsonMap = JsonUtils.parseObject(response, Map.class);
if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) {
if (jsonMap.containsKey("result")) { if (jsonMap.containsKey("result")) {
log.info("MCP初始化成功,智能体ID: {}", id); log.info("MCP初始化成功,智能体ID: {}", id);
@ -123,7 +123,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
// 等待工具列表响应 (id=2) // 等待工具列表响应 (id=2)
List<String> toolsResponses = client.listener(response -> { List<String> toolsResponses = client.listener(response -> {
try { try {
Map<String, Object> jsonMap = JsonUtils.parseMap(response); Map<String, Object> jsonMap = JsonUtils.parseObject(response, Map.class);
return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id")); return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"));
} catch (Exception e) { } catch (Exception e) {
log.warn("解析工具列表响应失败: {}", response, e); log.warn("解析工具列表响应失败: {}", response, e);
@ -134,18 +134,18 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
// 处理工具列表响应 // 处理工具列表响应
for (String response : toolsResponses) { for (String response : toolsResponses) {
try { try {
Map<String, Object> jsonMap = JsonUtils.parseMap(response); Map<String, Object> jsonMap = JsonUtils.parseObject(response, Map.class);
if (jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"))) { if (jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"))) {
// 检查是否有result字段 // 检查是否有result字段
Object resultObj = jsonMap.get("result"); Object resultObj = jsonMap.get("result");
if (resultObj instanceof Map<?, ?>) { if (resultObj instanceof Map) {
Map<String, Object> resultMap = JsonUtils.toStringObjectMap(resultObj); Map<String, Object> resultMap = (Map<String, Object>) resultObj;
Object toolsObj = resultMap.get("tools"); Object toolsObj = resultMap.get("tools");
if (toolsObj instanceof List<?>) { if (toolsObj instanceof List) {
List<Map<String, Object>> toolsList = JsonUtils.toStringObjectMapList(toolsObj); List<Map<String, Object>> toolsList = (List<Map<String, Object>>) toolsObj;
// 提取工具名称列表 // 提取工具名称列表
List<String> result = toolsList.stream() List<String> result = toolsList.stream()
.map(tool -> String.class.cast(tool.get("name"))) .map(tool -> (String) tool.get("name"))
.filter(name -> name != null) .filter(name -> name != null)
.sorted() .sorted()
.collect(Collectors.toList()); .collect(Collectors.toList());
@ -226,10 +226,10 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
*/ */
private static String encryptToken(String agentId, String key) { private static String encryptToken(String agentId, String key) {
// 使用md5对智能体id进行加密 // 使用md5对智能体id进行加密
String md5 = DigestUtil.md5Hex(agentId); String md5 = HashEncryptionUtil.Md5hexDigest(agentId);
// aes需要加密文本 // aes需要加密文本
String json = "{\"agentId\": \"%s\"}".formatted(md5); String json = "{\"agentId\": \"%s\"}".formatted(md5);
// 加密后成token值 // 加密后成token值
return AESUtils.encrypt(key, json); return AESUtils.encrypt(key, json);
} }
} }

View file

@ -9,7 +9,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.spring.repository.CrudRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -29,7 +29,7 @@ import xiaozhi.modules.model.service.ModelConfigService;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j @Slf4j
public class AgentPluginMappingServiceImpl extends CrudRepository<AgentPluginMappingMapper, AgentPluginMapping> public class AgentPluginMappingServiceImpl extends ServiceImpl<AgentPluginMappingMapper, AgentPluginMapping>
implements AgentPluginMappingService { implements AgentPluginMappingService {
private final AgentPluginMappingMapper agentPluginMappingMapper; private final AgentPluginMappingMapper agentPluginMappingMapper;
private final KnowledgeBaseService knowledgeBaseService; private final KnowledgeBaseService knowledgeBaseService;

View file

@ -15,10 +15,9 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.repository.IRepository;
import cn.hutool.core.collection.CollUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.ErrorCode;
@ -30,11 +29,11 @@ import xiaozhi.common.service.impl.BaseServiceImpl;
import xiaozhi.common.user.UserDetail; import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.JsonUtils;
import xiaozhi.common.utils.ToolUtil;
import xiaozhi.modules.agent.dao.AgentDao; import xiaozhi.modules.agent.dao.AgentDao;
import xiaozhi.modules.agent.dao.AgentTagDao; import xiaozhi.modules.agent.dao.AgentTagDao;
import xiaozhi.modules.agent.dto.AgentCreateDTO; import xiaozhi.modules.agent.dto.AgentCreateDTO;
import xiaozhi.modules.agent.dto.AgentDTO; import xiaozhi.modules.agent.dto.AgentDTO;
import xiaozhi.modules.agent.dto.AgentMemoryDTO;
import xiaozhi.modules.agent.dto.AgentTagDTO; import xiaozhi.modules.agent.dto.AgentTagDTO;
import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO;
import xiaozhi.modules.agent.entity.AgentContextProviderEntity; import xiaozhi.modules.agent.entity.AgentContextProviderEntity;
@ -44,10 +43,9 @@ import xiaozhi.modules.agent.entity.AgentTagEntity;
import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.service.AgentChatHistoryService; import xiaozhi.modules.agent.service.AgentChatHistoryService;
import xiaozhi.modules.agent.service.AgentContextProviderService; import xiaozhi.modules.agent.service.AgentContextProviderService;
import xiaozhi.modules.agent.service.AgentPluginMappingService; import xiaozhi.modules.agent.service.AgentPluginMappingService;
import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.agent.service.AgentSnapshotService; import xiaozhi.modules.agent.service.AgentTagService;
import xiaozhi.modules.agent.service.AgentTagService;
import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.service.AgentTemplateService;
import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.agent.vo.AgentInfoVO;
import xiaozhi.modules.correctword.service.CorrectWordFileService; import xiaozhi.modules.correctword.service.CorrectWordFileService;
@ -58,9 +56,9 @@ import xiaozhi.modules.model.dto.VoiceDTO;
import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelConfigService;
import xiaozhi.modules.model.service.ModelProviderService; import xiaozhi.modules.model.service.ModelProviderService;
import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.enums.SuperAdminEnum; import xiaozhi.modules.sys.enums.SuperAdminEnum;
import xiaozhi.modules.timbre.service.TimbreService; import xiaozhi.modules.timbre.service.TimbreService;
@Service @Service
@AllArgsConstructor @AllArgsConstructor
@ -75,10 +73,9 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
private final AgentChatHistoryService agentChatHistoryService; private final AgentChatHistoryService agentChatHistoryService;
private final AgentTemplateService agentTemplateService; private final AgentTemplateService agentTemplateService;
private final ModelProviderService modelProviderService; private final ModelProviderService modelProviderService;
private final AgentContextProviderService agentContextProviderService; private final AgentContextProviderService agentContextProviderService;
private final AgentTagService agentTagService; private final AgentTagService agentTagService;
private final CorrectWordFileService correctWordFileService; private final CorrectWordFileService correctWordFileService;
private final AgentSnapshotService agentSnapshotService;
@Override @Override
public PageData<AgentEntity> adminAgentList(Map<String, Object> params) { public PageData<AgentEntity> adminAgentList(Map<String, Object> params) {
@ -95,7 +92,6 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
if (agent == null) { if (agent == null) {
throw new RenException(ErrorCode.AGENT_NOT_FOUND); throw new RenException(ErrorCode.AGENT_NOT_FOUND);
} }
requireCurrentUserPermissionIfPresent(agent);
if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) {
agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.IGNORE.getCode()); agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.IGNORE.getCode());
@ -110,74 +106,14 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
agent.setContextProviders(contextProviderEntity.getContextProviders()); agent.setContextProviders(contextProviderEntity.getContextProviders());
} }
// 查询替换词文件ID列表 // 查询替换词文件ID列表
List<String> correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id); List<String> correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id);
agent.setCorrectWordFileIds(correctWordFileIds); agent.setCorrectWordFileIds(correctWordFileIds);
agent.setCurrentVersionNo(agentSnapshotService.getCurrentVersionNo(id));
// 无需额外查询插件列表,已通过SQL查询出来
// 无需额外查询插件列表,已通过SQL查询出来 return agent;
return agent;
} }
@Override
public AgentInfoVO getAgentById(String id, Long userId) {
AgentInfoVO agent = getAgentById(id);
requireAgentPermission(agent, userId);
return agent;
}
private AgentEntity getAgentEntityOrThrow(String agentId) {
AgentEntity agent = agentDao.selectById(agentId);
if (agent == null) {
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
}
return agent;
}
private boolean isCurrentUserSuperAdmin() {
UserDetail user = SecurityUser.getUser();
return user != null && Integer.valueOf(SuperAdminEnum.YES.value()).equals(user.getSuperAdmin());
}
private void requireCurrentUserPermissionIfPresent(AgentEntity agent) {
Long userId = SecurityUser.getUserId();
if (userId != null) {
requireAgentPermission(agent, userId);
}
}
private boolean hasAgentPermission(AgentEntity agent, Long userId) {
if (agent == null) {
return false;
}
if (isCurrentUserSuperAdmin()) {
return true;
}
return userId != null && userId.equals(agent.getUserId());
}
private void requireAgentPermission(AgentEntity agent, Long userId) {
if (!hasAgentPermission(agent, userId)) {
throw new RenException(ErrorCode.NO_PERMISSION);
}
}
private boolean hasDevicePermission(DeviceEntity device, Long userId) {
if (device == null) {
return false;
}
if (isCurrentUserSuperAdmin()) {
return true;
}
return userId != null && userId.equals(device.getUserId());
}
private void requireDevicePermission(DeviceEntity device, Long userId) {
if (!hasDevicePermission(device, userId)) {
throw new RenException(ErrorCode.NO_PERMISSION);
}
}
@Override @Override
public boolean insert(AgentEntity entity) { public boolean insert(AgentEntity entity) {
// 如果ID为空,自动生成一个UUID作为ID // 如果ID为空,自动生成一个UUID作为ID
@ -198,35 +134,15 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
return super.insert(entity); return super.insert(entity);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) public void deleteAgentByUserId(Long userId) {
public void deleteAgentByUserId(Long userId) { UpdateWrapper<AgentEntity> wrapper = new UpdateWrapper<>();
List<AgentEntity> agents = baseDao.selectList(new QueryWrapper<AgentEntity>() wrapper.eq("user_id", userId);
.select("id") baseDao.delete(wrapper);
.eq("user_id", userId)); }
for (AgentEntity agent : agents) {
deleteAgent(agent.getId()); @Override
} public List<AgentDTO> getUserAgents(Long userId, String keyword, String searchType) {
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAgent(String agentId) {
if (agentDao.selectByIdForUpdate(agentId) == null) {
return;
}
deviceService.deleteByAgentId(agentId);
agentChatHistoryService.deleteByAgentId(agentId, true, true);
agentPluginMappingService.deleteByAgentId(agentId);
agentContextProviderService.deleteByAgentId(agentId);
correctWordFileService.deleteMappingsByAgentId(agentId);
agentTagService.deleteAgentTags(agentId);
agentSnapshotService.deleteByAgentId(agentId);
deleteById(agentId);
}
@Override
public List<AgentDTO> getUserAgents(Long userId, String keyword, String searchType) {
QueryWrapper<AgentEntity> queryWrapper = new QueryWrapper<>(); QueryWrapper<AgentEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", userId).orderByDesc("created_at"); queryWrapper.eq("user_id", userId).orderByDesc("created_at");
@ -243,13 +159,13 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
.map(DeviceEntity::getAgentId) .map(DeviceEntity::getAgentId)
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
if (CollUtil.isNotEmpty(agentIds)) { if (ToolUtil.isNotEmpty(agentIds)) {
w.or().in("id", agentIds); w.or().in("id", agentIds);
} }
// 按标签名搜索 // 按标签名搜索
List<String> tagAgentIds = agentTagService.getAgentIdsByTagName(keyword); List<String> tagAgentIds = agentTagService.getAgentIdsByTagName(keyword);
if (CollUtil.isNotEmpty(tagAgentIds)) { if (ToolUtil.isNotEmpty(tagAgentIds)) {
w.or().in("id", tagAgentIds); w.or().in("id", tagAgentIds);
} }
}); });
@ -291,7 +207,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
// 获取标签列表 // 获取标签列表
List<AgentTagEntity> tags = agentTagDao.selectByAgentId(agent.getId()); List<AgentTagEntity> tags = agentTagDao.selectByAgentId(agent.getId());
if (CollUtil.isNotEmpty(tags)) { if (ToolUtil.isNotEmpty(tags)) {
dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList())); dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList()));
} }
@ -337,56 +253,42 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
} }
@Override @Override
public boolean checkAgentPermission(String agentId, Long userId) { public boolean checkAgentPermission(String agentId, Long userId) {
AgentEntity agent = agentDao.selectById(agentId); if (SecurityUser.getUser() == null || SecurityUser.getUser().getId() == null) {
return hasAgentPermission(agent, userId); return false;
} }
// 获取智能体信息
// 根据id更新智能体信息 AgentEntity agent = getAgentById(agentId);
@Override if (agent == null) {
@Transactional(rollbackFor = Exception.class) return false;
public void updateAgentById(String agentId, AgentUpdateDTO dto) { }
updateAgentById(agentId, dto, true);
} // 如果是超级管理员,直接返回true
if (SecurityUser.getUser().getSuperAdmin() == SuperAdminEnum.YES.value()) {
@Override return true;
@Transactional(rollbackFor = Exception.class) }
public void updateAgentById(String agentId, AgentUpdateDTO dto, Long userId) {
updateAgentById(agentId, dto, userId, true); // 检查是否是智能体的所有者
} return userId.equals(agent.getUserId());
}
// 根据id更新智能体信息
@Override // 根据id更新智能体信息
@Transactional(rollbackFor = Exception.class) @Override
public void updateAgentById(String agentId, AgentUpdateDTO dto, boolean createSnapshot) { @Transactional(rollbackFor = Exception.class)
updateAgentById(agentId, dto, null, createSnapshot); public void updateAgentById(String agentId, AgentUpdateDTO dto) {
} // 先查询现有实体
AgentEntity existingEntity = this.getAgentById(agentId);
private void updateAgentById(String agentId, AgentUpdateDTO dto, Long userId, boolean createSnapshot) { if (existingEntity == null) {
AgentEntity lockedAgent = agentDao.selectByIdForUpdate(agentId); throw new RenException(ErrorCode.AGENT_NOT_FOUND);
if (lockedAgent == null) { }
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
} // 只更新提供的非空字段
if (userId == null) { if (dto.getAgentName() != null) {
requireCurrentUserPermissionIfPresent(lockedAgent); existingEntity.setAgentName(dto.getAgentName());
} else { }
requireAgentPermission(lockedAgent, userId); if (dto.getAgentCode() != null) {
} existingEntity.setAgentCode(dto.getAgentCode());
}
// 锁定后查询现有实体和关联配置
AgentEntity existingEntity = this.getAgentById(agentId);
if (createSnapshot) {
int currentVersionNo = agentSnapshotService.getCurrentVersionNo(agentId);
agentSnapshotService.createSnapshot(agentId, currentVersionNo == 0 ? "initial" : "current");
}
// 只更新提供的非空字段
if (dto.getAgentName() != null) {
existingEntity.setAgentName(dto.getAgentName());
}
if (dto.getAgentCode() != null) {
existingEntity.setAgentCode(dto.getAgentCode());
}
if (dto.getAsrModelId() != null) { if (dto.getAsrModelId() != null) {
existingEntity.setAsrModelId(dto.getAsrModelId()); existingEntity.setAsrModelId(dto.getAsrModelId());
} }
@ -483,10 +385,10 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
.toList(); .toList();
if (!toUpdate.isEmpty()) { if (!toUpdate.isEmpty()) {
agentPluginMappingService.updateBatchById(toUpdate, IRepository.DEFAULT_BATCH_SIZE); agentPluginMappingService.updateBatchById(toUpdate);
} }
if (!toInsert.isEmpty()) { if (!toInsert.isEmpty()) {
agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); agentPluginMappingService.saveBatch(toInsert);
} }
// 5. 删除本次不在提交列表里的插件映射 // 5. 删除本次不在提交列表里的插件映射
@ -495,7 +397,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
.map(AgentPluginMapping::getId) .map(AgentPluginMapping::getId)
.toList(); .toList();
if (!toDelete.isEmpty()) { if (!toDelete.isEmpty()) {
agentPluginMappingService.removeByIds(toDelete); agentPluginMappingService.removeBatchByIds(toDelete);
} }
} }
@ -524,48 +426,17 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
} }
// 更新替换词文件关联 // 更新替换词文件关联
if (dto.getCorrectWordFileIds() != null) { if (dto.getCorrectWordFileIds() != null) {
correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds()); correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds());
} }
// 更新智能体标签 boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId());
if (dto.getTagNames() != null || dto.getTagIds() != null) { if (!b) {
agentTagService.saveAgentTags(agentId, dto.getTagIds(), dto.getTagNames()); throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH);
} }
this.updateById(existingEntity);
boolean b = validateLLMIntentParams(existingEntity.getLlmModelId(), existingEntity.getIntentModelId()); }
if (!b) {
throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH);
}
this.updateById(existingEntity);
if (createSnapshot) {
agentSnapshotService.createSnapshot(agentId, "config");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAgentMemoryByDeviceMacAddress(String macAddress, AgentMemoryDTO dto, Long userId) {
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
if (device == null || StringUtils.isBlank(device.getAgentId()) || dto == null) {
return;
}
requireDevicePermission(device, userId);
AgentUpdateDTO agentUpdateDTO = new AgentUpdateDTO();
agentUpdateDTO.setSummaryMemory(dto.getSummaryMemory());
updateAgentById(device.getAgentId(), agentUpdateDTO, userId, false);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAgentById(String agentId, Long userId) {
AgentEntity agent = getAgentEntityOrThrow(agentId);
requireAgentPermission(agent, userId);
deleteAgent(agentId);
}
/** /**
* 验证大语言模型和意图识别的参数是否符合匹配 * 验证大语言模型和意图识别的参数是否符合匹配
* *
@ -616,22 +487,16 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
template.setTtsVoiceId(timbre.getId()); template.setTtsVoiceId(timbre.getId());
} }
} }
} }
entity.setTtsVoiceId(template.getTtsVoiceId()); entity.setTtsVoiceId(template.getTtsVoiceId());
entity.setTtsLanguage(defaultIfBlank(template.getTtsLanguage(), entity.setMemModelId(template.getMemModelId());
timbreModelService.getDefaultLanguageById(entity.getTtsVoiceId()))); entity.setIntentModelId(template.getIntentModelId());
entity.setMemModelId(template.getMemModelId()); entity.setSystemPrompt(template.getSystemPrompt());
entity.setIntentModelId(template.getIntentModelId()); entity.setSummaryMemory(template.getSummaryMemory());
entity.setSystemPrompt(template.getSystemPrompt());
entity.setSummaryMemory(template.getSummaryMemory()); // 根据记忆模型类型设置默认的chatHistoryConf值
if (Constant.MEMORY_NO_MEM.equals(entity.getMemModelId()) if (template.getMemModelId() != null) {
|| Constant.MEMORY_MEM_REPORT_ONLY.equals(entity.getMemModelId())) {
entity.setSummaryMemory("");
}
// 根据记忆模型类型设置默认的chatHistoryConf值
if (template.getMemModelId() != null) {
if (template.getMemModelId().equals("Memory_nomem")) { if (template.getMemModelId().equals("Memory_nomem")) {
// 无记忆功能的模型,默认不记录聊天记录 // 无记忆功能的模型,默认不记录聊天记录
entity.setChatHistoryConf(0); entity.setChatHistoryConf(0);
@ -677,7 +542,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
mapping.setPluginId(pluginId); mapping.setPluginId(pluginId);
Map<String, Object> paramInfo = new HashMap<>(); Map<String, Object> paramInfo = new HashMap<>();
List<Map<String, Object>> fields = JsonUtils.parseMapList(provider.getFields()); List<Map<String, Object>> fields = JsonUtils.parseObject(provider.getFields(), List.class);
if (fields != null) { if (fields != null) {
for (Map<String, Object> field : fields) { for (Map<String, Object> field : fields) {
paramInfo.put((String) field.get("key"), field.get("default")); paramInfo.put((String) field.get("key"), field.get("default"));
@ -686,18 +551,13 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
mapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); mapping.setParamInfo(JsonUtils.toJsonString(paramInfo));
mapping.setAgentId(entity.getId()); mapping.setAgentId(entity.getId());
toInsert.add(mapping); toInsert.add(mapping);
} }
// 保存默认插件 // 保存默认插件
agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); agentPluginMappingService.saveBatch(toInsert);
agentSnapshotService.createSnapshot(entity.getId(), "initial"); return entity.getId();
return entity.getId(); }
}
private String getDefaultLLMModelId() {
private String defaultIfBlank(String value, String defaultValue) {
return StringUtils.isBlank(value) ? defaultValue : value;
}
private String getDefaultLLMModelId() {
try { try {
List<ModelConfigEntity> llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); List<ModelConfigEntity> llmConfigs = modelConfigService.getEnabledModelsByType("LLM");
if (llmConfigs == null || llmConfigs.isEmpty()) { if (llmConfigs == null || llmConfigs.isEmpty()) {
@ -716,4 +576,4 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
} }
} }
} }

View file

@ -1,59 +0,0 @@
package xiaozhi.modules.agent.service.impl;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.modules.agent.service.AgentSnapshotService;
@Slf4j
@Component
@RequiredArgsConstructor
public class AgentSnapshotRedactionRunner implements SmartInitializingSingleton {
static final long ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS = 5_000;
static final long ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS = 15_000;
private final AgentSnapshotService agentSnapshotService;
@Override
public void afterSingletonsInstantiated() {
redactAndReport("startup");
}
@Scheduled(initialDelay = ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS,
fixedDelay = ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS)
public void redactLateRollingDeploymentWrites() {
redactAndReport("rolling-deployment");
}
private void redactAndReport(String trigger) {
long startedAt = System.nanoTime();
try {
long migrated = agentSnapshotService.redactLegacySnapshots();
long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
if (migrated > 0) {
log.warn("Agent snapshot legacy redaction trigger={} migrated={} durationMs={}. Rotate credentials "
+ "that may have appeared in historical snapshot URLs, cookies, sessions, or structured "
+ "headers.", trigger, migrated, durationMillis);
} else if ("startup".equals(trigger)) {
log.info("Agent snapshot legacy redaction startup pass completed: migrated=0 durationMs={}; "
+ "rolling-deployment compensation starts after {} ms and repeats every {} ms.",
durationMillis, ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS,
ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS);
}
} catch (RuntimeException exception) {
if ("startup".equals(trigger)) {
log.error("Agent snapshot legacy redaction failed during startup; blocking application startup "
+ "before it can accept traffic.", exception);
} else {
log.error("Agent snapshot legacy redaction failed during rolling-deployment compensation; the "
+ "scheduler will retry on its next run.", exception);
}
throw exception;
}
}
}

View file

@ -133,7 +133,7 @@ public class AgentTagServiceImpl extends BaseServiceImpl<AgentTagDao, AgentTagEn
} }
if (tagIds != null && !tagIds.isEmpty()) { if (tagIds != null && !tagIds.isEmpty()) {
List<AgentTagEntity> tagIdEntities = baseDao.selectByIds(tagIds); List<AgentTagEntity> tagIdEntities = baseDao.selectBatchIds(tagIds);
for (AgentTagEntity tag : tagIdEntities) { for (AgentTagEntity tag : tagIdEntities) {
if (tag != null && (currentTagNames.contains(tag.getTagName()) || if (tag != null && (currentTagNames.contains(tag.getTagName()) ||
newTagNames.contains(tag.getTagName()))) { newTagNames.contains(tag.getTagName()))) {

View file

@ -4,8 +4,8 @@ import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.spring.repository.CrudRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.modules.agent.dao.AgentTemplateDao; import xiaozhi.modules.agent.dao.AgentTemplateDao;
import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.service.AgentTemplateService;
@ -21,7 +21,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
* @createDate 2025-03-22 11:48:18 * @createDate 2025-03-22 11:48:18
*/ */
@Service @Service
public class AgentTemplateServiceImpl extends CrudRepository<AgentTemplateDao, AgentTemplateEntity> public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, AgentTemplateEntity>
implements AgentTemplateService { implements AgentTemplateService {
/** /**

View file

@ -22,7 +22,7 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.spring.repository.CrudRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
@ -46,7 +46,7 @@ import xiaozhi.modules.sys.service.SysParamsService;
*/ */
@Service @Service
@Slf4j @Slf4j
public class AgentVoicePrintServiceImpl extends CrudRepository<AgentVoicePrintDao, AgentVoicePrintEntity> public class AgentVoicePrintServiceImpl extends ServiceImpl<AgentVoicePrintDao, AgentVoicePrintEntity>
implements AgentVoicePrintService { implements AgentVoicePrintService {
private final AgentChatAudioService agentChatAudioService; private final AgentChatAudioService agentChatAudioService;
private final RestTemplate restTemplate; private final RestTemplate restTemplate;

View file

@ -1,59 +0,0 @@
package xiaozhi.modules.agent.typehandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.fasterxml.jackson.core.type.TypeReference;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.dto.ContextProviderDTO;
/**
* JSON type handler for context providers.
*
* <p>Do not extend MyBatis-Plus {@code AbstractJsonTypeHandler}: its constructor and JSON handler
* contract changed in MyBatis-Plus 3.5.6. {@link BaseTypeHandler} is part of MyBatis itself and
* keeps this handler compatible with both 3.5.5 and newer MyBatis-Plus releases.</p>
*/
public class ContextProviderListTypeHandler extends BaseTypeHandler<List<ContextProviderDTO>> {
private static final TypeReference<List<ContextProviderDTO>> CONTEXT_PROVIDER_LIST_TYPE = new TypeReference<>() {
};
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<ContextProviderDTO> parameter,
JdbcType jdbcType) throws SQLException {
ps.setString(i, JsonUtils.toJsonString(parameter));
}
@Override
public List<ContextProviderDTO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseNullable(rs.getString(columnName));
}
@Override
public List<ContextProviderDTO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseNullable(rs.getString(columnIndex));
}
@Override
public List<ContextProviderDTO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseNullable(cs.getString(columnIndex));
}
private List<ContextProviderDTO> parseNullable(String json) {
if (StringUtils.isBlank(json)) {
return null;
}
List<ContextProviderDTO> providers = JsonUtils.parseObject(json, CONTEXT_PROVIDER_LIST_TYPE);
return providers == null ? Collections.emptyList() : providers;
}
}

View file

@ -1,5 +1,7 @@
package xiaozhi.modules.agent.vo; package xiaozhi.modules.agent.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
@ -18,6 +20,7 @@ import java.util.List;
public class AgentInfoVO extends AgentEntity public class AgentInfoVO extends AgentEntity
{ {
@Schema(description = "插件列表Id") @Schema(description = "插件列表Id")
@TableField(typeHandler = JacksonTypeHandler.class)
private List<AgentPluginMapping> functions; private List<AgentPluginMapping> functions;
@Schema(description = "上下文源配置") @Schema(description = "上下文源配置")
@ -25,7 +28,4 @@ public class AgentInfoVO extends AgentEntity
@Schema(description = "替换词文件ID列表") @Schema(description = "替换词文件ID列表")
private List<String> correctWordFileIds; private List<String> correctWordFileIds;
@Schema(description = "当前配置版本号")
private Integer currentVersionNo;
} }

View file

@ -1,34 +0,0 @@
package xiaozhi.modules.agent.vo;
import java.util.Date;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO;
@Data
@Schema(description = "智能体配置快照")
public class AgentSnapshotVO {
private String id;
private String agentId;
@Schema(description = "所属用户ID,表示该快照归属的智能体所有者")
private Long userId;
private Integer versionNo;
private List<String> changedFields;
private List<String> fieldOrder;
private String source;
@Schema(description = "恢复来源快照ID,仅恢复结果版本有值")
private String restoreFromSnapshotId;
@Schema(description = "恢复来源版本号,仅恢复结果版本有值")
private Integer restoreFromVersionNo;
@Schema(description = "创建者,表示触发本次快照写入的操作人")
private Long creator;
private Date createdAt;
private AgentSnapshotDataDTO snapshotData;
private AgentSnapshotDataDTO afterSnapshotData;
@Schema(description = "恢复预览对应的脱敏当前配置,仅详情接口有值")
private AgentSnapshotDataDTO currentSnapshotData;
@Schema(description = "恢复预览对应的当前配置状态指纹,仅详情接口有值")
private String currentStateToken;
}

View file

@ -10,7 +10,7 @@ public interface ConfigService {
* @param isCache 是否缓存 * @param isCache 是否缓存
* @return 配置信息 * @return 配置信息
*/ */
Map<String, Object> getConfig(Boolean isCache); Object getConfig(Boolean isCache);
/** /**
* 获取智能体模型配置 * 获取智能体模型配置
@ -28,4 +28,4 @@ public interface ConfigService {
* @return 替换词列表,格式如 ["模板1|模板01", "模板2|模板02"] * @return 替换词列表,格式如 ["模板1|模板01", "模板2|模板02"]
*/ */
List<String> getCorrectWords(String macAddress); List<String> getCorrectWords(String macAddress);
} }

View file

@ -65,12 +65,12 @@ public class ConfigServiceImpl implements ConfigService {
private final CorrectWordFileService correctWordFileService; private final CorrectWordFileService correctWordFileService;
@Override @Override
public Map<String, Object> getConfig(Boolean isCache) { public Object getConfig(Boolean isCache) {
if (isCache) { if (isCache) {
// 先从Redis获取配置 // 先从Redis获取配置
Object cachedConfig = redisUtils.get(RedisKeys.getServerConfigKey()); Object cachedConfig = redisUtils.get(RedisKeys.getServerConfigKey());
if (cachedConfig != null) { if (cachedConfig != null) {
return JsonUtils.toStringObjectMap(cachedConfig); return cachedConfig;
} }
} }
@ -123,7 +123,7 @@ public class ConfigServiceImpl implements ConfigService {
if (isAdminRequest != null && "true".equals(isAdminRequest)) { if (isAdminRequest != null && "true".equals(isAdminRequest)) {
// 管理控制台请求,返回getConfig的结果 // 管理控制台请求,返回getConfig的结果
redisUtils.delete(redisKey); // 使用后清理 redisUtils.delete(redisKey); // 使用后清理
return getConfig(true); return (Map<String, Object>) getConfig(true);
} }
// 根据MAC地址查找设备 // 根据MAC地址查找设备
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
@ -277,10 +277,10 @@ public class ConfigServiceImpl implements ConfigService {
// 遍历除最后一个key之外的所有key // 遍历除最后一个key之外的所有key
for (int i = 0; i < keys.length - 1; i++) { for (int i = 0; i < keys.length - 1; i++) {
String key = keys[i]; String key = keys[i];
Object nestedConfig = current.computeIfAbsent(key, ignored -> new HashMap<String, Object>()); if (!current.containsKey(key)) {
Map<String, Object> nestedMap = JsonUtils.toStringObjectMap(nestedConfig); current.put(key, new HashMap<String, Object>());
current.put(key, nestedMap); }
current = nestedMap; current = (Map<String, Object>) current.get(key);
} }
// 处理最后一个key // 处理最后一个key

View file

@ -125,9 +125,7 @@ public class DeviceController {
return new Result<Void>().error("设备不存在"); return new Result<Void>().error("设备不存在");
} }
BeanUtils.copyProperties(deviceUpdateDTO, entity); BeanUtils.copyProperties(deviceUpdateDTO, entity);
if (!deviceService.updateById(entity)) { deviceService.updateById(entity);
return new Result<Void>().error(ErrorCode.UPDATE_DATA_FAILED);
}
return new Result<Void>(); return new Result<Void>();
} }
@ -174,9 +172,6 @@ public class DeviceController {
@Operation(summary = "获取设备通讯录") @Operation(summary = "获取设备通讯录")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Object> getAddressBook(@PathVariable String macAddress) { public Result<Object> getAddressBook(@PathVariable String macAddress) {
if (deviceService.getOwnedDeviceByMacAddress(macAddress) == null) {
return new Result<Object>().error(ErrorCode.DEVICE_NOT_EXIST);
}
return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress)); return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress));
} }
@ -195,7 +190,9 @@ public class DeviceController {
@Operation(summary = "更新设备通讯录别名") @Operation(summary = "更新设备通讯录别名")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) { public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) {
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) { UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
return new Result<Void>().error("无权限操作该设备"); return new Result<Void>().error("无权限操作该设备");
} }
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null); deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null);
@ -206,10 +203,12 @@ public class DeviceController {
@Operation(summary = "更新设备通讯录权限") @Operation(summary = "更新设备通讯录权限")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) { public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) {
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) { UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
return new Result<Void>().error("无权限操作该设备"); return new Result<Void>().error("无权限操作该设备");
} }
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission()); deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission());
return new Result<Void>(); return new Result<Void>();
} }
} }

View file

@ -5,6 +5,8 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
@ -29,7 +31,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import cn.hutool.crypto.digest.DigestUtil;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
@ -287,7 +288,7 @@ public class OTAMagController {
// 返回文件路径 // 返回文件路径
return new Result<String>().ok(filePath.toString()); return new Result<String>().ok(filePath.toString());
} catch (IOException e) { } catch (IOException | NoSuchAlgorithmException e) {
return new Result<String>().error("文件上传失败:" + e.getMessage()); return new Result<String>().error("文件上传失败:" + e.getMessage());
} }
} }
@ -328,7 +329,13 @@ public class OTAMagController {
return result; return result;
} }
private String calculateMD5(MultipartFile file) throws IOException { private String calculateMD5(MultipartFile file) throws IOException, NoSuchAlgorithmException {
return DigestUtil.md5Hex(file.getBytes()); MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(file.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} }
} }

View file

@ -12,11 +12,6 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
@Mapper @Mapper
public interface DeviceAddressBookDao extends BaseMapper<DeviceAddressBookEntity> { public interface DeviceAddressBookDao extends BaseMapper<DeviceAddressBookEntity> {
/**
* 新增设备通讯录记录
*/
int insertAddressBook(DeviceAddressBookEntity entity);
/** /**
* 获取设备通讯录列表 * 获取设备通讯录列表
*/ */
@ -36,4 +31,4 @@ public interface DeviceAddressBookDao extends BaseMapper<DeviceAddressBookEntity
* 批量删除设备相关的通讯录记录 * 批量删除设备相关的通讯录记录
*/ */
void deleteByMacAddresses(@Param("macAddresses") List<String> macAddresses); void deleteByMacAddresses(@Param("macAddresses") List<String> macAddresses);
} }

View file

@ -83,16 +83,6 @@ public interface DeviceService extends BaseService<DeviceEntity> {
*/ */
DeviceEntity getDeviceByMacAddress(String macAddress); DeviceEntity getDeviceByMacAddress(String macAddress);
/**
* 根据MAC地址获取当前登录用户名下的设备信息
* <p>
* 设备不存在或不属于当前用户时返回null,调用方无需再自行比对归属。
*
* @param macAddress MAC地址
* @return 当前用户名下的设备信息,不存在或无权限时返回null
*/
DeviceEntity getOwnedDeviceByMacAddress(String macAddress);
/** /**
* 根据设备ID获取激活码 * 根据设备ID获取激活码
* *

View file

@ -1,14 +1,11 @@
package xiaozhi.modules.device.service.impl; package xiaozhi.modules.device.service.impl;
import java.time.Instant; import java.util.Date;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.nio.charset.StandardCharsets;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
@ -16,13 +13,12 @@ import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.device.dao.DeviceAddressBookDao; import xiaozhi.modules.device.dao.DeviceAddressBookDao;
import xiaozhi.modules.device.entity.DeviceAddressBookEntity; import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceAddressBookService; import xiaozhi.modules.device.service.DeviceAddressBookService;
import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysParamsService;
@ -45,11 +41,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
@Override @Override
public List<DeviceAddressBookEntity> getAddressBookList(String macAddress) { public List<DeviceAddressBookEntity> getAddressBookList(String macAddress) {
List<DeviceAddressBookEntity> rows = assignUniqueAliases(deviceAddressBookDao.getAddressBookList(macAddress)); return deviceAddressBookDao.getAddressBookList(macAddress);
// 取名按固定顺序算完了,前端要看的是最近改过的排前面,放回去
rows.sort(Comparator
.comparing(DeviceAddressBookEntity::getUpdateDate, Comparator.nullsLast(Comparator.reverseOrder())));
return rows;
} }
@Override @Override
@ -72,7 +64,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
} }
// 主动呼叫模式 // 主动呼叫模式
Map<String, String> callerBook = allBooks.get(bookKey(callerMac)); Map<String, String> callerBook = allBooks.get(callerMac.toLowerCase());
if (callerBook == null) { if (callerBook == null) {
return errorResult("未找到备注为'" + nickname + "'的设备"); return errorResult("未找到备注为'" + nickname + "'的设备");
} }
@ -89,20 +81,13 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
} }
// 获取目标设备如何称呼主叫方 // 获取目标设备如何称呼主叫方
Map<String, String> targetBook = allBooks.get(bookKey(targetMac)); Map<String, String> targetBook = allBooks.get(targetMac.toLowerCase());
String callerNickname = null; String callerNickname = null;
if (targetBook != null) { if (targetBook != null) {
callerNickname = targetBook.get(bookKey(callerMac)); callerNickname = targetBook.get(callerMac.toLowerCase());
} }
if (StringUtils.isBlank(callerNickname)) { if (StringUtils.isBlank(callerNickname)) {
// 主叫显示名取的是主叫方自己那台设备在设备表里的名字,不是对方的。 callerNickname = deviceService.getDeviceByMacAddress(callerMac).getAlias();
// 对方那边给主叫方起的称呼在上面的 targetBook 里已经查过。
// 产品上按「来电显示」的口径处理,所以这里不套通讯录那套「不抄对方私产」的限制
// 这个接口没有登录用户上下文,归属校验那个查法在这里会返回空,只能用不校验归属的查法
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(callerMac);
if (callerDevice != null) {
callerNickname = callerDevice.getAlias();
}
if (StringUtils.isBlank(callerNickname)) { if (StringUtils.isBlank(callerNickname)) {
callerNickname = formatMacAsDeviceName(callerMac); callerNickname = formatMacAsDeviceName(callerMac);
} }
@ -116,26 +101,32 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
@Override @Override
public void refreshCache() { public void refreshCache() {
Map<String, Map<String, String>> result = new HashMap<>(); Map<String, Map<String, String>> result = new HashMap<>();
List<DeviceAddressBookEntity> allRecords = assignUniqueAliases(deviceAddressBookDao.selectList(null)); List<DeviceAddressBookEntity> allRecords = deviceAddressBookDao.selectList(null);
Map<String, String> reverseMap = new HashMap<>(); Map<String, String> reverseMap = new HashMap<>();
for (DeviceAddressBookEntity entity : allRecords) { for (DeviceAddressBookEntity entity : allRecords) {
String macA = bookKey(entity.getMacAddress()); String macA = entity.getMacAddress().toLowerCase();
String macB = bookKey(entity.getTargetMac()); String macB = entity.getTargetMac().toLowerCase();
String alias = entity.getAlias();
Boolean hasPermission = entity.getHasPermission();
// 构建正向映射: A对B的映射 nickname -> macB|permission // 构建正向映射: A对B的映射 nickname -> macB|permission
Map<String, String> book = result.computeIfAbsent(macA, k -> new HashMap<>()); if (alias != null && !alias.isEmpty()) {
String permStr = (Boolean.TRUE.equals(entity.getHasPermission())) ? "1" : "0"; result.computeIfAbsent(macA, k -> new HashMap<>());
book.put(entity.getAlias(), macB + "|" + permStr); String permStr = (hasPermission != null && hasPermission) ? "1" : "0";
result.get(macA).put(alias, macB + "|" + permStr);
}
// 构建反向记录用于查找B对A的称呼,用同一个去重后的名字,两边才对得上 // 构建反向记录用于查找B对A的称呼
reverseMap.put(macB + ":" + macA, entity.getAlias()); if (alias != null && !alias.isEmpty()) {
reverseMap.put(macB + ":" + macA, alias);
}
} }
// 构建反向映射: B对A的映射 macA -> nickname // 构建反向映射: B对A的映射 macA -> nickname
for (DeviceAddressBookEntity entity : allRecords) { for (DeviceAddressBookEntity entity : allRecords) {
String macA = bookKey(entity.getMacAddress()); String macA = entity.getMacAddress().toLowerCase();
String macB = bookKey(entity.getTargetMac()); String macB = entity.getTargetMac().toLowerCase();
String aliasBtoA = reverseMap.get(macA + ":" + macB); String aliasBtoA = reverseMap.get(macA + ":" + macB);
if (aliasBtoA != null && !aliasBtoA.isEmpty()) { if (aliasBtoA != null && !aliasBtoA.isEmpty()) {
result.computeIfAbsent(macB, k -> new HashMap<>()); result.computeIfAbsent(macB, k -> new HashMap<>());
@ -146,54 +137,6 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
redisUtils.set(RedisKeys.getAddressBookKey(), result); redisUtils.set(RedisKeys.getAddressBookKey(), result);
} }
/**
* 给每行算出一个不重名的称呼,返回排好序、alias 已写好的新列表
*
* 昵称在同一个人的通讯录里是索引,同名后写的会盖掉先写的,按昵称呼会呼错设备。
* 库里本来就有重名:空别名补出来的尾号称呼只有 256 种取值,一本通讯录十几条
* 没起名就撞上了。所以显示和呼叫都得走这一份,
* 不然前端看到的字和呼叫时用的名字对不上,用户照着点的名字呼不到人。
* 不改传入的那个列表:它是 DAO 刚查出来的,调用方还要按自己的顺序用
*/
private List<DeviceAddressBookEntity> assignUniqueAliases(List<DeviceAddressBookEntity> rows) {
// 取名要靠先后定谁拿原名,而 selectList 不带 order by,返回顺序不保证。
// 排一次,同样的数据每次算出来的结果一样,缓存不会来回变。
// 按归一后的地址排:同一个人不管库里是哪种写法都排到一起,
// 后面两级比较器再分先后。同一本里 target_mac 不会重复(主键摆着),
// 所以顺序还是由这三个键定死的,不会掉回"跟着数据库返回顺序走"
List<DeviceAddressBookEntity> ordered = new ArrayList<>(rows);
ordered.sort(Comparator
.comparing((DeviceAddressBookEntity row) -> bookKey(row.getMacAddress()),
Comparator.nullsFirst(Comparator.naturalOrder()))
// 权限排在地址前面:撞名时让对方准许呼我的那台先拿原名。
// 排在后面等于不起作用,两条地址不同时谁先谁后是地址定的,
// 没权限那条照样占住原名,用户照前端看到的名字呼叫命中的就是它,
// 界面上只会说没权限,怎么点都不通
.thenComparing(DeviceAddressBookEntity::getHasPermission,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(DeviceAddressBookEntity::getTargetMac, Comparator.nullsFirst(Comparator.naturalOrder())));
Map<String, Set<String>> takenByOwner = new HashMap<>();
for (DeviceAddressBookEntity row : ordered) {
// 建表时 alias 默认是空的,用户没起名就是空的,这是默认状态不是异常。
// 补个尾号称呼顶上,整条跳过的话接口照样返回成功,对方却再也呼不过来
String alias = StringUtils.isBlank(row.getAlias())
? formatMacAsDeviceName(row.getTargetMac())
: row.getAlias();
// 加后缀的写法跟 generateUniqueAlias 保持一致,不搞两套命名规则
Set<String> taken = takenByOwner.computeIfAbsent(bookKey(row.getMacAddress()), k -> new HashSet<>());
String uniqueAlias = alias;
int suffix = 1;
while (taken.contains(uniqueAlias)) {
uniqueAlias = alias + suffix++;
}
taken.add(uniqueAlias);
row.setAlias(uniqueAlias);
}
return ordered;
}
@Override @Override
public void updateAlias(String macAddress, String targetMac, String alias) { public void updateAlias(String macAddress, String targetMac, String alias) {
String finalAlias = generateUniqueAlias(macAddress, targetMac, alias); String finalAlias = generateUniqueAlias(macAddress, targetMac, alias);
@ -212,35 +155,20 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
QueryWrapper<DeviceAddressBookEntity> wrapper = new QueryWrapper<>(); QueryWrapper<DeviceAddressBookEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac); wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac);
DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper); DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper);
System.out.println("saveOrUpdate - mac=" + macAddress + ", targetMac=" + targetMac + ", alias=" + alias + ", record=" + (record == null ? "null" : "not null"));
if (record == null) { if (record == null) {
DeviceAddressBookEntity entity = new DeviceAddressBookEntity(); DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
entity.setMacAddress(macAddress); entity.setMacAddress(macAddress);
entity.setTargetMac(targetMac); entity.setTargetMac(targetMac);
// 调用方没起名就退回尾号称呼。对方设备在智控台上起的名字是对方的私产, // 如果 alias 为空,就默认使用设备名称
// 抄进调用方的通讯录等于把别人的昵称漏出去,所以别人的设备一律不去设备表取名
if (StringUtils.isBlank(alias)) { if (StringUtils.isBlank(alias)) {
// 只有给自己那台设备起名时才用设备表里的名字,那本来就是调用方自己的 alias = deviceService.getDeviceByMacAddress(targetMac).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 进去,缓存刷新会把整条跳过,
// 接口照样返回成功,对方却永远呼不过来
if (StringUtils.isBlank(alias)) {
alias = formatMacAsDeviceName(targetMac);
}
} }
// 检查重名 // 检查重名
alias = generateUniqueAlias(macAddress, targetMac, alias); alias = generateUniqueAlias(macAddress, targetMac, alias);
entity.setAlias(alias); entity.setAlias(alias);
entity.setHasPermission(hasPermission); entity.setHasPermission(hasPermission);
deviceAddressBookDao.insertAddressBook(entity); deviceAddressBookDao.insert(entity);
} else { } else {
if (alias != null) { if (alias != null) {
updateAlias(macAddress, targetMac, alias); updateAlias(macAddress, targetMac, alias);
@ -273,22 +201,36 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
result.put("status", "error"); result.put("status", "error");
String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true);
String mqttSignatureKey = sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, true); String mqttSignatureKey = sysParamsService.getValue("server.mqtt_signature_key", true);
if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl) if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)
|| MqttGatewayAuthorization.isMissingSignatureKey(mqttSignatureKey)) { || StringUtils.isBlank(mqttSignatureKey) || "null".equals(mqttSignatureKey)) {
result.put("message", action + "失败,网关配置缺失"); result.put("message", action + "失败,网关配置缺失");
return result; return result;
} }
String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date());
try { try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest((dateStr + mqttSignatureKey).getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
String token = hexString.toString();
String url = "http://" + mqttGatewayUrl + path; String url = "http://" + mqttGatewayUrl + path;
String response = MqttGatewayAuthorization.postJson( String response = HttpRequest.post(url)
url, .header("Authorization", "Bearer " + token)
JSONUtil.toJsonStr(body), .header("Content-Type", "application/json")
mqttSignatureKey, .body(JSONUtil.toJsonStr(body))
Instant.now(), .timeout(5000)
5000); .execute()
.body();
if (StringUtils.isNotBlank(response)) { if (StringUtils.isNotBlank(response)) {
Map<String, Object> gwResult = JSONUtil.parseObj(response); Map<String, Object> gwResult = JSONUtil.parseObj(response);
@ -302,37 +244,11 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
} }
} }
/**
* 通讯录里当主人用的地址键
*
* <p>
* 写缓存、查缓存、算称呼都靠它分组,三处必须是同一个值。少归一一次,同一个人的两行
* 会被当成两个人:各自拿到同名,写进同一本时后者盖掉前者,一台设备直接从缓存里消失。
* 库里确实能出现这种数据——表是 utf8mb4_0900_ai_ci,主键 (mac_address, target_mac)
* 大小写不敏感,owner 只差大小写而 target 不同的话两行不撞
*/
private static String bookKey(String macAddress) {
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) { private String formatMacAsDeviceName(String mac) {
if (StringUtils.isBlank(mac) || mac.length() < 2) { if (StringUtils.isBlank(mac) || mac.length() < 2) {
return mac; return mac;
} }
// MAC 本身不区分大小写,落库、查库走的都是小写化的值。 String lastTwo = mac.substring(mac.length() - 2);
// 这里跟着小写化,不跟着的话同一个地址在两条路径上会算出两个称呼,
// 数据搬到智控台上看到的名字就叫不到人了
String lastTwo = mac.substring(mac.length() - 2).toLowerCase();
return "尾号为" + lastTwo + "的设备"; return "尾号为" + lastTwo + "的设备";
} }
@ -354,4 +270,4 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
} }
return newAlias; return newAlias;
} }
} }

View file

@ -31,10 +31,15 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray; import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
@ -51,7 +56,7 @@ import xiaozhi.common.service.impl.BaseServiceImpl;
import xiaozhi.common.user.UserDetail; import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.DateUtils; import xiaozhi.common.utils.DateUtils;
import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.ToolUtil;
import xiaozhi.modules.device.dao.DeviceDao; import xiaozhi.modules.device.dao.DeviceDao;
import xiaozhi.modules.device.dto.DeviceManualAddDTO; import xiaozhi.modules.device.dto.DeviceManualAddDTO;
import xiaozhi.modules.device.dto.DevicePageUserDTO; import xiaozhi.modules.device.dto.DevicePageUserDTO;
@ -103,15 +108,15 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
throw new RenException(ErrorCode.ACTIVATION_CODE_EMPTY); throw new RenException(ErrorCode.ACTIVATION_CODE_EMPTY);
} }
String deviceKey = RedisKeys.getOtaActivationCode(activationCode); String deviceKey = RedisKeys.getOtaActivationCode(activationCode);
String cacheDeviceId = (String) redisUtils.get(deviceKey); Object cacheDeviceId = redisUtils.get(deviceKey);
if (StringUtils.isBlank(cacheDeviceId)) { if (ToolUtil.isEmpty(cacheDeviceId)) {
throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR); throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR);
} }
String deviceId = cacheDeviceId; String deviceId = (String) cacheDeviceId;
String safeDeviceId = deviceId.replace(":", "_").toLowerCase(); String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
String cacheDeviceKey = RedisKeys.getOtaDeviceActivationInfo(safeDeviceId); String cacheDeviceKey = RedisKeys.getOtaDeviceActivationInfo(safeDeviceId);
Map<String, Object> cacheMap = JsonUtils.toStringObjectMap(redisUtils.get(cacheDeviceKey)); Map<String, Object> cacheMap = (Map<String, Object>) redisUtils.get(cacheDeviceKey);
if (MapUtil.isEmpty(cacheMap)) { if (ToolUtil.isEmpty(cacheMap)) {
throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR); throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR);
} }
String cachedCode = (String) cacheMap.get("activation_code"); String cachedCode = (String) cacheMap.get("activation_code");
@ -181,8 +186,15 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
.builder(new HashMap<String, Set<String>>()) .builder(new HashMap<String, Set<String>>())
.put("clientIds", deviceIds).build(); .put("clientIds", deviceIds).build();
if (CollUtil.isNotEmpty(deviceIds)) { if (ToolUtil.isNotEmpty(deviceIds)) {
return postToMqttGateway(url, params); // 发送请求
String resultMessage = HttpRequest.post(url)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.header(Header.AUTHORIZATION, "Bearer " + generateBearerToken())
.body(JSONUtil.toJsonStr(params))
.timeout(10000) // 超时,毫秒
.execute().body();
return resultMessage;
} }
// 返回响应 // 返回响应
return ""; return "";
@ -202,8 +214,8 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
firmware.setUrl(Constant.INVALID_FIRMWARE_URL); firmware.setUrl(Constant.INVALID_FIRMWARE_URL);
response.setFirmware(firmware); response.setFirmware(firmware);
} else { } else {
// 只有在设备已绑定且明确开启自动升级时才返回固件升级信息 // 只有在设备已绑定且autoUpdate不为0的情况下才返回固件升级信息
if (Integer.valueOf(1).equals(deviceById.getAutoUpdate())) { if (deviceById.getAutoUpdate() != 0) {
String type = deviceReport.getBoard() == null ? null : deviceReport.getBoard().getType(); String type = deviceReport.getBoard() == null ? null : deviceReport.getBoard().getType();
DeviceReportRespDTO.Firmware firmware = buildFirmwareInfo(type, DeviceReportRespDTO.Firmware firmware = buildFirmwareInfo(type,
deviceReport.getApplication() == null ? null : deviceReport.getApplication().getVersion()); deviceReport.getApplication() == null ? null : deviceReport.getApplication().getVersion());
@ -292,21 +304,15 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
@Override @Override
public List<UserShowDeviceListVO> getUserDeviceList(Long userId, String agentId) { public List<UserShowDeviceListVO> getUserDeviceList(Long userId, String agentId) {
List<DeviceEntity> devices = getUserDevices(userId, agentId); List<DeviceEntity> devices = getUserDevices(userId, agentId);
return devices.stream().map(this::toUserShowDeviceListVO).toList(); return devices.stream().map(device -> {
} UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class);
vo.setDeviceType(device.getBoard());
private UserShowDeviceListVO toUserShowDeviceListVO(DeviceEntity device) { // 设置UTC时间戳供前端使用时区转换
UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); if (device.getLastConnectedAt() != null) {
vo.setDeviceType(device.getBoard()); vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime());
vo.setBoard(device.getBoard()); }
vo.setAutoUpdate(device.getAutoUpdate()); return vo;
vo.setCreateDateTimestamp(toTimestamp(device.getCreateDate())); }).toList();
vo.setLastConnectedAtTimestamp(toTimestamp(device.getLastConnectedAt()));
return vo;
}
private Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
} }
@Override @Override
@ -316,12 +322,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
if (device == null) { if (device == null) {
return; return;
} }
// 后面删通讯录那步是按 mac_address 删的,不看 user_id。
// 设备本身因为带了 user_id 条件删不掉,通讯录却会照删不误,
// 任意登录用户知道对方的设备 id 就能把对方整本通讯录清空
if (userId == null || device.getUserId() == null || !device.getUserId().equals(userId)) {
return;
}
String macAddress = device.getMacAddress(); String macAddress = device.getMacAddress();
if (StringUtils.isNotBlank(device.getAgentId())) { if (StringUtils.isNotBlank(device.getAgentId())) {
// 清除智能体设备数量缓存 // 清除智能体设备数量缓存
@ -385,11 +385,17 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
.like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords())); .like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords()));
// 循环处理page获取回来的数据,返回需要的字段 // 循环处理page获取回来的数据,返回需要的字段
List<UserShowDeviceListVO> list = page.getRecords().stream().map(device -> { List<UserShowDeviceListVO> list = page.getRecords().stream().map(device -> {
UserShowDeviceListVO vo = toUserShowDeviceListVO(device); UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class);
// 把最后修改的时间,改为简短描述的时间 // 把最后修改的时间,改为简短描述的时间
vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate())); vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate()));
sysUserUtilService.assignUsername(device.getUserId(), sysUserUtilService.assignUsername(device.getUserId(),
vo::setBindUserName); vo::setBindUserName);
vo.setDeviceType(device.getBoard());
vo.setBoard(device.getBoard());
// 设置UTC时间戳供前端使用时区转换
if (device.getLastConnectedAt() != null) {
vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime());
}
return vo; return vo;
}).toList(); }).toList();
// 计算页数 // 计算页数
@ -406,29 +412,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return baseDao.selectOne(wrapper); return baseDao.selectOne(wrapper);
} }
@Override
public DeviceEntity getOwnedDeviceByMacAddress(String macAddress) {
if (StringUtils.isBlank(macAddress)) {
return null;
}
// 同一 MAC 可能有两行只差大小写,selectOne 会抛 TooManyResultsException
// 把整个读通讯录接口带崩。按 id 取第一条做归属校验,撞行不报错
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress).orderByAsc("id");
List<DeviceEntity> devices = baseDao.selectList(wrapper);
if (devices == null || devices.isEmpty()) {
return null;
}
DeviceEntity device = devices.get(0);
UserDetail user = SecurityUser.getUser();
// getUser() 在取不到 subject、principal 时返回的是空对象,不是 null,
// 所以这里不会拿到 null。匿名调用走的就是空对象那一条,id 是空的,比不上
if (device.getUserId() == null || !device.getUserId().equals(user.getId())) {
return null;
}
return device;
}
private DeviceReportRespDTO.ServerTime buildServerTime() { private DeviceReportRespDTO.ServerTime buildServerTime() {
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime(); DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
TimeZone tz = TimeZone.getDefault(); TimeZone tz = TimeZone.getDefault();
@ -442,7 +425,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
public String geCodeByDeviceId(String deviceId) { public String geCodeByDeviceId(String deviceId) {
String dataKey = getDeviceCacheKey(deviceId); String dataKey = getDeviceCacheKey(deviceId);
Map<String, Object> cacheMap = JsonUtils.toStringObjectMap(redisUtils.get(dataKey)); Map<String, Object> cacheMap = (Map<String, Object>) redisUtils.get(dataKey);
if (cacheMap != null && cacheMap.containsKey("activation_code")) { if (cacheMap != null && cacheMap.containsKey("activation_code")) {
String cachedCode = (String) cacheMap.get("activation_code"); String cachedCode = (String) cacheMap.get("activation_code");
return cachedCode; return cachedCode;
@ -716,13 +699,20 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return mqtt; return mqtt;
} }
private String postToMqttGateway(String url, Object requestBody) { /**
String signatureKey = sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, false); * 生成BearerToken
return MqttGatewayAuthorization.postJson( */
url, private String generateBearerToken() {
JSONUtil.toJsonStr(requestBody), try {
signatureKey, String dateStr = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
Instant.now()); String signatureKey = sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, false);
if (ToolUtil.isEmpty(signatureKey)) {
return null;
}
return DigestUtil.sha256Hex(dateStr + signatureKey);
} catch (Exception e) {
return null;
}
} }
@Override @Override
@ -783,7 +773,13 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
.put("payload", payload) .put("payload", payload)
.build(); .build();
String resultMessage = postToMqttGateway(url, requestBody); // 发送请求
String resultMessage = HttpRequest.post(url)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.header(Header.AUTHORIZATION, "Bearer " + generateBearerToken())
.body(JSONUtil.toJsonStr(requestBody))
.timeout(10000) // 超时,毫秒
.execute().body();
// 解析响应 // 解析响应
if (StringUtils.isBlank(resultMessage)) { if (StringUtils.isBlank(resultMessage)) {
@ -874,7 +870,13 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
.put("payload", payload) .put("payload", payload)
.build(); .build();
String resultMessage = postToMqttGateway(url, requestBody); // 发送请求
String resultMessage = HttpRequest.post(url)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.header(Header.AUTHORIZATION, "Bearer " + generateBearerToken())
.body(JSONUtil.toJsonStr(requestBody))
.timeout(10000) // 超时,毫秒
.execute().body();
// 解析响应 // 解析响应
if (StringUtils.isNotBlank(resultMessage)) { if (StringUtils.isNotBlank(resultMessage)) {

View file

@ -1,111 +0,0 @@
package xiaozhi.modules.device.service.impl;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;
import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
final class MqttGatewayAuthorization {
private static final int HTTP_UNAUTHORIZED = 401;
private static final int DEFAULT_TIMEOUT_MILLIS = 10000;
private MqttGatewayAuthorization() {
}
static String postJson(String url, String jsonBody, String signatureKey, Instant now) {
return postJson(url, jsonBody, signatureKey, now, DEFAULT_TIMEOUT_MILLIS);
}
static String postJson(String url, String jsonBody, String signatureKey, Instant now, int timeoutMillis) {
GatewayResponse response = executeWithDateFallback(
signatureKey,
now,
token -> executeRequest(url, jsonBody, token, timeoutMillis));
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new GatewayRequestException(
"MQTT Gateway request failed with HTTP status " + response.statusCode(),
response.statusCode());
}
return response.body();
}
static List<String> generateDailyTokens(String signatureKey, Instant now) {
if (isMissingSignatureKey(signatureKey)) {
throw new GatewayRequestException("MQTT Gateway signature key is empty", null);
}
LocalDate utcDate = now.atZone(ZoneOffset.UTC).toLocalDate();
return List.of(
tokenFor(utcDate, signatureKey),
tokenFor(utcDate.minusDays(1), signatureKey),
tokenFor(utcDate.plusDays(1), signatureKey));
}
static GatewayResponse executeWithDateFallback(String signatureKey, Instant now,
Function<String, GatewayResponse> requestExecutor) {
GatewayResponse lastAuthenticationFailure = null;
for (String token : generateDailyTokens(signatureKey, now)) {
GatewayResponse response = requestExecutor.apply(token);
if (!isAuthenticationFailure(response.statusCode())) {
return response;
}
lastAuthenticationFailure = response;
}
Integer statusCode = lastAuthenticationFailure == null ? null : lastAuthenticationFailure.statusCode();
throw new GatewayRequestException(
"MQTT Gateway rejected all daily authorization tokens"
+ (statusCode == null ? "" : " (HTTP " + statusCode + ")"),
statusCode);
}
private static String tokenFor(LocalDate date, String signatureKey) {
return DigestUtil.sha256Hex(date + signatureKey);
}
private static boolean isAuthenticationFailure(int statusCode) {
return statusCode == HTTP_UNAUTHORIZED;
}
static boolean isMissingSignatureKey(String signatureKey) {
return StringUtils.isBlank(signatureKey) || "null".equalsIgnoreCase(signatureKey.trim());
}
private static GatewayResponse executeRequest(String url, String jsonBody, String token, int timeoutMillis) {
try (HttpResponse response = HttpRequest.post(url)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.header(Header.AUTHORIZATION, "Bearer " + token)
.body(jsonBody)
.timeout(timeoutMillis)
.execute()) {
return new GatewayResponse(response.getStatus(), response.body());
}
}
record GatewayResponse(int statusCode, String body) {
}
static final class GatewayRequestException extends RuntimeException {
private final Integer statusCode;
GatewayRequestException(String message, Integer statusCode) {
super(message);
this.statusCode = statusCode;
}
Integer statusCode() {
return statusCode;
}
}
}

View file

@ -56,7 +56,7 @@ public class OtaServiceImpl extends BaseServiceImpl<OtaDao, OtaEntity> implement
@Override @Override
public void delete(String[] ids) { public void delete(String[] ids) {
baseDao.deleteByIds(Arrays.asList(ids)); baseDao.deleteBatchIds(Arrays.asList(ids));
} }
@Override @Override
@ -82,4 +82,4 @@ public class OtaServiceImpl extends BaseServiceImpl<OtaDao, OtaEntity> implement
.last("LIMIT 1"); .last("LIMIT 1");
return baseDao.selectOne(wrapper); return baseDao.selectOne(wrapper);
} }
} }

View file

@ -32,20 +32,17 @@ public class UserShowDeviceListVO {
@Schema(description = "设备别名") @Schema(description = "设备别名")
private String alias; private String alias;
@Schema(description = "自动更新开关(0关闭/1开启)") @Schema(description = "开启OTA")
private Integer autoUpdate; private Integer otaUpgrade;
@Schema(description = "最近对话时间") @Schema(description = "最近对话时间")
private String recentChatTime; private String recentChatTime;
@Schema(description = "最后连接时间戳(毫秒)", type = "string", example = "1783689702000") @Schema(description = "最后连接时间(UTC毫秒)")
private Long lastConnectedAtTimestamp; private Long lastConnectedAtTimestamp;
@Schema(description = "绑定时间戳(毫秒)", type = "string", example = "1783689702000") @Schema(description = "绑定时间")
private Long createDateTimestamp;
@Schema(description = "绑定时间(兼容字段,请使用 createDateTimestamp)", deprecated = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC")
private Date createDate; private Date createDate;
} }

View file

@ -15,7 +15,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.collection.CollUtil;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -24,6 +23,7 @@ import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException; import xiaozhi.common.exception.RenException;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.common.utils.ToolUtil;
import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO;
import xiaozhi.modules.knowledge.service.KnowledgeBaseService; import xiaozhi.modules.knowledge.service.KnowledgeBaseService;
import xiaozhi.modules.knowledge.service.KnowledgeManagerService; import xiaozhi.modules.knowledge.service.KnowledgeManagerService;
@ -140,7 +140,7 @@ public class KnowledgeBaseController {
List<String> idList = Arrays.asList(ids.split(",")); List<String> idList = Arrays.asList(ids.split(","));
List<KnowledgeBaseDTO> knowledgeBaseDTOs = Optional.ofNullable(knowledgeBaseService.getByDatasetIdList(idList)) List<KnowledgeBaseDTO> knowledgeBaseDTOs = Optional.ofNullable(knowledgeBaseService.getByDatasetIdList(idList))
.orElseGet(ArrayList::new); .orElseGet(ArrayList::new);
if (CollUtil.isNotEmpty(knowledgeBaseDTOs)) { if (ToolUtil.isNotEmpty(knowledgeBaseDTOs)) {
knowledgeBaseDTOs.forEach(item -> { knowledgeBaseDTOs.forEach(item -> {
// 检查权限:用户只能删除自己创建的知识库 // 检查权限:用户只能删除自己创建的知识库
if (item.getCreator() == null || !item.getCreator().equals(currentUserId)) { if (item.getCreator() == null || !item.getCreator().equals(currentUserId)) {
@ -160,4 +160,4 @@ public class KnowledgeBaseController {
List<ModelConfigEntity> result = knowledgeBaseService.getRAGModels(); List<ModelConfigEntity> result = knowledgeBaseService.getRAGModels();
return new Result<List<ModelConfigEntity>>().ok(result); return new Result<List<ModelConfigEntity>>().ok(result);
} }
} }

View file

@ -149,8 +149,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
log.info("=== [RAGFlow] 获取文档列表: datasetId={} ===", datasetId); log.info("=== [RAGFlow] 获取文档列表: datasetId={} ===", datasetId);
// 使用 Jackson 将 DTO 转为 Map 作为查询参数 // 使用 Jackson 将 DTO 转为 Map 作为查询参数
Map<String, Object> params = objectMapper.convertValue(req, new TypeReference<Map<String, Object>>() { @SuppressWarnings("unchecked")
}); Map<String, Object> params = objectMapper.convertValue(req, Map.class);
Map<String, Object> response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params); Map<String, Object> response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params);
@ -174,12 +174,13 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
.pageSize(1) .pageSize(1)
.build(); .build();
Map<String, Object> params = objectMapper.convertValue(req, new TypeReference<Map<String, Object>>() { @SuppressWarnings("unchecked")
}); Map<String, Object> params = objectMapper.convertValue(req, Map.class);
Map<String, Object> response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params); Map<String, Object> response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params);
Object dataObj = response.get("data"); Object dataObj = response.get("data");
if (dataObj instanceof Map<?, ?> dataMap) { if (dataObj instanceof Map) {
Map<String, Object> dataMap = (Map<String, Object>) dataObj;
List<?> documents = (List<?>) dataMap.get("docs"); List<?> documents = (List<?>) dataMap.get("docs");
if (documents != null && !documents.isEmpty()) { if (documents != null && !documents.isEmpty()) {
return objectMapper.convertValue(documents.get(0), DocumentDTO.InfoVO.class); return objectMapper.convertValue(documents.get(0), DocumentDTO.InfoVO.class);
@ -566,8 +567,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
return new PageData<>(new ArrayList<>(), 0); return new PageData<>(new ArrayList<>(), 0);
} }
Map<?, ?> dataMap = Map.class.cast(dataObj); Map<String, Object> dataMap = (Map<String, Object>) dataObj;
List<?> documents = List.class.cast(dataMap.get("docs")); List<Map<String, Object>> documents = (List<Map<String, Object>>) dataMap.get("docs");
if (documents == null || documents.isEmpty()) { if (documents == null || documents.isEmpty()) {
// RAGFlow 明确返回了空文档列表,这是合法的"真空" // RAGFlow 明确返回了空文档列表,这是合法的"真空"
return new PageData<>(new ArrayList<>(), 0); return new PageData<>(new ArrayList<>(), 0);
@ -678,9 +679,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
dto.setChunkMethod(info.getChunkMethod().name().toLowerCase()); dto.setChunkMethod(info.getChunkMethod().name().toLowerCase());
} }
if (info.getParserConfig() != null) { if (info.getParserConfig() != null) {
dto.setParserConfig(objectMapper.convertValue(info.getParserConfig(), dto.setParserConfig(objectMapper.convertValue(info.getParserConfig(), Map.class));
new TypeReference<Map<String, Object>>() {
}));
} }
return dto; return dto;
@ -718,4 +717,4 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
return !multipartFile.isEmpty(); return !multipartFile.isEmpty();
} }
} }
} }

View file

@ -36,7 +36,6 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
static { static {
THINKING_DISABLED_DOMAINS.put("aliyuncs.com", Map.of("enable_thinking", false)); THINKING_DISABLED_DOMAINS.put("aliyuncs.com", Map.of("enable_thinking", false));
Map<String, Object> thinkingDisabled = Map.of("thinking", Map.of("type", "disabled")); Map<String, Object> thinkingDisabled = Map.of("thinking", Map.of("type", "disabled"));
THINKING_DISABLED_DOMAINS.put("deepseek.com", thinkingDisabled);
THINKING_DISABLED_DOMAINS.put("bigmodel.cn", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("bigmodel.cn", thinkingDisabled);
THINKING_DISABLED_DOMAINS.put("moonshot.cn", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("moonshot.cn", thinkingDisabled);
THINKING_DISABLED_DOMAINS.put("volces.com", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("volces.com", thinkingDisabled);
@ -64,37 +63,6 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}"; 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 @Override
public String generateSummary(String conversation) { public String generateSummary(String conversation) {
return generateSummary(conversation, null, null); return generateSummary(conversation, null, null);
@ -132,13 +100,6 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url"); String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name"); String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key"); 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"); Double temperature = configJson.getDouble("temperature");
Integer maxTokens = configJson.getInt("max_tokens"); Integer maxTokens = configJson.getInt("max_tokens");
@ -155,11 +116,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
Map<String, Object> requestBody = new HashMap<>(); Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); requestBody.put("model", model != null ? model : "gpt-3.5-turbo");
Map<String, Object>[] messages = new Map[1];
Map<String, Object> message = new HashMap<>(); Map<String, Object> message = new HashMap<>();
message.put("role", "user"); message.put("role", "user");
message.put("content", prompt); message.put("content", prompt);
messages[0] = message;
requestBody.put("messages", List.of(message)); requestBody.put("messages", messages);
requestBody.put("temperature", temperature != null ? temperature : 0.7); requestBody.put("temperature", temperature != null ? temperature : 0.7);
requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000); requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000);
@ -234,13 +197,6 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url"); String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name"); String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key"); 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)) { if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空"); log.error("LLM配置不完整,baseUrl或apiKey为空");
@ -256,11 +212,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
Map<String, Object> requestBody = new HashMap<>(); Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); requestBody.put("model", model != null ? model : "gpt-3.5-turbo");
Map<String, Object>[] messages = new Map[1];
Map<String, Object> message = new HashMap<>(); Map<String, Object> message = new HashMap<>();
message.put("role", "user"); message.put("role", "user");
message.put("content", prompt); message.put("content", prompt);
messages[0] = message;
requestBody.put("messages", List.of(message)); requestBody.put("messages", messages);
requestBody.put("temperature", 0.2); requestBody.put("temperature", 0.2);
requestBody.put("max_tokens", 2000); requestBody.put("max_tokens", 2000);
@ -316,10 +274,8 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url"); String baseUrl = configJson.getStr("base_url");
String apiKey = configJson.getStr("api_key"); String apiKey = configJson.getStr("api_key");
// Ollama免鉴权:不要求api_key
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
return baseUrl != null && !baseUrl.trim().isEmpty() && return baseUrl != null && !baseUrl.trim().isEmpty() &&
(ollama || (apiKey != null && !apiKey.trim().isEmpty())); apiKey != null && !apiKey.trim().isEmpty();
} catch (Exception e) { } catch (Exception e) {
log.error("检查LLM服务可用性时发生异常:", e); log.error("检查LLM服务可用性时发生异常:", e);
return false; return false;
@ -344,10 +300,8 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url"); String baseUrl = configJson.getStr("base_url");
String apiKey = configJson.getStr("api_key"); String apiKey = configJson.getStr("api_key");
// Ollama免鉴权:不要求api_key
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
return baseUrl != null && !baseUrl.trim().isEmpty() && return baseUrl != null && !baseUrl.trim().isEmpty() &&
(ollama || (apiKey != null && !apiKey.trim().isEmpty())); apiKey != null && !apiKey.trim().isEmpty();
} catch (Exception e) { } catch (Exception e) {
log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e); log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e);
return false; return false;
@ -403,13 +357,6 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url"); String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name"); String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key"); 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)) { if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空"); log.error("LLM配置不完整,baseUrl或apiKey为空");
@ -421,11 +368,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
Map<String, Object> requestBody = new HashMap<>(); Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); requestBody.put("model", model != null ? model : "gpt-3.5-turbo");
Map<String, Object>[] messages = new Map[1];
Map<String, Object> message = new HashMap<>(); Map<String, Object> message = new HashMap<>();
message.put("role", "user"); message.put("role", "user");
message.put("content", prompt); message.put("content", prompt);
messages[0] = message;
requestBody.put("messages", List.of(message)); requestBody.put("messages", messages);
requestBody.put("temperature", 0.3); requestBody.put("temperature", 0.3);
requestBody.put("max_tokens", 50); requestBody.put("max_tokens", 50);
@ -473,4 +422,4 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return null; return null;
} }
} }

View file

@ -110,8 +110,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
// 1. 参数验证 // 1. 参数验证
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO); validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
// 2. 验证模型提供者,使用注册类型的大小写 // 2. 验证模型提供者
String registeredModelType = resolveModelType(modelType, provideCode); validateModelProvider(modelType, provideCode);
// 3. 获取原始配置(不经过敏感数据处理) // 3. 获取原始配置(不经过敏感数据处理)
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id); ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
@ -120,7 +120,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
validateLlmConfiguration(modelConfigBodyDTO); validateLlmConfiguration(modelConfigBodyDTO);
// 5. 准备更新实体并处理敏感数据 // 5. 准备更新实体并处理敏感数据
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, registeredModelType, id); ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id);
// 6. 执行数据库更新 // 6. 执行数据库更新
modelConfigDao.updateById(modelConfigEntity); modelConfigDao.updateById(modelConfigEntity);
@ -136,9 +136,9 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) { public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
validateAddParameters(modelType, provideCode, modelConfigBodyDTO); validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
String registeredModelType = resolveModelType(modelType, provideCode); validateModelProvider(modelType, provideCode);
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, registeredModelType); ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, modelType);
modelConfigDao.insert(modelConfigEntity); modelConfigDao.insert(modelConfigEntity);
@ -283,14 +283,13 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
} }
/** /**
* 验证模型提供者并获取注册类型,保留 TTS、Memory、Intent 等类型的大小写 * 验证模型提供者
*/ */
private String resolveModelType(String modelType, String provideCode) { private void validateModelProvider(String modelType, String provideCode) {
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode); List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
if (CollectionUtil.isEmpty(providerList)) { if (CollectionUtil.isEmpty(providerList)) {
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST); throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
} }
return providerList.get(0).getModelType();
} }
/** /**
@ -363,14 +362,14 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
if (SensitiveDataUtils.isSensitiveField(key)) { if (SensitiveDataUtils.isSensitiveField(key)) {
if (value instanceof String && !SensitiveDataUtils.isMaskedValue((String) value)) { if (value instanceof String && !SensitiveDataUtils.isMaskedValue((String) value)) {
updatedJson.set(key, value); updatedJson.put(key, value);
} }
} else if (value instanceof JSONObject) { } else if (value instanceof JSONObject) {
// 递归处理嵌套JSON // 递归处理嵌套JSON
mergeJson(updatedJson, key, (JSONObject) value); mergeJson(updatedJson, key, (JSONObject) value);
} else { } else {
// 非敏感字段直接更新 // 非敏感字段直接更新
updatedJson.set(key, value); updatedJson.put(key, value);
} }
} }
@ -406,7 +405,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
// 如果 original 中不存在 key,创建一个新的 JSON 对象 // 如果 original 中不存在 key,创建一个新的 JSON 对象
if (!original.containsKey(key)) { if (!original.containsKey(key)) {
original.set(key, new JSONObject()); original.put(key, new JSONObject());
} }
// 获取 original 中的子对象 // 获取 original 中的子对象
@ -421,7 +420,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
log.warn("mergeJson: key '{}' 的值不是 JSONObject 类型 (实际类型:{}),将创建新对象", log.warn("mergeJson: key '{}' 的值不是 JSONObject 类型 (实际类型:{}),将创建新对象",
key, originalValue != null ? originalValue.getClass().getSimpleName() : "null"); key, originalValue != null ? originalValue.getClass().getSimpleName() : "null");
originalChild = new JSONObject(); originalChild = new JSONObject();
original.set(key, originalChild); original.put(key, originalChild);
} }
for (String childKey : updated.keySet()) { for (String childKey : updated.keySet()) {
@ -431,7 +430,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
} else { } else {
if (!SensitiveDataUtils.isSensitiveField(childKey) || if (!SensitiveDataUtils.isSensitiveField(childKey) ||
(childValue instanceof String && !isMaskedValue((String) childValue))) { (childValue instanceof String && !isMaskedValue((String) childValue))) {
originalChild.set(childKey, childValue); originalChild.put(childKey, childValue);
} }
} }
} }

View file

@ -164,7 +164,7 @@ public class ModelProviderServiceImpl extends BaseServiceImpl<ModelProviderDao,
@Override @Override
public void delete(List<String> ids) { public void delete(List<String> ids) {
if (modelProviderDao.deleteByIds(ids) == 0) { if (modelProviderDao.deleteBatchIds(ids) == 0) {
throw new RenException(ErrorCode.DELETE_DATA_FAILED); throw new RenException(ErrorCode.DELETE_DATA_FAILED);
} }
} }

View file

@ -4,19 +4,16 @@ import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.config.ShiroFilterConfiguration; import org.apache.shiro.web.config.ShiroFilterConfiguration;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Role;
import jakarta.servlet.Filter; import jakarta.servlet.Filter;
import xiaozhi.modules.security.oauth2.Oauth2Filter; import xiaozhi.modules.security.oauth2.Oauth2Filter;
@ -42,7 +39,7 @@ public class ShiroConfig {
} }
@Bean("securityManager") @Bean("securityManager")
public WebSecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) { public SecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(oAuth2Realm); securityManager.setRealm(oAuth2Realm);
securityManager.setSessionManager(sessionManager); securityManager.setSessionManager(sessionManager);
@ -51,8 +48,7 @@ public class ShiroConfig {
} }
@Bean("shiroFilter") @Bean("shiroFilter")
public static ShiroFilterFactoryBean shirFilter(@Lazy WebSecurityManager securityManager, public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager, SysParamsService sysParamsService) {
@Lazy SysParamsService sysParamsService) {
ShiroFilterConfiguration config = new ShiroFilterConfiguration(); ShiroFilterConfiguration config = new ShiroFilterConfiguration();
config.setFilterOncePerRequest(true); config.setFilterOncePerRequest(true);
@ -86,7 +82,6 @@ public class ShiroConfig {
filterMap.put("/user/captcha", "anon"); filterMap.put("/user/captcha", "anon");
filterMap.put("/user/smsVerification", "anon"); filterMap.put("/user/smsVerification", "anon");
filterMap.put("/user/login", "anon"); filterMap.put("/user/login", "anon");
filterMap.put("/user/refresh", "anon");
filterMap.put("/user/pub-config", "anon"); filterMap.put("/user/pub-config", "anon");
filterMap.put("/user/register", "anon"); filterMap.put("/user/register", "anon");
filterMap.put("/user/retrieve-password", "anon"); filterMap.put("/user/retrieve-password", "anon");
@ -106,14 +101,12 @@ public class ShiroConfig {
} }
@Bean("lifecycleBeanPostProcessor") @Bean("lifecycleBeanPostProcessor")
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor(); return new LifecycleBeanPostProcessor();
} }
@Bean @Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
public static AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
@Lazy WebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager); advisor.setSecurityManager(securityManager);
return advisor; return advisor;

View file

@ -16,7 +16,6 @@ import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -111,17 +110,6 @@ public class LoginController {
return sysUserTokenService.createToken(userDTO.getId()); return sysUserTokenService.createToken(userDTO.getId());
} }
@PostMapping("/refresh")
@Operation(summary = "刷新token:用旧token换新token")
public Result<TokenDTO> refresh(HttpServletRequest request) {
String authorization = request.getHeader(Constant.AUTHORIZATION);
if (StringUtils.isBlank(authorization) || !authorization.startsWith("Bearer ")) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
String oldToken = authorization.replace("Bearer ", "");
return sysUserTokenService.refreshToken(oldToken);
}
@PostMapping("/register") @PostMapping("/register")
@Operation(summary = "注册") @Operation(summary = "注册")
public Result<Void> register(@RequestBody LoginDTO login) { public Result<Void> register(@RequestBody LoginDTO login) {

View file

@ -21,14 +21,4 @@ public interface SysUserTokenDao extends BaseDao<SysUserTokenEntity> {
SysUserTokenEntity getByUserId(Long userId); SysUserTokenEntity getByUserId(Long userId);
void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate); void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate);
/**
* 用旧 token 换新 token 的 CAS 更新:仅当旧 token 未过期且属于指定 user 时才覆盖。
* 返回受影响行数(0 表示条件不满足 = token 已被并发刷新或过期)。
*/
int refreshTokenCAS(@Param("userId") Long userId,
@Param("oldToken") String oldToken,
@Param("newToken") String newToken,
@Param("newExpire") Date newExpire,
@Param("updateDate") Date updateDate);
} }

View file

@ -21,13 +21,6 @@ public interface SysUserTokenService extends BaseService<SysUserTokenEntity> {
*/ */
Result<TokenDTO> createToken(Long userId); Result<TokenDTO> createToken(Long userId);
/**
* 用旧token换新token,旧token立即失效
*
* @param oldToken 旧token字符串
*/
Result<TokenDTO> refreshToken(String oldToken);
SysUserDTO getUserByToken(String token); SysUserDTO getUserByToken(String token);
/** /**

View file

@ -1,7 +1,8 @@
package xiaozhi.modules.security.service.impl; package xiaozhi.modules.security.service.impl;
import java.io.IOException; import java.io.IOException;
import java.time.Duration; import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -12,7 +13,6 @@ import com.google.common.cache.CacheBuilder;
import com.wf.captcha.SpecCaptcha; import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha; import com.wf.captcha.base.Captcha;
import cn.hutool.core.util.RandomUtil;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
@ -41,7 +41,7 @@ public class CaptchaServiceImpl implements CaptchaService {
* Local Cache 5分钟过期 * Local Cache 5分钟过期
*/ */
Cache<String, String> localCache = CacheBuilder.newBuilder().maximumSize(1000) Cache<String, String> localCache = CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterAccess(Duration.ofMinutes(5)).build(); .expireAfterAccess(5, TimeUnit.MINUTES).build();
@Override @Override
public void create(HttpServletResponse response, String uuid) throws IOException { public void create(HttpServletResponse response, String uuid) throws IOException {
@ -113,7 +113,7 @@ public class CaptchaServiceImpl implements CaptchaService {
} }
String key = RedisKeys.getSMSValidateCodeKey(phone); String key = RedisKeys.getSMSValidateCodeKey(phone);
String validateCodes = RandomUtil.randomNumbers(6); String validateCodes = generateValidateCode(6);
// 设置验证码 // 设置验证码
setCache(key, validateCodes); setCache(key, validateCodes);
@ -135,6 +135,22 @@ public class CaptchaServiceImpl implements CaptchaService {
return validate(key, code, delete); return validate(key, code, delete);
} }
/**
* 生成指定数量的随机数验证码
*
* @param length 数量
* @return 随机码
*/
private String generateValidateCode(Integer length) {
String chars = "0123456789"; // 字符范围可以自定义:数字
Random random = new Random();
StringBuilder code = new StringBuilder();
for (int i = 0; i < length; i++) {
code.append(chars.charAt(random.nextInt(chars.length())));
}
return code.toString();
}
private void setCache(String key, String value) { private void setCache(String key, String value) {
if (open) { if (open) {
key = RedisKeys.getCaptchaKey(key); key = RedisKeys.getCaptchaKey(key);
@ -164,4 +180,4 @@ public class CaptchaServiceImpl implements CaptchaService {
} }
return captcha; return captcha;
} }
} }

View file

@ -2,9 +2,7 @@ package xiaozhi.modules.security.service.impl;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@ -83,36 +81,6 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, Sy
return new Result<TokenDTO>().ok(tokenDTO); return new Result<TokenDTO>().ok(tokenDTO);
} }
@Override
@Transactional
public Result<TokenDTO> refreshToken(String oldToken) {
if (StringUtils.isBlank(oldToken)) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
SysUserTokenEntity tokenEntity = baseDao.getByToken(oldToken);
if (tokenEntity == null) {
throw new RenException(ErrorCode.TOKEN_INVALID);
}
if (tokenEntity.getExpireDate().before(new Date())) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
// CAS 更新:并发场景下只有一个请求能匹配到该 oldToken,另一个返 0 行
String newToken = TokenGenerator.generateValue();
Date now = new Date();
Date expireTime = new Date(now.getTime() + EXPIRE * 1000L);
int affected = baseDao.refreshTokenCAS(tokenEntity.getUserId(), oldToken, newToken, expireTime, now);
if (affected == 0) {
throw new RenException(ErrorCode.TOKEN_INVALID);
}
TokenDTO dto = new TokenDTO();
dto.setToken(newToken);
dto.setExpire(EXPIRE);
dto.setClientHash(HttpContextUtils.getClientCode());
return new Result<TokenDTO>().ok(dto);
}
@Override @Override
public SysUserDTO getUserByToken(String token) { public SysUserDTO getUserByToken(String token) {
SysUserTokenEntity userToken = baseDao.getByToken(token); SysUserTokenEntity userToken = baseDao.getByToken(token);

View file

@ -31,7 +31,7 @@ public class SysUserDTO implements Serializable {
@NotNull(message = "{id.require}", groups = UpdateGroup.class) @NotNull(message = "{id.require}", groups = UpdateGroup.class)
private Long id; private Long id;
@Schema(description = "用户名", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "用户名", required = true)
@NotBlank(message = "{sysuser.username.require}", groups = DefaultGroup.class) @NotBlank(message = "{sysuser.username.require}", groups = DefaultGroup.class)
private String username; private String username;
@ -40,14 +40,14 @@ public class SysUserDTO implements Serializable {
@NotBlank(message = "{sysuser.password.require}", groups = AddGroup.class) @NotBlank(message = "{sysuser.password.require}", groups = AddGroup.class)
private String password; private String password;
@Schema(description = "姓名", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "姓名", required = true)
@NotBlank(message = "{sysuser.realname.require}", groups = DefaultGroup.class) @NotBlank(message = "{sysuser.realname.require}", groups = DefaultGroup.class)
private String realName; private String realName;
@Schema(description = "头像") @Schema(description = "头像")
private String headUrl; private String headUrl;
@Schema(description = "性别 0:男 1:女 2:保密", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "性别 0:男 1:女 2:保密", required = true)
@Range(min = 0, max = 2, message = "{sysuser.gender.range}", groups = DefaultGroup.class) @Range(min = 0, max = 2, message = "{sysuser.gender.range}", groups = DefaultGroup.class)
private Integer gender; private Integer gender;
@ -58,11 +58,11 @@ public class SysUserDTO implements Serializable {
@Schema(description = "手机号") @Schema(description = "手机号")
private String mobile; private String mobile;
@Schema(description = "部门ID", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "部门ID", required = true)
@NotNull(message = "{sysuser.deptId.require}", groups = DefaultGroup.class) @NotNull(message = "{sysuser.deptId.require}", groups = DefaultGroup.class)
private Long deptId; private Long deptId;
@Schema(description = "状态 0:停用 1:正常", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "状态 0:停用 1:正常", required = true)
@Range(min = 0, max = 1, message = "{sysuser.status.range}", groups = DefaultGroup.class) @Range(min = 0, max = 1, message = "{sysuser.status.range}", groups = DefaultGroup.class)
private Integer status; private Integer status;
@ -84,4 +84,4 @@ public class SysUserDTO implements Serializable {
@Schema(description = "部门名称") @Schema(description = "部门名称")
private String deptName; private String deptName;
} }

View file

@ -12,7 +12,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.hutool.core.collection.CollUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import xiaozhi.common.exception.RenException; import xiaozhi.common.exception.RenException;
import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.ErrorCode;
@ -21,7 +20,7 @@ import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.service.impl.BaseServiceImpl;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.ToolUtil;
import xiaozhi.modules.sys.dao.SysDictDataDao; import xiaozhi.modules.sys.dao.SysDictDataDao;
import xiaozhi.modules.sys.dao.SysUserDao; import xiaozhi.modules.sys.dao.SysUserDao;
import xiaozhi.modules.sys.dto.SysDictDataDTO; import xiaozhi.modules.sys.dto.SysDictDataDTO;
@ -104,13 +103,13 @@ public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysD
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void delete(Long[] ids) { public void delete(Long[] ids) {
List<Long> idList = Arrays.asList(ids); List<Long> idList = Arrays.asList(ids);
if (CollUtil.isNotEmpty(idList)) { if (ToolUtil.isNotEmpty(idList)) {
//批量删除redis字典 //批量删除redis字典
List<String> redisKeyList = new ArrayList<>(); List<String> redisKeyList = new ArrayList<>();
//批量获取字典类型 //批量获取字典类型
List<String> dictTypeList = Optional.ofNullable(baseDao.getDictTypesByIdList(idList)).orElseGet(ArrayList::new); List<String> dictTypeList = Optional.ofNullable(baseDao.getDictTypesByIdList(idList)).orElseGet(ArrayList::new);
dictTypeList.forEach(dictType -> redisKeyList.add(RedisKeys.getDictDataByTypeKey(dictType))); dictTypeList.forEach(dictType -> redisKeyList.add(RedisKeys.getDictDataByTypeKey(dictType)));
if (CollUtil.isNotEmpty(redisKeyList)) { if (ToolUtil.isNotEmpty(redisKeyList)) {
//清除缓存 //清除缓存
redisUtils.delete(redisKeyList); redisUtils.delete(redisKeyList);
} }
@ -139,7 +138,7 @@ public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysD
// 设置更新者和创建者名称 // 设置更新者和创建者名称
if (!userIds.isEmpty()) { if (!userIds.isEmpty()) {
List<SysUserEntity> sysUserEntities = sysUserDao.selectByIds(userIds); List<SysUserEntity> sysUserEntities = sysUserDao.selectBatchIds(userIds);
// 把List转成Map,Map<Long, String> // 把List转成Map,Map<Long, String>
Map<Long, String> userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId, Map<Long, String> userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId,
SysUserEntity::getUsername, (existing, replacement) -> existing)); SysUserEntity::getUsername, (existing, replacement) -> existing));
@ -171,7 +170,7 @@ public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysD
// 先从Redis获取缓存 // 先从Redis获取缓存
String key = RedisKeys.getDictDataByTypeKey(dictType); String key = RedisKeys.getDictDataByTypeKey(dictType);
List<SysDictDataItem> cachedData = JsonUtils.toList(redisUtils.get(key), SysDictDataItem.class); List<SysDictDataItem> cachedData = (List<SysDictDataItem>) redisUtils.get(key);
if (cachedData != null) { if (cachedData != null) {
return cachedData; return cachedData;
} }
@ -186,4 +185,4 @@ public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysD
return data; return data;
} }
} }

View file

@ -128,7 +128,7 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeDao, SysD
// 设置更新者和创建者名称 // 设置更新者和创建者名称
if (!userIds.isEmpty()) { if (!userIds.isEmpty()) {
List<SysUserEntity> sysUserEntities = sysUserDao.selectByIds(userIds); List<SysUserEntity> sysUserEntities = sysUserDao.selectBatchIds(userIds);
// 把List转成Map,Map<Long, String> // 把List转成Map,Map<Long, String>
Map<Long, String> userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId, Map<Long, String> userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId,
SysUserEntity::getUsername, (existing, replacement) -> existing)); SysUserEntity::getUsername, (existing, replacement) -> existing));
@ -151,4 +151,4 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeDao, SysD
throw new RenException(ErrorCode.DICT_TYPE_DUPLICATE); throw new RenException(ErrorCode.DICT_TYPE_DUPLICATE);
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show more