update:合并最新代码

This commit is contained in:
hrz 2025-04-22 10:20:07 +08:00
parent 65a66774a8
commit d4d162f140
128 changed files with 2863 additions and 2234 deletions

1
.gitignore vendored
View file

@ -158,6 +158,7 @@ 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/bind_not_found.wav !main/xiaozhi-server/config/assets/bind_not_found.wav
!main/xiaozhi-server/config/assets/bind_code/*.wav !main/xiaozhi-server/config/assets/bind_code/*.wav
!main/xiaozhi-server/config/assets/max_output_size.wav
main/manager-api/.vscode main/manager-api/.vscode
# Ignore webpack cache directory # Ignore webpack cache directory

View file

@ -1,302 +0,0 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<center>
<h1>Xiaozhi Backend Server xiaozhi-esp32-server</h1>
</center>
<p align="center">
This project provides backend services for the open-source smart hardware project
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Implemented in Python according to the <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi Communication Protocol</a><br/>
Helping you quickly set up your Xiaozhi server
</p>
<p align="center">
<a href="./README.md">简体中文</a>
· English
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Changelog</a>
· <a href="./docs/Deployment.md">Deployment Guide</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Report Issues</a>
</p>
<p align="center">
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors">
<img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/xinnan-tech/xiaozhi-esp32-server?logo=github" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
<img alt="GitHub pull requests" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
</a>
</p>
---
## Target Users 👥
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 these videos 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="Xiaozhi esp32 connecting to your own backend model" src="docs/images/demo1.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="Custom voice" src="docs/images/demo2.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="Communicating in Cantonese" src="docs/images/demo3.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="Control home appliances" src="docs/images/demo5.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1kgA2eYEQ9" target="_blank">
<picture>
<img alt="Lowest cost configuration" src="docs/images/demo4.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1Vy96YCE3R" target="_blank">
<picture>
<img alt="Custom voice" src="docs/images/demo6.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="Play music" src="docs/images/demo7.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
<picture>
<img alt="Weather plugin" src="docs/images/demo8.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV178XuYfEpi" target="_blank">
<picture>
<img alt="IOT command control device" src="docs/images/demo9.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
<picture>
<img alt="News broadcast" src="docs/images/demo0.png" />
</picture>
</a>
</td>
</tr>
</table>
---
## System Requirements and Prerequisites 🖥️
- **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 ⚠️
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.
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:
auth:
# Enable protection
enabled: true
```
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 `xiaozhi-esp32` protocol, implementing data interaction through WebSocket.
- **Dialogue Interaction**
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**
Supports flexible switching of LLM modules, default using ChatGLMLLM, can also use Alibaba Bailian, DeepSeek, Ollama, and other interfaces.
- **TTS Module**
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.
### Under Development 🚧
- Multiple mood modes
- Smart control panel webui
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 List 📋
### LLM Language Models
| 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 supporting openai interface calls can be integrated.
---
### TTS Speech Synthesis
| 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 Voice Activity Detection
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Local Use | Free | |
---
### ASR Speech Recognition
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| Local Use | FunASR, SherpaASR | FunASR, SherpaASR |
| Interface Call | DoubaoASR | - |
---
### Memory Storage
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Interface Call | 1000 times/month quota | |
| Memory | mem_local_short | Local Summary | Free | |
---
### Intent Recognition
| 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 |
---
## Acknowledgments 🙏
- 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.
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture>
</a>

View file

@ -4,7 +4,16 @@
先按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf) 先按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf)
## 第2步 打开配置文件 ## 第2步 打开配置文件
配置好编译环境后,下载虾哥[xiaozhi-esp32](https://github.com/78/xiaozhi-esp32)项目源码,进入虾哥项目,打开`xiaozhi-esp32/main/Kconfig.projbuild`文件。 配置好编译环境后,下载虾哥iaozhi-esp32项目源码,
从这里下载虾哥[xiaozhi-esp32项目源码](https://github.com/78/xiaozhi-esp32/archive/refs/tags/v1.6.0.zip)。
从这里下载虾哥[xiaozhi-esp32项目源码](https://github.com/78/xiaozhi-esp32/archive/refs/tags/v1.6.0.zip)。
从这里下载虾哥[xiaozhi-esp32项目源码](https://github.com/78/xiaozhi-esp32/archive/refs/tags/v1.6.0.zip)。
下载后,解压缩包,打开`xiaozhi-esp32/main/Kconfig.projbuild`文件。
## 第3步 修改WEBSOCKET地址 ## 第3步 修改WEBSOCKET地址
找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net/xiaozhi/v1/` 找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net/xiaozhi/v1/`

Binary file not shown.

Before

Width:  |  Height:  |  Size: 576 KiB

View file

@ -1,5 +0,0 @@
{
"recommendations": [
"github.copilot-chat"
]
}

View file

@ -1,3 +0,0 @@
{
"java.compile.nullAnalysis.mode": "automatic"
}

View file

@ -1,8 +1,6 @@
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](./FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) 本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
# 项目目录介绍 # 项目目录介绍
当你看到这份文件的时候,这个这个项目还没完善好。我们还有很多东西要做。
如果你是一名软件开发者,这里有一份[《致开发者的公开信》](../docs/contributor_open_letter.md),欢迎归队! 如果你是一名软件开发者,这里有一份[《致开发者的公开信》](../docs/contributor_open_letter.md),欢迎归队!
``` ```
@ -12,9 +10,9 @@ xiaozhi-esp32-server
├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api ├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api
``` ```
# xiaozhi-server 接口协议 # xiaozhi-server 和ESP32通讯协议
[虾哥团队通信协议:Websocket 连接](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh
# manager-web 、manager-api接口协议 # manager-web 、manager-api接口协议

View file

@ -1,4 +1,5 @@
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../../docs/Deployment.md) 本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
# 项目介绍 # 项目介绍
manager-api 该项目基于SpringBoot框架开发。 manager-api 该项目基于SpringBoot框架开发。
@ -12,80 +13,6 @@ MySQL 8.0+
Redis 5.0+ Redis 5.0+
Vue 3.x Vue 3.x
# 创建数据库
如果本机已经安装了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" -d mysql:latest
```
# 确认项目数据库连接信息
在`src/main/resources/application-dev.yml`中配置数据库连接信息
```
spring:
datasource:
username: root
password: 123456
```
# 连接Redis
如果还没有Redis,你可以通过docker安装redis
```
docker run --name xiaozhi-esp32-server-redis -d -p 6379:6379 redis
```
# 确认项目Redis连接信息
在`src/main/resources/application-dev.yml`中配置Redis连接信息
```
spring:
data:
redis:
host: localhost
port: 6379
password:
database: 0
```
# 测试启动
本项目为SpringBoot项目,启动方式为:
打开`Application.java`运行`Main`方法启动
```
路径地址:
src/main/java/xiaozhi/AdminApplication.java
```
# 打包编译
执行以下命令生产jar包
```
mvn clean install
```
把jar包放在服务器上,执行
```
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.activate=dev
```
# 接口文档 # 接口文档
启动后打开:http://localhost:8002/xiaozhi/doc.html 启动后打开:http://localhost:8002/xiaozhi/doc.html

View file

@ -195,7 +195,6 @@
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.30</version>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
</dependencies> </dependencies>
@ -233,8 +232,10 @@
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.2.0</version> <configuration>
<skipTests>true</skipTests>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>

View file

@ -71,6 +71,14 @@ public class SwaggerConfig {
.build(); .build();
} }
@Bean
public GroupedOpenApi configApi() {
return GroupedOpenApi.builder()
.group("config")
.pathsToMatch("/config/**")
.build();
}
@Bean @Bean
public OpenAPI customOpenAPI() { public OpenAPI customOpenAPI() {
return new OpenAPI().info(new Info() return new OpenAPI().info(new Info()

View file

@ -84,6 +84,16 @@ public interface Constant {
*/ */
String SERVER_SECRET = "server.secret"; String SERVER_SECRET = "server.secret";
/**
* 是否允许用户注册
*/
String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register";
/**
* 下发六位验证码时显示的控制面板地址
*/
String SERVER_FRONTED_URL = "server.fronted_url";
/** /**
* 路径分割符 * 路径分割符
*/ */
@ -153,4 +163,9 @@ public interface Constant {
return value; return value;
} }
} }
/**
* 版本号
*/
public static final String VERSION = "0.3.9";
} }

View file

@ -51,4 +51,8 @@ public interface ErrorCode {
int PARAM_NUMBER_INVALID = 10037; int PARAM_NUMBER_INVALID = 10037;
int PARAM_BOOLEAN_INVALID = 10038; int PARAM_BOOLEAN_INVALID = 10038;
int PARAM_ARRAY_INVALID = 10039; int PARAM_ARRAY_INVALID = 10039;
int PARAM_JSON_INVALID = 10040;
int OTA_DEVICE_NOT_FOUND = 10041;
int OTA_DEVICE_NEED_BIND = 10042;
} }

View file

@ -38,7 +38,14 @@ public class RedisKeys {
* 模型名称的Key * 模型名称的Key
*/ */
public static String getModelNameById(String id) { public static String getModelNameById(String id) {
return "sys:model:name:" + id; return "model:name:" + id;
}
/**
* 模型配置的Key
*/
public static String getModelConfigById(String id) {
return "model:data:" + id;
} }
/** /**
@ -54,4 +61,25 @@ public class RedisKeys {
public static String getAgentDeviceCountById(String id) { public static String getAgentDeviceCountById(String id) {
return "agent:device:count:" + id; return "agent:device:count:" + id;
} }
/**
* 获取系统配置缓存key
*/
public static String getServerConfigKey() {
return "server:config";
}
/**
* 获取音色详情缓存key
*/
public static String getTimbreDetailsKey(String id) {
return "timbre:details:" + id;
}
/**
* 获取版本号Key
*/
public static String getVersionKey() {
return "system:version";
}
} }

View file

@ -1,11 +1,14 @@
package xiaozhi.common.redis; package xiaozhi.common.redis;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
@ -27,7 +30,7 @@ public class RedisUtils {
/** /**
* 过期时长为1小时,单位:秒 * 过期时长为1小时,单位:秒
*/ */
public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L; public final static long HOUR_ONE_EXPIRE = (long) 60 * 60;
/** /**
* 过期时长为6小时,单位:秒 * 过期时长为6小时,单位:秒
*/ */
@ -124,4 +127,24 @@ public class RedisUtils {
public Object rightPop(String key) { public Object rightPop(String key) {
return redisTemplate.opsForList().rightPop(key); return redisTemplate.opsForList().rightPop(key);
} }
/**
* 清空所有 Redis 数据库中的所有键
*/
public void emptyAll() {
// Lua 脚本 FLUSHALL是redis清空所有库的命令
String luaScript ="redis.call('FLUSHALL')";
// 创建 DefaultRedisScript 对象
DefaultRedisScript<Void> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(luaScript); // 设置 Lua 脚本内容
redisScript.setResultType(Void.class); // 设置返回值类型
// 执行 Lua 脚本
List<String> keys = Collections.emptyList(); // 如果脚本不依赖 key,可以传入空列表
redisTemplate.execute(redisScript, keys);
}
} }

View file

@ -191,4 +191,5 @@ public class AgentController {
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort")); .list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list); return new Result<List<AgentTemplateEntity>>().ok(list);
} }
} }

View file

@ -17,4 +17,12 @@ public interface AgentTemplateService extends IService<AgentTemplateEntity> {
* @return 默认模板实体 * @return 默认模板实体
*/ */
AgentTemplateEntity getDefaultTemplate(); AgentTemplateEntity getDefaultTemplate();
/**
* 更新默认模板中的模型ID
*
* @param modelType 模型类型
* @param modelId 模型ID
*/
void updateDefaultTemplateModelId(String modelType, String modelId);
} }

View file

@ -44,7 +44,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
@Override @Override
public PageData<AgentEntity> adminAgentList(Map<String, Object> params) { public PageData<AgentEntity> adminAgentList(Map<String, Object> params) {
IPage<AgentEntity> page = agentDao.selectPage( IPage<AgentEntity> page = agentDao.selectPage(
getPage(params, "sort", true), getPage(params, "agent_name", true),
new QueryWrapper<>()); new QueryWrapper<>());
return new PageData<>(page.getRecords(), page.getTotal()); return new PageData<>(page.getRecords(), page.getTotal());
} }

View file

@ -3,6 +3,7 @@ package xiaozhi.modules.agent.service.impl;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.modules.agent.dao.AgentTemplateDao; import xiaozhi.modules.agent.dao.AgentTemplateDao;
@ -29,4 +30,40 @@ public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, Agen
.last("LIMIT 1"); .last("LIMIT 1");
return this.getOne(wrapper); return this.getOne(wrapper);
} }
/**
* 更新默认模板中的模型ID
*
* @param modelType 模型类型
* @param modelId 模型ID
*/
@Override
public void updateDefaultTemplateModelId(String modelType, String modelId) {
modelType = modelType.toUpperCase();
UpdateWrapper<AgentTemplateEntity> wrapper = new UpdateWrapper<>();
switch (modelType) {
case "ASR":
wrapper.set("asr_model_id", modelId);
break;
case "VAD":
wrapper.set("vad_model_id", modelId);
break;
case "LLM":
wrapper.set("llm_model_id", modelId);
break;
case "TTS":
wrapper.set("tts_model_id", modelId);
wrapper.set("tts_voice_id", null);
break;
case "MEMORY":
wrapper.set("mem_model_id", modelId);
break;
case "INTENT":
wrapper.set("intent_model_id", modelId);
break;
}
wrapper.ge("sort", 0);
update(wrapper);
}
} }

View file

