merge: integrate downstream westernization onto upstream/main

Merge 154 upstream commits with the 12-commit westernization stack,
preserving upstream features (theme refactor, knowledge base, device
calling, web search) while keeping downstream provider policy, English
defaults, and westernized surfaces.
This commit is contained in:
lapy 2026-06-13 11:22:28 +01:00
commit a5db8f8b11
930 changed files with 48186 additions and 43036 deletions

View file

@ -28,7 +28,7 @@ jobs:
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.TOKEN }} password: ${{ github.token }}
- name: Build and push server-base - name: Build and push server-base
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6

View file

@ -3,7 +3,7 @@ name: Docker Image CI
on: on:
push: push:
tags: tags:
- 'v*.*.*' # 只在以 v 开头的标签推送时触发,例如 v1.0.0 - 'v*.*.*' # Semver tags only, e.g. v1.0.0
workflow_dispatch: workflow_dispatch:
workflow_run: workflow_run:
workflows: ["Build Base Image"] workflows: ["Build Base Image"]
@ -11,25 +11,45 @@ on:
- completed - completed
jobs: jobs:
release: version:
name: Release Docker images name: Resolve version
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs:
version: ${{ steps.meta.outputs.version }}
is_version: ${{ steps.meta.outputs.is_version }}
steps:
- id: meta
run: |
if [[ "$GITHUB_REF" =~ ^refs/tags/v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
echo "is_version=true" >> "$GITHUB_OUTPUT"
else
echo "version=latest" >> "$GITHUB_OUTPUT"
echo "is_version=false" >> "$GITHUB_OUTPUT"
fi
release:
name: Build and push ${{ matrix.name }}
needs: version
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- name: xiaozhi-server
file: Dockerfile-server
tag_prefix: server
cache_scope: docker-server
- name: manager-web
file: Dockerfile-web
tag_prefix: web
cache_scope: docker-web
permissions: permissions:
packages: write packages: write
contents: write contents: write
id-token: write id-token: write
issues: write issues: write
steps: steps:
- name: Check Disk Space
run: |
df -h
docker system df
- name: Clean up Docker resources
run: |
docker system prune -af
docker builder prune -af
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -44,45 +64,19 @@ jobs:
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.TOKEN }} password: ${{ github.token }}
- name: Extract version from tag # linux/arm64 was slow under QEMU; add native ARM runners or restore: platforms: linux/amd64,linux/arm64
id: get_version - name: Build and push ${{ matrix.name }}
run: |
if [[ "$GITHUB_REF" =~ ^refs/tags/v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "VERSION=${BASH_REMATCH[1]}" >> $GITHUB_ENV
echo "IS_VERSION=true" >> $GITHUB_ENV
else
echo "VERSION=latest" >> $GITHUB_ENV
echo "IS_VERSION=false" >> $GITHUB_ENV
fi
# 构建 xiaozhi-server 镜像
- name: Build and push xiaozhi-server
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
context: . context: .
file: Dockerfile-server file: ${{ matrix.file }}
push: true push: true
tags: | tags: ${{ needs.version.outputs.is_version == 'true' && format('ghcr.io/{0}:{1}_{2},ghcr.io/{0}:{1}_latest', github.repository, matrix.tag_prefix, needs.version.outputs.version) || format('ghcr.io/{0}:{1}_latest', github.repository, matrix.tag_prefix) }}
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:server_{1},ghcr.io/{0}:server_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:server_latest', github.repository) }} platforms: linux/amd64
platforms: linux/amd64,linux/arm64 cache-from: type=gha,scope=${{ matrix.cache_scope }}
cache-from: type=gha cache-to: type=gha,mode=max,scope=${{ matrix.cache_scope }}
cache-to: type=gha,mode=max
build-args: |
BUILDKIT_PROGRESS=plain
# 构建 manager-api 镜像
- name: Build and push manager-web
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile-web
push: true
tags: |
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:web_{1},ghcr.io/{0}:web_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:web_latest', github.repository) }}
platforms: linux/amd64,linux/arm64
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: | build-args: |
BUILDKIT_PROGRESS=plain BUILDKIT_PROGRESS=plain
SERVER_BASE_IMAGE=ghcr.io/${{ github.repository }}:server-base

16
.gitignore vendored
View file

@ -3,9 +3,7 @@ __pycache__/
.idea/ .idea/
*.py[cod] *.py[cod]
*$py.class *$py.class
.vscode .venv-xiaozhi/
.claude
AGENTS.md
# C extensions # C extensions
*.so *.so
@ -149,7 +147,6 @@ tmp
.history .history
.DS_Store .DS_Store
main/xiaozhi-server/data main/xiaozhi-server/data
main/xiaozhi-server/.claude
main/manager-web/node_modules main/manager-web/node_modules
.config.yaml .config.yaml
@ -158,13 +155,9 @@ main/manager-web/node_modules
.env.development .env.development
# model files # model files
main/xiaozhi-server/models/SenseVoiceSmall/model.pt
main/xiaozhi-server/models/sherpa-onnx* main/xiaozhi-server/models/sherpa-onnx*
/main/xiaozhi-server/audio_ref/ /main/xiaozhi-server/audio_ref/
/audio_ref/ /audio_ref/
/asr-models/iic/SenseVoiceSmall/
/main/xiaozhi-server/asr-models/iic/SenseVoiceSmall/
/models/SenseVoiceSmall/model.pt
my_wakeup_words.mp3 my_wakeup_words.mp3
!main/xiaozhi-server/config/assets/bind_code.wav !main/xiaozhi-server/config/assets/bind_code.wav
!main/xiaozhi-server/config/assets/wakeup_words.wav !main/xiaozhi-server/config/assets/wakeup_words.wav
@ -187,8 +180,5 @@ uploadfile
!main/manager-mobile/**/env/ !main/manager-mobile/**/env/
!main/manager-mobile/**/.env* !main/manager-mobile/**/.env*
!main/manager-mobile/**/*.json !main/manager-mobile/**/*.json
!main/xiaozhi-server/**/*.json
!main/digital-human/**/*.json original-server
main/digital-human/wakeword_runtime/models
main/digital-human/wakeword_runtime/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2

View file

@ -1,7 +1,9 @@
# 生产镜像,仅包含应用代码 # Production image: application code on top of the published server-base image.
FROM ghcr.io/xinnan-tech/xiaozhi-esp32-server:server-base # CI should pass SERVER_BASE_IMAGE=ghcr.io/${{ github.repository }}:server-base.
# Local default pulls the lapy org base (build server-base first if missing).
ARG SERVER_BASE_IMAGE=ghcr.io/lapy/xiaozhi-esp32-server:server-base
FROM ${SERVER_BASE_IMAGE}
COPY main/xiaozhi-server . COPY main/xiaozhi-server .
# 启动应用
CMD ["python", "app.py"] CMD ["python", "app.py"]

View file

@ -1,32 +1,32 @@
# Dockerfile-server-base # Dockerfile-server-base
# 基础镜像,包含系统依赖和Python包 # Base image with system dependencies and Python packages (matches upstream layout;
# locale and comments are Western; pip install kept compatible with openai-whisper).
FROM python:3.10-slim FROM python:3.10-slim
# 安装系统依赖 # System packages: audio stack + locales for UTF-8 (en_US, not zh_CN)
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y --no-install-recommends libopus0 ffmpeg locales && \ apt-get install -y --no-install-recommends libopus0 ffmpeg locales && \
sed -i '/zh_CN.UTF-8/s/^# //g' /etc/locale.gen && \ sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \
locale-gen && \ locale-gen && \
apt-get clean && \ apt-get clean && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
# 配置pip使用国内镜像源(阿里云)并设置超时和重试 # Pip mirror and network resilience (same mirror family as upstream product)
RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \
pip config set global.trusted-host mirrors.aliyun.com && \ pip config set global.trusted-host mirrors.aliyun.com && \
pip config set global.timeout 120 && \ pip config set global.timeout 120 && \
pip config set install.retries 5 pip config set install.retries 5
# 设置环境变量以确保正确的字符编码 ENV LANG=en_US.UTF-8 \
ENV LANG=zh_CN.UTF-8 \ LC_ALL=en_US.UTF-8 \
LC_ALL=zh_CN.UTF-8 \ LANGUAGE=en_US:en \
LANGUAGE=zh_CN:zh \
PYTHONIOENCODING=utf-8 PYTHONIOENCODING=utf-8
WORKDIR /opt/xiaozhi-esp32-server WORKDIR /opt/xiaozhi-esp32-server
# 复制requirements.txt
COPY main/xiaozhi-server/requirements.txt . COPY main/xiaozhi-server/requirements.txt .
# 安装Python依赖 # openai-whisper uses legacy setuptools hooks; pin setuptools and skip build isolation
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ RUN pip install --no-cache-dir --upgrade pip "setuptools<81" wheel && \
pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 pip install --no-cache-dir --no-build-isolation -r requirements.txt --default-timeout=120 --retries 5

View file

@ -1,4 +1,4 @@
# 第一阶段:构建Vue前端 # Stage 1: Build Vue frontend
FROM node:18 AS web-builder FROM node:18 AS web-builder
WORKDIR /app WORKDIR /app
COPY main/manager-web/package*.json ./ COPY main/manager-web/package*.json ./
@ -6,17 +6,16 @@ RUN npm install
COPY main/manager-web . COPY main/manager-web .
RUN npm run build RUN npm run build
# 第二阶段:构建Java后端 # Stage 2: Build Java backend
FROM maven:3.9.4-eclipse-temurin-21 AS api-builder FROM maven:3.9.4-eclipse-temurin-21 AS api-builder
WORKDIR /app WORKDIR /app
COPY main/manager-api/pom.xml . COPY main/manager-api/pom.xml .
COPY main/manager-api/src ./src COPY main/manager-api/src ./src
RUN mvn clean package -Dmaven.test.skip=true RUN mvn clean package -Dmaven.test.skip=true
# 第三阶段:构建最终镜像 # Stage 3: Final runtime image
FROM bellsoft/liberica-runtime-container:jre-21-glibc FROM bellsoft/liberica-runtime-container:jre-21-glibc
# 安装Nginx和字体库
RUN apk update && \ RUN apk update && \
apk add --no-cache --no-scripts \ apk add --no-cache --no-scripts \
nginx \ nginx \
@ -26,25 +25,18 @@ RUN apk update && \
&& rm -rf /var/cache/apk/* \ && rm -rf /var/cache/apk/* \
&& mkdir -p /run/nginx /var/log/nginx /var/tmp/nginx /etc/nginx/conf.d && mkdir -p /run/nginx /var/log/nginx /var/tmp/nginx /etc/nginx/conf.d
# 复制项目自带的中文字体
COPY main/manager-web/public/generator/static/fonts/*.ttf /usr/share/fonts/ COPY main/manager-web/public/generator/static/fonts/*.ttf /usr/share/fonts/
# 更新字体缓存
RUN fc-cache -f -v RUN fc-cache -f -v
# 配置Nginx
COPY docs/docker/nginx.conf /etc/nginx/nginx.conf COPY docs/docker/nginx.conf /etc/nginx/nginx.conf
# 复制前端构建产物
COPY --from=web-builder /app/dist /usr/share/nginx/html COPY --from=web-builder /app/dist /usr/share/nginx/html
# 复制Java后端JAR包
COPY --from=api-builder /app/target/xiaozhi-esp32-api.jar /app/xiaozhi-esp32-api.jar COPY --from=api-builder /app/target/xiaozhi-esp32-api.jar /app/xiaozhi-esp32-api.jar
# 暴露端口
EXPOSE 8002 EXPOSE 8002
# 启动脚本
COPY docs/docker/start.sh /start.sh COPY docs/docker/start.sh /start.sh
RUN chmod +x /start.sh RUN chmod +x /start.sh
CMD ["/start.sh"] CMD ["/start.sh"]

View file

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2025 xinnan-tech Copyright (c) 2025 lapy
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

409
README.md
View file

@ -1,363 +1,262 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) <h1 align="center">Xiaozhi Backend Service xiaozhi-esp32-server</h1>
<h1 align="center">小智后端服务xiaozhi-esp32-server</h1>
<p align="center"> <p align="center">
本项目基于人机共生智能理论和技术研发智能终端软硬件体系<br/>为开源智能硬件项目 This project is based on human-machine symbiotic intelligence theory and technology to develop intelligent terminal hardware and software systems<br/>providing backend services for the open-source intelligent hardware project
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a>提供后端服务<br/> <a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
根据<a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">小智通信协议</a>使用Python、Java、Vue实现<br/> Implemented using Python, Java, and Vue according to the <a href="https://github.com/lapy/xiaozhi-esp32-server/wiki">Xiaozhi Communication Protocol</a><br/>
支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别、知识库 Supports MCP endpoints and voiceprint recognition
</p> </p>
<p align="center"> <p align="center">
<a href="./docs/FAQ.md">常见问题</a> <a href="./docs/support/faq.md">FAQ</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">反馈问题</a> · <a href="https://github.com/lapy/xiaozhi-esp32-server/issues">Report Issues</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">部署文档</a> · <a href="https://github.com/lapy/xiaozhi-esp32-server/releases">Release Notes</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">更新日志</a>
</p> </p>
<p align="center"> <p align="center">
<a href="./README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DBEDFA"></a> <a href="https://github.com/lapy/xiaozhi-esp32-server/releases">
<a href="./docs/readme/README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a> <img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/lapy/xiaozhi-esp32-server?logo=docker" />
<a href="./docs/readme/README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./docs/readme/README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./docs/readme/README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="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>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE"> <a href="https://github.com/lapy/xiaozhi-esp32-server/graphs/contributors">
<img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/lapy/xiaozhi-esp32-server?logo=github" />
</a>
<a href="https://github.com/lapy/xiaozhi-esp32-server/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/lapy/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/lapy/xiaozhi-esp32-server/pulls">
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/lapy/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/lapy/xiaozhi-esp32-server/blob/main/LICENSE">
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" /> <img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
</a> </a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server"> <a href="https://github.com/lapy/xiaozhi-esp32-server">
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" /> <img alt="stars" src="https://img.shields.io/github/stars/lapy/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
</a> </a>
</p> </p>
<p align="center">
Spearheaded by Professor Siyuan Liu's Team (South China University of Technology)
</br>
刘思源教授团队主导研发(华南理工大学)
</br>
<img src="./docs/images/hnlg.jpg" alt="华南理工大学" width="50%">
</p>
--- ---
## 适用人群 👥 ## ⚠️ Important Disclaimer
本项目需要配合 ESP32 硬件设备使用。如果您已经购买了 ESP32 相关硬件,且成功对接过虾哥部署的后端服务,并希望独立搭建自己的 **This is a complete port and refactoring of the original [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server) project, specifically adapted for Western users.**
`xiaozhi-esp32` 后端服务,那么本项目非常适合您。
想看使用效果?请猛戳视频 🎥 ### Credits & Acknowledgments
- **Original Project**: All credits for the original excellent work go to the [xinnan-tech](https://github.com/xinnan-tech) team
- **Original Repository**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server)
- **This Port**: Adapted by [lapy](https://github.com/lapy) for Western users
<table> ### What Changed
<tr> This port removes Chinese AI providers and infrastructure dependencies, replacing them with Western alternatives:
<td> - **STT**: WhisperASR (offline, multilingual) instead of Chinese ASR services
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank"> - **LLM**: LMStudioLLM (local, open-source) instead of Chinese LLM providers
<picture> - **TTS**: EdgeTTS (Microsoft, free) - kept as default
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture> - **Infrastructure**: Replaced Chinese mirrors with international alternatives
</a> - **Documentation**: Translated and adapted for Western users
</td>
<td> The core architecture, ESP32 communication protocol, and fundamental functionality remain unchanged from the original excellent work.
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
</a>
</td>
</tr>
</table>
--- ---
## 警告 ⚠️ ## Target Users 👥
1、本项目为开源软件,本软件与对接的任何第三方API服务商(包括但不限于语音识别、大模型、语音合成等平台)均不存在商业合作关系,不为其服务质量及资金安全提供任何形式的担保。 This project requires ESP32 hardware devices to work. If you have purchased ESP32-related hardware, successfully connected to Brother Xia's deployed backend service, and want to build your own `xiaozhi-esp32` backend service independently, then this project is perfect for you.
建议使用者优先选择持有相关业务牌照的服务商,并仔细阅读其服务协议及隐私政策。本软件不托管任何账户密钥、不参与资金流转、不承担充值资金损失风险。
2、本项目功能未完善,且未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必做好必要的防护。
--- ---
## 部署文档 ## Warnings ⚠️
![Banners](docs/images/banner2.png) 1. This project is open-source software. This software has no commercial partnership with any third-party API service providers (including but not limited to speech recognition, large models, speech synthesis, and other platforms) that it interfaces with, and does not provide any form of guarantee for their service quality or financial security. It is recommended that users prioritize service providers with relevant business licenses and carefully read their service agreements and privacy policies. This software does not host any account keys, does not participate in fund flows, and does not bear the risk of recharge fund losses.
本项目提供两种部署方式,请根据您的具体需求选择: 2. The functionality of this project is not complete and has not passed network security assessment. Please do not use it in production environments. If you deploy this project for learning purposes in a public network environment, please ensure necessary protection measures are in place.
#### 🚀 部署方式选择 ---
| 部署方式 | 特点 | 适用场景 | 部署文档 | 配置要求 | 视频教程 |
## Deployment Documentation
This project provides two deployment methods. Please choose based on your specific needs:
#### 🚀 Deployment Method Selection
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|---------|------|---------|---------|---------|---------| |---------|------|---------|---------|---------|---------|
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①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 | - | | **Simplified Installation** | Intelligent dialogue, IOT, MCP, visual perception | Low-configuration environments, data stored in config files, no database required | [①Docker Version](./docs/installation/docker.md) / [②Source Code Deployment](./docs/installation/local.md)| 2 cores 2GB if all APIs | - |
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①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) | | **Full Module Installation** | Intelligent dialogue, IOT, MCP endpoints, voiceprint recognition, visual perception, OTA, intelligent control console | Complete functionality experience, data stored in database |[①Docker Version](./docs/installation/docker.md) / [②Source Code Deployment](./docs/installation/local.md) | 2 cores 4GB if all APIs| - |
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据, > 💡 Note: Below is a test platform deployed with the latest code. You can burn and test if needed. Concurrent users: 6, data will be cleared daily.
``` ```
智控台地址: https://2662r3426b.vicp.fun Intelligent Control Console Address: https://2662r3426b.vicp.fun
智控台(h5版): https://2662r3426b.vicp.fun/h5/index.html Intelligent Control Console Address (H5): https://2662r3426b.vicp.fun/h5/index.html
服务测试工具: https://2662r3426b.vicp.fun/test/ Service Test Tool: https://2662r3426b.vicp.fun/test/
OTA接口地址: https://2662r3426b.vicp.fun/xiaozhi/ota/ OTA Interface Address: https://2662r3426b.vicp.fun/xiaozhi/ota/
Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/ Websocket Interface Address: wss://2662r3426b.vicp.fun/xiaozhi/v1/
``` ```
#### 🚩 配置说明和推荐 #### 🚩 Configuration Description and Recommendations
> [!Note] > [!Note]
> 本项目提供两种配置方案: > This project provides two configuration schemes:
> >
> 1. `入门全免费`配置:适合个人家庭使用,所有组件均采用免费方案,无需额外付费。 > 1. `Entry Level Free Settings`: Suitable for personal and home use, all components use free solutions, no additional payment required.
> >
> 2. `流式配置`:适合演示、培训、超过2个并发等场景,采用流式处理技术,响应速度更快,体验更佳。 > 2. `Streaming Configuration`: Suitable for demonstrations, training, scenarios with more than 2 concurrent users, etc. Uses streaming processing technology for faster response speed and better experience.
> >
> 自`0.5.2`版本起,项目支持流式配置,相比早期版本,响应速度提升约`2.5秒`,显著改善用户体验。 > Starting from version `0.5.2`, the project supports streaming configuration. Compared to earlier versions, response speed is improved by approximately `2.5 seconds`, significantly improving user experience.
| 模块名称 | 入门全免费设置 | 流式配置 | | Module Name | Entry Level Free Settings | Streaming Configuration |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| ASR(语音识别) | FunASR(本地) | 👍XunfeiStreamASR(讯飞流式) | | ASR(Speech Recognition) | ✅WhisperASR(Local, Offline) | 👍WhisperASR(Local, Offline) |
| LLM(大模型) | glm-4-flash(智谱) | 👍qwen-flash(阿里百炼) | | LLM(Large Model) | ✅LMStudioLLM(Local, Open Source) | 👍LMStudioLLM(Local, Open Source) |
| VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) | | VLLM(Vision Large Model) | OpenAILLMVLLM(OpenAI gpt-4o) | 👍OpenAILLMVLLM(OpenAI gpt-4o) |
| TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) | | TTS(Speech Synthesis) | ✅EdgeTTS(Microsoft Edge TTS) | 👍EdgeTTS(Microsoft Edge TTS) |
| Intent(意图识别) | function_call(函数调用) | function_call(函数调用) | | Intent(Intent Recognition) | function_call(Function calling) | function_call(Function calling) |
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) | | Memory(Memory function) | mem_local_short(Local short-term memory) | mem_local_short(Local short-term memory) |
如果您关心各组件的耗时,请查阅[小智各组件性能测试报告](https://github.com/xinnan-tech/xiaozhi-performance-research),可按报告中的测试方法在您的环境中实际测试。 #### 🔧 Testing Tools
This project provides the following testing tools to help you verify the system and choose suitable models:
#### 🔧 测试工具 | Tool Name | Location | Usage Method | Function Description |
本项目提供以下测试工具,帮助您验证系统和选择合适的模型:
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|:---:|:---|:---:|:---:| |:---:|:---|:---:|:---:|
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 执行 `python start.py` 后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 | | Audio Interaction Test Tool | main/xiaozhi-server/test/test_page.html | Open directly with Google Chrome | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 | | Model Response Test Tool 1 | main/xiaozhi-server/performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), TTS(speech synthesis) |
| Model Response Test Tool 2 | main/xiaozhi-server/performance_tester_vllm.py | Execute `python performance_tester_vllm.py` | Tests VLLM(vision model) response speed |
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。 > 💡 Note: When testing model speed, only models with configured keys will be tested.
--- ---
## 功能清单 ✨ ## Feature List ✨
### 已实现 ✅ ### Implemented ✅
![请参考-全模块安装架构图](docs/images/deploy2.png) | Feature Module | Description |
| 功能模块 | 描述 |
|:---:|:---| |:---:|:---|
| 核心架构 | 基于[MQTT+UDP网关](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md)、WebSocket、HTTP服务器,提供完整的控制台管理和认证系统 | | Core Architecture | Based on [MQTT+UDP gateway](https://github.com/lapy/xiaozhi-esp32-server/blob/main/docs/guides/mqtt.md), WebSocket and HTTP servers, provides complete console management and authentication system |
| 语音交互 | 支持流式ASR(语音识别)、流式TTS(语音合成)、VAD(语音活动检测),支持多语言识别和语音处理 | | Voice Interaction | Supports streaming ASR(speech recognition), streaming TTS(speech synthesis), VAD(voice activity detection), supports multi-language recognition and voice processing |
| 声纹识别 | 支持多用户声纹注册、管理和识别,与ASR并行处理,实时识别说话人身份并传递给LLM进行个性化回应 | | 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 |
| 智能对话 | 支持多种LLM(大语言模型),实现智能对话 | | Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
| 视觉感知 | 支持多种VLLM(视觉大模型),实现多模态交互 | | Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 | | Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 | | Memory System | Supports local short-term memory, mem0ai interface memory, with memory summarization functionality |
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 | | Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 | | Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 | | Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports English display |
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 | | 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 |
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 | | Plugin System | Supports functional plugin extensions, custom plugin development, and plugin hot-loading |
| 插件系统 | 支持功能插件扩展、自定义插件开发和插件热加载 |
### 正在开发 🚧 ### Under Development 🚧
想了解具体开发计划进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3)。常见问题及相关教程,可参考[这个链接](./docs/FAQ.md) If you are a software developer, here is our [Contributing Guide](docs/support/contributing.md). Welcome to join!
如果你是一名软件开发者,这里有一份[《致开发者的公开信》](docs/contributor_open_letter.md),欢迎加入!
--- ---
## 产品生态 👬 ## Product Ecosystem 👬
小智是一个生态,当你使用这个产品时,也可以看看其他在这个生态圈的[优秀项目](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) Xiaozhi is an ecosystem. When using this product, you can also check out other [excellent projects](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#related-open-source-projects) in this ecosystem
| Project Name | Project Address | Project Description |
|:---------------------|:--------|:--------|
| Xiaozhi Android Client | [xiaozhi-android-client](https://github.com/TOM88812/xiaozhi-android-client) | An Android and iOS voice dialogue application based on xiaozhi-server, supporting real-time voice interaction and text dialogue.<br/>Currently a Flutter version, connecting iOS and Android platforms. |
| Xiaozhi Desktop Client | [py-xiaozhi](https://github.com/Huang-junsen/py-xiaozhi) | This project provides a Python-based AI client for beginners, allowing users to experience Xiaozhi AI functionality through code even without physical hardware conditions. |
| Xiaozhi Java Server | [xiaozhi-esp32-server-java](https://github.com/joey-zhou/xiaozhi-esp32-server-java) | Xiaozhi open-source backend service Java version is a Java-based open-source project.<br/>It includes frontend and backend services, aiming to provide users with a complete backend service solution. |
--- ---
## 本项目支持的平台/组件列表 📋 ## Supported Platforms/Components List 📋
### LLM 语言模型 ### LLM Language Models
| 使用方式 | 支持平台 | 免费平台 | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini | | Local deployment | **LMStudioLLM**, OllamaLLM, XinferenceLLM | **LMStudioLLM**, OllamaLLM, XinferenceLLM |
| ollama 接口调用 | Ollama | - | | OpenAI interface calls | OpenAILLM | - |
| dify 接口调用 | Dify | - | | Google interface calls | GeminiLLM | GeminiLLM |
| fastgpt 接口调用 | Fastgpt | - | | Platform integrations | DifyLLM, HomeAssistant | - |
| coze 接口调用 | Coze | - |
| xinference 接口调用 | Xinference | - |
| homeassistant 接口调用 | HomeAssistant | - |
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。 In fact, any LLM that supports OpenAI interface calls can be integrated and used, including Xinference and HomeAssistant interfaces.
--- ---
### VLLM 视觉模型 ### VLLM Vision Models
| 使用方式 | 支持平台 | 免费平台 | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| openai 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM | | OpenAI interface calls | OpenAILLMVLLM | - |
| Google interface calls | GeminiVLLM | GeminiVLLM |
实际上,任何支持 openai 接口调用的 VLLM 均可接入使用。 In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
--- ---
### TTS 语音合成 ### TTS Speech Synthesis
| 使用方式 | 支持平台 | 免费平台 | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) | | Interface calls | OpenAITTS, EdgeTTS | EdgeTTS |
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、Index-TTS、PaddleSpeech | Index-TTS、PaddleSpeech、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 | | Local services | CustomTTS | CustomTTS |
--- ---
### VAD 语音活动检测 ### VAD Voice Activity Detection
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | | Type | Platform Name | Usage Method | Pricing Model | Notes |
|:---:|:---------:|:----:|:----:|:--:| |:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | 本地使用 | 免费 | | | VAD | SileroVAD | Local use | Free | |
--- ---
### ASR 语音识别 ### ASR Speech Recognition
| 使用方式 | 支持平台 | 免费平台 | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR | | Local deployment | SherpaASR, VoskASR, **WhisperASR** | SherpaASR, VoskASR, **WhisperASR** |
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer | | OpenAI interface calls | OpenaiASR, GroqASR | OpenaiASR, GroqASR |
| Google interface calls | GeminiASR | GeminiASR |
--- ---
### Voiceprint 声纹识别 ### Voiceprint Recognition
| 使用方式 | 支持平台 | 免费平台 | | Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:| |:---:|:---:|:---:|
| 本地使用 | 3D-Speaker | 3D-Speaker | | Local use | 3D-Speaker | 3D-Speaker |
--- ---
### Memory 记忆存储 ### Memory Storage
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | | Type | Platform Name | Usage Method | Pricing Model | Notes |
|:------:|:---------------:|:----:|:---------:|:--:| |:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | 接口调用 | 1000次/月额度 | | | Memory | **mem_local_short** | Local summarization | Free | Local short-term memory with LLM summarization |
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 | | Memory | mem0ai | Interface calls | 1000 times/month quota | Cloud-based memory service |
| Memory | mem_local_short | 本地总结 | 免费 | | | Memory | nomem | No memory | Free | Disables memory functionality |
| Memory | nomem | 无记忆模式 | 免费 | |
--- ---
### Intent 意图识别 ### Intent Recognition
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | | Type | Platform Name | Usage Method | Pricing Model | Notes |
|:------:|:-------------:|:----:|:-------:|:---------------------:| |:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | 接口调用 | 根据LLM收费 | 通过大模型识别意图,通用性强 | | Intent | **function_call** | Interface calls | Based on LLM pricing | Function calling through LLM, fast speed, good effect |
| Intent | function_call | 接口调用 | 根据LLM收费 | 通过大模型函数调用完成意图,速度快,效果好 | | Intent | intent_llm | Interface calls | Based on LLM pricing | Intent recognition through LLM, strong generalization |
| Intent | nointent | 无意图模式 | 免费 | 不进行意图识别,直接返回对话结果 | | Intent | nointent | No intent | Free | Disables intent recognition |
--- ---
### Rag 检索增强生成 ## Acknowledgments 🙏
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | | Logo | Project/Company | Description |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | 接口调用 | 根据切片、分词消耗的token收费 | 借助RagFlow的检索增强生成功能,提供更准确的对话回复 |
---
## 鸣谢 🙏
| Logo | 项目/公司 | 说明 |
|:---:|:---:|:---| |:---:|:---:|:---|
| <img src="./docs/images/logo_bailing.png" width="160"> | [百聆语音对话机器人](https://github.com/wwbin2017/bailing) | 本项目受[百聆语音对话机器人](https://github.com/wwbin2017/bailing)启发,并在其基础上实现 | | 🎤 | [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) | This project is inspired by [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented on its basis |
| <img src="./docs/images/logo_tenclass.png" width="160"> | [十方融海](https://www.tenclass.com/) | 感谢[十方融海](https://www.tenclass.com/)为小智生态制定了标准的通讯协议、多设备兼容性方案及高并发场景实践示范;为本项目提供了全链路技术文档支持 | | 🏫 | [Tenclass](https://www.tenclass.com/) | Thanks to [Tenclass](https://www.tenclass.com/) for formulating standard communication protocols, multi-device compatibility solutions, and high-concurrency scenario practice demonstrations for the Xiaozhi ecosystem; providing full-link technical documentation support for this project |
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [玄凤科技](https://github.com/Eric0308) | 感谢[玄凤科技](https://github.com/Eric0308)贡献函数调用框架、MCP通信协议及插件化调用机制的实现代码,通过标准化的指令调度体系与动态扩展能力,显著提升了前端设备(IoT)的交互效率和功能延展性 | | 🌪️ | [Xuanfeng Technology](https://github.com/Eric0308) | Thanks to [Xuanfeng Technology](https://github.com/Eric0308) for contributing function calling framework, MCP communication protocol, and plugin-based calling mechanism implementation code. Through standardized instruction scheduling system and dynamic expansion capabilities, it significantly improves the interaction efficiency and functional extensibility of frontend devices (IoT) |
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | 感谢[huangjunsen](https://github.com/huangjunsen0406) 贡献`智控台移动端`模块,实现了跨平台移动设备的高效控制与实时交互,大幅提升了系统在移动场景下的操作便捷性和管理效率 | | 📱 | [huangjunsen](https://github.com/huangjunsen0406) | Thanks to [huangjunsen](https://github.com/huangjunsen0406) for contributing the `Smart Control Console Mobile` module, which enables efficient control and real-time interaction across mobile devices, significantly enhancing the system's operational convenience and management efficiency in mobile scenarios. |
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [汇远设计](http://ui.kwd988.net/) | 感谢[汇远设计](http://ui.kwd988.net/)为本项目提供专业视觉解决方案,用其服务超千家企业的设计实战经验,赋能本项目产品用户体验 | | 🎨 | [Huiyuan Design](http://ui.kwd988.net/) | Thanks to [Huiyuan Design](http://ui.kwd988.net/) for providing professional visual solutions for this project, using their design practical experience serving over a thousand enterprises to empower this project's product user experience |
| <img src="./docs/images/logo_qinren.png" width="160"> | [西安勤人信息科技](https://www.029app.com/) | 感谢[西安勤人信息科技](https://www.029app.com/)深化本项目视觉体系,确保整体设计风格在多场景应用中的一致性和扩展性 | | 🏢 | [Xi'an Qinren Information Technology](https://www.029app.com/) | Thanks to [Xi'an Qinren Information Technology](https://www.029app.com/) for deepening this project's visual system, ensuring consistency and extensibility of overall design style in multi-scenario applications |
| <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)贡献者,你们的付出让项目更加健壮和强大。 | | 👥 | [Code Contributors](https://github.com/lapy/xiaozhi-esp32-server/graphs/contributors) | Thanks to [all code contributors](https://github.com/lapy/xiaozhi-esp32-server/graphs/contributors), your efforts have made the project more robust and powerful. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date"> <a href="https://star-history.com/#lapy/xiaozhi-esp32-server&Date">
<picture> <picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" /> <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=lapy/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" /> <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=lapy/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" /> <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=lapy/xiaozhi-esp32-server&type=Date" />
</picture> </picture>
</a> </a>

View file

@ -1,43 +1,42 @@
#!/bin/sh #!/bin/sh
# 脚本作者@VanillaNahida # Script author @VanillaNahida
# 本文件是用于一键自动下载本项目所需文件,自动创建好目录 # This file is used for one-click automatic download of required files for this project and automatic directory creation
# 暂且只支持X86版本的Ubuntu系统,其他系统未测试 # Currently only supports X86 version of Ubuntu system, other systems are not tested
# 定义中断处理函数 # Define interrupt handler function
handle_interrupt() { handle_interrupt() {
echo "" echo ""
echo "安装已被用户中断(Ctrl+C或Esc)" echo "Installation interrupted by user (Ctrl+C or Esc)"
echo "如需重新安装,请再次运行脚本" echo "To reinstall, please run the script again"
exit 1 exit 1
} }
# 设置信号捕获,处理Ctrl+C # Set signal capture to handle Ctrl+C
trap handle_interrupt SIGINT trap handle_interrupt SIGINT
# 处理Esc键 # Handle Esc key
# 保存终端设置 # Save terminal settings
old_stty_settings=$(stty -g) old_stty_settings=$(stty -g)
# 设置终端立即响应,不回显 # Set terminal to respond immediately, no echo
stty -icanon -echo min 1 time 0 stty -icanon -echo min 1 time 0
# 后台进程检测Esc键 # Background process to detect Esc key
(while true; do (while true; do
read -r key read -r key
if [[ $key == $'\e' ]]; then if [[ $key == $'\e' ]]; then
# 检测到Esc键,触发中断处理 # Detected Esc key, trigger interrupt handler
kill -SIGINT $$ kill -SIGINT $$
break break
fi fi
done) & done) &
# 脚本结束时恢复终端设置 # Restore terminal settings when script ends
trap 'stty "$old_stty_settings"' EXIT trap 'stty "$old_stty_settings"' EXIT
# Print colored ASCII art
# 打印彩色字符画 echo -e "\e[1;32m" # Set color to bright green
echo -e "\e[1;32m" # 设置颜色为亮绿色
cat << "EOF" cat << "EOF"
脚本作者:@Bilibili 香草味的纳西妲喵 Script Author: @Bilibili Vanilla Nahida Meow
__ __ _ _ _ _ _ _ _ _ __ __ _ _ _ _ _ _ _ _
\ \ / / (_)| || | | \ | | | | (_) | | \ \ / / (_)| || | | \ | | | | (_) | |
\ \ / /__ _ _ __ _ | || | __ _ | \| | __ _ | |__ _ __| | __ _ \ \ / /__ _ _ __ _ | || | __ _ | \| | __ _ | |__ _ __| | __ _
@ -45,16 +44,16 @@ cat << "EOF"
\ /| (_| || | | || || || || (_| | | |\ || (_| || | | || || (_| || (_| | \ /| (_| || | | || || || || (_| | | |\ || (_| || | | || || (_| || (_| |
\/ \__,_||_| |_||_||_||_| \__,_| |_| \_| \__,_||_| |_||_| \__,_| \__,_| \/ \__,_||_| |_||_||_||_| \__,_| |_| \_| \__,_||_| |_||_| \__,_| \__,_|
EOF EOF
echo -e "\e[0m" # 重置颜色 echo -e "\e[0m" # Reset color
echo -e "\e[1;36m 小智服务端全量部署一键安装脚本 Ver 0.2 2025年8月20日更新 \e[0m\n" echo -e "\e[1;36m Xiaozhi Server Full Deployment One-Click Installation Script Ver 0.2 Updated August 20, 2025 \e[0m\n"
sleep 1 sleep 1
# 检查并安装whiptail # Check and install whiptail
check_whiptail() { check_whiptail() {
if ! command -v whiptail &> /dev/null; then if ! command -v whiptail &> /dev/null; then
echo "正在安装whiptail..." echo "Installing whiptail..."
apt update apt update
apt install -y whiptail apt install -y whiptail
fi fi
@ -62,11 +61,11 @@ check_whiptail() {
check_whiptail check_whiptail
# 创建确认对话框 # Create confirmation dialog
whiptail --title "安装确认" --yesno "即将安装小智服务端,是否继续?" \ whiptail --title "Installation Confirmation" --yesno "About to install Xiaozhi Server, continue?" \
--yes-button "继续" --no-button "退出" 10 50 --yes-button "Continue" --no-button "Exit" 10 50
# 根据用户选择执行操作 # Execute operation based on user choice
case $? in case $? in
0) 0)
;; ;;
@ -75,72 +74,72 @@ case $? in
;; ;;
esac esac
# 检查root权限 # Check root permissions
if [ $EUID -ne 0 ]; then if [ $EUID -ne 0 ]; then
whiptail --title "权限错误" --msgbox "请使用root权限运行本脚本" 10 50 whiptail --title "Permission Error" --msgbox "Please run this script with root privileges" 10 50
exit 1 exit 1
fi fi
# 检查系统版本 # Check system version
if [ -f /etc/os-release ]; then if [ -f /etc/os-release ]; then
. /etc/os-release . /etc/os-release
if [ "$ID" != "debian" ] && [ "$ID" != "ubuntu" ]; then if [ "$ID" != "debian" ] && [ "$ID" != "ubuntu" ]; then
whiptail --title "系统错误" --msgbox "该脚本只支持Debian/Ubuntu系统执行" 10 60 whiptail --title "System Error" --msgbox "This script only supports Debian/Ubuntu systems" 10 60
exit 1 exit 1
fi fi
else else
whiptail --title "系统错误" --msgbox "无法确定系统版本,该脚本只支持Debian/Ubuntu系统执行" 10 60 whiptail --title "System Error" --msgbox "Cannot determine system version, this script only supports Debian/Ubuntu systems" 10 60
exit 1 exit 1
fi fi
# 下载配置文件函数 # Download configuration file function
check_and_download() { check_and_download() {
local filepath=$1 local filepath=$1
local url=$2 local url=$2
if [ ! -f "$filepath" ]; then if [ ! -f "$filepath" ]; then
if ! curl -fL --progress-bar "$url" -o "$filepath"; then if ! curl -fL --progress-bar "$url" -o "$filepath"; then
whiptail --title "错误" --msgbox "${filepath}文件下载失败" 10 50 whiptail --title "Error" --msgbox "${filepath} file download failed" 10 50
exit 1 exit 1
fi fi
else else
echo "${filepath}文件已存在,跳过下载" echo "${filepath} file already exists, skipping download"
fi fi
} }
# 检查是否已安装 # Check if already installed
check_installed() { check_installed() {
# 检查目录是否存在且非空 # Check if directory exists and is not empty
if [ -d "/opt/xiaozhi-server/" ] && [ "$(ls -A /opt/xiaozhi-server/)" ]; then if [ -d "/opt/xiaozhi-server/" ] && [ "$(ls -A /opt/xiaozhi-server/)" ]; then
DIR_CHECK=1 DIR_CHECK=1
else else
DIR_CHECK=0 DIR_CHECK=0
fi fi
# 检查容器是否存在 # Check if container exists
if docker inspect xiaozhi-esp32-server > /dev/null 2>&1; then if docker inspect xiaozhi-esp32-server > /dev/null 2>&1; then
CONTAINER_CHECK=1 CONTAINER_CHECK=1
else else
CONTAINER_CHECK=0 CONTAINER_CHECK=0
fi fi
# 两次检查都通过 # Both checks passed
if [ $DIR_CHECK -eq 1 ] && [ $CONTAINER_CHECK -eq 1 ]; then if [ $DIR_CHECK -eq 1 ] && [ $CONTAINER_CHECK -eq 1 ]; then
return 0 # 已安装 return 0 # Already installed
else else
return 1 # 未安装 return 1 # Not installed
fi fi
} }
# 更新相关 # Update related
if check_installed; then if check_installed; then
if whiptail --title "已安装检测" --yesno "检测到小智服务端已安装,是否进行升级?" 10 60; then if whiptail --title "Installation Detected" --yesno "Xiaozhi server installation detected, do you want to upgrade?" 10 60; then
# 用户选择升级,执行清理操作 # User chose to upgrade, execute cleanup operations
echo "开始升级操作..." echo "Starting upgrade operation..."
# 停止并移除所有docker-compose服务 # Stop and remove all docker-compose services
docker compose -f /opt/xiaozhi-server/docker-compose_all.yml down docker compose -f /opt/xiaozhi-server/docker-compose_all.yml down
# 停止并删除特定容器(考虑容器可能不存在的情况) # Stop and delete specific containers (considering containers may not exist)
containers=( containers=(
"xiaozhi-esp32-server" "xiaozhi-esp32-server"
"xiaozhi-esp32-server-web" "xiaozhi-esp32-server-web"
@ -152,135 +151,135 @@ if check_installed; then
if docker ps -a --format '{{.Names}}' | grep -q "^${container}$"; then if docker ps -a --format '{{.Names}}' | grep -q "^${container}$"; then
docker stop "$container" >/dev/null 2>&1 && \ docker stop "$container" >/dev/null 2>&1 && \
docker rm "$container" >/dev/null 2>&1 && \ docker rm "$container" >/dev/null 2>&1 && \
echo "成功移除容器: $container" echo "Successfully removed container: $container"
else else
echo "容器不存在,跳过: $container" echo "Container does not exist, skipping: $container"
fi fi
done done
# 删除特定镜像(考虑镜像可能不存在的情况) # Delete specific images (considering images may not exist)
images=( images=(
"ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest" "ghcr.io/lapy/xiaozhi-esp32-server:server_latest"
"ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest" "ghcr.io/lapy/xiaozhi-esp32-server:web_latest"
) )
for image in "${images[@]}"; do for image in "${images[@]}"; do
if docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^${image}$"; then if docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^${image}$"; then
docker rmi "$image" >/dev/null 2>&1 && \ docker rmi "$image" >/dev/null 2>&1 && \
echo "成功删除镜像: $image" echo "Successfully deleted image: $image"
else else
echo "镜像不存在,跳过: $image" echo "Image does not exist, skipping: $image"
fi fi
done done
echo "所有清理操作完成" echo "All cleanup operations completed"
# 备份原有配置文件 # Backup original configuration files
mkdir -p /opt/xiaozhi-server/backup/ mkdir -p /opt/xiaozhi-server/backup/
if [ -f /opt/xiaozhi-server/data/.config.yaml ]; then if [ -f /opt/xiaozhi-server/data/.config.yaml ]; then
cp /opt/xiaozhi-server/data/.config.yaml /opt/xiaozhi-server/backup/.config.yaml cp /opt/xiaozhi-server/data/.config.yaml /opt/xiaozhi-server/backup/.config.yaml
echo "已备份原有配置文件到 /opt/xiaozhi-server/backup/.config.yaml" echo "Original configuration file backed up to /opt/xiaozhi-server/backup/.config.yaml"
fi fi
# 下载最新版配置文件 # Download latest configuration files
check_and_download "/opt/xiaozhi-server/docker-compose_all.yml" "https://ghfast.top/https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/docker-compose_all.yml" check_and_download "/opt/xiaozhi-server/docker-compose_all.yml" "https://raw.githubusercontent.com/lapy/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose_all.yml"
check_and_download "/opt/xiaozhi-server/data/.config.yaml" "https://ghfast.top/https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/config_from_api.yaml" check_and_download "/opt/xiaozhi-server/data/.config.yaml" "https://raw.githubusercontent.com/lapy/xiaozhi-esp32-server/main/main/xiaozhi-server/config_from_api.yaml"
# 启动Docker服务 # Start Docker services
echo "开始启动最新版本服务..." echo "Starting latest version services..."
# 升级完成后标记,跳过后续下载步骤 # Mark upgrade completion, skip subsequent download steps
UPGRADE_COMPLETED=1 UPGRADE_COMPLETED=1
docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d
else else
whiptail --title "跳过升级" --msgbox "已取消升级,将继续使用当前版本。" 10 50 whiptail --title "Skip Upgrade" --msgbox "Upgrade cancelled, will continue using current version." 10 50
# 跳过升级,继续执行后续安装流程 # Skip upgrade, continue with subsequent installation process
fi fi
fi fi
# 检查curl安装 # Check curl installation
if ! command -v curl &> /dev/null; then if ! command -v curl &> /dev/null; then
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "未检测到curl,正在安装..." echo "curl not detected, installing..."
apt update apt update
apt install -y curl apt install -y curl
else else
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "curl已安装,跳过安装步骤" echo "curl already installed, skipping installation step"
fi fi
# 检查Docker安装 # Check Docker installation
if ! command -v docker &> /dev/null; then if ! command -v docker &> /dev/null; then
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "未检测到Docker,正在安装..." echo "Docker not detected, installing..."
# 使用国内镜像源替代官方源 # Use official Docker source
DISTRO=$(lsb_release -cs) DISTRO=$(lsb_release -cs)
MIRROR_URL="https://mirrors.aliyun.com/docker-ce/linux/ubuntu" MIRROR_URL="https://download.docker.com/linux/ubuntu"
GPG_URL="https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg" GPG_URL="https://download.docker.com/linux/ubuntu/gpg"
# 安装基础依赖 # Install basic dependencies
apt update apt update
apt install -y apt-transport-https ca-certificates curl software-properties-common gnupg apt install -y apt-transport-https ca-certificates curl software-properties-common gnupg
# 创建密钥目录并添加国内镜像源密钥 # Create key directory and add domestic mirror source key
mkdir -p /etc/apt/keyrings mkdir -p /etc/apt/keyrings
curl -fsSL "$GPG_URL" | gpg --dearmor -o /etc/apt/keyrings/docker.gpg curl -fsSL "$GPG_URL" | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
# 添加国内镜像源 # Add domestic mirror source
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] $MIRROR_URL $DISTRO stable" \ echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] $MIRROR_URL $DISTRO stable" \
> /etc/apt/sources.list.d/docker.list > /etc/apt/sources.list.d/docker.list
# 添加备用官方源密钥(避免国内源密钥验证失败) # Add backup official source key (avoid domestic source key verification failure)
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7EA0A9C3F273FCD8 2>/dev/null || \ apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7EA0A9C3F273FCD8 2>/dev/null || \
echo "警告:部分密钥添加失败,继续尝试安装..." echo "Warning: Some keys failed to add, continuing installation attempt..."
# 安装Docker # Install Docker
apt update apt update
apt install -y docker-ce docker-ce-cli containerd.io apt install -y docker-ce docker-ce-cli containerd.io
# 启动服务 # Start services
systemctl start docker systemctl start docker
systemctl enable docker systemctl enable docker
# 检查是否安装成功 # Check if installation was successful
if docker --version; then if docker --version; then
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "Docker安装完成!" echo "Docker installation completed!"
else else
whiptail --title "错误" --msgbox "Docker安装失败,请检查日志。" 10 50 whiptail --title "Error" --msgbox "Docker installation failed, please check logs." 10 50
exit 1 exit 1
fi fi
else else
echo "Docker已安装,跳过安装步骤" echo "Docker already installed, skipping installation step"
fi fi
# Docker镜像源配置 # Docker mirror source configuration
MIRROR_OPTIONS=( MIRROR_OPTIONS=(
"1" "轩辕镜像 (推荐)" "1" "Docker Hub Official (Recommended)"
"2" "腾讯云镜像源" "2" "Google Container Registry"
"3" "中科大镜像源" "3" "Amazon ECR Public"
"4" "网易163镜像源" "4" "Microsoft Container Registry"
"5" "华为云镜像源" "5" "Quay.io Registry"
"6" "阿里云镜像源" "6" "GitHub Container Registry"
"7" "自定义镜像源" "7" "Custom Mirror Source"
"8" "跳过配置" "8" "Skip Configuration"
) )
MIRROR_CHOICE=$(whiptail --title "选择Docker镜像源" --menu "请选择要使用的Docker镜像源" 20 60 10 \ MIRROR_CHOICE=$(whiptail --title "Select Docker Mirror Source" --menu "Please select the Docker mirror source to use" 20 60 10 \
"${MIRROR_OPTIONS[@]}" 3>&1 1>&2 2>&3) || { "${MIRROR_OPTIONS[@]}" 3>&1 1>&2 2>&3) || {
echo "用户取消选择,退出脚本" echo "User cancelled selection, exiting script"
exit 1 exit 1
} }
case $MIRROR_CHOICE in case $MIRROR_CHOICE in
1) MIRROR_URL="https://docker.xuanyuan.me" ;; 1) MIRROR_URL="https://registry-1.docker.io" ;;
2) MIRROR_URL="https://mirror.ccs.tencentyun.com" ;; 2) MIRROR_URL="https://gcr.io" ;;
3) MIRROR_URL="https://docker.mirrors.ustc.edu.cn" ;; 3) MIRROR_URL="https://public.ecr.aws" ;;
4) MIRROR_URL="https://hub-mirror.c.163.com" ;; 4) MIRROR_URL="https://mcr.microsoft.com" ;;
5) MIRROR_URL="https://05f073ad3c0010ea0f4bc00b7105ec20.mirror.swr.myhuaweicloud.com" ;; 5) MIRROR_URL="https://quay.io" ;;
6) MIRROR_URL="https://registry.aliyuncs.com" ;; 6) MIRROR_URL="https://ghcr.io" ;;
7) MIRROR_URL=$(whiptail --title "自定义镜像源" --inputbox "请输入完整的镜像源URL:" 10 60 3>&1 1>&2 2>&3) ;; 7) MIRROR_URL=$(whiptail --title "Custom Mirror Source" --inputbox "Please enter the complete mirror source URL:" 10 60 3>&1 1>&2 2>&3) ;;
8) MIRROR_URL="" ;; 8) MIRROR_URL="" ;;
esac esac
@ -295,76 +294,434 @@ if [ -n "$MIRROR_URL" ]; then
"registry-mirrors": ["$MIRROR_URL"] "registry-mirrors": ["$MIRROR_URL"]
} }
EOF EOF
whiptail --title "配置成功" --msgbox "已成功添加镜像源: $MIRROR_URL\n请按Enter键重启Docker服务并继续..." 12 60 whiptail --title "Configuration Success" --msgbox "Successfully added mirror source: $MIRROR_URL\nPlease press Enter to restart Docker service and continue..." 12 60
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "开始重启Docker服务..." echo "Starting Docker service restart..."
systemctl restart docker.service systemctl restart docker.service
fi fi
# 创建安装目录 # Create installation directory
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "开始创建安装目录..." echo "Starting to create installation directory..."
# 检查并创建数据目录 # Check and create data directory
if [ ! -d /opt/xiaozhi-server/data ]; then if [ ! -d /opt/xiaozhi-server/data ]; then
mkdir -p /opt/xiaozhi-server/data mkdir -p /opt/xiaozhi-server/data
echo "已创建数据目录: /opt/xiaozhi-server/data" echo "Created data directory: /opt/xiaozhi-server/data"
else else
echo "目录xiaozhi-server/data已存在,跳过创建" echo "Directory xiaozhi-server/data already exists, skipping creation"
fi fi
# 检查并创建模型目录 # Check and create models directory
if [ ! -d /opt/xiaozhi-server/models/SenseVoiceSmall ]; then if [ ! -d /opt/xiaozhi-server/models ]; then
mkdir -p /opt/xiaozhi-server/models/SenseVoiceSmall mkdir -p /opt/xiaozhi-server/models
echo "已创建模型目录: /opt/xiaozhi-server/models/SenseVoiceSmall" echo "Created models directory: /opt/xiaozhi-server/models"
else else
echo "目录xiaozhi-server/models/SenseVoiceSmall已存在,跳过创建" echo "Directory xiaozhi-server/models already exists, skipping creation"
fi fi
echo "------------------------------------------------------------" # Download and extract Vosk English model
echo "开始下载语音识别模型" download_vosk_model() {
# 下载模型文件 echo "------------------------------------------------------------"
MODEL_PATH="/opt/xiaozhi-server/models/SenseVoiceSmall/model.pt" echo "Checking Vosk English model..."
if [ ! -f "$MODEL_PATH" ]; then
( VOSK_MODEL_DIR="/opt/xiaozhi-server/models/vosk"
for i in {1..20}; do VOSK_MODEL_PATH="$VOSK_MODEL_DIR/vosk-model-en-us-0.22"
echo $((i*5))
sleep 0.5 # Check if model is already downloaded and extracted
if [ -d "$VOSK_MODEL_PATH" ] && [ -f "$VOSK_MODEL_PATH/am/final.mdl" ]; then
echo "Vosk English model already exists, skipping download"
return 0
fi
echo "Vosk English model not found, starting download..."
# Create vosk directory
mkdir -p "$VOSK_MODEL_DIR"
# Download the model
MODEL_URL="https://alphacephei.com/vosk/models/vosk-model-en-us-0.22.zip"
MODEL_ZIP="$VOSK_MODEL_DIR/vosk-model-en-us-0.22.zip"
echo "Downloading Vosk English model from $MODEL_URL"
echo "This may take several minutes depending on your internet connection..."
if ! curl -L --progress-bar "$MODEL_URL" -o "$MODEL_ZIP"; then
echo "Warning: Failed to download Vosk model. You can download it manually later."
echo "Visit: https://alphacephei.com/vosk/models"
echo "Download: vosk-model-en-us-0.22.zip"
echo "Extract to: $VOSK_MODEL_DIR/"
return 1
fi
# Check if download was successful
if [ ! -f "$MODEL_ZIP" ]; then
echo "Warning: Vosk model download failed. You can download it manually later."
return 1
fi
echo "Download completed, extracting model..."
# Check if unzip is available
if ! command -v unzip &> /dev/null; then
echo "Installing unzip..."
apt update
apt install -y unzip
fi
# Extract the model
if unzip -q "$MODEL_ZIP" -d "$VOSK_MODEL_DIR/"; then
echo "Vosk model extracted successfully"
# Clean up zip file
rm "$MODEL_ZIP"
echo "Vosk English model setup completed: $VOSK_MODEL_PATH"
else
echo "Warning: Failed to extract Vosk model. You can extract it manually later."
echo "Extract $MODEL_ZIP to $VOSK_MODEL_DIR/"
return 1
fi
}
# Download Sherpa ONNX models function
download_sherpa_models() {
echo "------------------------------------------------------------"
echo "Checking Sherpa ONNX ASR models..."
SHERPA_BASE_DIR="/opt/xiaozhi-server/models"
SHERPA_SENSE_VOICE_DIR="$SHERPA_BASE_DIR/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17"
SHERPA_PARAFORMER_DIR="$SHERPA_BASE_DIR/sherpa-onnx-paraformer-zh-small-2024-03-09"
# Check if models are already downloaded
SENSE_VOICE_EXISTS=false
PARAFORMER_EXISTS=false
if [ -f "$SHERPA_SENSE_VOICE_DIR/model.int8.onnx" ] && [ -f "$SHERPA_SENSE_VOICE_DIR/tokens.txt" ]; then
SENSE_VOICE_EXISTS=true
echo "Sherpa ONNX Sense Voice model already exists, skipping download"
fi
if [ -f "$SHERPA_PARAFORMER_DIR/model.int8.onnx" ] && [ -f "$SHERPA_PARAFORMER_DIR/tokens.txt" ]; then
PARAFORMER_EXISTS=true
echo "Sherpa ONNX Paraformer model already exists, skipping download"
fi
# If both models exist, skip download
if [ "$SENSE_VOICE_EXISTS" = true ] && [ "$PARAFORMER_EXISTS" = true ]; then
echo "All Sherpa ONNX models already exist, skipping download"
return 0
fi
echo "Sherpa ONNX models not found, starting download..."
# Download Sense Voice model if needed
if [ "$SENSE_VOICE_EXISTS" = false ]; then
echo "Downloading Sherpa ONNX Sense Voice model..."
mkdir -p "$SHERPA_SENSE_VOICE_DIR"
SENSE_VOICE_URL="https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17.tar.bz2"
SENSE_VOICE_ARCHIVE="$SHERPA_SENSE_VOICE_DIR/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17.tar.bz2"
echo "Downloading from $SENSE_VOICE_URL"
echo "This may take several minutes depending on your internet connection..."
if curl -L --progress-bar "$SENSE_VOICE_URL" -o "$SENSE_VOICE_ARCHIVE"; then
echo "Download completed, extracting Sense Voice model..."
# Check if tar is available
if ! command -v tar &> /dev/null; then
echo "Installing tar..."
apt update
apt install -y tar
fi
# Extract the model
if tar -xjf "$SENSE_VOICE_ARCHIVE" -C "$SHERPA_SENSE_VOICE_DIR/"; then
echo "Sense Voice model extracted successfully"
rm "$SENSE_VOICE_ARCHIVE"
echo "Sherpa ONNX Sense Voice model setup completed: $SHERPA_SENSE_VOICE_DIR"
else
echo "Warning: Failed to extract Sense Voice model"
return 1
fi
else
echo "Warning: Failed to download Sense Voice model"
return 1
fi
fi
# Download Paraformer model if needed
if [ "$PARAFORMER_EXISTS" = false ]; then
echo "Downloading Sherpa ONNX Paraformer model..."
mkdir -p "$SHERPA_PARAFORMER_DIR"
PARAFORMER_URL="https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-paraformer-zh-small-2024-03-09.tar.bz2"
PARAFORMER_ARCHIVE="$SHERPA_PARAFORMER_DIR/sherpa-onnx-paraformer-zh-small-2024-03-09.tar.bz2"
echo "Downloading from $PARAFORMER_URL"
echo "This may take several minutes depending on your internet connection..."
if curl -L --progress-bar "$PARAFORMER_URL" -o "$PARAFORMER_ARCHIVE"; then
echo "Download completed, extracting Paraformer model..."
# Extract the model
if tar -xjf "$PARAFORMER_ARCHIVE" -C "$SHERPA_PARAFORMER_DIR/"; then
echo "Paraformer model extracted successfully"
rm "$PARAFORMER_ARCHIVE"
echo "Sherpa ONNX Paraformer model setup completed: $SHERPA_PARAFORMER_DIR"
else
echo "Warning: Failed to extract Paraformer model"
return 1
fi
else
echo "Warning: Failed to download Paraformer model"
return 1
fi
fi
echo "All Sherpa ONNX models downloaded successfully!"
echo "Models are now available for Docker deployment"
}
# Download Whisper models function
download_whisper_models() {
echo "------------------------------------------------------------"
echo "Checking Whisper models..."
WHISPER_BASE_DIR="/opt/xiaozhi-server/models/whisper"
# Check if Whisper models directory exists
if [ ! -d "$WHISPER_BASE_DIR" ]; then
mkdir -p "$WHISPER_BASE_DIR"
echo "Created Whisper models directory: $WHISPER_BASE_DIR"
fi
# Define available Whisper models
WHISPER_MODELS=(
"tiny.en"
"tiny"
"base.en"
"base"
"small.en"
"small"
"medium.en"
"medium"
"large-v1"
"large-v2"
"large-v3"
)
# Check which models are already downloaded
EXISTING_MODELS=()
MISSING_MODELS=()
for model in "${WHISPER_MODELS[@]}"; do
MODEL_PATH="$WHISPER_BASE_DIR/$model"
if [ -d "$MODEL_PATH" ] && [ -f "$MODEL_PATH/encoder.onnx" ] || [ -f "$MODEL_PATH/encoder.pt" ]; then
EXISTING_MODELS+=("$model")
echo "Whisper model '$model' already exists, skipping download"
else
MISSING_MODELS+=("$model")
fi
done done
) | whiptail --title "下载中" --gauge "开始下载语音识别模型..." 10 60 0
curl -fL --progress-bar https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt -o "$MODEL_PATH" || {
whiptail --title "错误" --msgbox "model.pt文件下载失败" 10 50
exit 1
}
else
echo "model.pt文件已存在,跳过下载"
fi
# 如果不是升级完成,才执行下载 # If all models exist, skip download
if [ ${#MISSING_MODELS[@]} -eq 0 ]; then
echo "All Whisper models already exist, skipping download"
return 0
fi
echo "Whisper models not found, starting download..."
echo "Available models: ${WHISPER_MODELS[*]}"
echo "Missing models: ${MISSING_MODELS[*]}"
# Note: Whisper models are downloaded automatically by the Python whisper library
# when first used. We'll create placeholder directories and download scripts.
echo "Creating Whisper model download setup..."
# Create a Python script to download models
cat > "$WHISPER_BASE_DIR/download_models.py" << 'EOF'
#!/usr/bin/env python3
"""
Whisper model download script
This script downloads Whisper models to the specified directory
"""
import os
import sys
import whisper
import argparse
def download_whisper_model(model_name, download_dir):
"""Download a Whisper model to the specified directory"""
try:
print(f"Downloading Whisper model: {model_name}")
# Set the cache directory for Whisper
os.environ['WHISPER_CACHE_DIR'] = download_dir
# Load the model (this will download it if not present)
model = whisper.load_model(model_name)
print(f"Successfully downloaded Whisper model: {model_name}")
return True
except Exception as e:
print(f"Failed to download Whisper model {model_name}: {e}")
return False
def main():
parser = argparse.ArgumentParser(description='Download Whisper models')
parser.add_argument('--model', required=True, help='Model name to download')
parser.add_argument('--dir', required=True, help='Download directory')
args = parser.parse_args()
success = download_whisper_model(args.model, args.dir)
sys.exit(0 if success else 1)
if __name__ == '__main__':
main()
EOF
chmod +x "$WHISPER_BASE_DIR/download_models.py"
# Create a shell script for easy model downloads
cat > "$WHISPER_BASE_DIR/download_all_models.sh" << 'EOF'
#!/bin/bash
# Whisper model download script
WHISPER_MODELS=(
"tiny.en"
"tiny"
"base.en"
"base"
"small.en"
"small"
"medium.en"
"medium"
"large-v1"
"large-v2"
"large-v3"
)
DOWNLOAD_DIR="/opt/xiaozhi-server/models/whisper"
echo "Starting Whisper model downloads..."
echo "This may take a long time depending on your internet connection"
echo "Models will be downloaded to: $DOWNLOAD_DIR"
for model in "${WHISPER_MODELS[@]}"; do
echo "Downloading model: $model"
python3 "$DOWNLOAD_DIR/download_models.py" --model "$model" --dir "$DOWNLOAD_DIR"
if [ $? -eq 0 ]; then
echo "Successfully downloaded: $model"
else
echo "Failed to download: $model"
fi
echo "---"
done
echo "Whisper model download process completed"
EOF
chmod +x "$WHISPER_BASE_DIR/download_all_models.sh"
# Create model info file
cat > "$WHISPER_BASE_DIR/MODELS.md" << 'EOF'
# Whisper Models
This directory contains Whisper ASR models for offline speech recognition.
## Available Models
- **tiny.en** - Fastest, English only (~39 MB)
- **tiny** - Fastest, multilingual (~39 MB)
- **base.en** - Small, English only (~74 MB)
- **base** - Small, multilingual (~74 MB)
- **small.en** - Medium, English only (~244 MB)
- **small** - Medium, multilingual (~244 MB)
- **medium.en** - Large, English only (~769 MB)
- **medium** - Large, multilingual (~769 MB)
- **large-v1** - Very large, multilingual (~1550 MB)
- **large-v2** - Very large, multilingual (~1550 MB)
- **large-v3** - Very large, multilingual (~1550 MB)
## Usage
Models are automatically downloaded when first used by the Whisper ASR provider.
You can also download them manually using the provided scripts:
```bash
# Download a specific model
python3 /opt/xiaozhi-server/models/whisper/download_models.py --model base --dir /opt/xiaozhi-server/models/whisper
# Download all models (takes a long time)
/opt/xiaozhi-server/models/whisper/download_all_models.sh
```
## Configuration
Configure Whisper models in your config.yaml:
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base # Choose from available models above
device: auto # auto, cpu, cuda
language: null # null for auto-detect, or specific language code
output_dir: tmp/
```
## Performance Notes
- **tiny/tiny.en**: Fastest, lowest accuracy, good for real-time applications
- **base/base.en**: Good balance of speed and accuracy
- **small/small.en**: Better accuracy, slower than base
- **medium/medium.en**: High accuracy, significantly slower
- **large-v1/v2/v3**: Highest accuracy, slowest processing
Choose the model based on your accuracy vs speed requirements.
EOF
echo "Whisper model setup completed!"
echo "Models will be downloaded automatically when first used"
echo "Manual download scripts available in: $WHISPER_BASE_DIR"
echo "Model information available in: $WHISPER_BASE_DIR/MODELS.md"
}
# Only download models if not upgrading
if [ -z "$UPGRADE_COMPLETED" ]; then if [ -z "$UPGRADE_COMPLETED" ]; then
check_and_download "/opt/xiaozhi-server/docker-compose_all.yml" "https://ghfast.top/https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/docker-compose_all.yml" download_vosk_model
check_and_download "/opt/xiaozhi-server/data/.config.yaml" "https://ghfast.top/https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/config_from_api.yaml" download_sherpa_models
download_whisper_models
fi fi
# 启动Docker服务
# Only execute download if upgrade is not completed
if [ -z "$UPGRADE_COMPLETED" ]; then
check_and_download "/opt/xiaozhi-server/docker-compose_all.yml" "https://raw.githubusercontent.com/lapy/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose_all.yml"
check_and_download "/opt/xiaozhi-server/data/.config.yaml" "https://raw.githubusercontent.com/lapy/xiaozhi-esp32-server/main/main/xiaozhi-server/config_from_api.yaml"
fi
# Start Docker service
( (
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "正在拉取Docker镜像..." echo "Pulling Docker images..."
echo "这可能需要几分钟时间,请耐心等待" echo "This may take a few minutes, please be patient"
docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
whiptail --title "错误" --msgbox "Docker服务启动失败,请尝试更换镜像源后重新执行本脚本" 10 60 whiptail --title "Error" --msgbox "Docker service startup failed, please try changing the image source and re-execute this script" 10 60
exit 1 exit 1
fi fi
echo "------------------------------------------------------------" echo "------------------------------------------------------------"
echo "正在检查服务启动状态..." echo "Checking service startup status..."
TIMEOUT=300 TIMEOUT=300
START_TIME=$(date +%s) START_TIME=$(date +%s)
while true; do while true; do
CURRENT_TIME=$(date +%s) CURRENT_TIME=$(date +%s)
if [ $((CURRENT_TIME - START_TIME)) -gt $TIMEOUT ]; then if [ $((CURRENT_TIME - START_TIME)) -gt $TIMEOUT ]; then
whiptail --title "错误" --msgbox "服务启动超时,未在指定时间内找到预期日志内容" 10 60 whiptail --title "Error" --msgbox "Service startup timeout, expected log content not found within specified time" 10 60
exit 1 exit 1
fi fi
@ -374,18 +731,18 @@ while true; do
sleep 1 sleep 1
done done
echo "服务端启动成功!正在完成配置..." echo "Server started successfully! Completing configuration..."
echo "正在启动服务..." echo "Starting services..."
docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d docker compose -f /opt/xiaozhi-server/docker-compose_all.yml up -d
echo "服务启动完成!" echo "Service startup completed!"
) )
# 密钥配置 # Secret key configuration
# 获取服务器公网地址 # Get server public IP address
PUBLIC_IP=$(hostname -I | awk '{print $1}') PUBLIC_IP=$(hostname -I | awk '{print $1}')
whiptail --title "配置服务器密钥" --msgbox "请使用浏览器,访问下方链接,打开智控台并注册账号: \n\n内网地址:http://127.0.0.1:8002/\n公网地址:http://$PUBLIC_IP:8002/ (若是云服务器请在服务器安全组放行端口 8000 8001 8002)。\n\n注册的第一个用户即是超级管理员,以后注册的用户都是普通用户。普通用户只能绑定设备和配置智能体; 超级管理员可以进行模型管理、用户管理、参数配置等功能。\n\n注册好后请按Enter键继续" 18 70 whiptail --title "Configure Server Secret Key" --msgbox "Please use a browser to access the following link, open the Smart Control Panel and register an account: \n\nInternal address: http://127.0.0.1:8002/\nPublic address: http://$PUBLIC_IP:8002/ (If it's a cloud server, please open ports 8000 8001 8002 in the server security group).\n\nThe first registered user is the super administrator, and subsequent users are ordinary users. Ordinary users can only bind devices and configure intelligent agents; super administrators can perform model management, user management, parameter configuration and other functions.\n\nAfter registration, please press Enter to continue" 18 70
SECRET_KEY=$(whiptail --title "配置服务器密钥" --inputbox "请使用超级管理员账号登录智控台\n内网地址:http://127.0.0.1:8002/\n公网地址:http://$PUBLIC_IP:8002/\n在顶部菜单 参数字典 → 参数管理 找到参数编码: server.secret (服务器密钥) \n复制该参数值并输入到下面输入框\n\n请输入密钥(留空则跳过配置):" 15 60 3>&1 1>&2 2>&3) SECRET_KEY=$(whiptail --title "Configure Server Secret Key" --inputbox "Please use the super administrator account to log into the Smart Control Panel\nInternal address: http://127.0.0.1:8002/\nPublic address: http://$PUBLIC_IP:8002/\nIn the top menu Parameter Dictionary → Parameter Management, find parameter code: server.secret (Server Secret Key) \nCopy the parameter value and enter it in the input box below\n\nPlease enter the secret key (leave empty to skip configuration):" 15 60 3>&1 1>&2 2>&3)
if [ -n "$SECRET_KEY" ]; then if [ -n "$SECRET_KEY" ]; then
python3 -c " python3 -c "
@ -400,14 +757,14 @@ with open(config_path, 'w') as f:
docker restart xiaozhi-esp32-server docker restart xiaozhi-esp32-server
fi fi
# 获取并显示地址信息 # Get and display address information
LOCAL_IP=$(hostname -I | awk '{print $1}') LOCAL_IP=$(hostname -I | awk '{print $1}')
# 修复日志文件获取不到ws的问题,改为硬编码 # Fix log file unable to get ws issue, change to hardcode
whiptail --title "安装完成!" --msgbox "\ whiptail --title "Installation Complete!" --msgbox "\
服务端相关地址如下:\n\ Server related addresses are as follows:\n\
管理后台访问地址: http://$LOCAL_IP:8002\n\ Management backend access address: http://$LOCAL_IP:8002\n\
OTA 地址: http://$LOCAL_IP:8002/xiaozhi/ota/\n\ OTA address: http://$LOCAL_IP:8003/xiaozhi/ota/\n\
视觉分析接口地址: http://$LOCAL_IP:8003/mcp/vision/explain\n\ Vision analysis interface address: http://$LOCAL_IP:8003/mcp/vision/explain\n\
WebSocket 地址: ws://$LOCAL_IP:8000/xiaozhi/v1/\n\ WebSocket address: ws://$LOCAL_IP:8000/xiaozhi/v1/\n\
\n安装完毕!感谢您的使用!\n按Enter键退出..." 16 70 \nInstallation complete! Thank you for using!\nPress Enter to exit..." 16 70

View file

@ -1,291 +0,0 @@
# 部署架构图
![请参考-最简化架构图](../docs/images/deploy1.png)
# 方式一:Docker只运行Server
`0.8.2`版本开始,本项目发行的docker镜像只支持`x86架构`,如果需要在`arm64架构`的CPU上部署,可按照[这个教程](docker-build.md)在本机编译`arm64的镜像`。
## 1. 安装docker
如果您的电脑还没安装docker,可以按照这里的教程安装:[docker安装](https://www.runoob.com/docker/ubuntu-docker-install.html)
安装好docker后,进继续。
### 1.1 手动部署
#### 1.1.1 创建目录
安装完docker后,你需要为这个项目找一个安放配置文件的目录,例如我们可以新建一个文件夹叫`xiaozhi-server`。
创建好目录后,你需要在`xiaozhi-server`下面创建`data`文件夹和`models`文件夹,`models`下面还要再创建`SenseVoiceSmall`文件夹。
最终目录结构如下所示:
```
xiaozhi-server
├─ data
├─ models
├─ SenseVoiceSmall
```
#### 1.1.2 下载语音识别模型文件
你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。可通过这个方式下载
[跳转到下载语音识别模型文件](#模型文件)
下载完后,回到本教程。
#### 1.1.3 下载配置文件
你需要下载两个配置文件:`docker-compose.yaml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
##### 1.1.3.1 下载 docker-compose.yaml
用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`docker-compose.yml`文件。 把文件下载到你的
`xiaozhi-server`中。
下载完后,回到本教程继续往下。
##### 1.1.3.2 创建 config.yaml
用浏览器打开[这个链接](../main/xiaozhi-server/config.yaml)。
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的
`xiaozhi-server`下面的`data`文件夹中,然后把`config.yaml`文件重命名为`.config.yaml`。
下载完配置文件后,我们确认一下整个`xiaozhi-server`里面的文件如下所示:
```
xiaozhi-server
├─ docker-compose.yml
├─ data
├─ .config.yaml
├─ models
├─ SenseVoiceSmall
├─ model.pt
```
如果你的文件目录结构也是上面的,就继续往下。如果不是,你就再仔细看看是不是漏操作了什么。
## 2. 配置项目文件
接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
[跳转到配置项目文件](#配置项目)
配置完项目文件后,回到本教程继续往下。
## 3. 执行docker命令
打开命令行工具,使用`终端`或`命令行`工具 进入到你的`xiaozhi-server`,执行以下命令
```
docker compose up -d
```
执行完后,再执行以下命令,查看日志信息。
```
docker logs -f xiaozhi-esp32-server
```
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
## 5. 版本升级操作
如果后期想升级版本,可以这么操作
5.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。
5.2、执行以下命令
```
docker stop xiaozhi-esp32-server
docker rm xiaozhi-esp32-server
docker stop xiaozhi-esp32-server-web
docker rm xiaozhi-esp32-server-web
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
```
5.3、重新按docker方式部署
# 方式二:本地源码只运行Server
## 1.安装基础环境
本项目使用`conda`管理依赖环境。如果不方便安装`conda`,需要根据实际的操作系统安装好`libopus`和`ffmpeg`。
如果确定使用`conda`,则安装好后,开始执行以下命令。
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
![conda_prompt](./images/conda_env_1.png)
运行之后,如果你能看到命令行窗口前面有一个(base)字样,说明你成功进入了`conda`环境。那么你就可以执行以下命令了。
![conda_env](./images/conda_env_2.png)
```
conda remove -n xiaozhi-esp32-server --all -y
conda create -n xiaozhi-esp32-server python=3.10 -y
conda activate xiaozhi-esp32-server
# 添加清华源通道
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
conda install libopus -y
conda install ffmpeg -y
# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装
conda install libiconv -y
```
请注意,以上命令,不是一股脑执行就成功的,你需要一步步执行,每一步执行完后,都检查一下输出的日志,查看是否成功。
## 2.安装本项目依赖
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
你可以用浏览器打开这个地址`https://github.com/xinnan-tech/xiaozhi-esp32-server.git`
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`xiaozhi-esp32-server-main`
你需要把它重命名成`xiaozhi-esp32-server`,在这个文件里,进入到`main`文件夹,再进入到`xiaozhi-server`,好了请记住这个目录`xiaozhi-server`。
```
# 继续使用conda环境
conda activate xiaozhi-esp32-server
# 进入到你的项目根目录,再进入main/xiaozhi-server
cd main/xiaozhi-server
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip install -r requirements.txt
```
## 3.下载语音识别模型文件
你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。可通过这个方式下载
[跳转到下载语音识别模型文件](#模型文件)
下载完后,回到本教程。
## 4.配置项目文件
接下来,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
[跳转到配置项目文件](#配置项目)
## 5.运行项目
```
# 确保在xiaozhi-server目录下执行
conda activate xiaozhi-esp32-server
python app.py
```
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
# 汇总
## 配置项目
如果你的`xiaozhi-server`目录没有`data`,你需要创建`data`目录。
如果你的`data`下面没有`.config.yaml`文件,有两个方式,任选一种:
第一个方式:你可以把`xiaozhi-server`目录下的`config.yaml`文件复制到`data`,并重命名为`.config.yaml`。在此文件上修改
第二个方式:你也可以创建在`data`目录下手动创建`.config.yaml`空文件,然后在这个文件中增加必要的配置信息,系统会优先读取`.config.yaml`文件的配置,如果`.config.yaml`没有配置的,系统会自动去加载`xiaozhi-server`目录下的`config.yaml`的配置。推荐使用这种方式,这种方式是最简洁的方式。
- 默认的LLM使用的是`ChatGLMLLM`,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
以下是一个能正常跑起来的,最简单的`.config.yaml`配置示例
```
server:
websocket: ws://你的ip或者域名:端口号/xiaozhi/v1/
prompt: |
我是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
我的男朋友是一个程序员,梦想是开发出一个机器人,能够帮助人们解决生活中的各种问题。
我是一个喜欢哈哈大笑的女孩,爱东说西说吹牛,不合逻辑的也照吹,就要逗别人开心。
请你像一个人一样说话,请勿返回配置xml及其他特殊字符。
selected_module:
LLM: DoubaoLLM
LLM:
ChatGLMLLM:
api_key: xxxxxxxxxxxxxxx.xxxxxx
```
建议先将最简单的配置运行起来,然后再去`xiaozhi/config.yaml`阅读配置的使用说明。
比如你要换更换模型,修改`selected_module`下的配置就行。
## 模型文件
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
文件放在`models/SenseVoiceSmall`
目录下。下面两个下载路线任选一个。
- 线路一:阿里魔搭下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
`qvna`
## 运行状态确认
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
```
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======================================================
```
正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。
但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。
最正确的方法,是根据电脑的局域网IP来确定你的接口地址。
如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000/xiaozhi/v1/`,对应的OTA地址就是:`http://192.168.1.25:8003/xiaozhi/ota/`。
这个信息很有用的,后面`编译esp32固件`需要用到。
接下来,你就可以开始操作你的esp32设备了,你可以`自行编译esp32固件`也可以配置使用`虾哥编译好的1.6.1以上版本的固件`。两个任选一个
1、 [编译自己的esp32固件](firmware-build.md)了。
2、 [基于虾哥编译好的固件配置自定义服务器](firmware-setting.md)了。
# 常见问题
以下是一些常见问题,供参考:
1、[为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)<br/>
2、[为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)<br/>
3、[TTS 经常失败,经常超时](./FAQ.md)<br/>
4、[使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)<br/>
5、[如何提高小智对话响应速度?](./FAQ.md)<br/>
6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)<br/>
## 部署相关教程
1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)<br/>
2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)<br/>
3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)<br/>
## 拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)<br/>
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)<br/>
3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)<br/>
4、[如何部署MCP接入点](./mcp-endpoint-enable.md)<br/>
5、[如何接入MCP接入点](./mcp-endpoint-integration.md)<br/>
6、[如何开启声纹识别](./voiceprint-integration.md)<br/>
7、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
8、[天气插件使用指南](./weather-integration.md)<br/>
## 语音克隆、本地语音部署相关教程
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
2、[如何部署集成index-tts本地语音](./index-stream-integration.md)<br/>
3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)<br/>
4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)<br/>
## 性能测试教程
1、[各组件速度测试指南](./performance_tester.md)<br/>
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)<br/>

View file

@ -1,492 +0,0 @@
# 部署架构图
![请参考-全模块安装架构图](../docs/images/deploy2.png)
# 方式一:Docker运行全模块
`0.8.2`版本开始,本项目发行的docker镜像只支持`x86架构`,如果需要在`arm64架构`的CPU上部署,可按照[这个教程](docker-build.md)在本机编译`arm64的镜像`。
## 1. 安装docker
如果您的电脑还没安装docker,可以按照这里的教程安装:[docker安装](https://www.runoob.com/docker/ubuntu-docker-install.html)
docker 安装全模块有两种方式,你可以[使用懒人脚本](./Deployment_all.md#11-懒人脚本)(作者[@VanillaNahida](https://github.com/VanillaNahida))
脚本会自动帮你下载所需的文件和配置文件,你也可以使用[手动部署](./Deployment_all.md#12-手动部署)从零搭建。
### 1.1 懒人脚本
部署简便,可以参考[视频教程](https://www.bilibili.com/video/BV17bbvzHExd/) ,文字版教程如下:
> [!NOTE]
> 暂且只支持Ubuntu服务器一键部署,其他系统未尝试,可能会有一些奇怪的bug
使用SSH工具连接到服务器,以root权限执行如下脚本
```bash
sudo bash -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/docker-setup.sh)"
```
脚本会自动完成以下操作:
> 1. 安装Docker
> 2. 配置镜像源
> 3. 下载/拉取镜像
> 4. 下载语音识别模型文件
> 5. 引导配置服务端
>
执行完成后简单配置后,再参照[4. 运行程序](#4. 运行程序)和[5.重启xiaozhi-esp32-server](#5.重启xiaozhi-esp32-server)里提到的最重要的3件事情,完成3这三项配置后即可使用。
### 1.2 手动部署
#### 1.2.1 创建目录
安装完后,你需要为这个项目找一个安放配置文件的目录,例如我们可以新建一个文件夹叫`xiaozhi-server`。
创建好目录后,你需要在`xiaozhi-server`下面创建`data`文件夹和`models`文件夹,`models`下面还要再创建`SenseVoiceSmall`文件夹。
最终目录结构如下所示:
```
xiaozhi-server
├─ data
├─ models
├─ SenseVoiceSmall
```
#### 1.2.2 下载语音识别模型文件
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
文件放在`models/SenseVoiceSmall`
目录下。下面两个下载路线任选一个。
- 线路一:阿里魔搭下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
`qvna`
#### 1.2.3 下载配置文件
你需要下载两个配置文件:`docker-compose_all.yaml` 和 `config_from_api.yaml`。需要从项目仓库下载这两个文件。
##### 1.2.3.1 下载 docker-compose_all.yaml
用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose_all.yml)。
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`docker-compose_all.yml`文件。 把文件下载到你的
`xiaozhi-server`中。
或者直接执行 `wget https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/docker-compose_all.yml` 下载。
下载完后,回到本教程继续往下。
##### 1.2.3.2 下载 config_from_api.yaml
用浏览器打开[这个链接](../main/xiaozhi-server/config_from_api.yaml)。
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config_from_api.yaml`文件。 把文件下载到你的
`xiaozhi-server`下面的`data`文件夹中,然后把`config_from_api.yaml`文件重命名为`.config.yaml`。
或者直接执行 `wget https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/refs/heads/main/main/xiaozhi-server/config_from_api.yaml` 下载保存。
下载完配置文件后,我们确认一下整个`xiaozhi-server`里面的文件如下所示:
```
xiaozhi-server
├─ docker-compose_all.yml
├─ data
├─ .config.yaml
├─ models
├─ SenseVoiceSmall
├─ model.pt
```
如果你的文件目录结构也是上面的,就继续往下。如果不是,你就再仔细看看是不是漏操作了什么。
## 2. 备份数据
如果你之前已经成功运行智控台,如果上面保存有你的密钥信息,请先从智控台上拷贝重要数据下来。因为升级过程中,有可能会覆盖原来的数据。
## 3. 清除历史版本镜像和容器
接下来打开命令行工具,使用`终端`或`命令行`工具 进入到你的`xiaozhi-server`,执行以下命令
```
docker compose -f docker-compose_all.yml down
docker stop xiaozhi-esp32-server
docker rm xiaozhi-esp32-server
docker stop xiaozhi-esp32-server-web
docker rm xiaozhi-esp32-server-web
docker stop xiaozhi-esp32-server-db
docker rm xiaozhi-esp32-server-db
docker stop xiaozhi-esp32-server-redis
docker rm xiaozhi-esp32-server-redis
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. 运行程序
执行以下命令启动新版本容器
```
docker compose -f docker-compose_all.yml up -d
```
执行完后,再执行以下命令,查看日志信息。
```
docker logs -f xiaozhi-esp32-server-web
```
当你看到输出日志时,说明你的`智控台`启动成功了。
```
2025-xx-xx 22:11:12.445 [main] INFO c.a.d.s.b.a.DruidDataSourceAutoConfigure - Init DruidDataSource
2025-xx-xx 21:28:53.873 [main] INFO xiaozhi.AdminApplication - Started AdminApplication in 16.057 seconds (process running for 17.941)
http://localhost:8002/xiaozhi/doc.html
```
请注意此刻仅是`智控台`能运行,如果8000端口`xiaozhi-esp32-server`报错,先不要理会。
这时,你需要使用浏览器,打开`智控台`,链接:http://127.0.0.1:8002 ,注册第一个用户。第一个用户即是超级管理员,以后的用户都是普通用户。普通用户只能绑定设备和配置智能体;超级管理员可以进行模型管理、用户管理、参数配置等功能。
接下来要做三件重要的事情:
### 第一件重要的事情
使用超级管理员账号,登录智控台,在顶部菜单找到`参数管理`,找到列表中第一条数据,参数编码是`server.secret`,复制它到`参数值`。
`server.secret`需要说明一下,这个`参数值`很重要,作用是让我们的`Server`端连接`manager-api`。`server.secret`是每次从零部署manager模块时,会自动随机生成的密钥。
复制`参数值`后,打开`xiaozhi-server`下的`data`目录的`.config.yaml`文件。此刻你的配置文件内容应该是这样的:
```
manager-api:
url: http://127.0.0.1:8002/xiaozhi
secret: 你的server.secret值
```
1、把你刚才从`智控台`复制过来的`server.secret`的`参数值`复制到`.config.yaml`文件里的`secret`里。
2、因为你是docker部署,把`url`改成下面的`http://xiaozhi-esp32-server-web:8002/xiaozhi`
3、因为你是docker部署,把`url`改成下面的`http://xiaozhi-esp32-server-web:8002/xiaozhi`
4、因为你是docker部署,把`url`改成下面的`http://xiaozhi-esp32-server-web:8002/xiaozhi`
类似这样的效果
```
manager-api:
url: http://xiaozhi-esp32-server-web:8002/xiaozhi
secret: 12345678-xxxx-xxxx-xxxx-123456789000
```
保存好后,继续往下做第二件重要的事情
### 第二件重要的事情
使用超级管理员账号,登录智控台,在顶部菜单找到`模型配置`,然后在左侧栏点击`大语言模型`,找到第一条数据`智谱AI`,点击`修改`按钮,
弹出修改框后,将你注册到的`智谱AI`的密钥填写到`API密钥`中。然后点击保存。
## 5.重启xiaozhi-esp32-server
接下来打开命令行工具,使用`终端`或`命令行`工具 输入
```
docker restart xiaozhi-esp32-server
docker logs -f xiaozhi-esp32-server
```
如果你能看到,类似以下日志,则是Server启动成功的标志。
```
25-02-23 12:01:09[core.websocket_server] - INFO - Websocket地址是 ws://xxx.xx.xx.xx:8000/xiaozhi/v1/
25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
25-02-23 12:01:09[core.websocket_server] - INFO - =======================================================
```
由于你是全模块部署,因此你有两个重要的接口需要写入到esp32中。
OTA接口:
```
http://你宿主机局域网的ip:8002/xiaozhi/ota/
```
Websocket接口:
```
ws://你宿主机的ip:8000/xiaozhi/v1/
```
### 第三件重要的事情
使用超级管理员账号,登录智控台,在顶部菜单找到`参数管理`,找到参数编码是`server.websocket`,输入你的`Websocket接口`。
使用超级管理员账号,登录智控台,在顶部菜单找到`参数管理`,找到数编码是`server.ota`,输入你的`OTA接口`。
接下来,你就可以开始操作你的esp32设备了,你可以`自行编译esp32固件`也可以配置使用`虾哥编译好的1.6.1以上版本的固件`。两个任选一个
1、 [编译自己的esp32固件](firmware-build.md)了。
2、 [基于虾哥编译好的固件配置自定义服务器](firmware-setting.md)了。
# 方式二:本地源码运行全模块
## 1.安装MySQL数据库
如果本机已经安装了MySQL,可以直接在数据库中创建名为`xiaozhi_esp32_server`的数据库。
```sql
CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
如果还没有MySQL,你可以通过docker安装mysql
```
docker run --name xiaozhi-esp32-server-db -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -e MYSQL_DATABASE=xiaozhi_esp32_server -e MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" -e TZ=Asia/Shanghai -d mysql:latest
```
## 2.安装redis
如果还没有Redis,你可以通过docker安装redis
```
docker run --name xiaozhi-esp32-server-redis -d -p 6379:6379 redis
```
## 3.运行manager-api程序
3.1 安装JDK21,设置JDK环境变量
3.2 安装Maven,设置Maven环境变量
3.3 使用Vscode编程工具,安装好Java环境相关插件
3.4 使用Vscode编程工具加载manager-api模块
在`src/main/resources/application-dev.yml`中配置数据库连接信息
```
spring:
datasource:
username: root
password: 123456
```
在`src/main/resources/application-dev.yml`中配置Redis连接信息
```
spring:
data:
redis:
host: localhost
port: 6379
password:
database: 0
```
3.5 运行主程序
本项目为SpringBoot项目,启动方式为:
打开`Application.java`运行`Main`方法启动
```
路径地址:
src/main/java/xiaozhi/AdminApplication.java
```
当你看到输出日志时,说明你的`manager-api`启动成功了。
```
2025-xx-xx 22:11:12.445 [main] INFO c.a.d.s.b.a.DruidDataSourceAutoConfigure - Init DruidDataSource
2025-xx-xx 21:28:53.873 [main] INFO xiaozhi.AdminApplication - Started AdminApplication in 16.057 seconds (process running for 17.941)
http://localhost:8002/xiaozhi/doc.html
```
## 4.运行manager-web程序
4.1 安装nodejs
4.2 使用Vscode编程工具加载manager-web模块
终端命令进入manager-web目录下
```
npm install
```
然后启动
```
npm run serve
```
请注意,如果你的manager-api的接口不在`http://localhost:8002`,请在开发时,修改
`main/manager-web/.env.development`中的路径
运行成功后,你需要使用浏览器,打开`智控台`,链接:http://127.0.0.1:8001 ,注册第一个用户。第一个用户即是超级管理员,以后的用户都是普通用户。普通用户只能绑定设备和配置智能体;超级管理员可以进行模型管理、用户管理、参数配置等功能。
重要:注册成功后,使用超级管理员账号,登录智控台,在顶部菜单找到`模型配置`,然后在左侧栏点击`大语言模型`,找到第一条数据`智谱AI`,点击`修改`按钮,
弹出修改框后,将你注册到的`智谱AI`的密钥填写到`API密钥`中。然后点击保存。
重要:注册成功后,使用超级管理员账号,登录智控台,在顶部菜单找到`模型配置`,然后在左侧栏点击`大语言模型`,找到第一条数据`智谱AI`,点击`修改`按钮,
弹出修改框后,将你注册到的`智谱AI`的密钥填写到`API密钥`中。然后点击保存。
重要:注册成功后,使用超级管理员账号,登录智控台,在顶部菜单找到`模型配置`,然后在左侧栏点击`大语言模型`,找到第一条数据`智谱AI`,点击`修改`按钮,
弹出修改框后,将你注册到的`智谱AI`的密钥填写到`API密钥`中。然后点击保存。
## 5.安装Python环境
本项目使用`conda`管理依赖环境。如果不方便安装`conda`,需要根据实际的操作系统安装好`libopus`和`ffmpeg`。
如果确定使用`conda`,则安装好后,开始执行以下命令。
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
![conda_prompt](./images/conda_env_1.png)
运行之后,如果你能看到命令行窗口前面有一个(base)字样,说明你成功进入了`conda`环境。那么你就可以执行以下命令了。
![conda_env](./images/conda_env_2.png)
```
conda remove -n xiaozhi-esp32-server --all -y
conda create -n xiaozhi-esp32-server python=3.10 -y
conda activate xiaozhi-esp32-server
# 添加清华源通道
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
conda install libopus -y
conda install ffmpeg -y
# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装
conda install libiconv -y
```
请注意,以上命令,不是一股脑执行就成功的,你需要一步步执行,每一步执行完后,都检查一下输出的日志,查看是否成功。
## 6.安装本项目依赖
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
你可以用浏览器打开这个地址`https://github.com/xinnan-tech/xiaozhi-esp32-server.git`
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`xiaozhi-esp32-server-main`
你需要把它重命名成`xiaozhi-esp32-server`,在这个文件里,进入到`main`文件夹,再进入到`xiaozhi-server`,好了请记住这个目录`xiaozhi-server`。
```
# 继续使用conda环境
conda activate xiaozhi-esp32-server
# 进入到你的项目根目录,再进入main/xiaozhi-server
cd main/xiaozhi-server
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip install -r requirements.txt
```
### 7.下载语音识别模型文件
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
文件放在`models/SenseVoiceSmall`
目录下。下面两个下载路线任选一个。
- 线路一:阿里魔搭下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
`qvna`
## 8.配置项目文件
使用超级管理员账号,登录智控台 ,在顶部菜单找到`参数管理`,找到列表中第一条数据,参数编码是`server.secret`,复制它到`参数值`。
`server.secret`需要说明一下,这个`参数值`很重要,作用是让我们的`Server`端连接`manager-api`。`server.secret`是每次从零部署manager模块时,会自动随机生成的密钥。
如果你的`xiaozhi-server`目录没有`data`,你需要创建`data`目录。
如果你的`data`下面没有`.config.yaml`文件,你可以把`xiaozhi-server`目录下的`config_from_api.yaml`文件复制到`data`,并重命名为`.config.yaml`
复制`参数值`后,打开`xiaozhi-server`下的`data`目录的`.config.yaml`文件。此刻你的配置文件内容应该是这样的:
```
manager-api:
url: http://127.0.0.1:8002/xiaozhi
secret: 你的server.secret值
```
把你刚才从`智控台`复制过来的`server.secret`的`参数值`复制到`.config.yaml`文件里的`secret`里。
类似这样的效果
```
manager-api:
url: http://127.0.0.1:8002/xiaozhi
secret: 12345678-xxxx-xxxx-xxxx-123456789000
```
## 9.运行项目
```
# 确保在xiaozhi-server目录下执行
conda activate xiaozhi-esp32-server
python app.py
```
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
```
25-02-23 12:01:09[core.websocket_server] - INFO - Server is running at ws://xxx.xx.xx.xx:8000/xiaozhi/v1/
25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
25-02-23 12:01:09[core.websocket_server] - INFO - =======================================================
```
由于你是全模块部署,因此你有两个重要的接口。
OTA接口:
```
http://你电脑局域网的ip:8002/xiaozhi/ota/
```
Websocket接口:
```
ws://你电脑局域网的ip:8000/xiaozhi/v1/
```
请你务必把以上两个接口地址写入到智控台中:他们将会影响websocket地址发放和自动升级功能。
1、使用超级管理员账号,登录智控台,在顶部菜单找到`参数管理`,找到参数编码是`server.websocket`,输入你的`Websocket接口`。
2、使用超级管理员账号,登录智控台,在顶部菜单找到`参数管理`,找到数编码是`server.ota`,输入你的`OTA接口`。
接下来,你就可以开始操作你的esp32设备了,你可以`自行编译esp32固件`也可以配置使用`虾哥编译好的1.6.1以上版本的固件`。两个任选一个
1、 [编译自己的esp32固件](firmware-build.md)了。
2、 [基于虾哥编译好的固件配置自定义服务器](firmware-setting.md)了。
# 常见问题
以下是一些常见问题,供参考:
1、[为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)<br/>
2、[为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)<br/>
3、[TTS 经常失败,经常超时](./FAQ.md)<br/>
4、[使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)<br/>
5、[如何提高小智对话响应速度?](./FAQ.md)<br/>
6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)<br/>
## 部署相关教程
1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)<br/>
2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)<br/>
3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)<br/>
## 拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)<br/>
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)<br/>
3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)<br/>
4、[如何部署MCP接入点](./mcp-endpoint-enable.md)<br/>
5、[如何接入MCP接入点](./mcp-endpoint-integration.md)<br/>
6、[如何开启声纹识别](./voiceprint-integration.md)<br/>
7、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
8、[天气插件使用指南](./weather-integration.md)<br/>
## 语音克隆、本地语音部署相关教程
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
2、[如何部署集成index-tts本地语音](./index-stream-integration.md)<br/>
3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)<br/>
4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)<br/>
## 性能测试教程
1、[各组件速度测试指南](./performance_tester.md)<br/>
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)<br/>

View file

@ -1,107 +0,0 @@
# 常见问题 ❓
### 1、为什么我说的话,小智识别出来很多韩文、日文、英文?🇰🇷
建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt`
文件,如果没有就要下载,查看这里[下载语音识别模型文件](Deployment.md#模型文件)
### 2、为什么会出现"TTS 任务出错 文件不存在"?📁
建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。
如果没有安装,就安装
```
conda install conda-forge::libopus
conda install conda-forge::ffmpeg
```
### 3、TTS 经常失败,经常超时 ⏰
建议:如果 `EdgeTTS` 经常失败,请先检查是否使用了代理(梯子)。如果使用了,请尝试关闭代理后再试;
如果用的是火山引擎的豆包 TTS,经常失败时建议使用付费版本,因为测试版本仅支持 2 个并发。
### 4、使用Wifi能连接自建服务器,但是4G模式却接不上 🔐
原因:虾哥的固件,4G模式需要使用安全连接。
解决方法:目前有两种方法可以解决。任选一种:
1、改代码。参考这个视频解决 https://www.bilibili.com/video/BV18MfTYoE85
2、使用nginx配置ssl证书。参考教程 https://icnt94i5ctj4.feishu.cn/docx/GnYOdMNJOoRCljx1ctecsj9cnRe
### 5、如何提高小智对话响应速度? ⚡
本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决"跑得动"的问题,再优化"跑得快"。
如需提升响应速度,可尝试更换各组件。自`0.5.2`版本起,项目支持流式配置,相比早期版本,响应速度提升约`2.5秒`,显著改善用户体验。
| 模块名称 | 入门全免费设置 | 流式配置 |
|:---:|:---:|:---:|
| ASR(语音识别) | FunASR(本地) | 👍XunfeiStreamASR(讯飞流式) |
| LLM(大模型) | glm-4-flash(智谱) | 👍qwen-flash(阿里百炼) |
| VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) |
| TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) |
| Intent(意图识别) | function_call(函数调用) | function_call(函数调用) |
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) |
如果您关心各组件的耗时,请查阅[小智各组件性能测试报告](https://github.com/xinnan-tech/xiaozhi-performance-research),可按报告中的测试方法在您的环境中实际测试。
### 6、我说话很慢,停顿时小智老是抢话 🗣️
建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`):
```yaml
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大
```
### 7、部署相关教程
1、[如何进行最简化部署](./Deployment.md)<br/>
2、[如何进行全模块部署](./Deployment_all.md)<br/>
3、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)<br/>
4、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)<br/>
5、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)<br/>
6、[修改代码后怎么编译自己的Docker镜像](./docker-build.md)<br/>
### 8、编译固件相关教程
1、[如何自己编译小智固件](./firmware-build.md)<br/>
2、[如何基于虾哥编译好的固件修改OTA地址](./firmware-setting.md)<br/>
3、[单模块部署如何配置固件OTA自动升级](./ota-upgrade-guide.md)<br/>
### 9、拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)<br/>
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)<br/>
3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)<br/>
4、[如何部署MCP接入点](./mcp-endpoint-enable.md)<br/>
5、[如何接入MCP接入点](./mcp-endpoint-integration.md)<br/>
6、[MCP方法如何获取设备信息](./mcp-get-device-info.md)<br/>
7、[如何开启声纹识别](./voiceprint-integration.md)<br/>
8、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
9、[知识库ragflow集成指南](./ragflow-integration.md)<br/>
10、[如何部署上下文源](./context-provider-integration.md)<br/>
11、[如何集成PowerMem智能记忆](./powermem-integration.md)<br/>
12、[如何配置天气插件查询天气](./weather-integration.md)<br/>
13、[如何开启设备呼叫插件](./device-call-guide.md)<br/>
14、[如何开启联网搜索功能](./web-search-integration.md)<br/>
### 10、数字人相关教程
1、[数字人digital-human启动方法](./digital-human-wakeword.md)<br/>
2、[如何在N100迷你主机上部署数字人digital-human](./all-in-one-digital-human-setup.md)<br/>
### 11、语音克隆、本地语音部署相关教程
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
2、[如何部署集成index-tts本地语音](./index-stream-integration.md)<br/>
3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)<br/>
4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)<br/>
### 12、性能测试教程
1、[各组件速度测试指南](./performance_tester.md)<br/>
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)<br/>
### 13、更多问题,可联系我们反馈 💬
可以在[issues](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues)提交您的问题。

111
docs/README.md Normal file
View file

@ -0,0 +1,111 @@
# 📚 Xiaozhi ESP32 Server Documentation
Welcome to the comprehensive documentation for Xiaozhi ESP32 Server - your gateway to building intelligent voice-controlled ESP32 devices.
## 🚀 Quick Start
New to Xiaozhi? Start here for a quick 5-minute setup:
👉 **[Get Started in 5 Minutes](getting-started/quick-start.md)**
## 📖 Documentation Sections
### 🎯 Getting Started
Perfect for newcomers - understand what Xiaozhi is and get your first device working.
- **[Overview](getting-started/overview.md)** - What is Xiaozhi and what can it do?
- **[Prerequisites](getting-started/prerequisites.md)** - System requirements and what you'll need
- **[Quick Start](getting-started/quick-start.md)** - Get up and running in 5 minutes
- **[First Device](getting-started/first-device.md)** - Connect your first ESP32 device
### 🛠️ Installation
Choose your preferred installation method and get Xiaozhi running.
- **[Docker Installation](installation/docker.md)** - Recommended for most users
- **[Local Installation](installation/local.md)** - Install directly on your system
- **[Installation Troubleshooting](support/troubleshooting.md)** - Common installation issues
### ⚙️ Configuration
Configure Xiaozhi to work with your preferred AI providers and settings.
- **[Basic Setup](configuration/basic-setup.md)** - Essential configuration
- **[AI Providers](configuration/providers.md)** - Set up OpenAI, LMStudio, Whisper, etc.
- **[Advanced Settings](configuration/advanced.md)** - Fine-tune your setup
- **[Configuration Examples](configuration/examples.md)** - Real-world examples
### 🔧 Hardware
Everything about ESP32 devices, firmware, and hardware setup.
- **[Supported Devices](hardware/supported-devices.md)** - Compatible ESP32 devices
- **[Firmware Compilation](hardware/firmware.md)** - Build custom firmware
- **[Device Flashing](hardware/flashing.md)** - Flash firmware to your device
- **[Hardware Troubleshooting](hardware/troubleshooting.md)** - Hardware-specific issues
### ✨ Features
Explore Xiaozhi's capabilities and how to use them.
- **[Voice Interaction](features/voice-interaction.md)** - Speech recognition and synthesis
- **[Integrations](features/integrations.md)** - Third-party service integrations
- **[Plugin System](features/plugins.md)** - Extend functionality with plugins
- **[API Reference](features/api.md)** - Programmatic access to Xiaozhi
### 📋 Guides
Step-by-step guides for specific use cases and integrations.
- **[HomeAssistant Integration](guides/homeassistant.md)** - Connect to HomeAssistant
- **[MQTT Gateway](guides/mqtt.md)** - Set up MQTT communication
- **[Vision Capabilities](guides/vision.md)** - Enable image recognition
- **[Plugin Development](features/plugins.md)** - Create your own plugins
### 📚 Reference
Complete technical documentation for developers and advanced users.
- **[API Documentation](features/api.md)** - Complete API reference
- **[Configuration Reference](reference/configuration.md)** - All configuration options
- **[Communication Protocols](reference/protocols.md)** - ESP32 communication details
- **[Changelog](reference/changelog.md)** - Version history and changes
### 🆘 Support
Get help when you need it.
- **[FAQ](support/faq.md)** - Frequently asked questions
- **[Troubleshooting](support/troubleshooting.md)** - Problem-solving guide
- **[Community](support/community.md)** - Community resources and support
- **[Contributing](support/contributing.md)** - How to contribute to the project
## 🎯 Popular Use Cases
### 🏠 Smart Home Assistant
Transform your ESP32 into a voice-controlled smart home hub that integrates with HomeAssistant, MQTT, and other home automation systems.
### 🎮 Voice-Controlled Projects
Build voice-controlled robots, IoT devices, or interactive projects using ESP32's capabilities.
### 🔬 Educational Projects
Learn about AI, voice recognition, and IoT development through hands-on projects.
### 🏢 Professional IoT Solutions
Deploy Xiaozhi in professional environments for voice-controlled automation and monitoring.
## 🆘 Need Help?
- **Stuck?** Check our [Troubleshooting Guide](support/troubleshooting.md)
- **Questions?** Browse our [FAQ](support/faq.md)
- **Community?** Join our [Community](support/community.md)
- **Issues?** Report them on [GitHub](https://github.com/lapy/xiaozhi-esp32-server/issues)
## 🔄 Keep Updated
- **Latest Version**: Check our [Releases](https://github.com/lapy/xiaozhi-esp32-server/releases)
- **News**: Follow our [GitHub Discussions](https://github.com/lapy/xiaozhi-esp32-server/discussions)
- **Contributing**: See how to [Contribute](support/contributing.md)
---
## ⚠️ Important Note
This is a Western adaptation of the original [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server) project. All credits for the original excellent work go to the xinnan-tech team. This port removes Chinese AI providers and infrastructure dependencies, replacing them with Western alternatives while preserving the core architecture and functionality.
---
*Happy building! 🚀*

View file

@ -1,44 +0,0 @@
# 阿里云短信集成指南
登录阿里云控制台,进入“短信服务”页面:https://dysms.console.aliyun.com/overview
## 第一步 添加签名
![步骤](images/alisms/sms-01.png)
![步骤](images/alisms/sms-02.png)
以上步骤,会得到签名,请把它写入到智控台参数,`aliyun.sms.sign_name`
## 第二步 添加模版
![步骤](images/alisms/sms-11.png)
以上步骤,会得到模版code,请把它写入到智控台参数,`aliyun.sms.sms_code_template_code`
注意,签名要等7个工作日,等运营商报备成功后才能发送成功。
注意,签名要等7个工作日,等运营商报备成功后才能发送成功。
注意,签名要等7个工作日,等运营商报备成功后才能发送成功。
可以等报备成功后,再继续往下操作。
## 第三步 创建短信账户和开通权限
登录阿里云控制台,进入“访问控制”页面:https://ram.console.aliyun.com/overview?activeTab=overview
![步骤](images/alisms/sms-21.png)
![步骤](images/alisms/sms-22.png)
![步骤](images/alisms/sms-23.png)
![步骤](images/alisms/sms-24.png)
![步骤](images/alisms/sms-25.png)
以上步骤,会得到access_key_id和access_key_secret,请把它写入到智控台参数,`aliyun.sms.access_key_id`、`aliyun.sms.access_key_secret`
## 第四步 启动手机注册功能
1、正常来说,以上信息都填完后,会有这个效果,如果没有,可能缺少了某个步骤
![步骤](images/alisms/sms-31.png)
2、开启允许非管理员用户可注册,将参数`server.allow_user_register`设置成`true`
3、开启手机注册功能,将参数`server.enable_mobile_register`设置成`true`
![步骤](images/alisms/sms-32.png)

View file

@ -0,0 +1,619 @@
# ⚙️ Advanced Configuration
This guide covers advanced configuration options for fine-tuning Xiaozhi ESP32 Server performance, security, and functionality.
## 🎯 Advanced Configuration Overview
Advanced configuration allows you to:
- **Optimize performance** for your specific use case
- **Configure security** settings and authentication
- **Set up custom plugins** and integrations
- **Fine-tune AI models** and parameters
- **Configure logging** and monitoring
## 🔧 Performance Optimization
### **Streaming Configuration**
Enable streaming for faster response times:
```yaml
# Enable streaming for all components
streaming:
enabled: true
buffer_size: 1024
chunk_size: 512
# Component-specific streaming
ASR:
WhisperASR:
type: whisper
model_name: base
streaming: true
chunk_length: 30 # Process audio in 30-second chunks
overlap: 2 # 2-second overlap between chunks
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
streaming: true
temperature: 0.7
max_tokens: 1000
timeout: 30
```
### **Model Optimization**
#### **GPU Acceleration**
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base
device: cuda # Use GPU acceleration
compute_type: float16 # Use half precision for speed
batch_size: 4 # Process multiple audio chunks
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
gpu_layers: 35 # Number of layers to offload to GPU
context_length: 4096 # Context window size
```
#### **Model Caching**
```yaml
# Enable model caching for faster startup
model_cache:
enabled: true
cache_dir: models/cache/
max_cache_size: 5000 # MB
cleanup_interval: 3600 # seconds
```
### **Audio Processing Optimization**
```yaml
# Audio processing settings
audio:
sample_rate: 16000 # Standard sample rate
channels: 1 # Mono audio
bit_depth: 16 # 16-bit audio
buffer_size: 4096 # Audio buffer size
chunk_size: 1024 # Processing chunk size
# VAD optimization
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700
pre_padding_ms: 300
post_padding_ms: 300
# Advanced VAD settings
window_size: 512
hop_length: 256
min_speech_duration_ms: 250
max_speech_duration_ms: 30000
```
## 🔐 Security Configuration
### **API Authentication**
```yaml
# API security settings
security:
# Enable API key authentication
api_auth:
enabled: true
api_key: your-secure-api-key-here
header_name: X-API-Key
# Rate limiting
rate_limit:
enabled: true
requests_per_minute: 60
burst_size: 10
# CORS settings
cors:
enabled: true
allowed_origins:
- "http://localhost:3000"
- "https://yourdomain.com"
allowed_methods:
- GET
- POST
- PUT
- DELETE
allowed_headers:
- Content-Type
- Authorization
- X-API-Key
```
### **WebSocket Security**
```yaml
# WebSocket security
websocket:
# Enable SSL/TLS
ssl:
enabled: true
cert_file: /path/to/cert.pem
key_file: /path/to/key.pem
# Authentication
auth:
enabled: true
token_expiry: 3600 # 1 hour
refresh_token_expiry: 86400 # 24 hours
# Connection limits
max_connections: 100
max_connections_per_ip: 10
connection_timeout: 300 # 5 minutes
```
### **Data Encryption**
```yaml
# Data encryption settings
encryption:
# Encrypt stored data
storage:
enabled: true
algorithm: AES-256-GCM
key_file: /path/to/encryption.key
# Encrypt audio data
audio:
enabled: true
algorithm: AES-128-CBC
key_rotation: 86400 # Rotate keys daily
```
## 🔌 Plugin Configuration
### **Custom Plugin Development**
```yaml
# Plugin system configuration
plugins:
enabled: true
plugin_dir: plugins/
auto_load: true
# Plugin-specific settings
weather:
api_key: your-weather-api-key
units: metric
cache_duration: 300
news:
api_key: your-news-api-key
sources: ["bbc", "cnn", "reuters"]
max_articles: 10
smart_home:
homeassistant_url: http://homeassistant.local:8123
api_key: your-ha-api-key
entities:
- light.living_room
- switch.kitchen
- sensor.temperature
```
### **Function Calling Configuration**
```yaml
# Function calling settings
function_calling:
enabled: true
# Available functions
functions:
- name: get_weather
description: Get current weather information
parameters:
location:
type: string
description: City name or coordinates
required: true
- name: control_light
description: Control smart home lights
parameters:
entity_id:
type: string
description: HomeAssistant entity ID
required: true
action:
type: string
enum: [on, off, toggle]
required: true
```
## 📊 Monitoring and Logging
### **Logging Configuration**
```yaml
# Logging settings
logging:
level: INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# Log files
files:
main: logs/xiaozhi.log
error: logs/error.log
access: logs/access.log
# Log rotation
rotation:
max_size: 10MB
backup_count: 5
when: midnight
# Component-specific logging
components:
ASR:
level: DEBUG
file: logs/asr.log
LLM:
level: INFO
file: logs/llm.log
TTS:
level: INFO
file: logs/tts.log
```
### **Performance Monitoring**
```yaml
# Performance monitoring
monitoring:
enabled: true
# Metrics collection
metrics:
response_time: true
memory_usage: true
cpu_usage: true
audio_processing_time: true
model_inference_time: true
# Health checks
health_checks:
enabled: true
interval: 30 # seconds
timeout: 10 # seconds
checks:
- name: database
type: database
query: "SELECT 1"
- name: redis
type: redis
command: "PING"
- name: ai_models
type: model_health
models: [ASR, LLM, TTS]
```
### **Alerting Configuration**
```yaml
# Alerting settings
alerts:
enabled: true
# Email alerts
email:
smtp_server: smtp.gmail.com
smtp_port: 587
username: your-email@gmail.com
password: your-app-password
recipients:
- admin@yourdomain.com
# Webhook alerts
webhooks:
- name: slack
url: https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK
events: [error, warning, critical]
- name: discord
url: https://discord.com/api/webhooks/YOUR/DISCORD/WEBHOOK
events: [error, critical]
# Alert conditions
conditions:
- name: high_response_time
metric: response_time
threshold: 5.0 # seconds
operator: greater_than
- name: low_memory
metric: memory_usage
threshold: 90 # percentage
operator: greater_than
```
## 🌐 Network Configuration
### **Proxy Settings**
```yaml
# Network proxy configuration
network:
# HTTP proxy
http_proxy:
enabled: true
host: proxy.company.com
port: 8080
username: proxy_user
password: proxy_password
# HTTPS proxy
https_proxy:
enabled: true
host: proxy.company.com
port: 8080
username: proxy_user
password: proxy_password
# Proxy bypass
no_proxy:
- localhost
- 127.0.0.1
- *.local
- 192.168.*
```
### **Load Balancing**
```yaml
# Load balancing configuration
load_balancer:
enabled: true
# AI model load balancing
ai_models:
ASR:
strategy: round_robin
instances:
- url: http://asr-1:8000
weight: 1
- url: http://asr-2:8000
weight: 1
LLM:
strategy: least_connections
instances:
- url: http://llm-1:8000
weight: 2
- url: http://llm-2:8000
weight: 1
# Health checks
health_check:
interval: 30
timeout: 10
retries: 3
```
## 🔄 Backup and Recovery
### **Configuration Backup**
```yaml
# Backup configuration
backup:
enabled: true
# Backup schedule
schedule:
daily: true
time: "02:00" # 2 AM
retention_days: 30
# Backup locations
locations:
- type: local
path: /backups/xiaozhi/
- type: s3
bucket: xiaozhi-backups
region: us-west-2
access_key: your-access-key
secret_key: your-secret-key
# Backup content
content:
config_files: true
model_files: true
database: true
logs: true
audio_cache: false # Skip large audio files
```
### **Disaster Recovery**
```yaml
# Disaster recovery settings
disaster_recovery:
enabled: true
# Recovery procedures
procedures:
- name: full_restore
description: Complete system restore
steps:
- restore_config
- restore_database
- restore_models
- restart_services
- name: config_only
description: Restore configuration only
steps:
- restore_config
- restart_services
# Recovery testing
testing:
enabled: true
schedule: weekly
test_restore: true
```
## 🎯 Environment-Specific Configuration
### **Development Environment**
```yaml
# Development settings
environment: development
# Development-specific overrides
development:
debug: true
hot_reload: true
mock_ai_services: true
reduced_logging: false
# Development AI providers
ASR:
MockASR:
type: mock
response_delay: 0.5
LLM:
MockLLM:
type: mock
response: "This is a mock response for development"
```
### **Production Environment**
```yaml
# Production settings
environment: production
# Production-specific overrides
production:
debug: false
hot_reload: false
mock_ai_services: false
reduced_logging: true
# Production optimizations
performance:
enable_caching: true
enable_compression: true
enable_monitoring: true
# Security hardening
security:
strict_cors: true
rate_limiting: true
input_validation: true
```
## 🛠️ Troubleshooting Advanced Issues
### **Performance Issues**
#### **Slow Response Times**
```yaml
# Optimize for speed
performance:
streaming: true
caching: true
gpu_acceleration: true
model_optimization: true
```
#### **High Memory Usage**
```yaml
# Optimize memory usage
memory:
model_cache_size: 1000 # MB
audio_buffer_size: 2048 # samples
max_concurrent_requests: 5
```
### **Security Issues**
#### **Authentication Failures**
```yaml
# Debug authentication
security:
debug_auth: true
log_auth_attempts: true
auth_timeout: 30
```
#### **SSL/TLS Issues**
```yaml
# SSL debugging
ssl:
debug: true
verify_certificates: true
cipher_suites: ["TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256"]
```
## 🎯 Next Steps
After advanced configuration:
1. **[Configuration Examples](examples.md)** - Real-world configuration examples
2. **[Performance Tuning](../guides/performance.md)** - Optimize for your use case
3. **[Security Hardening](../guides/security.md)** - Secure your deployment
4. **[Monitoring Setup](../guides/monitoring.md)** - Set up comprehensive monitoring
## 🆘 Need Help?
- **Configuration Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Performance Questions?** See [Performance Guide](../guides/performance.md)
- **Security Concerns?** Review [Security Guide](../guides/security.md)
---
## 🎯 Quick Reference
### **Performance Optimization**
```yaml
streaming: true
gpu_acceleration: true
model_caching: true
```
### **Security Essentials**
```yaml
api_auth: true
ssl_enabled: true
rate_limiting: true
```
### **Monitoring Setup**
```yaml
logging: INFO
metrics: true
health_checks: true
```
---
**Your advanced configuration is ready! 🎉**
👉 **[Next: Configuration Examples →](examples.md)**

View file

@ -0,0 +1,324 @@
# ⚙️ Basic Configuration Setup
This guide covers the essential configuration steps to get Xiaozhi ESP32 Server running with your preferred AI providers.
## 🎯 Configuration Overview
Xiaozhi uses a modular configuration system where you can choose different AI providers for each component:
- **ASR (Speech Recognition)**: Convert speech to text
- **LLM (Large Language Model)**: Process and generate responses
- **TTS (Text-to-Speech)**: Convert text to speech
- **VLLM (Vision Language Model)**: Process images and visual content
## 📋 Prerequisites
Before configuring Xiaozhi, ensure you have:
- ✅ **Xiaozhi Server** installed and running
- ✅ **Configuration file** (`data/.config.yaml`) accessible
- ✅ **API keys** for your chosen providers
- ✅ **Model files** downloaded (for local providers)
## 🚀 Quick Configuration
### **Step 1: Access Configuration File**
**For Docker Deployment:**
```bash
# Edit the configuration file
nano xiaozhi-server/data/.config.yaml
```
**For Local Deployment:**
```bash
# Edit the configuration file
nano /path/to/xiaozhi-server/data/.config.yaml
```
### **Step 2: Basic Configuration Template**
```yaml
# Server Configuration
server:
websocket: ws://YOUR_IP:8000/xiaozhi/v1/
ota: http://YOUR_IP:8003/xiaozhi/ota/
# AI Module Selection
selected_module:
VAD: SileroVAD
ASR: WhisperASR
LLM: LMStudioLLM
VLLM: OpenAILLMVLLM
TTS: EdgeTTS
# AI Provider Configurations
ASR:
WhisperASR:
type: whisper
model_name: base
device: auto
language: null
output_dir: tmp/
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
temperature: 0.7
max_tokens: 1000
TTS:
EdgeTTS:
type: edge
voice: en-US-AriaNeural
rate: 1.0
volume: 1.0
output_dir: tmp/
# Voice Activity Detection
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700
# Memory Configuration
memory:
mem_local_short:
type: local_short
max_messages: 20
max_age_hours: 24
```
### **Step 3: Replace Placeholder Values**
1. **Replace `YOUR_IP`** with your actual server IP address
2. **Configure API keys** for cloud providers
3. **Set model paths** for local providers
4. **Adjust parameters** based on your needs
## 🔧 Provider-Specific Configuration
### **Speech Recognition (ASR)**
#### **WhisperASR (Recommended - Offline)**
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base # tiny, base, small, medium, large-v1, large-v2, large-v3
device: auto # auto, cpu, cuda
language: null # null for auto-detect, or specific language code
output_dir: tmp/
```
#### **OpenAI ASR (Cloud)**
```yaml
ASR:
OpenAIASR:
type: openai
api_key: your_openai_api_key
model: whisper-1
language: en
temperature: 0.0
```
### **Large Language Model (LLM)**
#### **LMStudioLLM (Recommended - Local)**
```yaml
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
temperature: 0.7
max_tokens: 1000
timeout: 30
```
#### **OpenAI LLM (Cloud)**
```yaml
LLM:
OpenAILLM:
type: openai
api_key: your_openai_api_key
model: gpt-4o-mini
temperature: 0.7
max_tokens: 1000
```
### **Text-to-Speech (TTS)**
#### **EdgeTTS (Recommended - Free)**
```yaml
TTS:
EdgeTTS:
type: edge
voice: en-US-AriaNeural # See available voices below
rate: 1.0 # Speech rate (0.5-2.0)
volume: 1.0 # Volume (0.0-1.0)
output_dir: tmp/
```
#### **OpenAI TTS (Cloud)**
```yaml
TTS:
OpenAITTS:
type: openai
api_key: your_openai_api_key
model: tts-1
voice: alloy # alloy, echo, fable, onyx, nova, shimmer
speed: 1.0 # Speech speed (0.25-4.0)
output_dir: tmp/
```
## 🎤 Voice Configuration
### **Available EdgeTTS Voices**
| Voice | Language | Gender | Description |
|-------|----------|--------|-------------|
| `en-US-AriaNeural` | English (US) | Female | Natural, friendly |
| `en-US-DavisNeural` | English (US) | Male | Professional, clear |
| `en-US-JennyNeural` | English (US) | Female | Warm, conversational |
| `en-US-GuyNeural` | English (US) | Male | Confident, authoritative |
| `en-GB-SoniaNeural` | English (UK) | Female | British accent |
| `en-GB-RyanNeural` | English (UK) | Male | British accent |
### **Voice Activity Detection (VAD)**
```yaml
VAD:
SileroVAD:
threshold: 0.5 # Sensitivity (0.0-1.0)
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700 # Minimum silence before stopping
pre_padding_ms: 300 # Audio before speech
post_padding_ms: 300 # Audio after speech
```
## 🧠 Memory Configuration
### **Local Short-term Memory (Recommended)**
```yaml
memory:
mem_local_short:
type: local_short
max_messages: 20 # Maximum messages to remember
max_age_hours: 24 # Maximum age of memories
cleanup_interval: 3600 # Cleanup interval in seconds
```
### **Local Long-term Memory**
```yaml
memory:
mem_local_long:
type: local_long
storage_path: data/memory/
max_entries: 1000
similarity_threshold: 0.8
```
## 🔄 Testing Configuration
### **Step 1: Restart Services**
```bash
# For Docker deployment
docker restart xiaozhi-esp32-server
# For local deployment
# Restart your Xiaozhi server process
```
### **Step 2: Check Logs**
```bash
# View server logs
docker logs -f xiaozhi-esp32-server
# Look for successful initialization messages
```
### **Step 3: Test Voice Interaction**
1. **Wake up your ESP32 device**
2. **Speak a test phrase**
3. **Check server logs** for processing steps
4. **Verify response** is generated correctly
## 🛠️ Common Configuration Issues
### **Issue: "Model not found" Error**
**Solution:** Ensure model files are downloaded and paths are correct
```bash
# Check if model directory exists
ls -la models/
```
### **Issue: "API key invalid" Error**
**Solution:** Verify API keys are correct and have proper permissions
```yaml
# Double-check API key format
api_key: sk-your-actual-api-key-here
```
### **Issue: "Connection timeout" Error**
**Solution:** Check network connectivity and service availability
```bash
# Test API endpoint
curl -H "Authorization: Bearer YOUR_API_KEY" https://api.openai.com/v1/models
```
### **Issue: "Audio file not found" Error**
**Solution:** Ensure output directories exist and are writable
```bash
# Create output directories
mkdir -p tmp/
chmod 755 tmp/
```
## 🎯 Next Steps
After basic configuration:
1. **[Advanced Configuration](advanced.md)** - Fine-tune settings
2. **[Provider Configuration](providers.md)** - Detailed provider setup
3. **[Configuration Examples](examples.md)** - Real-world examples
4. **[Testing Your Setup](../getting-started/first-device.md)** - Verify everything works
## 🆘 Need Help?
- **Configuration Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Provider Questions?** See [Provider Configuration](providers.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Essential Configuration**
```yaml
selected_module:
ASR: WhisperASR # Offline speech recognition
LLM: LMStudioLLM # Local language model
TTS: EdgeTTS # Free text-to-speech
```
### **Key Directories**
- **Models**: `models/` - AI model files
- **Data**: `data/` - Configuration and data
- **Temp**: `tmp/` - Temporary audio files
### **Important URLs**
- **WebSocket**: `ws://YOUR_IP:8000/xiaozhi/v1/`
- **OTA Interface**: `http://YOUR_IP:8003/xiaozhi/ota/`
---
**Your basic configuration is ready! 🎉**
👉 **[Next: Advanced Configuration →](advanced.md)**

View file

@ -0,0 +1,798 @@
# ⚙️ Configuration Examples
This guide provides real-world configuration examples for different use cases and scenarios.
## 🎯 Configuration Examples Overview
These examples cover:
- **Home Assistant** integration setups
- **Educational** and learning environments
- **Professional** deployment configurations
- **Development** and testing setups
- **High-performance** configurations
## 🏠 Home Assistant Integration
### **Complete Smart Home Setup**
```yaml
# Complete Home Assistant integration
server:
websocket: ws://192.168.1.100:8000/xiaozhi/v1/
ota: http://192.168.1.100:8003/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: WhisperASR
LLM: LMStudioLLM
TTS: EdgeTTS
# AI Configuration
ASR:
WhisperASR:
type: whisper
model_name: base
device: auto
language: en
output_dir: tmp/
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
temperature: 0.7
max_tokens: 1000
timeout: 30
TTS:
EdgeTTS:
type: edge
voice: en-US-AriaNeural
rate: 1.0
volume: 1.0
output_dir: tmp/
# Home Assistant Integration
homeassistant:
enabled: true
url: http://homeassistant.local:8123
api_key: your-homeassistant-api-key
entities:
lights:
- light.living_room
- light.kitchen
- light.bedroom
switches:
- switch.coffee_maker
- switch.tv_power
sensors:
- sensor.temperature
- sensor.humidity
climate:
- climate.thermostat
# Function Calling for Smart Home
function_calling:
enabled: true
functions:
- name: control_light
description: Control smart home lights
parameters:
entity_id:
type: string
description: HomeAssistant entity ID
required: true
action:
type: string
enum: [on, off, toggle, dim]
required: true
brightness:
type: integer
description: Brightness level (0-255)
required: false
- name: get_weather
description: Get current weather information
parameters:
location:
type: string
description: City name
required: true
- name: set_temperature
description: Set thermostat temperature
parameters:
temperature:
type: number
description: Temperature in Celsius
required: true
# Memory for context
memory:
mem_local_short:
type: local_short
max_messages: 30
max_age_hours: 24
# Voice Activity Detection
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 800
pre_padding_ms: 300
post_padding_ms: 300
```
### **Voice Commands for Smart Home**
```yaml
# Custom voice commands
voice_commands:
enabled: true
commands:
- pattern: "turn on the (.*) light"
function: control_light
parameters:
entity_id: "light.{1}"
action: "on"
- pattern: "turn off the (.*) light"
function: control_light
parameters:
entity_id: "light.{1}"
action: "off"
- pattern: "dim the (.*) light to (.*) percent"
function: control_light
parameters:
entity_id: "light.{1}"
action: "dim"
brightness: "{2}"
- pattern: "set temperature to (.*) degrees"
function: set_temperature
parameters:
temperature: "{1}"
- pattern: "what's the weather like"
function: get_weather
parameters:
location: "current"
```
## 🎓 Educational Environment
### **Classroom Learning Setup**
```yaml
# Educational configuration for classroom use
server:
websocket: ws://192.168.1.50:8000/xiaozhi/v1/
ota: http://192.168.1.50:8003/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: WhisperASR
LLM: OpenAILLM
TTS: EdgeTTS
# Educational AI Configuration
ASR:
WhisperASR:
type: whisper
model_name: base
device: auto
language: en
output_dir: tmp/
LLM:
OpenAILLM:
type: openai
api_key: your-openai-api-key
model: gpt-4o-mini
temperature: 0.3 # Lower temperature for more consistent responses
max_tokens: 500 # Shorter responses for educational context
timeout: 30
TTS:
EdgeTTS:
type: edge
voice: en-US-JennyNeural # Friendly, educational voice
rate: 0.9 # Slightly slower for clarity
volume: 1.0
output_dir: tmp/
# Educational plugins
plugins:
enabled: true
# Math helper
math_helper:
enabled: true
functions:
- calculate
- solve_equation
- explain_concept
# Language learning
language_learning:
enabled: true
target_language: spanish
difficulty: beginner
functions:
- translate
- practice_conversation
- grammar_check
# Science assistant
science_assistant:
enabled: true
subjects: [physics, chemistry, biology]
functions:
- explain_concept
- solve_problem
- provide_examples
# Educational memory settings
memory:
mem_local_short:
type: local_short
max_messages: 50 # More context for learning
max_age_hours: 48 # Longer memory for educational sessions
# Educational voice settings
VAD:
SileroVAD:
threshold: 0.4 # More sensitive for student questions
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 1000 # Longer pause for student thinking
pre_padding_ms: 500
post_padding_ms: 500
# Educational prompts
prompts:
system: |
You are an educational assistant designed to help students learn.
You should:
- Provide clear, step-by-step explanations
- Encourage critical thinking
- Ask follow-up questions to check understanding
- Use age-appropriate language
- Be patient and supportive
When students ask questions, break down complex topics into
manageable parts and provide examples.
user: |
I'm a student learning about {topic}. Can you help me understand
this concept and provide some examples?
```
## 🏢 Professional Deployment
### **Enterprise Configuration**
```yaml
# Professional enterprise setup
server:
websocket: wss://xiaozhi.company.com/xiaozhi/v1/
ota: https://xiaozhi.company.com/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: OpenAIASR
LLM: OpenAILLM
TTS: OpenAITTS
# Professional AI Configuration
ASR:
OpenAIASR:
type: openai
api_key: your-openai-api-key
model: whisper-1
language: en
temperature: 0.0
timeout: 30
LLM:
OpenAILLM:
type: openai
api_key: your-openai-api-key
model: gpt-4o
temperature: 0.7
max_tokens: 2000
timeout: 60
TTS:
OpenAITTS:
type: openai
api_key: your-openai-api-key
model: tts-1
voice: alloy
speed: 1.0
output_dir: tmp/
# Security Configuration
security:
api_auth:
enabled: true
api_key: your-secure-api-key
header_name: X-API-Key
rate_limit:
enabled: true
requests_per_minute: 100
burst_size: 20
cors:
enabled: true
allowed_origins:
- "https://company.com"
- "https://app.company.com"
allowed_methods: [GET, POST, PUT, DELETE]
allowed_headers: [Content-Type, Authorization, X-API-Key]
# SSL/TLS Configuration
ssl:
enabled: true
cert_file: /etc/ssl/certs/xiaozhi.crt
key_file: /etc/ssl/private/xiaozhi.key
verify_certificates: true
# Professional monitoring
monitoring:
enabled: true
metrics:
response_time: true
memory_usage: true
cpu_usage: true
error_rate: true
health_checks:
enabled: true
interval: 30
timeout: 10
alerts:
enabled: true
email:
smtp_server: smtp.company.com
username: alerts@company.com
recipients: [admin@company.com, devops@company.com]
# Professional logging
logging:
level: INFO
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
files:
main: /var/log/xiaozhi/main.log
error: /var/log/xiaozhi/error.log
access: /var/log/xiaozhi/access.log
rotation:
max_size: 100MB
backup_count: 10
when: midnight
# Professional backup
backup:
enabled: true
schedule:
daily: true
time: "03:00"
retention_days: 90
locations:
- type: s3
bucket: company-xiaozhi-backups
region: us-east-1
access_key: your-s3-access-key
secret_key: your-s3-secret-key
content:
config_files: true
database: true
logs: true
audio_cache: false
# Professional memory
memory:
mem_local_short:
type: local_short
max_messages: 100
max_age_hours: 24
mem_local_long:
type: local_long
storage_path: /var/lib/xiaozhi/memory/
max_entries: 10000
similarity_threshold: 0.8
# Professional VAD
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700
pre_padding_ms: 300
post_padding_ms: 300
```
## 🚀 High-Performance Configuration
### **Optimized for Speed**
```yaml
# High-performance configuration
server:
websocket: ws://192.168.1.200:8000/xiaozhi/v1/
ota: http://192.168.1.200:8003/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: WhisperASR
LLM: LMStudioLLM
TTS: EdgeTTS
# High-performance AI Configuration
ASR:
WhisperASR:
type: whisper
model_name: tiny # Fastest model
device: cuda # GPU acceleration
compute_type: float16 # Half precision
language: en
output_dir: tmp/
streaming: true
chunk_length: 10 # Smaller chunks for faster processing
LLM:
LMStudioLLM:
type: lmstudio
base_url: http://localhost:1234/v1
model_name: llama-3.1:8b
temperature: 0.7
max_tokens: 500 # Shorter responses for speed
timeout: 15 # Shorter timeout
streaming: true
gpu_layers: 35 # Maximum GPU offload
context_length: 2048 # Smaller context for speed
TTS:
EdgeTTS:
type: edge
voice: en-US-AriaNeural
rate: 1.2 # Faster speech
volume: 1.0
output_dir: tmp/
streaming: true
# Performance optimizations
performance:
streaming: true
caching: true
gpu_acceleration: true
model_optimization: true
# Model caching
model_cache:
enabled: true
cache_dir: models/cache/
max_cache_size: 2000 # MB
cleanup_interval: 1800 # 30 minutes
# Audio processing optimization
audio:
sample_rate: 16000
channels: 1
bit_depth: 16
buffer_size: 2048 # Smaller buffer for lower latency
chunk_size: 512 # Smaller chunks
# Optimized VAD
VAD:
SileroVAD:
threshold: 0.6 # Higher threshold for faster detection
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 500 # Shorter silence detection
pre_padding_ms: 200
post_padding_ms: 200
window_size: 256 # Smaller window
hop_length: 128 # Smaller hop
# Optimized memory
memory:
mem_local_short:
type: local_short
max_messages: 10 # Fewer messages for speed
max_age_hours: 12 # Shorter memory
cleanup_interval: 1800 # More frequent cleanup
# Performance monitoring
monitoring:
enabled: true
metrics:
response_time: true
memory_usage: true
cpu_usage: true
gpu_usage: true
audio_processing_time: true
model_inference_time: true
# Real-time monitoring
real_time:
enabled: true
update_interval: 1 # 1 second updates
metrics_endpoint: /metrics
```
## 🧪 Development and Testing
### **Development Environment**
```yaml
# Development configuration
environment: development
server:
websocket: ws://localhost:8000/xiaozhi/v1/
ota: http://localhost:8003/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: MockASR
LLM: MockLLM
TTS: MockTTS
# Development AI Configuration (Mock services)
ASR:
MockASR:
type: mock
response_delay: 0.5
responses:
- "Hello world"
- "This is a test"
- "Mock speech recognition"
LLM:
MockLLM:
type: mock
response: "This is a mock response for development testing"
response_delay: 1.0
TTS:
MockTTS:
type: mock
response_delay: 0.5
output_file: tmp/mock_audio.wav
# Development settings
development:
debug: true
hot_reload: true
mock_ai_services: true
reduced_logging: false
# Development plugins
plugins:
enabled: true
# Test plugin
test_plugin:
enabled: true
functions:
- test_function
- mock_integration
# Development memory
memory:
mem_local_short:
type: local_short
max_messages: 5
max_age_hours: 1
# Development logging
logging:
level: DEBUG
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
files:
main: logs/dev.log
error: logs/dev_error.log
# Console logging for development
console:
enabled: true
level: DEBUG
# Development VAD
VAD:
SileroVAD:
threshold: 0.3 # More sensitive for testing
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 500
pre_padding_ms: 200
post_padding_ms: 200
```
### **Testing Configuration**
```yaml
# Testing configuration
environment: testing
server:
websocket: ws://test-server:8000/xiaozhi/v1/
ota: http://test-server:8003/xiaozhi/ota/
selected_module:
VAD: SileroVAD
ASR: TestASR
LLM: TestLLM
TTS: TestTTS
# Testing AI Configuration
ASR:
TestASR:
type: test
test_cases:
- input: "test_audio_1.wav"
output: "Hello, this is a test"
- input: "test_audio_2.wav"
output: "Testing speech recognition"
LLM:
TestLLM:
type: test
test_responses:
- input: "Hello"
output: "Hi there! How can I help you?"
- input: "What's the weather?"
output: "I can help you check the weather. What location?"
TTS:
TestTTS:
type: test
output_dir: test_output/
test_files: true
# Testing settings
testing:
enabled: true
# Test data
test_data:
audio_samples: test_data/audio/
expected_responses: test_data/responses/
test_configs: test_data/configs/
# Test execution
execution:
parallel_tests: true
test_timeout: 30
retry_failed: true
max_retries: 3
# Test reporting
reporting:
enabled: true
format: json
output_dir: test_reports/
include_metrics: true
# Testing memory
memory:
mem_local_short:
type: local_short
max_messages: 3
max_age_hours: 1
# Testing VAD
VAD:
SileroVAD:
threshold: 0.5
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700
pre_padding_ms: 300
post_padding_ms: 300
```
## 🎯 Configuration Best Practices
### **General Best Practices**
1. **Start Simple**: Begin with basic configuration and add complexity gradually
2. **Test Incrementally**: Test each component after configuration changes
3. **Monitor Performance**: Use monitoring to identify bottlenecks
4. **Backup Configurations**: Keep backups of working configurations
5. **Document Changes**: Document any custom modifications
### **Security Best Practices**
1. **Use Environment Variables**: Store sensitive data in environment variables
2. **Enable Authentication**: Always enable API authentication in production
3. **Use HTTPS/WSS**: Use secure connections for production deployments
4. **Regular Updates**: Keep all components updated
5. **Access Control**: Implement proper access controls
### **Performance Best Practices**
1. **Choose Appropriate Models**: Select models based on your performance requirements
2. **Enable Caching**: Use caching for frequently accessed data
3. **Optimize Audio Settings**: Tune audio parameters for your use case
4. **Monitor Resources**: Keep an eye on CPU, memory, and GPU usage
5. **Load Testing**: Test your configuration under expected load
## 🆘 Troubleshooting Configuration Issues
### **Common Issues and Solutions**
#### **Configuration Validation Errors**
```bash
# Validate configuration
python -m xiaozhi.config_validator --config data/.config.yaml
```
#### **Performance Issues**
```yaml
# Enable performance monitoring
monitoring:
enabled: true
metrics:
response_time: true
memory_usage: true
cpu_usage: true
```
#### **Memory Issues**
```yaml
# Optimize memory usage
memory:
mem_local_short:
max_messages: 10 # Reduce message count
max_age_hours: 12 # Reduce memory age
```
## 🎯 Next Steps
After reviewing these examples:
1. **[Basic Setup](basic-setup.md)** - Start with basic configuration
2. **[Advanced Configuration](advanced.md)** - Add advanced features
3. **[Provider Configuration](providers.md)** - Configure specific providers
4. **[Testing Your Setup](../getting-started/first-device.md)** - Verify everything works
## 🆘 Need Help?
- **Configuration Questions?** Check [Basic Setup](basic-setup.md)
- **Performance Issues?** See [Advanced Configuration](advanced.md)
- **Provider Setup?** Review [Provider Configuration](providers.md)
---
## 🎯 Quick Reference
### **Configuration Templates**
- **Home Assistant**: Complete smart home integration
- **Educational**: Classroom learning environment
- **Professional**: Enterprise deployment
- **High-Performance**: Optimized for speed
- **Development**: Testing and development
### **Key Settings**
- **ASR**: WhisperASR (offline) or OpenAIASR (cloud)
- **LLM**: LMStudioLLM (local) or OpenAILLM (cloud)
- **TTS**: EdgeTTS (free) or OpenAITTS (premium)
---
**Your configuration examples are ready! 🎉**
👉 **[Next: Provider Configuration →](providers.md)**

View file

@ -0,0 +1,457 @@
# 🤖 AI Providers Configuration
Configure your AI providers to enable speech recognition, language processing, and text-to-speech capabilities. Xiaozhi supports multiple providers for flexibility and cost optimization.
## 🎯 Provider Overview
### **AI Stack Components**
```mermaid
graph TB
A[ESP32 Device] --> B[Speech Recognition]
B --> C[Language Processing]
C --> D[Response Generation]
D --> E[Text-to-Speech]
E --> A
F[ASR Providers] --> B
G[LLM Providers] --> C
H[TTS Providers] --> E
```
### **Provider Categories**
| Category | Purpose | Examples |
|----------|---------|---------|
| **ASR** | Speech-to-Text | Whisper, OpenAI, Groq |
| **LLM** | Language Processing | OpenAI, LMStudio, Ollama |
| **TTS** | Text-to-Speech | EdgeTTS, OpenAI, Azure |
| **VLLM** | Vision Processing | OpenAI, Local Models |
## 🆓 Free Tier Setup
### **Recommended Free Configuration**
```yaml
# Free AI Stack
selected_module:
ASR: WhisperASR # Local speech recognition
LLM: LMStudioLLM # Local language model
TTS: EdgeTTS # Free text-to-speech
VLLM: OpenAILLMVLLM # OpenAI vision (optional)
```
### **WhisperASR (Speech Recognition)**
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base # Options: tiny, base, small, medium, large
device: auto # auto, cpu, cuda
language: null # null for auto-detect, or "en", "es", etc.
output_dir: tmp/
```
**Model Sizes:**
- **tiny**: ~39MB - Fastest, lowest accuracy
- **base**: ~74MB - Good balance
- **small**: ~244MB - Better accuracy
- **medium**: ~769MB - High accuracy
- **large**: ~1550MB - Best accuracy
### **LMStudioLLM (Language Model)**
```yaml
LLM:
LMStudioLLM:
type: openai
base_url: http://localhost:1234/v1
api_key: lm-studio
model_name: llama3.1:8b
```
**Setup Steps:**
1. **Download LMStudio**: [lmstudio.ai](https://lmstudio.ai)
2. **Load a model**: Download llama3.1:8b or similar
3. **Start local server**: Enable local API
4. **Configure Xiaozhi**: Use local API endpoint
### **EdgeTTS (Text-to-Speech)**
```yaml
TTS:
EdgeTTS:
type: edge_tts
voice: en-US-AriaNeural # Voice options
rate: +0% # Speech rate
pitch: +0Hz # Voice pitch
volume: +0% # Volume level
```
**Voice Options:**
- **en-US-AriaNeural**: Female, natural
- **en-US-GuyNeural**: Male, natural
- **en-US-JennyNeural**: Female, friendly
- **en-US-RyanNeural**: Male, professional
## 💎 Premium Setup
### **OpenAI Configuration**
```yaml
# Premium AI Stack
selected_module:
ASR: OpenAIASR
LLM: OpenAILLM
TTS: OpenAITTS
VLLM: OpenAILLMVLLM
```
### **OpenAI ASR**
```yaml
ASR:
OpenAIASR:
type: openai
api_key: your_openai_api_key
model_name: whisper-1
language: en
response_format: json
```
### **OpenAI LLM**
```yaml
LLM:
OpenAILLM:
type: openai
api_key: your_openai_api_key
model_name: gpt-4o-mini # Options: gpt-4o, gpt-4o-mini, gpt-3.5-turbo
temperature: 0.7
max_tokens: 1000
top_p: 1.0
```
**Model Options:**
- **gpt-4o**: Latest, most capable
- **gpt-4o-mini**: Faster, cost-effective
- **gpt-3.5-turbo**: Budget option
### **OpenAI TTS**
```yaml
TTS:
OpenAITTS:
type: openai
api_key: your_openai_api_key
model_name: tts-1 # Options: tts-1, tts-1-hd
voice: alloy # Options: alloy, echo, fable, onyx, nova, shimmer
response_format: mp3
speed: 1.0
```
## 🔧 Advanced Configurations
### **Hybrid Setup (Best of Both Worlds)**
```yaml
# Hybrid Configuration
selected_module:
ASR: WhisperASR # Local for privacy
LLM: OpenAILLM # Cloud for capability
TTS: EdgeTTS # Free for cost
```
### **Privacy-Focused Setup**
```yaml
# Complete Local Setup
selected_module:
ASR: WhisperASR # Local processing
LLM: LMStudioLLM # Local processing
TTS: EdgeTTS # Local processing
```
### **Performance-Optimized Setup**
```yaml
# High-Performance Configuration
selected_module:
ASR: OpenAIASR # Cloud for speed
LLM: OpenAILLM # Cloud for capability
TTS: OpenAITTS # Cloud for quality
```
## 🌐 Additional Providers
### **Groq (Fast LLM)**
```yaml
LLM:
GroqLLM:
type: openai
base_url: https://api.groq.com/openai/v1
api_key: your_groq_api_key
model_name: llama-3.1-70b-versatile
```
### **Ollama (Local LLM)**
```yaml
LLM:
OllamaLLM:
type: openai
base_url: http://localhost:11434/v1
api_key: ollama
model_name: llama3.1:8b
```
### **Azure Cognitive Services**
```yaml
ASR:
AzureASR:
type: azure
subscription_key: your_azure_key
region: your_azure_region
language: en-US
TTS:
AzureTTS:
type: azure
subscription_key: your_azure_key
region: your_azure_region
voice: en-US-AriaNeural
```
## ⚙️ Configuration Methods
### **Method 1: Web Interface**
1. **Open web interface**: http://localhost:8001
2. **Go to Model Configuration**
3. **Select provider type** (ASR, LLM, TTS)
4. **Configure settings** and API keys
5. **Save configuration**
### **Method 2: Configuration File**
```bash
# Edit configuration file
nano data/.config.yaml
# Add provider configuration
ASR:
WhisperASR:
type: whisper
model_name: base
LLM:
OpenAILLM:
type: openai
api_key: your_api_key
model_name: gpt-4o-mini
TTS:
EdgeTTS:
type: edge_tts
voice: en-US-AriaNeural
```
### **Method 3: Environment Variables**
```bash
# Set environment variables
export OPENAI_API_KEY=your_api_key
export GROQ_API_KEY=your_groq_key
export AZURE_SUBSCRIPTION_KEY=your_azure_key
# Restart server
docker-compose restart
```
## 🧪 Testing Providers
### **Test Speech Recognition**
```bash
# Test ASR provider
curl -X POST http://localhost:8000/api/test/asr \
-H "Content-Type: application/json" \
-d '{"audio_file": "test.wav"}'
```
### **Test Language Model**
```bash
# Test LLM provider
curl -X POST http://localhost:8000/api/test/llm \
-H "Content-Type: application/json" \
-d '{"message": "Hello, how are you?"}'
```
### **Test Text-to-Speech**
```bash
# Test TTS provider
curl -X POST http://localhost:8000/api/test/tts \
-H "Content-Type: application/json" \
-d '{"text": "Hello, this is a test."}'
```
## 💰 Cost Optimization
### **Free Tier Strategy**
```yaml
# Maximize free usage
selected_module:
ASR: WhisperASR # Completely free
LLM: LMStudioLLM # Completely free
TTS: EdgeTTS # Completely free
```
### **Hybrid Cost Strategy**
```yaml
# Balance cost and quality
selected_module:
ASR: WhisperASR # Free for privacy
LLM: OpenAILLM # Pay for capability
TTS: EdgeTTS # Free for cost
```
### **Usage Monitoring**
```bash
# Monitor API usage
curl -X GET http://localhost:8000/api/usage/stats
# Check provider status
curl -X GET http://localhost:8000/api/providers/status
```
## 🛠️ Troubleshooting
### **Common Issues**
#### **API Key Errors**
```bash
# Check API key format
echo $OPENAI_API_KEY
# Test API key
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
https://api.openai.com/v1/models
```
#### **Provider Connection Issues**
```bash
# Check provider status
curl -X GET http://localhost:8000/api/providers/health
# View provider logs
docker-compose logs xiaozhi-server | grep -i provider
```
#### **Model Loading Issues**
```bash
# Check model files
ls -la models/whisper/
ls -la models/vosk/
# Verify model integrity
python -c "import whisper; whisper.load_model('base')"
```
### **Performance Optimization**
#### **Local Model Optimization**
```yaml
# Optimize Whisper performance
ASR:
WhisperASR:
device: cuda # Use GPU if available
model_name: base # Balance speed/accuracy
language: en # Specify language for speed
```
#### **Cloud Provider Optimization**
```yaml
# Optimize OpenAI usage
LLM:
OpenAILLM:
model_name: gpt-4o-mini # Use faster model
max_tokens: 500 # Limit response length
temperature: 0.7 # Reduce randomness
```
## 🎯 Best Practices
### **Provider Selection**
1. **Start with free providers** for testing
2. **Use local providers** for privacy-sensitive applications
3. **Use cloud providers** for production and high-volume usage
4. **Mix providers** for optimal cost/performance balance
### **Configuration Management**
1. **Use environment variables** for sensitive data
2. **Version control** configuration files
3. **Test configurations** before deploying
4. **Monitor usage** and costs regularly
### **Security Considerations**
1. **Rotate API keys** regularly
2. **Use least privilege** access
3. **Monitor API usage** for anomalies
4. **Encrypt sensitive data** at rest
## 🎯 Next Steps
### **After Configuration**
1. **[Basic Setup](../configuration/basic-setup.md)** - Configure server settings
2. **[Test Voice Interaction](../features/voice-interaction.md)** - Verify everything works
3. **[Connect ESP32 Device](../getting-started/first-device.md)** - Add your first device
4. **[Advanced Configuration](../configuration/advanced.md)** - Fine-tune your setup
### **Advanced Topics**
- **[Custom Providers](../configuration/advanced.md)** - Create custom AI providers
- **[Performance Tuning](../configuration/advanced.md)** - Optimize for your use case
- **[Monitoring](../configuration/advanced.md)** - Set up monitoring and alerts
## 🆘 Need Help?
- **Configuration Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Provider Questions?** Browse [FAQ](../support/faq.md)
- **API Problems?** See [API Documentation](../reference/api.md)
---
## 🎯 Quick Reference
### **Free Providers**
- **ASR**: WhisperASR (local)
- **LLM**: LMStudioLLM (local)
- **TTS**: EdgeTTS (free)
### **Premium Providers**
- **ASR**: OpenAIASR
- **LLM**: OpenAILLM
- **TTS**: OpenAITTS
### **Configuration Files**
- **Web Interface**: http://localhost:8001
- **Config File**: `data/.config.yaml`
- **Environment**: `.env` file
---
**Your AI providers are now configured! 🎉**
👉 **[Next: Basic Setup →](../configuration/basic-setup.md)**

View file

@ -1,135 +1,145 @@
# 上下文源使用教程 # Context Provider Guide
## 概述 ## Overview
`上下文源`,就是为小智系统提示词的上下文添加【数据源】。 A context provider adds external data sources to Xiaozhi's system prompt context.
`上下文源` 在小智在唤醒那一刻,获取外部系统的数据,并将其动态注入到大模型的系统提示词(System Prompt)中。 At wake time, Xiaozhi can fetch data from external systems and inject it into the large language model's system prompt. This lets the assistant start each interaction with fresh awareness of device state, environment data, or business status.
让其做到唤醒时感知世界某个事物的状态。
它和MCP、记忆有本质的区别:`上下文源`是强制让小智感知世界的数据;`记忆(Mem)`是让他知道之前聊了什么内容;`MCP(functionc all)`是当需要调用某项能力/知识的时候使用调用。 Context providers are different from MCP and memory:
通过这个功能,在小智唤醒的一刹那,“感知”到: - `Context providers` inject wake-time context proactively.
- 人体健康传感器状态(体温、血压、血氧状态等) - `Memory` helps Xiaozhi remember prior conversations.
- 业务系统的实时数据(服务器负载、待办数据、股票信息等) - `MCP` is used when the assistant needs to actively call a tool or query a capability during the conversation.
- 任何可以通过 HTTP API 获取的文本信息
**注意**:该功能只是方便小智在唤醒的时候感知事物的状态,而如果想要小智唤醒后实时获取事物的状态,建议在此功能上再结合MCP工具的调用。 Typical use cases include:
## 工作原理 - health or wellness sensor summaries
- live business metrics such as server load, queue length, or market data
- any text payload available from an HTTP API
1. **配置源**:用户配置一个或多个 HTTP API 地址。 This feature is best for preload context. If you need Xiaozhi to fetch live data after wake-up on demand, pair it with MCP tool calls.
2. **触发请求**:当系统构建 Prompt 时,如果发现模板中包含 `{{ dynamic_context }}` 占位符,会请求所有配置的 API。
3. **自动注入**:系统会自动将 API 返回的数据格式化为 Markdown 列表,替换 `{{ dynamic_context }}` 占位符。
## 接口规范 ## How It Works
为了让小智正确解析数据,您的 API 需要满足以下规范: 1. Configure one or more HTTP API endpoints.
2. When the prompt template includes `{{ dynamic_context }}`, Xiaozhi requests those endpoints.
3. Returned data is formatted into Markdown and injected into the prompt.
- **请求方式**:`GET` ## API Requirements
- **请求头**:系统会自动添加 `device-id` 字段到 Request Header。
- **响应格式**:必须返回 JSON 格式,且包含 `code` 和 `data` 字段。
### 响应示例 To work reliably, your API should follow these rules:
- Method: `GET`
- Headers: Xiaozhi automatically sends `device-id` in the request headers
- Response format: JSON with `code` and `data`
### Response Examples
**Example 1: key/value payload**
**情况 1:返回键值对**
```json ```json
{ {
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"data": { "data": {
"客厅温度": "26℃", "Living room temperature": "26 C",
"客厅湿度": "45%", "Living room humidity": "45%",
"大门状态": "已关闭" "Front door": "Closed"
} }
} }
``` ```
*注入效果:*
Injected result:
```markdown ```markdown
<context> <context>
- **客厅温度:** 26℃ - **Living room temperature:** 26 C
- **客厅湿度:** 45% - **Living room humidity:** 45%
- **大门状态:** 已关闭 - **Front door:** Closed
</context> </context>
``` ```
**情况 2:返回列表** **Example 2: list payload**
```json ```json
{ {
"code": 0, "code": 0,
"data": [ "data": [
"您有10个待办事项", "You have 10 open tasks",
"当前汽车的行驶速度是100km每小时" "The current vehicle speed is 100 km/h"
] ]
} }
``` ```
*注入效果:*
Injected result:
```markdown ```markdown
<context> <context>
- 您有10个待办事项 - You have 10 open tasks
- 当前汽车的行驶速度是100km每小时 - The current vehicle speed is 100 km/h
</context> </context>
``` ```
## 配置指南 ## Configuration
### 方式 1:智控台配置(全模块部署) ### Option 1: Admin Console configuration
1. 登录智控台,进入**角色配置**页面。 1. Sign in to the Admin Console.
2. 找到**上下文源**配置项(点击“编辑源”按钮)。 2. Open the role or agent configuration page.
3. 点击**添加**,输入您的 API 地址。 3. Find the context provider setting and select `Edit Sources`.
4. 如果 API 需要鉴权,可以在**请求头**部分添加 `Authorization` 或其他 Header。 4. Add one or more API URLs.
5. 保存配置。 5. If your API requires authentication, add the necessary request headers.
6. Save the configuration.
### 方式 2:配置文件配置(单模块部署) ### Option 2: Config file configuration
编辑 `xiaozhi-server/data/.config.yaml` 文件,添加 `context_providers` 配置段: Edit `xiaozhi-server/data/.config.yaml` and add a `context_providers` section:
```yaml ```yaml
# 上下文源配置 # Context provider configuration
context_providers: context_providers:
- url: "http://api.example.com/data" - url: "http://api.example.com/data"
headers: headers:
Authorization: "Bearer your-token" Authorization: "Bearer your-token"
- url: "http://another-api.com/data" - url: "http://another-api.example.com/data"
``` ```
## 启用功能 ## Enabling Prompt Injection
默认情况下,系统的提示词模板文件(`data/.agent-base-prompt.txt`)中已经预置了 `{{ dynamic_context }}` 占位符,您无需手动添加。 By default, the prompt template in `data/.agent-base-prompt.txt` already contains the `{{ dynamic_context }}` placeholder, so most deployments do not need to add it manually.
**示例:** Example:
```markdown ```markdown
<context> <context>
【重要!以下信息已实时提供,无需调用工具查询,请直接使用:】 [Important: the following information has already been provided in real time. Use it directly instead of calling tools.]
- **设备ID:** {{device_id}} - **Device ID:** {{device_id}}
- **当前时间:** {{current_time}} - **Current time:** {{current_time}}
... ...
{{ dynamic_context }} {{ dynamic_context }}
</context> </context>
``` ```
**注意**:如果您不需要使用此功能,可以选择**不配置任何上下文源**,也可以从提示词模板文件中**删除** `{{ dynamic_context }}` 占位符。 If you do not want to use context providers, either leave `context_providers` unset or remove `{{ dynamic_context }}` from the prompt template.
## 附录:Mock 测试服务示例 ## Appendix: Mock Test Service
为了方便您测试和开发,我们提供了一个简单的 Python Mock Server 脚本。您可以运行此脚本在本地模拟 API 接口。 The following local mock server is useful for testing and development.
**mock_api_server.py** **mock_api_server.py**
```python ```python
import http.server import http.server
import socketserver
import json import json
from urllib.parse import urlparse, parse_qs import socketserver
from urllib.parse import parse_qs, urlparse
# 设置端口号
PORT = 8081 PORT = 8081
class MockRequestHandler(http.server.SimpleHTTPRequestHandler): class MockRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self): def do_GET(self):
# 解析路径和参数
parsed_path = urlparse(self.path) parsed_path = urlparse(self.path)
path = parsed_path.path path = parsed_path.path
query = parse_qs(parsed_path.query) query = parse_qs(parsed_path.query)
@ -137,11 +147,8 @@ class MockRequestHandler(http.server.SimpleHTTPRequestHandler):
response_data = {} response_data = {}
status_code = 200 status_code = 200
print(f"收到请求: {path}, 参数: {query}") print(f"Received request: {path}, query: {query}")
# Case 1: 模拟健康数据 (返回字典 Dict)
# 路径参数风格: /health
# device_id 从 Header 获取
if path == "/health": if path == "/health":
device_id = self.headers.get("device-id", "unknown_device") device_id = self.headers.get("device-id", "unknown_device")
print(f"device_id: {device_id}") print(f"device_id: {device_id}")
@ -149,76 +156,62 @@ class MockRequestHandler(http.server.SimpleHTTPRequestHandler):
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"data": { "data": {
"测试设备ID": device_id, "Device under test": device_id,
"心率": "80 bpm", "Heart rate": "80 bpm",
"血压": "120/80 mmHg", "Blood pressure": "120/80 mmHg",
"状态": "良好" "Status": "Good"
} }
} }
# Case 2: 模拟新闻列表 (返回列表 List)
# 无参数: /news/list
elif path == "/news/list": elif path == "/news/list":
response_data = { response_data = {
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"data": [ "data": [
"今日头条:Python 3.14 发布", "Headline: Python 3.14 released",
"科技新闻:AI 助手改变生活", "Tech news: AI assistants reshape daily life",
"本地新闻:明日有大雨,记得带伞" "Local alert: heavy rain expected tomorrow"
] ]
} }
# Case 3: 模拟天气简报 (返回字符串 String)
# 无参数: /weather/simple
elif path == "/weather/simple": elif path == "/weather/simple":
response_data = { response_data = {
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"data": "今日晴转多云,气温 20-25 度,空气质量优,适合出行。" "data": "Sunny turning partly cloudy today, 20-25 C, good air quality."
} }
# Case 4: 模拟设备详情 (Query参数风格)
# 参数风格: /device/info
# device_id 从 Header 获取
elif path == "/device/info": elif path == "/device/info":
device_id = self.headers.get("device-id", "unknown_device") device_id = self.headers.get("device-id", "unknown_device")
response_data = { response_data = {
"code": 0, "code": 0,
"msg": "success", "msg": "success",
"data": { "data": {
"查询方式": "Header参数", "Lookup mode": "Header parameter",
"设备ID": device_id, "Device ID": device_id,
"电量": "85%", "Battery": "85%",
"固件": "v2.0.1" "Firmware": "v2.0.1"
} }
} }
# Case 5: 404 Not Found
else: else:
status_code = 404 status_code = 404
response_data = {"error": "接口不存在"} response_data = {"error": "Endpoint not found"}
# 发送响应
self.send_response(status_code) self.send_response(status_code)
self.send_header('Content-type', 'application/json; charset=utf-8') self.send_header("Content-type", "application/json; charset=utf-8")
self.end_headers() self.end_headers()
self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8')) self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode("utf-8"))
# 启动服务
# 允许地址重用,防止快速重启报错
socketserver.TCPServer.allow_reuse_address = True socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(("", PORT), MockRequestHandler) as httpd: with socketserver.TCPServer(("", PORT), MockRequestHandler) as httpd:
print(f"==================================================") print("==================================================")
print(f"Mock API Server 已启动: http://localhost:{PORT}") print(f"Mock API server started: http://localhost:{PORT}")
print(f"可用接口列表:") print("Available endpoints:")
print(f"1. [字典] http://localhost:{PORT}/health") print(f"1. [Dict] http://localhost:{PORT}/health")
print(f"2. [列表] http://localhost:{PORT}/news/list") print(f"2. [List] http://localhost:{PORT}/news/list")
print(f"3. [文本] http://localhost:{PORT}/weather/simple") print(f"3. [Text] http://localhost:{PORT}/weather/simple")
print(f"4. [参数] http://localhost:{PORT}/device/info") print(f"4. [Query] http://localhost:{PORT}/device/info")
print(f"==================================================") print("==================================================")
try: try:
httpd.serve_forever() httpd.serve_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
print("\n服务已停止") print("\\nServer stopped")
``` ```

View file

@ -1,50 +0,0 @@
# 致开发者的公开信
"春江水暖鸭先知,正是河豚欲上时!"
亲爱的朋友,我是John,是一名普通公司里的Java程序员,今天,我怀着无比真挚的心情,向热爱AI技术与创新的你发出这封公开信。
半年前我看到很多优秀的项目,比如`Dify`、`Chat2DB`等人工智能相关的项目,我在想,我要是能参与这些项目多好,可惜“报国无门,空打十年代码”。
我是2025年初刷到虾哥团队的视频,我非常好奇他是怎么实现的,我想复刻他们的后端服务,打造一个低成本民用贾维斯。很可惜现在做的作品依然只是一个人工智障,它并发低、没有灵魂,响应很慢,bug很多。
虾哥团队是我们学习的对象,我很想拥有像虾哥团队一样智能的小智后端服务。但是我也能理解虾哥不开源的决定。“一花独放不是春,百花齐放春满园”,人工智能遍地开花的时代,也许就在我们这代实现,我们可以用自己的双手,实现低成本民用贾维斯。我个人认为,他能实现的,我们也能实现,只是时间问题而已,我称之为“我们的取经之路”。
那么这条取经之路,我们会遇到什么困难?我想应该不少于八十一难。这一路必然会出现各种妖怪,当然也有神仙暗中帮助我们,也有人加入取经队伍。
以上内容,如果你觉得好笑。那我也觉得非常的幸运。我能够在你人生3万多天里博你笑五秒,也算是为你做了一次贡献。
民用低成本贾维斯这个想法,会失败吗,我不知道,但是我们普通人的一生,这种失败不是很常见吗?
未来,有一点是可以确定的,就一定会有人完全复刻虾哥团队的功能,实现民用低成本贾维斯。这个项目会是我们吗?
期待与你携手前行,共创未来。
John,2025.3.11,广州
# 附 开发贡献指南
## 项目目标
1. **民用低成本贾维斯解决方案**
2. **智能联动周边硬件的解决方案**
## 加入我们
我们热忱欢迎志同道合的朋友加入,共同为项目贡献力量。您可在[这个链接](https://github.com/users/xinnan-tech/projects/3)查看我们近期要实现的功能,功能列表中还没指派相关人员处理的,正是急需您的参与。参与方式如下:
### 1、成为普通贡献者
Fork 项目,提交 PR,由开发者审核后合入主分支。
### 2、成为开发者
当你累计提交 3 次有效 PR 后,可以联系群主申请成为开发者,群主将邀请你加入独立的开发者群,共同探讨项目未来。
## 开发者开发流程
1. **创建新分支**
每个功能点请以新分支方式开发,分支名称应简洁明了,让人一眼看出所实现的功能,避免功能撞车。
2. **提交 PR 审核**
功能开发完成后,请在 GitHub 上提交 PR,由其他开发者审核,审核通过后合并入主分支。

View file

@ -1,182 +0,0 @@
# 全模块源码部署自动升级方法
本教程是方便全模块源码部署的爱好者,如何通过自动命令,自动拉取源码,自动编译,自动启动端口运行。实现最高效率的升级系统。
本项目的测试平台`https://2662r3426b.vicp.fun`,从开放以来就使用了该方法,效果良好。
教程可参考B站博主`毕乐labs`发布的视频教程:[《开源小智服务器xiaozhi-server自动更新以及最新版本MCP接入点配置保姆教程》](https://www.bilibili.com/video/BV15H37zHE7Q)
# 开始条件
- 你的电脑/服务器是linux操作系统
- 你已经跑通了整个流程
- 你喜欢跟进最新功能,但是觉得每次手动部署有点麻烦,期待有一个自动更新的方法
第二个条件必须满足,因为本教程所涉及的某些文件,JDK、Node.js环境、Conda环境等,是需要你跑通整个流程才有的,如果你没有跑通,当我讲到某个文件的时候,你可能就不知道什么意思。
# 教程效果
- 解决国内不能拉取最新项目源码问题
- 自动拉取代码编译前端文件
- 自动拉取代码编译java文件,自动杀掉8002端口,自动启动8002端口
- 自动拉取python代码,自动杀掉8000端口,自动启动8000端口
# 第一步 选好你的项目目录
例如,我规划了我的项目目录是,这是一个新建的空白的目录,如果你不想出错,可以和我一样
```
/home/system/xiaozhi
```
# 第二步 克隆本项目
此刻,先要执行第一句话,拉取源码,这句命令适用于国内网络的服务器和电脑,无需翻墙
```
cd /home/system/xiaozhi
git clone https://ghproxy.net/https://github.com/xinnan-tech/xiaozhi-esp32-server.git
```
执行完后,你的项目目录会多了一个文件夹`xiaozhi-esp32-server`,这个就是项目的源码
# 第三步 复制基础的文件
如果你之前已经跑通了整个流程,对funasr的模型文件`xiaozhi-server/models/SenseVoiceSmall/model.pt`和你的私有配置文件`xiaozhi-server/data/.config.yaml`这两个文件不会陌生。
此刻你需要把`model.pt`文件复制到新的目录去,你可以这样
```
# 创建需要的目录
mkdir -p /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/data/
cp 你原来的.config.yaml完整路径 /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/data/.config.yaml
cp 你原来的model.pt完整路径 /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/models/SenseVoiceSmall/model.pt
```
# 第四步 建立三个自动编译文件
## 4.1 自动编译mananger-web模块
在`/home/system/xiaozhi/`目录下,创建名字为`update_8001.sh`的文件,内容如下
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git fetch --all
git reset --hard
git pull origin main
cd /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-web
npm install
npm run build
rm -rf /home/system/xiaozhi/manager-web
mv /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-web/dist /home/system/xiaozhi/manager-web
```
保存好后执行赋权命令
```
chmod 777 update_8001.sh
```
执行完后,继续往下
## 4.2 自动编译运行manager-api模块
在`/home/system/xiaozhi/`目录下,创建名字为`update_8002.sh`的文件,内容如下
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git pull origin main
cd /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-api
rm -rf target
mvn clean package -Dmaven.test.skip=true
cd /home/system/xiaozhi/
# 查找占用8002端口的进程号
PID=$(sudo netstat -tulnp | grep 8002 | awk '{print $7}' | cut -d'/' -f1)
rm -rf /home/system/xiaozhi/xiaozhi-esp32-api.jar
mv /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-api/target/xiaozhi-esp32-api.jar /home/system/xiaozhi/xiaozhi-esp32-api.jar
# 检查是否找到进程号
if [ -z "$PID" ]; then
echo "没有找到占用8002端口的进程"
else
echo "找到占用8002端口的进程,进程号为: $PID"
# 杀掉进程
kill -9 $PID
kill -9 $PID
echo "已杀掉进程 $PID"
fi
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev &
tail tail -f nohup.out
```
保存好后执行赋权命令
```
chmod 777 update_8002.sh
```
执行完后,继续往下
## 4.3 自动编译运行Python项目
在`/home/system/xiaozhi/`目录下,创建名字为`update_8000.sh`的文件,内容如下
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git pull origin main
# 查找占用8000端口的进程号
PID=$(sudo netstat -tulnp | grep 8000 | awk '{print $7}' | cut -d'/' -f1)
# 检查是否找到进程号
if [ -z "$PID" ]; then
echo "没有找到占用8000端口的进程"
else
echo "找到占用8000端口的进程,进程号为: $PID"
# 杀掉进程
kill -9 $PID
kill -9 $PID
echo "已杀掉进程 $PID"
fi
cd main/xiaozhi-server
# 初始化conda环境
source ~/.bashrc
conda activate xiaozhi-esp32-server
pip install -r requirements.txt
nohup python app.py >/dev/null &
tail -f /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/tmp/server.log
```
保存好后执行赋权命令
```
chmod 777 update_8000.sh
```
执行完后,继续往下
# 日常更新
以上的脚本都建立好后,日常更新,我们只要依次执行以下命令就可以做到自动更新和启动
```
cd /home/system/xiaozhi
# 更新并启动Java程序
./update_8001.sh
# 更新web程序
./update_8002.sh
# 更新并启动python程序
./update_8000.sh
# 后期想查看java日志,执行以下命令
tail -f nohup.out
# 后期想查看python日志,执行以下命令
tail -f /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/tmp/server.log
```
# 注意事项
测试平台`https://2662r3426b.vicp.fun`,是使用nginx做了反向代理。nginx.conf详细配置可以[参考这里](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
## 常见问题
### 1、为什么没有见到8001端口?
回答:8001是开发环境使用的,用于运行前端的端口。如果你是服务器部署,不建议使用`npm run serve`启动8001端口运行前端,而是像本教程一样编译成html文件,然后使用nginx来管理访问。
### 2、每次更新需要更新手动SQL语句吗?
回答:不需要,因为项目使用**Liquibase**管理数据库版本,会自动执行新的sql脚本。

View file

@ -1,74 +0,0 @@
# 本地编译docker镜像方法
现在本项目已经使用`github`的`自动编译docker镜像`功能,如果您拉取的是项目发行的镜像,您没有自己编译镜像的需求,那就忽略本文档。
如果您修改了源码,然后想采用`docker`的方式部署运行,可以参照以下步骤操作:
## 1、环境准备
安装docker:
```bash
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```
## 2、编译镜像
当你修改好代码后,需要编译新的镜像时,需要按照以下步骤操作:
准备好你的`你的用户名`和`新的版本号`。
- 这个`你的用户名`是你在`docker hub`注册的用户名,例如`xiaozhi`。当然,如果你不需要推送到`docker hub`,你可以自由定义。
- 这个`新的版本号`是你编译的镜像版本,例如`1.2.3`,你可以根据需要自定义或者使用日期格式(例如`20260609`)主要是方便和现在运行的版本号做区分,同时也方便下次回忆你是什么时候构建的,不要和现在你本机运行的版本号相同。
进入`xiaozhi-esp32-server`项目根目录,编译 server 和 web 两个镜像:
```bash
cd 项目根目录
# 编译server镜像
docker build -f Dockerfile-server -t 你的用户名/xiaozhi-esp32-server:新的版本号 .
# 编译web镜像
docker build -f Dockerfile-web -t 你的用户名/xiaozhi-esp32-server-web:新的版本号 .
```
## 3、修改docker-compose配置
```bash
cd main/xiaozhi-server
```
编辑 `docker-compose_all.yml` 文件,将镜像版本替换为你刚才编译的版本:
```yaml
services:
xiaozhi-esp32-server:
image: 你的用户名/xiaozhi-esp32-server:新的版本号 # 修改为你的镜像地址
...
xiaozhi-esp32-server-web:
image: 你的用户名/xiaozhi-esp32-server-web:新的版本号 #修改为你的镜像地址
...
```
## 4、重启服务
```bash
# 停止旧容器
docker compose -f docker-compose_all.yml down
# 启动新容器
docker compose -f docker-compose_all.yml up -d
```
## 5、验证
查看日志确认服务启动正常:
```bash
# 查看server日志
docker logs -f -n 50 xiaozhi-esp32-server
# 查看web日志
docker logs -f -n 50 xiaozhi-esp32-server-web
```

View file

@ -23,18 +23,18 @@ http {
gzip_vary on; gzip_vary on;
server { server {
# 无域名访问,就用localhost # Access without domain name, use localhost
server_name localhost; server_name localhost;
# 80端口 # Port 80
listen 8002; listen 8002;
# 转发到编译后到web目录 # Forward to compiled web directory
location / { location / {
root /usr/share/nginx/html; root /usr/share/nginx/html;
try_files $uri $uri/ /index.html; try_files $uri $uri/ /index.html;
} }
# 转发到manager-api # Forward to manager-api
location /xiaozhi/ { location /xiaozhi/ {
proxy_pass http://127.0.0.1:8003; proxy_pass http://127.0.0.1:8003;
proxy_set_header Host $host; proxy_set_header Host $host;

View file

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
# 启动Java后端(docker内监听8003端口) # Start Java backend (listening on port 8003 in docker)
java -jar /app/xiaozhi-esp32-api.jar \ java -jar /app/xiaozhi-esp32-api.jar \
--server.port=8003 \ --server.port=8003 \
--spring.datasource.druid.url=${SPRING_DATASOURCE_DRUID_URL} \ --spring.datasource.druid.url=${SPRING_DATASOURCE_DRUID_URL} \
@ -9,5 +9,5 @@ java -jar /app/xiaozhi-esp32-api.jar \
--spring.data.redis.password=${SPRING_DATA_REDIS_PASSWORD} \ --spring.data.redis.password=${SPRING_DATA_REDIS_PASSWORD} \
--spring.data.redis.port=${SPRING_DATA_REDIS_PORT} & --spring.data.redis.port=${SPRING_DATA_REDIS_PORT} &
# 启动Nginx(前台运行保持容器存活) # Start Nginx (run in foreground to keep container alive)
nginx -g 'daemon off;' nginx -g 'daemon off;'

804
docs/features/api.md Normal file
View file

@ -0,0 +1,804 @@
# 📚 API Reference
This guide provides comprehensive documentation for the Xiaozhi ESP32 Server API, including endpoints, parameters, responses, and examples.
## 🎯 API Overview
The Xiaozhi ESP32 Server provides several APIs:
- **WebSocket API** - Real-time communication with ESP32 devices
- **REST API** - HTTP endpoints for configuration and management
- **OTA API** - Over-the-air firmware updates
- **Plugin API** - Extend functionality with custom plugins
## 🔌 WebSocket API
### **Connection**
```javascript
// Connect to WebSocket
const ws = new WebSocket('ws://YOUR_IP:8000/xiaozhi/v1/');
ws.onopen = function() {
console.log('Connected to Xiaozhi WebSocket');
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
ws.onclose = function() {
console.log('WebSocket connection closed');
};
```
### **Message Format**
All WebSocket messages use JSON format:
```json
{
"type": "message_type",
"data": {
"key": "value"
},
"timestamp": "2024-01-01T00:00:00Z"
}
```
### **Message Types**
#### **Device Registration**
```json
{
"type": "device_register",
"data": {
"device_id": "esp32_device_001",
"device_type": "esp32s3",
"firmware_version": "1.0.0",
"capabilities": ["audio_input", "audio_output", "wifi"]
}
}
```
#### **Audio Data**
```json
{
"type": "audio_data",
"data": {
"device_id": "esp32_device_001",
"audio_format": "wav",
"sample_rate": 16000,
"channels": 1,
"data": "base64_encoded_audio_data"
}
}
```
#### **Voice Command**
```json
{
"type": "voice_command",
"data": {
"device_id": "esp32_device_001",
"command": "turn on the living room light",
"confidence": 0.95,
"language": "en"
}
}
```
#### **Response**
```json
{
"type": "response",
"data": {
"device_id": "esp32_device_001",
"text": "I'll turn on the living room light for you.",
"audio_url": "http://YOUR_IP:8000/audio/response_123.wav",
"actions": [
{
"type": "homeassistant",
"action": "turn_on",
"entity_id": "light.living_room"
}
]
}
}
```
#### **Error**
```json
{
"type": "error",
"data": {
"device_id": "esp32_device_001",
"error_code": "AUDIO_PROCESSING_FAILED",
"error_message": "Failed to process audio data",
"details": {
"reason": "Invalid audio format"
}
}
}
```
## 🌐 REST API
### **Base URL**
```
http://YOUR_IP:8000/api/v1/
```
### **Authentication**
Most endpoints require API key authentication:
```bash
curl -H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
http://YOUR_IP:8000/api/v1/endpoint
```
### **Endpoints**
#### **GET /devices**
Get list of connected devices.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/devices
```
**Response:**
```json
{
"devices": [
{
"device_id": "esp32_device_001",
"device_type": "esp32s3",
"firmware_version": "1.0.0",
"status": "connected",
"last_seen": "2024-01-01T00:00:00Z",
"capabilities": ["audio_input", "audio_output", "wifi"]
}
],
"total": 1
}
```
#### **GET /devices/{device_id}**
Get specific device information.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/devices/esp32_device_001
```
**Response:**
```json
{
"device_id": "esp32_device_001",
"device_type": "esp32s3",
"firmware_version": "1.0.0",
"status": "connected",
"last_seen": "2024-01-01T00:00:00Z",
"capabilities": ["audio_input", "audio_output", "wifi"],
"configuration": {
"wake_word": "hey xiaozhi",
"language": "en",
"volume": 0.8
}
}
```
#### **POST /devices/{device_id}/command**
Send command to specific device.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"command": "turn on the living room light"}' \
http://YOUR_IP:8000/api/v1/devices/esp32_device_001/command
```
**Response:**
```json
{
"success": true,
"message": "Command sent successfully",
"command_id": "cmd_123456"
}
```
#### **GET /devices/{device_id}/status**
Get device status and health.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/devices/esp32_device_001/status
```
**Response:**
```json
{
"device_id": "esp32_device_001",
"status": "connected",
"health": "good",
"uptime": 3600,
"memory_usage": 65,
"cpu_usage": 45,
"wifi_signal": -45,
"last_command": "2024-01-01T00:00:00Z"
}
```
#### **POST /audio/process**
Process audio data and get response.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
-H "Content-Type: multipart/form-data" \
-F "audio=@audio_file.wav" \
-F "device_id=esp32_device_001" \
http://YOUR_IP:8000/api/v1/audio/process
```
**Response:**
```json
{
"success": true,
"transcription": "turn on the living room light",
"response": "I'll turn on the living room light for you.",
"audio_url": "http://YOUR_IP:8000/audio/response_123.wav",
"processing_time": 1.5
}
```
#### **GET /config**
Get current configuration.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/config
```
**Response:**
```json
{
"server": {
"websocket": "ws://YOUR_IP:8000/xiaozhi/v1/",
"ota": "http://YOUR_IP:8003/xiaozhi/ota/"
},
"selected_module": {
"VAD": "SileroVAD",
"ASR": "WhisperASR",
"LLM": "LMStudioLLM",
"TTS": "EdgeTTS"
},
"plugins": {
"enabled": true,
"loaded_plugins": ["weather", "news", "homeassistant"]
}
}
```
#### **PUT /config**
Update configuration.
**Request:**
```bash
curl -X PUT \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"selected_module": {"ASR": "OpenAIASR"}}' \
http://YOUR_IP:8000/api/v1/config
```
**Response:**
```json
{
"success": true,
"message": "Configuration updated successfully",
"restart_required": true
}
```
## 📡 OTA API
### **Base URL**
```
http://YOUR_IP:8003/xiaozhi/ota/
```
### **Endpoints**
#### **GET /**
Get OTA interface status.
**Request:**
```bash
curl http://YOUR_IP:8003/xiaozhi/ota/
```
**Response:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Xiaozhi OTA Interface</title>
</head>
<body>
<h1>OTA interface is running normally</h1>
<p>Websocket address sent to the device is: ws://YOUR_IP:8000/xiaozhi/v1/</p>
</body>
</html>
```
#### **GET /firmware**
Get available firmware versions.
**Request:**
```bash
curl http://YOUR_IP:8003/xiaozhi/ota/firmware
```
**Response:**
```json
{
"firmware_versions": [
{
"version": "1.0.0",
"release_date": "2024-01-01",
"download_url": "http://YOUR_IP:8003/xiaozhi/ota/firmware/1.0.0.bin",
"size": 1048576,
"checksum": "sha256:abc123..."
}
],
"latest_version": "1.0.0"
}
```
#### **POST /firmware/upload**
Upload new firmware.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
-F "firmware=@firmware.bin" \
-F "version=1.0.1" \
http://YOUR_IP:8003/xiaozhi/ota/firmware/upload
```
**Response:**
```json
{
"success": true,
"message": "Firmware uploaded successfully",
"version": "1.0.1",
"download_url": "http://YOUR_IP:8003/xiaozhi/ota/firmware/1.0.1.bin"
}
```
## 🔌 Plugin API
### **Plugin Management**
#### **GET /plugins**
Get list of available plugins.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/plugins
```
**Response:**
```json
{
"plugins": [
{
"name": "weather",
"version": "1.0.0",
"enabled": true,
"status": "running",
"description": "Weather information plugin"
},
{
"name": "news",
"version": "1.0.0",
"enabled": true,
"status": "running",
"description": "News information plugin"
}
]
}
```
#### **POST /plugins/{plugin_name}/enable**
Enable a plugin.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/plugins/weather/enable
```
**Response:**
```json
{
"success": true,
"message": "Plugin enabled successfully"
}
```
#### **POST /plugins/{plugin_name}/disable**
Disable a plugin.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/plugins/weather/disable
```
**Response:**
```json
{
"success": true,
"message": "Plugin disabled successfully"
}
```
#### **POST /plugins/{plugin_name}/command**
Send command to plugin.
**Request:**
```bash
curl -X POST \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"command": "get weather"}' \
http://YOUR_IP:8000/api/v1/plugins/weather/command
```
**Response:**
```json
{
"success": true,
"response": "Current weather: Sunny, 25°C",
"plugin": "weather"
}
```
## 📊 Monitoring API
### **System Status**
#### **GET /status**
Get system status and health.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/status
```
**Response:**
```json
{
"status": "running",
"uptime": 3600,
"version": "1.0.0",
"components": {
"websocket": "running",
"rest_api": "running",
"ota": "running",
"plugins": "running"
},
"metrics": {
"active_connections": 5,
"total_requests": 1000,
"average_response_time": 1.5,
"memory_usage": 65,
"cpu_usage": 45
}
}
```
#### **GET /metrics**
Get detailed metrics.
**Request:**
```bash
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/metrics
```
**Response:**
```json
{
"timestamp": "2024-01-01T00:00:00Z",
"metrics": {
"requests_total": 1000,
"requests_per_second": 10,
"average_response_time": 1.5,
"error_rate": 0.01,
"active_connections": 5,
"memory_usage": {
"total": 8192,
"used": 5324,
"free": 2868
},
"cpu_usage": {
"user": 30,
"system": 15,
"idle": 55
}
}
}
```
## 🔐 Authentication
### **API Key Authentication**
All API endpoints require authentication via API key:
```bash
# Set API key in header
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/endpoint
# Or use query parameter
curl "http://YOUR_IP:8000/api/v1/endpoint?api_key=your-api-key"
```
### **JWT Token Authentication**
For advanced authentication, use JWT tokens:
```bash
# Get JWT token
curl -X POST \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}' \
http://YOUR_IP:8000/api/v1/auth/login
# Use JWT token
curl -H "Authorization: Bearer your-jwt-token" \
http://YOUR_IP:8000/api/v1/endpoint
```
## 📝 Error Handling
### **Error Response Format**
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human readable error message",
"details": {
"field": "Additional error details"
}
},
"timestamp": "2024-01-01T00:00:00Z"
}
```
### **Common Error Codes**
| Code | Description | HTTP Status |
|------|-------------|-------------|
| `INVALID_API_KEY` | Invalid or missing API key | 401 |
| `DEVICE_NOT_FOUND` | Device not found | 404 |
| `PLUGIN_NOT_FOUND` | Plugin not found | 404 |
| `INVALID_REQUEST` | Invalid request format | 400 |
| `RATE_LIMIT_EXCEEDED` | Rate limit exceeded | 429 |
| `INTERNAL_ERROR` | Internal server error | 500 |
### **Error Handling Example**
```javascript
fetch('/api/v1/devices')
.then(response => {
if (!response.ok) {
return response.json().then(error => {
throw new Error(error.error.message);
});
}
return response.json();
})
.then(data => {
console.log('Devices:', data);
})
.catch(error => {
console.error('Error:', error.message);
});
```
## 🧪 Testing the API
### **Using curl**
```bash
# Test WebSocket connection
curl -i -N -H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==" \
http://YOUR_IP:8000/xiaozhi/v1/
# Test REST API
curl -H "X-API-Key: your-api-key" \
http://YOUR_IP:8000/api/v1/status
# Test OTA API
curl http://YOUR_IP:8003/xiaozhi/ota/
```
### **Using Python**
```python
import requests
import websocket
import json
# Test REST API
def test_rest_api():
headers = {'X-API-Key': 'your-api-key'}
response = requests.get('http://YOUR_IP:8000/api/v1/status', headers=headers)
print(response.json())
# Test WebSocket
def test_websocket():
def on_message(ws, message):
data = json.loads(message)
print('Received:', data)
def on_error(ws, error):
print('Error:', error)
def on_close(ws):
print('Connection closed')
def on_open(ws):
print('Connected')
# Send test message
ws.send(json.dumps({
'type': 'device_register',
'data': {
'device_id': 'test_device',
'device_type': 'esp32s3',
'firmware_version': '1.0.0'
}
}))
ws = websocket.WebSocketApp('ws://YOUR_IP:8000/xiaozhi/v1/',
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open)
ws.run_forever()
# Run tests
test_rest_api()
test_websocket()
```
### **Using JavaScript**
```javascript
// Test REST API
async function testRestAPI() {
try {
const response = await fetch('http://YOUR_IP:8000/api/v1/status', {
headers: {
'X-API-Key': 'your-api-key'
}
});
const data = await response.json();
console.log('Status:', data);
} catch (error) {
console.error('Error:', error);
}
}
// Test WebSocket
function testWebSocket() {
const ws = new WebSocket('ws://YOUR_IP:8000/xiaozhi/v1/');
ws.onopen = function() {
console.log('Connected');
// Send test message
ws.send(JSON.stringify({
type: 'device_register',
data: {
device_id: 'test_device',
device_type: 'esp32s3',
firmware_version: '1.0.0'
}
}));
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onerror = function(error) {
console.error('Error:', error);
};
ws.onclose = function() {
console.log('Connection closed');
};
}
// Run tests
testRestAPI();
testWebSocket();
```
## 🎯 Next Steps
After understanding the API:
1. **[Test Voice Interaction](../features/voice-interaction.md)** - Use the API for voice commands
2. **[Create Custom Integrations](../features/integrations.md)** - Build API-based integrations
3. **[Develop Plugins](../features/plugins.md)** - Use the Plugin API
4. **[Monitor Performance](../guides/monitoring.md)** - Use the Monitoring API
## 🆘 Need Help?
- **API Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Authentication Problems?** See [Security Guide](../guides/security.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **API Endpoints**
- **WebSocket**: `ws://YOUR_IP:8000/xiaozhi/v1/`
- **REST API**: `http://YOUR_IP:8000/api/v1/`
- **OTA API**: `http://YOUR_IP:8003/xiaozhi/ota/`
### **Authentication**
- **API Key**: `X-API-Key: your-api-key`
- **JWT Token**: `Authorization: Bearer your-jwt-token`
### **Common Commands**
```bash
# Get status
curl -H "X-API-Key: your-api-key" http://YOUR_IP:8000/api/v1/status
# List devices
curl -H "X-API-Key: your-api-key" http://YOUR_IP:8000/api/v1/devices
# Send command
curl -X POST -H "X-API-Key: your-api-key" \
-d '{"command": "hello"}' \
http://YOUR_IP:8000/api/v1/devices/device_id/command
```
---
**Your API reference is ready! 🎉**
👉 **[Next: Communication Protocols →](../reference/protocols.md)**

View file

@ -0,0 +1,586 @@
# ✨ Integrations
This guide covers the various integrations available with Xiaozhi ESP32 Server, including smart home platforms, communication services, and third-party APIs.
## 🎯 Integration Overview
Xiaozhi supports integrations with:
- **Smart Home Platforms** (HomeAssistant, MQTT)
- **Communication Services** (SMS, Email, Notifications)
- **AI Services** (Vision models, Voice recognition)
- **Data Sources** (Weather, News, APIs)
- **Development Tools** (MCP, Function calling)
## 🏠 Smart Home Integrations
### **HomeAssistant Integration**
Connect Xiaozhi to HomeAssistant for comprehensive smart home control.
#### **Features**
- **Voice control** of lights, switches, and sensors
- **Temperature control** via thermostats
- **Security monitoring** with cameras and alarms
- **Automation triggers** based on voice commands
#### **Setup**
```yaml
# In your configuration
homeassistant:
enabled: true
url: http://homeassistant.local:8123
api_key: your-homeassistant-api-key
entities:
lights:
- light.living_room
- light.kitchen
- light.bedroom
switches:
- switch.coffee_maker
- switch.tv_power
sensors:
- sensor.temperature
- sensor.humidity
climate:
- climate.thermostat
```
#### **Voice Commands**
- "Turn on the living room light"
- "Set temperature to 72 degrees"
- "Turn off the coffee maker"
- "What's the temperature in the bedroom?"
#### **Advanced Features**
- **Function calling** for complex operations
- **MCP service** integration for advanced automation
- **Custom entities** and device support
### **MQTT Gateway Integration**
Use MQTT for lightweight IoT device communication.
#### **Features**
- **Publish/subscribe** messaging
- **Device discovery** and management
- **Real-time updates** from sensors
- **Command execution** via MQTT topics
#### **Setup**
```yaml
# MQTT configuration
mqtt:
enabled: true
broker: mqtt://broker.hivemq.com:1883
username: your-username
password: your-password
topics:
commands: xiaozhi/commands
status: xiaozhi/status
sensors: xiaozhi/sensors
```
#### **MQTT Topics**
- **Commands**: `xiaozhi/commands/{device_id}`
- **Status**: `xiaozhi/status/{device_id}`
- **Sensors**: `xiaozhi/sensors/{sensor_id}`
## 📱 Communication Integrations
### **SMS Integration**
Send and receive SMS messages via Twilio or other providers.
#### **Features**
- **Send SMS** notifications
- **Receive SMS** commands
- **Two-factor authentication** support
- **Emergency alerts** and notifications
#### **Setup**
```yaml
# SMS configuration
sms:
enabled: true
provider: twilio
account_sid: your-twilio-account-sid
auth_token: your-twilio-auth-token
from_number: +1234567890
to_numbers:
- +1234567890
- +0987654321
```
#### **Voice Commands**
- "Send SMS to John: Meeting at 3 PM"
- "Text my wife: I'll be home late"
- "Send emergency alert"
### **Email Integration**
Send email notifications and reports.
#### **Features**
- **Email notifications** for events
- **Daily reports** and summaries
- **Alert emails** for critical issues
- **Custom email templates**
#### **Setup**
```yaml
# Email configuration
email:
enabled: true
smtp_server: smtp.gmail.com
smtp_port: 587
username: your-email@gmail.com
password: your-app-password
recipients:
- admin@yourdomain.com
- alerts@yourdomain.com
```
## 🤖 AI Service Integrations
### **Vision Model Integration**
Enable image recognition and analysis capabilities.
#### **Features**
- **Image recognition** and classification
- **Object detection** and counting
- **Text extraction** from images
- **Scene analysis** and description
#### **Setup**
```yaml
# Vision model configuration
VLLM:
OpenAILLMVLLM:
type: openai
api_key: your-openai-api-key
model: gpt-4o
vision_enabled: true
max_image_size: 1024
supported_formats: [jpg, png, gif, webp]
```
#### **Voice Commands**
- "What do you see in this image?"
- "Describe the scene"
- "Count the objects"
- "Read the text in this image"
### **Voiceprint Recognition**
Identify users by their voice patterns.
#### **Features**
- **User identification** by voice
- **Personalized responses** based on user
- **Access control** via voice recognition
- **Multi-user support** with different profiles
#### **Setup**
```yaml
# Voiceprint configuration
voiceprint:
enabled: true
url: http://192.168.1.100:8005/voiceprint/health?key=abcd
speakers:
- "user1,John,John is a software engineer"
- "user2,Jane,Jane is a designer"
- "user3,Bob,Bob is a student"
```
#### **Voice Commands**
- "Do you know who I am?"
- "Register my voice"
- "Delete my voice profile"
## 🌐 Data Source Integrations
### **Weather Integration**
Get real-time weather information and forecasts.
#### **Features**
- **Current weather** conditions
- **Weather forecasts** for multiple days
- **Location-based** weather data
- **Weather alerts** and warnings
#### **Setup**
```yaml
# Weather configuration
weather:
enabled: true
provider: openweathermap
api_key: your-openweathermap-api-key
default_location: "New York, NY"
units: metric
cache_duration: 300
```
#### **Voice Commands**
- "What's the weather like?"
- "Will it rain today?"
- "What's the temperature?"
- "Weather forecast for tomorrow"
### **News Integration**
Get the latest news and updates.
#### **Features**
- **Latest news** headlines
- **News summaries** and briefings
- **Topic-specific** news filtering
- **News alerts** for breaking stories
#### **Setup**
```yaml
# News configuration
news:
enabled: true
provider: newsapi
api_key: your-newsapi-key
sources: ["bbc-news", "cnn", "reuters"]
categories: ["technology", "science", "health"]
max_articles: 10
```
#### **Voice Commands**
- "What's the latest news?"
- "News about technology"
- "Breaking news"
- "News summary"
## 🔧 Development Integrations
### **MCP (Model Context Protocol) Integration**
Use MCP for advanced AI model communication.
#### **Features**
- **Standardized communication** with AI models
- **Function calling** capabilities
- **Context management** for conversations
- **Plugin system** for extensibility
#### **Setup**
```yaml
# MCP configuration
mcp:
enabled: true
servers:
- name: homeassistant
url: http://homeassistant.local:8123
api_key: your-ha-api-key
- name: weather
url: http://weather-api.local:8000
api_key: your-weather-api-key
```
#### **MCP Functions**
- **HomeAssistant**: Control smart home devices
- **Weather**: Get weather information
- **News**: Fetch news articles
- **Custom**: Define your own functions
### **Function Calling Integration**
Enable AI models to call external functions.
#### **Features**
- **Dynamic function** execution
- **Parameter validation** and type checking
- **Error handling** and fallback mechanisms
- **Function chaining** for complex operations
#### **Setup**
```yaml
# Function calling configuration
function_calling:
enabled: true
functions:
- name: get_weather
description: Get current weather information
parameters:
location:
type: string
description: City name or coordinates
required: true
units:
type: string
enum: [metric, imperial]
default: metric
- name: control_light
description: Control smart home lights
parameters:
entity_id:
type: string
description: HomeAssistant entity ID
required: true
action:
type: string
enum: [on, off, toggle, dim]
required: true
brightness:
type: integer
description: Brightness level (0-255)
required: false
```
## 🔌 Custom Integration Development
### **Creating Custom Integrations**
Develop your own integrations for specific needs.
#### **Integration Structure**
```python
# Custom integration example
class CustomIntegration:
def __init__(self, config):
self.config = config
self.enabled = config.get('enabled', False)
def initialize(self):
"""Initialize the integration"""
pass
def process_command(self, command):
"""Process voice commands"""
pass
def get_status(self):
"""Get integration status"""
pass
```
#### **Configuration Template**
```yaml
# Custom integration configuration
custom_integration:
enabled: true
name: "My Custom Integration"
version: "1.0.0"
settings:
api_key: your-api-key
endpoint: https://api.example.com
timeout: 30
```
### **Integration Best Practices**
#### **Error Handling**
```python
def safe_api_call(self, endpoint, data):
try:
response = requests.post(endpoint, json=data, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"API call failed: {e}")
return None
```
#### **Configuration Validation**
```python
def validate_config(self, config):
required_fields = ['api_key', 'endpoint']
for field in required_fields:
if field not in config:
raise ValueError(f"Missing required field: {field}")
```
#### **Logging and Monitoring**
```python
import logging
logger = logging.getLogger(__name__)
def log_integration_activity(self, action, details):
logger.info(f"Integration {self.name}: {action} - {details}")
```
## 📊 Integration Monitoring
### **Health Checks**
Monitor integration status and performance.
```yaml
# Integration monitoring
monitoring:
integrations:
enabled: true
health_checks:
interval: 60 # seconds
timeout: 10 # seconds
checks:
- name: homeassistant
type: http
url: http://homeassistant.local:8123/api/
expected_status: 200
- name: weather_api
type: http
url: https://api.openweathermap.org/data/2.5/weather
expected_status: 200
```
### **Performance Metrics**
Track integration performance and usage.
```yaml
# Performance monitoring
metrics:
enabled: true
integration_metrics:
response_time: true
success_rate: true
error_count: true
usage_count: true
```
## 🎯 Integration Examples
### **Complete Smart Home Setup**
```yaml
# Complete smart home integration
integrations:
homeassistant:
enabled: true
url: http://homeassistant.local:8123
api_key: your-ha-api-key
entities:
lights: [light.living_room, light.kitchen]
switches: [switch.coffee_maker, switch.tv]
sensors: [sensor.temperature, sensor.humidity]
mqtt:
enabled: true
broker: mqtt://broker.hivemq.com:1883
topics:
commands: xiaozhi/commands
status: xiaozhi/status
weather:
enabled: true
provider: openweathermap
api_key: your-weather-api-key
default_location: "New York, NY"
sms:
enabled: true
provider: twilio
account_sid: your-twilio-sid
auth_token: your-twilio-token
from_number: +1234567890
```
### **Educational Environment Setup**
```yaml
# Educational integration setup
integrations:
math_helper:
enabled: true
functions:
- calculate
- solve_equation
- explain_concept
language_learning:
enabled: true
target_language: spanish
difficulty: beginner
functions:
- translate
- practice_conversation
- grammar_check
news:
enabled: true
provider: newsapi
api_key: your-newsapi-key
sources: ["bbc-news", "cnn"]
categories: ["technology", "science"]
```
## 🛠️ Troubleshooting Integrations
### **Common Issues**
#### **Integration Not Working**
1. **Check configuration** - Verify all required fields
2. **Test connectivity** - Ping endpoints and check ports
3. **Check logs** - Look for error messages
4. **Verify credentials** - Ensure API keys are valid
#### **Performance Issues**
1. **Monitor response times** - Check API latency
2. **Optimize requests** - Use caching and batching
3. **Check rate limits** - Ensure you're not exceeding limits
4. **Scale resources** - Add more processing power if needed
#### **Authentication Failures**
1. **Verify API keys** - Check expiration and permissions
2. **Test authentication** - Use curl or Postman
3. **Check network** - Ensure firewall allows connections
4. **Update credentials** - Refresh expired tokens
## 🎯 Next Steps
After setting up integrations:
1. **[Test Voice Commands](../features/voice-interaction.md)** - Verify integration functionality
2. **[Configure AI Providers](../configuration/providers.md)** - Set up AI services
3. **[Advanced Configuration](../configuration/advanced.md)** - Fine-tune settings
4. **[Create Custom Integrations](../guides/custom-integrations.md)** - Build your own
## 🆘 Need Help?
- **Integration Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Specific Integrations?** See individual integration guides
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Popular Integrations**
- **HomeAssistant**: Smart home control
- **MQTT**: IoT device communication
- **Weather**: Weather information
- **SMS**: Text messaging
- **Vision**: Image recognition
### **Integration Types**
- **Smart Home**: HomeAssistant, MQTT
- **Communication**: SMS, Email
- **AI Services**: Vision, Voiceprint
- **Data Sources**: Weather, News
- **Development**: MCP, Function calling
### **Setup Checklist**
- ✅ Configure integration settings
- ✅ Test API connectivity
- ✅ Verify authentication
- ✅ Test voice commands
- ✅ Monitor performance
---
**Your integrations are ready! 🎉**
👉 **[Next: Plugin System →](plugins.md)**

987
docs/features/plugins.md Normal file
View file

@ -0,0 +1,987 @@
# 🔌 Plugin System
This guide covers the Xiaozhi ESP32 Server plugin system, including how to create, configure, and manage plugins for extending functionality.
## 🎯 Plugin System Overview
The plugin system allows you to:
- **Extend functionality** with custom features
- **Integrate third-party services** and APIs
- **Create reusable components** for different use cases
- **Modularize complex functionality** into manageable pieces
## 🔧 Plugin Architecture
### **Plugin Structure**
```
plugins/
├── __init__.py
├── base/
│ ├── __init__.py
│ └── plugin.py
├── weather/
│ ├── __init__.py
│ ├── weather_plugin.py
│ └── config.yaml
├── news/
│ ├── __init__.py
│ ├── news_plugin.py
│ └── config.yaml
└── custom/
├── __init__.py
├── my_plugin.py
└── config.yaml
```
### **Base Plugin Class**
```python
# plugins/base/plugin.py
from abc import ABC, abstractmethod
import logging
logger = logging.getLogger(__name__)
class BasePlugin(ABC):
"""Base class for all Xiaozhi plugins"""
def __init__(self, config):
self.config = config
self.name = config.get('name', 'Unknown Plugin')
self.version = config.get('version', '1.0.0')
self.enabled = config.get('enabled', False)
self.logger = logging.getLogger(f"plugin.{self.name}")
@abstractmethod
def initialize(self):
"""Initialize the plugin"""
pass
@abstractmethod
def process_command(self, command, context=None):
"""Process voice commands"""
pass
@abstractmethod
def get_status(self):
"""Get plugin status"""
pass
def cleanup(self):
"""Cleanup plugin resources"""
pass
def validate_config(self, config):
"""Validate plugin configuration"""
return True
```
## 🚀 Creating Your First Plugin
### **Step 1: Create Plugin Directory**
```bash
# Create plugin directory
mkdir -p plugins/my_first_plugin
cd plugins/my_first_plugin
```
### **Step 2: Create Plugin Files**
#### **Plugin Implementation**
```python
# plugins/my_first_plugin/my_first_plugin.py
from plugins.base.plugin import BasePlugin
import requests
import json
class MyFirstPlugin(BasePlugin):
"""My first custom plugin"""
def __init__(self, config):
super().__init__(config)
self.api_key = config.get('api_key')
self.endpoint = config.get('endpoint', 'https://api.example.com')
def initialize(self):
"""Initialize the plugin"""
self.logger.info(f"Initializing {self.name} v{self.version}")
# Validate configuration
if not self.api_key:
raise ValueError("API key is required")
# Test API connectivity
try:
response = requests.get(f"{self.endpoint}/health", timeout=10)
response.raise_for_status()
self.logger.info("Plugin initialized successfully")
except requests.exceptions.RequestException as e:
self.logger.error(f"Failed to initialize plugin: {e}")
raise
def process_command(self, command, context=None):
"""Process voice commands"""
self.logger.info(f"Processing command: {command}")
# Parse command
if "hello" in command.lower():
return self._handle_hello()
elif "status" in command.lower():
return self._handle_status()
else:
return "I don't understand that command"
def _handle_hello(self):
"""Handle hello command"""
return "Hello! This is my first plugin speaking."
def _handle_status(self):
"""Handle status command"""
try:
response = requests.get(f"{self.endpoint}/status", timeout=10)
response.raise_for_status()
data = response.json()
return f"Plugin status: {data.get('status', 'unknown')}"
except requests.exceptions.RequestException as e:
self.logger.error(f"Failed to get status: {e}")
return "Sorry, I couldn't get the status"
def get_status(self):
"""Get plugin status"""
return {
"name": self.name,
"version": self.version,
"enabled": self.enabled,
"status": "running" if self.enabled else "disabled"
}
def cleanup(self):
"""Cleanup plugin resources"""
self.logger.info(f"Cleaning up {self.name}")
```
#### **Plugin Configuration**
```yaml
# plugins/my_first_plugin/config.yaml
name: "My First Plugin"
version: "1.0.0"
enabled: true
description: "A simple example plugin"
# Plugin-specific settings
api_key: "your-api-key-here"
endpoint: "https://api.example.com"
timeout: 30
retry_count: 3
# Command patterns
commands:
- pattern: "hello"
description: "Say hello"
- pattern: "status"
description: "Get plugin status"
```
#### **Plugin Initialization**
```python
# plugins/my_first_plugin/__init__.py
from .my_first_plugin import MyFirstPlugin
__all__ = ['MyFirstPlugin']
```
### **Step 3: Register Plugin**
```python
# plugins/__init__.py
from .my_first_plugin import MyFirstPlugin
PLUGINS = {
'my_first_plugin': MyFirstPlugin,
}
def get_plugin(name):
"""Get plugin class by name"""
return PLUGINS.get(name)
def list_plugins():
"""List all available plugins"""
return list(PLUGINS.keys())
```
## 🔌 Plugin Configuration
### **Main Configuration**
```yaml
# In main config.yaml
plugins:
enabled: true
plugin_dir: plugins/
auto_load: true
# Plugin-specific configurations
my_first_plugin:
enabled: true
api_key: "your-api-key-here"
endpoint: "https://api.example.com"
timeout: 30
weather_plugin:
enabled: true
api_key: "your-weather-api-key"
default_location: "New York, NY"
units: "metric"
news_plugin:
enabled: true
api_key: "your-news-api-key"
sources: ["bbc-news", "cnn", "reuters"]
max_articles: 10
```
### **Plugin-Specific Configuration**
```yaml
# plugins/weather_plugin/config.yaml
name: "Weather Plugin"
version: "1.0.0"
enabled: true
description: "Get weather information"
# Weather API settings
api_key: "your-openweathermap-api-key"
default_location: "New York, NY"
units: "metric"
cache_duration: 300
# Supported commands
commands:
- pattern: "weather"
description: "Get current weather"
- pattern: "forecast"
description: "Get weather forecast"
- pattern: "temperature"
description: "Get current temperature"
```
## 🌟 Advanced Plugin Features
### **Plugin Dependencies**
```python
# plugins/advanced_plugin/advanced_plugin.py
from plugins.base.plugin import BasePlugin
from plugins.weather_plugin import WeatherPlugin
from plugins.news_plugin import NewsPlugin
class AdvancedPlugin(BasePlugin):
"""Advanced plugin with dependencies"""
def __init__(self, config):
super().__init__(config)
self.dependencies = config.get('dependencies', [])
self.weather_plugin = None
self.news_plugin = None
def initialize(self):
"""Initialize plugin and dependencies"""
self.logger.info(f"Initializing {self.name} with dependencies: {self.dependencies}")
# Initialize dependencies
for dep_name in self.dependencies:
if dep_name == 'weather':
self.weather_plugin = WeatherPlugin(self.config.get('weather', {}))
self.weather_plugin.initialize()
elif dep_name == 'news':
self.news_plugin = NewsPlugin(self.config.get('news', {}))
self.news_plugin.initialize()
def process_command(self, command, context=None):
"""Process commands using dependencies"""
if "weather" in command.lower() and self.weather_plugin:
return self.weather_plugin.process_command(command, context)
elif "news" in command.lower() and self.news_plugin:
return self.news_plugin.process_command(command, context)
else:
return "I can help with weather and news. What would you like to know?"
```
### **Plugin Events and Hooks**
```python
# plugins/event_plugin/event_plugin.py
from plugins.base.plugin import BasePlugin
import asyncio
class EventPlugin(BasePlugin):
"""Plugin with event handling"""
def __init__(self, config):
super().__init__(config)
self.events = {}
self.hooks = {}
def initialize(self):
"""Initialize plugin with event system"""
self.logger.info(f"Initializing {self.name} with event system")
# Register event handlers
self.register_event('voice_command', self._handle_voice_command)
self.register_event('system_startup', self._handle_system_startup)
self.register_event('system_shutdown', self._handle_system_shutdown)
def register_event(self, event_name, handler):
"""Register event handler"""
if event_name not in self.events:
self.events[event_name] = []
self.events[event_name].append(handler)
self.logger.info(f"Registered handler for event: {event_name}")
def emit_event(self, event_name, data=None):
"""Emit event to all handlers"""
if event_name in self.events:
for handler in self.events[event_name]:
try:
handler(data)
except Exception as e:
self.logger.error(f"Error in event handler for {event_name}: {e}")
def _handle_voice_command(self, data):
"""Handle voice command events"""
self.logger.info(f"Voice command received: {data}")
def _handle_system_startup(self, data):
"""Handle system startup events"""
self.logger.info("System startup detected")
def _handle_system_shutdown(self, data):
"""Handle system shutdown events"""
self.logger.info("System shutdown detected")
```
### **Plugin Caching**
```python
# plugins/cache_plugin/cache_plugin.py
from plugins.base.plugin import BasePlugin
import json
import time
from functools import wraps
class CachePlugin(BasePlugin):
"""Plugin with caching capabilities"""
def __init__(self, config):
super().__init__(config)
self.cache = {}
self.cache_duration = config.get('cache_duration', 300) # 5 minutes
def cache_result(self, duration=None):
"""Decorator for caching function results"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
cache_key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
current_time = time.time()
# Check if cached result exists and is still valid
if cache_key in self.cache:
cached_time, cached_result = self.cache[cache_key]
if current_time - cached_time < (duration or self.cache_duration):
self.logger.debug(f"Cache hit for {cache_key}")
return cached_result
# Execute function and cache result
result = func(*args, **kwargs)
self.cache[cache_key] = (current_time, result)
self.logger.debug(f"Cached result for {cache_key}")
return result
return wrapper
return decorator
def clear_cache(self, pattern=None):
"""Clear cache entries"""
if pattern:
keys_to_remove = [key for key in self.cache.keys() if pattern in key]
for key in keys_to_remove:
del self.cache[key]
self.logger.info(f"Cleared {len(keys_to_remove)} cache entries matching '{pattern}'")
else:
self.cache.clear()
self.logger.info("Cleared all cache entries")
@cache_result(duration=600) # 10 minutes
def expensive_operation(self, data):
"""Example of expensive operation with caching"""
self.logger.info("Performing expensive operation...")
time.sleep(2) # Simulate expensive operation
return f"Processed: {data}"
```
## 🔧 Plugin Management
### **Plugin Loader**
```python
# plugins/plugin_loader.py
import os
import yaml
import importlib
import logging
logger = logging.getLogger(__name__)
class PluginLoader:
"""Plugin loader and manager"""
def __init__(self, plugin_dir="plugins"):
self.plugin_dir = plugin_dir
self.loaded_plugins = {}
self.plugin_configs = {}
def load_plugins(self, config):
"""Load all enabled plugins"""
logger.info("Loading plugins...")
# Scan plugin directory
for plugin_name in os.listdir(self.plugin_dir):
plugin_path = os.path.join(self.plugin_dir, plugin_name)
if os.path.isdir(plugin_path) and not plugin_name.startswith('_'):
self._load_plugin(plugin_name, plugin_path, config)
logger.info(f"Loaded {len(self.loaded_plugins)} plugins")
def _load_plugin(self, plugin_name, plugin_path, config):
"""Load individual plugin"""
try:
# Load plugin configuration
config_file = os.path.join(plugin_path, "config.yaml")
if os.path.exists(config_file):
with open(config_file, 'r') as f:
plugin_config = yaml.safe_load(f)
else:
plugin_config = {}
# Merge with main config
plugin_config.update(config.get('plugins', {}).get(plugin_name, {}))
# Check if plugin is enabled
if not plugin_config.get('enabled', False):
logger.info(f"Plugin {plugin_name} is disabled, skipping")
return
# Import plugin module
module_name = f"plugins.{plugin_name}"
module = importlib.import_module(module_name)
# Get plugin class
plugin_class = getattr(module, plugin_name.title().replace('_', ''))
# Initialize plugin
plugin_instance = plugin_class(plugin_config)
plugin_instance.initialize()
# Store plugin
self.loaded_plugins[plugin_name] = plugin_instance
self.plugin_configs[plugin_name] = plugin_config
logger.info(f"Successfully loaded plugin: {plugin_name}")
except Exception as e:
logger.error(f"Failed to load plugin {plugin_name}: {e}")
def get_plugin(self, name):
"""Get plugin instance by name"""
return self.loaded_plugins.get(name)
def list_plugins(self):
"""List all loaded plugins"""
return list(self.loaded_plugins.keys())
def process_command(self, command, context=None):
"""Process command through all plugins"""
responses = []
for plugin_name, plugin in self.loaded_plugins.items():
try:
response = plugin.process_command(command, context)
if response:
responses.append(response)
except Exception as e:
logger.error(f"Error processing command in plugin {plugin_name}: {e}")
return responses
def cleanup(self):
"""Cleanup all plugins"""
for plugin_name, plugin in self.loaded_plugins.items():
try:
plugin.cleanup()
except Exception as e:
logger.error(f"Error cleaning up plugin {plugin_name}: {e}")
self.loaded_plugins.clear()
self.plugin_configs.clear()
```
### **Plugin Manager CLI**
```python
# plugins/plugin_manager.py
import argparse
import sys
from plugin_loader import PluginLoader
def main():
parser = argparse.ArgumentParser(description="Xiaozhi Plugin Manager")
parser.add_argument("--list", action="store_true", help="List all plugins")
parser.add_argument("--enable", help="Enable a plugin")
parser.add_argument("--disable", help="Disable a plugin")
parser.add_argument("--status", help="Get plugin status")
parser.add_argument("--test", help="Test a plugin")
args = parser.parse_args()
loader = PluginLoader()
if args.list:
plugins = loader.list_plugins()
print("Available plugins:")
for plugin in plugins:
print(f" - {plugin}")
elif args.enable:
# Enable plugin logic
print(f"Enabling plugin: {args.enable}")
elif args.disable:
# Disable plugin logic
print(f"Disabling plugin: {args.disable}")
elif args.status:
plugin = loader.get_plugin(args.status)
if plugin:
status = plugin.get_status()
print(f"Plugin {args.status} status: {status}")
else:
print(f"Plugin {args.status} not found")
elif args.test:
plugin = loader.get_plugin(args.test)
if plugin:
response = plugin.process_command("test")
print(f"Plugin {args.test} test response: {response}")
else:
print(f"Plugin {args.test} not found")
if __name__ == "__main__":
main()
```
## 📊 Plugin Monitoring
### **Plugin Health Monitoring**
```python
# plugins/plugin_monitor.py
import time
import logging
from datetime import datetime
logger = logging.getLogger(__name__)
class PluginMonitor:
"""Monitor plugin health and performance"""
def __init__(self):
self.metrics = {}
self.alerts = []
def start_monitoring(self, plugin_loader):
"""Start monitoring plugins"""
logger.info("Starting plugin monitoring...")
while True:
try:
self._check_plugin_health(plugin_loader)
self._check_plugin_performance(plugin_loader)
time.sleep(60) # Check every minute
except KeyboardInterrupt:
logger.info("Plugin monitoring stopped")
break
except Exception as e:
logger.error(f"Error in plugin monitoring: {e}")
def _check_plugin_health(self, plugin_loader):
"""Check plugin health"""
for plugin_name, plugin in plugin_loader.loaded_plugins.items():
try:
status = plugin.get_status()
if status.get('status') != 'running':
self._create_alert(plugin_name, f"Plugin status: {status.get('status')}")
except Exception as e:
self._create_alert(plugin_name, f"Health check failed: {e}")
def _check_plugin_performance(self, plugin_loader):
"""Check plugin performance"""
for plugin_name, plugin in plugin_loader.loaded_plugins.items():
start_time = time.time()
try:
plugin.process_command("health_check")
response_time = time.time() - start_time
if response_time > 5.0: # 5 second threshold
self._create_alert(plugin_name, f"Slow response time: {response_time:.2f}s")
# Store metrics
if plugin_name not in self.metrics:
self.metrics[plugin_name] = []
self.metrics[plugin_name].append({
'timestamp': datetime.now(),
'response_time': response_time
})
except Exception as e:
self._create_alert(plugin_name, f"Performance check failed: {e}")
def _create_alert(self, plugin_name, message):
"""Create alert"""
alert = {
'timestamp': datetime.now(),
'plugin': plugin_name,
'message': message,
'severity': 'warning'
}
self.alerts.append(alert)
logger.warning(f"Plugin alert: {plugin_name} - {message}")
def get_metrics(self, plugin_name=None):
"""Get plugin metrics"""
if plugin_name:
return self.metrics.get(plugin_name, [])
return self.metrics
def get_alerts(self, plugin_name=None):
"""Get plugin alerts"""
if plugin_name:
return [alert for alert in self.alerts if alert['plugin'] == plugin_name]
return self.alerts
```
## 🎯 Plugin Examples
### **Weather Plugin**
```python
# plugins/weather_plugin/weather_plugin.py
from plugins.base.plugin import BasePlugin
import requests
import json
class WeatherPlugin(BasePlugin):
"""Weather information plugin"""
def __init__(self, config):
super().__init__(config)
self.api_key = config.get('api_key')
self.default_location = config.get('default_location', 'New York, NY')
self.units = config.get('units', 'metric')
self.base_url = "https://api.openweathermap.org/data/2.5"
def initialize(self):
"""Initialize weather plugin"""
if not self.api_key:
raise ValueError("Weather API key is required")
self.logger.info("Weather plugin initialized")
def process_command(self, command, context=None):
"""Process weather commands"""
command_lower = command.lower()
if "weather" in command_lower:
return self._get_current_weather()
elif "forecast" in command_lower:
return self._get_forecast()
elif "temperature" in command_lower:
return self._get_temperature()
else:
return "I can help with weather information. Ask me about current weather, forecast, or temperature."
def _get_current_weather(self):
"""Get current weather"""
try:
url = f"{self.base_url}/weather"
params = {
'q': self.default_location,
'appid': self.api_key,
'units': self.units
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
weather = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
return f"Current weather in {self.default_location}: {weather}, {temp}°C, humidity {humidity}%"
except requests.exceptions.RequestException as e:
self.logger.error(f"Weather API error: {e}")
return "Sorry, I couldn't get the weather information."
def _get_forecast(self):
"""Get weather forecast"""
try:
url = f"{self.base_url}/forecast"
params = {
'q': self.default_location,
'appid': self.api_key,
'units': self.units
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
forecast = data['list'][0] # Next 3 hours
weather = forecast['weather'][0]['description']
temp = forecast['main']['temp']
time = forecast['dt_txt']
return f"Weather forecast for {time}: {weather}, {temp}°C"
except requests.exceptions.RequestException as e:
self.logger.error(f"Weather forecast API error: {e}")
return "Sorry, I couldn't get the weather forecast."
def _get_temperature(self):
"""Get current temperature"""
try:
url = f"{self.base_url}/weather"
params = {
'q': self.default_location,
'appid': self.api_key,
'units': self.units
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
temp = data['main']['temp']
feels_like = data['main']['feels_like']
return f"Current temperature in {self.default_location}: {temp}°C (feels like {feels_like}°C)"
except requests.exceptions.RequestException as e:
self.logger.error(f"Temperature API error: {e}")
return "Sorry, I couldn't get the temperature information."
def get_status(self):
"""Get plugin status"""
return {
"name": self.name,
"version": self.version,
"enabled": self.enabled,
"status": "running" if self.enabled else "disabled",
"api_connected": bool(self.api_key)
}
```
### **News Plugin**
```python
# plugins/news_plugin/news_plugin.py
from plugins.base.plugin import BasePlugin
import requests
import json
class NewsPlugin(BasePlugin):
"""News information plugin"""
def __init__(self, config):
super().__init__(config)
self.api_key = config.get('api_key')
self.sources = config.get('sources', ['bbc-news', 'cnn'])
self.max_articles = config.get('max_articles', 5)
self.base_url = "https://newsapi.org/v2"
def initialize(self):
"""Initialize news plugin"""
if not self.api_key:
raise ValueError("News API key is required")
self.logger.info("News plugin initialized")
def process_command(self, command, context=None):
"""Process news commands"""
command_lower = command.lower()
if "news" in command_lower:
return self._get_latest_news()
elif "headlines" in command_lower:
return self._get_headlines()
elif "breaking" in command_lower:
return self._get_breaking_news()
else:
return "I can help with news information. Ask me about latest news, headlines, or breaking news."
def _get_latest_news(self):
"""Get latest news"""
try:
url = f"{self.base_url}/everything"
params = {
'sources': ','.join(self.sources),
'apiKey': self.api_key,
'pageSize': self.max_articles,
'sortBy': 'publishedAt'
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
articles = data['articles']
if not articles:
return "No news articles found."
news_summary = "Latest news:\n"
for i, article in enumerate(articles[:3], 1):
title = article['title']
source = article['source']['name']
news_summary += f"{i}. {title} ({source})\n"
return news_summary
except requests.exceptions.RequestException as e:
self.logger.error(f"News API error: {e}")
return "Sorry, I couldn't get the latest news."
def _get_headlines(self):
"""Get news headlines"""
try:
url = f"{self.base_url}/top-headlines"
params = {
'sources': ','.join(self.sources),
'apiKey': self.api_key,
'pageSize': self.max_articles
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
articles = data['articles']
if not articles:
return "No headlines found."
headlines = "Top headlines:\n"
for i, article in enumerate(articles[:3], 1):
title = article['title']
headlines += f"{i}. {title}\n"
return headlines
except requests.exceptions.RequestException as e:
self.logger.error(f"Headlines API error: {e}")
return "Sorry, I couldn't get the headlines."
def _get_breaking_news(self):
"""Get breaking news"""
try:
url = f"{self.base_url}/top-headlines"
params = {
'sources': ','.join(self.sources),
'apiKey': self.api_key,
'pageSize': 3,
'sortBy': 'publishedAt'
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
articles = data['articles']
if not articles:
return "No breaking news found."
breaking_news = "Breaking news:\n"
for i, article in enumerate(articles, 1):
title = article['title']
breaking_news += f"{i}. {title}\n"
return breaking_news
except requests.exceptions.RequestException as e:
self.logger.error(f"Breaking news API error: {e}")
return "Sorry, I couldn't get the breaking news."
def get_status(self):
"""Get plugin status"""
return {
"name": self.name,
"version": self.version,
"enabled": self.enabled,
"status": "running" if self.enabled else "disabled",
"api_connected": bool(self.api_key),
"sources": self.sources
}
```
## 🎯 Next Steps
After setting up plugins:
1. **[Test Plugin Functionality](../features/voice-interaction.md)** - Verify plugins work correctly
2. **[Create Custom Plugins](../guides/custom-plugins.md)** - Build your own plugins
3. **[Plugin Management](../configuration/advanced.md)** - Advanced plugin configuration
4. **[Monitor Plugin Performance](../guides/monitoring.md)** - Track plugin health
## 🆘 Need Help?
- **Plugin Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Plugin Development?** See [Custom Plugins](../guides/custom-plugins.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Plugin Structure**
```
plugins/
├── __init__.py
├── base/
│ └── plugin.py
├── my_plugin/
│ ├── __init__.py
│ ├── my_plugin.py
│ └── config.yaml
```
### **Plugin Methods**
- `initialize()` - Initialize plugin
- `process_command()` - Process voice commands
- `get_status()` - Get plugin status
- `cleanup()` - Cleanup resources
### **Configuration**
```yaml
plugins:
enabled: true
plugin_dir: plugins/
auto_load: true
```
---
**Your plugin system is ready! 🎉**
👉 **[Next: API Reference →](api.md)**

View file

@ -0,0 +1,581 @@
# 🎤 Voice Interaction
Xiaozhi's voice interaction system enables natural conversations with your ESP32 devices. This guide covers how voice recognition, language processing, and speech synthesis work together to create seamless voice experiences.
## 🎯 How Voice Interaction Works
### **Voice Processing Pipeline**
```mermaid
graph TB
A[ESP32 Device] -->|Audio Stream| B[Voice Activity Detection]
B -->|Speech Detected| C[Speech Recognition]
C -->|Text| D[Language Processing]
D -->|Response| E[Text-to-Speech]
E -->|Audio| A
F[Wake Word] --> B
G[ASR Provider] --> C
H[LLM Provider] --> D
I[TTS Provider] --> E
```
### **Processing Steps**
1. **🎤 Audio Capture**: ESP32 captures audio from microphone
2. **🔍 Voice Activity Detection**: Detects when speech starts/stops
3. **📝 Speech Recognition**: Converts speech to text
4. **🧠 Language Processing**: Understands intent and generates response
5. **🔊 Speech Synthesis**: Converts response to audio
6. **📡 Audio Output**: ESP32 plays synthesized speech
## 🔍 Voice Activity Detection (VAD)
### **What is VAD?**
Voice Activity Detection determines when someone is speaking, filtering out background noise and silence. This improves accuracy and reduces unnecessary processing.
### **VAD Providers**
#### **SileroVAD (Default)**
```yaml
VAD:
SileroVAD:
type: silero_vad
model_path: models/silero_vad.jit
threshold: 0.5
min_speech_duration: 0.25
min_silence_duration: 0.5
```
**Features:**
- **High accuracy** speech detection
- **Low latency** processing
- **Noise robust** performance
- **Free** and open source
#### **WebRTC VAD**
```yaml
VAD:
WebRTCVAD:
type: webrtc_vad
mode: 2
sample_rate: 16000
frame_duration: 30
```
**Features:**
- **Lightweight** processing
- **Real-time** performance
- **Configurable** sensitivity
- **Free** implementation
### **VAD Configuration**
```yaml
# VAD settings
vad:
enabled: true
provider: SileroVAD
sensitivity: 0.5 # 0.0 = most sensitive, 1.0 = least sensitive
min_speech_ms: 250 # Minimum speech duration
min_silence_ms: 500 # Minimum silence duration
pre_padding_ms: 100 # Audio before speech
post_padding_ms: 100 # Audio after speech
```
## 📝 Speech Recognition (ASR)
### **ASR Providers**
#### **WhisperASR (Recommended)**
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base # tiny, base, small, medium, large
device: auto # auto, cpu, cuda
language: null # null for auto-detect
temperature: 0.0
compression_ratio_threshold: 2.4
logprob_threshold: -1.0
no_speech_threshold: 0.6
```
**Model Comparison:**
| Model | Size | Speed | Accuracy | Use Case |
|-------|------|-------|----------|----------|
| **tiny** | 39MB | Fastest | Basic | Quick testing |
| **base** | 74MB | Fast | Good | General use |
| **small** | 244MB | Medium | Better | Production |
| **medium** | 769MB | Slow | High | High accuracy |
| **large** | 1550MB | Slowest | Best | Maximum quality |
#### **OpenAI ASR**
```yaml
ASR:
OpenAIASR:
type: openai
api_key: your_openai_api_key
model_name: whisper-1
language: en
response_format: json
temperature: 0.0
```
#### **Groq ASR**
```yaml
ASR:
GroqASR:
type: openai
base_url: https://api.groq.com/openai/v1
api_key: your_groq_api_key
model_name: whisper-large-v3
language: en
```
### **ASR Configuration**
```yaml
# ASR settings
asr:
provider: WhisperASR
language: null # null for auto-detect
sample_rate: 16000 # Audio sample rate
channels: 1 # Mono audio
chunk_size: 1024 # Audio chunk size
timeout: 30 # Processing timeout
retry_count: 3 # Retry attempts
```
## 🧠 Language Processing (LLM)
### **LLM Providers**
#### **OpenAI LLM**
```yaml
LLM:
OpenAILLM:
type: openai
api_key: your_openai_api_key
model_name: gpt-4o-mini
temperature: 0.7
max_tokens: 1000
top_p: 1.0
frequency_penalty: 0.0
presence_penalty: 0.0
```
**Model Options:**
- **gpt-4o**: Latest, most capable
- **gpt-4o-mini**: Faster, cost-effective
- **gpt-3.5-turbo**: Budget option
#### **LMStudio LLM**
```yaml
LLM:
LMStudioLLM:
type: openai
base_url: http://localhost:1234/v1
api_key: lm-studio
model_name: llama3.1:8b
temperature: 0.7
max_tokens: 1000
```
#### **Ollama LLM**
```yaml
LLM:
OllamaLLM:
type: openai
base_url: http://localhost:11434/v1
api_key: ollama
model_name: llama3.1:8b
temperature: 0.7
```
### **LLM Configuration**
```yaml
# LLM settings
llm:
provider: OpenAILLM
system_prompt: |
You are Xiaozhi, a helpful AI assistant.
Respond naturally and conversationally.
max_tokens: 1000
temperature: 0.7
top_p: 1.0
timeout: 30
retry_count: 3
```
## 🔊 Text-to-Speech (TTS)
### **TTS Providers**
#### **EdgeTTS (Free)**
```yaml
TTS:
EdgeTTS:
type: edge_tts
voice: en-US-AriaNeural
rate: +0%
pitch: +0Hz
volume: +0%
output_format: mp3
```
**Voice Options:**
- **en-US-AriaNeural**: Female, natural
- **en-US-GuyNeural**: Male, natural
- **en-US-JennyNeural**: Female, friendly
- **en-US-RyanNeural**: Male, professional
#### **OpenAI TTS**
```yaml
TTS:
OpenAITTS:
type: openai
api_key: your_openai_api_key
model_name: tts-1
voice: alloy
response_format: mp3
speed: 1.0
```
**Voice Options:**
- **alloy**: Neutral, balanced
- **echo**: Male, clear
- **fable**: British accent
- **onyx**: Deep, authoritative
- **nova**: Young, energetic
- **shimmer**: Soft, gentle
#### **Azure TTS**
```yaml
TTS:
AzureTTS:
type: azure
subscription_key: your_azure_key
region: your_azure_region
voice: en-US-AriaNeural
rate: +0%
pitch: +0Hz
```
### **TTS Configuration**
```yaml
# TTS settings
tts:
provider: EdgeTTS
voice: en-US-AriaNeural
rate: +0% # Speech rate
pitch: +0Hz # Voice pitch
volume: +0% # Volume level
output_format: mp3 # Audio format
sample_rate: 22050 # Output sample rate
timeout: 30 # Processing timeout
```
## 🎯 Wake Word Detection
### **What is Wake Word Detection?**
Wake word detection allows the device to respond only when a specific phrase is spoken, preventing accidental activations and saving power.
### **Wake Word Configuration**
```yaml
# Wake word settings
wake_word:
enabled: true
phrase: "Hello Xiaozhi"
sensitivity: 0.5 # 0.0 = most sensitive, 1.0 = least sensitive
timeout: 5 # Seconds to listen after wake word
cooldown: 2 # Seconds before listening again
```
### **Custom Wake Words**
```yaml
# Multiple wake words
wake_words:
- "Hello Xiaozhi"
- "Hey Assistant"
- "Wake up"
- "Computer"
```
## 🔄 Conversation Flow
### **Basic Conversation**
```mermaid
sequenceDiagram
participant U as User
participant E as ESP32
participant S as Server
participant A as ASR
participant L as LLM
participant T as TTS
U->>E: Says "Hello Xiaozhi"
E->>S: Sends audio stream
S->>A: Processes speech
A->>S: Returns text
S->>L: Processes text
L->>S: Returns response
S->>T: Synthesizes speech
T->>S: Returns audio
S->>E: Sends audio
E->>U: Plays response
```
### **Conversation States**
```yaml
# Conversation state management
conversation:
states:
idle: "Waiting for wake word"
listening: "Processing speech"
thinking: "Generating response"
speaking: "Playing response"
error: "Handling error"
timeouts:
listening: 10 # Seconds to listen
thinking: 30 # Seconds to generate response
speaking: 60 # Seconds to play response
error: 5 # Seconds to recover
```
## ⚙️ Advanced Configuration
### **Audio Processing**
```yaml
# Audio processing settings
audio:
input:
sample_rate: 16000
channels: 1
bit_depth: 16
buffer_size: 1024
noise_reduction: true
echo_cancellation: true
output:
sample_rate: 22050
channels: 1
bit_depth: 16
buffer_size: 1024
volume: 0.8
equalizer: true
```
### **Performance Optimization**
```yaml
# Performance settings
performance:
streaming: true # Enable streaming
parallel_processing: true # Process audio while speaking
cache_responses: true # Cache common responses
preload_models: true # Preload AI models
gpu_acceleration: true # Use GPU when available
```
### **Error Handling**
```yaml
# Error handling settings
error_handling:
retry_count: 3
retry_delay: 1
fallback_responses:
- "I didn't catch that, could you repeat?"
- "Sorry, I'm having trouble understanding."
- "Could you speak a bit louder?"
timeout_responses:
- "I'm still thinking..."
- "Let me process that..."
```
## 🧪 Testing Voice Interaction
### **Basic Tests**
#### **Wake Word Test**
```bash
# Test wake word detection
curl -X POST http://localhost:8000/api/test/wake-word \
-H "Content-Type: application/json" \
-d '{"audio_file": "wake_word_test.wav"}'
```
#### **Speech Recognition Test**
```bash
# Test speech recognition
curl -X POST http://localhost:8000/api/test/asr \
-H "Content-Type: application/json" \
-d '{"audio_file": "speech_test.wav"}'
```
#### **Language Processing Test**
```bash
# Test language processing
curl -X POST http://localhost:8000/api/test/llm \
-H "Content-Type: application/json" \
-d '{"message": "Hello, how are you?"}'
```
#### **Speech Synthesis Test**
```bash
# Test speech synthesis
curl -X POST http://localhost:8000/api/test/tts \
-H "Content-Type: application/json" \
-d '{"text": "Hello, this is a test."}'
```
### **End-to-End Test**
```bash
# Complete voice interaction test
curl -X POST http://localhost:8000/api/test/voice-interaction \
-H "Content-Type: application/json" \
-d '{"audio_file": "complete_test.wav"}'
```
## 🛠️ Troubleshooting
### **Common Issues**
#### **No Wake Word Detection**
1. **Check microphone** connections
2. **Adjust sensitivity** settings
3. **Test with different** wake phrases
4. **Check audio levels**
#### **Poor Speech Recognition**
1. **Improve microphone** positioning
2. **Reduce background** noise
3. **Use appropriate** ASR model
4. **Check audio quality**
#### **Slow Response Times**
1. **Enable streaming** processing
2. **Use faster** AI models
3. **Optimize network** connection
4. **Check server** performance
#### **Audio Quality Issues**
1. **Check speaker** connections
2. **Adjust volume** levels
3. **Use better** audio components
4. **Optimize audio** processing
### **Performance Optimization**
#### **Latency Reduction**
```yaml
# Optimize for low latency
performance:
streaming: true
parallel_processing: true
preload_models: true
gpu_acceleration: true
audio_buffer_size: 512
```
#### **Accuracy Improvement**
```yaml
# Optimize for accuracy
asr:
model_name: large # Use larger model
language: en # Specify language
temperature: 0.0 # Reduce randomness
llm:
temperature: 0.7 # Balanced creativity
max_tokens: 1000 # Sufficient length
```
## 🎯 Best Practices
### **Voice Interaction Design**
1. **Keep responses concise** - Users prefer short, clear responses
2. **Use natural language** - Avoid robotic or formal speech
3. **Provide feedback** - Let users know when you're processing
4. **Handle errors gracefully** - Provide helpful error messages
### **Performance Optimization**
1. **Use appropriate models** - Balance speed and accuracy
2. **Enable streaming** - Process audio while speaking
3. **Cache responses** - Store common responses
4. **Monitor performance** - Track latency and accuracy
### **User Experience**
1. **Test with real users** - Get feedback on voice interaction
2. **Handle interruptions** - Allow users to interrupt responses
3. **Provide alternatives** - Offer text input as backup
4. **Customize responses** - Adapt to user preferences
## 🎯 Next Steps
### **After Voice Setup**
1. **[Integrations](../features/integrations.md)** - Connect to other services
2. **[Plugin System](../features/plugins.md)** - Add custom functionality
3. **[API Reference](../features/api.md)** - Programmatic access
4. **[Advanced Configuration](../configuration/advanced.md)** - Fine-tune settings
### **Advanced Topics**
- **[Custom Wake Words](../configuration/advanced.md)** - Create custom wake phrases
- **[Voice Training](../configuration/advanced.md)** - Train for specific users
- **[Multi-language Support](../configuration/advanced.md)** - Support multiple languages
## 🆘 Need Help?
- **Voice Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Configuration Problems?** See [Configuration Guide](../configuration/basic-setup.md)
- **Performance Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Voice Providers**
- **ASR**: WhisperASR (local), OpenAIASR (cloud)
- **LLM**: OpenAILLM (cloud), LMStudioLLM (local)
- **TTS**: EdgeTTS (free), OpenAITTS (premium)
### **Key Settings**
- **Wake Word**: "Hello Xiaozhi"
- **Language**: Auto-detect or specify
- **Voice**: en-US-AriaNeural
- **Sample Rate**: 16kHz input, 22kHz output
### **Testing Commands**
```bash
# Test wake word
curl -X POST http://localhost:8000/api/test/wake-word
# Test speech recognition
curl -X POST http://localhost:8000/api/test/asr
# Test complete interaction
curl -X POST http://localhost:8000/api/test/voice-interaction
```
---
**Your voice interaction system is ready! 🎉**
👉 **[Next: Integrations →](../features/integrations.md)**

View file

@ -1,138 +0,0 @@
# esp32固件编译
## 第1步 准备你的ota地址
如果你,使用的是本项目0.3.12版本,不管是简单Server部署还是全模块部署,都会有ota地址。
由于简单Server部署和全模块部署的OTA地址设置方式不一样,请你选择下面的具体方式:
### 如果你用的是简单Server部署
此刻,请你用浏览器打开你的ota地址,例如我的ota地址
```
http://192.168.1.25:8003/xiaozhi/ota/
```
如果显示“OTA接口运行正常,向设备发送的websocket地址是:ws://xxx:8000/xiaozhi/v1/
你可以启动`digital-human`模块后打开`index.html`测试一下,是否能连上ota页面输出的websocket地址。
如果访问不到,你需要到配置文件`.config.yaml`里修改`server.websocket`的地址,重启后再重新测试,直到`index.html`能正常访问。
成功后,请往下进行第2步
### 如果你用的是全模块部署
此刻,请你用浏览器打开你的ota地址,例如我的ota地址
```
http://192.168.1.25:8002/xiaozhi/ota/
```
如果显示“OTA接口运行正常,websocket集群数量:X”。那就往下进行2步。
如果显示“OTA接口运行不正常”,大概是你还没在`智控台`配置`Websocket`地址。那就:
- 1、使用超级管理员登录智控台
- 2、顶部菜单点击`参数管理`
- 3、在列表中找到`server.websocket`项目,输入你的`Websocket`地址。例如我的就是
```
ws://192.168.1.25:8000/xiaozhi/v1/
```
配置完后,再使用浏览器刷新你的ota接口地址,看看是不是正常了。如果还不正常就,就再次确认一下Websocket是否正常启动,是否配置了Websocket地址。
## 第2步 配置环境
先按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf)
## 第3步 打开配置文件
配置好编译环境后,下载虾哥iaozhi-esp32项目源码,
从这里下载虾哥[xiaozhi-esp32项目源码](https://github.com/78/xiaozhi-esp32)。
下载后,打开`xiaozhi-esp32/main/Kconfig.projbuild`文件。
## 第4步 修改OTA地址
找到`OTA_URL`的`default`的内容,把`https://api.tenclass.net/xiaozhi/ota/`
改成你自己的地址,例如,我的接口地址是`http://192.168.1.25:8002/xiaozhi/ota/`,就把内容改成这个。
修改前:
```
config OTA_URL
string "Default OTA URL"
default "https://api.tenclass.net/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
修改后:
```
config OTA_URL
string "Default OTA URL"
default "http://192.168.1.25:8002/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
## 第4步 设置编译参数
设置编译参数
```
# 终端命令行进入xiaozhi-esp32的根目录
cd xiaozhi-esp32
# 例如我使用的板子是esp32s3,所以设置编译目标为esp32s3,如果你的板子是其他型号,请替换成对应的型号
idf.py set-target esp32s3
# 进入菜单配置
idf.py menuconfig
```
进入菜单配置后,再进入`Xiaozhi Assistant`,将`BOARD_TYPE`设置你板子的具体型号
保存退出,回到终端命令行。
## 第5步 编译固件
```
idf.py build
```
## 第6步 打包bin固件
```
cd scripts
python release.py
```
上面的打包命令执行完成后,会在项目根目录下的`build`目录下生成固件文件`merged-binary.bin`。
这个`merged-binary.bin`就是要烧录到硬件上的固件文件。
注意:如果执行到第二命令后,报了“zip”相关的错误,请忽略这个错误,只要`build`目录下生成固件文件`merged-binary.bin`
,对你没有太大影响,请继续。
## 第7步 烧录固件
将esp32设备连接电脑,使用chrome浏览器,打开以下网址
```
https://espressif.github.io/esp-launchpad/
```
打开这个教程,[Flash工具/Web端烧录固件(无IDF开发环境)](https://ccnphfhqs21z.feishu.cn/wiki/Zpz4wXBtdimBrLk25WdcXzxcnNS)。
翻到:`方式二:ESP-Launchpad 浏览器WEB端烧录`,从`3. 烧录固件/下载到开发板`开始,按照教程操作。
烧录成功且联网成功后,通过唤醒词唤醒小智,留意server端输出的控制台信息。
## 常见问题
以下是一些常见问题,供参考:
[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)
[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)
[3、TTS 经常失败,经常超时](./FAQ.md)
[4、使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)
[5、如何提高小智对话响应速度?](./FAQ.md)
[6、我说话很慢,停顿时小智老是抢话](./FAQ.md)
[7、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md)

View file

@ -1,54 +0,0 @@
# 基于虾哥编译好的固件配置自定义服务器
## 第1步 确认版本
烧录虾哥已经编译好的[1.6.1版本以上固件](https://github.com/78/xiaozhi-esp32/releases)
## 第2步 准备你的ota地址
如果你按照教程使用的是全模块部署,就应该会有ota地址。
此刻,请你用浏览器打开你的ota地址,例如我的ota地址
```
https://2662r3426b.vicp.fun/xiaozhi/ota/
```
如果显示“OTA接口运行正常,websocket集群数量:X”。那就往下。
如果显示“OTA接口运行不正常”,大概是你还没在`智控台`配置`Websocket`地址。那就:
- 1、使用超级管理员登录智控台
- 2、顶部菜单点击`参数管理`
- 3、在列表中找到`server.websocket`项目,输入你的`Websocket`地址。例如我的就是
```
wss://2662r3426b.vicp.fun/xiaozhi/v1/
```
配置完后,再使用浏览器刷新你的ota接口地址,看看是不是正常了。如果还不正常就,就再次确认一下Websocket是否正常启动,是否配置了Websocket地址。
## 第3步 进入配网模式
进入机器的配网模式,在页面顶部,点击“高级选项”,在里面输入你服务器的`ota`地址,点击保存。重启设备
![请参考-OTA地址设置](../docs/images/firmware-setting-ota.png)
## 第4步 唤醒小智,查看日志输出
唤醒小智,看看日志是不是正常输出。
## 常见问题
以下是一些常见问题,供参考:
[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)
[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)
[3、TTS 经常失败,经常超时](./FAQ.md)
[4、使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)
[5、如何提高小智对话响应速度?](./FAQ.md)
[6、我说话很慢,停顿时小智老是抢话](./FAQ.md)
[7、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md)

View file

@ -1,72 +0,0 @@
登录AutoDL,租赁镜像
选择镜像:
```
PyTorch / 2.1.0 / 3.10(ubuntu22.04) / cuda 12.1
```
机器开机后,设置学术加速
```
source /etc/network_turbo
```
进入工作目录
```
cd autodl-tmp/
```
拉取项目
```
git clone https://gitclone.com/github.com/fishaudio/fish-speech.git ; cd fish-speech
```
安装依赖
```
pip install -e.
```
如果报错,安装portaudio
```
apt-get install portaudio19-dev -y
```
安装后执行
```
pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu121
```
下载模型
```
cd tools
python download_models.py
```
下载完模型后运行接口
```
python -m tools.api_server --listen 0.0.0.0:6006
```
然后用浏览器去到aotodl实例页面
```
https://autodl.com/console/instance/list
```
如下图点击你刚才机器的`自定义服务`按钮,开启端口转发服务
![自定义服务](images/fishspeech/autodl-01.png)
端口转发服务设置完成后,你本地电脑打开网址`http://localhost:6006/`,就可以访问fish-speech的接口了
![服务预览](images/fishspeech/autodl-02.png)
如果你是单模块部署,核心配置如下
```
selected_module:
TTS: FishSpeech
TTS:
FishSpeech:
reference_audio: ["config/assets/wakeup_words.wav",]
reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",]
api_key: "123"
api_url: "http://127.0.0.1:6006/v1/tts"
```
然后重启服务

View file

@ -0,0 +1,347 @@
# 🔌 First Device Setup
Connect your first ESP32 device to Xiaozhi and start having conversations! This guide will walk you through the complete process from hardware setup to voice interaction.
## 🎯 What You'll Accomplish
By the end of this guide, you'll have:
- ✅ ESP32 device properly configured
- ✅ Firmware compiled and flashed
- ✅ Device connected to Xiaozhi server
- ✅ Voice interaction working
- ✅ Basic commands responding
## 🔧 Hardware Setup
### **Required Components**
#### **ESP32 Development Board**
Choose one of these recommended options:
- **ESP32-S3-DevKitC-1** - Official Espressif board
- **ESP32-S3-BOX** - With built-in microphone and speaker
- **ESP32-S3-BOX-3** - Latest version with improved audio
- **ESP32-S3-Korvo-2** - Audio-focused development board
#### **Audio Components** (if not built-in)
- **Microphone**: SPH0645LM4H or INMP441
- **Speaker**: Small speaker (8Ω, 0.5W+) with amplifier
- **Amplifier**: PAM8403 or MAX98357A
#### **Connection Components**
- **USB Cable**: Type-C or Micro-USB
- **Breadboard**: For prototyping
- **Jumper Wires**: For connections
- **Resistors**: 10kΩ, 4.7kΩ
### **Wiring Diagram**
```mermaid
graph TB
A[ESP32-S3] --> B[Microphone]
A --> C[Speaker Amplifier]
A --> D[USB Power]
B --> E[SPH0645LM4H]
C --> F[PAM8403]
C --> G[Speaker]
H[3.3V] --> B
H --> C
I[GND] --> B
I --> C
I --> G
```
#### **Pin Connections**
| Component | ESP32-S3 Pin | Notes |
|-----------|--------------|-------|
| Microphone VCC | 3.3V | Power supply |
| Microphone GND | GND | Ground |
| Microphone WS | GPIO 15 | Word select |
| Microphone BCK | GPIO 16 | Bit clock |
| Microphone DIN | GPIO 17 | Data input |
| Amplifier VCC | 3.3V | Power supply |
| Amplifier GND | GND | Ground |
| Amplifier DIN | GPIO 18 | Audio data |
| Amplifier BCK | GPIO 19 | Bit clock |
| Amplifier LRC | GPIO 20 | Left/right clock |
## 💾 Firmware Preparation
### **Step 1: Get Firmware Source**
```bash
# Clone the ESP32 firmware repository
git clone https://github.com/78/xiaozhi-esp32.git
cd xiaozhi-esp32
```
### **Step 2: Configure Build Environment**
#### **Install ESP-IDF**
```bash
# Download ESP-IDF
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh
# Set up environment
. ./export.sh
```
#### **Alternative: Use ESP-IDF Installer**
- **Windows**: Download from [Espressif](https://espressif.com)
- **macOS**: `brew install espressif/esp-idf/esp-idf`
- **Linux**: Follow [official guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/)
### **Step 3: Configure Firmware**
1. **Open project** in ESP-IDF
2. **Run configuration**:
```bash
idf.py menuconfig
```
3. **Configure settings**:
- **WiFi**: Set your network credentials
- **Audio**: Configure microphone and speaker pins
- **WebSocket**: Set server URL (will be configured later)
### **Step 4: Build Firmware**
```bash
# Build the firmware
idf.py build
# This creates firmware.bin in build/ directory
```
## 🔌 Device Flashing
### **Method 1: Web-based Flashing (Easiest)**
1. **Go to**: [ESP-Launchpad](https://espressif.github.io/esp-launchpad/)
2. **Upload firmware**: Select your `firmware.bin` file
3. **Connect ESP32**: Via USB cable
4. **Select port**: Choose your ESP32's COM port
5. **Flash**: Click "Flash" and wait for completion
### **Method 2: Command Line**
```bash
# Install esptool
pip install esptool
# Flash firmware (adjust port and baud rate)
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 firmware.bin
```
### **Method 3: ESP-IDF**
```bash
# Flash using ESP-IDF
idf.py -p COM3 flash
# Monitor output
idf.py -p COM3 monitor
```
## 🌐 Network Configuration
### **Step 1: Configure WiFi**
1. **Power on** your ESP32 device
2. **Wait for WiFi setup** mode (LED indication)
3. **Connect to ESP32** WiFi network
4. **Open browser** to configuration page
5. **Enter WiFi credentials**:
- Network name (SSID)
- Password
- Server URL: `ws://YOUR_SERVER_IP:8000/xiaozhi/v1/`
### **Step 2: Verify Connection**
1. **Check OTA interface**: http://YOUR_SERVER_IP:8003/xiaozhi/ota/
2. **Look for your device** in the connected devices list
3. **Verify WebSocket connection** is active
## 🎤 Audio Testing
### **Step 1: Test Microphone**
1. **Say "Hello"** near the microphone
2. **Check server logs** for audio input
3. **Verify audio levels** are appropriate
### **Step 2: Test Speaker**
1. **Send test command** via web interface
2. **Listen for audio output**
3. **Adjust volume** if needed
### **Step 3: Test Voice Interaction**
1. **Say**: "Hello Xiaozhi"
2. **Wait for response**
3. **Try basic commands**:
- "What's the weather?"
- "Tell me a joke"
- "What time is it?"
## ⚙️ Device Configuration
### **Web Interface Configuration**
1. **Open web interface**: http://YOUR_SERVER_IP:8001
2. **Go to Devices** section
3. **Find your ESP32** device
4. **Configure settings**:
- Device name
- Audio settings
- Wake word sensitivity
- Response behavior
### **Advanced Configuration**
```yaml
# Device configuration example
device:
name: "My ESP32 Assistant"
wake_word: "Hello Xiaozhi"
audio:
microphone_gain: 1.0
speaker_volume: 0.8
noise_reduction: true
behavior:
response_delay: 0.5
max_response_length: 100
enable_interruptions: true
```
## 🧪 Testing and Validation
### **Basic Functionality Tests**
1. **Wake Word Detection**
- Say "Hello Xiaozhi"
- Verify device responds
2. **Voice Recognition**
- Speak clearly
- Check text accuracy
3. **Response Generation**
- Ask questions
- Verify appropriate responses
4. **Audio Output**
- Listen to synthesized speech
- Check audio quality
### **Advanced Tests**
1. **Multiple Commands**
- Try various command types
- Test conversation flow
2. **Error Handling**
- Test with unclear speech
- Verify graceful error handling
3. **Performance**
- Measure response times
- Check resource usage
## 🛠️ Troubleshooting
### **Device Won't Connect**
1. **Check WiFi credentials**
2. **Verify server URL** format
3. **Check firewall** settings
4. **Restart device** and server
### **No Audio Input**
1. **Check microphone** connections
2. **Verify audio** configuration
3. **Test microphone** separately
4. **Check audio levels**
### **No Audio Output**
1. **Check speaker** connections
2. **Verify amplifier** power
3. **Test speaker** separately
4. **Check volume** settings
### **Poor Voice Recognition**
1. **Improve microphone** positioning
2. **Reduce background** noise
3. **Adjust microphone** gain
4. **Check audio** quality
## 🎉 Success! What's Next?
### **🎯 Try These Features**
- **Voice Commands**: Control your device with voice
- **Conversations**: Have natural conversations
- **Custom Responses**: Create personalized responses
- **Integrations**: Connect to other services
### **🔧 Advanced Configuration**
1. **Custom Wake Words**: Set your own wake phrase
2. **Audio Optimization**: Fine-tune audio settings
3. **Response Customization**: Personalize AI responses
4. **Plugin Integration**: Add custom functionality
### **📚 Next Steps**
- **[Configuration Guide](../configuration/basic-setup.md)** - Fine-tune your setup
- **[Features Guide](../features/voice-interaction.md)** - Explore capabilities
- **[Integrations Guide](../guides/homeassistant.md)** - Connect to other systems
- **[Custom Plugins](../guides/custom-plugins.md)** - Add custom functionality
## 🆘 Need Help?
- **Hardware Issues?** Check [Hardware Troubleshooting](../hardware/troubleshooting.md)
- **Configuration Problems?** See [Configuration Guide](../configuration/basic-setup.md)
- **General Issues?** Browse [Troubleshooting Guide](../support/troubleshooting.md)
---
## 🎯 Quick Reference
### **Key Commands**
```bash
# Build firmware
idf.py build
# Flash firmware
idf.py -p COM3 flash
# Monitor output
idf.py -p COM3 monitor
```
### **Key URLs**
- **OTA Interface**: http://YOUR_SERVER_IP:8003/xiaozhi/ota/
- **Web Interface**: http://YOUR_SERVER_IP:8001
- **Device Config**: Web Interface → Devices
### **Pin Reference**
- **Microphone**: GPIO 15-17
- **Speaker**: GPIO 18-20
- **Power**: 3.3V, GND
---
**Congratulations! Your ESP32 device is now connected and ready for voice interaction! 🎉**
👉 **[Next: Configuration Guide →](../configuration/basic-setup.md)**

View file

@ -0,0 +1,160 @@
# 🎯 What is Xiaozhi ESP32 Server?
Xiaozhi ESP32 Server is a powerful backend service that transforms ESP32 microcontrollers into intelligent voice-controlled devices. Think of it as the "brain" that enables your ESP32 to understand speech, process requests, and respond with synthesized voice.
## 🌟 What Makes Xiaozhi Special?
### 🎤 **Voice-First Design**
- **Real-time speech recognition** using Whisper, OpenAI, or other ASR providers
- **Natural language processing** powered by OpenAI, LMStudio, or local LLMs
- **High-quality speech synthesis** with EdgeTTS, OpenAI TTS, or other providers
- **Low-latency communication** via WebSocket for responsive interactions
### 🔌 **ESP32 Integration**
- **Direct ESP32 support** - works with most ESP32 development boards
- **WebSocket communication** - reliable, real-time data exchange
- **OTA updates** - update firmware over-the-air
- **Hardware flexibility** - supports various ESP32 configurations
### 🤖 **AI-Powered Intelligence**
- **Multiple AI providers** - OpenAI, LMStudio, Whisper, EdgeTTS
- **Local processing** - run AI models locally for privacy
- **Cloud integration** - leverage cloud AI services when needed
- **Customizable responses** - tailor AI behavior to your needs
### 🏠 **Smart Home Ready**
- **HomeAssistant integration** - seamless smart home connectivity
- **MQTT support** - communicate with IoT devices
- **Plugin system** - extend functionality with custom plugins
- **REST API** - integrate with other systems
## 🎮 What Can You Build?
### 🏠 **Smart Home Assistant**
Transform your ESP32 into a voice-controlled smart home hub:
- Control lights, thermostats, and appliances
- Get weather updates and news
- Set reminders and timers
- Answer questions about your home
### 🤖 **Voice-Controlled Robot**
Build an intelligent robot that responds to voice commands:
- Navigate using voice instructions
- Perform tasks based on spoken requests
- Provide status updates via voice
- Learn and adapt to your preferences
### 🎯 **Interactive Projects**
Create engaging interactive experiences:
- Voice-controlled games
- Educational tools
- Accessibility devices
- Creative installations
### 🏢 **Professional Solutions**
Deploy Xiaozhi in professional environments:
- Voice-controlled automation systems
- Customer service interfaces
- Industrial monitoring devices
- Educational platforms
## 🏗️ How It Works
```mermaid
graph TB
A[ESP32 Device] -->|WebSocket| B[Xiaozhi Server]
B --> C[Speech Recognition]
B --> D[Language Processing]
B --> E[Response Generation]
B --> F[Speech Synthesis]
C --> D
D --> E
E --> F
F -->|Audio| A
G[AI Providers] --> C
G --> D
G --> F
H[Plugins] --> B
I[HomeAssistant] --> B
J[MQTT] --> B
```
### 🔄 **The Voice Interaction Flow**
1. **🎤 Speech Input**: ESP32 captures audio and sends it to the server
2. **🧠 Speech Recognition**: Server converts speech to text using ASR
3. **💭 Language Processing**: LLM processes the text and generates responses
4. **🔊 Speech Synthesis**: Server converts response to audio
5. **📡 Audio Output**: ESP32 plays the synthesized speech
### 🔌 **Communication Protocol**
- **WebSocket Connection**: Real-time, bidirectional communication
- **Audio Streaming**: Efficient audio data transmission
- **Command Protocol**: Structured command and response format
- **Error Handling**: Robust error recovery and retry mechanisms
## 🎯 Key Features
### ✨ **Core Capabilities**
- **Real-time voice interaction** with sub-second response times
- **Multi-language support** for global accessibility
- **Offline operation** with local AI models
- **Cloud integration** for advanced AI capabilities
- **Extensible architecture** with plugin support
### 🛠️ **Developer Features**
- **REST API** for programmatic access
- **WebSocket API** for real-time communication
- **Plugin system** for custom functionality
- **Configuration management** via web interface
- **Comprehensive logging** for debugging
### 🔒 **Security & Privacy**
- **Local processing** options for sensitive data
- **Secure communication** with TLS support
- **Access control** and user management
- **Data privacy** with configurable retention
## 🚀 Why Choose Xiaozhi?
### 🎯 **For Beginners**
- **Easy setup** with Docker and guided configuration
- **Clear documentation** with step-by-step tutorials
- **Active community** for support and inspiration
- **Low cost** with free AI provider options
### 👨‍💻 **For Developers**
- **Open source** with full access to code
- **Extensible architecture** for custom features
- **Multiple AI providers** for flexibility
- **Professional APIs** for integration
### 🏢 **For Organizations**
- **Scalable deployment** options
- **Enterprise features** like user management
- **Integration capabilities** with existing systems
- **Professional support** and documentation
## 🎮 Getting Started
Ready to build something amazing? Here's how to get started:
1. **📋 Check Prerequisites** - [What you'll need](prerequisites.md)
2. **⚡ Quick Setup** - [Get running in 5 minutes](quick-start.md)
3. **🔌 Connect Device** - [Set up your first ESP32](first-device.md)
## 🤝 Community & Support
- **💬 GitHub Discussions** - Ask questions and share projects
- **🐛 Issue Tracker** - Report bugs and request features
- **📚 Documentation** - Comprehensive guides and references
- **🌟 Showcase** - Share your amazing projects
---
**Ready to transform your ESP32 into an intelligent voice assistant? Let's get started!** 🚀
👉 **[Next: Prerequisites →](prerequisites.md)**

View file

@ -0,0 +1,218 @@
# 📋 Prerequisites
Before you start building with Xiaozhi ESP32 Server, let's make sure you have everything you need for a smooth setup experience.
## 🖥️ System Requirements
### **Operating System**
- **Windows 10/11** (64-bit)
- **macOS 10.15+** (Intel or Apple Silicon)
- **Linux** (Ubuntu 20.04+, Debian 11+, CentOS 8+)
### **Hardware Requirements**
- **CPU**: 2+ cores, 2.0+ GHz
- **RAM**: 4GB minimum, 8GB recommended
- **Storage**: 10GB free space
- **Network**: Internet connection for AI services
### **Development Environment**
- **Python 3.10+** (for local installation)
- **Node.js 16+** (for web interface)
- **Git** (for cloning repositories)
## 🔧 Required Software
### **Essential Tools**
#### **Docker** (Recommended)
```bash
# Windows/macOS: Download from https://docker.com
# Linux: Install via package manager
sudo apt update
sudo apt install docker.io docker-compose
```
#### **Python Environment** (Alternative)
```bash
# Install Python 3.10+
# Windows: Download from python.org
# macOS: brew install python@3.10
# Linux: sudo apt install python3.10 python3.10-venv
```
#### **Git**
```bash
# Windows: Download from git-scm.com
# macOS: brew install git
# Linux: sudo apt install git
```
### **Optional but Recommended**
#### **Visual Studio Code**
- **Extensions**: Python, Docker, GitLens
- **Download**: [code.visualstudio.com](https://code.visualstudio.com)
#### **Postman** (API Testing)
- **Download**: [postman.com](https://postman.com)
## 🔌 Hardware Requirements
### **ESP32 Development Board**
Choose one of these popular options:
#### **🏆 Recommended Boards**
- **ESP32-S3-DevKitC-1** - Official Espressif board
- **ESP32-S3-BOX** - With built-in microphone and speaker
- **ESP32-S3-BOX-3** - Latest version with improved audio
- **ESP32-S3-Korvo-2** - Audio-focused development board
#### **💡 Budget Options**
- **ESP32-DevKitC** - Basic development board
- **ESP32-WROOM-32** - Module with development board
- **ESP32-S2-Saola-1** - Single-core option
#### **🎯 Specialized Boards**
- **ESP32-S3-BOX-Lite** - Compact version
- **ESP32-S3-USB-OTG** - USB OTG support
- **ESP32-S3-EYE** - With camera and microphone
### **Audio Components** (if not included)
#### **Microphone**
- **SPH0645LM4H** - Digital MEMS microphone
- **INMP441** - I2S digital microphone
- **MAX9814** - Analog microphone with AGC
#### **Speaker**
- **Small speaker** (8Ω, 0.5W+)
- **Amplifier module** (PAM8403, MAX98357A)
- **Audio jack** for external speakers
### **Additional Components**
- **USB Cable** (Type-C or Micro-USB)
- **Breadboard** and jumper wires
- **Resistors** (10kΩ, 4.7kΩ)
- **Capacitors** (100µF, 10µF)
## 🌐 Internet Requirements
### **AI Service Access**
You'll need access to at least one AI service:
#### **Free Options**
- **OpenAI API** - GPT models (requires API key)
- **Whisper** - Local speech recognition (free)
- **EdgeTTS** - Microsoft text-to-speech (free)
- **LMStudio** - Local LLM hosting (free)
#### **Paid Options**
- **OpenAI GPT-4** - Advanced language models
- **Google Gemini** - Alternative LLM provider
- **Azure Cognitive Services** - Microsoft AI services
### **Network Configuration**
- **Port 8000** - WebSocket communication
- **Port 8001** - Web management interface
- **Port 8003** - OTA updates
- **HTTPS** - For secure connections (optional)
## 🎯 AI Provider Setup
### **Choose Your AI Stack**
#### **🆓 Free Tier Setup**
```yaml
ASR: WhisperASR # Local speech recognition
LLM: LMStudioLLM # Local language model
TTS: EdgeTTS # Free text-to-speech
```
#### **💎 Premium Setup**
```yaml
ASR: OpenAIASR # OpenAI Whisper API
LLM: OpenAILLM # GPT-4 or GPT-3.5
TTS: OpenAITTS # OpenAI TTS
```
#### **🔒 Privacy-Focused Setup**
```yaml
ASR: WhisperASR # Local processing
LLM: LMStudioLLM # Local processing
TTS: EdgeTTS # Local processing
```
### **API Keys Required**
#### **OpenAI** (Optional)
- **Sign up**: [platform.openai.com](https://platform.openai.com)
- **Get API key**: Account → API Keys
- **Add billing**: Required for API usage
#### **Google** (Optional)
- **Sign up**: [console.cloud.google.com](https://console.cloud.google.com)
- **Enable APIs**: Speech-to-Text, Text-to-Speech
- **Create credentials**: Service account key
## 🛠️ Development Tools
### **ESP32 Development**
#### **ESP-IDF** (Espressif IoT Development Framework)
```bash
# Install ESP-IDF
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh
```
#### **Arduino IDE** (Alternative)
- **Download**: [arduino.cc](https://arduino.cc)
- **Install ESP32 board package**
- **Install required libraries**
### **Firmware Flashing Tools**
#### **esptool.py**
```bash
pip install esptool
```
#### **ESP32 Flash Tool**
- **Windows**: [ESP32 Flash Download Tool](https://espressif.com)
- **Web-based**: [ESP-Launchpad](https://espressif.github.io/esp-launchpad/)
## 📱 Mobile App (Optional)
### **Manager Mobile App**
- **Platform**: UniApp-based mobile app
- **Features**: Device management, configuration
- **Installation**: Via package managers or direct download
## ✅ Pre-Flight Checklist
Before you start, verify you have:
- [ ] **Compatible operating system**
- [ ] **Docker installed** (or Python 3.10+)
- [ ] **ESP32 development board**
- [ ] **USB cable** for ESP32
- [ ] **Internet connection**
- [ ] **AI service API key** (if using cloud services)
- [ ] **Basic electronics knowledge** (helpful but not required)
## 🚀 Ready to Start?
Once you have everything on the checklist, you're ready to begin!
👉 **[Next: Quick Start →](quick-start.md)**
## 🆘 Need Help?
- **Missing something?** Check our [Troubleshooting Guide](../support/troubleshooting.md)
- **Hardware questions?** See [Supported Devices](../hardware/supported-devices.md)
- **AI provider setup?** Check [Configuration Guide](../configuration/providers.md)
---
*Let's build something amazing! 🚀*

View file

@ -0,0 +1,218 @@
# ⚡ Quick Start Guide
Get Xiaozhi ESP32 Server up and running in just 5 minutes! This guide will have you talking to your ESP32 device in no time.
## 🎯 What We'll Build
By the end of this guide, you'll have:
- ✅ Xiaozhi server running locally
- ✅ ESP32 device connected and configured
- ✅ Voice interaction working
- ✅ Basic voice commands responding
## 🚀 Step 1: Start the Server (2 minutes)
### **Option A: Docker (Recommended)**
```bash
# Clone the repository
git clone https://github.com/lapy/xiaozhi-esp32-server.git
cd xiaozhi-esp32-server
# Start with Docker Compose
docker-compose up -d
```
### **Option B: Local Installation**
```bash
# Clone the repository
git clone https://github.com/lapy/xiaozhi-esp32-server.git
cd xiaozhi-esp32-server
# Install dependencies
cd main/xiaozhi-server
pip install -r requirements.txt
# Start the server
python app.py
```
### **✅ Verify Server is Running**
Open your browser and go to:
- **Web Interface**: http://localhost:8001
- **OTA Interface**: http://localhost:8003/xiaozhi/ota/
You should see the Xiaozhi management interface!
## 🔧 Step 2: Configure AI Providers (1 minute)
### **Quick Configuration**
1. **Open the web interface**: http://localhost:8001
2. **Register** your first admin account
3. **Go to Model Configuration** → **Large Language Model**
4. **Configure OpenAI** (or use free alternatives):
```yaml
# For OpenAI (requires API key)
LLM_OpenAILLM:
api_key: your_openai_api_key_here
model_name: gpt-4o-mini
# For free local setup
LLM_LMStudioLLM:
base_url: http://localhost:1234/v1
model_name: llama3.1:8b
```
### **Free Alternative Setup**
If you don't have OpenAI API access, use the free local setup:
```bash
# Install LMStudio
# Download from: https://lmstudio.ai
# Start LMStudio and load a model
# Use the local API endpoint: http://localhost:1234/v1
```
## 🔌 Step 3: Prepare Your ESP32 (1 minute)
### **Download Firmware**
1. **Go to OTA interface**: http://localhost:8003/xiaozhi/ota/
2. **Copy the WebSocket URL**: `ws://YOUR_IP:8000/xiaozhi/v1/`
3. **Download firmware** for your ESP32 board
### **Flash Your ESP32**
#### **Method 1: Web-based Flashing**
1. **Go to**: [ESP-Launchpad](https://espressif.github.io/esp-launchpad/)
2. **Upload firmware** file
3. **Connect ESP32** via USB
4. **Flash** the firmware
#### **Method 2: Command Line**
```bash
# Install esptool
pip install esptool
# Flash firmware
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 firmware.bin
```
## 🎤 Step 4: Connect and Test (1 minute)
### **Connect Your ESP32**
1. **Power on** your ESP32 device
2. **Wait for connection** (LED should indicate connection)
3. **Check OTA interface** for device status
### **Test Voice Interaction**
1. **Say**: "Hello Xiaozhi"
2. **Wait for response** (should hear synthesized speech)
3. **Try commands**:
- "What's the weather?"
- "Tell me a joke"
- "What time is it?"
## 🎉 Success! What's Next?
### **🎯 Try These Commands**
- **"Hello"** - Basic greeting
- **"What's the weather?"** - Weather information
- **"Tell me a joke"** - Entertainment
- **"What time is it?"** - Time and date
- **"Help"** - List available commands
### **🔧 Customize Your Setup**
1. **Add more AI providers** in the web interface
2. **Configure custom responses** in agent settings
3. **Set up integrations** with HomeAssistant or MQTT
4. **Create custom plugins** for specific functionality
## 🛠️ Troubleshooting
### **Server Won't Start**
```bash
# Check Docker status
docker ps
# Check logs
docker logs xiaozhi-esp32-server
# Restart if needed
docker-compose restart
```
### **ESP32 Won't Connect**
1. **Check WebSocket URL** in OTA interface
2. **Verify network** connection
3. **Check firewall** settings
4. **Restart ESP32** device
### **No Voice Response**
1. **Check AI provider** configuration
2. **Verify microphone** is working
3. **Check audio output** settings
4. **Review server logs** for errors
## 📚 Next Steps
Now that you have the basics working, explore more:
- **[Configuration Guide](../configuration/basic-setup.md)** - Fine-tune your setup
- **[Hardware Guide](../hardware/supported-devices.md)** - Learn about ESP32 devices
- **[Features Guide](../features/voice-interaction.md)** - Explore capabilities
- **[Integrations Guide](../guides/homeassistant.md)** - Connect to other systems
## 🆘 Need Help?
- **Issues?** Check our [Troubleshooting Guide](../support/troubleshooting.md)
- **Questions?** Browse our [FAQ](../support/faq.md)
- **Community?** Join our [GitHub Discussions](https://github.com/lapy/xiaozhi-esp32-server/discussions)
---
## 🎯 Quick Reference
### **Key URLs**
- **Web Interface**: http://localhost:8001
- **OTA Interface**: http://localhost:8003/xiaozhi/ota/
- **API Documentation**: http://localhost:8001/api/docs
### **Key Commands**
```bash
# Start server
docker-compose up -d
# Stop server
docker-compose down
# View logs
docker logs xiaozhi-esp32-server
# Restart server
docker-compose restart
```
### **Configuration Files**
- **Server Config**: `main/xiaozhi-server/config.yaml`
- **Docker Config**: `docker-compose.yml`
- **Environment**: `.env` files
---
**Congratulations! You've successfully set up Xiaozhi ESP32 Server! 🎉**
👉 **[Next: First Device Setup →](first-device.md)**

182
docs/guides/dev-ops.md Normal file
View file

@ -0,0 +1,182 @@
# Full Module Source Code Deployment Automatic Upgrade Method
This tutorial is for enthusiasts of full module source code deployment, showing how to automatically pull source code, compile, and start port operations through automated commands. Achieving the most efficient system upgrade.
This project's test platform `https://2662r3426b.vicp.fun` has been using this method since its launch, with good results.
Tutorial can refer to the video tutorial published by Bilibili blogger `Bile Labs`: ["Open Source Xiaozhi Server xiaozhi-server Automatic Update and Latest Version MCP Access Point Configuration Tutorial"](https://www.bilibili.com/video/BV15H37zHE7Q)
# Prerequisites
- Your computer/server is a Linux operating system
- You have already run through the entire process
- You like to keep up with the latest features, but find manual deployment a bit troublesome each time, and expect an automatic update method
The second condition must be met, because some files involved in this tutorial, such as JDK, Node.js environment, Conda environment, etc., are only available after you run through the entire process. If you haven't run through it, when I mention a certain file, you might not know what it means.
# Tutorial Effects
- Solve the problem of not being able to pull the latest project source code domestically
- Automatically pull code and compile frontend files
- Automatically pull code and compile Java files, automatically kill port 8002, automatically start port 8002
- Automatically pull Python code, automatically kill port 8000, automatically start port 8000
# Step 1: Choose Your Project Directory
For example, I planned my project directory as follows. This is a newly created blank directory. If you don't want to make mistakes, you can do the same as me
```
/home/system/xiaozhi
```
# Step 2: Clone This Project
At this moment, first execute the first command to pull the source code. This command is suitable for domestic network servers and computers, no VPN required
```
cd /home/system/xiaozhi
git clone https://ghproxy.net/https://github.com/lapy/xiaozhi-esp32-server.git
```
After execution, your project directory will have an additional folder `xiaozhi-esp32-server`, which is the project's source code
# Step 3: Copy Basic Files
If you have already run through the entire process before, you should be familiar with your private configuration file `xiaozhi-server/data/.config.yaml`.
Now you need to copy the `model.pt` file to the new directory, you can do this
```
# Create required directories
mkdir -p /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/data/
cp your_original_.config.yaml_full_path /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/data/.config.yaml
# Model files no longer needed - ASR services have been updated
```
# Step 4: Create Three Automatic Compilation Files
## 4.1 Automatically Compile manager-web Module
In the `/home/system/xiaozhi/` directory, create a file named `update_8001.sh` with the following content
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git fetch --all
git reset --hard
git pull origin main
cd /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-web
npm install
npm run build
rm -rf /home/system/xiaozhi/manager-web
mv /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-web/dist /home/system/xiaozhi/manager-web
```
After saving, execute the permission command
```
chmod 777 update_8001.sh
```
After execution, continue
## 4.2 Automatically Compile and Run manager-api Module
In the `/home/system/xiaozhi/` directory, create a file named `update_8002.sh` with the following content
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git pull origin main
cd /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-api
rm -rf target
mvn clean package -Dmaven.test.skIP=true
cd /home/system/xiaozhi/
# Find process ID occupying port 8002
PID=$(sudo netstat -tulnp | grep 8002 | awk '{print $7}' | cut -d'/' -f1)
rm -rf /home/system/xiaozhi/xiaozhi-esp32-api.jar
mv /home/system/xiaozhi/xiaozhi-esp32-server/main/manager-api/target/xiaozhi-esp32-api.jar /home/system/xiaozhi/xiaozhi-esp32-api.jar
# Check if process ID is found
if [ -z "$PID" ]; then
echo "No process found occupying port 8002"
else
echo "Found process occupying port 8002, process ID: $PID"
# Kill process
kill -9 $PID
kill -9 $PID
echo "Killed process $PID"
fi
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev &
tail tail -f nohup.out
```
After saving, execute the permission command
```
chmod 777 update_8002.sh
```
After execution, continue
## 4.3 Automatically Compile and Run Python Project
In the `/home/system/xiaozhi/` directory, create a file named `update_8000.sh` with the following content
```
cd /home/system/xiaozhi/xiaozhi-esp32-server
git pull origin main
# Find process ID occupying port 8000
PID=$(sudo netstat -tulnp | grep 8000 | awk '{print $7}' | cut -d'/' -f1)
# Check if process ID is found
if [ -z "$PID" ]; then
echo "No process found occupying port 8000"
else
echo "Found process occupying port 8000, process ID: $PID"
# Kill process
kill -9 $PID
kill -9 $PID
echo "Killed process $PID"
fi
cd main/xiaozhi-server
# Initialize conda environment
source ~/.bashrc
conda activate xiaozhi-esp32-server
pIP install -r requirements.txt
nohup python app.py >/dev/null &
tail -f /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/tmp/server.log
```
After saving, execute the permission command
```
chmod 777 update_8000.sh
```
After execution, continue
# Daily Updates
After all the above scrIPts are established, for daily updates, we only need to execute the following commands in sequence to achieve automatic updates and startup
```
cd /home/system/xiaozhi
# Update and start Java program
./update_8001.sh
# Update web program
./update_8002.sh
# Update and start python program
./update_8000.sh
# To view Java logs later, execute the following command
tail -f nohup.out
# To view Python logs later, execute the following command
tail -f /home/system/xiaozhi/xiaozhi-esp32-server/main/xiaozhi-server/tmp/server.log
```
# Notes
Test platform `https://2662r3426b.vicp.fun` uses nginx for reverse proxy. Detailed nginx.conf configuration can be [referenced here](https://github.com/lapy/xiaozhi-esp32-server/issues/791)
## Common Issues
### 1. Why is port 8001 not seen?
Answer: 8001 is used in the development environment for running the frontend port. If you are deploying on a server, it is not recommended to use `npm run serve` to start port 8001 to run the frontend. Instead, like this tutorial, compile it into HTML files and then use nginx to manage access.
### 2. Do I need to manually update SQL statements for each update?
Answer: No, because the project uses **Liquibase** to manage database versions, which will automatically execute new SQL scrIPts.

View file

@ -0,0 +1,212 @@
# Xiaozhi ESP32 Open Source Server and HomeAssistant Integration Guide
[TOC]
-----
## Introduction
This document will guide you on how to integrate ESP32 devices with HomeAssistant.
## Prerequisites
- HomeAssistant is installed and configured
- The model I chose this time is: free OpenAI, which supports function call
## Pre-start Operations (Required)
### 1. Get HA Network Address Information
Please visit your Home Assistant network address. For example, my HA address is 192.168.4.7, and the port is the default 8123, then open in the browser
```
http://192.168.4.7:8123
```
> Manual method to query HA's IP address**(Only applicable when xiaozhi-esp32-server and HA are deployed on the same network device [e.g., same wifi])**:
>
> 1. Enter Home Assistant (frontend).
>
> 2. Click **Settings** in the bottom left corner → **System** → **Network**.
>
> 3. Scroll to the bottom `Home Assistant website` area, in `local network`, click the `eye` button to see the currently used IP address (such as `192.168.1.10`) and network interface. Click `copy link` to copy directly.
Alternatively, if you have set up a directly accessible Home Assistant OAuth address, you can also access it directly in the browser
```
http://homeassistant.local:8123
```
### 2. Login to `Home Assistant` to get development key
Login to `HomeAssistant`, click `bottom left avatar -> Profile`, switch to `Security` navigation bar, scroll to the bottom `Long-lived access tokens` to generate api_key, and copy and save it. All subsequent methods require this api key and it only appears once (tIP: you can save the generated QR code image, and scan the QR code later to extract the api key again).
## Method 1: Xiaozhi Community-built HA Calling Function
### Function DescrIPtion
- If you need to add new devices later, this method requires manually restarting the `xiaozhi-esp32-server service` to update device information**(Important**).
- You need to ensure that `Xiaomi Home` has been integrated in HomeAssistant and Mi Home devices have been imported into `HomeAssistant`.
- You need to ensure that the `xiaozhi-esp32-server Smart Control Console` can be used normally.
- My `xiaozhi-esp32-server Smart Control Console` and `HomeAssistant` are deployed on the same machine on another port, version is `0.3.10`
```
http://192.168.4.7:8002
```
### Configuration Steps
#### 1. Login to `HomeAssistant` to organize the device list that needs to be controlled
Login to `HomeAssistant`, click `Settings in the bottom left corner`, then enter `Devices & Services`, and click `Entities` at the top.
Then search for the switches you want to control in entities. After the results appear, click on one of the results in the list, and a switch interface will appear.
In the switch interface, we try clicking the switch to see if it turns on/off with our clicks. If it can be operated, it means it's properly connected to the network.
Then find the settings button in the switch panel, click it, and you can view the `Entity ID` of this switch.
We open a notepad and organize a piece of data in this format:
Location + English comma + Device name + English comma + `Entity ID` + English semicolon
For example, I'm at the company, I have a toy light, its identifier is switch.cuco_cn_460494544_cp1_on_p_2_1, then write this piece of data:
```
Company,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1;
```
Of course, in the end I might need to operate two lights, my final result is:
```
Company,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1;
Company,Desk Lamp,switch.iot_cn_831898993_socn1_on_p_2_1;
```
This string, we call it "device list string" and need to save it well, it will be useful later.
#### 2. Login to `Smart Control Console`
Use the administrator account to login to the `Smart Control Console`. In `Agent Management`, find your agent, then click `Configure Role`.
Set intent recognition to `Function Call` or `LLM Intent Recognition`. At this time you will see an `Edit Functions` button on the right. Click the `Edit Functions` button, and a `Function Management` dialog will pop up.
In the `Function Management` dialog, you need to check `HomeAssistant Device Status Query` and `HomeAssistant Device Status Modification`.
After checking, click `HomeAssistant Device Status Query` in `Selected Functions`, then configure your `HomeAssistant` address, key, and device list string in `Parameter Configuration`.
After editing, click `Save Configuration`, then the `Function Management` dialog will be hidden, then click save agent configuration.
After successful saving, you can wake up the device for operation.
#### 3. Wake up device for control
Try saying to the esp32, "Turn on XXX light"
## Method 2: Xiaozhi uses Home Assistant's voice assistant as LLM tool
### Function DescrIPtion
- This method has a relatively serious disadvantage——**This method cannot use the function_call plugin capabilities of the Xiaozhi open source ecosystem**, because using Home Assistant as Xiaozhi's LLM tool will transfer the intent recognition capability to Home Assistant. However, **this method can experience the native Home Assistant operation functions, and Xiaozhi's chat capability remains unchanged**. If you are really concerned, you can use [Method 3](##Method 3: Using Home Assistant's MCP service (recommended)) which is also supported by Home Assistant, which can maximize the experience of Home Assistant's functions.
### Configuration Steps:
#### 1. Configure Home Assistant's large model voice assistant.
**You need to configure Home Assistant's voice assistant or large model tool in advance.**
#### 2. Get Home Assistant's voice assistant Agent ID.
1. Enter the Home Assistant page. Click `Developer Tools` on the left.
2. In the opened `Developer Tools`, click the `Actions` tab (as shown in operation 1), in the `Actions` option bar on the page, find or enter `conversation.process (conversation-process)` and select `Conversation: Process` (as shown in operation 2).
3. Check the `Agent` option on the page, in the highlighted `Conversation Agent`, select the voice assistant name you configured in step 1, as shown in the figure, I have configured `OpenAI` and select it.
4. After selection, click `Enter YAML mode` at the bottom left of the form.
5. Copy the agent-id value, for example, mine in the figure is `01JP2DYMBDF7F4ZA2DMCF2AGX2` (for reference only).
6. Switch to the `config.yaml` file of the Xiaozhi open source server `xiaozhi-esp32-server`, in the LLM configuration, find Home Assistant, set your Home Assistant network address, Api key and the agent_id you just queried.
7. Modify the `LLM` of the `selected_module` attribute in the `config.yaml` file to `HomeAssistant`, and `Intent` to `nointent`.
8. Restart the Xiaozhi open source server `xiaozhi-esp32-server` to use it normally.
## Method 3: Using Home Assistant's MCP service (recommended)
### Function DescrIPtion
- You need to integrate and install the HA integration in Home Assistant in advance——[Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/).
- This method and Method 2 are both solutions provided by HA officially. Unlike Method 2, you can normally use the open source community-built plugins of the Xiaozhi open source server `xiaozhi-esp32-server`, while allowing you to freely use any LLM large model that supports function_call functionality.
### Configuration Steps
#### 1. Install Home Assistant's MCP service integration.
Official integration website——[Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/)..
Or follow the manual operations below.
> - Go to Home Assistant page **[Settings > Devices & Services](https://my.home-assistant.io/redirect/integrations)**.
>
> - In the bottom right corner, select the **[Add Integration](https://my.home-assistant.io/redirect/config_flow_start?domain=mcp_server)** button.
>
> - Select **Model Context Protocol Server** from the list.
>
> - Follow the on-screen instructions to complete the setup.
#### 2. Configure Xiaozhi open source server MCP configuration information
Enter the `data` directory and find the `.mcp_server_settings.json` file.
If you don't have a `.mcp_server_settings.json` file in your `data` directory,
- Please copy the `mcp_server_settings.json` file from the root directory of the `xiaozhi-server` folder to the `data` directory and rename it to `.mcp_server_settings.json`
- Or [download this file](https://github.com/lapy/xiaozhi-esp32-server/blob/main/main/xiaozhi-server/mcp_server_settings.json), download it to the `data` directory and rename it to `.mcp_server_settings.json`
Modify this part of the content in `"mcpServers"`:
```json
"Home Assistant": {
"command": "mcp-proxy",
"args": [
"http://YOUR_HA_HOST/mcp_server/sse"
],
"env": {
"API_ACCESS_TOKEN": "YOUR_API_ACCESS_TOKEN"
}
},
```
Note:
1. **Replace configuration:**
- Replace `YOUR_HA_HOST` in `args` with your HA service address. If your service address already contains https/http (e.g., `http://192.168.1.101:8123`), just fill in `192.168.1.101:8123`.
- Replace `YOUR_API_ACCESS_TOKEN` in `API_ACCESS_TOKEN` in `env` with the development key api key you obtained earlier.
2. **If you add configuration and there are no new `mcpServers` configurations after the `"mcpServers"` brackets, you need to remove the final comma `,`**, otherwise parsing may fail.
**Final effect reference (as follows)**:
```json
"mcpServers": {
"Home Assistant": {
"command": "mcp-proxy",
"args": [
"http://192.168.1.101:8123/mcp_server/sse"
],
"env": {
"API_ACCESS_TOKEN": "abcd.efghi.jkl"
}
}
}
```
#### 3. Configure Xiaozhi open source server system configuration
1. **Select any LLM large model that supports function_call as Xiaozhi's LLM chat assistant (but don't select Home Assistant as LLM tool)**. The model I chose this time is: free OpenAI, which supports functioncall function calling, but sometimes the calls are not very stable. If you want to pursue stability, it is recommended to set LLM to: OpenAILLM, using the specific model_name: gpt-4o-mini.
2. Switch to the `config.yaml` file of the Xiaozhi open source server `xiaozhi-esp32-server`, set your LLM large model configuration, and adjust the `Intent` of the `selected_module` configuration to `function_call`.
3. Restart the Xiaozhi open source server `xiaozhi-esp32-server` to use it normally.

122
docs/guides/mcp-enable.md Normal file
View file

@ -0,0 +1,122 @@
# MCP Endpoint Deployment Usage Guide
This tutorial contains 3 parts
- 1. How to deploy the MCP endpoint service
- 2. How to configure MCP endpoint when deploying all modules
- 3. How to configure MCP endpoint when deploying single module
# 1. How to Deploy MCP Endpoint Service
## Step 1: Download MCP Endpoint Project Source Code
Open [MCP Endpoint Project Address](https://github.com/lapy/mcp-endpoint-server) in browser
After opening, find a green button on the page that says `Code`, click it, and then you'll see the `Download ZIP` button.
Click it to download the project source code archive. After downloading to your computer, extract it. At this time, its name might be `mcp-endpoint-server-main`
You need to rename it to `mcp-endpoint-server`.
## Step 2: Start the Program
This project is a very simple project, it is recommended to use docker to run. However, if you don't want to use docker to run, you can refer to [this page](https://github.com/lapy/mcp-endpoint-server/blob/main/README_dev.md) to run with source code. The following is the docker running method
```
# Enter the root directory of this project source code
cd mcp-endpoint-server
# Clear cache
docker compose -f docker-compose.yml down
docker stop mcp-endpoint-server
docker rm mcp-endpoint-server
docker rmi ghcr.io/lapy/mcp-endpoint-server:latest
# Start docker container
docker compose -f docker-compose.yml up -d
# View logs
docker logs -f mcp-endpoint-server
```
At this point, the logs will output similar logs as follows
```
250705 INFO-=====The following addresses are Smart Control Panel/Single Module MCP endpoint addresses====
250705 INFO-Smart Control Panel MCP parameter configuration: http://172.22.0.2:8004/mcp_endpoint/health?key=abc
250705 INFO-Single module deployment MCP endpoint: ws://172.22.0.2:8004/mcp_endpoint/mcp/?token=def
250705 INFO-=====Please choose according to specific deployment, do not leak to anyone======
```
Please copy out the two interface addresses:
Since you are using docker deployment, you must not use the above addresses directly!
First copy out the addresses and put them in a draft. You need to know what your computer's local network IP is. For example, my computer's local network IP is `192.168.1.25`, then
My original interface addresses
```
Smart Control Panel MCP parameter configuration: http://172.22.0.2:8004/mcp_endpoint/health?key=abc
Single module deployment MCP endpoint: ws://172.22.0.2:8004/mcp_endpoint/mcp/?token=def
```
Should be changed to
```
Smart Control Panel MCP parameter configuration: http://192.168.1.25:8004/mcp_endpoint/health?key=abc
Single module deployment MCP endpoint: ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=def
```
After making the changes, please use your browser to directly access the `Smart Control Panel MCP parameter configuration`. When the browser shows similar code like this, it means it's successful.
```
{"result":{"status":"success","connections":{"tool_connections":0,"robot_connections":0,"total_connections":0}},"error":null,"id":null,"jsonrpc":"2.0"}
```
Please keep the above two `interface addresses` safe, you will need them in the next step.
# 2. How to configure MCP endpoint for full module deployment
If you are using full module deployment, use the administrator account to log in to the Smart Control Panel, click the top `Parameter Dictionary`, and select the `Parameter Management` function.
Then search for the parameter `server.mcp_endpoint`. At this point, its value should be `null`.
Click the modify button and paste the `Smart Control Panel MCP parameter configuration` obtained from the previous step into the `Parameter Value`. Then save.
If it can be saved successfully, it means everything is going well, and you can go to the agent to see the effect. If it's not successful, it means the Smart Control Panel cannot access the MCP endpoint, most likely due to network firewall or not filling in the correct local network IP.
# 3. How to configure MCP endpoint for single module deployment
If you are using single module deployment, find your configuration file `data/.config.yaml`.
Search for `mcp_endpoint` in the configuration file. If not found, add the `mcp_endpoint` configuration. Similar to mine like this
```
server:
websocket: ws://your_IP_or_domain:port_number/xiaozhi/v1/
http_port: 8002
log:
log_level: INFO
# There may be more configurations here..
mcp_endpoint: your_endpoint_websocket_address
```
At this point, please paste the `Single module deployment MCP endpoint` obtained from `How to deploy MCP endpoint service` into `mcp_endpoint`. Similar to this
```
server:
websocket: ws://your_IP_or_domain:port_number/xiaozhi/v1/
http_port: 8002
log:
log_level: INFO
# There may be more configurations here
mcp_endpoint: ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=def
```
After configuration, starting the single module will output the following logs.
```
250705[__main__]-INFO-Component initialization: vad successful SileroVAD
250705[__main__]-INFO-Component initialization: asr successful OpenaiASR
250705[__main__]-INFO-OTA interface is http://192.168.1.25:8003/xiaozhi/ota/
250705[__main__]-INFO-Vision analysis interface is http://192.168.1.25:8003/mcp/vision/explain
250705[__main__]-INFO-MCP endpoint is ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
250705[__main__]-INFO-Websocket address is ws://192.168.1.25:8000/xiaozhi/v1/
250705[__main__]-INFO-=======The above addresses are websocket protocol addresses, do not access with browser=======
250705[__main__]-INFO-If you want to test websocket, please use Google Chrome to open test_page.html in the test directory
250705[__main__]-INFO-=============================================================
```
As above, if you can output similar `MCP endpoint is` with `ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc`, it means the configuration is successful.

View file

@ -0,0 +1,94 @@
# MCP Endpoint Usage Guide
This tutorial uses the open-source mcp calculator functionality as an example to introduce how to integrate your own custom mcp service into your own endpoint.
The premise of this tutorial is that your `xiaozhi-server` has already enabled the mcp endpoint functionality. If you haven't enabled it yet, you can first enable it according to [this tutorial](./mcp-endpoint-enable.md).
# How to integrate a simple mcp functionality for agents, such as calculator functionality
### If you are using full module deployment
If you are using full module deployment, you can enter the control console, agent management, click `Configure Role`, on the right side of `Intent Recognition`, there is an `Edit Functions` button.
Click this button. In the popup page, at the bottom, there will be `MCP Endpoint`. Normally, it will display the `MCP Endpoint Address` of this agent. Next, let's extend this agent with a calculator functionality based on MCP technology.
This `MCP Endpoint Address` is very important, you will use it later.
### If you are using single module deployment
If you are using single module deployment and you have configured the MCP endpoint address in the configuration file, then normally, when the single module deployment starts, it will output the following logs.
```
250705[__main__]-INFO-Initialize component: vad successful SileroVAD
250705[__main__]-INFO-Initialize component: asr successful OpenaiASR
250705[__main__]-INFO-OTA interface is http://192.168.1.25:8003/xiaozhi/ota/
250705[__main__]-INFO-Vision analysis interface is http://192.168.1.25:8002/mcp/vision/explain
250705[__main__]-INFO-mcp endpoint is ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
250705[__main__]-INFO-Websocket address is ws://192.168.1.25:8000/xiaozhi/v1/
250705[__main__]-INFO-=======The above addresses are websocket protocol addresses, please do not access with browser=======
250705[__main__]-INFO-If you want to test websocket, please open test_page.html in the test directory with Google browser
250705[__main__]-INFO-=============================================================
```
As shown above, the `ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc` in the output `mcp endpoint is` is your `MCP Endpoint Address`.
This `MCP endpoint address` is important, you will need it later.
## Step 1: Download the MCP Calculator Project Code
Open the [Calculator Project](https://github.com/78/mcp-calculator) in your browser,
After opening, find the green button that says `Code`, click it, and then you'll see the `Download ZIP` button.
Click it to download the project source code zip file. After downloading to your computer, extract it. At this point, its name might be `mcp-calculator-main`
You need to rename it to `mcp-calculator`. Next, we'll use the command line to enter the project directory and install dependencies
```bash
# Enter project directory
cd mcp-calculator
conda remove -n mcp-calculator --all -y
conda create -n mcp-calculator python=3.10 -y
conda activate mcp-calculator
pIP install -r requirements.txt
```
## Step 2: Start
Before starting, first copy the MCP endpoint address from your smart control panel's agent.
For example, my agent's MCP address is
```
ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
```
Start entering commands
```bash
export MCP_ENDPOINT=ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
```
After entering, start the program
```bash
python mcp_pipe.py calculator.py
```
### If you are using Smart Control Panel deployment
If you are using Smart Control Panel deployment, after starting, go back to the Smart Control Panel and click refresh MCP connection status, and you will see your extended function list.
### If you are using single module deployment
If you are using single module deployment, when the device connects, it will output similar logs, indicating success
```
250705 -INFO-Initializing MCP endpoint: wss://2662r3426b.vicp.fun/mcp_e
250705 -INFO-Sending MCP endpoint initialization message
250705 -INFO-MCP endpoint connection successful
250705 -INFO-MCP endpoint initialization successful
250705 -INFO-Unified tool processor initialization complete
250705 -INFO-MCP endpoint server info: name=Calculator, version=1.9.4
250705 -INFO-MCP endpoint supported tools count: 1
250705 -INFO-All MCP endpoint tools obtained, client ready
250705 -INFO-Tool cache refreshed
250705 -INFO-Current supported function list: [ 'get_time', 'get_calendar', 'play_music', 'get_weather', 'handle_exit_intent', 'calculator']
```
If it includes `'calculator'`, it means the device can call the calculator tool based on intent recognition.

136
docs/guides/mqtt.md Normal file
View file

@ -0,0 +1,136 @@
# MQTT Gateway Deployment Tutorial
The `xiaozhi-esp32-server` project can be combined with the open-source [xiaozhi-mqtt-gateway](https://github.com/78/xiaozhi-mqtt-gateway) project for simple modification to enable xiaozhi hardware MQTT+UDP connection.
## Preparation
Check the version number at the bottom of your control console homepage to confirm whether your control console version is `0.7.7` or above. If not, you need to upgrade the control console.
Prepare your `mqtt-websocket` connection address for `xiaozhi-server`. Based on your original `websocket address`, add the characters `?from=mqtt_gateway` to get the `mqtt-websocket` connection address.
1. If you are using source code deployment, your `mqtt-websocket` address is:
```
ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway
```
2. If you are using docker deployment, your `mqtt-websocket` address is
```
ws://your_host_lan_IP:8000/xiaozhi/v1?from=mqtt_gateway
```
## Step 1: Deploy MQTT Gateway
1. Clone the [modified xiaozhi-mqtt-gateway project](https://github.com/lapy/xiaozhi-mqtt-gateway.git):
```bash
git clone https://ghfast.top/https://github.com/lapy/xiaozhi-mqtt-gateway.git
cd xiaozhi-mqtt-gateway
```
2. Install dependencies:
```bash
npm install
npm install -g pm2
```
3. Configure `config.json`:
```bash
cp config/mqtt.json.example config/mqtt.json
```
4. Edit the configuration file config/mqtt.json, replace the `mqtt-websocket` address from the preparation phase into `chat_servers`. For example, the source code deployment of `xiaozhi-server` is configured as follows:
```
{
"production": {
"chat_servers": [
"ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway"
]
},
"debug": false,
"max_mqtt_payload_size": 8192,
"mcp_client": {
"capabilities": {
},
"client_info": {
"name": "xiaozhi-mqtt-client",
"version": "1.0.0"
},
"max_tools_count": 128
}
}
```
5. Create a `.env` file in the project root directory and set the following environment variables:
```
PUBLIC_IP=your-IP # Server public IP
MQTT_PORT=1883 # MQTT server port
UDP_PORT=8884 # UDP server port
API_PORT=8007 # Management API port
MQTT_SIGNATURE_KEY=test # MQTT signature key
```
Please note the `PUBLIC_IP` configuration, ensure it matches the actual public IP address, or use domain name if available.
`MQTT_SIGNATURE_KEY` is the key used for MQTT connection authentication. It's recommended to set it to something more complex, preferably 8+ characters with both uppercase and lowercase letters. This key will be used later.
- Do not use simple passwords like `123456`, `test`, etc.
- Do not use simple passwords like `123456`, `test`, etc.
- Do not use simple passwords like `123456`, `test`, etc.
6. Start MQTT Gateway
```
# Start service
pm2 start ecosystem.config.js
# View logs
pm2 logs xz-mqtt
```
When you see the following logs, it means the MQTT gateway has started successfully:
```
0|xz-mqtt | 2025-09-11T12:14:48: MQTT server is listening on port 1883
0|xz-mqtt | 2025-09-11T12:14:48: UDP server is listening on x.x.x.x:8884
```
If you need to restart the MQTT gateway, execute the following command:
```
pm2 restart xz-mqtt
```
## Step 2: Configure Smart Control Panel
1. At the top of the Smart Control Panel, click `Parameter Management`, search for `server.mqtt_gateway`, click edit, and fill in the `PUBLIC_IP`+`:`+`MQTT_PORT` you set in the `.env` file. Similar to this
```
192.168.0.7:1883
```
2. At the top of the Smart Control Panel, click `Parameter Management`, search for `server.mqtt_signature_key`, click edit, and fill in the `MQTT_SIGNATURE_KEY` you set in the `.env` file.
3. At the top of the Smart Control Panel, click `Parameter Management`, search for `server.udp_gateway`, click edit, and fill in the `PUBLIC_IP`+`:`+`UDP_PORT` you set in the `.env` file. Similar to this
```
192.168.0.7:8884
```
4. At the top of the Smart Control Panel, click `Parameter Management`, search for `server.mqtt_manager_api`, click edit, and fill in the `PUBLIC_IP`+`:`+`UDP_PORT` you set in the `.env` file. Similar to this
```
192.168.0.7:8007
```
After completing the above configuration, you can use the curl command to verify whether your OTA address will distribute MQTT configuration. Change the `http://localhost:8002/xiaozhi/ota/` below to your OTA address
```
curl 'http://localhost:8003/xiaozhi/ota/' \
-H 'Content-Type: application/json' \
-H 'Client-Id: 7b94d69a-9808-4c59-9c9b-704333b38aff' \
-H 'Device-Id: 11:22:33:44:55:66' \
--data-raw $'{\n "application": {\n "version": "1.0.1",\n "elf_sha256": "1"\n },\n "board": {\n "mac": "11:22:33:44:55:66"\n }\n}'
```
If the returned content contains `mqtt` related configuration, it means the configuration is successful. Similar to this
```
{"server_time":{"timestamp":1757567894012,"timeZone":"Asia/Shanghai","timezone_offset":480},"activation":{"code":"460609","message":"http://xiaozhi.server.com\n460609","challenge":"11:22:33:44:55:66"},"firmware":{"version":"1.0.1","url":"http://xiaozhi.server.com:8003/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL"},"websocket":{"url":"ws://192.168.4.23:8000/xiaozhi/v1/"},"mqtt":{"endpoint":"192.168.0.7:1883","client_id":"GID_default@@@11_22_33_44_55_66@@@7b94d69a-9808-4c59-9c9b-704333b38aff","username":"eyJpcCI6IjA6MDowOjA6MDowOjA6MSJ9","password":"Y8XP9xcUhVIN9OmbCHT9ETBiYNE3l3Z07Wk46wV9PE8=","publish_topic":"device-server","subscribe_topic":"devices/p2p/11_22_33_44_55_66"}}
```
## Step 3: Restart Xiaozhi Device
Since MQTT information needs to be distributed through the OTA address, you only need to ensure that you can normally connect to the server's OTA address, then restart and wake up.
After waking up, pay attention to the mqtt-gateway logs to confirm if there are successful connection logs.
```
pm2 logs xz-mqtt
```

231
docs/guides/news.md Normal file
View file

@ -0,0 +1,231 @@
# News Plugin Integration
This document describes how to use and configure the News plugin for getting news from major news sources worldwide.
## Overview
The News plugin (`get_news`) allows users to get the latest news from major news sources through RSS feeds. It features automatic source rotation, enhanced content parsing, and robust fallback mechanisms for maximum reliability.
## Features
- **Major News Sources**: Reuters, CNN, BBC, Guardian, TechCrunch, and more
- **Multiple News Categories**: World, Technology, Business, Sports, Health, Politics, Science
- **Source Rotation**: Automatically tries multiple sources for reliability and variety
- **Enhanced Content Parsing**: Optimized for major news site structures
- **Random News Selection**: Randomly selects news items for variety
- **Detailed Content**: Can fetch full article content when requested
- **Multi-language Support**: Supports responses in different languages
- **Robust Error Handling**: Multiple fallback options and timeout management
- **Smart Content Extraction**: Advanced parsing for Reuters, CNN, BBC, Guardian, NYT, and more
## Configuration
### 1. Plugin Configuration (config.yaml)
```yaml
plugins:
get_news:
default_rss_url: "https://feeds.reuters.com/reuters/worldNews"
# Built-in sources include: Reuters, CNN, BBC, Guardian, TechCrunch, and more
# These are automatically rotated for variety and reliability
# Custom sources can be added here if needed
```
### 2. Enable Plugin
Add the plugin to the functions list in `config.yaml`:
```yaml
Intent:
function_call:
functions:
- get_news
# ... other plugins
```
## Supported News Categories
| Category | Keywords | Description |
|----------|----------|-------------|
| **World News** | `world`, `world news`, `international`, `international news`, `global`, `global news` | Global news and international affairs |
| **Technology** | `technology`, `tech`, `tech news`, `technology news`, `innovation`, `ai`, `artificial intelligence` | Technology and innovation news |
| **Business** | `business`, `business news`, `finance`, `financial`, `economy`, `economic`, `market`, `markets`, `stocks` | Business and economic news |
| **Sports** | `sports`, `sport`, `sports news`, `football`, `soccer`, `basketball`, `baseball` | Sports news and updates |
| **Health** | `health`, `health news`, `medical`, `medicine`, `healthcare` | Health and medical news |
| **Politics** | `politics`, `political`, `election`, `government` | Political news and government affairs |
| **Science** | `science`, `scientific`, `research`, `climate`, `environment` | Science news and research |
## Usage Examples
### Basic News Query
```
User: "What's the latest news?"
Response: [Random world news item]
```
### Category-Specific News
```
User: "Get me some technology news"
Response: [Random technology news item]
```
### Detailed News Content
```
User: "Please provide more details about this news"
Response: [Full article content with summary]
```
## Function Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `category` | string | No | News category (world, technology, business, sports, health) |
| `detail` | boolean | No | Whether to get detailed content (default: false) |
| `lang` | string | Yes | Language code for response (e.g., en_US, zh_CN) |
## News Sources
The plugin automatically uses multiple RSS feeds from major news sources:
### Built-in Sources by Category
**World News:**
- Reuters World News
- CNN International Edition
- BBC World News
- Reuters Global News
**Technology:**
- Reuters Technology News
- CNN Technology
- TechCrunch
- O'Reilly Radar
**Business:**
- Reuters Business News
- CNN Money
- Reuters Wealth
- CNN Business
**Sports:**
- Reuters Sports News
- CNN Sports
- CNN Football
**Health:**
- Reuters Health News
- CNN Health
**Politics:**
- CNN Politics
- BBC Politics
- Reuters Politics
**Science:**
- BBC Science & Environment
- Reuters Science News
### Source Rotation & Reliability
The plugin automatically:
- **Tries multiple sources** in order until news is found
- **Falls back to configuration** if built-in sources fail
- **Logs source usage** for monitoring and debugging
- **Handles timeouts and errors** gracefully
## Technical Details
### RSS Parsing
- Uses `xml.etree.ElementTree` for XML parsing
- Extracts title, link, description, and publication date
- Handles various RSS formats and structures
### Content Fetching
- Uses `requests` with proper headers for web scraping
- Implements multiple content selectors for different website structures
- Limits content length to prevent excessive responses
### Error Handling
- Network timeout handling (10s for RSS, 15s for content)
- Fallback to default category if specified category fails
- Graceful degradation when content cannot be fetched
## Troubleshooting
### Common Issues
1. **No News Retrieved**
- Check internet connectivity
- Verify RSS URLs are accessible
- Check logs for specific error messages
2. **Content Fetching Failures**
- Some websites may block automated requests
- Content selectors may need updating for site changes
- Consider using alternative RSS sources
3. **Category Not Found**
- Ensure category keywords match supported values
- Check configuration for correct RSS URL mapping
### Logging
Enable debug logging to troubleshoot issues:
```python
# Check logs for:
# - RSS fetch attempts and results
# - Content parsing errors
# - Category mapping issues
```
## Security Considerations
- Uses proper User-Agent headers to avoid blocking
- Implements request timeouts to prevent hanging
- Validates RSS feed responses before parsing
- Limits content extraction to prevent abuse
## Performance
- RSS feeds are fetched on-demand (not cached)
- Content fetching is only performed when detailed content is requested
- Random selection ensures variety without performance impact
- Timeout settings prevent long waits
## Future Enhancements
Potential improvements for future versions:
1. **Caching**: Implement RSS feed caching for better performance
2. **More Sources**: Add support for additional news sources
3. **Custom Categories**: Allow user-defined category mappings
4. **Content Filtering**: Add content filtering and summarization
5. **Multi-language**: Enhanced multi-language content support
## API Reference
### Function Signature
```python
def get_news_from_western_sources(
conn,
category: str = None,
detail: bool = False,
lang: str = "en_US"
) -> ActionResponse
```
### Return Types
- `ActionResponse(Action.REQLLM, message, None)`: Success with news content
- `ActionResponse(Action.REQLLM, error_message, None)`: Error or no content found
## Support
For issues or questions regarding the Western News plugin:
1. Check the logs for error messages
2. Verify configuration settings
3. Test RSS URLs manually
4. Review this documentation for troubleshooting steps
The plugin is designed to be robust and handle various edge cases, but may require configuration adjustments for specific use cases or news sources.

131
docs/guides/sms.md Normal file
View file

@ -0,0 +1,131 @@
# Twilio SMS Integration
This document describes how to configure and use Twilio SMS service for sending verification codes in the Xiaozhi system.
## Overview
Twilio SMS service has been implemented as a replacement for the previous Aliyun SMS service, providing Western-based SMS functionality for user verification.
## Configuration
### 1. Twilio Account Setup
1. Visit [Twilio Console](https://console.twilio.com/)
2. Create a new account or sign in to existing account
3. Navigate to the Console Dashboard
4. Get your Account SID and Auth Token from the Account Info section
5. Purchase a phone number for sending SMS messages
### 2. System Configuration
Configure the following parameters in the system configuration:
#### Required Parameters
- **twilio.sms.account_sid**: Your Twilio Account SID
- **twilio.sms.auth_token**: Your Twilio Auth Token
- **twilio.sms.phone_number**: Your Twilio phone number (in E.164 format, e.g., +1234567890)
- **twilio.sms.template_message**: SMS message template (default: "Your verification code is: %s")
#### Optional Parameters
- **server.sms_max_send_count**: Maximum SMS messages per phone number per day (default: 10)
- **server.enable_mobile_register**: Enable mobile phone registration (default: false)
### 3. Configuration Examples
#### Basic Configuration
```
twilio.sms.account_sid=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
twilio.sms.auth_token=your_auth_token_here
twilio.sms.phone_number=+1234567890
twilio.sms.template_message=Your verification code is: %s
```
#### Custom Template
```
twilio.sms.template_message=Welcome to Xiaozhi! Your verification code is %s. This code will expire in 10 minutes.
```
## Features
### SMS Verification
- Send verification codes via SMS
- Rate limiting (configurable daily limit per phone number)
- 60-second cooldown between SMS sends
- Automatic retry mechanism on failure
### Error Handling
- Connection failure detection
- Invalid phone number handling
- Rate limit enforcement
- Comprehensive error logging
## API Usage
### Sending Verification Code
```java
@Autowired
private SmsService smsService;
// Send verification code
smsService.sendVerificationCodeSms("+1234567890", "123456");
```
### Rate Limiting
The system implements the following rate limiting:
- **Daily Limit**: Configurable via `server.sms_max_send_count` (default: 10 messages per day)
- **Cooldown**: 60 seconds between consecutive SMS sends to the same number
- **Redis Storage**: Rate limit data stored in Redis for persistence
## Security Considerations
1. **API Keys**: Store Twilio credentials securely in system configuration
2. **Rate Limiting**: Prevents SMS abuse and spam
3. **Phone Number Validation**: Ensures proper E.164 format
4. **Error Handling**: Prevents credential exposure in logs
## Troubleshooting
### Common Issues
1. **Invalid Phone Number Format**
- Ensure phone numbers are in E.164 format (+1234567890)
- Remove spaces, dashes, and parentheses
2. **Authentication Failures**
- Verify Account SID and Auth Token are correct
- Check if credentials have SMS permissions
3. **Rate Limiting**
- Check daily send limits in Twilio console
- Verify system rate limiting configuration
4. **Phone Number Issues**
- Ensure Twilio phone number is verified
- Check if phone number supports SMS in target region
### Error Codes
- `SMS_SEND_FAILED`: Failed to send SMS message
- `SMS_CONNECTION_FAILED`: Failed to connect to Twilio service
- `SMS_SEND_TOO_FREQUENTLY`: Rate limit exceeded (60-second cooldown)
- `TODAY_SMS_LIMIT_REACHED`: Daily limit exceeded
## Migration from Aliyun SMS
If migrating from the previous Aliyun SMS service:
1. Remove old Aliyun SMS configuration parameters
2. Add new Twilio SMS configuration parameters
3. Update phone number formats to E.164 standard
4. Test SMS functionality with new configuration
## Support
For Twilio-specific issues, refer to:
- [Twilio SMS Documentation](https://www.twilio.com/docs/sms)
- [Twilio Console](https://console.twilio.com/)
- [Twilio Support](https://support.twilio.com/)

171
docs/guides/vision.md Normal file
View file

@ -0,0 +1,171 @@
# Vision Model Usage Guide
This tutorial is divided into two parts:
- Part 1: Running xiaozhi-server in single module mode to enable vision model
- Part 2: How to enable vision model when running in full module mode
Before enabling the vision model, you need to prepare three things:
- You need to prepare a device with a camera, and this device is already in the repository with camera functionality implemented. For example, `LCSC ESP32-S3 Development Board`
- Your device firmware version is upgraded to 1.6.6 or above
- You have successfully run the basic conversation module
## Single Module Running xiaozhi-server to Enable Vision Model
### Step 1: Confirm Network
Since the vision model will start port 8003 by default.
If you are running with docker, please confirm whether your `docker-compose.yml` has port `8003`, if not, update to the latest `docker-compose.yml` file
If you are running with source code, confirm whether the firewall allows port `8003`
### Step 2: Choose Your Vision Model
Open your `data/.config.yaml` file and set your `selected_module.VLLM` to a vision model. Currently we support vision models with `openai` type interfaces. `OpenAILLMVLLM` is one of the models compatible with `openai`.
```
selected_module:
VAD: ..
ASR: ..
LLM: ..
VLLM: OpenAILLMVLLM
TTS: ..
Memory: ..
Intent: ..
```
Assuming we use `OpenAILLMVLLM` as the vision model, we need to first log in to the [OpenAI](https://platform.openai.com/api-keys) website to apply for an API key. If you have already applied for a key before, you can reuse that key.
In your configuration file, add this configuration. If you already have this configuration, set up your api_key.
```
VLLM:
OpenAILLMVLLM:
api_key: your_api_key
```
### Step 3: Start xiaozhi-server service
If you are using source code, enter the command to start
```
python app.py
```
If you are running with docker, restart the container
```
docker restart xiaozhi-esp32-server
```
After starting, it will output logs with the following content.
```
2025-06-01 **** - OTA interface is http://192.168.4.7:8003/xiaozhi/ota/
2025-06-01 **** - Vision analysis interface is http://192.168.4.7:8003/mcp/vision/explain
2025-06-01 **** - Websocket address is ws://192.168.4.7:8000/xiaozhi/v1/
2025-06-01 **** - =======The above addresses are websocket protocol addresses, do not access with browser=======
2025-06-01 **** - If you want to test websocket, please use Google Chrome to open test_page.html in the test directory
2025-06-01 **** - =============================================================
```
After starting, use your browser to open the `Vision analysis interface` connection in the logs. See what it outputs? If you are on Linux and don't have a browser, you can execute this command:
```
curl -i your_vision_analysis_interface
```
Normally it will display like this
```
MCP Vision interface is running normally, vision explanation interface address is: http://xxxx:8003/mcp/vision/explain
```
Please note, if you are using public network deployment or docker deployment, you must change this configuration in your `data/.config.yaml`
```
server:
vision_explain: http://your_IP_or_domain:port_number/mcp/vision/explain
```
Why? Because the vision explanation interface needs to be distributed to the device. If your address is a local network address or a docker internal address, the device cannot access it.
Assuming your public network address is `111.111.111.111`, then `vision_explain` should be configured like this
```
server:
vision_explain: http://111.111.111.111:8003/mcp/vision/explain
```
If your MCP Vision interface is running normally, and you have also tried to access the distributed `Vision explanation interface address` normally with your browser, please continue to the next step
### Step 4: Device Wake-up Activation
Say to the device "Please turn on the camera and tell me what you see"
Pay attention to the xiaozhi-server log output to see if there are any errors.
## How to enable vision model when running full module
### Step 1: Confirm Network
Since the vision model will start port 8003 by default.
If you are running with docker, please confirm whether your `docker-compose_all.yml` maps port `8003`. If not, update to the latest `docker-compose_all.yml` file
If you are running from source code, confirm whether the firewall allows port `8003`
### Step 2: Confirm Your Configuration File
Open your `data/.config.yaml` file and confirm whether the structure of your configuration file is the same as `data/config_from_api.yaml`. If it's different or missing something, please complete it.
### Step 3: Configure Vision Model API Key
We need to first log in to the [OpenAI](https://platform.openai.com/api-keys) website to apply for an API key. If you have already applied for a key before, you can reuse that key.
Log in to the `Smart Control Panel`, click `Model Configuration` in the top menu, click `Vision Large Language Model` in the left sidebar, find `VLLM_OpenAILLMVLLM`, click the modify button, enter your API key in the `API Key` field in the popup, and click save.
After saving successfully, go to the agent you need to test, click `Configure Role`, in the opened content, check whether `Vision Large Language Model (VLLM)` has selected the vision model just configured. Click save.
### Step 4: Start xiaozhi-server module
If you are using source code, enter the command to start
```
python app.py
```
If you are running with docker, restart the container
```
docker restart xiaozhi-esp32-server
```
After starting, it will output logs with the following content.
```
2025-06-01 **** - Vision analysis interface is http://192.168.4.7:8003/mcp/vision/explain
2025-06-01 **** - Websocket address is ws://192.168.4.7:8000/xiaozhi/v1/
2025-06-01 **** - =======The above addresses are websocket protocol addresses, do not access with browser=======
2025-06-01 **** - If you want to test websocket, please use Google Chrome to open test_page.html in the test directory
2025-06-01 **** - =============================================================
```
After starting, use your browser to open the `Vision analysis interface` connection in the logs. See what it outputs? If you are on Linux and don't have a browser, you can execute this command:
```
curl -i your_vision_analysis_interface
```
Normally it will display like this
```
MCP Vision interface is running normally, vision explanation interface address is: http://xxxx:8003/mcp/vision/explain
```
Please note, if you are using public network deployment or docker deployment, you must change this configuration in your `data/.config.yaml`
```
server:
vision_explain: http://your_IP_or_domain:port_number/mcp/vision/explain
```
Why? Because the vision explanation interface needs to be distributed to the device. If your address is a local network address or a docker internal address, the device cannot access it.
Assuming your public network address is `111.111.111.111`, then `vision_explain` should be configured like this
```
server:
vision_explain: http://111.111.111.111:8003/mcp/vision/explain
```
If your MCP Vision interface is running normally, and you have also tried to access the distributed `Vision explanation interface address` normally with your browser, please continue to the next step
### Step 4: Device Wake-up Activation
Say to the device "Please turn on the camera and tell me what you see"
Pay attention to the xiaozhi-server log output to see if there are any errors.

149
docs/guides/voiceprint.md Normal file
View file

@ -0,0 +1,149 @@
# 🎤 Voiceprint Recognition
**⚠️ Important Notice: Voiceprint recognition is not currently implemented in the English version of Xiaozhi ESP32 Server.**
## 🎯 What is Voiceprint Recognition?
Voiceprint recognition is a biometric technology that identifies users by their unique voice characteristics. It allows Xiaozhi to:
- **Identify users** by their voice patterns
- **Provide personalized responses** based on who is speaking
- **Enable access control** through voice authentication
- **Support multi-user environments** with different user profiles
## 🚧 Current Status
The voiceprint recognition feature is **not available** in the current English version of Xiaozhi ESP32 Server. This feature was part of the original Chinese implementation but has not been ported to the Western version.
## 🔗 Original Implementation
For users who need voiceprint recognition functionality, please refer to the **original Chinese implementation**:
### **Original Documentation**
- **Chinese Documentation**: [Voiceprint Integration Guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md)
- **Original Repository**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server)
### **Original Voiceprint Service**
- **Voiceprint API**: [xinnan-tech/voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)
- **Service Documentation**: [Voiceprint API README](https://github.com/xinnan-tech/voiceprint-api/blob/main/README.md)
## 🛠️ Implementation Details (Original)
The original voiceprint recognition system includes:
### **Components**
- **Voiceprint API Service** - Standalone service for voice processing
- **MySQL Database** - Stores voiceprint feature vectors
- **Docker Deployment** - Containerized service deployment
- **REST API** - HTTP endpoints for voiceprint management
### **Features**
- **Voice Registration** - Register users' voice patterns
- **Voice Recognition** - Identify users by their voice
- **Database Storage** - Persistent storage of voiceprint data
- **API Integration** - RESTful API for voiceprint operations
### **Technical Requirements**
- **MySQL Database** - For storing voiceprint data
- **Docker** - For service deployment
- **Audio Processing** - WAV audio file handling
- **Feature Extraction** - Voice characteristic analysis
## 🔮 Future Implementation
Voiceprint recognition may be implemented in future versions of the English Xiaozhi ESP32 Server. This would involve:
### **Planned Features**
- **English Voice Models** - Optimized for English speech patterns
- **Western API Integration** - Integration with Western voice recognition services
- **Privacy-Focused Design** - Local processing with privacy protection
- **Multi-language Support** - Support for multiple languages
### **Implementation Considerations**
- **Privacy Concerns** - Voice biometric data handling
- **Accuracy Requirements** - High accuracy for user identification
- **Performance Impact** - Minimal impact on system performance
- **Legal Compliance** - Compliance with privacy regulations
## 🎯 Alternative Solutions
While voiceprint recognition is not available, you can achieve similar functionality through:
### **User Identification Methods**
- **Device-based Identification** - Different devices for different users
- **Voice Commands** - Custom voice commands for user identification
- **Manual User Selection** - Manual user switching in the interface
- **Time-based Profiles** - Different profiles based on time of day
### **Personalization Features**
- **Custom Responses** - Personalized responses based on user preferences
- **User Profiles** - Different user profiles with custom settings
- **Voice Customization** - Different TTS voices for different users
- **Command Customization** - Custom voice commands per user
## 📚 Related Documentation
### **Available Features**
- **[Voice Interaction](../features/voice-interaction.md)** - Basic voice recognition and synthesis
- **[Plugin System](../features/plugins.md)** - Extensible functionality
- **[Integrations](../features/integrations.md)** - Third-party service integrations
- **[Configuration](../configuration/basic-setup.md)** - System configuration
### **Original Features**
- **[Original Repository](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Complete original implementation
- **[Chinese Documentation](https://github.com/xinnan-tech/xiaozhi-esp32-server/tree/main/docs)** - Original documentation
- **[Voiceprint API](https://github.com/xinnan-tech/voiceprint-api)** - Original voiceprint service
## 🆘 Support and Questions
### **For Voiceprint Recognition**
- **Original Implementation**: Refer to [xinnan-tech repository](https://github.com/xinnan-tech/xiaozhi-esp32-server)
- **Voiceprint Service**: Check [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)
- **Chinese Documentation**: [Original voiceprint guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md)
### **For English Version**
- **Feature Requests**: [GitHub Issues](https://github.com/lapy/xiaozhi-esp32-server/issues)
- **Community Support**: [Discord Community](https://discord.gg/xiaozhi-esp32)
- **General Questions**: [FAQ](../support/faq.md)
## 🎯 Next Steps
Since voiceprint recognition is not available in the English version:
1. **[Use Available Features](../features/voice-interaction.md)** - Explore current voice capabilities
2. **[Check Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Refer to Chinese version if needed
3. **[Request Feature Implementation](https://github.com/lapy/xiaozhi-esp32-server/issues)** - Submit feature request
4. **[Explore Alternatives](#alternative-solutions)** - Use alternative user identification methods
## 🆘 Need Help?
- **Voiceprint Questions?** Check [Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server)
- **English Version Questions?** Browse [FAQ](../support/faq.md)
- **Feature Requests?** Submit [GitHub Issue](https://github.com/lapy/xiaozhi-esp32-server/issues)
---
## 🎯 Quick Reference
### **Current Status**
- ❌ **Not Available** in English version
- ✅ **Available** in original Chinese version
- 🔗 **Original Implementation**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server)
### **Alternative Solutions**
- Device-based identification
- Custom voice commands
- Manual user selection
- Time-based profiles
### **Future Plans**
- English voice models
- Western API integration
- Privacy-focused design
- Multi-language support
---
**Voiceprint recognition is not available in the English version. Please refer to the original Chinese implementation for this feature. 🎤**
👉 **[Next: Available Features →](../features/voice-interaction.md)**

214
docs/guides/weather.md Normal file
View file

@ -0,0 +1,214 @@
# Weather Plugin Integration
This document describes how to use and configure the Weather plugin using OpenWeatherMap API for getting weather information from a reliable weather service.
## Overview
The Weather plugin (`get_weather`) allows users to get current weather conditions and forecasts for any location worldwide using the OpenWeatherMap API. It provides comprehensive weather data including current conditions, detailed parameters, and 5-day forecasts.
## Features
- **Global Coverage**: Weather data for any location worldwide
- **Current Conditions**: Temperature, humidity, pressure, wind, visibility
- **5-Day Forecast**: Detailed daily forecasts with temperature ranges
- **Multiple Languages**: Support for various languages (English, Japanese, Spanish, French, German)
- **IP-Based Location**: Automatically detects user location from IP address
- **Caching**: 10-minute cache to reduce API calls and improve performance
- **Error Handling**: Robust error handling with user-friendly messages
## Configuration
### 1. Plugin Configuration (config.yaml)
```yaml
plugins:
get_weather:
api_key: "your_openweathermap_api_key"
default_location: "New York"
```
### 2. Enable Plugin
Add the plugin to the functions list in `config.yaml`:
```yaml
Intent:
intent_llm:
functions:
- get_weather
- get_news
- play_music
function_call:
functions:
- change_role
- get_weather
- get_news
- play_music
```
### 3. Database Configuration
The plugin is automatically registered in the database with the following configuration:
- **Plugin Name**: `get_weather`
- **Display Name**: `Weather Service`
- **API Key**: OpenWeatherMap API key (configurable)
- **Default Location**: New York (configurable)
## API Setup
### OpenWeatherMap API Key
1. **Sign Up**: Visit [OpenWeatherMap](https://openweathermap.org/api) and create a free account
2. **Get API Key**: Navigate to your account dashboard and copy your API key
3. **Configure**: Replace `your_openweathermap_api_key` in the configuration with your actual API key
### API Limits
- **Free Tier**: 1000 calls per day, 60 calls per minute
- **Paid Plans**: Available for higher usage requirements
- **Caching**: Plugin uses 10-minute caching to minimize API calls
## Usage Examples
### Basic Weather Query
```
User: "What's the weather like?"
→ Gets weather for user's detected location or default location
User: "What's the weather in London?"
→ Gets current weather and 5-day forecast for London
User: "How's the weather in Tokyo?"
→ Gets weather information for Tokyo
```
### Advanced Queries
```
User: "What's the weather in Los Angeles, CA?"
→ Gets weather for Los Angeles, California
User: "Weather forecast for Paris, France"
→ Gets 5-day forecast for Paris
User: "Tell me about the weather in Sydney"
→ Gets comprehensive weather information for Sydney
```
## Supported Locations
The plugin supports any location worldwide that OpenWeatherMap covers:
- **Cities**: New York, London, Tokyo, Paris, etc.
- **Cities with State/Province**: Los Angeles, CA; Toronto, ON; etc.
- **Cities with Country**: London, UK; Tokyo, Japan; etc.
- **International Locations**: Any city worldwide
## Weather Data Provided
### Current Conditions
- **Temperature**: Current temperature and "feels like" temperature
- **Conditions**: Weather description (sunny, cloudy, rain, etc.)
- **Temperature Range**: Daily minimum and maximum temperatures
- **Humidity**: Relative humidity percentage
- **Pressure**: Atmospheric pressure in hPa
- **Wind**: Wind speed and direction
- **Visibility**: Visibility distance in kilometers
### 5-Day Forecast
- **Daily Summary**: Most common weather condition for each day
- **Temperature Range**: Daily high and low temperatures
- **Average Humidity**: Daily average humidity
- **Average Wind Speed**: Daily average wind speed
## Language Support
The plugin supports multiple languages for weather descriptions:
| Language Code | Description |
|---------------|-------------|
| `en_US` | English (default) |
| `ja_JP` | Japanese |
| `es_ES` | Spanish |
| `fr_FR` | French |
| `de_DE` | German |
## Technical Details
### API Endpoints Used
1. **Current Weather**: `https://api.openweathermap.org/data/2.5/weather`
- Provides current weather conditions
- Parameters: location, API key, units (metric), language
2. **5-Day Forecast**: `https://api.openweathermap.org/data/2.5/forecast`
- Provides 5-day weather forecast
- Parameters: location, API key, units (metric), language
### Data Processing
- **Weather Conditions**: Standardized weather condition descriptions
- **Temperature**: Converted to Celsius (°C)
- **Wind Direction**: Converted to compass directions (N, NE, E, etc.)
- **Forecast Grouping**: Daily forecasts grouped from hourly data
### Caching Strategy
- **Cache Key**: `western_weather_{location}_{lang}`
- **Cache Duration**: 10 minutes (600 seconds)
- **Cache Type**: Weather cache type from cache manager
## Error Handling
The plugin handles various error scenarios:
1. **API Key Not Configured**: Returns helpful message to contact administrator
2. **Invalid Location**: Returns error message asking user to check location name
3. **API Errors**: Logs detailed error information and returns user-friendly message
4. **Network Issues**: Handles timeouts and connection errors gracefully
## Migration from Previous Weather Service
If migrating from a previous weather service:
1. **Replace Plugin**: Change weather plugin configuration
2. **Update API Key**: Replace previous API key with OpenWeatherMap API key
3. **Update Default Location**: Change default location to Western city
4. **Test Functionality**: Verify weather queries work correctly
## Performance Considerations
- **API Limits**: Monitor daily API usage to avoid hitting limits
- **Caching**: 10-minute cache significantly reduces API calls
- **Error Handling**: Graceful degradation when API is unavailable
- **Timeout**: 10-second timeout prevents long waits
## Security Notes
- **API Key Protection**: Store API key securely and don't commit to version control
- **Input Validation**: Location input is validated by the API
- **Rate Limiting**: Built-in caching helps prevent rate limit issues
## Troubleshooting
### Common Issues
1. **"Weather service not configured"**
- Solution: Configure OpenWeatherMap API key in settings
2. **"Unable to get weather data"**
- Solution: Check if location name is correct and spelled properly
3. **API rate limit exceeded**
- Solution: Wait for rate limit reset or upgrade to paid plan
### Debug Information
Check logs for detailed error information:
- API response codes and error messages
- Location parsing issues
- Network connectivity problems
## Conclusion
The Western Weather plugin provides reliable, comprehensive weather information using the industry-standard OpenWeatherMap API. With global coverage, multiple language support, and robust error handling, it's suitable for production use in Western markets.

276
docs/guides/whisper-asr.md Normal file
View file

@ -0,0 +1,276 @@
# Whisper ASR Integration Guide
[TOC]
-----
## Introduction
OpenAI Whisper is a state-of-the-art automatic speech recognition (ASR) system that provides excellent accuracy for multilingual speech recognition. This guide will help you integrate and configure Whisper ASR with the Xiaozhi ESP32 Server.
## Features
- **Offline Operation**: Complete offline speech recognition after initial model download
- **Multilingual Support**: Supports 99+ languages with auto-detection
- **Multiple Model Sizes**: From tiny (39MB) to large-v3 (1.5GB) models
- **GPU Acceleration**: Automatic CUDA detection and usage
- **High Accuracy**: State-of-the-art accuracy for speech recognition
## Available Models
| Model | Size | Speed | Accuracy | Languages | Recommended Use |
|-------|------|-------|----------|-----------|-----------------|
| tiny.en | ~39 MB | Fastest | Lowest | English only | Real-time applications, limited resources |
| tiny | ~39 MB | Fastest | Lowest | Multilingual | Real-time applications, limited resources |
| base.en | ~74 MB | Fast | Good | English only | Balanced performance for English |
| base | ~74 MB | Fast | Good | Multilingual | **Recommended default** |
| small.en | ~244 MB | Medium | Better | English only | Better accuracy for English |
| small | ~244 MB | Medium | Better | Multilingual | Better accuracy, multilingual |
| medium.en | ~769 MB | Slow | High | English only | High accuracy for English |
| medium | ~769 MB | Slow | High | Multilingual | High accuracy, multilingual |
| large-v1 | ~1550 MB | Slowest | Highest | Multilingual | Maximum accuracy |
| large-v2 | ~1550 MB | Slowest | Highest | Multilingual | Maximum accuracy |
| large-v3 | ~1550 MB | Slowest | Highest | Multilingual | **Latest model, maximum accuracy** |
## Installation and Setup
### Method 1: Automatic Setup (Recommended)
The Whisper models are automatically downloaded when first used. The `docker-setup.sh` script creates the necessary directories and download scripts.
```bash
# Run the setup script (if not already done)
./docker-setup.sh
```
### Method 2: Manual Model Download
If you want to pre-download models or download them manually:
```bash
# Navigate to the Whisper models directory
cd /opt/xiaozhi-server/models/whisper
# Download a specific model
python3 download_models.py --model base --dir /opt/xiaozhi-server/models/whisper
# Download all models (takes a long time and requires significant disk space)
./download_all_models.sh
```
## Configuration
### Basic Configuration
Add the following to your `config.yaml` file:
```yaml
selected_module:
ASR: WhisperASR
ASR:
WhisperASR:
type: whisper
model_name: base # Choose from available models above
device: auto # auto (auto-detect), cpu, cuda (GPU acceleration)
language: null # null for auto-detect, or specific language code
output_dir: tmp/
```
### Advanced Configuration Options
```yaml
ASR:
WhisperASR:
type: whisper
model_name: large-v3 # Use the latest and most accurate model
device: cuda # Force GPU usage (requires CUDA)
language: "en" # Force English recognition
output_dir: tmp/
```
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `type` | string | `whisper` | Provider type (must be "whisper") |
| `model_name` | string | `base` | Whisper model to use |
| `device` | string | `auto` | Device selection: `auto`, `cpu`, `cuda` |
| `language` | string/null | `null` | Language code or `null` for auto-detect |
| `output_dir` | string | `tmp/` | Directory for temporary audio files |
### Supported Language Codes
Whisper supports 99+ languages. Common language codes include:
| Language | Code | Language | Code |
|----------|------|----------|------|
| English | `en` | Japanese | `ja` |
| French | `fr` | Korean | `ko` |
| German | `de` | Russian | `ru` |
| Italian | `it` | Arabic | `ar` |
| Portuguese | `pt` | Hindi | `hi` |
For the complete list, refer to the [Whisper documentation](https://github.com/openai/whisper#available-models-and-languages).
## Performance Optimization
### Model Selection Guidelines
1. **For Real-time Applications**: Use `tiny` or `base` models
2. **For Balanced Performance**: Use `base` or `small` models
3. **For Maximum Accuracy**: Use `large-v3` model
4. **For English Only**: Use `.en` variants for better performance
### Device Configuration
```yaml
# For systems with GPU
device: cuda
# For CPU-only systems
device: cpu
# For automatic detection (recommended)
device: auto
```
### Language Optimization
```yaml
# For auto-detection (recommended for multilingual environments)
language: null
# For specific language (faster processing)
language: "en"
```
## Usage Examples
### Example 1: English-Only Setup
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base.en
device: auto
language: "en"
output_dir: tmp/
```
### Example 2: Multilingual Setup
```yaml
ASR:
WhisperASR:
type: whisper
model_name: base
device: auto
language: null # Auto-detect language
output_dir: tmp/
```
### Example 3: High-Accuracy Setup
```yaml
ASR:
WhisperASR:
type: whisper
model_name: large-v3
device: cuda
language: null
output_dir: tmp/
```
## Troubleshooting
### Common Issues
#### 1. CUDA Out of Memory
**Error**: `RuntimeError: CUDA out of memory`
**Solution**: Use a smaller model or switch to CPU:
```yaml
model_name: base # Instead of large-v3
device: cpu # Force CPU usage
```
#### 2. Model Download Fails
**Error**: Models not downloading automatically
**Solution**: Download manually:
```bash
cd /opt/xiaozhi-server/models/whisper
python3 download_models.py --model base --dir /opt/xiaozhi-server/models/whisper
```
#### 3. Slow Processing
**Issue**: Speech recognition is too slow
**Solutions**:
- Use a smaller model (`tiny`, `base`)
- Use language-specific models (`.en` variants)
- Specify the language instead of auto-detection
#### 4. Low Accuracy
**Issue**: Recognition accuracy is poor
**Solutions**:
- Use a larger model (`small`, `medium`, `large-v3`)
- Ensure clear audio input
- Use language-specific models when possible
### Performance Monitoring
Monitor Whisper performance through logs:
```bash
# Check Whisper logs
docker logs xiaozhi-server | grep -i whisper
# Monitor processing times
docker logs xiaozhi-server | grep "Whisper transcription completed"
```
## Comparison with Other ASR Providers
| Provider | Type | Accuracy | Speed | Languages | Offline |
|----------|------|----------|-------|-----------|---------|
| Whisper | Local | Very High | Medium | 99+ | ✅ |
| OpenAI ASR | API | High | Fast | 99+ | ❌ |
| Vosk | Local | Medium | Fast | 20+ | ✅ |
| Sherpa ONNX | Local | High | Fast | 10+ | ✅ |
| Gemini ASR | API | High | Fast | 99+ | ❌ |
## Best Practices
1. **Start with `base` model**: Good balance of speed and accuracy
2. **Use GPU when available**: Significantly faster processing
3. **Specify language when known**: Improves accuracy and speed
4. **Monitor disk space**: Large models require significant storage
5. **Test different models**: Find the best fit for your use case
## Additional Resources
- [Whisper GitHub Repository](https://github.com/openai/whisper)
- [Whisper Paper](https://arxiv.org/abs/2212.04356)
- [Xiaozhi ESP32 Server Documentation](../README.md)
- [Performance Testing Guide](../guides/dev-ops.md)
## Support
For issues related to Whisper ASR integration:
1. Check the troubleshooting section above
2. Review the application logs
3. Test with different model configurations
4. Open an issue on the project repository
---
*Last updated: January 2025*

137
docs/hardware/firmware.md Normal file
View file

@ -0,0 +1,137 @@
# ESP32 Firmware Compilation
## Step 1: Prepare Your OTA Address
If you are using version 0.3.12 of this project, whether it's simple Server deployment or full module deployment, you will have an OTA address.
Since the OTA address setup method for simple Server deployment and full module deployment is different, please choose the specific method below:
### If you are using Simple Server Deployment
At this time, please open your OTA address with a browser, for example my OTA address
```
http://192.168.1.25:8003/xiaozhi/ota/
```
If it displays "OTA interface is running normally, the websocket address sent to the device is: ws://xxx:8000/xiaozhi/v1/
You can use the project's built-in `test_page.html` to test whether you can connect to the websocket address output by the OTA page.
If you can't access it, you need to modify the `server.websocket` address in the configuration file `.config.yaml`, restart and test again until `test_page.html` can access normally.
After success, please proceed to Step 2
### If you are using Full Module Deployment
At this time, please open your OTA address with a browser, for example my OTA address
```
http://192.168.1.25:8003/xiaozhi/ota/
```
If it displays "OTA interface is running normally, websocket cluster count: X". Then proceed to step 2.
If it displays "OTA interface is not running normally", you probably haven't configured the `Websocket` address in the `Control Console`. Then:
- 1. Use super administrator to login to the control console
- 2. Click `Parameter Management` in the top menu
- 3. Find the `server.websocket` item in the list and enter your `Websocket` address. For example, mine is
```
ws://192.168.1.25:8000/xiaozhi/v1/
```
After configuration, refresh your OTA interface address with a browser to see if it's normal. If it's still not normal, confirm again whether Websocket is started normally and whether the Websocket address is configured.
## Step 2: Configure Environment
First configure the project environment according to this tutorial [Windows ESP IDF 5.3.2 Development Environment Setup and Xiaozhi Compilation](https://github.com/lapy/xiaozhi-esp32-server/wiki)
## Step 3: Open Configuration File
After configuring the compilation environment, download the xiaozhi-esp32 project source code,
Download the xiaozhi-esp32 project source code from here: [xiaozhi-esp32 project source code](https://github.com/78/xiaozhi-esp32).
After downloading, open the `xiaozhi-esp32/main/Kconfig.projbuild` file.
## Step 4: Modify OTA Address
Find the content of `default` for `OTA_URL`, change `https://api.tenclass.net/xiaozhi/ota/`
to your own address. For example, if my interface address is `http://192.168.1.25:8003/xiaozhi/ota/`, change the content to this.
Before modification:
```
config OTA_URL
string "Default OTA URL"
default "https://api.tenclass.net/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
After modification:
```
config OTA_URL
string "Default OTA URL"
default "http://192.168.1.25:8003/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
## Step 4: Set Compilation Parameters
Set compilation parameters
```
# Enter the xiaozhi-esp32 root directory from terminal command line
cd xiaozhi-esp32
# For example, I use esp32s3 board, so set compilation target to esp32s3. If your board is other model, please replace with corresponding model
idf.py set-target esp32s3
# Enter menu configuration
idf.py menuconfig
```
After entering menu configuration, go to `Xiaozhi Assistant` and set `BOARD_TYPE` to your board's specific model
Save and exit, return to terminal command line.
## Step 5: Compile Firmware
```
idf.py build
```
## Step 6: Package bin Firmware
```
cd scrIPts
python release.py
```
After the above packaging command is executed, the firmware file `merged-binary.bin` will be generated in the `build` directory under the project root directory.
This `merged-binary.bin` is the firmware file to be burned to the hardware.
Note: If you encounter a "zIP" related error after executing the second command, please ignore this error. As long as the firmware file `merged-binary.bin` is generated in the `build` directory, it won't have much impact on you, please continue.
## Step 7: Burn Firmware
Connect the ESP32 device to your computer, use Chrome browser to open the following URL
```
https://espressif.github.io/esp-launchpad/
```
Open this tutorial, [Flash Tool/Web-based Firmware Burning (No IDF Development Environment)](https://github.com/lapy/xiaozhi-esp32-server/wiki).
Go to: `Method 2: ESP-Launchpad Browser WEB-based Burning`, starting from `3. Burn Firmware/Download to Development Board`, follow the tutorial.
After successful burning and network connection, wake up Xiaozhi through the wake word and pay attention to the console information output by the server.
## Common Issues
The following are some common issues for reference:
[1. Why does Xiaozhi recognize many Korean, Japanese, and English words when I speak?](../support/faq.md)
[2. Why does "TTS task error file does not exist" occur?](../support/faq.md)
[3. TTS often fails and times out](../support/faq.md)
[4. Can connect to self-built server using WiFi, but cannot connect in 4G mode](../support/faq.md)
[5. How to improve Xiaozhi's conversation response speed?](../support/faq.md)
[6. I speak slowly, and Xiaozhi keeps interrupting when I pause](../support/faq.md)
[7. I want to control lights, air conditioning, remote power on/off and other operations through Xiaozhi](../support/faq.md)

403
docs/hardware/flashing.md Normal file
View file

@ -0,0 +1,403 @@
# 🔌 Device Flashing Guide
This guide covers how to flash firmware to your ESP32 device using various methods.
## 🎯 Flashing Methods Overview
Choose the method that works best for your setup:
- **Web-based Flashing** (Recommended) - No software installation required
- **Command Line Flashing** - For developers and advanced users
- **IDE Flashing** - Using Arduino IDE or PlatformIO
- **OTA Flashing** - Over-the-air updates for existing devices
## 🌐 Web-based Flashing (Recommended)
### **Step 1: Prepare Your Device**
1. **Connect ESP32** to your computer via USB
2. **Install USB drivers** if needed (usually automatic on Windows/Mac)
3. **Identify COM port** (Windows) or device path (Mac/Linux)
**Windows:**
- Open Device Manager → Ports (COM & LPT)
- Look for "Silicon Labs CP210x" or similar
**Mac/Linux:**
```bash
# List USB devices
ls /dev/tty.*
# Look for /dev/tty.usbserial-* or /dev/ttyUSB*
```
### **Step 2: Access ESP-Launchpad**
1. **Open Chrome browser** (recommended for best compatibility)
2. **Navigate to**: https://espressif.github.io/esp-launchpad/
3. **Allow camera/microphone** permissions if prompted
### **Step 3: Upload Firmware**
1. **Click "Choose File"** or drag and drop your firmware file
2. **Select your firmware**: `merged-binary.bin` (from firmware compilation)
3. **Click "Connect"** and select your ESP32 device
4. **Wait for connection** to be established
### **Step 4: Flash Firmware**
1. **Click "Flash"** to start the flashing process
2. **Wait for completion** (usually 30-60 seconds)
3. **Device will restart** automatically after flashing
4. **Check console output** for any errors
### **Step 5: Verify Installation**
1. **Check device status** - LED indicators should show normal operation
2. **Test wake word** - Say "Hey Xiaozhi" or configured wake word
3. **Check server logs** - Look for device connection in server logs
## 💻 Command Line Flashing
### **Prerequisites**
- **ESP-IDF** development environment installed
- **esptool.py** available in your PATH
- **Firmware file** ready for flashing
### **Step 1: Install esptool**
```bash
# Install esptool if not already installed
pip install esptool
# Verify installation
esptool.py version
```
### **Step 2: Identify Device**
```bash
# List available serial ports
esptool.py --port auto chip_id
# Or specify port directly
esptool.py --port COM3 chip_id # Windows
esptool.py --port /dev/ttyUSB0 chip_id # Linux
esptool.py --port /dev/tty.usbserial-* chip_id # Mac
```
### **Step 3: Flash Firmware**
```bash
# Basic flashing command
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 merged-binary.bin
# With verification
esptool.py --chip esp32s3 --port COM3 --baud 921600 --verify write_flash 0x0 merged-binary.bin
# With progress indicator
esptool.py --chip esp32s3 --port COM3 --baud 921600 --verify --progress write_flash 0x0 merged-binary.bin
```
### **Step 4: Advanced Flashing Options**
```bash
# Flash with specific memory layout
esptool.py --chip esp32s3 --port COM3 --baud 921600 \
--flash_mode dio \
--flash_freq 80m \
--flash_size 16MB \
write_flash 0x0 merged-binary.bin
# Flash multiple files
esptool.py --chip esp32s3 --port COM3 --baud 921600 \
write_flash 0x0 bootloader.bin \
0x8000 partition-table.bin \
0x10000 merged-binary.bin
```
## 🔧 IDE Flashing
### **Arduino IDE Method**
#### **Step 1: Install ESP32 Board Package**
1. **Open Arduino IDE**
2. **Go to**: File → Preferences
3. **Add board manager URL**:
```
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
```
4. **Go to**: Tools → Board → Boards Manager
5. **Search for "ESP32"** and install "ESP32 by Espressif Systems"
#### **Step 2: Configure Board**
1. **Select board**: Tools → Board → ESP32 Arduino → ESP32S3 Dev Module
2. **Select port**: Tools → Port → [Your COM port]
3. **Configure settings**:
- **Upload Speed**: 921600
- **Flash Mode**: DIO
- **Flash Frequency**: 80MHz
- **Flash Size**: 16MB
#### **Step 3: Flash Firmware**
1. **Open firmware file** (if available as .ino)
2. **Click Upload** button
3. **Wait for completion**
### **PlatformIO Method**
#### **Step 1: Install PlatformIO**
```bash
# Install PlatformIO
pip install platformio
# Or use PlatformIO IDE
# Download from: https://platformio.org/install/ide
```
#### **Step 2: Create Project**
```bash
# Create new project
pio project init --board esp32s3-devkitc-1
# Or use existing project
cd your-project-directory
```
#### **Step 3: Configure platformio.ini**
```ini
[env:esp32s3]
platform = espressif32
board = esp32s3-devkitc-1
framework = arduino
monitor_speed = 115200
upload_speed = 921600
```
#### **Step 4: Flash Firmware**
```bash
# Upload firmware
pio run --target upload
# Monitor serial output
pio device monitor
```
## 📡 OTA (Over-the-Air) Flashing
### **Prerequisites**
- **Device already running** Xiaozhi firmware
- **Network connectivity** to your server
- **OTA interface** accessible
- **New firmware file** ready
### **Step 1: Prepare OTA Update**
1. **Access OTA interface**: `http://YOUR_IP:8003/xiaozhi/ota/`
2. **Verify interface** shows "OTA interface is running normally"
3. **Prepare firmware file** for upload
### **Step 2: Upload Firmware**
1. **Click "Choose File"** in OTA interface
2. **Select new firmware** file
3. **Click "Upload"** to start OTA update
4. **Wait for upload** to complete
### **Step 3: Trigger Update**
1. **Wake up device** using wake word
2. **Say "Update firmware"** or similar command
3. **Device will download** and install new firmware
4. **Device will restart** automatically
### **Step 4: Verify Update**
1. **Check device status** after restart
2. **Test functionality** with voice commands
3. **Check server logs** for successful connection
## 🛠️ Troubleshooting Flashing Issues
### **Common Issues and Solutions**
#### **"Port not found" Error**
```bash
# Check available ports
esptool.py --port auto chip_id
# Install USB drivers
# Windows: Download from Silicon Labs website
# Mac: Usually automatic
# Linux: Add user to dialout group
sudo usermod -a -G dialout $USER
```
#### **"Failed to connect" Error**
1. **Hold BOOT button** while pressing RESET
2. **Release RESET** while holding BOOT
3. **Release BOOT** after 2 seconds
4. **Try flashing again**
#### **"Flash write error" Error**
```bash
# Try slower baud rate
esptool.py --chip esp32s3 --port COM3 --baud 115200 write_flash 0x0 merged-binary.bin
# Try different flash mode
esptool.py --chip esp32s3 --port COM3 --baud 921600 --flash_mode qio write_flash 0x0 merged-binary.bin
```
#### **"Verification failed" Error**
```bash
# Flash without verification first
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 merged-binary.bin
# Then verify separately
esptool.py --chip esp32s3 --port COM3 --baud 921600 verify_flash 0x0 merged-binary.bin
```
#### **"Device not responding" Error**
1. **Check USB cable** - use data cable, not charging cable
2. **Try different USB port** - prefer USB 2.0 ports
3. **Check power supply** - ensure stable 5V supply
4. **Reset device** - press RESET button
### **Advanced Troubleshooting**
#### **Erase Flash Before Flashing**
```bash
# Erase entire flash
esptool.py --chip esp32s3 --port COM3 erase_flash
# Erase specific sectors
esptool.py --chip esp32s3 --port COM3 erase_region 0x0 0x400000
```
#### **Read Flash for Verification**
```bash
# Read flash content
esptool.py --chip esp32s3 --port COM3 read_flash 0x0 0x400000 flash_content.bin
# Compare with original
diff merged-binary.bin flash_content.bin
```
#### **Reset to Factory Settings**
```bash
# Erase flash and reset
esptool.py --chip esp32s3 --port COM3 erase_flash
esptool.py --chip esp32s3 --port COM3 run
```
## 🔍 Flashing Verification
### **Step 1: Check Flash Content**
```bash
# Read flash and verify
esptool.py --chip esp32s3 --port COM3 verify_flash 0x0 merged-binary.bin
```
### **Step 2: Monitor Boot Process**
```bash
# Monitor serial output during boot
esptool.py --chip esp32s3 --port COM3 monitor
```
### **Step 3: Test Device Functionality**
1. **Power on device**
2. **Check LED indicators**
3. **Test wake word detection**
4. **Verify server connection**
## 📊 Flashing Performance Tips
### **Optimize Flashing Speed**
```bash
# Use maximum baud rate
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 merged-binary.bin
# Use optimal flash mode
esptool.py --chip esp32s3 --port COM3 --baud 921600 --flash_mode dio write_flash 0x0 merged-binary.bin
```
### **Batch Flashing Multiple Devices**
```bash
#!/bin/bash
# Flash multiple devices script
DEVICES=("/dev/ttyUSB0" "/dev/ttyUSB1" "/dev/ttyUSB2")
FIRMWARE="merged-binary.bin"
for device in "${DEVICES[@]}"; do
echo "Flashing $device..."
esptool.py --chip esp32s3 --port "$device" --baud 921600 write_flash 0x0 "$FIRMWARE"
if [ $? -eq 0 ]; then
echo "Successfully flashed $device"
else
echo "Failed to flash $device"
fi
done
```
## 🎯 Next Steps
After successful flashing:
1. **[Configure Your Device](../getting-started/first-device.md)** - Complete device setup
2. **[Test Voice Interaction](../features/voice-interaction.md)** - Verify functionality
3. **[Configure AI Providers](../configuration/providers.md)** - Set up AI services
4. **[Hardware Troubleshooting](troubleshooting.md)** - Common hardware issues
## 🆘 Need Help?
- **Flashing Issues?** Check [Troubleshooting](troubleshooting.md)
- **Hardware Questions?** See [Supported Devices](supported-devices.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Flashing Commands**
```bash
# Web-based (recommended)
https://espressif.github.io/esp-launchpad/
# Command line
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 merged-binary.bin
# OTA update
http://YOUR_IP:8003/xiaozhi/ota/
```
### **Common Ports**
- **Windows**: COM3, COM4, COM5...
- **Mac**: /dev/tty.usbserial-*
- **Linux**: /dev/ttyUSB0, /dev/ttyUSB1...
### **Troubleshooting Steps**
1. Check USB connection
2. Install drivers
3. Try different baud rate
4. Hold BOOT button during reset
5. Use web-based flashing
---
**Your device is ready to flash! 🎉**
👉 **[Next: Hardware Troubleshooting →](troubleshooting.md)**

View file

@ -0,0 +1,764 @@
# 🔧 ESP32 Firmware Compilation
This guide covers how to compile ESP32 firmware for Xiaozhi ESP32 Server, including both custom compilation and using pre-compiled firmware.
## 🎯 Firmware Options
### **Option 1: Custom Firmware Compilation**
- **Full control** over firmware features
- **Custom OTA addresses** and configurations
- **Latest features** and bug fixes
- **Requires ESP-IDF** development environment
### **Option 2: Pre-compiled Firmware**
- **Quick setup** with minimal configuration
- **No development environment** required
- **OTA address modification** only
- **Requires firmware version 1.6.1+**
## 📋 Prerequisites
### **For Custom Compilation**
- **ESP-IDF 5.3.2+** development environment
- **Python 3.10+** with pip
- **Git** for source code management
- **USB drivers** for ESP32 board
### **For Pre-compiled Firmware**
- **ESP32 board** with firmware version 1.6.1+
- **Web browser** for OTA configuration
- **Network access** to your Xiaozhi server
## 🚀 Option 1: Custom Firmware Compilation
### **Step 1: Prepare OTA Address**
**For Simple Server Deployment:**
1. Open your OTA address: `http://YOUR_IP:8003/xiaozhi/ota/`
2. Verify it shows: "OTA interface is running normally, the websocket address sent to the device is: ws://xxx:8000/xiaozhi/v1/"
3. Test WebSocket connection using `test_page.html`
**For Full Module Deployment:**
1. Open your OTA address: `http://YOUR_IP:8003/xiaozhi/ota/`
2. Verify it shows: "OTA interface is running normally, websocket cluster count: X"
3. If not working, configure `server.websocket` in Smart Control Panel
### **Step 2: Set Up ESP-IDF Environment**
Follow the [Windows ESP-IDF 5.3.2 Development Environment Setup Guide](https://github.com/lapy/xiaozhi-esp32-server/wiki) for detailed instructions.
**Quick Setup:**
```bash
# Install ESP-IDF
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh
# Set up environment
. ./export.sh
```
### **Step 3: Download Firmware Source Code**
```bash
# Clone the ESP32 firmware repository
git clone https://github.com/78/xiaozhi-esp32.git
cd xiaozhi-esp32
```
### **Step 4: Configure OTA Address**
Edit `main/Kconfig.projbuild` and modify the OTA URL:
**Before modification:**
```
config OTA_URL
string "Default OTA URL"
default "https://api.tenclass.net/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
**After modification:**
```
config OTA_URL
string "Default OTA URL"
default "http://192.168.1.25:8003/xiaozhi/ota/"
help
The application will access this URL to check for new firmwares and server address.
```
### **Step 5: Set Compilation Parameters**
```bash
# Set target board (replace esp32s3 with your board)
idf.py set-target esp32s3
# Enter menu configuration
idf.py menuconfig
```
**In menuconfig:**
1. Go to `Xiaozhi Assistant`
2. Set `BOARD_TYPE` to your specific board model
3. Save and exit
### **Step 6: Compile Firmware**
```bash
# Build the firmware
idf.py build
```
### **Step 7: Package Firmware**
```bash
# Navigate to scripts directory
cd scripts
# Package the firmware
python release.py
```
This creates `merged-binary.bin` in the `build` directory.
### **Step 8: Flash Firmware**
**Method 1: Web-based Flashing (Recommended)**
1. Open: https://espressif.github.io/esp-launchpad/
2. Upload `merged-binary.bin`
3. Connect ESP32 via USB
4. Select correct COM port
5. Click "Flash"
**Method 2: Command Line**
```bash
# Flash using esptool
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 merged-binary.bin
```
## 🚀 Option 2: Pre-compiled Firmware Configuration
### **Step 1: Download Pre-compiled Firmware**
Download firmware version 1.6.1 or above from: https://github.com/78/xiaozhi-esp32/releases
### **Step 2: Flash Pre-compiled Firmware**
**Web-based Flashing:**
1. Open: https://espressif.github.io/esp-launchpad/
2. Upload the downloaded firmware file
3. Connect ESP32 via USB
4. Flash the firmware
### **Step 3: Configure OTA Address**
**For Full Module Deployment:**
1. Open OTA address: `http://YOUR_IP:8003/xiaozhi/ota/`
2. Verify it shows: "OTA interface is running normally, websocket cluster count: X"
3. If not working, configure `server.websocket` in Smart Control Panel
**For Simple Server Deployment:**
1. Open OTA address: `http://YOUR_IP:8003/xiaozhi/ota/`
2. Verify it shows: "OTA interface is running normally"
3. Test WebSocket connection
### **Step 4: Enter Network Configuration Mode**
1. **Wake up the device** and say "Advanced Options"
2. **Click "Advanced Options"** at the top of the page
3. **Enter your server's OTA address**
4. **Click Save** and restart the device
**Example OTA Address:**
```
http://192.168.1.25:8003/xiaozhi/ota/
```
### **Step 5: Test Connection**
1. **Wake up Xiaozhi** using the wake word
2. **Check server logs** for connection confirmation
3. **Test voice interaction** with basic commands
## 🔧 Supported ESP32 Boards
### **Recommended Boards**
| Board | Chip | Features | Price | Best For |
|-------|------|----------|-------|----------|
| **ESP32-S3-DevKitC-1** | ESP32-S3 | Official board, good I/O | $15-25 | Development |
| **ESP32-S3-BOX** | ESP32-S3 | Built-in mic/speaker, display | $35-45 | Complete solution |
| **ESP32-S3-BOX-3** | ESP32-S3 | Improved audio, display | $40-50 | Production |
| **ESP32-S3-Korvo-2** | ESP32-S3 | High-quality audio array | $30-40 | Audio-focused |
### **Budget Options**
| Board | Chip | Features | Price | Best For |
|-------|------|----------|-------|----------|
| **ESP32-DevKitC** | ESP32 | Basic development | $8-15 | Learning |
| **ESP32-WROOM-32** | ESP32 | Module + dev board | $6-12 | Cost-sensitive |
| **ESP32-S2-Saola-1** | ESP32-S2 | Single-core option | $10-18 | Simple projects |
## 🎤 Audio Components
### **Microphone Options**
**Digital MEMS Microphones:**
- **SPH0645LM4H**: I2S interface, high quality
- **INMP441**: I2S interface, budget option
- **ICS-43434**: I2S interface, professional grade
**Analog Microphones:**
- **MAX9814**: Built-in AGC, easy to use
- **MAX4466**: Budget option
- **ADMP401**: Good quality
### **Speaker Options**
**Amplifier Modules:**
- **PAM8403**: Stereo, 3W power
- **MAX98357A**: Mono, excellent quality
- **TDA2822**: Simple, budget option
**Speakers:**
- **Small Speaker**: 8Ω, 0.5W+ power
- **Piezo Buzzer**: Simple beeps only
- **Headphone Jack**: External audio output
## 🔌 Pin Configurations
### **ESP32-S3 Standard Pinout**
| Function | ESP32-S3 Pin | ESP32 Pin | Notes |
|----------|--------------|-----------|-------|
| **Microphone WS** | GPIO 15 | GPIO 25 | Word select |
| **Microphone BCK** | GPIO 16 | GPIO 26 | Bit clock |
| **Microphone DIN** | GPIO 17 | GPIO 27 | Data input |
| **Speaker DOUT** | GPIO 18 | GPIO 32 | Data output |
| **Speaker BCK** | GPIO 19 | GPIO 33 | Bit clock |
| **Speaker LRC** | GPIO 20 | GPIO 25 | Left/right clock |
| **Power 3.3V** | 3.3V | 3.3V | Power supply |
| **Ground** | GND | GND | Ground |
### **Wiring Diagram**
```
ESP32-S3 Microphone Speaker
| | |
|-- 3.3V ----------|-- VCC |
|-- GND -----------|-- GND ------------|-- GND
|-- GPIO 15 -------|-- WS |
|-- GPIO 16 -------|-- BCK |
|-- GPIO 17 -------|-- DIN |
|-- GPIO 18 ---------------------------|-- DIN
|-- GPIO 19 ---------------------------|-- BCK
|-- GPIO 20 ---------------------------|-- LRC
```
## 🛠️ Troubleshooting
### **Common Issues**
#### **Firmware Won't Flash**
1. **Check USB connection** and drivers
2. **Verify COM port** selection
3. **Try different baud rates** (115200, 921600)
4. **Reset ESP32** before flashing
#### **Device Won't Connect**
1. **Verify OTA address** format and accessibility
2. **Check WebSocket address** configuration
3. **Test network connectivity** from ESP32
4. **Check firewall** settings
#### **No Audio Input/Output**
1. **Check microphone connections** (GPIO 15-17)
2. **Verify speaker connections** (GPIO 18-20)
3. **Test power supply** (3.3V, GND)
4. **Check audio component** functionality
#### **Poor Voice Recognition**
1. **Improve microphone positioning**
2. **Reduce background noise**
3. **Check audio levels** and gain
4. **Verify ASR model** configuration
### **Performance Optimization**
#### **Reduce Latency**
1. **Use faster ASR models** (WhisperASR base)
2. **Enable streaming** processing
3. **Optimize network** connection
4. **Use local AI providers**
#### **Improve Accuracy**
1. **Use larger ASR models** (WhisperASR large)
2. **Specify language** in configuration
3. **Improve audio quality**
4. **Reduce noise** in environment
## 🎯 Next Steps
### **After Firmware Setup**
1. **[Configure AI Providers](../configuration/providers.md)** - Set up your AI services
2. **[Test Voice Interaction](../features/voice-interaction.md)** - Verify everything works
3. **[Connect to Server](../getting-started/first-device.md)** - Complete device setup
4. **[Advanced Configuration](../configuration/advanced.md)** - Fine-tune settings
### **Advanced Topics**
- **[Custom Hardware](../hardware/custom.md)** - Design custom hardware
- **[Performance Optimization](../hardware/optimization.md)** - Optimize for your use case
- **[Hardware Troubleshooting](../hardware/troubleshooting.md)** - Common issues and solutions
## 🆘 Need Help?
- **Firmware Issues?** Check [Troubleshooting](../support/troubleshooting.md)
- **Hardware Questions?** See [Hardware Troubleshooting](../hardware/troubleshooting.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Firmware Compilation**
```bash
# Set target
idf.py set-target esp32s3
# Configure
idf.py menuconfig
# Build
idf.py build
# Package
cd scripts && python release.py
```
### **Pre-compiled Firmware**
1. Download from GitHub releases
2. Flash using ESP-Launchpad
3. Configure OTA address
4. Test connection
### **Key URLs**
- **OTA Interface**: http://YOUR_IP:8003/xiaozhi/ota/
- **WebSocket**: ws://YOUR_IP:8000/xiaozhi/v1/
- **ESP-Launchpad**: https://espressif.github.io/esp-launchpad/
---
**Your ESP32 firmware is ready! 🎉**
👉 **[Next: Configure AI Providers →](../configuration/providers.md)**
### **💡 Budget Options**
These boards offer good value for money:
#### **ESP32-DevKitC**
- **Chip**: ESP32 (Dual-core, 240MHz)
- **Memory**: 520KB SRAM
- **Audio**: External microphone/speaker required
- **Price**: $8-15
- **Best for**: Learning, basic projects
#### **ESP32-WROOM-32**
- **Chip**: ESP32 (Dual-core, 240MHz)
- **Memory**: 520KB SRAM
- **Audio**: External microphone/speaker required
- **Price**: $6-12
- **Best for**: Cost-sensitive projects
#### **ESP32-S2-Saola-1**
- **Chip**: ESP32-S2 (Single-core, 240MHz)
- **Memory**: 320KB SRAM
- **Audio**: External microphone/speaker required
- **Price**: $10-18
- **Best for**: Simple applications
### **🎯 Specialized Boards**
These boards offer specific features for particular use cases:
#### **ESP32-S3-BOX-Lite**
- **Chip**: ESP32-S3 (Dual-core, 240MHz)
- **Memory**: 512KB SRAM, 8MB PSRAM
- **Audio**: Built-in microphone and speaker
- **Price**: $25-35
- **Best for**: Compact voice assistant
#### **ESP32-S3-EYE**
- **Chip**: ESP32-S3 (Dual-core, 240MHz)
- **Memory**: 512KB SRAM, 8MB PSRAM
- **Audio**: Built-in microphone
- **Camera**: 2MP camera module
- **Price**: $30-40
- **Best for**: Vision + voice applications
#### **ESP32-S3-USB-OTG**
- **Chip**: ESP32-S3 (Dual-core, 240MHz)
- **Memory**: 512KB SRAM, 8MB PSRAM
- **USB**: USB OTG support
- **Price**: $20-30
- **Best for**: USB device applications
## 🔌 Hardware Requirements
### **Minimum Requirements**
| Component | Requirement | Notes |
|-----------|-------------|-------|
| **Chip** | ESP32 or ESP32-S3 | Dual-core recommended |
| **Memory** | 320KB+ SRAM | More memory = better performance |
| **Storage** | 4MB+ Flash | For firmware and audio buffers |
| **WiFi** | 802.11 b/g/n | Required for server communication |
| **Audio** | I2S interface | For microphone and speaker |
### **Recommended Specifications**
| Component | Specification | Benefits |
|-----------|---------------|----------|
| **Chip** | ESP32-S3 | Better performance, more features |
| **Memory** | 512KB+ SRAM, 8MB+ PSRAM | Smooth audio processing |
| **Storage** | 8MB+ Flash | Room for updates and features |
| **Audio** | Built-in microphone/speaker | Easier setup, better integration |
| **Display** | Optional LCD | Visual feedback and control |
## 🎤 Audio Components
### **Microphone Options**
#### **Digital MEMS Microphones**
| Model | Interface | Sensitivity | Price | Notes |
|-------|-----------|-------------|-------|-------|
| **SPH0645LM4H** | I2S | -26dBFS | $2-4 | High quality, recommended |
| **INMP441** | I2S | -26dBFS | $1-3 | Good quality, budget option |
| **ICS-43434** | I2S | -26dBFS | $3-5 | Professional grade |
#### **Analog Microphones**
| Model | Interface | Sensitivity | Price | Notes |
|-------|-----------|-------------|-------|-------|
| **MAX9814** | Analog | 60dB | $2-4 | Built-in AGC, easy to use |
| **MAX4466** | Analog | 60dB | $1-3 | Budget option |
| **ADMP401** | Analog | 60dB | $2-4 | Good quality |
### **Speaker Options**
#### **Amplifier Modules**
| Model | Power | Interface | Price | Notes |
|-------|-------|-----------|-------|-------|
| **PAM8403** | 3W | I2S | $1-2 | Stereo, good quality |
| **MAX98357A** | 3.2W | I2S | $2-4 | Mono, excellent quality |
| **TDA2822** | 1W | Analog | $1-2 | Simple, budget option |
#### **Speakers**
| Type | Power | Impedance | Price | Notes |
|------|-------|-----------|-------|-------|
| **Small Speaker** | 0.5W | 8Ω | $1-3 | Basic audio output |
| **Piezo Buzzer** | 0.1W | N/A | $0.5-1 | Simple beeps only |
| **Headphone Jack** | N/A | 32Ω | $1-2 | External audio output |
## 🔌 Pin Configurations
### **ESP32-S3 Pin Mapping**
```mermaid
graph TB
A[ESP32-S3] --> B[Audio Pins]
A --> C[Power Pins]
A --> D[GPIO Pins]
B --> E[I2S Audio]
B --> F[Analog Audio]
E --> G[WS: GPIO 15]
E --> H[BCK: GPIO 16]
E --> I[DIN: GPIO 17]
E --> J[DOUT: GPIO 18]
C --> K[3.3V Power]
C --> L[GND Ground]
C --> M[5V Input]
D --> N[GPIO 0-21]
D --> O[GPIO 26-48]
```
### **Standard Audio Pinout**
| Function | ESP32-S3 Pin | ESP32 Pin | Notes |
|----------|--------------|-----------|-------|
| **Microphone WS** | GPIO 15 | GPIO 25 | Word select |
| **Microphone BCK** | GPIO 16 | GPIO 26 | Bit clock |
| **Microphone DIN** | GPIO 17 | GPIO 27 | Data input |
| **Speaker DOUT** | GPIO 18 | GPIO 32 | Data output |
| **Speaker BCK** | GPIO 19 | GPIO 33 | Bit clock |
| **Speaker LRC** | GPIO 20 | GPIO 25 | Left/right clock |
| **Power 3.3V** | 3.3V | 3.3V | Power supply |
| **Ground** | GND | GND | Ground |
### **Alternative Pin Configurations**
#### **Custom Pin Mapping**
```yaml
# Custom pin configuration
audio:
microphone:
ws_pin: 15
bck_pin: 16
din_pin: 17
speaker:
dout_pin: 18
bck_pin: 19
lrc_pin: 20
```
## 🔧 Hardware Setup
### **Basic Audio Setup**
#### **Wiring Diagram**
```
ESP32-S3 Microphone Speaker
| | |
|-- 3.3V ----------|-- VCC |
|-- GND -----------|-- GND ------------|-- GND
|-- GPIO 15 -------|-- WS |
|-- GPIO 16 -------|-- BCK |
|-- GPIO 17 -------|-- DIN |
|-- GPIO 18 ---------------------------|-- DIN
|-- GPIO 19 ---------------------------|-- BCK
|-- GPIO 20 ---------------------------|-- LRC
```
#### **Step-by-Step Wiring**
1. **Connect Power**
- Connect 3.3V to microphone VCC
- Connect GND to microphone GND and speaker GND
2. **Connect Microphone**
- Connect GPIO 15 to microphone WS
- Connect GPIO 16 to microphone BCK
- Connect GPIO 17 to microphone DIN
3. **Connect Speaker**
- Connect GPIO 18 to speaker DIN
- Connect GPIO 19 to speaker BCK
- Connect GPIO 20 to speaker LRC
### **Advanced Audio Setup**
#### **Microphone Array**
```yaml
# Multiple microphones for better audio
microphones:
- pin: 15
gain: 1.0
- pin: 21
gain: 1.0
- pin: 22
gain: 1.0
```
#### **Stereo Audio**
```yaml
# Stereo speaker configuration
speakers:
left:
pin: 18
channel: 0
right:
pin: 19
channel: 1
```
## 🧪 Hardware Testing
### **Audio Component Testing**
#### **Microphone Test**
```python
# Test microphone functionality
import machine
import time
# Configure I2S for microphone
i2s = machine.I2S(
machine.I2S.MASTER,
sck=machine.Pin(16),
ws=machine.Pin(15),
sd=machine.Pin(17),
mode=machine.I2S.RX,
bits=16,
format=machine.I2S.MONO,
rate=16000,
ibuf=40000
)
# Read audio data
audio_data = i2s.read(1000)
print(f"Audio data length: {len(audio_data)}")
```
#### **Speaker Test**
```python
# Test speaker functionality
import machine
import time
# Configure I2S for speaker
i2s = machine.I2S(
machine.I2S.MASTER,
sck=machine.Pin(19),
ws=machine.Pin(20),
sd=machine.Pin(18),
mode=machine.I2S.TX,
bits=16,
format=machine.I2S.MONO,
rate=16000,
ibuf=40000
)
# Generate test tone
import math
samples = []
for i in range(16000):
samples.append(int(32767 * math.sin(2 * math.pi * 440 * i / 16000)))
# Play test tone
i2s.write(bytes(samples))
```
### **Power Consumption Testing**
#### **Current Measurement**
```python
# Measure power consumption
import machine
import time
# Enable power monitoring
machine.freq(240000000) # Set CPU frequency
# Measure current during different operations
# Idle: ~50mA
# WiFi active: ~80mA
# Audio processing: ~120mA
# Peak usage: ~200mA
```
## 🔧 Troubleshooting
### **Common Hardware Issues**
#### **No Audio Input**
1. **Check microphone connections**
2. **Verify power supply** (3.3V)
3. **Test microphone** with multimeter
4. **Check I2S configuration**
#### **No Audio Output**
1. **Check speaker connections**
2. **Verify amplifier power**
3. **Test speaker** with multimeter
4. **Check I2S configuration**
#### **Poor Audio Quality**
1. **Check power supply** stability
2. **Verify ground connections**
3. **Test with different components**
4. **Adjust gain settings**
#### **Device Won't Boot**
1. **Check power supply** (5V input)
2. **Verify USB connection**
3. **Check for short circuits**
4. **Test with minimal configuration**
### **Performance Issues**
#### **Audio Dropouts**
1. **Increase buffer sizes**
2. **Optimize WiFi settings**
3. **Check power supply**
4. **Reduce CPU load**
#### **High Latency**
1. **Optimize audio buffers**
2. **Check network latency**
3. **Reduce processing overhead**
4. **Use faster components**
## 🎯 Device Selection Guide
### **For Beginners**
- **ESP32-S3-BOX** - Complete solution with built-in audio
- **ESP32-S3-DevKitC-1** - Good for learning with external components
### **For Developers**
- **ESP32-S3-DevKitC-1** - Maximum flexibility
- **ESP32-S3-Korvo-2** - Audio-focused development
### **For Production**
- **ESP32-S3-BOX-3** - Production-ready with all features
- **ESP32-S3-BOX-Lite** - Cost-effective production option
### **For Specialized Applications**
- **ESP32-S3-EYE** - Vision + voice applications
- **ESP32-S3-USB-OTG** - USB device applications
## 🎯 Next Steps
### **After Hardware Selection**
1. **[Firmware Compilation](../hardware/firmware.md)** - Build firmware for your device
2. **[Device Flashing](../hardware/flashing.md)** - Flash firmware to your device
3. **[Hardware Testing](../hardware/troubleshooting.md)** - Test your hardware setup
4. **[Connect to Server](../getting-started/first-device.md)** - Connect to Xiaozhi server
### **Advanced Topics**
- **[Custom Hardware](../hardware/custom.md)** - Design custom hardware
- **[Performance Optimization](../hardware/optimization.md)** - Optimize for your use case
- **[Hardware Troubleshooting](../hardware/troubleshooting.md)** - Common issues and solutions
## 🆘 Need Help?
- **Hardware Questions?** Check [Hardware Troubleshooting](../hardware/troubleshooting.md)
- **Firmware Issues?** See [Firmware Guide](../hardware/firmware.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Recommended Boards**
- **Complete Solution**: ESP32-S3-BOX-3
- **Development**: ESP32-S3-DevKitC-1
- **Budget**: ESP32-S3-BOX-Lite
### **Audio Components**
- **Microphone**: SPH0645LM4H (I2S)
- **Amplifier**: MAX98357A (I2S)
- **Speaker**: Small 8Ω speaker
### **Pin Connections**
- **Microphone**: GPIO 15-17
- **Speaker**: GPIO 18-20
- **Power**: 3.3V, GND
---
**Choose the right ESP32 device for your project! 🎉**
👉 **[Next: Firmware Compilation →](../hardware/firmware.md)**

View file

@ -0,0 +1,559 @@
# 🔧 Hardware Troubleshooting
This guide helps you diagnose and fix common hardware issues with ESP32 devices and Xiaozhi ESP32 Server.
## 🎯 Troubleshooting Overview
This guide covers:
- **Device connection** issues
- **Audio problems** (microphone/speaker)
- **Power and stability** issues
- **Network connectivity** problems
- **Performance optimization** tips
## 🔌 Device Connection Issues
### **Device Not Detected**
#### **Symptoms**
- Device not showing up in Device Manager
- "Port not found" errors
- No response from flashing tools
#### **Solutions**
**1. Check USB Connection**
```bash
# Windows: Check Device Manager
# Look for "Silicon Labs CP210x" or similar
# Mac: Check system information
system_profiler SPUSBDataType
# Linux: Check USB devices
lsusb
```
**2. Install USB Drivers**
- **Windows**: Download CP210x drivers from Silicon Labs
- **Mac**: Usually automatic, may need Xcode Command Line Tools
- **Linux**: Add user to dialout group
```bash
sudo usermod -a -G dialout $USER
# Log out and back in
```
**3. Try Different USB Ports**
- Use **USB 2.0 ports** (more stable than USB 3.0)
- Avoid **USB hubs** (use direct connection)
- Try **different cables** (ensure data cable, not charging cable)
**4. Reset Device**
```bash
# Hold BOOT button, press RESET, release RESET, release BOOT
# This puts device in download mode
```
### **Flashing Failures**
#### **Symptoms**
- "Failed to connect" errors
- "Flash write error" messages
- Verification failures
#### **Solutions**
**1. Use Correct Baud Rate**
```bash
# Try different baud rates
esptool.py --chip esp32s3 --port COM3 --baud 115200 write_flash 0x0 firmware.bin
esptool.py --chip esp32s3 --port COM3 --baud 460800 write_flash 0x0 firmware.bin
esptool.py --chip esp32s3 --port COM3 --baud 921600 write_flash 0x0 firmware.bin
```
**2. Try Different Flash Modes**
```bash
# Try different flash modes
esptool.py --chip esp32s3 --port COM3 --flash_mode dio write_flash 0x0 firmware.bin
esptool.py --chip esp32s3 --port COM3 --flash_mode qio write_flash 0x0 firmware.bin
```
**3. Erase Flash First**
```bash
# Erase entire flash
esptool.py --chip esp32s3 --port COM3 erase_flash
# Then flash normally
esptool.py --chip esp32s3 --port COM3 write_flash 0x0 firmware.bin
```
**4. Use Web-based Flashing**
- Navigate to: https://espressif.github.io/esp-launchpad/
- Often more reliable than command line tools
## 🎤 Audio Issues
### **No Audio Input (Microphone)**
#### **Symptoms**
- Device not responding to wake word
- No audio detected in server logs
- "No audio input" errors
#### **Solutions**
**1. Check Microphone Connections**
```
ESP32-S3 Pinout:
- GPIO 15: Microphone WS (Word Select)
- GPIO 16: Microphone BCK (Bit Clock)
- GPIO 17: Microphone DIN (Data Input)
- 3.3V: Power supply
- GND: Ground
```
**2. Verify Microphone Type**
- **I2S Microphones**: SPH0645LM4H, INMP441, ICS-43434
- **Analog Microphones**: MAX9814, MAX4466, ADMP401
- **Check datasheet** for correct pin connections
**3. Test Microphone Functionality**
```bash
# Check if microphone is detected
# Look for I2S initialization in device logs
```
**4. Adjust Audio Settings**
```yaml
# In configuration file
audio:
sample_rate: 16000
channels: 1
bit_depth: 16
buffer_size: 4096
gain: 1.0 # Adjust if audio is too quiet/loud
```
### **No Audio Output (Speaker)**
#### **Symptoms**
- No sound from device
- TTS responses not audible
- "Audio output failed" errors
#### **Solutions**
**1. Check Speaker Connections**
```
ESP32-S3 Pinout:
- GPIO 18: Speaker DOUT (Data Output)
- GPIO 19: Speaker BCK (Bit Clock)
- GPIO 20: Speaker LRC (Left/Right Clock)
- 3.3V: Power supply
- GND: Ground
```
**2. Verify Speaker Type**
- **I2S Speakers**: MAX98357A, PCM5102A
- **Analog Speakers**: Use amplifier (PAM8403, TDA2822)
- **Check power requirements** (3.3V, 5V, or external power)
**3. Test Speaker Functionality**
```bash
# Check if speaker is detected
# Look for I2S output initialization in device logs
```
**4. Adjust Audio Settings**
```yaml
# In configuration file
TTS:
EdgeTTS:
type: edge
voice: en-US-AriaNeural
rate: 1.0
volume: 1.0 # Adjust volume level
output_dir: tmp/
```
### **Poor Audio Quality**
#### **Symptoms**
- Distorted audio
- Low volume
- Background noise
- Echo or feedback
#### **Solutions**
**1. Improve Audio Quality**
```yaml
# Optimize audio settings
audio:
sample_rate: 44100 # Higher sample rate for better quality
bit_depth: 24 # Higher bit depth
buffer_size: 8192 # Larger buffer for stability
gain: 0.8 # Reduce gain to prevent distortion
```
**2. Reduce Background Noise**
- **Position microphone** away from speaker
- **Use directional microphone** (cardioid pattern)
- **Add acoustic foam** around device
- **Reduce ambient noise** in environment
**3. Fix Echo/Feedback**
- **Increase distance** between microphone and speaker
- **Use echo cancellation** in audio processing
- **Adjust VAD settings** to prevent feedback loops
## ⚡ Power and Stability Issues
### **Device Crashes or Reboots**
#### **Symptoms**
- Device randomly restarts
- "Brownout" errors in logs
- Unstable operation
#### **Solutions**
**1. Check Power Supply**
- **Use stable 5V supply** (not USB power from computer)
- **Check current capacity** (ESP32-S3 needs ~500mA)
- **Use quality USB cable** with proper gauge wires
- **Add capacitors** for power smoothing
**2. Monitor Power Consumption**
```bash
# Check power consumption
# ESP32-S3: ~240mA active, ~10mA sleep
# Add components: microphone (~1mA), speaker (~100mA)
```
**3. Optimize Power Settings**
```yaml
# In configuration file
power:
cpu_freq: 240 # MHz (80, 160, 240)
sleep_mode: light_sleep # light_sleep, deep_sleep
wifi_power_save: true
```
### **WiFi Connection Issues**
#### **Symptoms**
- Device can't connect to WiFi
- Frequent disconnections
- "WiFi connection failed" errors
#### **Solutions**
**1. Check WiFi Settings**
```yaml
# In configuration file
wifi:
ssid: "YourWiFiNetwork"
password: "YourWiFiPassword"
# Use 2.4GHz band (ESP32 doesn't support 5GHz)
```
**2. Improve Signal Strength**
- **Position device** closer to router
- **Use WiFi extender** if needed
- **Check for interference** (microwaves, Bluetooth devices)
- **Use 2.4GHz band** (ESP32 doesn't support 5GHz)
**3. Debug WiFi Connection**
```bash
# Check WiFi status in device logs
# Look for connection attempts and failures
```
## 🌐 Network Connectivity Issues
### **Can't Connect to Server**
#### **Symptoms**
- Device connects to WiFi but not to server
- "Server connection failed" errors
- No communication with Xiaozhi server
#### **Solutions**
**1. Check Server Configuration**
```yaml
# In configuration file
server:
websocket: ws://YOUR_IP:8000/xiaozhi/v1/
ota: http://YOUR_IP:8003/xiaozhi/ota/
```
**2. Verify Network Connectivity**
```bash
# Test from device (if possible)
ping YOUR_SERVER_IP
# Test from server
ping DEVICE_IP
```
**3. Check Firewall Settings**
- **Allow ports** 8000 (WebSocket) and 8003 (OTA)
- **Check NAT settings** if using router
- **Verify IP addresses** are correct
**4. Test OTA Interface**
- **Open OTA URL**: `http://YOUR_IP:8003/xiaozhi/ota/`
- **Should show**: "OTA interface is running normally"
- **If not working**: Check server configuration
### **4G Mode Connection Issues**
#### **Symptoms**
- Works on WiFi but not on 4G
- "Secure connection required" errors
- Can't connect via mobile data
#### **Solutions**
**1. Enable HTTPS/WSS**
```yaml
# In configuration file
server:
websocket: wss://YOUR_DOMAIN:8000/xiaozhi/v1/ # Note: wss://
ota: https://YOUR_DOMAIN:8003/xiaozhi/ota/ # Note: https://
```
**2. Configure SSL Certificates**
```yaml
# SSL configuration
ssl:
enabled: true
cert_file: /path/to/cert.pem
key_file: /path/to/key.pem
```
**3. Use Domain Name**
- **ESP32 firmware** requires secure connections for 4G
- **Use domain name** instead of IP address
- **Configure DNS** properly
## 🚀 Performance Optimization
### **Slow Response Times**
#### **Symptoms**
- Long delays between speech and response
- "Processing timeout" errors
- Poor user experience
#### **Solutions**
**1. Optimize AI Models**
```yaml
# Use faster models
ASR:
WhisperASR:
model_name: tiny # Instead of base/small/medium/large
device: cuda # Use GPU if available
LLM:
LMStudioLLM:
model_name: llama-3.1:8b # Smaller model
context_length: 2048 # Smaller context window
```
**2. Enable Streaming**
```yaml
# Enable streaming for faster responses
streaming:
enabled: true
buffer_size: 1024
chunk_size: 512
```
**3. Optimize Network**
- **Use local AI providers** (LMStudio, WhisperASR)
- **Reduce network latency** (local server)
- **Optimize WiFi connection** (strong signal)
### **High Memory Usage**
#### **Symptoms**
- Device running out of memory
- "Memory allocation failed" errors
- Crashes due to memory issues
#### **Solutions**
**1. Reduce Memory Usage**
```yaml
# Optimize memory settings
memory:
mem_local_short:
max_messages: 10 # Reduce from default 20
max_age_hours: 12 # Reduce from default 24
# Reduce audio buffer sizes
audio:
buffer_size: 2048 # Reduce from default 4096
chunk_size: 512 # Reduce from default 1024
```
**2. Use Smaller Models**
```yaml
# Use smaller AI models
ASR:
WhisperASR:
model_name: tiny # 39MB instead of 142MB (base)
LLM:
LMStudioLLM:
model_name: llama-3.1:8b # Smaller context window
context_length: 1024 # Reduce from default 4096
```
## 🔍 Diagnostic Tools
### **Device Status Check**
```bash
# Check device information
esptool.py --chip esp32s3 --port COM3 chip_id
esptool.py --chip esp32s3 --port COM3 flash_id
# Monitor serial output
esptool.py --chip esp32s3 --port COM3 monitor
```
### **Network Diagnostics**
```bash
# Test network connectivity
ping YOUR_SERVER_IP
telnet YOUR_SERVER_IP 8000
curl http://YOUR_SERVER_IP:8003/xiaozhi/ota/
```
### **Audio Testing**
```bash
# Test microphone (if supported)
# Look for I2S initialization messages in logs
# Test speaker (if supported)
# Look for audio output messages in logs
```
## 📊 Performance Monitoring
### **Monitor Device Performance**
```yaml
# Enable performance monitoring
monitoring:
enabled: true
metrics:
response_time: true
memory_usage: true
cpu_usage: true
audio_processing_time: true
# Log performance data
logging:
level: INFO
performance_logs: true
```
### **Common Performance Metrics**
| Metric | Good | Warning | Critical |
|--------|------|---------|----------|
| **Response Time** | < 2s | 2-5s | > 5s |
| **Memory Usage** | < 70% | 70-90% | > 90% |
| **CPU Usage** | < 80% | 80-95% | > 95% |
| **Audio Latency** | < 100ms | 100-300ms | > 300ms |
## 🛠️ Advanced Troubleshooting
### **Firmware Issues**
#### **Corrupted Firmware**
```bash
# Erase and reflash
esptool.py --chip esp32s3 --port COM3 erase_flash
esptool.py --chip esp32s3 --port COM3 write_flash 0x0 firmware.bin
```
#### **Boot Loop Issues**
```bash
# Check boot logs
esptool.py --chip esp32s3 --port COM3 monitor
# Look for boot errors and stack traces
```
### **Hardware Debugging**
#### **Use Oscilloscope**
- **Check clock signals** (I2S BCK, WS)
- **Verify data signals** (I2S DIN, DOUT)
- **Monitor power supply** stability
#### **Use Logic Analyzer**
- **Capture I2S communication**
- **Verify protocol compliance**
- **Check timing requirements**
## 🎯 Next Steps
After resolving hardware issues:
1. **[Test Voice Interaction](../features/voice-interaction.md)** - Verify functionality
2. **[Configure AI Providers](../configuration/providers.md)** - Set up AI services
3. **[Performance Optimization](../guides/performance.md)** - Optimize for your use case
4. **[Advanced Configuration](../configuration/advanced.md)** - Fine-tune settings
## 🆘 Need Help?
- **Hardware Issues?** Check [Supported Devices](supported-devices.md)
- **Flashing Problems?** See [Device Flashing](flashing.md)
- **General Questions?** Browse [FAQ](../support/faq.md)
---
## 🎯 Quick Reference
### **Common Issues**
- **Device not detected**: Check USB drivers and connections
- **No audio**: Verify microphone/speaker connections
- **WiFi issues**: Check 2.4GHz network and signal strength
- **Performance**: Use smaller models and enable streaming
### **Diagnostic Commands**
```bash
# Check device
esptool.py --chip esp32s3 --port COM3 chip_id
# Monitor logs
esptool.py --chip esp32s3 --port COM3 monitor
# Test network
ping YOUR_SERVER_IP
curl http://YOUR_SERVER_IP:8003/xiaozhi/ota/
```
### **Emergency Recovery**
```bash
# Erase and reflash
esptool.py --chip esp32s3 --port COM3 erase_flash
esptool.py --chip esp32s3 --port COM3 write_flash 0x0 firmware.bin
```
---
**Your hardware troubleshooting guide is ready! 🎉**
👉 **[Next: Test Voice Interaction →](../features/voice-interaction.md)**

View file

@ -1,226 +0,0 @@
# 小智ESP32-开源服务端与HomeAssistant集成指南
[TOC]
-----
## 简介
本文档将指导您如何将ESP32设备与HomeAssistant进行集成。
## 前提条件
- 已安装并配置好`HomeAssistant`
- 本次我选择的模型是:免费的ChatGLM,它支持functioncall函数调用
## 开始前的操作(必要)
### 1. 获取HA的网络网络地址信息
请访问你Home Assistant的网络地址,例如,我的HA的地址是192.168.4.7,端口则是默认的8123,则在浏览器打开
```
http://192.168.4.7:8123
```
> 手动查询 HA 的 IP 地址方法**(仅限小智esp32-server和HA部署在同一个网络设备[例如同一个wifi]下)**:
>
> 1. 进入 Home Assistant(前端)。
>
> 2. 点击左下角 **设置(Settings)** → **系统(System)** → **网络(Network)**。
>
> 3. 滑到最底部`Home Assistant 网址(Home Assistant website)`区域,在`本地网络(local network)`中,点击`眼睛`按钮,可以看到当前使用的 IP 地址(如 `192.168.1.10`)和网络接口。点击`复制连接(copy link)`可以直接复制。
>
> ![image-20250504051716417](images/image-ha-integration-01.png)
或,您已经设置了直接可以访问的Home Assistant的OAuth地址,您也可以在浏览器内直接访问
```
http://homeassistant.local:8123
```
### 2. 登录`Home Assistant`拿到开发密钥
登录`HomeAssistant`,点击`左下角头像 -> 个人`,切换`安全`导航栏,划到底部`长期访问令牌`生成api_key,并复制保存,后续的方法都需要使用这个api key且仅出现一次(小tips: 您可以保存生成的二维码图像,后续可以扫描二维码再此提取api key)。
## 方法1:小智社区共建的HA调用功能
### 功能描述
- 如您后续需要增加新的设备,该方法需要手动重启`xiaozhi-esp32-server服务端`以此更新设备信息**(重要**)。
- 需要您确保已经在HomeAssistant中集成`Xiaomi Home`,并将米家的设备导入进`HomeAssistant`。
- 需要您确保`xiaozhi-esp32-server智控台`能正常使用。
- 我的`xiaozhi-esp32-server智控台`和`HomeAssistant`部署在同一台机器的另一个端口,版本是`0.3.10`
```
http://192.168.4.7:8002
```
### 配置步骤
#### 1. 登录`HomeAssistant`整理需要控制的设备清单
登录`HomeAssistant`,点击`左下角的设置`,然后进入`设备与服务`,再点击顶部的`实体`。
然后在实体中搜索你相关控制的开关,结果出来后,在列表中,点击其中一个结果,这是会出现一个开关的界面。
在开关的界面,我们尝试点击开关,看看是开发会随着我们的点击开/关。如果能操作,说明是正常联网的。
接着在开关面板找到设置按钮,点击后,可以查看这个开关的`实体标识符`。
我们打开一个记事本,按照这样格式整理一条数据:
位置+英文逗号+设备名称+英文逗号+`实体标识符`+英文分号
例如,我在公司,我有一个玩具灯,他的标识符是switch.cuco_cn_460494544_cp1_on_p_2_1,那么就这个写这一条数据
```
公司,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;
```
当然最后我可能要操作两个灯,我的最终的结果是:
```
公司,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;
公司,台灯,switch.iot_cn_831898993_socn1_on_p_2_1;
```
这段字符,我们称为“设备清单字符”需要保存好,等一下有用。
#### 2. 登录`智控台`
![image-20250504051716417](images/image-ha-integration-06.png)
使用管理员账号,登录`智控台`。在`智能体管理`,找到你的智能体,再点击`配置角色`。
将意图识别设置成`外挂的大模型意图识别`或`大模型自主函数调用`。这时你会看到右侧有一个`编辑功能`。点击`编辑功能`按钮,会弹出`功能管理`的框。
在`功能管理`的框里,你需要勾选`HomeAssistant设备状态查询`和`HomeAssistant设备状态修改`。
勾选后,在`已选功能`点击`HomeAssistant设备状态查询`,然后在`参数配置`里配置你的`HomeAssistant`地址、密钥、设备清单字符。
编辑好后,点击`保存配置`,这时`功能管理`的框会隐藏,这时你再点击保存智能体配置。
保存成功后,即可唤醒设备操作。
#### 3. 唤醒设别进行控制
尝试和esp32说,“打开XXX灯”
## 方法2:小智将Home Assistant的语音助手作为LLM工具
### 功能描述
- 该方法有一个比较严重的缺点——**该方法无法使用小智开源生态的function_call插件功能的能力**,因为使用Home Assistant作为小智的LLM工具会将意图识别能力转让给Home Assistant。但是**这个方法是能体验到原生的Home Assistant操作功能,且小智的聊天能力不变**。如实在介意可以使用同样是Home Assistant支持的[方法3](##方法3:使用Home Assistant的MCP服务(推荐)),能够最大程度体验到Home Assistant的功能。
### 配置步骤:
#### 1. 配置Home Assistant的大模型语音助手。
**需要您提前配置好Home Assistant的语音助手或大模型工具。**
#### 2. 获取Home Assistant的语言助手的Agent ID.
1. 进入Home Assistant页面内。左侧点击`开发者助手`。
2. 在打开的`开发者助手`内,点击`动作`选项卡(如图示操作1),在页面内的选项栏`动作`中,找到或输入`conversation.process(对话-处理)`并选择`对话(conversation): 处理`(如图示操作2)。
![image-20250504043539343](images/image-ha-integration-02.png)
3. 在页面内勾选`代理(agent)`选项,在变成常亮的`对话代理(conversation agent)`内选择您步骤一配置好的语音助手名称,如图示,我这边配置好的是`ZhipuAi`并选择。
![image-20250504043854760](images/image-ha-integration-03.png)
4. 选中后,点击表单左下方的`进入YAML模式`。
![image-20250504043951126](images/image-ha-integration-04.png)
5. 复制其中的agent-id的值,例如图示中我的是`01JP2DYMBDF7F4ZA2DMCF2AGX2`(仅供参考)。
![image-20250504044046466](images/image-ha-integration-05.png)
6. 切换到小智开源服务端`xiaozhi-esp32-server`的`config.yaml`文件内,在LLM配置中,找到Home Assistant,设置您的Home Assistant的网络地址,Api key和刚刚查询到的agent_id。
7. 修改`config.yaml`文件内的`selected_module`属性的`LLM`为`HomeAssistant`,`Intent`为`nointent`。
8. 重启小智开源服务端`xiaozhi-esp32-server`即可正常使用。
## 方法3:使用Home Assistant的MCP服务(推荐)
### 功能描述
- 需要您提前在Home Assistant内集成并安装好HA集成——[Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/)。
- 这个方法与方法2都是HA官方提供的解决方法,与方法2不同的是,您可以正常使用小智开源服务端`xiaozhi-esp32-server`的开源共建的插件,同时允许您随意使用任何一个支持function_call功能的LLM大模型。
### 配置步骤
#### 1. 安装Home Assistant的MCP服务集成。
集成官方网址——[Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/)。。
或跟随以下手动操作。
> - 前往Home Assistant页面的**[设置 > 设备和服务(Settings > Devices & Services.)](https://my.home-assistant.io/redirect/integrations)**。
>
> - 在右下角,选择 **[添加集成(Add Integration)](https://my.home-assistant.io/redirect/config_flow_start?domain=mcp_server)**按钮。
>
> - 从列表中选择**模型上下文协议服务器(Model Context Protocol Server)**。
>
> - 按照屏幕上的说明完成设置。
#### 2. 配置小智开源服务端MCP配置信息
进入`data`目录,找到`.mcp_server_settings.json`文件。
如果你的`data`目录下没有`.mcp_server_settings.json`文件,
- 请把在`xiaozhi-server`文件夹根目录的`mcp_server_settings.json`文件复制到`data`目录下,并重命名为`.mcp_server_settings.json`
- 或[下载这个文件](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/main/xiaozhi-server/mcp_server_settings.json),下载到`data`目录下,并重命名为`.mcp_server_settings.json`
修改`"mcpServers"`里的这部分的内容:
```json
"Home Assistant": {
"command": "mcp-proxy",
"args": [
"http://YOUR_HA_HOST/mcp_server/sse"
],
"env": {
"API_ACCESS_TOKEN": "YOUR_API_ACCESS_TOKEN"
}
},
```
注意:
1. **替换配置:**
- 替换`args`内的`YOUR_HA_HOST`为您的HA服务地址,如果你的服务地址已经包含了https/http字样(例如`http://192.168.1.101:8123`),则只需要填入`192.168.1.101:8123`即可。
- 将`env`内`API_ACCESS_TOKEN`的`YOUR_API_ACCESS_TOKEN`替换成您之前获取到的开发密钥api key。
2. **如果你添加配置是在`"mcpServers"`的括号内后续没有新的`mcpServers`的配置时,需要把最后的逗号`,`移除**,否则可能会解析失败。
**最后效果参考以下(参考如下)**:
```json
"mcpServers": {
"Home Assistant": {
"command": "mcp-proxy",
"args": [
"http://192.168.1.101:8123/mcp_server/sse"
],
"env": {
"API_ACCESS_TOKEN": "abcd.efghi.jkl"
}
}
}
```
#### 3. 配置小智开源服务端的系统配置
1. **选择任意一款支持function_call的LLM大模型作为小智的LLM聊天助手(但不要选择Home Assistant作为LLM工具)**,本次我选择的模型是:免费的ChatGLM,它支持functioncall函数调用,但部分时候调用不太稳定,如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-1-5-pro-32k-250115。
2. 切换到小智开源服务端`xiaozhi-esp32-server`的`config.yaml`文件内,设置您的LLM大模型配置,并且将`selected_module`配置的`Intent`调整为`function_call`。
3. 重启小智开源服务端`xiaozhi-esp32-server`即可正常使用。

View file

@ -1,58 +0,0 @@
# 智控台 火山双流式语音合成+音色克隆配置教程
本教程分为4个阶段:准备阶段、配置阶段、克隆阶段、使用阶段。主要是介绍通过智控台配置火山双流式语音合成+音色克隆的过程。
## 第一阶段:准备阶段
超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火上引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。
如果你想克隆多个音色,需要购买开通多个音色资源。只要把每个音色资源的声音ID(S_xxxxx)复制到本项目。然后分配给系统的账号使用即可。以下是详细步骤:
### 1.开通火山引擎服务
访问 https://console.volcengine.com/speech/app 在应用管理创建应用,勾选语音合成大模型和声音复刻大模型。
### 2.获取音色资源ID
访问 https://console.volcengine.com/speech/service/9999 复制三项内容,分别是App Id,Access Token以及声音ID(S_xxxxx)。如图
![获取音色资源](images/image-clone-integration-01.png)
## 第二阶段:配置火山引擎服务
### 1.填写火山引擎配置
使用超级管理员账号登录智控台,点击顶部【模型配置】,再点击模型配置页面左侧的【语音合成】,搜索找到“火山双流式语音合成”,点击修改,将你火山引擎的`App Id`填入到【应用ID】字段里,将`Access Token`填入到【访问令牌】字段里。然后保存。
### 2.将音色资源ID分配给系统账号
使用超级管理员账号登录智控台,点击顶部`参数字典`,在下拉菜单中,点击`系统功能配置`页面。在页面上勾选`音色克隆`,点击保存配置。即可在顶部菜单看到`音色克隆`按钮。
使用超级管理员账号登录智控台,点击顶部【音色克隆】、【音色资源】。
点击新增按钮,在【平台名称】选择“火山双流式语音合成”;
在【音色资源ID】填入你火山引擎的声音资源ID(S_xxxxx),填入后按回车;
在【归属账号】选择你要分配给的系统账号,你可以分配给你自己。然后点击保存
## 第三阶段:克隆阶段
如果登录后,点击顶部【音色克隆】》【音色克隆】,显示【您的账号暂无音色资源请联系管理员分配音色资源】,说明你在第二阶段还没有把音色资源ID分配给这个账号。那就是回到第二阶段,分配音色资源给对应的账号。
如果登录后,点击顶部【音色克隆】》【音色克隆】,能看到对应的音色列表。请继续。
在列表里会看到对应的音色列表。选择其中一个音色资源,点击【上传音频】按钮。上传后,可以试听一下声音或者截取某段声音。确认后点击【上传音频】按钮。
![上传音频](images/image-clone-integration-02.png)
上传音频后,在列表里会看到对应的音色会变成“待复刻”状态。点击【立即复刻】按钮。等1~2秒会返回结果。
如果复刻失败,请将鼠标放到“错误信息”图标上,会显示失败的原因。
如果复刻成功,在列表里会看到对应的音色会变成“训练成功”状态。此时你可以点击【声音名称】栏的修改按钮,修改音色资源的名称,方便后期选择使用。
## 第四阶段:使用阶段
点击顶部【智能体管理】,选择任意一个智能体,点击【配置角色】按钮。
语音合成(TTS)选择“火山双流式语音合成”。在列表里,找到名字带有“克隆音色”的音色资源(如图),选择它,点击保存。
![选择音色](images/image-clone-integration-03.png)
接下来,可以唤醒小智和它对话。

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 781 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 588 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 518 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 359 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 338 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 429 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

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