diff --git a/.gitignore b/.gitignore index 985ec651d..0a684e6ac 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,7 @@ docs/_build/ # PyBuilder .pybuilder/ target/ +*.pid # Jupyter Notebook .ipynb_checkpoints diff --git a/README.md b/README.md index 191790bcf..c3bb8ee2a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,28 @@ -[![SVG Banners](https://svg-banners.vercel.app/api?type=origin&text1=你好😃,小智📟&text2=开源小智ESP-32后端服务&width=830&height=210)](https://github.com/xinnan-tech/xiaozhi-esp32-server) +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + + +

小智后端服务xiaozhi-esp32-server

+

+本项目为开源智能硬件项目 +xiaozhi-esp32提供后端服务
+根据小智通信协议使用Python实现
+帮助您快速搭建小智服务器 +

+ +

+English +· 简体中文 +· 更新日志 +· 部署文档 +· 反馈问题 +

+

+ + GitHub Contributors + - GitHub Contributors + GitHub Contributors Issues @@ -9,15 +30,14 @@ GitHub pull requests + + GitHub pull requests + + + stars +

-# 小智 ESP-32 后端服务(xiaozhi-esp32-server) - -(中文 | [English](README_en.md)) - -本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) -提供后端服务。根据 [小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) 使用 `Python` 实现。 - --- ## 适用人群 👥 @@ -108,20 +128,8 @@ ## 系统要求与部署前提 🖥️ -- **硬件**:一套兼容 `xiaozhi-esp32` - 的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。 - - **电脑或服务器**:建议 4 核 CPU、8G 内存的电脑。如果开启ASR也使用API,可运行在2核CPU、2G内存的服务器中。 -- **固件编译**:请将本后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译`xiaozhi-esp32`固件并烧录到设备上。 - -![图片](docs/images/deploy.png) - -如果你没有esp32相关的硬件设备,但是非常想体验该项目,可以使用以下的项目让你的电脑、手机模拟成esp32设备。 - -- [小智安卓端](https://github.com/TOM88812/xiaozhi-android-client) -- [小智电脑端](https://github.com/Huang-junsen/py-xiaozhi) - -如果你是一名软件开发者,这里有一份[《致开发者的公开信》](docs/contributor_open_letter.md),欢迎加入! +- **修改客户端接口**:请将本后端服务的接口地址更新至 客户端中。 --- @@ -144,115 +152,7 @@ server: --- -## 功能清单 ✨ - -### 已实现 ✅ - -- **通信协议** - 基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。 -- **对话交互** - 支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠 -- **意图识别** - 支持使用LLM意图识别、function call函数调用,减少硬编码意图判断 -- **多语言识别** - 支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。 -- **LLM 模块** - 支持灵活切换 LLM 模块,默认使用 ChatGLMLLM,也可选用阿里百炼、DeepSeek、Ollama 等接口。 -- **TTS 模块** - 支持 EdgeTTS(默认)、火山引擎豆包 TTS 等多种 TTS 接口,满足语音合成需求。 -- **记忆功能** - 支持超长记忆、本地总结记忆、无记忆三种模式,满足不同场景需求。 -- **IOT功能** - 支持管理注册设备IOT功能,支持基于对话上下文语境下的智能物联网控制。 - -### 正在开发 🚧 - -- 多种心情模式 -- 智控台webui - -想了解具体开发进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3) - -![图片](docs/images/webui.png) ---- - -## 本项目支持的平台/组件列表 📋 - -### LLM 语言模型 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:------------------:|:---------------------:|:-----------:|:-----------------------------------------------------------------------------------------------------------------------:| -| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) | -| LLM | DoubaoLLM | openai 接口调用 | 消耗 token | [点击申请密钥](https://console.volcengine.com/ark/region:ark+cn-beijing/model/detail?Id=doubao-pro-32k&projectName=undefined) | -| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) | -| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| LLM | OllamaLLM | ollama 接口调用 | 免费/消耗 token | 需预先下载模型(`ollama pull`),服务地址:`http://localhost:11434` | -| LLM | DifyLLM | dify 接口调用 | 免费/消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 | -| LLM | FastgptLLM | fastgpt 接口调用 | 免费/消耗 token | 本地化部署,注意配置提示词需在 Fastgpt 控制台设置 | -| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) | -| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 | - -实际上,任何支持 openai 接口调用的 LLM 均可接入使用。 - ---- - -### TTS 语音合成 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:----------------------:|:----:|:--------:|:-------------------------------------------------------------------------:| -| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 | -| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 | -| TTS | AliyunTTS | 接口调用 | 消耗 token | [点击创建密钥](https://nls-portal.console.aliyun.com/applist) | -| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav | -| TTS | TTS302AI | 接口调用 | 消耗 token | [点击创建密钥](https://dash.302.ai/apis/list) | -| TTS | CozeCnTTS | 接口调用 | 消耗 token | 需提供 Coze API key;输出格式为 wav | -| TTS | GizwitsTTS | 接口调用 | 消耗 token | [点击创建密钥](https://agentrouter.gizwitsapi.com) | -| TTS | ACGNTTS | 接口调用 | 消耗 token | [联系网站管理员购买密钥](www.ttson.cn) | -| TTS | OpenAITTS | 接口调用 | 消耗 token | 境外使用,境外购买 | -| TTS | FishSpeech | 接口调用 | 免费/自定义 | 本地启动 TTS 服务;启动方法见配置文件内说明 | -| TTS | GPT_SOVITS_V2 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | -| TTS | GPT_SOVITS_V3 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | -| TTS | MinimaxTTS | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | - ---- - -### VAD 语音活动检测 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:---------:|:----:|:----:|:--:| -| VAD | SileroVAD | 本地使用 | 免费 | | - ---- - -### ASR 语音识别 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:---------:|:----:|:----:|:--:| -| ASR | FunASR | 本地使用 | 免费 | | -| ASR | SherpaASR | 本地使用 | 免费 | | -| ASR | DoubaoASR | 接口调用 | 收费 | | - - ---- - -### Memory 记忆存储 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:------:|:---------------:|:----:|:---------:|:--:| -| Memory | mem0ai | 接口调用 | 1000次/月额度 | | -| Memory | mem_local_short | 本地总结 | 免费 | | - ---- - -### Intent 意图识别 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:------:|:-------------:|:----:|:-------:|:---------------------:| -| Intent | intent_llm | 接口调用 | 根据LLM收费 | 通过大模型识别意图,通用性强 | -| Intent | function_call | 接口调用 | 根据LLM收费 | 通过大模型函数调用完成意图,速度快,效果好 | - ---- - -## 使用方式 🚀 +## 部署方式 🚀 ### 一、[部署文档](./docs/Deployment.md) @@ -282,143 +182,112 @@ server: ## 常见问题 ❓ -### 1、为什么我说的话,小智识别出来很多韩文、日文、英文?🇰🇷 +如遇到问题或产品建议反馈[点这里](docs/FAQ.md)。 -建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt` -文件,如果没有就要下载,查看这里[下载语音识别模型文件](docs/Deployment.md#模型文件) +--- -### 2、为什么会出现“TTS 任务出错 文件不存在”?📁 +## 产品生态 👬 +小智是一个生态,当你使用这个产品时,也可以看看其他在这个生态圈的优秀项目 -建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。 +- [小智安卓客户端](https://github.com/TOM88812/xiaozhi-android-client) -如果没有安装,就安装 + 一个基于xiaozhi-server的Android、IOS语音对话应用,支持实时语音交互和文字对话。现在是flutter版本,打通IOS、Android端。 +- [小智电脑客户端](https://github.com/Huang-junsen/py-xiaozhi) -``` -conda install conda-forge::libopus -conda install conda-forge::ffmpeg -``` + 该项目提供了一个基于 Python 实现的小白 AI 客户端,使得在不具备实体硬件条件的情况下,依然能够体过代码体验小智 AI 的功能。主要功能包括 AI 语音交互、视觉多模态识别、IoT 设备集成、联网音乐播放、语音唤醒、自动对话模式、图形化界面、命令行模式、跨平台支持、音量控制、会话管理、加密音频传输、自动验证码处理等。 +- [小智Java服务端](https://github.com/joey-zhou/xiaozhi-esp32-server-java) -### 3、TTS 经常失败,经常超时 ⏰ + 小智开源后端服务 Java 版本是一个基于 Java 的开源项目,它包括前后端的服务,旨在为用户提供一个完整的后端服务解决方案。 +--- +## 功能清单 ✨ -建议:如果 `EdgeTTS` 经常失败,请先检查是否使用了代理(梯子)。如果使用了,请尝试关闭代理后再试; -如果用的是火山引擎的豆包 TTS,经常失败时建议使用付费版本,因为测试版本仅支持 2 个并发。 +### 已实现 ✅ -### 4、如何提高小智对话响应速度? ⚡ +- **通信协议** + 基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。 +- **对话交互** + 支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠 +- **意图识别** + 支持使用LLM意图识别、function call函数调用,减少硬编码意图判断 +- **多语言识别** + 支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。 +- **LLM 模块** + 支持灵活切换 LLM 模块,默认使用 ChatGLMLLM,也可选用阿里百炼、DeepSeek、Ollama 等接口。 +- **TTS 模块** + 支持 EdgeTTS(默认)、火山引擎豆包 TTS 等多种 TTS 接口,满足语音合成需求。 +- **记忆功能** + 支持超长记忆、本地总结记忆、无记忆三种模式,满足不同场景需求。 +- **IOT功能** + 支持管理注册设备IOT功能,支持基于对话上下文语境下的智能物联网控制。 -本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决“跑得动”的问题,再优化“跑得快”。 -如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺): +### 正在开发 🚧 -| 影响因素 | 因素值 | -|:-----:|:----------------:| -| 测试地点 | 广东省广州市海珠区 | -| 测试时间 | 2025年2月19日 12:52 | -| 宽带运营商 | 中国联通 | +- 多种心情模式 +- 智控台webui -测试方法: +想了解具体开发进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3) -1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。 +如果你是一名软件开发者,这里有一份[《致开发者的公开信》](docs/contributor_open_letter.md),欢迎加入! -2、配置完密钥后,执行以下方法 +--- -``` -# 进入项目根目录,执行以下命令: -conda activate xiaozhi-esp32-server -python performance_tester.py -``` +## 本项目支持的平台/组件列表 📋 -生成报告如下 +### LLM 语言模型 -LLM 性能排行: +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| openai 接口调用 | 阿里百炼、火山引擎豆包、深度求索、智谱ChatGLM、Gemini | 智谱ChatGLM、Gemini | +| ollama 接口调用 | Ollama | - | +| dify 接口调用 | Dify | - | +| fastgpt 接口调用 | Fastgpt | - | +| coze 接口调用 | Coze | - | -| 模块名称 | 平均首Token时间 | 平均总响应时间 | -|:-----------|:-----------|:--------| -| AliLLM | 0.547s | 1.485s | -| ChatGLMLLM | 0.677s | 3.057s | +实际上,任何支持 openai 接口调用的 LLM 均可接入使用。 -TTS 性能排行: +--- -| 模块名称 | 平均合成时间 | -|----------------------|--------| -| EdgeTTS | 1.019s | -| DoubaoTTS | 0.503s | -| CosyVoiceSiliconflow | 3.732s | +### TTS 语音合成 -推荐配置组合 (综合响应速度): +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| 接口调用 | EdgeTTS、火山引擎豆包TTS、腾讯云、阿里云TTS、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS | EdgeTTS、CosyVoiceSiliconflow(部分) | +| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、MinimaxTTS | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、MinimaxTTS | -| 组合方案 | 综合得分 | LLM首Token | TTS合成 | -|-------------------------------|-------|-----------|--------| -| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | -| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | -| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | -| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | -| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | +--- -### 结论 🔍 +### VAD 语音活动检测 -`2025年2月19日`,如果我的电脑在`广东省广州市海珠区`,且使用的是`中国联通`网络,我会优先使用: +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:---:|:---------:|:----:|:----:|:--:| +| VAD | SileroVAD | 本地使用 | 免费 | | -- LLM:`AliLLM` -- TTS:`DoubaoTTS` +--- -### 5、我说话很慢,停顿时小智老是抢话 🗣️ +### ASR 语音识别 -建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`): +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR | +| 接口调用 | DoubaoASR | - | -```yaml -VAD: - SileroVAD: - threshold: 0.5 - model_dir: models/snakers4_silero-vad - min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大 -``` +--- -### 6、我想通过小智控制电灯、空调、远程开关机等操作 💡 +### Memory 记忆存储 -本项目,支持以工具调用的方式控制HomeAssistant设备 +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:---------------:|:----:|:---------:|:--:| +| Memory | mem0ai | 接口调用 | 1000次/月额度 | | +| Memory | mem_local_short | 本地总结 | 免费 | | -1、首先选择一款支持function call支持的LLM,例如`ChatGLMLLM`。 +--- -2、在配置文件中,将 `selected_module.Intent` 设置为 `function_call`。 +### Intent 意图识别 -3、登录`HomeAssistant`,点击`左下角个人`,切换`安全`导航栏,划到底部`长期访问令牌`生成api_key。 - -在配置文件中,配置好你的home assistant的`devices`(被控制的设备)和`api_key`和`base_url`等信息。例如: - -``` yaml -plugins - home_assistant: - devices: - - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 - - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 - base_url: http://你的homeassistant地址:8123 - api_key: 你的home assistant api访问令牌 -``` - -最后,允许function_call 插件在配置文件中启用`hass_get_state`(必须)、`hass_set_state`(必须)、`hass_play_music`(不想用ha听音乐可以不启动),例如: - -``` yaml -Intent: - ... - function_call: - type: nointent - functions: - - change_role - - get_weather - - get_news - - hass_get_state - - hass_set_state - - hass_play_music -``` - -### 7、更多问题,可联系我们反馈 💬 - -我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。 - -网盘里有“硬件烧录QQ群”、“开源服务端交流群”、“产品建议联系人” 三张图片,请根据需要选择加入。 - -- 硬件烧录QQ群:适用于硬件烧录问题 -- 开源服务端交流群:适用于服务端问题 -- 产品建议联系人:适用于产品功能、产品设计等建议 +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:-------------:|:----:|:-------:|:---------------------:| +| Intent | intent_llm | 接口调用 | 根据LLM收费 | 通过大模型识别意图,通用性强 | +| Intent | function_call | 接口调用 | 根据LLM收费 | 通过大模型函数调用完成意图,速度快,效果好 | --- @@ -433,4 +302,4 @@ Intent: Star History Chart - + \ No newline at end of file diff --git a/README_en.md b/README_en.md index 883066752..1dd705549 100644 --- a/README_en.md +++ b/README_en.md @@ -1,8 +1,29 @@ +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + +
+