@ -5,6 +5,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.config.service.ConfigService;
import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysParamsService;
@ -18,8 +21,20 @@ public class SystemInitConfig {
@Autowired @Autowired
private ConfigService configService; private ConfigService configService;
@Autowired
private RedisUtils redisUtils;
@PostConstruct @PostConstruct
public void init() { public void init() {
// 检查版本号
String redisVersion = (String) redisUtils.get(RedisKeys.getVersionKey());
if (!Constant.VERSION.equals(redisVersion)) {
// 如果版本不一致,清空Redis
redisUtils.emptyAll();
// 存储新版本号
redisUtils.set(RedisKeys.getVersionKey(), Constant.VERSION);
}
sysParamsService.initServerSecret(); sysParamsService.initServerSecret();
configService.getConfig(false); configService.getConfig(false);
} }

View file

@ -91,6 +91,7 @@ public class ConfigServiceImpl implements ConfigService {
} }
throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND, "not found device"); throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND, "not found device");
} }
// 获取智能体信息 // 获取智能体信息
AgentEntity agent = agentService.getAgentById(device.getAgentId()); AgentEntity agent = agentService.getAgentById(device.getAgentId());
if (agent == null) { if (agent == null) {
@ -104,7 +105,9 @@ public class ConfigServiceImpl implements ConfigService {
} }
// 构建返回数据 // 构建返回数据
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
// 获取单台设备每天最多输出字数
String deviceMaxOutputSize = sysParamsService.getValue("device_max_output_size", true);
result.put("device_max_output_size", deviceMaxOutputSize);
// 如果客户端已实例化模型,则不返回 // 如果客户端已实例化模型,则不返回
String alreadySelectedVadModelId = (String) selectedModule.get("VAD"); String alreadySelectedVadModelId = (String) selectedModule.get("VAD");
if (alreadySelectedVadModelId != null && alreadySelectedVadModelId.equals(agent.getVadModelId())) { if (alreadySelectedVadModelId != null && alreadySelectedVadModelId.equals(agent.getVadModelId())) {
@ -288,7 +291,7 @@ public class ConfigServiceImpl implements ConfigService {
result.put("selected_module", selectedModule); result.put("selected_module", selectedModule);
if (StringUtils.isNotBlank(prompt)) { if (StringUtils.isNotBlank(prompt)) {
prompt = prompt.replace("{{assistant_name}}", "小智"); prompt = prompt.replace("{{assistant_name}}", StringUtils.isBlank(assistantName) ? "小智" : assistantName);
} }
result.put("prompt", prompt); result.put("prompt", prompt);
} }

View file

@ -1,249 +1,82 @@
package xiaozhi.modules.device.controller; package xiaozhi.modules.device.controller;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import xiaozhi.common.page.PageData; import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportReqDTO;
import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO;
import xiaozhi.modules.device.entity.OtaEntity; import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.device.service.OtaService;
import xiaozhi.modules.device.utils.NetworkUtil; import xiaozhi.modules.device.utils.NetworkUtil;
import xiaozhi.common.constant.Constant;
import io.swagger.v3.oas.annotations.Parameters;
import xiaozhi.common.validator.ValidatorUtils;
@Tag(name = "固件管理", description = "OTA固件管理接口") @Tag(name = "设备管理", description = "OTA 相关接口")
@Slf4j
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/ota") @RequestMapping("/ota/")
public class OTAController { public class OTAController {
private static final Logger logger = LoggerFactory.getLogger(OTAController.class);
private final DeviceService deviceService; private final DeviceService deviceService;
private final OtaService otaService;
@GetMapping("/otas")
@Operation(summary = "分页查询 OTA 固件信息")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true)
})
public Result<PageData<OtaEntity>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
ValidatorUtils.validateEntity(params);
PageData<OtaEntity> page = otaService.page(params);
return new Result<PageData<OtaEntity>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息 OTA 固件信息")
public Result<OtaEntity> get(@PathVariable("id") String id) {
OtaEntity data = otaService.getById(id);
return new Result<OtaEntity>().ok(data);
}
@Operation(summary = "OTA版本和设备激活状态检查")
@PostMapping @PostMapping
@Operation(summary = "保存 OTA 固件信息")
public Result<Void> save(@RequestBody OtaEntity entity) {
if (entity == null) {
return new Result<Void>().error("固件信息不能为空");
}
if (StringUtils.isBlank(entity.getFirmwareName())) {
return new Result<Void>().error("固件名称不能为空");
}
if (StringUtils.isBlank(entity.getType())) {
return new Result<Void>().error("固件类型不能为空");
}
if (StringUtils.isBlank(entity.getVersion())) {
return new Result<Void>().error("版本号不能为空");
}
try {
otaService.save(entity);
return new Result<Void>();
} catch (RuntimeException e) {
return new Result<Void>().error(e.getMessage());
}
}
@PutMapping("/{id}")
@Operation(summary = "修改 OTA 固件信息")
public Result<?> update(@PathVariable("id") String id, @RequestBody OtaEntity entity) {
if (entity == null) {
return new Result<>().error("固件信息不能为空");
}
entity.setId(id);
try {
otaService.update(entity);
return new Result<>();
} catch (RuntimeException e) {
return new Result<>().error(e.getMessage());
}
}
@DeleteMapping("/{id}")
@Operation(summary = "OTA 删除")
public Result<Void> delete(@PathVariable("id") String[] ids) {
if (ids == null || ids.length == 0) {
return new Result<Void>().error("删除的固件ID不能为空");
}
otaService.delete(ids);
return new Result<Void>();
}
@Operation(summary = "检查 OTA 版本和设备激活状态")
@PostMapping("check")
public ResponseEntity<String> checkOTAVersion( public ResponseEntity<String> checkOTAVersion(
@RequestBody DeviceReportReqDTO deviceReportReqDTO, @RequestBody DeviceReportReqDTO deviceReportReqDTO,
@Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId,
@Parameter(name = "Client-Id", description = "客户端标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Client-Id") String clientId) { @Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) {
if (StringUtils.isAnyBlank(deviceId, clientId)) { if (StringUtils.isBlank(deviceId)) {
return createResponse(DeviceReportRespDTO.createError("Device ID is required")); return createResponse(DeviceReportRespDTO.createError("Device ID is required"));
} }
if (StringUtils.isBlank(clientId)) {
clientId = deviceId;
}
String macAddress = deviceReportReqDTO.getMacAddress(); String macAddress = deviceReportReqDTO.getMacAddress();
boolean macAddressValid = NetworkUtil.isMacAddressValid(macAddress); boolean macAddressValid = NetworkUtil.isMacAddressValid(macAddress);
// 设备Id和Mac地址应是一致的, 并且必须需要application字段 // 设备Id和Mac地址应是一致的, 并且必须需要application字段
if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) { if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) {
return createResponse(DeviceReportRespDTO.createError("Invalid OTA request")); return createResponse(DeviceReportRespDTO.createError("Invalid OTA request"));
} }
return createResponse(deviceService.checkDeviceActive(macAddress, deviceId, clientId, deviceReportReqDTO)); return createResponse(deviceService.checkDeviceActive(macAddress, clientId, deviceReportReqDTO));
} }
@Operation(summary = "获取 OTA 提示信息") @Operation(summary = "设备快速检查激活状态")
@GetMapping("prompt") @PostMapping("activate")
public ResponseEntity<String> getOTAPrompt() { public ResponseEntity<String> activateDevice(
return createResponse(DeviceReportRespDTO.createError("请提交正确的ota参数")); @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId,
@Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) {
if (StringUtils.isBlank(deviceId)) {
return ResponseEntity.status(202).build();
}
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
if (device == null) {
return ResponseEntity.status(202).build();
}
return ResponseEntity.ok("success");
} }
@GetMapping("/download/{id}") @GetMapping
@Operation(summary = "下载固件文件") @Hidden
public ResponseEntity<byte[]> downloadFirmware(@PathVariable("id") String id) { public ResponseEntity<String> getOTA() {
try { return ResponseEntity.ok("OTA接口运行正常");
// 获取固件信息
OtaEntity otaEntity = otaService.getById(id);
if (otaEntity == null || StringUtils.isBlank(otaEntity.getFirmwarePath())) {
logger.warn("Firmware not found or path is empty for ID: {}", id);
return ResponseEntity.notFound().build();
}
// 获取文件路径 - 确保路径是绝对路径或正确的相对路径
String firmwarePath = otaEntity.getFirmwarePath();
Path path;
// 检查是否是绝对路径
if (Paths.get(firmwarePath).isAbsolute()) {
path = Paths.get(firmwarePath);
} else {
// 如果是相对路径,则从当前工作目录解析
path = Paths.get(System.getProperty("user.dir"), firmwarePath);
}
logger.info("Attempting to download firmware for ID: {}, DB path: {}, resolved path: {}",
id, firmwarePath, path.toAbsolutePath());
if (!Files.exists(path) || !Files.isRegularFile(path)) {
// 尝试直接从firmware目录下查找文件名
String fileName = new File(firmwarePath).getName();
Path altPath = Paths.get(System.getProperty("user.dir"), "firmware", fileName);
logger.info("File not found at primary path, trying alternative path: {}", altPath.toAbsolutePath());
if (Files.exists(altPath) && Files.isRegularFile(altPath)) {
path = altPath;
} else {
logger.error("Firmware file not found at either path: {} or {}",
path.toAbsolutePath(), altPath.toAbsolutePath());
return ResponseEntity.notFound().build();
}
}
// 读取文件内容
byte[] fileContent = Files.readAllBytes(path);
// 设置响应头
String originalFilename = otaEntity.getFirmwareName() + "_" + otaEntity.getVersion();
if (firmwarePath.contains(".")) {
String extension = firmwarePath.substring(firmwarePath.lastIndexOf("."));
originalFilename += extension;
}
// 清理文件名,移除不安全字符
String safeFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_");
logger.info("Providing download for firmware ID: {}, filename: {}, size: {} bytes",
id, safeFilename, fileContent.length);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + safeFilename + "\"")
.body(fileContent);
} catch (IOException e) {
logger.error("Error reading firmware file for ID: {}", id, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
} catch (Exception e) {
logger.error("Unexpected error during firmware download for ID: {}", id, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@PostMapping("/upload")
@Operation(summary = "上传固件文件")
public Result<String> uploadFirmware(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new Result<String>().error("上传文件不能为空");
}
try {
// 获取文件名
String originalFilename = file.getOriginalFilename();
// 生成唯一的文件名
String uniqueFileName = UUID.randomUUID().toString() + "_" + originalFilename;
// 设置存储路径
String uploadDir = "firmware";
Path uploadPath = Paths.get(uploadDir);
System.out.println(uploadPath);
// 如果目录不存在,创建目录
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 完整的文件路径
Path filePath = uploadPath.resolve(uniqueFileName);
// 保存文件
Files.copy(file.getInputStream(), filePath);
// 返回文件路径
return new Result<String>().ok(filePath.toString());
} catch (IOException e) {
return new Result<String>().error("文件上传失败:" + e.getMessage());
}
} }
@SneakyThrows @SneakyThrows

View file

@ -44,6 +44,8 @@ public class DeviceReportRespDTO {
@Schema(description = "激活码信息: 激活地址") @Schema(description = "激活码信息: 激活地址")
private String message; private String message;
@Schema(description = "挑战码")
private String challenge;
} }
@Getter @Getter

View file

@ -19,7 +19,7 @@ public interface DeviceService {
/** /**
* 检查设备是否激活 * 检查设备是否激活
*/ */
DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId, DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
DeviceReportReqDTO deviceReport); DeviceReportReqDTO deviceReport);
/** /**
@ -66,4 +66,20 @@ public interface DeviceService {
* @return 用户列表分页数据 * @return 用户列表分页数据
*/ */
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto); PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
/**
* 根据MAC地址获取设备信息
*
* @param macAddress MAC地址
* @return 设备信息
*/
DeviceEntity getDeviceByMacAddress(String macAddress);
/**
* 根据设备ID获取激活码
*
* @param deviceId 设备ID
* @return 激活码
*/
String geCodeByDeviceId(String deviceId);
} }

View file

@ -9,7 +9,6 @@ import java.util.TimeZone;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -34,6 +33,7 @@ import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserUtilService; import xiaozhi.modules.sys.service.SysUserUtilService;
@Service @Service
@ -49,11 +49,11 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
// 添加构造函数来初始化 deviceMapper // 添加构造函数来初始化 deviceMapper
public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService, public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService,
@Value("${app.fronted-url:http://localhost:8001}") String frontedUrl, SysParamsService sysParamsService,
RedisTemplate<String, Object> redisTemplate) { RedisTemplate<String, Object> redisTemplate) {
this.deviceDao = deviceDao; this.deviceDao = deviceDao;
this.sysUserUtilService = sysUserUtilService; this.sysUserUtilService = sysUserUtilService;
this.frontedUrl = frontedUrl; this.frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true);
this.redisTemplate = redisTemplate; this.redisTemplate = redisTemplate;
} }
@ -120,7 +120,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
} }
@Override @Override
public DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId, public DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
DeviceReportReqDTO deviceReport) { DeviceReportReqDTO deviceReport) {
DeviceReportRespDTO response = new DeviceReportRespDTO(); DeviceReportRespDTO response = new DeviceReportRespDTO();
response.setServer_time(buildServerTime()); response.setServer_time(buildServerTime());
@ -132,46 +132,12 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
firmware.setUrl("http://localhost:8002/xiaozhi/ota/download"); firmware.setUrl("http://localhost:8002/xiaozhi/ota/download");
response.setFirmware(firmware); response.setFirmware(firmware);
DeviceEntity deviceById = getDeviceById(deviceId); DeviceEntity deviceById = getDeviceById(macAddress);
if (deviceById != null) { // 如果设备存在,则更新上次连接时间 if (deviceById != null) { // 如果设备存在,则更新上次连接时间
deviceById.setLastConnectedAt(new Date()); deviceById.setLastConnectedAt(new Date());
deviceDao.updateById(deviceById); deviceDao.updateById(deviceById);
} else { // 如果设备不存在,则生成激活码 } else { // 如果设备不存在,则生成激活码
String safeDeviceId = deviceId.replace(":", "_").toLowerCase(); DeviceReportRespDTO.Activation code = buildActivation(macAddress, deviceReport);
String dataKey = String.format("ota:activation:data:%s", safeDeviceId);
Map<Object, Object> cacheMap = redisTemplate.opsForHash().entries(dataKey);
DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation();
if (cacheMap != null && cacheMap.containsKey("activation_code")) {
String cachedCode = (String) cacheMap.get("activation_code");
code.setCode(cachedCode);
code.setMessage(frontedUrl + "\n" + cachedCode);
} else {
String newCode = RandomUtil.randomNumbers(6);
code.setCode(newCode);
code.setMessage(frontedUrl + "\n" + newCode);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", deviceId);
dataMap.put("mac_address", macAddress);
dataMap.put("board", (deviceReport.getChipModelName() != null) ? deviceReport.getChipModelName()
: (deviceReport.getBoard() != null ? deviceReport.getBoard().getType() : "unknown"));
dataMap.put("app_version", (deviceReport.getApplication() != null)
? deviceReport.getApplication().getVersion()
: null);
dataMap.put("deviceId", deviceId);
dataMap.put("activation_code", newCode);
// 写入主数据 key
redisTemplate.opsForHash().putAll(dataKey, dataMap);
redisTemplate.expire(dataKey, 24, TimeUnit.HOURS);
// 写入反查激活码 key
String codeKey = "ota:activation:code:" + newCode;
redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS);
}
response.setActivation(code); response.setActivation(code);
} }
@ -221,7 +187,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
params.put(Constant.PAGE, dto.getPage()); params.put(Constant.PAGE, dto.getPage());
params.put(Constant.LIMIT, dto.getLimit()); params.put(Constant.LIMIT, dto.getLimit());
IPage<DeviceEntity> page = baseDao.selectPage( IPage<DeviceEntity> page = baseDao.selectPage(
getPage(params, "sort", true), getPage(params, "mac_address", true),
// 定义查询条件 // 定义查询条件
new QueryWrapper<DeviceEntity>() new QueryWrapper<DeviceEntity>()
// 必须设备关键词查找 // 必须设备关键词查找
@ -240,6 +206,16 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return new PageData<>(list, page.getTotal()); return new PageData<>(list, page.getTotal());
} }
@Override
public DeviceEntity getDeviceByMacAddress(String macAddress) {
if (StringUtils.isBlank(macAddress)) {
return null;
}
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress);
return baseDao.selectOne(wrapper);
}
private DeviceReportRespDTO.ServerTime buildServerTime() { private DeviceReportRespDTO.ServerTime buildServerTime() {
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime(); DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
TimeZone tz = TimeZone.getDefault(); TimeZone tz = TimeZone.getDefault();
@ -248,4 +224,63 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000)); serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000));
return serverTime; return serverTime;
} }
@Override
public String geCodeByDeviceId(String deviceId) {
String dataKey = getDeviceCacheKey(deviceId);
Map<Object, Object> cacheMap = redisTemplate.opsForHash().entries(dataKey);
if (cacheMap != null && cacheMap.containsKey("activation_code")) {
String cachedCode = (String) cacheMap.get("activation_code");
return cachedCode;
}
return null;
}
private String getDeviceCacheKey(String deviceId) {
String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
String dataKey = String.format("ota:activation:data:%s", safeDeviceId);
return dataKey;
}
public DeviceReportRespDTO.Activation buildActivation(String deviceId, DeviceReportReqDTO deviceReport) {
DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation();
String cachedCode = geCodeByDeviceId(deviceId);
if (StringUtils.isNotBlank(cachedCode)) {
code.setCode(cachedCode);
code.setMessage(frontedUrl + "\n" + cachedCode);
code.setChallenge(deviceId);
} else {
String newCode = RandomUtil.randomNumbers(6);
code.setCode(newCode);
code.setMessage(frontedUrl + "\n" + newCode);
code.setChallenge(deviceId);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", deviceId);
dataMap.put("mac_address", deviceId);
dataMap.put("board", (deviceReport.getBoard() != null && deviceReport.getBoard().getType() != null)
? deviceReport.getBoard().getType()
: (deviceReport.getChipModelName() != null ? deviceReport.getChipModelName() : "unknown"));
dataMap.put("app_version", (deviceReport.getApplication() != null)
? deviceReport.getApplication().getVersion()
: null);
dataMap.put("deviceId", deviceId);
dataMap.put("activation_code", newCode);
// 写入主数据 key
String dataKey = getDeviceCacheKey(deviceId);
redisTemplate.opsForHash().putAll(dataKey, dataMap);
redisTemplate.expire(dataKey, 24, TimeUnit.HOURS);
// 写入反查激活码 key
String codeKey = "ota:activation:code:" + newCode;
redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS);
}
return code;
}
} }

View file

@ -19,6 +19,8 @@ import lombok.AllArgsConstructor;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.modules.agent.service.AgentTemplateService;
import xiaozhi.modules.config.service.ConfigService;
import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
import xiaozhi.modules.model.dto.ModelConfigDTO; import xiaozhi.modules.model.dto.ModelConfigDTO;
@ -38,6 +40,8 @@ public class ModelController {
private final ModelProviderService modelProviderService; private final ModelProviderService modelProviderService;
private final TimbreService timbreService; private final TimbreService timbreService;
private final ModelConfigService modelConfigService; private final ModelConfigService modelConfigService;
private final ConfigService configService;
private final AgentTemplateService agentTemplateService;
@GetMapping("/names") @GetMapping("/names")
@Operation(summary = "获取所有模型名称") @Operation(summary = "获取所有模型名称")
@ -75,6 +79,7 @@ public class ModelController {
@PathVariable String provideCode, @PathVariable String provideCode,
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO); ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO);
configService.getConfig(false);
return new Result<ModelConfigDTO>().ok(modelConfigDTO); return new Result<ModelConfigDTO>().ok(modelConfigDTO);
} }
@ -86,6 +91,7 @@ public class ModelController {
@PathVariable String id, @PathVariable String id,
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO); ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO);
configService.getConfig(false);
return new Result<ModelConfigDTO>().ok(modelConfigDTO); return new Result<ModelConfigDTO>().ok(modelConfigDTO);
} }
@ -119,6 +125,27 @@ public class ModelController {
return new Result<Void>(); return new Result<Void>();
} }
@PutMapping("/default/{id}")
@Operation(summary = "设置默认模型")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> setDefaultModel(@PathVariable String id) {
ModelConfigEntity entity = modelConfigService.selectById(id);
if (entity == null) {
return new Result<Void>().error("模型配置不存在");
}
// 将其他模型设置为非默认
modelConfigService.setDefaultModel(entity.getModelType(), 0);
entity.setIsEnabled(1);
entity.setIsDefault(1);
modelConfigService.updateById(entity);
// 更新模板表中对应的模型ID
agentTemplateService.updateDefaultTemplateModelId(entity.getModelType(), entity.getId());
configService.getConfig(false);
return new Result<Void>();
}
@GetMapping("/{modelId}/voices") @GetMapping("/{modelId}/voices")
@Operation(summary = "获取模型音色") @Operation(summary = "获取模型音色")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")

View file

@ -28,4 +28,21 @@ public interface ModelConfigService extends BaseService<ModelConfigEntity> {
* @return 模型名称 * @return 模型名称
*/ */
String getModelNameById(String id); String getModelNameById(String id);
/**
* 根据ID获取模型配置
*
* @param id 模型ID
* @param isCache 是否缓存
* @return 模型配置实体
*/
ModelConfigEntity getModelById(String id, boolean isCache);
/**
* 设置默认模型
*
* @param modelType 模型类型
* @param isDefault 是否默认
*/
void setDefaultModel(String modelType, int isDefault);
} }

View file

@ -42,6 +42,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
List<ModelConfigEntity> entities = modelConfigDao.selectList( List<ModelConfigEntity> entities = modelConfigDao.selectList(
new QueryWrapper<ModelConfigEntity>() new QueryWrapper<ModelConfigEntity>()
.eq("model_type", modelType) .eq("model_type", modelType)
.eq("is_enabled", 1)
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%") .like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%")
.select("id", "model_name")); .select("id", "model_name"));
return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class); return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class);
@ -94,6 +95,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
modelConfigEntity.setId(id); modelConfigEntity.setId(id);
modelConfigEntity.setModelType(modelType); modelConfigEntity.setModelType(modelType);
modelConfigDao.updateById(modelConfigEntity); modelConfigDao.updateById(modelConfigEntity);
// 清除缓存
redisUtils.delete(RedisKeys.getModelConfigById(modelConfigEntity.getId()));
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class); return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
} }
@ -125,4 +128,30 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
return null; return null;
} }
@Override
public ModelConfigEntity getModelById(String id, boolean isCache) {
if (StringUtils.isBlank(id)) {
return null;
}
if (isCache) {
ModelConfigEntity cachedConfig = (ModelConfigEntity) redisUtils.get(RedisKeys.getModelConfigById(id));
if (cachedConfig != null) {
return ConvertUtils.sourceToTarget(cachedConfig, ModelConfigEntity.class);
}
}
ModelConfigEntity entity = modelConfigDao.selectById(id);
if (entity != null) {
redisUtils.set(RedisKeys.getModelConfigById(id), entity);
}
return entity;
}
@Override
public void setDefaultModel(String modelType, int isDefault) {
ModelConfigEntity entity = new ModelConfigEntity();
entity.setIsDefault(isDefault);
modelConfigDao.update(entity, new QueryWrapper<ModelConfigEntity>()
.eq("model_type", modelType));
}
} }

View file

@ -76,8 +76,10 @@ public class ShiroConfig {
filterMap.put("/favicon.ico", "anon"); filterMap.put("/favicon.ico", "anon");
filterMap.put("/user/captcha", "anon"); filterMap.put("/user/captcha", "anon");
filterMap.put("/user/login", "anon"); filterMap.put("/user/login", "anon");
filterMap.put("/user/pub-config", "anon");
filterMap.put("/user/register", "anon"); filterMap.put("/user/register", "anon");
filterMap.put("/device/register", "anon"); filterMap.put("/config/server-base", "anon");
filterMap.put("/config/agent-models", "anon");
filterMap.put("/**", "oauth2"); filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap); shiroFilter.setFilterChainDefinitionMap(filterMap);

View file

@ -1,6 +1,8 @@
package xiaozhi.modules.security.controller; package xiaozhi.modules.security.controller;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -13,6 +15,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException; import xiaozhi.common.exception.RenException;
import xiaozhi.common.page.TokenDTO; import xiaozhi.common.page.TokenDTO;
@ -75,6 +78,9 @@ public class LoginController {
@PostMapping("/register") @PostMapping("/register")
@Operation(summary = "注册") @Operation(summary = "注册")
public Result<Void> register(@RequestBody LoginDTO login) { public Result<Void> register(@RequestBody LoginDTO login) {
if (!sysUserService.getAllowUserRegister()) {
throw new RenException("当前不允许普通用户注册");
}
// 验证是否正确输入验证码 // 验证是否正确输入验证码
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha()); boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha());
if (!validate) { if (!validate) {
@ -111,4 +117,13 @@ public class LoginController {
sysUserTokenService.changePassword(userId, passwordDTO); sysUserTokenService.changePassword(userId, passwordDTO);
return new Result<>(); return new Result<>();
} }
@GetMapping("/pub-config")
@Operation(summary = "公共配置")
public Result<Map<String, Object>> pubConfig() {
Map<String, Object> config = new HashMap<>();
config.put("version", Constant.VERSION);
config.put("allowUserRegister", sysUserService.getAllowUserRegister());
return new Result<Map<String, Object>>().ok(config);
}
} }

View file

@ -27,6 +27,7 @@ import xiaozhi.common.validator.ValidatorUtils;
import xiaozhi.common.validator.group.AddGroup; import xiaozhi.common.validator.group.AddGroup;
import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.DefaultGroup;
import xiaozhi.common.validator.group.UpdateGroup; import xiaozhi.common.validator.group.UpdateGroup;
import xiaozhi.modules.config.service.ConfigService;
import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.dto.SysParamsDTO;
import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysParamsService;
@ -42,6 +43,7 @@ import xiaozhi.modules.sys.service.SysParamsService;
@AllArgsConstructor @AllArgsConstructor
public class SysParamsController { public class SysParamsController {
private final SysParamsService sysParamsService; private final SysParamsService sysParamsService;
private final ConfigService configService;
@GetMapping("page") @GetMapping("page")
@Operation(summary = "分页") @Operation(summary = "分页")
@ -77,7 +79,7 @@ public class SysParamsController {
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class); ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysParamsService.save(dto); sysParamsService.save(dto);
configService.getConfig(false);
return new Result<Void>(); return new Result<Void>();
} }
@ -90,7 +92,7 @@ public class SysParamsController {
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysParamsService.update(dto); sysParamsService.update(dto);
configService.getConfig(false);
return new Result<Void>(); return new Result<Void>();
} }
@ -103,7 +105,7 @@ public class SysParamsController {
AssertUtils.isArrayEmpty(ids, "id"); AssertUtils.isArrayEmpty(ids, "id");
sysParamsService.delete(ids); sysParamsService.delete(ids);
configService.getConfig(false);
return new Result<Void>(); return new Result<Void>();
} }
} }

View file

@ -65,4 +65,11 @@ public interface SysUserService extends BaseService<SysUserEntity> {
* @param userIds 用户ID数组 * @param userIds 用户ID数组
*/ */
void changeStatus(Integer status, String[] userIds); void changeStatus(Integer status, String[] userIds);
/**
* 获取是否允许用户注册
*
* @return 是否允许用户注册
*/
boolean getAllowUserRegister();
} }

View file

@ -37,7 +37,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
@Override @Override
public PageData<SysParamsDTO> page(Map<String, Object> params) { public PageData<SysParamsDTO> page(Map<String, Object> params) {
IPage<SysParamsEntity> page = baseDao.selectPage( IPage<SysParamsEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false), getPage(params, null, false),
getWrapper(params)); getWrapper(params));
return getPageData(page, SysParamsDTO.class); return getPageData(page, SysParamsDTO.class);
@ -125,6 +125,13 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
throw new RenException(ErrorCode.PARAM_BOOLEAN_INVALID); throw new RenException(ErrorCode.PARAM_BOOLEAN_INVALID);
} }
break; break;
case "json":
try {
JsonUtils.parseObject(paramValue, Object.class);
} catch (Exception e) {
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
}
break;
default: default:
throw new RenException(ErrorCode.PARAM_TYPE_INVALID); throw new RenException(ErrorCode.PARAM_TYPE_INVALID);
} }

View file

@ -30,6 +30,7 @@ import xiaozhi.modules.sys.dto.PasswordDTO;
import xiaozhi.modules.sys.dto.SysUserDTO; import xiaozhi.modules.sys.dto.SysUserDTO;
import xiaozhi.modules.sys.entity.SysUserEntity; import xiaozhi.modules.sys.entity.SysUserEntity;
import xiaozhi.modules.sys.enums.SuperAdminEnum; import xiaozhi.modules.sys.enums.SuperAdminEnum;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserService; import xiaozhi.modules.sys.service.SysUserService;
import xiaozhi.modules.sys.vo.AdminPageUserVO; import xiaozhi.modules.sys.vo.AdminPageUserVO;
@ -45,6 +46,8 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
private final AgentService agentService; private final AgentService agentService;
private final SysParamsService sysParamsService;
@Override @Override
public SysUserDTO getByUsername(String username) { public SysUserDTO getByUsername(String username) {
QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>(); QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
@ -205,4 +208,17 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
updateById(entity); updateById(entity);
} }
} }
@Override
public boolean getAllowUserRegister() {
String allowUserRegister = sysParamsService.getValue(Constant.SERVER_ALLOW_USER_REGISTER, true);
if (allowUserRegister.equals("true")) {
return true;
}
Long userCount = baseDao.selectCount(new QueryWrapper<SysUserEntity>());
if (userCount == 0) {
return true;
}
return false;
}
} }

View file