Xiaozhi Backend Server xiaozhi-esp32-server

+
-[![SVG Banners](https://svg-banners.vercel.app/api?type=origin&text1=Hello😃,%20XiaoZhi📟&text2=Open%20Source%20XiaoZhi%20ESP-32%20Backend%20Service&width=830&height=210)](https://github.com/xinnan-tech/xiaozhi-esp32-server)

+This project provides backend services for the open-source smart hardware project +xiaozhi-esp32
+Implemented in Python according to the Xiaozhi Communication Protocol
+Helping you quickly set up your Xiaozhi server +

+ +

+简体中文 +· English +· Changelog +· Deployment Guide +· Report Issues +

+

+ + GitHub Contributors + - GitHub Contributors + GitHub Contributors Issues @@ -10,79 +31,114 @@ GitHub pull requests + + GitHub pull requests + + + GitHub pull requests +

-# XiaoZhi ESP-32 Backend Service (xiaozhi-esp32-server) - -([中文](README.md) | English) - -This project provides the backend service for the open source smart hardware project [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32). It is implemented in `Python` based on the [XiaoZhi Communication Protocol](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh). - --- -## Target Audience 👥 +## Target Users 👥 -This project is designed to be used in conjunction with ESP32 hardware devices. If you have already purchased an ESP32 device, successfully connected to the backend service deployed by XieGe, and now wish to set up your own `xiaozhi-esp32` backend service, then this project is perfect for you. +This project requires ESP32 hardware devices. If you have purchased ESP32-related hardware, successfully connected to Brother Xia's backend service, and wish to set up your own `xiaozhi-esp32` backend service, then this project is perfect for you. -Want to see it in action? Check out the videos 🎥 +Want to see it in action? Check out these videos 🎥 + + + + + +
- - - XiaoZhi ESP32 connecting to a custom backend model - - + + + Xiaozhi esp32 connecting to your own backend model + + - - - Custom Voice - - + + + Custom voice + + - - - Conversing in Cantonese - - + + + Communicating in Cantonese + + - - - Control Home Appliances - - + + + Control home appliances + + - - - Lowest Cost Configuration - - + + + Lowest cost configuration + + +
+ + + Custom voice + + + + + Play music + + + + + + Weather plugin + + + + + + IOT command control device + + + + + + News broadcast + +
--- -## System Requirements and Deployment Prerequisites 🖥️ +## System Requirements and Prerequisites 🖥️ -- **Hardware**: A set of devices compatible with `xiaozhi-esp32` (for specific models, please refer to [this link](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf)). -- **Server**: A computer with at least a 4-core CPU and 8GB of memory. -- **Firmware Compilation**: Please update the backend service API endpoint in the `xiaozhi-esp32` project, then recompile the firmware and flash it to your device. +- **Computer or Server**: Recommended 4-core CPU, 8GB RAM computer. If using ASR with API, can run on a 2-core CPU, 2GB RAM server. +- **Update Client Interface**: Please update the backend service interface address in the client. --- ## Warning ⚠️ -This project is relatively new and has not yet undergone network security evaluations. **Do not use it in a production environment.** +1. This is open-source software. This software and any third-party API service providers it interfaces with (including but not limited to speech recognition, large language models, speech synthesis, and other platforms) have no commercial partnership. We do not provide any form of guarantee for their service quality or financial security. +We recommend 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 transfers, and does not bear the risk of recharge fund losses. -If you deploy this project on a public network for learning purposes, be sure to enable protection in the configuration file `config.yaml`: +2. This project is relatively new and has not yet passed network security testing. Please do not use it in production environments. If you deploy this project for learning purposes in a public network environment, please make sure to enable protection in the `config.yaml` configuration file: ```yaml server: @@ -91,202 +147,151 @@ server: enabled: true ``` -Once protection is enabled, you will need to validate the machine's token or MAC address based on your actual situation. Please refer to the configuration documentation for details. +After enabling protection, you need to verify the machine's token or MAC address according to actual circumstances. Please refer to the configuration documentation for details. --- +## Deployment Methods 🚀 + +### I. [Deployment Guide](./docs/Deployment.md) + +This project supports three deployment methods. You can choose based on your actual needs. + +1. [Quick Docker Deployment](./docs/Deployment.md) + +Suitable for regular users who want to quickly experience without much environment configuration. The downside is that pulling the image can be slow. Video tutorial available: [Beautiful expert teaches Docker deployment](https://www.bilibili.com/video/BV1RNQnYDE5t) + +2. [Deploy Using Docker Environment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) + +For software engineers who have Docker installed and want to make custom code modifications. + +3. [Local Source Code Run](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C) + +Suitable for users familiar with `Conda` environment or who want to build the running environment from scratch. + +For scenarios requiring higher response speed, we recommend using the local source code run method to reduce additional overhead. Video tutorial available: [Handsome expert teaches source code deployment](https://www.bilibili.com/video/BV1GvQWYZEd2) + +### II. [Firmware Compilation](./docs/firmware-build.md) + +Click here to view the detailed process of [firmware compilation](./docs/firmware-build.md). + +After successful flashing and network connection, wake up Xiaozhi using the wake word and pay attention to the console output on the server side. + +--- + +## Common Questions ❓ + +For issues or product suggestions, please [click here](docs/FAQ.md). + +--- + +## Product Ecosystem 👬 +Xiaozhi is an ecosystem. When using this product, you might want to check out other excellent projects in this ecosystem: + +- [Xiaozhi Android Client](https://github.com/TOM88812/xiaozhi-android-client) + A voice dialogue application based on xiaozhi-server for Android and iOS, supporting real-time voice interaction and text dialogue. Now in Flutter version, supporting both iOS and Android. +- [Xiaozhi PC Client](https://github.com/Huang-junsen/py-xiaozhi) + This project provides a Python-based Xiaobai AI client, allowing you to experience Xiaozhi AI features through code even without physical hardware. Main features include AI voice interaction, visual multimodal recognition, IoT device integration, online music playback, voice wake-up, automatic dialogue mode, graphical interface, command-line mode, cross-platform support, volume control, session management, encrypted audio transmission, automatic verification code processing, etc. +- [Xiaozhi Java Server](https://github.com/joey-zhou/xiaozhi-esp32-server-java) + + The Xiaozhi open-source backend service Java version is a Java-based open-source project that includes both frontend and backend services, aiming to provide users with a complete backend service solution. +--- ## Feature List ✨ ### Implemented ✅ - **Communication Protocol** - Based on the `xiaozhi-esp32` protocol, data exchange is implemented via WebSocket. + Based on `xiaozhi-esp32` protocol, implementing data interaction through WebSocket. - **Dialogue Interaction** - Supports wake-up dialogues, manual conversations, and real-time interruptions. Automatically enters sleep mode after long periods of inactivity. -- **Multilingual Recognition** - Supports Mandarin, Cantonese, English, Japanese, and Korean (default using FunASR). + Supports wake-up dialogue, manual dialogue, and real-time interruption. Automatically sleeps after long periods without dialogue +- **Intent Recognition** + Supports LLM intent recognition and function call, reducing hard-coded intent judgment +- **Multi-language Recognition** + Supports Mandarin, Cantonese, English, Japanese, Korean (default using FunASR). - **LLM Module** - Allows flexible switching of LLM modules. The default is ChatGLMLLM, with options to use AliLLM, DeepSeek, Ollama, and others. + Supports flexible switching of LLM modules, default using ChatGLMLLM, can also use Alibaba Bailian, DeepSeek, Ollama, and other interfaces. - **TTS Module** - Supports multiple TTS interfaces including EdgeTTS (default) and Volcano Engine Doubao TTS to meet speech synthesis requirements. + Supports EdgeTTS (default), Volcano Engine Doubao TTS, and other TTS interfaces to meet speech synthesis needs. +- **Memory Function** + Supports ultra-long memory, local summary memory, and no memory modes to meet different scenario needs. +- **IOT Function** + Supports managing registered device IOT functions, supporting intelligent IoT control based on dialogue context. -### In Development 🚧 +### Under Development 🚧 -- Conversation Memory Feature -- Multiple Mood Modes -- Smart Control Panel Web UI +- Multiple mood modes +- Smart control panel webui -![Screenshot](docs/images/webui.png) +To learn about specific development progress, [click here](https://github.com/users/xinnan-tech/projects/3) + +If you are a software developer, here's an [Open Letter to Developers](docs/contributor_open_letter.md), welcome to join! --- -## Supported Platforms/Components 📋 +## Supported Platforms/Components List 📋 -### LLM +### LLM Language Models -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-----------------------------:|:-----------------------------:|:-----------------:|:-------------------------------------------------------------------------:| -| LLM | AliLLM (阿里百炼) | OpenAI API call | Token consumption | [Click to apply for API key](https://bailian.console.aliyun.com/?apiKey=1#/api-key) | -| LLM | DeepSeekLLM (深度求索) | OpenAI API call | Token consumption | [Click to apply for API key](https://platform.deepseek.com/) | -| LLM | ChatGLMLLM (智谱) | OpenAI API call | Free | Although free, you still need to [click to apply for an API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| LLM | OllamaLLM | Ollama API call | Free/Custom | Requires pre-downloading the model (`ollama pull`); service URL: `http://localhost:11434` | -| LLM | DifyLLM | Dify API call | Token consumption | For local deployment. Note that prompt configuration must be set in the Dify console. | -| LLM | GeminiLLM | Gemini API call | Free | [Click to apply for API key](https://aistudio.google.com/apikey) | -| LLM | CozeLLM | Coze API call | Token consumption | Requires providing bot_id, user_id, and personal token. | -| LLM | Home Assistant | Home Assistant voice assistant API call | Free | Requires providing a Home Assistant token. | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| openai interface call | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini | +| ollama interface call | Ollama | - | +| dify interface call | Dify | - | +| fastgpt interface call | Fastgpt | - | +| coze interface call | Coze | - | -In fact, any LLM that supports OpenAI API calls can be integrated. +In fact, any LLM supporting openai interface calls can be integrated. --- -### TTS +### TTS Speech Synthesis -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:--------------------------------------:|:------------:|:-----------------:|:--------------------------------------------------------------------------------------:| -| TTS | EdgeTTS | API call | Free | Default TTS based on Microsoft's speech synthesis technology. | -| TTS | DoubaoTTS (火山引擎豆包 TTS) | API call | Token consumption | [Click to create an API key](https://console.volcengine.com/speech/service/8); it is recommended to use the paid version for higher concurrency. | -| TTS | CosyVoiceSiliconflow | API call | Token consumption | Requires application for the Siliconflow API key; output format is WAV. | -| TTS | CozeCnTTS | API call | Token consumption | Requires providing a Coze API key; output format is WAV. | -| TTS | FishSpeech | API call | Free/Custom | Starts a local TTS service; see the configuration file for startup instructions. | -| TTS | GPT_SOVITS_V2 | API call | Free/Custom | Starts a local TTS service, suitable for personalized speech synthesis scenarios. | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Interface Call | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS | EdgeTTS, CosyVoiceSiliconflow(partial) | +| Local Service | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | --- -### VAD +### VAD Voice Activity Detection -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-------------------:|:------------:|:-------------:|:-------:| -| VAD | SileroVAD | Local | Free | | +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:---:|:---------:|:----:|:----:|:--:| +| VAD | SileroVAD | Local Use | Free | | --- -### ASR +### ASR Speech Recognition -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-------------------:|:------------:|:-------------:|:-------:| -| ASR | FunASR | Local | Free | | -| ASR | SherpaASR | Local | Free | | -| ASR | DoubaoASR | API call | Paid | | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Local Use | FunASR, SherpaASR | FunASR, SherpaASR | +| Interface Call | DoubaoASR | - | --- -## Usage 🚀 +### Memory Storage -### 1. [Deployment Documentation](./docs/Deployment.md) - -This project supports three deployment methods. Choose the one that best fits your needs. - -The documentation provided here is a **written tutorial**. If you prefer a **video tutorial**, you can refer to [this expert's hands-on guide](https://www.bilibili.com/video/BV1gePuejEvT). - -Combining both the written and video tutorials can help you get started more quickly. - -1. [Docker Quick Deployment](./docs/Deployment.md) - Suitable for general users who want a quick experience without extensive environment configuration. The only downside is that pulling the image can be a bit slow. - -2. [Deployment Using Docker Environment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) - Ideal for software engineers who already have Docker installed and wish to customize the code. - -3. [Running from Local Source Code](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C) - Suitable for users familiar with the `Conda` environment or those who wish to build the runtime environment from scratch. - -For scenarios requiring higher response speeds, running from the local source code is recommended to reduce additional overhead. - -### 2. [Firmware Compilation](./docs/firmware-build.md) - -Click [here](./docs/firmware-build.md) for a detailed guide on firmware compilation. - -After successful compilation and network connection, wake up XiaoZhi using the wake-up word and monitor the server console for output. +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:---------------:|:----:|:---------:|:--:| +| Memory | mem0ai | Interface Call | 1000 times/month quota | | +| Memory | mem_local_short | Local Summary | Free | | --- -## Frequently Asked Questions ❓ +### Intent Recognition -### 1. TTS often fails and times out ⏰ - -**Suggestion:** -If `EdgeTTS` frequently fails, please first check whether you are using a proxy (VPN). If so, try disabling the proxy and try again. If you are using Volcano Engine Doubao TTS and it often fails, it is recommended to use the paid version since the trial only supports 2 concurrent requests. - -### 2. I want to control lights, air conditioners, remote power on/off, etc. with XiaoZhi 💡 - -**Suggestion:** -Set the `LLM` to `HomeAssistant` in the configuration file and use the `HomeAssistant` API to perform the relevant controls. - -### 3. I speak slowly, and XiaoZhi always interrupts during pauses 🗣️ - -**Suggestion:** -Locate the following section in the configuration file and increase the value of `min_silence_duration_ms` (for example, change it to `1000`): - -```yaml -VAD: - SileroVAD: - threshold: 0.5 - model_dir: models/snakers4_silero-vad - min_silence_duration_ms: 700 # If your pauses are longer, increase this value -``` - -### 4. Why does XiaoZhi recognize a lot of Korean, Japanese, and English in what I say? 🇰🇷 - -**Suggestion:** -Check whether the `model.pt` file exists in the `models/SenseVoiceSmall` directory. If it does not, please download it. See [Download ASR Model Files](docs/Deployment.md#模型文件) for details. - -### 5. Why does the error “TTS task error: file does not exist” occur? 📁 - -**Suggestion:** -Verify that you have correctly installed the `libopus` and `ffmpeg` libraries using `conda`. If not, install them using: - -``` -conda install conda-forge::libopus -conda install conda-forge::ffmpeg -``` - -### 6. How can I improve XiaoZhi's dialogue response speed? ⚡ - -The default configuration of this project is designed to be cost-effective. It is recommended that beginners first use the default free models to ensure that the system runs smoothly, then optimize for faster response times. -To improve response speed, you can try replacing individual components. Below are the response time test results for each component (for reference only, not a guarantee): - -**LLM Performance Ranking:** - -| Module Name | Average First Token Time | Average Total Response Time | -|--------------|--------------------------|-----------------------------| -| AliLLM | 0.547s | 1.485s | -| ChatGLMLLM | 0.677s | 3.057s | -| OllamaLLM | 0.003s | 0.003s | - -**TTS Performance Ranking:** - -| Module Name | Average Synthesis Time | -|----------------------------|------------------------| -| EdgeTTS | 1.019s | -| DoubaoTTS | 0.503s | -| CosyVoiceSiliconflow | 3.732s | - -**Recommended Configuration Combination (Overall Response Speed):** - -| Combination Scheme | Overall Score | LLM First Token | TTS Synthesis | -|-----------------------------------|---------------|-----------------|---------------| -| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | -| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | -| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | -| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | -| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | - -**Conclusion 🔍** - -_As of February 19, 2025, if my computer were located in Haizhu District, Guangzhou, Guangdong Province, and connected via China Unicom, I would prioritize using:_ - -- **LLM:** `AliLLM` -- **TTS:** `DoubaoTTS` - -### 7. For more questions, feel free to contact us for feedback 💬 - -Our contact information is in [Baidu Netdisk](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),The extraction code is`223y`。 +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:-------------:|:----:|:-------:|:---------------------:| +| Intent | intent_llm | Interface Call | Based on LLM pricing | Intent recognition through large models, highly generalizable | +| Intent | function_call | Interface Call | Based on LLM pricing | Intent completion through large model function calls, fast and effective | --- -## Acknowledgements 🙏 +## Acknowledgments 🙏 -- This project was inspired by the [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented based on it. -- Many thanks to [Tenclass](https://www.tenclass.com/) for providing detailed documentation support for the XiaoZhi communication protocol. +- This project was inspired by [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented based on it. +- Thanks to [Tenclass](https://www.tenclass.com/) for providing detailed documentation support for the Xiaozhi communication protocol. @@ -294,4 +299,4 @@ Our contact information is in [Baidu Netdisk](https://pan.baidu.com/s/1x6USjvP1n Star History Chart - \ No newline at end of file + \ No newline at end of file diff --git a/docs/Deployment.md b/docs/Deployment.md index cb64e604b..7338a9812 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -328,14 +328,14 @@ LLM: 以下是一些常见问题,供参考: -[1、为什么我说的话,小智识别出来很多韩文、日文、英文](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) -[2、为什么会出现“TTS 任务出错 文件不存在”?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) -[3、TTS 经常失败,经常超时](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[3、TTS 经常失败,经常超时](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) -[4、如何提高小智对话响应速度?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[4、如何提高小智对话响应速度?](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) -[5、我说话很慢,停顿时小智老是抢话](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[5、我说话很慢,停顿时小智老是抢话](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) -[6、我想通过小智控制电灯、空调、远程开关机等操作](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[6、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 000000000..8acdb1a04 --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,139 @@ +# 常见问题 ❓ + +### 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、如何提高小智对话响应速度? ⚡ + +本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决"跑得动"的问题,再优化"跑得快"。 +如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺): + +| 影响因素 | 因素值 | +|:-----:|:----------------:| +| 测试地点 | 广东省广州市海珠区 | +| 测试时间 | 2025年2月19日 12:52 | +| 宽带运营商 | 中国联通 | + +测试方法: + +1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。 + +2、配置完密钥后,执行以下方法 + +``` +# 进入项目根目录,执行以下命令: +conda activate xiaozhi-esp32-server +python performance_tester.py +``` + +生成报告如下 + +LLM 性能排行: + +| 模块名称 | 平均首Token时间 | 平均总响应时间 | +|:-----------|:-----------|:--------| +| AliLLM | 0.547s | 1.485s | +| ChatGLMLLM | 0.677s | 3.057s | + +TTS 性能排行: + +| 模块名称 | 平均合成时间 | +|----------------------|--------| +| EdgeTTS | 1.019s | +| DoubaoTTS | 0.503s | +| CosyVoiceSiliconflow | 3.732s | + +推荐配置组合 (综合响应速度): + +| 组合方案 | 综合得分 | LLM首Token | TTS合成 | +|-------------------------------|-------|-----------|--------| +| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | +| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | +| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | +| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | +| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | + +### 结论 🔍 + +`2025年2月19日`,如果我的电脑在`广东省广州市海珠区`,且使用的是`中国联通`网络,我会优先使用: + +- LLM:`AliLLM` +- TTS:`DoubaoTTS` + +### 5、我说话很慢,停顿时小智老是抢话 🗣️ + +建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`): + +```yaml +VAD: + SileroVAD: + threshold: 0.5 + model_dir: models/snakers4_silero-vad + min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大 +``` + +### 6、我想通过小智控制电灯、空调、远程开关机等操作 💡 + +本项目,支持以工具调用的方式控制HomeAssistant设备 + +1、首先选择一款支持function call支持的LLM,例如`ChatGLMLLM`。 + +2、在配置文件中,将 `selected_module.Intent` 设置为 `function_call`。 + +3、登录`HomeAssistant`,点击`左下角个人`,切换`安全`导航栏,划到底部`长期访问令牌`生成api_key。 + +在配置文件中,配置好你的home assistant的`devices`(被控制的设备)和`api_key`和`base_url`等信息。例如: + +``` yaml +plugins + home_assistant: + devices: + - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 + - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 + base_url: http://你的homeassistant地址:8123 + api_key: 你的home assistant api访问令牌 +``` + +最后,允许function_call 插件在配置文件中启用`hass_get_state`(必须)、`hass_set_state`(必须)、`hass_play_music`(不想用ha听音乐可以不启动),例如: + +``` yaml +Intent: + ... + function_call: + type: nointent + functions: + - change_role + - get_weather + - get_news + - hass_get_state + - hass_set_state + - hass_play_music +``` + +### 7、更多问题,可联系我们反馈 💬 + +我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。 + +网盘里有"硬件烧录QQ群"、"开源服务端交流群"、"产品建议联系人" 三张图片,请根据需要选择加入。 + +- 硬件烧录QQ群:适用于硬件烧录问题 +- 开源服务端交流群:适用于服务端问题 +- 产品建议联系人:适用于产品功能、产品设计等建议 \ No newline at end of file diff --git a/docs/firmware-build.md b/docs/firmware-build.md index b726826c9..78a90ae87 100644 --- a/docs/firmware-build.md +++ b/docs/firmware-build.md @@ -92,14 +92,14 @@ https://espressif.github.io/esp-launchpad/ 以下是一些常见问题,供参考: -[1、为什么我说的话,小智识别出来很多韩文、日文、英文](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) -[2、为什么会出现“TTS 任务出错 文件不存在”?](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) -[3、TTS 经常失败,经常超时](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[3、TTS 经常失败,经常超时](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) -[4、如何提高小智对话响应速度?](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[4、如何提高小智对话响应速度?](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) -[5、我说话很慢,停顿时小智老是抢话](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[5、我说话很慢,停顿时小智老是抢话](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) -[6、我想通过小智控制电灯、空调、远程开关机等操作](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[6、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) diff --git a/docs/images/banner1.png b/docs/images/banner1.png new file mode 100644 index 000000000..974ddaf35 Binary files /dev/null and b/docs/images/banner1.png differ diff --git a/docs/images/webui.png b/docs/images/webui.png deleted file mode 100644 index 4d4ae599c..000000000 Binary files a/docs/images/webui.png and /dev/null differ diff --git a/main/README.md b/main/README.md index 741a626b3..9dc57ee39 100644 --- a/main/README.md +++ b/main/README.md @@ -1,4 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../README.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](./FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) # 项目目录介绍 当你看到这份文件的时候,这个这个项目还没完善好。我们还有很多东西要做。 diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 0491632b5..5f7fda867 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,4 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](.././FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) # 项目介绍 manager-api 该项目基于SpringBoot框架开发。 @@ -81,15 +81,16 @@ src/main/java/xiaozhi/AdminApplication.java 执行以下命令生产jar包 ``` -mvn install +mvn clean install ``` 把jar包放在服务器上,执行 ``` -nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev >/dev/null & +nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.activate=dev ``` + # 接口文档 启动后打开:http://localhost:8002/xiaozhi-esp32-api/doc.html diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index 250ea1f6d..5e8778dc7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -20,6 +20,7 @@ import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.Result; import xiaozhi.modules.device.dto.DeviceBindDTO; +import xiaozhi.modules.device.dto.DeviceRegisterDTO; import xiaozhi.modules.device.dto.DeviceUnBindDTO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; @@ -63,6 +64,25 @@ public class DeviceController { // return new Result().ok(device); // } + @PostMapping("/register") + @Operation(summary = "注册设备") + public Result registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) { + String macAddress = deviceRegisterDTO.getMacAddress(); + if (StringUtils.isBlank(macAddress)) { + return new Result().error(ErrorCode.NOT_NULL, "mac地址不能为空"); + } + // 生成六位验证码 + String code = String.valueOf(Math.random()).substring(2, 8); + String key = RedisKeys.getDeviceCaptchaKey(code); + String existsMac = null; + do { + existsMac = (String) redisUtils.get(key); + } while (StringUtils.isNotBlank(existsMac)); + + redisUtils.set(key, macAddress); + return new Result().ok(code); + } + @GetMapping("/bind/{agentId}") @Operation(summary = "获取已绑定设备") @RequiresPermissions("sys:role:normal") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java new file mode 100644 index 000000000..ce37c517a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java @@ -0,0 +1,23 @@ +package xiaozhi.modules.device.dto; + +import java.io.Serializable; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 设备注册头信息 + * + * @author zjy + * @since 2025-3-28 + */ +@Setter +@Getter +@Schema(description = "设备注册头信息") +public class DeviceRegisterDTO implements Serializable { + + @Schema(description = "mac地址") + private String macAddress; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index fc5db7050..e5b89c99f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -77,6 +77,7 @@ public class ShiroConfig { filterMap.put("/user/captcha", "anon"); filterMap.put("/user/login", "anon"); filterMap.put("/user/register", "anon"); + filterMap.put("/device/register", "anon"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java index e66327f59..aad888dfd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java @@ -82,8 +82,6 @@ public class Oauth2Filter extends AuthenticatingFilter { httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); try { - // 处理登录失败的异常 - logger.error("onLoginFailure:登录失败!", e); Throwable throwable = e.getCause() == null ? e : e.getCause(); Result r = new Result().error(ErrorCode.UNAUTHORIZED, throwable.getMessage()); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java index ee5514005..535fb5485 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java @@ -50,7 +50,7 @@ public class AdminController { AdminPageUserDTO dto = new AdminPageUserDTO(); dto.setMobile((String) params.get("mobile")); dto.setLimit((String) params.get(Constant.LIMIT)); - dto.setPage((String) params.get("pages")); + dto.setPage((String) params.get(Constant.PAGE)); ValidatorUtils.validateEntity(dto); PageData page = sysUserService.page(dto); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java index 71d507c6b..3849b485b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java @@ -156,6 +156,7 @@ public class SysUserServiceImpl extends BaseServiceImpl - - - - - + + + + + + + + + + + + ${LOG_HOME} + true + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}) - %msg%n + UTF-8 + + + + + + ${LOG_HOME}/xiaozhi-esp32-api.log + + ${LOG_HOME}/xiaozhi-esp32-api.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 2GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + + ${LOG_HOME}/error.log + + ERROR + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 1GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + - - + + + + + + + + - - + + + + + + + + + + + + + + - + + + ${LOG_HOME}/xiaozhi-esp32-api.log - - /home/system/logs/admin.%d{yyyy-MM-dd}.%i.log - - 1MB - - 7 + ${LOG_HOME}/xiaozhi-esp32-api.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 2GB - - + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 - - - + + + + ${LOG_HOME}/error.log + + ERROR + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 1GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + + + + + + + + + + - - \ No newline at end of file + + + + true + + diff --git a/main/manager-web/README.md b/main/manager-web/README.md index a81c8ff61..3d26f25e4 100644 --- a/main/manager-web/README.md +++ b/main/manager-web/README.md @@ -1,4 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](.././FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) # xiaozhi @@ -6,8 +6,6 @@ 开发使用代码编辑器,导入项目时,选择`manager-web`文件夹作为项目目录 -参照[manager前后端接口协议](https://app.apifox.com/invite/project?token=H_8qhgfjUeaAL0wybghgU)开发 - ``` npm install ``` diff --git a/main/manager-web/src/apis/api.js b/main/manager-web/src/apis/api.js index 3a0370326..1a9d15ab0 100755 --- a/main/manager-web/src/apis/api.js +++ b/main/manager-web/src/apis/api.js @@ -7,7 +7,7 @@ import admin from './module/admin.js' * 如果你想调用8002端口,就用'/xiaozhi-esp32-api/api/v1',请与vue.config.js的devServer配置相结合,方便跨域请求 * */ -// const DEV_API_SERVICE = 'https://2662r3426b.vicp.fun/xiaozhi-esp32-api' +const DEV_API_SERVICE = 'https://2662r3426b.vicp.fun/xiaozhi-esp32-api' // 8002开发完成完成后使用这个 const DEV_API_SERVICE = 'http://localhost:8002/xiaozhi-esp32-api' @@ -16,7 +16,8 @@ const DEV_API_SERVICE = 'http://localhost:8002/xiaozhi-esp32-api' * @returns {string} */ export function getServiceUrl() { - return '/xiaozhi-esp32-api' + // return '/xiaozhi-esp32-api' + return DEV_API_SERVICE } diff --git a/main/manager-web/src/apis/module/admin.js b/main/manager-web/src/apis/module/admin.js index 977437ab9..83da30230 100644 --- a/main/manager-web/src/apis/module/admin.js +++ b/main/manager-web/src/apis/module/admin.js @@ -4,20 +4,58 @@ import {getServiceUrl} from '../api' export default { // 用户列表 - getUserList(callback) { + getUserList(params, callback) { + const queryParams = new URLSearchParams({ + page: params.page, + limit: params.limit, + mobile: params.mobile + }).toString(); + + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/admin/users?${queryParams}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime() + callback(res) + }) + .fail((err) => { + console.error('请求失败:', err) + RequestService.reAjaxFun(() => { + this.getUserList(callback) + }) + }).send() + }, + // 删除用户 + deleteUser(id, callback) { RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/admin/users`) - .method('GET') + .url(`${getServiceUrl()}/api/v1/admin/users/${id}`) + .method('DELETE') .success((res) => { RequestService.clearRequestTime() callback(res) }) .fail((err) => { - console.error('请求失败:', err) + console.error('删除失败:', err) RequestService.reAjaxFun(() => { - this.getUserList(callback) + this.deleteUser(id, callback) }) + }).send() + }, + // 重置用户密码 + resetUserPassword(id, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/admin/users/${id}`) + .method('PUT') + .success((res) => { + RequestService.clearRequestTime() + callback(res) }) - .send() + .fail((err) => { + console.error('重置密码失败:', err) + RequestService.reAjaxFun(() => { + this.resetUserPassword(id, callback) + }) + }).send() } + } diff --git a/main/manager-web/src/apis/module/agent.js b/main/manager-web/src/apis/module/agent.js new file mode 100644 index 000000000..034cbf8a0 --- /dev/null +++ b/main/manager-web/src/apis/module/agent.js @@ -0,0 +1,100 @@ +import RequestService from '../httpRequest' +import {getServiceUrl} from '../api' + + +export default { + // 获取智能体列表 + getAgentList(callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent/list`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.getAgentList(callback); + }); + }).send(); + }, + // 添加智能体 + addAgent(agentName, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent`) + .method('POST') + .data({agentName: agentName}) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.addAgent(agentName, callback); + }); + }).send(); + }, + // 删除智能体 + deleteAgent(agentId, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent/${agentId}`) + .method('DELETE') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.deleteAgent(agentId, callback); + }); + }).send(); + }, + // 获取智能体配置 + getDeviceConfig(deviceId, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent/${deviceId}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取配置失败:', err); + RequestService.reAjaxFun(() => { + this.getDeviceConfig(deviceId, callback); + }); + }).send(); + }, + // 配置智能体 + updateAgentConfig(agentId, configData, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent/${agentId}`) + .method('PUT') + .data(configData) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.updateAgentConfig(agentId, configData, callback); + }); + }).send(); + }, + // 新增方法:获取智能体模板 + getAgentTemplate(callback) { // 移除templateName参数 + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/agent/template`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取模板失败:', err); + RequestService.reAjaxFun(() => { + this.getAgentTemplate(callback); + }); + }).send(); + }, +} diff --git a/main/manager-web/src/apis/module/device.js b/main/manager-web/src/apis/module/device.js new file mode 100644 index 000000000..e8dc2c719 --- /dev/null +++ b/main/manager-web/src/apis/module/device.js @@ -0,0 +1,54 @@ +import RequestService from '../httpRequest' +import {getServiceUrl} from '../api' + +export default { + // 已绑设备 + getAgentBindDevices(agentId, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/device/bind/${agentId}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取设备列表失败:', err); + RequestService.reAjaxFun(() => { + this.getAgentBindDevices(agentId, callback); + }); + }).send(); + }, + // 解绑设备 + unbindDevice(device_id, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/device/unbind`) + .method('POST') + .data({ deviceId: device_id }) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('解绑设备失败:', err); + RequestService.reAjaxFun(() => { + this.unbindDevice(device_id, callback); + }); + }).send(); + }, + // 绑定设备 + bindDevice(agentId, deviceCode, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/device/bind/${agentId}/${deviceCode}`) + .method('POST') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('绑定设备失败:', err); + RequestService.reAjaxFun(() => { + this.bindDevice(agentId, deviceCode, callback); + }); + }).send(); + }, +} \ No newline at end of file diff --git a/main/manager-web/src/apis/module/model.js b/main/manager-web/src/apis/module/model.js new file mode 100644 index 000000000..2534bb5a6 --- /dev/null +++ b/main/manager-web/src/apis/module/model.js @@ -0,0 +1,30 @@ +import RequestService from '../httpRequest' +import {getServiceUrl} from '../api' + + +export default { + // 获取模型配置列表 + getModelList(params, callback) { + const queryParams = new URLSearchParams({ + modelType: params.modelType, + modelName: params.modelName || '', + page: params.page || 0, + limit: params.limit || 10 + }).toString(); + + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/models/models/list?${queryParams}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime() + callback(res) + }) + .fail((err) => { + console.error('获取模型列表失败:', err) + RequestService.reAjaxFun(() => { + this.getModelList(params, callback) + }) + }).send() + }, + +} diff --git a/main/manager-web/src/apis/module/user.js b/main/manager-web/src/apis/module/user.js index 5ce209410..8464794c0 100755 --- a/main/manager-web/src/apis/module/user.js +++ b/main/manager-web/src/apis/module/user.js @@ -21,7 +21,6 @@ export default { }, // 获取验证码 getCaptcha(uuid, callback) { - RequestService.sendRequest() .url(`${getServiceUrl()}/api/v1/user/captcha?uuid=${uuid}`) .method('GET') @@ -52,7 +51,6 @@ export default { .fail(() => { }).send() }, - // 保存设备配置 saveDeviceConfig(device_id, configData, callback) { RequestService.sendRequest() @@ -70,21 +68,6 @@ export default { }); }).send(); }, - // 获取智能体列表 - getAgentList(callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent`) - .method('GET') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail(() => { - RequestService.reAjaxFun(() => { - this.getAgentList(callback); - }); - }).send(); - }, // 用户信息获取 getUserInfo(callback) { RequestService.sendRequest() @@ -101,37 +84,6 @@ export default { }) }).send() }, - // 添加智能体 - addAgent(agentName, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent`) - .method('POST') - .data({name: agentName}) - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail(() => { - RequestService.reAjaxFun(() => { - this.addAgent(agentName, callback); - }); - }).send(); - }, - // 删除智能体 - deleteAgent(agentId, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/${agentId}`) - .method('DELETE') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail(() => { - RequestService.reAjaxFun(() => { - this.deleteAgent(agentId, callback); - }); - }).send(); - }, // 修改用户密码 changePassword(oldPassword, newPassword, successCallback, errorCallback) { RequestService.sendRequest() @@ -152,101 +104,4 @@ export default { }) .send(); }, - // 获取智能体配置 - getDeviceConfig(deviceId, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/${deviceId}`) - .method('GET') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail((err) => { - console.error('获取配置失败:', err); - RequestService.reAjaxFun(() => { - this.getDeviceConfig(deviceId, callback); - }); - }).send(); - }, - // 配置智能体 - updateAgentConfig(agentId, configData, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/${agentId}`) - .method('PUT') - .data(configData) - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail(() => { - RequestService.reAjaxFun(() => { - this.updateAgentConfig(agentId, configData, callback); - }); - }).send(); - }, - // 已绑设备 - getAgentBindDevices(agentId, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/device/bind/${agentId}`) - .method('GET') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail((err) => { - console.error('获取设备列表失败:', err); - RequestService.reAjaxFun(() => { - this.getAgentBindDevices(agentId, callback); - }); - }).send(); - }, - // 解绑设备 - unbindDevice(device_id, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/device/unbind/${device_id}`) - .method('PUT') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail((err) => { - console.error('解绑设备失败:', err); - RequestService.reAjaxFun(() => { - this.unbindDevice(device_id, callback); - }); - }).send(); - }, - // 绑定设备 - bindDevice(agentId, code, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/device/bind/${agentId}`) - .method('POST') - .data({ code }) - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail((err) => { - console.error('绑定设备失败:', err); - RequestService.reAjaxFun(() => { - this.bindDevice(agentId, code, callback); - }); - }).send(); - }, - // 新增方法:获取智能体模板 - getAgentTemplate(templateName, callback) { - RequestService.sendRequest() - .url(`${getServiceUrl()}/api/v1/user/agent/templateId`) - .method('GET') - .success((res) => { - RequestService.clearRequestTime(); - callback(res); - }) - .fail((err) => { - console.error('获取模板失败:', err); - RequestService.reAjaxFun(() => { - this.getAgentTemplate(templateName, callback); - }); - }).send(); - }, } diff --git a/main/manager-web/src/components/AddDeviceDialog.vue b/main/manager-web/src/components/AddDeviceDialog.vue index 129ed1565..11189df7e 100644 --- a/main/manager-web/src/components/AddDeviceDialog.vue +++ b/main/manager-web/src/components/AddDeviceDialog.vue @@ -49,17 +49,23 @@ export default { return; } this.loading = true; - import('@/apis/module/user').then(({ default: userApi }) => { - userApi.bindDevice( + import('@/apis/module/device').then(({ default: deviceApi }) => { + deviceApi.bindDevice( this.agentId, this.deviceCode, ({data}) => { this.loading = false; if (data.code === 0) { this.$emit('refresh'); - this.$message.success('设备绑定成功'); + this.$message.success({ + message: '设备绑定成功', + showClose: true + }); this.closeDialog(); } else { - this.$message.error(data.msg || '绑定失败'); + this.$message.error({ + message: data.msg || '绑定失败', + showClose: true + }); } } ); diff --git a/main/manager-web/src/components/AddWisdomBodyDialog.vue b/main/manager-web/src/components/AddWisdomBodyDialog.vue index f143a5223..042cdbce3 100644 --- a/main/manager-web/src/components/AddWisdomBodyDialog.vue +++ b/main/manager-web/src/components/AddWisdomBodyDialog.vue @@ -4,7 +4,7 @@
- 添加智慧体 + 添加智能体
@@ -12,7 +12,7 @@
*
智慧体名称:
- +
@@ -29,7 +29,7 @@ + + diff --git a/main/manager-web/src/main.js b/main/manager-web/src/main.js index d12bf7317..12d672ca4 100644 --- a/main/manager-web/src/main.js +++ b/main/manager-web/src/main.js @@ -8,6 +8,7 @@ import 'element-ui/lib/theme-chalk/index.css'; import './styles/global.scss' Vue.use(ElementUI); + Vue.config.productionTip = false new Vue({ diff --git a/main/manager-web/src/store/index.js b/main/manager-web/src/store/index.js index d0292a63b..e3e21789c 100644 --- a/main/manager-web/src/store/index.js +++ b/main/manager-web/src/store/index.js @@ -7,7 +7,8 @@ Vue.use(Vuex) export default new Vuex.Store({ state: { token: '', - userInfo: {} // 添加用户信息存储 + userInfo: {}, // 添加用户信息存储 + isSuperAdmin: false // 添加superAdmin状态 }, getters: { getToken(state) { @@ -18,6 +19,12 @@ export default new Vuex.Store({ }, getUserInfo(state) { return state.userInfo + }, + getIsSuperAdmin(state) { + if (localStorage.getItem('isSuperAdmin') === null) { + return state.isSuperAdmin + } + return localStorage.getItem('isSuperAdmin') === 'true' } }, mutations: { @@ -27,11 +34,16 @@ export default new Vuex.Store({ }, setUserInfo(state, userInfo) { state.userInfo = userInfo + const isSuperAdmin = userInfo.superAdmin === 1 + state.isSuperAdmin = isSuperAdmin + localStorage.setItem('isSuperAdmin', isSuperAdmin) }, clearAuth(state) { state.token = '' state.userInfo = {} + state.isSuperAdmin = false localStorage.removeItem('token') + localStorage.removeItem('isSuperAdmin') } }, actions: { diff --git a/main/manager-web/src/utils/index.js b/main/manager-web/src/utils/index.js index b9c22fbc9..aeb728b49 100755 --- a/main/manager-web/src/utils/index.js +++ b/main/manager-web/src/utils/index.js @@ -54,7 +54,8 @@ export function showDanger(msg) { } Message({ message: msg, - type: 'error' + type: 'error', + showClose: true }) } @@ -68,7 +69,8 @@ export function showWarning(msg) { } Message({ message: msg, - type: 'warning' + type: 'warning', + showClose: true }); } @@ -81,7 +83,8 @@ export function showWarning(msg) { export function showSuccess(msg) { Message({ message: msg, - type: 'success' + type: 'success', + showClose: true }) } diff --git a/main/manager-web/src/views/DeviceManagement.vue b/main/manager-web/src/views/DeviceManagement.vue index 2e853f172..348b7cf35 100644 --- a/main/manager-web/src/views/DeviceManagement.vue +++ b/main/manager-web/src/views/DeviceManagement.vue @@ -59,6 +59,7 @@ diff --git a/main/manager-web/src/views/UserManagement.vue b/main/manager-web/src/views/UserManagement.vue index 53697b8eb..aee22aec8 100644 --- a/main/manager-web/src/views/UserManagement.vue +++ b/main/manager-web/src/views/UserManagement.vue @@ -11,11 +11,11 @@
- + - + - + @@ -68,18 +63,19 @@ @@ -256,9 +346,9 @@ $table-bg-color: #ecf1fd; } .user-card { - background: $table-bg-color; + background: white; border-radius: 12px; - padding: 20px; + padding: 15px; margin: 15px; } @@ -271,78 +361,203 @@ $table-bg-color: #ecf1fd; .ctrl_btn { display: flex; align-items: center; - margin-left: 25px; - } -} + margin-left: 30px; + .el-button { + min-width: 72px; + height: 32px; + padding: 7px 12px; + font-size: 12px; + border-radius: 4px; + line-height: 1; + font-weight: 500; + border: none; + transition: all 0.3s ease; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); + position: relative; + overflow: hidden; -.rotated-icon { - display: inline-block; - transform: rotate(45deg); - margin-right: 4px; - color: black; -} + &:hover { + transform: translateY(-1px); + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); + } -:deep(.el-table) { - background: $table-bg-color; + &:active { + transform: translateY(0); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + } - &.transparent-table { - .el-table__header th { - background: $table-bg-color !important; + &::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 5px; + height: 5px; + background: rgba(255, 255, 255, 0.5); + opacity: 0; + border-radius: 100%; + transform: scale(1, 1) translate(-50%, -50%); + transform-origin: 50% 50%; + } + + &:focus:not(:active)::after { + animation: ripple 0.6s ease-out; + } + } + + /* 全选按钮 */ + .el-button--primary { + background: #5f70f3; + box-shadow: 0 2px 6px rgba(95, 112, 243, 0.3); + + &:hover { + background: #4d5fe1; + box-shadow: 0 4px 8px rgba(95, 112, 243, 0.4); + } + + &:active { + background: #3a4bcf; + box-shadow: 0 2px 4px rgba(95, 112, 243, 0.2); + } + } + + /* 启用按钮 */ + .el-button--success { + background: #5bc98c; + box-shadow: 0 2px 6px rgba(91, 201, 140, 0.3); + + &:hover { + background: #4ab57d; + box-shadow: 0 4px 8px rgba(91, 201, 140, 0.4); + } + + &:active { + background: #3aa16e; + box-shadow: 0 2px 4px rgba(91, 201, 140, 0.2); + } + } + + /* 禁用按钮 */ + .el-button--warning { + background: #f6d075; color: black; + box-shadow: 0 2px 6px rgba(246, 208, 117, 0.3); + + &:hover { + background: #e4c068; + box-shadow: 0 4px 8px rgba(246, 208, 117, 0.4); + } + + &:active { + background: #d2b05b; + box-shadow: 0 2px 4px rgba(246, 208, 117, 0.2); + } + + .rotated-icon { + display: inline-block; + transform: rotate(45deg); + margin-right: 4px; + color: black; + } } - &::before { - display: none; - } + /* 删除按钮 */ + .el-button--danger { + background: #fd5b63; + box-shadow: 0 2px 6px rgba(253, 91, 99, 0.3); - &:last-child td { - border-bottom: none !important; - } + &:hover { + background: #e44a52; + box-shadow: 0 4px 8px rgba(253, 91, 99, 0.4); + } - .el-table__body tr { - background-color: $table-bg-color; - td { - border: { - top: 1px solid rgba(0, 0, 0, 0.04); - bottom: 1px solid rgba(0, 0, 0, 0.04); + &:active { + background: #cb3941; + box-shadow: 0 2px 4px rgba(253, 91, 99, 0.2); + } + } + } + + @keyframes ripple { + 0% { + transform: scale(0, 0); + opacity: 0.5; + } + 100% { + transform: scale(20, 20); + opacity: 0; + } + } + } + + .rotated-icon { + display: inline-block; + transform: rotate(45deg); + margin-right: 4px; + color: black; + } + + :deep(.el-table) { + background: white; + + &.transparent-table { + .el-table__header th { + background: white !important; + color: black; + } + + &::before { + display: none; + } + + &:last-child td { + border-bottom: none !important; + } + + .el-table__body tr { + background-color: white; + td { + border: { + top: 1px solid rgba(0, 0, 0, 0.04); + bottom: 1px solid rgba(0, 0, 0, 0.04); + } } } } } -} -.search-input { - width: 300px; - margin-right: 10px; + .search-input { + width: 300px; + margin-right: 10px; - :deep(.el-input__inner) { - background-color: transparent; - border-color: #d3d6dc; + :deep(.el-input__inner) { + background-color: transparent; + border-color: #d3d6dc; - &:focus { - border-color: #409eff; - } + &:focus { + border-color: #409eff; + } - &::placeholder { - color: #606266; - opacity: 0.7; + &::placeholder { + color: #606266; + opacity: 0.7; + } } } -} -:deep(.custom-selection-header) { - .el-checkbox { - display: none !important; - } + :deep(.custom-selection-header) { + .el-checkbox { + display: none !important; + } - &::after { - content: '选择'; - display: inline-block; - color: black; - font-weight: bold; - padding-bottom: 18px; + &::after { + content: '选择'; + display: inline-block; + color: black; + font-weight: bold; + padding-bottom: 18px; + } } -} .custom-pagination { display: flex; diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue index ca7f09d7e..06c9dceb4 100644 --- a/main/manager-web/src/views/home.vue +++ b/main/manager-web/src/views/home.vue @@ -94,7 +94,7 @@ export default { }, // 获取智能体列表 fetchAgentList() { - import('@/apis/module/user').then(({ default: userApi }) => { + import('@/apis/module/agent').then(({ default: userApi }) => { userApi.getAgentList(({data}) => { this.originalDevices = data.data.map(item => ({ ...item, @@ -115,7 +115,7 @@ export default { cancelButtonText: '取消', type: 'warning' }).then(() => { - import('@/apis/module/user').then(({ default: userApi }) => { + import('@/apis/module/agent').then(({ default: userApi }) => { userApi.deleteAgent(agentId, (res) => { if (res.data.code === 0) { this.$message.success('删除成功'); diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue index 95acfeaa6..cc01e0465 100644 --- a/main/manager-web/src/views/roleConfig.vue +++ b/main/manager-web/src/views/roleConfig.vue @@ -59,7 +59,7 @@ 清除 -
{{ form.langCode.length }}/1000
+
{{ (form.langCode || '').length }}/1000
@@ -132,7 +132,7 @@ export default { {label: '意图识别模型(Intent)', key: 'intentModelId'}, {label: '记忆模型(Memory)', key: 'memModelId'} ], - templates: ['台湾女友', '土豆子', '英语老师', '好奇小男孩', '汪汪队队长'], + templates: ['湾湾小何', '星际游子', '英语老师', '好奇男孩', '汪汪队长'], loadingTemplate: false } }, @@ -153,8 +153,8 @@ export default { language: this.form.language, sort: this.form.sort }; - import('@/apis/module/user').then(({default: userApi}) => { - userApi.updateAgentConfig(this.$route.query.agentId, configData, ({data}) => { + import('@/apis/module/agent').then(({default: agentApi}) => { + agentApi.updateAgentConfig(this.$route.query.agentId, configData, ({data}) => { if (data.code === 0) { this.$message.success('配置保存成功'); } else { @@ -192,27 +192,31 @@ export default { }) }, selectTemplate(templateName) { - if (this.loadingTemplate) return; - - this.loadingTemplate = true; - import('@/apis/module/user').then(({default: userApi}) => { - userApi.getAgentTemplate( - {templateName}, - (response) => { - this.loadingTemplate = false; - if (response.data.code === 0 && response.data.data.length > 0) { - this.applyTemplateData(response.data.data[0]); - this.$message.success(`「${templateName}」模板已应用`); - } else { - this.$message.warning(`未找到「${templateName}」模板`); - } - } - ); - }).catch((error) => { - this.loadingTemplate = false; - this.$message.error('模板加载失败'); - console.error('接口异常:', error); - }); + if (this.loadingTemplate) return; + this.loadingTemplate = true; + import('@/apis/module/agent').then(({default: agentApi}) => { + agentApi.getAgentTemplate((response) => { // 移除参数传递 + this.loadingTemplate = false; + if (response.data.code === 0) { + // 在客户端过滤匹配的模板 + const matchedTemplate = response.data.data.find( + t => t.agentName === templateName + ); + if (matchedTemplate) { + this.applyTemplateData(matchedTemplate); + this.$message.success(`「${templateName}」模板已应用`); + } else { + this.$message.warning(`未找到「${templateName}」模板`); + } + } else { + this.$message.error(response.data.msg || '获取模板失败'); + } + }); + }).catch((error) => { + this.loadingTemplate = false; + this.$message.error('模板加载失败'); + console.error('接口异常:', error); + }); }, applyTemplateData(templateData) { this.form = { @@ -232,8 +236,8 @@ export default { }; }, fetchAgentConfig(agentId) { - import('@/apis/module/user').then(({default: userApi}) => { - userApi.getDeviceConfig(agentId, ({data}) => { + import('@/apis/module/agent').then(({default: agentApi}) => { + agentApi.getDeviceConfig(agentId, ({data}) => { if (data.code === 0) { this.form = { ...this.form, diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 656819971..60ab7ab43 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -182,11 +182,21 @@ ASR: model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17 output_dir: tmp/ DoubaoASR: + # 可以在这里申请相关Key等信息 + # https://console.volcengine.com/speech/app type: doubao appid: 你的火山引擎语音合成服务appid access_token: 你的火山引擎语音合成服务access_token cluster: volcengine_input_common output_dir: tmp/ + TencentASR: + # token申请地址:https://console.cloud.tencent.com/cam/capi + # 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle + type: tencent + appid: 你的腾讯语音合成服务appid + secret_id: 你的腾讯语音合成服务secret_id + secret_key: 你的腾讯语音合成服务secret_key + output_dir: tmp/ VAD: SileroVAD: threshold: 0.5 @@ -274,6 +284,8 @@ LLM: CozeLLM: # 定义LLM API类型 type: coze + # 你可以在这里找到个人令牌 + # https://www.coze.cn/open/oauth/pats # bot_id和user_id的内容写在引号之内 bot_id: "你的bot_id" user_id: "你的user_id" @@ -289,6 +301,8 @@ LLM: type: fastgpt # 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词 base_url: https://host/api/v1 + # 你可以在这里找到你的api_key + # https://cloud.tryfastgpt.ai/account/apikey api_key: fastgpt-xxx variables: k: "v" @@ -530,6 +544,8 @@ TTS: OpenAITTS: # openai官方文本转语音服务,可支持全球大多数语种 type: openai + # 你可以在这里获取到 api key + # https://platform.openai.com/api-keys api_key: 你的openai api key # 国内需要使用代理 api_url: https://api.openai.com/v1/audio/speech diff --git a/main/xiaozhi-server/core/providers/asr/tencent.py b/main/xiaozhi-server/core/providers/asr/tencent.py new file mode 100644 index 000000000..8221f9df5 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/tencent.py @@ -0,0 +1,251 @@ +import base64 +import hashlib +import hmac +import json +import time +from datetime import datetime, timezone +import os +import uuid +from typing import Optional, Tuple, List +import wave +import opuslib_next + +import requests +from core.providers.asr.base import ASRProviderBase +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +class ASRProvider(ASRProviderBase): + API_URL = "https://asr.tencentcloudapi.com" + API_VERSION = "2019-06-14" + FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3 + + def __init__(self, config: dict, delete_audio_file: bool = True): + self.secret_id = config.get("secret_id") + self.secret_key = config.get("secret_key") + self.output_dir = config.get("output_dir") + + # 确保输出目录存在 + os.makedirs(self.output_dir, exist_ok=True) + + def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: + """将Opus音频数据解码并保存为WAV文件""" + + file_name = f"tencent_asr_{session_id}_{uuid.uuid4()}.wav" + file_path = os.path.join(self.output_dir, file_name) + + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + pcm_data = [] + + for opus_packet in opus_data: + try: + pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms + pcm_data.append(pcm_frame) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) + + with wave.open(file_path, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) # 2 bytes = 16-bit + wf.setframerate(16000) + wf.writeframes(b"".join(pcm_data)) + + return file_path + + @staticmethod + def decode_opus(opus_data: List[bytes]) -> bytes: + """将Opus音频数据解码为PCM数据""" + import opuslib_next + + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + pcm_data = [] + + for opus_packet in opus_data: + try: + pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms + pcm_data.append(pcm_frame) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) + + return b"".join(pcm_data) + + async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]: + """将语音数据转换为文本""" + if not opus_data: + logger.bind(tag=TAG).warn("音频数据为空!") + return None, None + + try: + # 检查配置是否已设置 + if not self.secret_id or not self.secret_key: + logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别") + return None, None + + # 将Opus音频数据解码为PCM + pcm_data = self.decode_opus(opus_data) + + # 将音频数据转换为Base64编码 + base64_audio = base64.b64encode(pcm_data).decode('utf-8') + + # 构建请求体 + request_body = self._build_request_body(base64_audio) + + # 获取认证头 + timestamp, authorization = self._get_auth_headers(request_body) + + # 发送请求 + start_time = time.time() + result = self._send_request(request_body, timestamp, authorization) + + if result: + logger.bind(tag=TAG).debug(f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}") + + return result, None + + except Exception as e: + logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) + return None, None + + def _build_request_body(self, base64_audio: str) -> str: + """构建请求体""" + request_map = { + "ProjectId": 0, + "SubServiceType": 2, # 一句话识别 + "EngSerViceType": "16k_zh", # 中文普通话通用 + "SourceType": 1, # 音频数据来源为语音文件 + "VoiceFormat": self.FORMAT, # 音频格式 + "Data": base64_audio, # Base64编码的音频数据 + "DataLen": len(base64_audio) # 数据长度 + } + return json.dumps(request_map) + + def _get_auth_headers(self, request_body: str) -> Tuple[str, str]: + """获取认证头""" + try: + # 获取当前UTC时间戳 + now = datetime.now(timezone.utc) + timestamp = str(int(now.timestamp())) + date = now.strftime("%Y-%m-%d") + + # 服务名称必须是 "asr" + service = "asr" + + # 拼接凭证范围 + credential_scope = f"{date}/{service}/tc3_request" + + # 使用TC3-HMAC-SHA256签名方法 + algorithm = "TC3-HMAC-SHA256" + + # 构建规范请求字符串 + http_request_method = "POST" + canonical_uri = "/" + canonical_query_string = "" + + # 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写 + # 必须包含content-type和host头部 + content_type = "application/json; charset=utf-8" + host = "asr.tencentcloudapi.com" + action = "SentenceRecognition" # 接口名称 + + # 构建规范头部信息,注意顺序和格式 + canonical_headers = f"content-type:{content_type.lower()}\n" + \ + f"host:{host.lower()}\n" + \ + f"x-tc-action:{action.lower()}\n" + + signed_headers = "content-type;host;x-tc-action" + + # 请求体哈希值 + payload_hash = self._sha256_hex(request_body) + + # 构建规范请求字符串 + canonical_request = f"{http_request_method}\n" + \ + f"{canonical_uri}\n" + \ + f"{canonical_query_string}\n" + \ + f"{canonical_headers}\n" + \ + f"{signed_headers}\n" + \ + f"{payload_hash}" + + # 计算规范请求的哈希值 + hashed_canonical_request = self._sha256_hex(canonical_request) + + # 构建待签名字符串 + string_to_sign = f"{algorithm}\n" + \ + f"{timestamp}\n" + \ + f"{credential_scope}\n" + \ + f"{hashed_canonical_request}" + + # 计算签名密钥 + secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date) + secret_service = self._hmac_sha256(secret_date, service) + secret_signing = self._hmac_sha256(secret_service, "tc3_request") + + # 计算签名 + signature = self._bytes_to_hex(self._hmac_sha256(secret_signing, string_to_sign)) + + # 构建授权头 + authorization = f"{algorithm} " + \ + f"Credential={self.secret_id}/{credential_scope}, " + \ + f"SignedHeaders={signed_headers}, " + \ + f"Signature={signature}" + + return timestamp, authorization + + except Exception as e: + logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True) + raise RuntimeError(f"生成认证头失败: {e}") + + def _send_request(self, request_body: str, timestamp: str, authorization: str) -> Optional[str]: + """发送请求到腾讯云API""" + headers = { + "Content-Type": "application/json; charset=utf-8", + "Host": "asr.tencentcloudapi.com", + "Authorization": authorization, + "X-TC-Action": "SentenceRecognition", + "X-TC-Version": self.API_VERSION, + "X-TC-Timestamp": timestamp, + "X-TC-Region": "ap-shanghai" + } + + try: + response = requests.post(self.API_URL, headers=headers, data=request_body) + + if not response.ok: + raise IOError(f"请求失败: {response.status_code} {response.reason}") + + response_json = response.json() + + # 检查是否有错误 + if "Response" in response_json and "Error" in response_json["Response"]: + error = response_json["Response"]["Error"] + error_code = error["Code"] + error_message = error["Message"] + raise IOError(f"API返回错误: {error_code}: {error_message}") + + # 提取识别结果 + if "Response" in response_json and "Result" in response_json["Response"]: + return response_json["Response"]["Result"] + else: + logger.bind(tag=TAG).warn(f"响应中没有识别结果: {response_json}") + return "" + + except Exception as e: + logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True) + return None + + def _sha256_hex(self, data: str) -> str: + """计算字符串的SHA256哈希值""" + digest = hashlib.sha256(data.encode('utf-8')).digest() + return self._bytes_to_hex(digest) + + def _hmac_sha256(self, key, data: str) -> bytes: + """计算HMAC-SHA256""" + if isinstance(key, str): + key = key.encode('utf-8') + + return hmac.new(key, data.encode('utf-8'), hashlib.sha256).digest() + + def _bytes_to_hex(self, bytes_data: bytes) -> str: + """字节数组转十六进制字符串""" + return ''.join(f"{b:02x}" for b in bytes_data) \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py index e09eb67f9..17846cfaf 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_init.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py @@ -10,7 +10,7 @@ HASS_CACHE = {} def append_devices_to_prompt(conn): if conn.use_function_call_mode: funcs = conn.config["Intent"]["function_call"].get("functions", []) - if "hass_get_state" in funcs or "hass_get_state" in funcs: + if "hass_get_state" in funcs or "hass_set_state" in funcs: prompt = "下面是我家智能设备,可以通过homeassistant控制\n" devices = conn.config["plugins"]["home_assistant"].get("devices", []) if len(devices) == 0: @@ -27,9 +27,13 @@ def initialize_hass_handler(conn): if HASS_CACHE == {}: if conn.use_function_call_mode: funcs = conn.config["Intent"]["function_call"].get("functions", []) - if "hass_get_state" in funcs or "hass_get_state" in funcs: - HASS_CACHE['base_url'] = conn.config["plugins"]["home_assistant"].get("base_url") - HASS_CACHE['api_key'] = conn.config["plugins"]["home_assistant"].get("api_key") + if "hass_get_state" in funcs or "hass_set_state" in funcs: + HASS_CACHE["base_url"] = conn.config["plugins"]["home_assistant"].get( + "base_url" + ) + HASS_CACHE["api_key"] = conn.config["plugins"]["home_assistant"].get( + "api_key" + ) - check_model_key("home_assistant", HASS_CACHE['api_key']) + check_model_key("home_assistant", HASS_CACHE["api_key"]) return HASS_CACHE