@ -31,7 +31,7 @@ public interface TimbreService extends BaseService<TimbreEntity> {
* @param timbreId 音色表id * @param timbreId 音色表id
* @return 音色信息 * @return 音色信息
*/ */
TimbreDetailsVO get(Long timbreId); TimbreDetailsVO get(String timbreId);
/** /**
* 保存音色信息 * 保存音色信息

View file

@ -47,7 +47,7 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
params.put(Constant.PAGE, dto.getPage()); params.put(Constant.PAGE, dto.getPage());
params.put(Constant.LIMIT, dto.getLimit()); params.put(Constant.LIMIT, dto.getLimit());
IPage<TimbreEntity> page = baseDao.selectPage( IPage<TimbreEntity> page = baseDao.selectPage(
getPage(params, "sort", true), getPage(params, null, true),
// 定义查询条件 // 定义查询条件
new QueryWrapper<TimbreEntity>() new QueryWrapper<TimbreEntity>()
// 必须按照ttsID查找 // 必须按照ttsID查找
@ -59,9 +59,33 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
} }
@Override @Override
public TimbreDetailsVO get(Long timbreId) { public TimbreDetailsVO get(String timbreId) {
if (StringUtils.isBlank(timbreId)) {
return null;
}
// 先从Redis获取缓存
String key = RedisKeys.getTimbreDetailsKey(timbreId);
TimbreDetailsVO cachedDetails = (TimbreDetailsVO) redisUtils.get(key);
if (cachedDetails != null) {
return cachedDetails;
}
// 如果缓存中没有,则从数据库获取
TimbreEntity entity = baseDao.selectById(timbreId); TimbreEntity entity = baseDao.selectById(timbreId);
return ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class); if (entity == null) {
return null;
}
// 转换为VO对象
TimbreDetailsVO details = ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class);
// 存入Redis缓存
if (details != null) {
redisUtils.set(key, details);
}
return details;
} }
@Override @Override
@ -79,6 +103,8 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class); TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class);
timbreEntity.setId(timbreId); timbreEntity.setId(timbreId);
baseDao.updateById(timbreEntity); baseDao.updateById(timbreEntity);
// 删除缓存
redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId));
} }
@Override @Override

View file

@ -12,9 +12,9 @@ spring:
druid: druid:
#MySQL #MySQL
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3308/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true url: jdbc:mysql://127.0.0.1:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root username: root
password: jky123456 password: 123456
initial-size: 10 initial-size: 10
max-active: 100 max-active: 100
min-idle: 10 min-idle: 10

View file

@ -64,6 +64,3 @@ mybatis-plus:
prefix: prefix:
blobType: BLOB blobType: BLOB
boolValue: TRUE boolValue: TRUE
app:
fronted-url: http://localhost:8001

View file

@ -0,0 +1,7 @@
-- 调整意图识别配置
delete from `ai_model_config` where id = 'Intent_function_call';
INSERT INTO `ai_model_config` VALUES ('Intent_function_call', 'Intent', 'function_call', '函数调用意图识别', 0, 1, '{\"type\": \"function_call\", \"functions\": \"change_role;get_weather;get_news;play_music\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL);
-- 增加单台设备每天最多聊天句数
delete from `sys_params` where id = 105;
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (105, 'device_max_output_size', '0', 'number', 1, '单台设备每天最多输出字数,0表示不限制');

View file

@ -0,0 +1,19 @@
-- 删除无用模型供应器
delete from `ai_model_provider` where id = 'SYSTEM_LLM_doubao';
delete from `ai_model_provider` where id = 'SYSTEM_LLM_chatglm';
delete from `ai_model_provider` where id = 'SYSTEM_TTS_302ai';
delete from `ai_model_provider` where id = 'SYSTEM_TTS_gizwits';
-- 添加模型供应器
delete from `ai_model_provider` where id = 'SYSTEM_ASR_TencentASR';
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
('SYSTEM_ASR_TencentASR', 'ASR', 'tencent', '腾讯语音识别', '[{"key":"appid","label":"应用ID","type":"string"},{"key":"secret_id","label":"Secret ID","type":"string"},{"key":"secret_key","label":"Secret Key","type":"string"},{"key":"output_dir","label":"输出目录","type":"string"}]', 4, 1, NOW(), 1, NOW());
-- 添加腾讯语音合成模型供应器
delete from `ai_model_provider` where id = 'SYSTEM_TTS_TencentTTS';
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
('SYSTEM_TTS_TencentTTS', 'TTS', 'tencent', '腾讯语音合成', '[{"key":"appid","label":"应用ID","type":"string"},{"key":"secret_id","label":"Secret ID","type":"string"},{"key":"secret_key","label":"Secret Key","type":"string"},{"key":"output_dir","label":"输出目录","type":"string"},{"key":"region","label":"区域","type":"string"},{"key":"voice","label":"音色ID","type":"string"}]', 5, 1, NOW(), 1, NOW());
-- 添加腾讯语音合成音色
delete from `ai_tts_voice` where id = 'TTS_TencentTTS0001';
INSERT INTO `ai_tts_voice` VALUES ('TTS_TencentTTS0001', 'TTS_TencentTTS', '智瑜', '101001', '中文', NULL, NULL, 1, NULL, NULL, NULL, NULL);

View file

@ -23,13 +23,6 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/2025_tts_voive.sql path: classpath:db/changelog/2025_tts_voive.sql
- changeSet:
id: 202504082210
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504082210.sql
- changeSet: - changeSet:
id: 202504082211 id: 202504082211
author: John author: John
@ -37,13 +30,6 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202504082211.sql path: classpath:db/changelog/202504082211.sql
- changeSet:
id: 202504092313
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504092313.sql
- changeSet: - changeSet:
id: 202504092335 id: 202504092335
author: John author: John
@ -51,3 +37,38 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202504092335.sql path: classpath:db/changelog/202504092335.sql
- changeSet:
id: 202504112044
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504112044.sql
- changeSet:
id: 202504112058
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504112058.sql
- changeSet:
id: 202504151206
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504151206.sql
- changeSet:
id: 202504181536
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504181536.sql
- changeSet:
id: 202504211118
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504211118.sql

View file

@ -40,3 +40,7 @@
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false 10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F 10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
10041=\u8BBE\u5907\u672A\u627E\u5230
10042={0}

View file

@ -40,3 +40,7 @@
10037=Parameter value must be a valid number 10037=Parameter value must be a valid number
10038=Parameter value must be true or false 10038=Parameter value must be true or false
10039=Parameter value must be a valid JSON array format 10039=Parameter value must be a valid JSON array format
10040=Parameter value must be a valid JSON format
10041=Device not found
10042={0}

View file

@ -40,3 +40,7 @@
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false 10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F 10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
10041=\u8BBE\u5907\u672A\u627E\u5230
10042={0}

View file

@ -40,3 +40,7 @@
10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57 10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57
10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false 10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false
10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F 10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F
10040=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
10041=\u8A2D\u5099\u672A\u627E\u5230
10042={0}

View file

@ -33,3 +33,5 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230
ota.device.need.bind={0}

View file

@ -32,3 +32,5 @@ timbre.ttsModelId.require=The TTS model ID of the timbre cannot be empty
timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty
timbre.voiceDemo.require=The voice demo of the timbre cannot be empty timbre.voiceDemo.require=The voice demo of the timbre cannot be empty
ota.device.not.found=Device not found
ota.device.need.bind={0}

View file

@ -32,3 +32,5 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u9375\u4E0D\u53EF\u4EE5\u7
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653E\u5730\u5740\u4E0D\u53EF\u4EE5\u70BA\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653E\u5730\u5740\u4E0D\u53EF\u4EE5\u70BA\u7A7A
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
ota.device.need.bind={0}

View file

@ -31,3 +31,6 @@ timbre.remark.require=\u97F3\u8272\u7684\u5907\u6CE8\u4E0D\u53EF\u4EE5\u4E3A\u7A
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
ota.device.need.bind={0}

View file

@ -77,7 +77,12 @@
</div> </div>
<div style="display: flex;justify-content: center;"> <div style="display: flex;justify-content: center;">
<el-button type="primary" @click="confirm" class="save-btn"> <el-button
type="primary"
@click="confirm"
class="save-btn"
:loading="saving"
:disabled="saving">
保存 保存
</el-button> </el-button>
</div> </div>
@ -94,6 +99,7 @@ export default {
}, },
data() { data() {
return { return {
saving: false,
providers: [], providers: [],
dialogVisible: false, dialogVisible: false,
providersLoaded: false, providersLoaded: false,
@ -175,6 +181,7 @@ export default {
}, },
handleClose() { handleClose() {
this.saving = false;
this.$emit('update:visible', false); this.$emit('update:visible', false);
}, },
initDynamicConfig() { initDynamicConfig() {
@ -185,8 +192,11 @@ export default {
this.formData.configJson = newConfig; this.formData.configJson = newConfig;
}, },
confirm() { confirm() {
this.saving = true;
if (!this.formData.supplier) { if (!this.formData.supplier) {
this.$message.error('请选择供应器'); this.$message.error('请选择供应器');
this.saving = false;
return; return;
} }
@ -206,11 +216,18 @@ export default {
} }
}; };
try {
this.$emit('confirm', submitData); this.$emit('confirm', submitData);
this.$emit('update:visible', false); this.$emit('update:visible', false);
this.resetForm(); this.resetForm();
} catch (e) {
console.error(e);
} finally {
this.saving = false;
}
}, },
resetForm() { resetForm() {
this.saving = false;
this.formData = { this.formData = {
modelName: '', modelName: '',
modelCode: '', modelCode: '',

View file

@ -11,7 +11,7 @@
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> 智慧体名称: <div style="color: red;display: inline-block;">*</div> 智能体名称:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input ref="inputRef" placeholder="请输入智能体名称.." v-model="wisdomBodyName" @keyup.enter.native="confirm" /> <el-input ref="inputRef" placeholder="请输入智能体名称.." v-model="wisdomBodyName" @keyup.enter.native="confirm" />

View file

@ -23,12 +23,6 @@
<div class="settings-btn" @click="handleConfigure"> <div class="settings-btn" @click="handleConfigure">
配置角色 配置角色
</div> </div>
<!-- <div class="settings-btn">-->
<!-- 声纹识别-->
<!-- </div>-->
<!-- <div class="settings-btn">-->
<!-- 历史对话-->
<!-- </div>-->
<div class="settings-btn" @click="handleDeviceManage"> <div class="settings-btn" @click="handleDeviceManage">
设备管理({{ device.deviceCount }}) 设备管理({{ device.deviceCount }})
</div> </div>
@ -80,7 +74,7 @@ export default {
.settings-btn { .settings-btn {
font-weight: 500; font-weight: 500;
font-size: 10px; font-size: 12px;
color: #5778ff; color: #5778ff;
background: #e6ebff; background: #e6ebff;
width: auto; width: auto;
@ -95,7 +89,7 @@ export default {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
margin-top: 15px; margin-top: 15px;
font-size: 10px; font-size: 12px;
color: #979db1; color: #979db1;
font-weight: 400; font-weight: 400;
} }

View file

@ -32,12 +32,6 @@
:style="{ filter: $route.path === '/params-management' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/params-management' ? 'brightness(0) invert(1)' : 'None' }" />
参数管理 参数管理
</div> </div>
<div v-if="isSuperAdmin" class="equipment-management"
:class="{ 'active-tab': $route.path === '/ota-management' }" @click="goOtaManagement">
<img loading="lazy" alt="" src="@/assets/header/firmware_update.png"
:style="{ filter: $route.path === '/ota-management' ? 'brightness(0) invert(1)' : 'None' }" />
OTA管理
</div>
</div> </div>
<!-- 右侧元素 --> <!-- 右侧元素 -->
@ -111,9 +105,6 @@ export default {
goParamManagement() { goParamManagement() {
this.$router.push('/params-management') this.$router.push('/params-management')
}, },
goOtaManagement() {
this.$router.push('/ota-management')
},
// 获取用户信息 // 获取用户信息
fetchUserInfo() { fetchUserInfo() {
userApi.getUserInfo(({ data }) => { userApi.getUserInfo(({ data }) => {
@ -179,7 +170,7 @@ export default {
.header { .header {
background: #f6fcfe66; background: #f6fcfe66;
border: 1px solid #fff; border: 1px solid #fff;
height: 53px !important; height: 63px !important;
min-width: 900px; min-width: 900px;
/* 设置最小宽度防止过度压缩 */ /* 设置最小宽度防止过度压缩 */
overflow: hidden; overflow: hidden;
@ -206,7 +197,7 @@ export default {
} }
.brand-img { .brand-img {
height: 18px; height: 20px;
} }
.header-center { .header-center {
@ -228,13 +219,13 @@ export default {
.equipment-management { .equipment-management {
padding: 0 9px; padding: 0 9px;
width: 82px; width: px;
height: 24px; height: 30px;
border-radius: 12px; border-radius: 15px;
background: #deeafe; background: #deeafe;
display: flex; display: flex;
justify-content: center; justify-content: center;
font-size: 10px; font-size: 14px;
font-weight: 500; font-weight: 500;
gap: 7px; gap: 7px;
color: #3d4566; color: #3d4566;
@ -244,6 +235,7 @@ export default {
cursor: pointer; cursor: pointer;
flex-shrink: 0; flex-shrink: 0;
/* 防止导航按钮被压缩 */ /* 防止导航按钮被压缩 */
padding: 0px 15px;
} }
.equipment-management.active-tab { .equipment-management.active-tab {

View file

@ -76,7 +76,12 @@
</div> </div>
<div style="display: flex;justify-content: center;"> <div style="display: flex;justify-content: center;">
<el-button type="primary" @click="handleSave" class="save-btn"> <el-button
type="primary"
@click="handleSave"
class="save-btn"
:loading="saving"
:disabled="saving">
保存 保存
</el-button> </el-button>
</div> </div>
@ -102,6 +107,7 @@ export default {
dialogVisible: this.visible, dialogVisible: this.visible,
providers: [], providers: [],
providersLoaded: false, providersLoaded: false,
saving: false,
allProvidersData: null, allProvidersData: null,
pendingProviderType: null, pendingProviderType: null,
pendingModelData: null, pendingModelData: null,
@ -195,6 +201,8 @@ export default {
} }
}, },
handleSave() { handleSave() {
this.saving = true; // 开始保存加载
const provideCode = this.form.configJson.type; const provideCode = this.form.configJson.type;
const formData = { const formData = {
id: this.modelData.id, id: this.modelData.id,
@ -209,8 +217,19 @@ export default {
...this.form.configJson, ...this.form.configJson,
} }
}; };
this.$emit("save", { provideCode, formData });
this.dialogVisible = false; this.$emit("save", {
provideCode,
formData,
done: () => {
this.saving = false; // 保存完成后回调
}
});
// 如果父组件不处理done回调,3秒后自动关闭加载状态
setTimeout(() => {
this.saving = false;
}, 3000);
}, },
loadProviders() { loadProviders() {
if (this.providersLoaded) return; if (this.providersLoaded) return;

View file

@ -40,7 +40,12 @@
</el-form> </el-form>
<div class="dialog-footer"> <div class="dialog-footer">
<el-button type="primary" @click="submit" class="save-btn"> <el-button
type="primary"
@click="submit"
class="save-btn"
:loading="saving"
:disabled="saving">
保存 保存
</el-button> </el-button>
<el-button @click="cancel" class="cancel-btn"> <el-button @click="cancel" class="cancel-btn">
@ -76,6 +81,7 @@ export default {
data() { data() {
return { return {
dialogKey: Date.now(), dialogKey: Date.now(),
saving: false,
valueTypeOptions: [ valueTypeOptions: [
{ value: 'string', label: '字符串(string)' }, { value: 'string', label: '字符串(string)' },
{ value: 'number', label: '数字(number)' }, { value: 'number', label: '数字(number)' },
@ -100,11 +106,22 @@ export default {
submit() { submit() {
this.$refs.form.validate((valid) => { this.$refs.form.validate((valid) => {
if (valid) { if (valid) {
this.$emit('submit', this.form); this.saving = true; // 开始加载
this.$emit('submit', {
form: this.form,
done: () => {
this.saving = false; // 加载完成
}
});
setTimeout(() => {
this.saving = false;
}, 3000);
} }
}); });
}, },
cancel() { cancel() {
this.saving = false; // 取消时重置状态
this.$emit('cancel'); this.$emit('cancel');
} }
}, },

View file

@ -20,7 +20,10 @@
style="width: 100%;" style="width: 100%;"
class="data-table" class="data-table"
header-row-class-name="table-header" header-row-class-name="table-header"
:fit="true"> :fit="true"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)">
<el-table-column label="选择" width="50" align="center"> <el-table-column label="选择" width="50" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
@ -187,13 +190,13 @@ export default {
}, },
methods: { methods: {
loadData() { loadData() {
this.loading = true;
const params = { const params = {
ttsModelId: this.ttsModelId, ttsModelId: this.ttsModelId,
page: this.currentPage, page: this.currentPage,
limit: this.pageSize, limit: this.pageSize,
name: this.searchQuery name: this.searchQuery
}; };
Api.timbre.getVoiceList(params, (data) => { Api.timbre.getVoiceList(params, (data) => {
if (data.code === 0) { if (data.code === 0) {
this.ttsModels = data.data.list this.ttsModels = data.data.list
@ -216,12 +219,14 @@ export default {
showClose: true showClose: true
}); });
} }
this.loading = false;
}, (err) => { }, (err) => {
console.error('加载失败:', err); console.error('加载失败:', err);
this.$message.error({ this.$message.error({
message: '加载音色数据失败', message: '加载音色数据失败',
showClose: true showClose: true
}); });
this.loading = false;
}); });
}, },

View file

@ -20,7 +20,11 @@
:data="paginatedDeviceList" :data="paginatedDeviceList"
@selection-change="handleSelectionChange" @selection-change="handleSelectionChange"
class="transparent-table" class="transparent-table"
:header-cell-class-name="headerCellClassName"> :header-cell-class-name="headerCellClassName"
v-loading="loading"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)">
<el-table-column type="selection" align="center" width="120"></el-table-column> <el-table-column type="selection" align="center" width="120"></el-table-column>
<el-table-column label="设备型号" prop="model" align="center"></el-table-column> <el-table-column label="设备型号" prop="model" align="center"></el-table-column>
<el-table-column label="固件版本" prop="firmwareVersion" align="center" ></el-table-column> <el-table-column label="固件版本" prop="firmwareVersion" align="center" ></el-table-column>

View file

@ -44,12 +44,22 @@
<!-- 右侧内容 --> <!-- 右侧内容 -->
<div class="content-area"> <div class="content-area">
<el-card class="model-card" shadow="never"> <el-card class="model-card" shadow="never">
<el-table ref="modelTable" style="width: 100%" :header-cell-style="{ background: 'transparent' }" <el-table
:data="modelList" class="data-table" header-row-class-name="table-header" ref="modelTable"
:header-cell-class-name="headerCellClassName" @selection-change="handleSelectionChange"> style="width: 100%"
v-loading="loading"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)"
:header-cell-style="{ background: 'transparent' }"
:data="modelList"
class="data-table"
header-row-class-name="table-header"
:header-cell-class-name="headerCellClassName"
@selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center"></el-table-column> <el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column label="模型ID" prop="id" align="center"></el-table-column>
<el-table-column label="模型名称" prop="modelName" align="center"></el-table-column> <el-table-column label="模型名称" prop="modelName" align="center"></el-table-column>
<el-table-column label="模型编码" prop="modelCode" align="center"></el-table-column>
<el-table-column label="提供商" align="center"> <el-table-column label="提供商" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ scope.row.configJson.type || '未知' }} {{ scope.row.configJson.type || '未知' }}
@ -101,11 +111,7 @@
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
<el-option <el-option v-for="item in pageSizeOptions" :key="item" :label="`${item}条/页`" :value="item">
v-for="item in pageSizeOptions"
:key="item"
:label="`${item}条/页`"
:value="item">
</el-option> </el-option>
</el-select> </el-select>
@ -157,7 +163,8 @@ export default {
pageSize: 10, pageSize: 10,
total: 0, total: 0,
selectedModels: [], selectedModels: [],
isAllSelected: false isAllSelected: false,
loading: false
}; };
}, },
@ -301,9 +308,10 @@ export default {
this.currentPage = page; this.currentPage = page;
this.$refs.modelTable.clearSelection(); this.$refs.modelTable.clearSelection();
}, },
handleModelSave({ provideCode, formData }) { handleModelSave({ provideCode, formData, done }) {
const modelType = this.activeTab; const modelType = this.activeTab;
const id = formData.id; const id = formData.id;
Api.model.updateModel( Api.model.updateModel(
{ modelType, provideCode, id, formData }, { modelType, provideCode, id, formData },
({ data }) => { ({ data }) => {
@ -314,6 +322,7 @@ export default {
} else { } else {
this.$message.error(data.msg || '保存失败'); this.$message.error(data.msg || '保存失败');
} }
done && done(); // 调用done回调关闭加载状态
} }
); );
}, },
@ -385,6 +394,7 @@ export default {
// 获取模型配置列表 // 获取模型配置列表
loadData() { loadData() {
this.loading = true; // 开始加载
const params = { const params = {
modelType: this.activeTab, modelType: this.activeTab,
modelName: this.search, modelName: this.search,
@ -393,6 +403,7 @@ export default {
}; };
Api.model.getModelList(params, ({ data }) => { Api.model.getModelList(params, ({ data }) => {
this.loading = false; // 结束加载
if (data.code === 0) { if (data.code === 0) {
this.modelList = data.data.list; this.modelList = data.data.list;
this.total = data.data.total; this.total = data.data.total;
@ -606,6 +617,7 @@ export default {
color: #606266; color: #606266;
font-size: 14px; font-size: 14px;
} }
::v-deep .page-size-select .el-input__suffix { ::v-deep .page-size-select .el-input__suffix {
right: 6px; right: 6px;
width: 15px; width: 15px;
@ -623,6 +635,7 @@ export default {
justify-content: center; justify-content: center;
width: 100%; width: 100%;
} }
::v-deep .page-size-select .el-icon-arrow-up:before { ::v-deep .page-size-select .el-icon-arrow-up:before {
content: ""; content: "";
display: inline-block; display: inline-block;
@ -912,4 +925,21 @@ export default {
overflow-y: auto; overflow-y: auto;
} }
::v-deep .el-loading-mask {
background-color: rgba(255, 255, 255, 0.6) !important;
backdrop-filter: blur(2px);
}
::v-deep .el-loading-spinner .circular {
width: 28px;
height: 28px;
}
::v-deep .el-loading-spinner .path {
stroke: #6b8cff;
}
::v-deep .el-loading-text {
color: #6b8cff !important;
font-size: 14px;
margin-top: 8px;
}
</style> </style>

View file

@ -15,7 +15,14 @@
<div class="content-panel"> <div class="content-panel">
<div class="content-area"> <div class="content-area">
<el-card class="params-card" shadow="never"> <el-card class="params-card" shadow="never">
<el-table ref="paramsTable" :data="paramsList" class="transparent-table" <el-table
ref="paramsTable"
:data="paramsList"
class="transparent-table"
v-loading="loading"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)"
:header-cell-class-name="headerCellClassName"> :header-cell-class-name="headerCellClassName">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="选择" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
@ -92,6 +99,7 @@ export default {
searchCode: "", searchCode: "",
paramsList: [], paramsList: [],
currentPage: 1, currentPage: 1,
loading: false,
pageSize: 10, pageSize: 10,
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
total: 0, total: 0,
@ -138,6 +146,7 @@ export default {
this.fetchParams(); this.fetchParams();
}, },
fetchParams() { fetchParams() {
this.loading = true;
Api.admin.getParamsList( Api.admin.getParamsList(
{ {
page: this.currentPage, page: this.currentPage,
@ -145,6 +154,7 @@ export default {
paramCode: this.searchCode, paramCode: this.searchCode,
}, },
({ data }) => { ({ data }) => {
this.loading = false;
if (data.code === 0) { if (data.code === 0) {
this.paramsList = data.data.list.map(item => ({ this.paramsList = data.data.list.map(item => ({
...item, ...item,
@ -185,7 +195,8 @@ export default {
this.paramForm = { ...row }; this.paramForm = { ...row };
this.dialogVisible = true; this.dialogVisible = true;
}, },
handleSubmit(form) {
handleSubmit({ form, done }) {
if (form.id) { if (form.id) {
// 编辑 // 编辑
Api.admin.updateParam(form, ({ data }) => { Api.admin.updateParam(form, ({ data }) => {
@ -197,6 +208,7 @@ export default {
this.dialogVisible = false; this.dialogVisible = false;
this.fetchParams(); this.fetchParams();
} }
done && done();
}); });
} else { } else {
// 新增 // 新增
@ -209,6 +221,7 @@ export default {
this.dialogVisible = false; this.dialogVisible = false;
this.fetchParams(); this.fetchParams();
} }
done && done();
}); });
} }
}, },
@ -656,4 +669,25 @@ export default {
max-height: calc(var(--table-max-height) - 40px); max-height: calc(var(--table-max-height) - 40px);
} }
} }
:deep(.el-loading-mask) {
background-color: rgba(255, 255, 255, 0.6) !important;
backdrop-filter: blur(2px);
}
:deep(.el-loading-spinner .circular) {
width: 28px;
height: 28px;
}
:deep(.el-loading-spinner .path) {
stroke: #6b8cff;
}
:deep(.el-loading-text) {
color: #6b8cff !important;
font-size: 14px;
margin-top: 8px;
}
</style> </style>

View file

@ -15,7 +15,14 @@
<div class="content-panel"> <div class="content-panel">
<div class="content-area"> <div class="content-area">
<el-card class="user-card" shadow="never"> <el-card class="user-card" shadow="never">
<el-table ref="userTable" :data="userList" class="transparent-table"> <el-table
ref="userTable"
:data="userList"
class="transparent-table"
v-loading="loading"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="选择" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
@ -103,7 +110,8 @@ export default {
currentPage: 1, currentPage: 1,
pageSize: 10, pageSize: 10,
total: 0, total: 0,
isAllSelected: false isAllSelected: false,
loading: false,
}; };
}, },
created() { created() {
@ -137,6 +145,7 @@ export default {
}, },
fetchUsers() { fetchUsers() {
this.loading = true;
Api.admin.getUserList( Api.admin.getUserList(
{ {
page: this.currentPage, page: this.currentPage,
@ -144,6 +153,7 @@ export default {
mobile: this.searchPhone, mobile: this.searchPhone,
}, },
({ data }) => { ({ data }) => {
this.loading = false; // 结束加载
if (data.code === 0) { if (data.code === 0) {
this.userList = data.data.list.map(item => ({ this.userList = data.data.list.map(item => ({
...item, ...item,
@ -682,5 +692,21 @@ export default {
} }
} }
:deep(.el-loading-mask) {
background-color: rgba(255, 255, 255, 0.6) !important;
backdrop-filter: blur(2px);
}
:deep(.el-loading-spinner .circular) {
width: 28px;
height: 28px;
}
:deep(.el-loading-spinner .path) {
stroke: #6b8cff;
}
:deep(.el-loading-text) {
color: #6b8cff !important;
font-size: 14px;
margin-top: 8px;
}
</style> </style>

View file

@ -31,8 +31,30 @@
</div> </div>
</div> </div>
<div class="device-list-container"> <div class="device-list-container">
<DeviceItem v-for="(item, index) in devices" :key="index" :device="item" @configure="goToRoleConfig" <template v-if="isLoading">
@deviceManage="handleDeviceManage" @delete="handleDeleteAgent" /> <div
v-for="i in skeletonCount"
:key="'skeleton-'+i"
class="skeleton-item"
>
<div class="skeleton-image"></div>
<div class="skeleton-content">
<div class="skeleton-line"></div>
<div class="skeleton-line-short"></div>
</div>
</div>
</template>
<template v-else>
<DeviceItem
v-for="(item, index) in devices"
:key="index"
:device="item"
@configure="goToRoleConfig"
@deviceManage="handleDeviceManage"
@delete="handleDeleteAgent"
/>
</template>
</div> </div>
</div> </div>
<AddWisdomBodyDialog :visible.sync="addDeviceDialogVisible" @confirm="handleWisdomBodyAdded" /> <AddWisdomBodyDialog :visible.sync="addDeviceDialogVisible" @confirm="handleWisdomBodyAdded" />
@ -60,7 +82,9 @@ export default {
devices: [], devices: [],
originalDevices: [], originalDevices: [],
isSearching: false, isSearching: false,
searchRegex: null searchRegex: null,
isLoading: true,
skeletonCount: localStorage.getItem('skeletonCount') || 8,
} }
}, },
@ -109,12 +133,26 @@ export default {
}, },
// 获取智能体列表 // 获取智能体列表
fetchAgentList() { fetchAgentList() {
this.isLoading = true;
Api.agent.getAgentList(({ data }) => { Api.agent.getAgentList(({ data }) => {
if (data?.data) {
this.originalDevices = data.data.map(item => ({ this.originalDevices = data.data.map(item => ({
...item, ...item,
agentId: item.id // 字段映射 agentId: item.id
})); }));
this.handleSearchReset(); // 重置搜索状态
// 动态设置骨架屏数量(可选)
this.skeletonCount = Math.min(
Math.max(this.originalDevices.length, 3), // 最少3个
10 // 最多10个
);
this.handleSearchReset();
}
this.isLoading = false;
}, (error) => {
console.error('Failed to fetch agent list:', error);
this.isLoading = false;
}); });
}, },
// 删除智能体 // 删除智能体
@ -199,7 +237,7 @@ export default {
.hi-hint { .hi-hint {
font-weight: 400; font-weight: 400;
font-size: 10px; font-size: 12px;
text-align: left; text-align: left;
color: #818cae; color: #818cae;
margin-left: 75px; margin-left: 75px;
@ -220,7 +258,7 @@ export default {
border-radius: 17px; border-radius: 17px;
background: #5778ff; background: #5778ff;
color: #fff; color: #fff;
font-size: 10px; font-size: 14px;
font-weight: 500; font-weight: 500;
text-align: center; text-align: center;
line-height: 34px; line-height: 34px;
@ -262,6 +300,65 @@ export default {
/* 居中显示 */ /* 居中显示 */
} }
/* 骨架屏动画 */
@keyframes shimmer {
100% { transform: translateX(100%); }
}
.skeleton-item {
background: #fff;
border-radius: 8px;
padding: 20px;
height: 120px;
position: relative;
overflow: hidden;
margin-bottom: 20px;
}
.skeleton-image {
width: 80px;
height: 80px;
background: #f0f2f5;
border-radius: 4px;
float: left;
position: relative;
overflow: hidden;
}
.skeleton-content {
margin-left: 100px;
}
.skeleton-line {
height: 16px;
background: #f0f2f5;
border-radius: 4px;
margin-bottom: 12px;
width: 70%;
position: relative;
overflow: hidden;
}
.skeleton-line-short {
height: 12px;
background: #f0f2f5;
border-radius: 4px;
width: 50%;
}
.skeleton-item::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 100%;
background: linear-gradient(
90deg,
rgba(255,255,255,0),
rgba(255,255,255,0.3),
rgba(255,255,255,0)
);
animation: shimmer 1.5s infinite;
}
</style> </style>

View file

@ -15,6 +15,9 @@
<img loading="lazy" src="@/assets/home/setting-user.png" alt=""> <img loading="lazy" src="@/assets/home/setting-user.png" alt="">
</div> </div>
<span class="header-title">{{ form.agentName }}</span> <span class="header-title">{{ form.agentName }}</span>
<button class="custom-close-btn" @click="goToHome">
×
</button>
</div> </div>
<div class="divider"></div> <div class="divider"></div>
@ -165,6 +168,9 @@ export default {
} }
}, },
methods: { methods: {
goToHome() {
this.$router.push('/home');
},
saveConfig() { saveConfig() {
const configData = { const configData = {
agentCode: this.form.agentCode, agentCode: this.form.agentCode,
@ -423,6 +429,7 @@ export default {
} }
.config-header { .config-header {
position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 13px; gap: 13px;
@ -560,8 +567,35 @@ export default {
background: none; background: none;
position: absolute; position: absolute;
font-size: 12px; font-size: 12px;
bottom: -10px; bottom: -10%;
right: 21px; right: 3%;
}
.custom-close-btn {
position: absolute;
top: 25%;
right: 0;
transform: translateY(-50%);
width: 35px;
height: 35px;
border-radius: 50%;
border: 2px solid #cfcfcf;
background: none;
font-size: 30px;
font-weight: lighter;
color: #cfcfcf;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
padding: 0;
outline: none;
}
.custom-close-btn:hover {
color: #409EFF;
border-color: #409EFF;
} }
</style> </style>

View file

@ -7,6 +7,7 @@ from core.utils.util import check_ffmpeg_installed
TAG = __name__ TAG = __name__
async def wait_for_exit(): async def wait_for_exit():
"""Windows 和 Linux 兼容的退出监听""" """Windows 和 Linux 兼容的退出监听"""
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
@ -19,10 +20,12 @@ async def wait_for_exit():
# Linux/macOS: 用 signal 监听 Ctrl + C # Linux/macOS: 用 signal 监听 Ctrl + C
def stop(): def stop():
stop_event.set() stop_event.set()
loop.add_signal_handler(signal.SIGINT, stop) loop.add_signal_handler(signal.SIGINT, stop)
loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程 loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
await stop_event.wait() await stop_event.wait()
async def main(): async def main():
check_config_file() check_config_file()
check_ffmpeg_installed() check_ffmpeg_installed()
@ -44,6 +47,7 @@ async def main():
pass pass
print("服务器已关闭,程序退出。") print("服务器已关闭,程序退出。")
if __name__ == "__main__": if __name__ == "__main__":
try: try:
asyncio.run(main()) asyncio.run(main())

View file

@ -52,7 +52,7 @@ enable_stop_tts_notify: false
# 说完话是否开启提示音,音效地址 # 说完话是否开启提示音,音效地址
stop_tts_notify_voice: "config/assets/tts_notify.mp3" stop_tts_notify_voice: "config/assets/tts_notify.mp3"
CMD_exit: exit_commands:
- "退出" - "退出"
- "关闭" - "关闭"
@ -147,7 +147,7 @@ selected_module:
Memory: nomem Memory: nomem
# 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。 # 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
# 不想开通意图识别,就设置成:nointent # 不想开通意图识别,就设置成:nointent
# 意图识别可使用intent_llm,如果你的LLM是DifyLLM或CozeLLM,建议使用这个。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作 # 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作
# 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令 # 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令
# 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028 # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028
Intent: function_call Intent: function_call
@ -163,7 +163,7 @@ Intent:
type: intent_llm type: intent_llm
# 配备意图识别独立的思考模型 # 配备意图识别独立的思考模型
# 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
# 如果你的selected_module.LLM选择了DifyLLM或CozeLLM,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM # 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
llm: ChatGLMLLM llm: ChatGLMLLM
function_call: function_call:
# 不需要动type # 不需要动type
@ -222,6 +222,7 @@ ASR:
output_dir: tmp/ output_dir: tmp/
VAD: VAD:
SileroVAD: SileroVAD:
type: silero
threshold: 0.5 threshold: 0.5
model_dir: models/snakers4_silero-vad model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些 min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些

Binary file not shown.

View file

@ -1,9 +1,34 @@
import os import os
import sys import sys
from loguru import logger from loguru import logger
from config.settings import load_config from config.config_loader import load_config
SERVER_VERSION = "0.2.1" SERVER_VERSION = "0.3.9"
def get_module_abbreviation(module_name, module_dict):
"""获取模块名称的缩写,如果为空则返回00"""
return (
module_dict.get(module_name, "")[:2] if module_dict.get(module_name) else "00"
)
def build_module_string(selected_module):
"""构建模块字符串"""
return (
get_module_abbreviation("VAD", selected_module)
+ get_module_abbreviation("ASR", selected_module)
+ get_module_abbreviation("LLM", selected_module)
+ get_module_abbreviation("TTS", selected_module)
+ get_module_abbreviation("Memory", selected_module)
+ get_module_abbreviation("Intent", selected_module)
)
def formatter(record):
"""为没有 tag 的日志添加默认值"""
record["extra"].setdefault("tag", record["name"])
return record["message"]
def setup_logging(): def setup_logging():
@ -18,11 +43,7 @@ def setup_logging():
"log_format_file", "log_format_file",
"{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}", "{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}",
) )
selected_module_str = build_module_string(config.get("selected_module", {}))
selected_module = config.get("selected_module")
selected_module_str = "".join(
[value[0] + value[1] for key, value in selected_module.items()]
)
log_format = log_format.replace("{version}", SERVER_VERSION) log_format = log_format.replace("{version}", SERVER_VERSION)
log_format = log_format.replace("{selected_module}", selected_module_str) log_format = log_format.replace("{selected_module}", selected_module_str)
@ -41,9 +62,14 @@ def setup_logging():
logger.remove() logger.remove()
# 输出到控制台 # 输出到控制台
logger.add(sys.stdout, format=log_format, level=log_level) logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
# 输出到文件 # 输出到文件
logger.add(os.path.join(log_dir, log_file), format=log_format_file, level=log_level) logger.add(
os.path.join(log_dir, log_file),
format=log_format_file,
level=log_level,
filter=formatter,
)
return logger return logger

View file

@ -1,241 +0,0 @@
import os
import time
import yaml
from config.logger import setup_logging
from typing import Dict, Any, Optional
from copy import deepcopy
from core.utils.util import get_project_dir
from core.utils import llm, tts
from core.utils.lock_manager import FileLockManager
TAG = __name__
class PrivateConfig:
def __init__(self, device_id: str, default_config: Dict[str, Any], auth_code_gen=None):
self.device_id = device_id
self.default_config = default_config
self.config_path = get_project_dir() + 'data/.private_config.yaml'
self.logger = setup_logging()
self.private_config = {}
self.auth_code_gen = auth_code_gen
self.lock_manager = FileLockManager()
async def load_or_create(self):
try:
await self.lock_manager.acquire_lock(self.config_path)
try:
if os.path.exists(self.config_path):
with open(self.config_path, 'r', encoding='utf-8') as f:
all_configs = yaml.safe_load(f) or {}
else:
all_configs = {}
if self.device_id not in all_configs:
# Get selected module names
selected_modules = self.default_config['selected_module']
selected_tts = selected_modules['TTS']
selected_llm = selected_modules['LLM']
selected_asr = selected_modules['ASR']
selected_vad = selected_modules['VAD']
# 生成认证码
auth_code = None
if self.auth_code_gen:
auth_code = self.auth_code_gen.generate_code()
# Initialize device config with only necessary configurations
device_config = {
'selected_module': deepcopy(selected_modules),
'prompt': self.default_config['prompt'],
'LLM': {
selected_llm: deepcopy(self.default_config['LLM'][selected_llm])
},
'TTS': {
selected_tts: deepcopy(self.default_config['TTS'][selected_tts])
},
'ASR': {
selected_asr: deepcopy(self.default_config['ASR'][selected_asr])
},
'VAD': {
selected_vad: deepcopy(self.default_config['VAD'][selected_vad])
},
'auth_code': auth_code # 添加认证码字段
}
all_configs[self.device_id] = device_config
# Save updated configs
with open(self.config_path, 'w', encoding='utf-8') as f:
yaml.dump(all_configs, f, allow_unicode=True)
self.private_config = all_configs[self.device_id]
finally:
self.lock_manager.release_lock(self.config_path)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error handling private config: {e}")
self.private_config = {}
async def update_config(self, selected_modules: Dict[str, str], prompt: str, nickname: str) -> bool:
"""更新设备配置
Args:
selected_modules: 选择的模块配置,格式如 {'LLM': 'AliLLM', 'TTS': 'EdgeTTS',...}
prompt: 提示词配置
Returns:
bool: 更新是否成功
"""
try:
await self.lock_manager.acquire_lock(self.config_path)
try:
# Read main config to get full module configurations
main_config = self.default_config
# Create new device config
device_config = {
'selected_module': selected_modules,
'prompt': prompt,
'nickname': nickname,
}
if self.private_config.get('last_chat_time'):
device_config['last_chat_time'] = self.private_config['last_chat_time']
if self.private_config.get('owner'):
device_config['owner'] = self.private_config['owner']
# Copy full module configurations from main config
for module_type, selected_name in selected_modules.items():
if selected_name and selected_name in main_config.get(module_type, {}):
device_config[module_type] = {
selected_name: main_config[module_type][selected_name]
}
# Read all configs
if os.path.exists(self.config_path):
with open(self.config_path, 'r', encoding='utf-8') as f:
all_configs = yaml.safe_load(f) or {}
else:
all_configs = {}
# Update device config
all_configs[self.device_id] = device_config
self.private_config = device_config
# Save back to file
with open(self.config_path, 'w', encoding='utf-8') as f:
yaml.dump(all_configs, f, allow_unicode=True)
return True
finally:
self.lock_manager.release_lock(self.config_path)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error updating config: {e}")
return False
async def delete_config(self) -> bool:
"""删除设备配置
Returns:
bool: 删除是否成功
"""
try:
await self.lock_manager.acquire_lock(self.config_path)
try:
# 读取所有配置
if os.path.exists(self.config_path):
with open(self.config_path, 'r', encoding='utf-8') as f:
all_configs = yaml.safe_load(f) or {}
else:
return False
# 删除设备配置
if self.device_id in all_configs:
del all_configs[self.device_id]
# 保存更新后的配置
with open(self.config_path, 'w', encoding='utf-8') as f:
yaml.dump(all_configs, f, allow_unicode=True)
self.private_config = {}
return True
return False
finally:
self.lock_manager.release_lock(self.config_path)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error deleting config: {e}")
return False
def create_private_instances(self):
# 判断存在私有配置,并且self.device_id在私有配置中
if not self.private_config:
self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id)
return None, None
"""创建私有处理模块实例"""
config = self.private_config
selected_modules = config['selected_module']
return (
llm.create_instance(
selected_modules["LLM"]
if not 'type' in config["LLM"][selected_modules["LLM"]]
else
config["LLM"][selected_modules["LLM"]]['type'],
config["LLM"][selected_modules["LLM"]],
),
tts.create_instance(
selected_modules["TTS"]
if not 'type' in config["TTS"][selected_modules["TTS"]]
else
config["TTS"][selected_modules["TTS"]]["type"],
config["TTS"][selected_modules["TTS"]],
self.default_config.get("delete_audio", True) # Using default_config for global settings
)
)
async def update_last_chat_time(self, timestamp=None):
"""更新设备最近一次的聊天时间
Args:
timestamp: 指定的时间戳,不传则使用当前时间
"""
if not self.private_config:
self.logger.bind(tag=TAG).error("Private config not found")
return False
try:
await self.lock_manager.acquire_lock(self.config_path)
try:
if timestamp is None:
timestamp = int(time.time())
self.private_config['last_chat_time'] = timestamp
# 读取所有配置
with open(self.config_path, 'r', encoding='utf-8') as f:
all_configs = yaml.safe_load(f) or {}
# 更新当前设备配置
all_configs[self.device_id] = self.private_config
# 保存回文件
with open(self.config_path, 'w', encoding='utf-8') as f:
yaml.dump(all_configs, f, allow_unicode=True)
return True
finally:
self.lock_manager.release_lock(self.config_path)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error updating last chat time: {e}")
return False
def get_auth_code(self) -> str:
"""获取设备的认证码
Returns:
str: 认证码,如果没有返回空字符串
"""
return self.private_config.get('auth_code', '')
def get_owner(self) -> Optional[str]:
"""获取设备当前所有者"""
return self.private_config.get('owner')

View file

@ -1,82 +1,11 @@
import os import os
import argparse
from ruamel.yaml import YAML
from collections.abc import Mapping from collections.abc import Mapping
from core.utils.util import read_config, get_project_dir from config.config_loader import read_config, get_project_dir, load_config
default_config_file = "config.yaml" default_config_file = "config.yaml"
def ensure_directories(config): def find_missing_keys(new_config, old_config, parent_key=""):
"""确保所有配置路径存在"""
dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录
# 日志文件目录
log_dir = config.get('log', {}).get('log_dir', 'tmp')
dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录
for module in ['ASR', 'TTS']:
for provider in config.get(module, {}).values():
output_dir = provider.get('output_dir', '')
if output_dir:
dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录
selected_modules = config.get('selected_module', {})
for module_type in ['ASR', 'LLM', 'TTS']:
selected_provider = selected_modules.get(module_type)
if not selected_provider:
continue
provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get('output_dir')
if output_dir:
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
# 统一创建目录(保留原data目录创建)
for dir_path in dirs_to_create:
try:
os.makedirs(dir_path, exist_ok=True)
except PermissionError:
print(f"警告:无法创建目录 {dir_path},请检查写入权限")
def get_config_file():
global default_config_file
"""获取配置文件路径,优先使用私有配置文件(若存在)。
Returns:
str: 配置文件路径(相对路径或默认路径)
"""
config_file = default_config_file
if os.path.exists(get_project_dir() + "data/." + default_config_file):
config_file = "data/." + default_config_file
return config_file
def load_config():
"""加载配置文件"""
parser = argparse.ArgumentParser(description="Server configuration")
config_file = get_config_file()
parser.add_argument("--config_path", type=str, default=config_file)
args = parser.parse_args()
config = read_config(args.config_path)
# 初始化目录
ensure_directories(config)
return config
def update_config(config):
yaml = YAML()
yaml.preserve_quotes = True
"""将配置保存到YAML文件"""
with open(get_config_file(), 'w') as f:
yaml.dump(config, f)
def find_missing_keys(new_config, old_config, parent_key=''):
""" """
递归查找缺失的配置项 递归查找缺失的配置项
返回格式:[缺失配置路径] 返回格式:[缺失配置路径]
@ -98,28 +27,36 @@ def find_missing_keys(new_config, old_config, parent_key=''):
# 递归检查嵌套字典 # 递归检查嵌套字典
if isinstance(value, Mapping): if isinstance(value, Mapping):
sub_missing = find_missing_keys( sub_missing = find_missing_keys(
value, value, old_config[key], parent_key=full_path
old_config[key],
parent_key=full_path
) )
missing_keys.extend(sub_missing) missing_keys.extend(sub_missing)
return missing_keys return missing_keys
def check_config_file(): def check_config_file():
old_config_file = get_config_file() old_config_file = get_project_dir() + "data/." + default_config_file
global default_config_file if not os.path.exists(old_config_file):
if not 'data' in old_config_file:
return return
old_config = read_config(get_project_dir() + old_config_file) old_config = load_config()
new_config = read_config(get_project_dir() + default_config_file) new_config = read_config(get_project_dir() + default_config_file)
# 查找缺失的配置项 # 查找缺失的配置项
missing_keys = find_missing_keys(new_config, old_config) missing_keys = find_missing_keys(new_config, old_config)
read_config_from_api = old_config.get("read_config_from_api", False)
if read_config_from_api:
old_config_origin = read_config(old_config_file)
if old_config_origin.get("selected_module") is not None:
missing_keys_str = "\n".join(f"- {key}" for key in missing_keys)
error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n"
error_msg += "\n建议您:\n"
error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n"
error_msg += "2、按教程配置好接口地址和密钥\n"
raise ValueError(error_msg)
return
if missing_keys: if missing_keys:
missing_keys_str = "\n".join(f"- {key}" for key in missing_keys)
error_msg = "您的配置文件太旧了,缺少了:\n" error_msg = "您的配置文件太旧了,缺少了:\n"
error_msg += "\n".join(f"- {key}" for key in missing_keys) error_msg += missing_keys_str
error_msg += "\n建议您:\n" error_msg += "\n建议您:\n"
error_msg += "1、备份data/.config.yaml文件\n" error_msg += "1、备份data/.config.yaml文件\n"
error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n" error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"

View file

@ -1,4 +1,5 @@
import os import os
import copy
import json import json
import uuid import uuid
import time import time
@ -17,16 +18,18 @@ from core.utils.util import (
get_string_no_punctuation_or_emoji, get_string_no_punctuation_or_emoji,
extract_json_from_string, extract_json_from_string,
get_ip_info, get_ip_info,
initialize_modules,
) )
from concurrent.futures import ThreadPoolExecutor, TimeoutError from concurrent.futures import ThreadPoolExecutor, TimeoutError
from core.handle.sendAudioHandle import sendAudioMessage from core.handle.sendAudioHandle import sendAudioMessage
from core.handle.receiveAudioHandle import handleAudioMessage from core.handle.receiveAudioHandle import handleAudioMessage
from core.handle.functionHandler import FunctionHandler from core.handle.functionHandler import FunctionHandler
from plugins_func.register import Action, ActionResponse from plugins_func.register import Action, ActionResponse
from config.private_config import PrivateConfig
from core.auth import AuthMiddleware, AuthenticationError from core.auth import AuthMiddleware, AuthenticationError
from core.utils.auth_code_gen import AuthCodeGenerator
from core.mcp.manager import MCPManager from core.mcp.manager import MCPManager
from config.config_loader import get_private_config_from_api
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
from core.utils.output_counter import add_device_output
TAG = __name__ TAG = __name__
@ -41,10 +44,13 @@ class ConnectionHandler:
def __init__( def __init__(
self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent
): ):
self.config = config self.config = copy.deepcopy(config)
self.logger = setup_logging() self.logger = setup_logging()
self.auth = AuthMiddleware(config) self.auth = AuthMiddleware(config)
self.need_bind = False
self.bind_code = None
self.websocket = None self.websocket = None
self.headers = None self.headers = None
self.client_ip = None self.client_ip = None
@ -52,6 +58,7 @@ class ConnectionHandler:
self.session_id = None self.session_id = None
self.prompt = None self.prompt = None
self.welcome_msg = None self.welcome_msg = None
self.max_output_size = 0
# 客户端状态相关 # 客户端状态相关
self.client_abort = False self.client_abort = False
@ -95,24 +102,45 @@ class ConnectionHandler:
self.iot_descriptors = {} self.iot_descriptors = {}
self.func_handler = None self.func_handler = None
self.cmd_exit = self.config["CMD_exit"] self.cmd_exit = self.config["exit_commands"]
self.max_cmd_length = 0 self.max_cmd_length = 0
for cmd in self.cmd_exit: for cmd in self.cmd_exit:
if len(cmd) > self.max_cmd_length: if len(cmd) > self.max_cmd_length:
self.max_cmd_length = len(cmd) self.max_cmd_length = len(cmd)
self.private_config = None
self.auth_code_gen = AuthCodeGenerator.get_instance()
self.is_device_verified = False # 添加设备验证状态标志
self.close_after_chat = False # 是否在聊天结束后关闭连接 self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = False self.use_function_call_mode = False
if self.config["selected_module"]["Intent"] == "function_call":
self.use_function_call_mode = True self.timeout_task = None
self.timeout_seconds = (
int(self.config.get("close_connection_no_voice_time", 120)) + 60
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
async def handle_connection(self, ws): async def handle_connection(self, ws):
try: try:
# 获取并验证headers # 获取并验证headers
self.headers = dict(ws.request.headers) self.headers = dict(ws.request.headers)
if self.headers.get("device-id", None) is None:
# 尝试从 URL 的查询参数中获取 device-id
from urllib.parse import parse_qs, urlparse
# 从 WebSocket 请求中获取路径
request_path = ws.request.path
if not request_path:
self.logger.bind(tag=TAG).error("无法获取请求路径")
return
parsed_url = urlparse(request_path)
query_params = parse_qs(parsed_url.query)
if "device-id" in query_params:
self.headers["device-id"] = query_params["device-id"][0]
self.headers["client-id"] = query_params["client-id"][0]
else:
self.logger.bind(tag=TAG).error(
"无法从请求头和URL查询参数中获取device-id"
)
return
# 获取客户端ip地址 # 获取客户端ip地址
self.client_ip = ws.remote_address[0] self.client_ip = ws.remote_address[0]
self.logger.bind(tag=TAG).info( self.logger.bind(tag=TAG).info(
@ -121,51 +149,22 @@ class ConnectionHandler:
# 进行认证 # 进行认证
await self.auth.authenticate(self.headers) await self.auth.authenticate(self.headers)
device_id = self.headers.get("device-id", None)
# 认证通过,继续处理 # 认证通过,继续处理
self.websocket = ws self.websocket = ws
self.session_id = str(uuid.uuid4()) self.session_id = str(uuid.uuid4())
# 启动超时检查任务
self.timeout_task = asyncio.create_task(self._check_timeout())
self.welcome_msg = self.config["xiaozhi"] self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id self.welcome_msg["session_id"] = self.session_id
await self.websocket.send(json.dumps(self.welcome_msg)) await self.websocket.send(json.dumps(self.welcome_msg))
# Load private configuration if device_id is provided
bUsePrivateConfig = self.config.get("use_private_config", False)
if bUsePrivateConfig and device_id:
try:
self.private_config = PrivateConfig(
device_id, self.config, self.auth_code_gen
)
await self.private_config.load_or_create()
# 判断是否已经绑定
owner = self.private_config.get_owner()
self.is_device_verified = owner is not None
if self.is_device_verified:
await self.private_config.update_last_chat_time()
llm, tts = self.private_config.create_private_instances()
if all([llm, tts]):
self.llm = llm
self.tts = tts
self.logger.bind(tag=TAG).info(
f"Loaded private config and instances for device {device_id}"
)
else:
self.logger.bind(tag=TAG).error(
f"Failed to create instances for device {device_id}"
)
self.private_config = None
except Exception as e:
self.logger.bind(tag=TAG).error(
f"Error initializing private config: {e}"
)
self.private_config = None
raise
# 获取差异化配置
private_config = self._initialize_private_config()
# 异步初始化 # 异步初始化
self.executor.submit(self._initialize_components) self.executor.submit(self._initialize_components, private_config)
# tts 消化线程 # tts 消化线程
self.tts_priority_thread = threading.Thread( self.tts_priority_thread = threading.Thread(
target=self._tts_priority_thread, daemon=True target=self._tts_priority_thread, daemon=True
@ -205,47 +204,184 @@ class ConnectionHandler:
async def _route_message(self, message): async def _route_message(self, message):
"""消息路由""" """消息路由"""
# 重置超时计时器
if self.timeout_task:
self.timeout_task.cancel()
self.timeout_task = asyncio.create_task(self._check_timeout())
if isinstance(message, str): if isinstance(message, str):
await handleTextMessage(self, message) await handleTextMessage(self, message)
elif isinstance(message, bytes): elif isinstance(message, bytes):
await handleAudioMessage(self, message) await handleAudioMessage(self, message)
def _initialize_components(self): def _initialize_components(self, private_config):
"""加载提示词""" """初始化组件"""
if private_config is not None:
self._initialize_models(private_config)
else:
self.prompt = self.config["prompt"] self.prompt = self.config["prompt"]
if self.private_config: self.change_system_prompt(self.prompt)
self.prompt = self.private_config.private_config.get("prompt", self.prompt)
self.dialogue.put(Message(role="system", content=self.prompt))
"""加载记忆""" """加载记忆"""
self._initialize_memory() self._initialize_memory()
"""加载意图识别""" """加载意图识别"""
self._initialize_intent() self._initialize_intent()
"""加载位置信息""" """加载位置信息"""
self.client_ip_info = get_ip_info(self.client_ip) self.client_ip_info = get_ip_info(self.client_ip, self.logger)
if self.client_ip_info is not None and "city" in self.client_ip_info: if self.client_ip_info is not None and "city" in self.client_ip_info:
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}") self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}" self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}"
self.dialogue.update_system_message(self.prompt) self.dialogue.update_system_message(self.prompt)
def _initialize_private_config(self):
read_config_from_api = self.config.get("read_config_from_api", False)
"""如果是从配置文件获取,则进行二次实例化"""
if not read_config_from_api:
return
"""从接口获取差异化的配置进行二次实例化,非全量重新实例化"""
try:
begin_time = time.time()
private_config = get_private_config_from_api(
self.config,
self.headers.get("device-id"),
self.headers.get("client-id", self.headers.get("device-id")),
)
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
self.logger.bind(tag=TAG).info(
f"{time.time() - begin_time} 秒,获取差异化配置成功: {private_config}"
)
except DeviceNotFoundException as e:
self.need_bind = True
private_config = {}
except DeviceBindException as e:
self.need_bind = True
self.bind_code = e.bind_code
private_config = {}
except Exception as e:
self.need_bind = True
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
private_config = {}
init_tts = False
if private_config.get("TTS", None) is not None:
init_tts = True
self.config["TTS"] = private_config["TTS"]
self.config["selected_module"]["TTS"] = private_config["selected_module"][
"TTS"
]
try:
modules = initialize_modules(
self.logger,
private_config,
False,
False,
False,
init_tts,
False,
False,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
if modules.get("prompt", None) is not None:
self.change_system_prompt(modules["prompt"])
private_config["prompt"] = None
return private_config
def _initialize_models(self, private_config):
init_vad, init_asr, init_llm, init_memory, init_intent = (
False,
False,
False,
False,
False,
)
if private_config.get("VAD", None) is not None:
init_vad = True
self.config["VAD"] = private_config["VAD"]
self.config["selected_module"]["VAD"] = private_config["selected_module"][
"VAD"
]
if private_config.get("ASR", None) is not None:
init_asr = True
self.config["ASR"] = private_config["ASR"]
self.config["selected_module"]["ASR"] = private_config["selected_module"][
"ASR"
]
if private_config.get("LLM", None) is not None:
init_llm = True
self.config["LLM"] = private_config["LLM"]
self.config["selected_module"]["LLM"] = private_config["selected_module"][
"LLM"
]
if private_config.get("Memory", None) is not None:
init_memory = True
self.config["Memory"] = private_config["Memory"]
self.config["selected_module"]["Memory"] = private_config[
"selected_module"
]["Memory"]
if private_config.get("Intent", None) is not None:
init_intent = True
self.config["Intent"] = private_config["Intent"]
self.config["selected_module"]["Intent"] = private_config[
"selected_module"
]["Intent"]
if private_config.get("device_max_output_size", None) is not None:
self.max_output_size = int(private_config["device_max_output_size"])
try:
modules = initialize_modules(
self.logger,
private_config,
init_vad,
init_asr,
init_llm,
False,
init_memory,
init_intent,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
modules = {}
if modules.get("vad", None) is not None:
self.vad = modules["vad"]
if modules.get("asr", None) is not None:
self.asr = modules["asr"]
if modules.get("llm", None) is not None:
self.llm = modules["llm"]
if modules.get("intent", None) is not None:
self.intent = modules["intent"]
if modules.get("memory", None) is not None:
self.memory = modules["memory"]
def _initialize_memory(self): def _initialize_memory(self):
"""初始化记忆模块""" """初始化记忆模块"""
device_id = self.headers.get("device-id", None) device_id = self.headers.get("device-id", None)
self.memory.init_memory(device_id, self.llm) self.memory.init_memory(device_id, self.llm)
def _initialize_intent(self): def _initialize_intent(self):
if (
self.config["Intent"][self.config["selected_module"]["Intent"]]["type"]
== "function_call"
):
self.use_function_call_mode = True
"""初始化意图识别模块""" """初始化意图识别模块"""
# 获取意图识别配置 # 获取意图识别配置
intent_config = self.config["Intent"] intent_config = self.config["Intent"]
intent_type = self.config["selected_module"]["Intent"] intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
"type"
]
# 如果使用 nointent,直接返回 # 如果使用 nointent,直接返回
if intent_type == "nointent": if intent_type == "nointent":
return return
# 使用 intent_llm 模式 # 使用 intent_llm 模式
elif intent_type == "intent_llm": elif intent_type == "intent_llm":
intent_llm_name = intent_config["intent_llm"]["llm"] intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
"llm"
]
if intent_llm_name and intent_llm_name in self.config["LLM"]: if intent_llm_name and intent_llm_name in self.config["LLM"]:
# 如果配置了专用LLM,则创建独立的LLM实例 # 如果配置了专用LLM,则创建独立的LLM实例
@ -276,46 +412,16 @@ class ConnectionHandler:
def change_system_prompt(self, prompt): def change_system_prompt(self, prompt):
self.prompt = prompt self.prompt = prompt
# 找到原来的role==system,替换原来的系统提示 # 更新系统prompt至上下文
for m in self.dialogue.dialogue: self.dialogue.update_system_message(self.prompt)
if m.role == "system":
m.content = prompt
async def _check_and_broadcast_auth_code(self):
"""检查设备绑定状态并广播认证码"""
if not self.private_config.get_owner():
auth_code = self.private_config.get_auth_code()
if auth_code:
# 发送验证码语音提示
text = f"请在后台输入验证码:{' '.join(auth_code)}"
self.recode_first_last_text(text)
future = self.executor.submit(self.speak_and_play, text)
self.tts_queue.put(future)
return False
return True
def isNeedAuth(self):
bUsePrivateConfig = self.config.get("use_private_config", False)
if not bUsePrivateConfig:
# 如果不使用私有配置,就不需要验证
return False
return not self.is_device_verified
def chat(self, query): def chat(self, query):
if self.isNeedAuth():
self.llm_finish_task = True
future = asyncio.run_coroutine_threadsafe(
self._check_and_broadcast_auth_code(), self.loop
)
future.result()
return True
self.dialogue.put(Message(role="user", content=query)) self.dialogue.put(Message(role="user", content=query))
response_message = [] response_message = []
processed_chars = 0 # 跟踪已处理的字符位置 processed_chars = 0 # 跟踪已处理的字符位置
try: try:
start_time = time.time()
# 使用带记忆的对话 # 使用带记忆的对话
future = asyncio.run_coroutine_threadsafe( future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop self.memory.query_memory(query), self.loop
@ -337,9 +443,6 @@ class ConnectionHandler:
if self.client_abort: if self.client_abort:
break break
end_time = time.time()
# self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
# 合并当前全部文本并处理未分割部分 # 合并当前全部文本并处理未分割部分
full_text = "".join(response_message) full_text = "".join(response_message)
current_text = full_text[processed_chars:] # 从未处理的位置开始 current_text = full_text[processed_chars:] # 从未处理的位置开始
@ -391,13 +494,6 @@ class ConnectionHandler:
def chat_with_function_calling(self, query, tool_call=False): def chat_with_function_calling(self, query, tool_call=False):
self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
"""Chat with function calling for intent detection using streaming""" """Chat with function calling for intent detection using streaming"""
if self.isNeedAuth():
self.llm_finish_task = True
future = asyncio.run_coroutine_threadsafe(
self._check_and_broadcast_auth_code(), self.loop
)
future.result()
return True
if not tool_call: if not tool_call:
self.dialogue.put(Message(role="user", content=query)) self.dialogue.put(Message(role="user", content=query))
@ -439,15 +535,18 @@ class ConnectionHandler:
function_id = None function_id = None
function_arguments = "" function_arguments = ""
content_arguments = "" content_arguments = ""
for response in llm_responses: for response in llm_responses:
content, tools_call = response content, tools_call = response
if "content" in response: if "content" in response:
content = response["content"] content = response["content"]
tools_call = None tools_call = None
if content is not None and len(content) > 0: if content is not None and len(content) > 0:
if len(response_message) <= 0 and ( content_arguments += content
content == "```" or "<tool_call>" in content
): if not tool_call_flag and content_arguments.startswith("<tool_call>"):
# print("content_arguments", content_arguments)
tool_call_flag = True tool_call_flag = True
if tools_call is not None: if tools_call is not None:
@ -460,9 +559,7 @@ class ConnectionHandler:
function_arguments += tools_call[0].function.arguments function_arguments += tools_call[0].function.arguments
if content is not None and len(content) > 0: if content is not None and len(content) > 0:
if tool_call_flag: if not tool_call_flag:
content_arguments += content
else:
response_message.append(content) response_message.append(content)
if self.client_abort: if self.client_abort:
@ -523,10 +620,9 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).error( self.logger.bind(tag=TAG).error(
f"function call error: {content_arguments}" f"function call error: {content_arguments}"
) )
else:
function_arguments = json.loads(function_arguments)
if not bHasError: if not bHasError:
self.logger.bind(tag=TAG).info( response_message.clear()
self.logger.bind(tag=TAG).debug(
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}" f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
) )
function_call_data = { function_call_data = {
@ -621,7 +717,6 @@ class ConnectionHandler:
self.tts_queue.put(future) self.tts_queue.put(future)
self.dialogue.put(Message(role="assistant", content=text)) self.dialogue.put(Message(role="assistant", content=text))
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
text = result.result text = result.result
if text is not None and len(text) > 0: if text is not None and len(text) > 0:
function_id = function_call_data["id"] function_id = function_call_data["id"]
@ -648,18 +743,14 @@ class ConnectionHandler:
Message(role="tool", tool_call_id=function_id, content=text) Message(role="tool", tool_call_id=function_id, content=text)
) )
self.chat_with_function_calling(text, tool_call=True) self.chat_with_function_calling(text, tool_call=True)
elif result.action == Action.NOTFOUND: elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
text = result.result text = result.result
self.recode_first_last_text(text, text_index) self.recode_first_last_text(text, text_index)
future = self.executor.submit(self.speak_and_play, text, text_index) future = self.executor.submit(self.speak_and_play, text, text_index)
self.tts_queue.put(future) self.tts_queue.put(future)
self.dialogue.put(Message(role="assistant", content=text)) self.dialogue.put(Message(role="assistant", content=text))
else: else:
text = result.result pass
self.recode_first_last_text(text, text_index)
future = self.executor.submit(self.speak_and_play, text, text_index)
self.tts_queue.put(future)
self.dialogue.put(Message(role="assistant", content=text))
def _tts_priority_thread(self): def _tts_priority_thread(self):
while not self.stop_event.is_set(): while not self.stop_event.is_set():
@ -677,7 +768,7 @@ class ConnectionHandler:
opus_datas, text_index, tts_file = [], 0, None opus_datas, text_index, tts_file = [], 0, None
try: try:
self.logger.bind(tag=TAG).debug("正在处理TTS任务...") self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
tts_timeout = self.config.get("tts_timeout", 10) tts_timeout = int(self.config.get("tts_timeout", 10))
tts_file, text, text_index = future.result(timeout=tts_timeout) tts_file, text, text_index = future.result(timeout=tts_timeout)
if text is None or len(text) <= 0: if text is None or len(text) <= 0:
self.logger.bind(tag=TAG).error( self.logger.bind(tag=TAG).error(
@ -757,6 +848,8 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).error(f"tts转换失败,{text}") self.logger.bind(tag=TAG).error(f"tts转换失败,{text}")
return None, text, text_index return None, text, text_index
self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}") self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}")
if self.max_output_size > 0:
add_device_output(self.headers.get("device-id"), len(text))
return tts_file, text, text_index return tts_file, text, text_index
def clearSpeakStatus(self): def clearSpeakStatus(self):
@ -773,6 +866,11 @@ class ConnectionHandler:
async def close(self, ws=None): async def close(self, ws=None):
"""资源清理方法""" """资源清理方法"""
# 取消超时任务
if self.timeout_task:
self.timeout_task.cancel()
self.timeout_task = None
# 清理MCP资源 # 清理MCP资源
if hasattr(self, "mcp_manager") and self.mcp_manager: if hasattr(self, "mcp_manager") and self.mcp_manager:
await self.mcp_manager.cleanup_all() await self.mcp_manager.cleanup_all()
@ -826,3 +924,15 @@ class ConnectionHandler:
self.close_after_chat = True self.close_after_chat = True
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
async def _check_timeout(self):
"""检查连接超时"""
try:
while not self.stop_event.is_set():
await asyncio.sleep(self.timeout_seconds)
if not self.stop_event.is_set():
self.logger.bind(tag=TAG).info("连接超时,准备关闭")
await self.close(self.websocket)
break
except Exception as e:
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")

View file

@ -57,7 +57,9 @@ class FunctionHandler:
def register_config_functions(self): def register_config_functions(self):
"""注册配置中的函数,可以不同客户端使用不同的配置""" """注册配置中的函数,可以不同客户端使用不同的配置"""
for func in self.config["Intent"]["function_call"].get("functions", []): for func in self.config["Intent"][self.config["selected_module"]["Intent"]].get(
"functions", []
):
self.function_registry.register_function(func) self.function_registry.register_function(func)
"""home assistant需要初始化提示词""" """home assistant需要初始化提示词"""
@ -77,7 +79,7 @@ class FunctionHandler:
func = funcItem.func func = funcItem.func
arguments = function_call_data["arguments"] arguments = function_call_data["arguments"]
arguments = json.loads(arguments) if arguments else {} arguments = json.loads(arguments) if arguments else {}
logger.bind(tag=TAG).info(f"调用函数: {function_name}, 参数: {arguments}") logger.bind(tag=TAG).debug(f"调用函数: {function_name}, 参数: {arguments}")
if ( if (
funcItem.type == ToolType.SYSTEM_CTL funcItem.type == ToolType.SYSTEM_CTL
or funcItem.type == ToolType.IOT_CTL or funcItem.type == ToolType.IOT_CTL

View file

@ -8,6 +8,7 @@ import os
import random import random
import time import time
TAG = __name__
logger = setup_logging() logger = setup_logging()
WAKEUP_CONFIG = { WAKEUP_CONFIG = {
@ -69,9 +70,19 @@ def getWakeupWordFile(file_name):
async def wakeupWordsResponse(conn): async def wakeupWordsResponse(conn):
wait_max_time = 5
while conn.llm is None or not conn.llm.response_no_stream:
await asyncio.sleep(1)
wait_max_time -= 1
if wait_max_time <= 0:
logger.bind(tag=TAG).error("连接对象没有llm")
return
"""唤醒词响应""" """唤醒词响应"""
wakeup_word = random.choice(WAKEUP_CONFIG["words"]) wakeup_word = random.choice(WAKEUP_CONFIG["words"])
result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word) result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word)
if result is None or result == "":
return
tts_file = await asyncio.to_thread(conn.tts.to_tts, result) tts_file = await asyncio.to_thread(conn.tts.to_tts, result)
if tts_file is not None and os.path.exists(tts_file): if tts_file is not None and os.path.exists(tts_file):

View file

@ -76,6 +76,11 @@ async def process_intent_result(conn, intent_result, original_text):
if function_name == "continue_chat": if function_name == "continue_chat":
return False return False
if function_name == "play_music":
funcItem = conn.func_handler.get_function(function_name)
if not funcItem:
conn.func_handler.function_registry.register_function("play_music")
function_args = None function_args = None
if "arguments" in intent_data["function_call"]: if "arguments" in intent_data["function_call"]:
function_args = intent_data["function_call"]["arguments"] function_args = intent_data["function_call"]["arguments"]

View file

@ -57,7 +57,7 @@ def create_iot_function(device_name, method_name, method_info):
response_failure = "操作失败" response_failure = "操作失败"
# 打印响应参数 # 打印响应参数
logger.bind(tag=TAG).info( logger.bind(tag=TAG).debug(
f"控制函数接收到的响应参数: success='{response_success}', failure='{response_failure}'" f"控制函数接收到的响应参数: success='{response_success}', failure='{response_failure}'"
) )
@ -144,8 +144,9 @@ class IotDescriptor:
self.methods = [] self.methods = []
# 根据描述创建属性 # 根据描述创建属性
if properties is not None:
for key, value in properties.items(): for key, value in properties.items():
property_item = globals()[key] = {} property_item = {}
property_item["name"] = key property_item["name"] = key
property_item["description"] = value["description"] property_item["description"] = value["description"]
if value["type"] == "number": if value["type"] == "number":
@ -157,19 +158,19 @@ class IotDescriptor:
self.properties.append(property_item) self.properties.append(property_item)
# 根据描述创建方法 # 根据描述创建方法
if methods is not None:
for key, value in methods.items(): for key, value in methods.items():
method = globals()[key] = {} method = {}
method["description"] = value["description"] method["description"] = value["description"]
method["name"] = key method["name"] = key
# 检查方法是否有参数
if "parameters" in value:
method["parameters"] = {}
for k, v in value["parameters"].items(): for k, v in value["parameters"].items():
method[k] = {} method["parameters"][k] = {
method[k]["description"] = v["description"] "description": v["description"],
if v["type"] == "number": "type": v["type"],
method[k]["value"] = 0 }
elif v["type"] == "boolean":
method[k]["value"] = False
else:
method[k]["value"] = ""
self.methods.append(method) self.methods.append(method)
@ -219,6 +220,11 @@ def register_device_type(descriptor):
func_name = f"{device_name.lower()}_{method_name.lower()}" func_name = f"{device_name.lower()}_{method_name.lower()}"
# 创建参数字典,添加原有参数 # 创建参数字典,添加原有参数
parameters = {}
required_params = []
# 如果方法有参数,则添加参数信息
if "parameters" in method_info:
parameters = { parameters = {
param_name: { param_name: {
"type": param_info["type"], "type": param_info["type"],
@ -226,6 +232,7 @@ def register_device_type(descriptor):
} }
for param_name, param_info in method_info["parameters"].items() for param_name, param_info in method_info["parameters"].items()
} }
required_params = list(method_info["parameters"].keys())
# 添加响应参数 # 添加响应参数
parameters.update( parameters.update(
@ -242,7 +249,6 @@ def register_device_type(descriptor):
) )
# 构建必须参数列表(原有参数 + 响应参数) # 构建必须参数列表(原有参数 + 响应参数)
required_params = list(method_info["parameters"].keys())
required_params.extend(["response_success", "response_failure"]) required_params.extend(["response_success", "response_failure"])
func_desc = { func_desc = {
@ -269,19 +275,36 @@ def register_device_type(descriptor):
# 用于接受前端设备推送的搜索iot描述 # 用于接受前端设备推送的搜索iot描述
async def handleIotDescriptors(conn, descriptors): async def handleIotDescriptors(conn, descriptors):
if not conn.use_function_call_mode:
return
wait_max_time = 5 wait_max_time = 5
while conn.func_handler is None or not conn.func_handler.finish_init: while conn.func_handler is None or not conn.func_handler.finish_init:
await asyncio.sleep(1) await asyncio.sleep(1)
wait_max_time -= 1 wait_max_time -= 1
if wait_max_time <= 0: if wait_max_time <= 0:
logger.bind(tag=TAG).error("连接对象没有func_handler") logger.bind(tag=TAG).debug("连接对象没有func_handler")
return return
"""处理物联网描述""" """处理物联网描述"""
functions_changed = False functions_changed = False
for descriptor in descriptors: for descriptor in descriptors:
# 如果descriptor没有properties和methods,则直接跳过
if "properties" not in descriptor and "methods" not in descriptor:
continue
# 处理缺失properties的情况
if "properties" not in descriptor:
descriptor["properties"] = {}
# 从methods中提取所有参数作为properties
if "methods" in descriptor:
for method_name, method_info in descriptor["methods"].items():
if "parameters" in method_info:
for param_name, param_info in method_info["parameters"].items():
# 将参数信息转换为属性信息
descriptor["properties"][param_name] = {
"description": param_info["description"],
"type": param_info["type"],
}
# 创建IOT设备描述符 # 创建IOT设备描述符
iot_descriptor = IotDescriptor( iot_descriptor = IotDescriptor(
descriptor["name"], descriptor["name"],
@ -375,19 +398,17 @@ async def send_iot_conn(conn, name, method_name, parameters):
for method in value.methods: for method in value.methods:
# 找到了方法 # 找到了方法
if method["name"] == method_name: if method["name"] == method_name:
await conn.websocket.send( # 构建命令对象
json.dumps( command = {
{
"type": "iot",
"commands": [
{
"name": name, "name": name,
"method": method_name, "method": method_name,
"parameters": parameters,
} }
],
} # 只有当参数不为空时才添加parameters字段
) if parameters:
) command["parameters"] = parameters
send_message = json.dumps({"type": "iot", "commands": [command]})
await conn.websocket.send(send_message)
logger.bind(tag=TAG).info(f"发送物联网指令: {send_message}")
return return
logger.bind(tag=TAG).error(f"未找到方法{method_name}") logger.bind(tag=TAG).error(f"未找到方法{method_name}")

View file

@ -3,6 +3,7 @@ import time
from core.utils.util import remove_punctuation_and_length from core.utils.util import remove_punctuation_and_length
from core.handle.sendAudioHandle import send_stt_message from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -35,9 +36,7 @@ async def handleAudioMessage(conn, audio):
if len(conn.asr_audio) < 15: if len(conn.asr_audio) < 15:
conn.asr_server_receive = True conn.asr_server_receive = True
else: else:
text, file_path = await conn.asr.speech_to_text( text, _ = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
conn.asr_audio, conn.session_id
)
logger.bind(tag=TAG).info(f"识别文本: {text}") logger.bind(tag=TAG).info(f"识别文本: {text}")
text_len, _ = remove_punctuation_and_length(text) text_len, _ = remove_punctuation_and_length(text)
if text_len > 0: if text_len > 0:
@ -49,6 +48,18 @@ async def handleAudioMessage(conn, audio):
async def startToChat(conn, text): async def startToChat(conn, text):
if conn.need_bind:
await check_bind_device(conn)
return
# 如果当日的输出字数大于限定的字数
if conn.max_output_size > 0:
if check_device_output_limit(
conn.headers.get("device-id"), conn.max_output_size
):
await max_out_size(conn)
return
# 首先进行意图分析 # 首先进行意图分析
intent_handled = await handle_user_intent(conn, text) intent_handled = await handle_user_intent(conn, text)
@ -71,8 +82,8 @@ async def no_voice_close_connect(conn):
conn.client_no_voice_last_time = time.time() * 1000 conn.client_no_voice_last_time = time.time() * 1000
else: else:
no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time
close_connection_no_voice_time = conn.config.get( close_connection_no_voice_time = int(
"close_connection_no_voice_time", 120 conn.config.get("close_connection_no_voice_time", 120)
) )
if ( if (
not conn.close_after_chat not conn.close_after_chat
@ -85,3 +96,56 @@ async def no_voice_close_connect(conn):
"请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。" "请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。"
) )
await startToChat(conn, prompt) await startToChat(conn, prompt)
async def max_out_size(conn):
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
await send_stt_message(conn, text)
conn.tts_first_text_index = 0
conn.tts_last_text_index = 0
conn.llm_finish_task = True
file_path = "config/assets/max_output_size.wav"
opus_packets, _ = conn.tts.audio_to_opus_data(file_path)
conn.audio_play_queue.put((opus_packets, text, 0))
conn.close_after_chat = True
async def check_bind_device(conn):
if conn.bind_code:
# 确保bind_code是6位数字
if len(conn.bind_code) != 6:
logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
text = "绑定码格式错误,请检查配置。"
await send_stt_message(conn, text)
return
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。"
await send_stt_message(conn, text)
conn.tts_first_text_index = 0
conn.tts_last_text_index = 6
conn.llm_finish_task = True
# 播放提示音
music_path = "config/assets/bind_code.wav"
opus_packets, _ = conn.tts.audio_to_opus_data(music_path)
conn.audio_play_queue.put((opus_packets, text, 0))
# 逐个播放数字
for i in range(6): # 确保只播放6位数字
try:
digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav"
num_packets, _ = conn.tts.audio_to_opus_data(num_path)
conn.audio_play_queue.put((num_packets, None, i + 1))
except Exception as e:
logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
continue
else:
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
await send_stt_message(conn, text)
conn.tts_first_text_index = 0
conn.tts_last_text_index = 0
conn.llm_finish_task = True
music_path = "config/assets/bind_not_found.wav"
opus_packets, _ = conn.tts.audio_to_opus_data(music_path)
conn.audio_play_queue.put((opus_packets, text, 0))

View file

@ -3,7 +3,6 @@ import json
import asyncio import asyncio
import time import time
from core.utils.util import ( from core.utils.util import (
remove_punctuation_and_length,
get_string_no_punctuation_or_emoji, get_string_no_punctuation_or_emoji,
) )

View file

@ -1,13 +1,15 @@
"""MCP服务管理器""" """MCP服务管理器"""
import os, json import os, json
from typing import Dict, Any, List from typing import Dict, Any, List
from .MCPClient import MCPClient from .MCPClient import MCPClient
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import get_project_dir from plugins_func.register import register_function, ToolType
from plugins_func.register import register_function, ActionResponse, Action, ToolType from config.config_loader import get_project_dir
TAG = __name__ TAG = __name__
class MCPManager: class MCPManager:
"""管理多个MCP服务的集中管理器""" """管理多个MCP服务的集中管理器"""
@ -17,10 +19,12 @@ class MCPManager:
""" """
self.conn = conn self.conn = conn
self.logger = setup_logging() self.logger = setup_logging()
self.config_path = get_project_dir() + 'data/.mcp_server_settings.json' self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
if os.path.exists(self.config_path) == False: if os.path.exists(self.config_path) == False:
self.config_path = "" self.config_path = ""
self.logger.bind(tag=TAG).warning(f"请检查mcp服务配置文件:data/.mcp_server_settings.json") self.logger.bind(tag=TAG).warning(
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
)
self.client: Dict[str, MCPClient] = {} self.client: Dict[str, MCPClient] = {}
self.tools = [] self.tools = []
@ -33,11 +37,13 @@ class MCPManager:
return {} return {}
try: try:
with open(self.config_path, 'r', encoding='utf-8') as f: with open(self.config_path, "r", encoding="utf-8") as f:
config = json.load(f) config = json.load(f)
return config.get('mcpServers', {}) return config.get("mcpServers", {})
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"Error loading MCP config from {self.config_path}: {e}") self.logger.bind(tag=TAG).error(
f"Error loading MCP config from {self.config_path}: {e}"
)
return {} return {}
async def initialize_servers(self) -> None: async def initialize_servers(self) -> None:
@ -45,7 +51,9 @@ class MCPManager:
config = self.load_config() config = self.load_config()
for name, srv_config in config.items(): for name, srv_config in config.items():
if not srv_config.get("command"): if not srv_config.get("command"):
self.logger.bind(tag=TAG).warning(f"Skipping server {name}: command not specified") self.logger.bind(tag=TAG).warning(
f"Skipping server {name}: command not specified"
)
continue continue
try: try:
@ -57,11 +65,17 @@ class MCPManager:
self.tools.extend(client_tools) self.tools.extend(client_tools)
for tool in client_tools: for tool in client_tools:
func_name = "mcp_" + tool["function"]["name"] func_name = "mcp_" + tool["function"]["name"]
register_function(func_name, tool, ToolType.MCP_CLIENT)(self.execute_tool) register_function(func_name, tool, ToolType.MCP_CLIENT)(
self.conn.func_handler.function_registry.register_function(func_name) self.execute_tool
)
self.conn.func_handler.function_registry.register_function(
func_name
)
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to initialize MCP server {name}: {e}") self.logger.bind(tag=TAG).error(
f"Failed to initialize MCP server {name}: {e}"
)
self.conn.func_handler.upload_functions_desc() self.conn.func_handler.upload_functions_desc()
def get_all_tools(self) -> List[Dict[str, Any]]: def get_all_tools(self) -> List[Dict[str, Any]]:
@ -79,7 +93,10 @@ class MCPManager:
bool: 是否是MCP工具 bool: 是否是MCP工具
""" """
for tool in self.tools: for tool in self.tools:
if tool.get("function") != None and tool["function"].get("name") == tool_name: if (
tool.get("function") != None
and tool["function"].get("name") == tool_name
):
return True return True
return False return False
@ -93,7 +110,9 @@ class MCPManager:
Raises: Raises:
ValueError: 工具未找到时抛出 ValueError: 工具未找到时抛出
""" """
self.logger.bind(tag=TAG).info(f"Executing tool {tool_name} with arguments: {arguments}") self.logger.bind(tag=TAG).info(
f"Executing tool {tool_name} with arguments: {arguments}"
)
for client in self.client.values(): for client in self.client.values():
if client.has_tool(tool_name): if client.has_tool(tool_name):
return await client.call_tool(tool_name, arguments) return await client.call_tool(tool_name, arguments)
@ -106,5 +125,7 @@ class MCPManager:
await client.cleanup() await client.cleanup()
self.logger.bind(tag=TAG).info(f"Cleaned up MCP client: {name}") self.logger.bind(tag=TAG).info(f"Cleaned up MCP client: {name}")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"Error cleaning up MCP client {name}: {e}") self.logger.bind(tag=TAG).error(
f"Error cleaning up MCP client {name}: {e}"
)
self.client.clear() self.client.clear()

View file

@ -35,4 +35,5 @@ class LLMProviderBase(ABC):
""" """
# For providers that don't support functions, just return regular response # For providers that don't support functions, just return regular response
for token in self.response(session_id, dialogue): for token in self.response(session_id, dialogue):
yield {"type": "content", "content": token} yield token, None

View file

@ -4,9 +4,11 @@ import json
import re import re
from core.providers.llm.base import LLMProviderBase from core.providers.llm.base import LLMProviderBase
import os import os
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py) # official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
from cozepy import COZE_CN_BASE_URL from cozepy import COZE_CN_BASE_URL
from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType # noqa from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType # noqa
from core.providers.llm.system_prompt import get_system_prompt_for_function
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -15,8 +17,8 @@ logger = setup_logging()
class LLMProvider(LLMProviderBase): class LLMProvider(LLMProviderBase):
def __init__(self, config): def __init__(self, config):
self.personal_access_token = config.get("personal_access_token") self.personal_access_token = config.get("personal_access_token")
self.bot_id = config.get("bot_id") self.bot_id = str(config.get("bot_id"))
self.user_id = config.get("user_id") self.user_id = str(config.get("user_id"))
self.session_conversation_map = {} # 存储session_id和conversation_id的映射 self.session_conversation_map = {} # 存储session_id和conversation_id的映射
def response(self, session_id, dialogue): def response(self, session_id, dialogue):
@ -30,10 +32,7 @@ class LLMProvider(LLMProviderBase):
# 如果没有找到conversation_id,则创建新的对话 # 如果没有找到conversation_id,则创建新的对话
if not conversation_id: if not conversation_id:
conversation = coze.conversations.create( conversation = coze.conversations.create(messages=[])
messages=[
]
)
conversation_id = conversation.id conversation_id = conversation.id
self.session_conversation_map[session_id] = conversation_id # 更新映射 self.session_conversation_map[session_id] = conversation_id # 更新映射
@ -48,3 +47,23 @@ class LLMProvider(LLMProviderBase):
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA: if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print(event.message.content, end="", flush=True) print(event.message.content, end="", flush=True)
yield event.message.content yield event.message.content
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1 :
if dialogue[-1]["role"] == "user":
dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"]
break
dialogue.pop()
for token in self.response(session_id, dialogue):
yield token, None

View file

@ -2,6 +2,7 @@ import json
from config.logger import setup_logging from config.logger import setup_logging
import requests import requests
from core.providers.llm.base import LLMProviderBase from core.providers.llm.base import LLMProviderBase
from core.providers.llm.system_prompt import get_system_prompt_for_function
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -58,7 +59,8 @@ class LLMProvider(LLMProviderBase):
self.session_conversation_map[session_id] = ( self.session_conversation_map[session_id] = (
conversation_id # 更新映射 conversation_id # 更新映射
) )
if event.get("answer"): # 过滤 message_replace 事件,此事件会全量推一次
if event.get("event") != "message_replace" and event.get("answer"):
yield event["answer"] yield event["answer"]
elif self.mode == "workflows/run": elif self.mode == "workflows/run":
for line in r.iter_lines(): for line in r.iter_lines():
@ -73,9 +75,30 @@ class LLMProvider(LLMProviderBase):
for line in r.iter_lines(): for line in r.iter_lines():
if line.startswith(b"data: "): if line.startswith(b"data: "):
event = json.loads(line[6:]) event = json.loads(line[6:])
if event.get("answer"): # 过滤 message_replace 事件,此事件会全量推一次
if event.get("event") != "message_replace" and event.get("answer"):
yield event["answer"] yield event["answer"]
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}") logger.bind(tag=TAG).error(f"Error in response generation: {e}")
yield "【服务响应异常】" yield "【服务响应异常】"
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1 :
if dialogue[-1]["role"] == "user":
dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"]
break
dialogue.pop()
for token in self.response(session_id, dialogue):
yield token, None

View file

@ -4,9 +4,11 @@ from core.providers.llm.base import LLMProviderBase
from config.logger import setup_logging from config.logger import setup_logging
import requests import requests
import json import json
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class LLMProvider(LLMProviderBase): class LLMProvider(LLMProviderBase):
def __init__(self, config): def __init__(self, config):
"""初始化Gemini LLM Provider""" """初始化Gemini LLM Provider"""
@ -62,19 +64,16 @@ class LLMProvider(LLMProviderBase):
role = "model" if msg["role"] == "assistant" else "user" role = "model" if msg["role"] == "assistant" else "user"
content = msg["content"].strip() content = msg["content"].strip()
if content: if content:
chat_history.append({ chat_history.append({"role": role, "parts": [{"text": content}]})
"role": role,
"parts": [{"text":content}]
})
# 获取当前消息 # 获取当前消息
current_msg = dialogue[-1]["content"] current_msg = dialogue[-1]["content"]
# 构建请求体 # 构建请求体
request_body = { request_body = {
"contents": chat_history + [{"role": "user", "parts": [{"text":current_msg}]}], "contents": chat_history
"generationConfig": self.generation_config + [{"role": "user", "parts": [{"text": current_msg}]}],
"generationConfig": self.generation_config,
} }
# 构建请求URL # 构建请求URL
@ -87,11 +86,17 @@ class LLMProvider(LLMProviderBase):
# 发送POST请求,经测试手动 request 无法使用 stream 模式 # 发送POST请求,经测试手动 request 无法使用 stream 模式
if self.proxies: if self.proxies:
response = requests.post(url, headers=headers, json=request_body, stream=False, proxies=self.proxies) response = requests.post(
url,
headers=headers,
json=request_body,
stream=False,
proxies=self.proxies,
)
try: try:
data = response.json() # 直接解析JSON data = response.json() # 直接解析JSON
if 'candidates' in data and data['candidates']: if "candidates" in data and data["candidates"]:
yield data['candidates'][0]['content']['parts'][0]['text'] yield data["candidates"][0]["content"]["parts"][0]["text"]
else: else:
yield "未找到候选回复。" yield "未找到候选回复。"
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
@ -104,13 +109,11 @@ class LLMProvider(LLMProviderBase):
# 发送消息并获取流式响应 # 发送消息并获取流式响应
response = chat.send_message( response = chat.send_message(
current_msg, current_msg, stream=True, generation_config=self.generation_config
stream=True,
generation_config=self.generation_config
) )
# 处理流式响应 # 处理流式响应
for chunk in response: for chunk in response:
if hasattr(chunk, 'text') and chunk.text: if hasattr(chunk, "text") and chunk.text:
yield chunk.text yield chunk.text
except Exception as e: except Exception as e:
@ -125,9 +128,6 @@ class LLMProvider(LLMProviderBase):
else: else:
yield f"【Gemini服务响应异常: {error_msg}】" yield f"【Gemini服务响应异常: {error_msg}】"
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
yield f"请求失败:{e}" yield f"请求失败:{e}"
except json.JSONDecodeError as e: except json.JSONDecodeError as e:

View file

@ -63,4 +63,4 @@ class LLMProvider(LLMProviderBase):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}") logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"} yield f"【Ollama服务响应异常: {str(e)}】", None

View file

@ -1,4 +1,5 @@
import openai import openai
from openai.types import CompletionUsage
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase from core.providers.llm.base import LLMProviderBase
@ -11,11 +12,19 @@ class LLMProvider(LLMProviderBase):
def __init__(self, config): def __init__(self, config):
self.model_name = config.get("model_name") self.model_name = config.get("model_name")
self.api_key = config.get("api_key") self.api_key = config.get("api_key")
if 'base_url' in config: if "base_url" in config:
self.base_url = config.get("base_url") self.base_url = config.get("base_url")
else: else:
self.base_url = config.get("url") self.base_url = config.get("url")
self.max_tokens = config.get("max_tokens", 500) max_tokens = config.get("max_tokens")
if max_tokens is None or max_tokens == "":
max_tokens = 500
try:
max_tokens = int(max_tokens)
except (ValueError, TypeError):
max_tokens = 500
self.max_tokens = max_tokens
check_model_key("LLM", self.api_key) check_model_key("LLM", self.api_key)
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url) self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
@ -33,18 +42,22 @@ class LLMProvider(LLMProviderBase):
for chunk in responses: for chunk in responses:
try: try:
# 检查是否存在有效的choice且content不为空 # 检查是否存在有效的choice且content不为空
delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None delta = (
content = delta.content if hasattr(delta, 'content') else '' chunk.choices[0].delta
if getattr(chunk, "choices", None)
else None
)
content = delta.content if hasattr(delta, "content") else ""
except IndexError: except IndexError:
content = '' content = ""
if content: if content:
# 处理标签跨多个chunk的情况 # 处理标签跨多个chunk的情况
if '<think>' in content: if "<think>" in content:
is_active = False is_active = False
content = content.split('<think>')[0] content = content.split("<think>")[0]
if '</think>' in content: if "</think>" in content:
is_active = True is_active = True
content = content.split('</think>')[-1] content = content.split("</think>")[-1]
if is_active: if is_active:
yield content yield content
@ -54,15 +67,22 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None):
try: try:
stream = self.client.chat.completions.create( stream = self.client.chat.completions.create(
model=self.model_name, model=self.model_name, messages=dialogue, stream=True, tools=functions
messages=dialogue,
stream=True,
tools=functions
) )
for chunk in stream: for chunk in stream:
# 检查是否存在有效的choice且content不为空
if getattr(chunk, "choices", None):
yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls
# 存在 CompletionUsage 消息时,生成 Token 消耗 log
elif isinstance(getattr(chunk, 'usage', None), CompletionUsage):
usage_info = getattr(chunk, 'usage', None)
logger.bind(tag=TAG).info(
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"} yield f"【OpenAI服务响应异常: {e}】", None

View file

@ -6,6 +6,7 @@ from core.utils.util import check_model_key
TAG = __name__ TAG = __name__
class MemoryProvider(MemoryProviderBase): class MemoryProvider(MemoryProviderBase):
def __init__(self, config): def __init__(self, config):
super().__init__(config) super().__init__(config)
@ -35,9 +36,12 @@ class MemoryProvider(MemoryProviderBase):
# Format the content as a message list for mem0 # Format the content as a message list for mem0
messages = [ messages = [
{"role": message.role, "content": message.content} {"role": message.role, "content": message.content}
for message in msgs if message.role != "system" for message in msgs
if message.role != "system"
] ]
result = self.client.add(messages, user_id=self.role_id, output_format=self.api_version) result = self.client.add(
messages, user_id=self.role_id, output_format=self.api_version
)
logger.bind(tag=TAG).debug(f"Save memory result: {result}") logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
@ -48,25 +52,23 @@ class MemoryProvider(MemoryProviderBase):
return "" return ""
try: try:
results = self.client.search( results = self.client.search(
query, query, user_id=self.role_id, output_format=self.api_version
user_id=self.role_id,
output_format=self.api_version
) )
if not results or 'results' not in results: if not results or "results" not in results:
return "" return ""
# Format each memory entry with its update time up to minutes # Format each memory entry with its update time up to minutes
memories = [] memories = []
for entry in results['results']: for entry in results["results"]:
timestamp = entry.get('updated_at', '') timestamp = entry.get("updated_at", "")
if timestamp: if timestamp:
try: try:
# Parse and reformat the timestamp # Parse and reformat the timestamp
dt = timestamp.split('.')[0] # Remove milliseconds dt = timestamp.split(".")[0] # Remove milliseconds
formatted_time = dt.replace('T', ' ') formatted_time = dt.replace("T", " ")
except: except:
formatted_time = timestamp formatted_time = timestamp
memory = entry.get('memory', '') memory = entry.get("memory", "")
if timestamp and memory: if timestamp and memory:
# Store tuple of (timestamp, formatted_string) for sorting # Store tuple of (timestamp, formatted_string) for sorting
memories.append((timestamp, f"[{formatted_time}] {memory}")) memories.append((timestamp, f"[{formatted_time}] {memory}"))

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