feat(manager-api): western surface, provider policy, migrations, and seed test

- English OpenAPI metadata and auth/summary copy

- Downstream provider allow-lists and agent/model filtering

- Append-only Liquibase cleanup plus fresh-DB LiquibaseWesternizationIntegrationTest
This commit is contained in:
lapy 2026-04-25 17:05:11 +01:00
parent c5ff101e66
commit eed2c0c144
327 changed files with 9057 additions and 6090 deletions

View file

@ -1,18 +1,17 @@
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
This document is for development purposes. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-docs)
# 项目介绍
# Project Introduction
manager-api 该项目基于SpringBoot框架开发。
manager-api is developed based on the SpringBoot framework.
开发使用代码编辑器,导入项目时,选择`manager-api`文件夹作为项目目录
When developing with a code editor, select the `manager-api` folder as the project directory when importing the project.
# 开发环境
# Development Environment
JDK 21
Maven 3.8+
MySQL 8.0+
Redis 5.0+
Vue 3.x
# 接口文档
启动后打开:http://localhost:8002/xiaozhi/doc.html
# API Documentation
After starting, open: http://localhost:8002/xiaozhi/doc.html

View file

@ -6,7 +6,7 @@
<packaging>jar</packaging>
<version>0.0.1</version>
<name>xiaozhi-esp32-api</name>
<description>小智后台管理系统</description>
<description>Xiaozhi Backend Management System</description>
<parent>
<groupId>org.springframework.boot</groupId>
@ -30,8 +30,7 @@
<captcha.version>1.6.2</captcha.version>
<guava.version>33.0.0-jre</guava.version>
<liquibase-core.version>4.20.0</liquibase-core.version>
<aliyun-sms-version>4.1.0</aliyun-sms-version>
<okio-version>3.4.0</okio-version>
<twilio-version>8.31.1</twilio-version>
</properties>
<dependencies>
@ -70,7 +69,7 @@
</exclusion>
</exclusions>
</dependency>
<!-- 验证码工具包 -->
<!-- Captcha toolkit -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
@ -158,7 +157,7 @@
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql驱动 -->
<!-- MySQL driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
@ -193,13 +192,13 @@
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<!--knife4j -->
<!-- knife4j -->
<dependency>
<groupId>com.github.xingfudeshi</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<!-- BouncyCastle SM2加密 -->
<!-- BouncyCastle SM2 encryption -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
@ -211,7 +210,7 @@
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<!-- 日常工具包 -->
<!-- Daily utility toolkit -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
@ -220,32 +219,33 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- 阿里云短信sdk -->
<!-- Twilio SMS SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>${aliyun-sms-version}</version>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>${twilio-version}</version>
</dependency>
<!-- 阿里云短信sdk使用的okio:1.15.0版本有安全漏洞:GHSA-w33c-445m-f8w7 现在升级成3.4.0安全版本-->
<!-- H2 Database for testing -->
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>${okio-version}</version>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 阿里云maven仓库 -->
<!-- Maven Central repository -->
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public/</url>
<id>central</id>
<name>Maven Central</name>
<url>https://repo1.maven.org/maven2/</url>
<releases>
<enabled>true</enabled>
</releases>
@ -253,9 +253,9 @@
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public/</url>
<id>central</id>
<name>Maven Central</name>
<url>https://repo1.maven.org/maven2/</url>
<releases>
<enabled>true</enabled>
</releases>
@ -270,12 +270,36 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>21</source>
<target>21</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
<skipTests>false</skipTests>
</configuration>
</plugin>
</plugins>

View file

@ -0,0 +1,46 @@
# Knowledge Base Module Full Integration Test Report
## 1. Test Background
This report covers deep integration testing for 14 endpoints across `KnowledgeBaseController` and `KnowledgeFilesController`. The main focus was aligning local shadow-database state with the remote RAGFlow service, improving deserialization compatibility, and hardening batch-operation safety.
## 2. Core Bug Fixes
| Module | Issue Type | Resolution | Verification |
| :--- | :--- | :--- | :--- |
| **DTO** | `positions` deserialization failed | Promoted the field type from `List<Integer>` to `Object` to support nested arrays | ✅ Verified |
| **DTO** | Date format incompatibility | Switched RAGFlow RFC 1123 date fields to `String` passthrough values | ✅ Verified |
| **Request** | Retrieval request rejected `null` values | Added `@JsonInclude(NON_NULL)` so optional null fields are skipped during serialization | ✅ Verified |
| **Sync** | State self-healing deadlock | Added a low-frequency 60-second sync path for `CANCEL` and `FAIL` states to avoid logic lock-in | ✅ Verified |
| **Logic** | Incorrect delete guard | Updated the guard from `status="1"` to `run="RUNNING"` | ✅ Verified |
## 3. Endpoint Coverage
### KnowledgeBaseController (7/7)
- [x] Paginated list (`GET /datasets`)
- [x] Detail lookup (`GET /datasets/{id}`)
- [x] Create knowledge base (`POST /datasets`)
- [x] Update configuration (`PUT /datasets/{id}`)
- [x] Hard delete (`DELETE /datasets/{id}`)
- [x] Batch delete (`DELETE /datasets/batch`)
- [x] Retrieve model list (`GET /datasets/rag-models`)
### KnowledgeFilesController (7/7)
- [x] Document list and sync (`GET /datasets/{id}/documents`)
- [x] Status-filtered query (`GET /datasets/{id}/documents/status/{s}`)
- [x] Document upload (`POST /datasets/{id}/documents`)
- [x] Trigger parsing (`POST /datasets/{id}/chunks`)
- [x] Chunk detail lookup (`GET /datasets/{id}/documents/{docId}/chunks`)
- [x] Retrieval test (`POST /datasets/{id}/retrieval-test`)
- [x] Batch delete documents (`DELETE /datasets/{id}/documents`)
## 4. Automated Audit Conclusion
The `comprehensive_audit.ps1` automation script simulated the full production flow: create -> upload -> parse -> sync -> retrieve -> delete.
- **Parse success rate**: 100%
- **Data accuracy**: DTO conversion completed without errors, and coordinate/score extraction behaved correctly
- **System safety**: the in-progress parsing guard worked as intended
- **Conclusion**: **Near production-ready**
---
*Report generated: 2026-02-13*
*Reviewed by: dora--1206563805@qq.com*

View file

@ -7,8 +7,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据过滤注解
* Copyright (c) 人人开源 All rights reserved.
* Data filter annotation
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Target(ElementType.METHOD)
@ -16,18 +16,18 @@ import java.lang.annotation.Target;
@Documented
public @interface DataFilter {
/**
* 表的别名
* Table alias
*/
String tableAlias() default "";
/**
* 用户ID
* User ID
*/
String userId() default "creator";
/**
* 部门ID
* Department ID
*/
String deptId() default "dept_id";
}
}

View file

@ -7,8 +7,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 操作日志注解
* Copyright (c) 人人开源 All rights reserved.
* Operation log annotation
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Target(ElementType.METHOD)

View file

@ -11,8 +11,8 @@ import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
/**
* Redis切面处理类
* Copyright (c) 人人开源 All rights reserved.
* Redis aspect processing class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Slf4j
@ -20,7 +20,7 @@ import xiaozhi.common.exception.RenException;
@Component
public class RedisAspect {
/**
* 是否开启redis缓存 true开启 false关闭
* Whether to enable redis cache true enable false disable
*/
@Value("${renren.redis.open}")
private boolean open;

View file

@ -22,15 +22,15 @@ public class AsyncConfig {
executor.setMaxPoolSize(4);
executor.setQueueCapacity(1000);
executor.setThreadNamePrefix("AsyncThread-");
// 设置拒绝策略:由调用线程执行
// Set rejection policy: execute by calling thread
executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// 如果线程池已满,则由调用线程执行
// If thread pool is full, execute by calling thread
r.run();
} catch (Exception e) {
throw new RuntimeException("执行异步任务失败", e);
throw new RuntimeException("Failed to execute async task", e);
}
}
});

View file

@ -11,8 +11,8 @@ import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerIntercept
import xiaozhi.common.interceptor.DataFilterInterceptor;
/**
* mybatis-plus配置
* Copyright (c) 人人开源 All rights reserved.
* mybatis-plus configuration
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Configuration
@ -21,16 +21,16 @@ public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 数据权限
// Data permission
mybatisPlusInterceptor.addInnerInterceptor(new DataFilterInterceptor());
// 分页插件
// Pagination plugin
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 乐观锁
// Optimistic lock
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 防止全表更新与删除
// Prevent full table update and delete
mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return mybatisPlusInterceptor;
}
}
}

View file

@ -7,7 +7,7 @@ import org.springframework.web.client.RestTemplate;
import java.time.Duration;
/**
* RestTemplate配置
* RestTemplate configuration
*/
@Configuration
public class RestTemplateConfig {

View file

@ -8,8 +8,8 @@ import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
/**
* Swagger配置
* Copyright (c) 人人开源 All rights reserved.
* Swagger configuration
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Configuration
@ -99,8 +99,8 @@ public class SwaggerConfig {
public OpenAPI customOpenAPI() {
return new OpenAPI().info(new Info()
.title("xiaozhi-esp32-manager-api")
.description("xiaozhi-esp32-manager-api文档")
.description("xiaozhi-esp32-manager-api documentation")
.version("3.0")
.termsOfService("https://127.0.0.1"));
}
}
}

View file

@ -3,17 +3,17 @@ package xiaozhi.common.constant;
import lombok.Getter;
/**
* 常量
* Copyright (c) 人人开源 All rights reserved.
* Shared constants.
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface Constant {
/**
* 成功
* Success.
*/
int SUCCESS = 1;
/**
* 失败
* Failure.
*/
int FAIL = 0;
/**
@ -21,138 +21,138 @@ public interface Constant {
*/
String OK = "OK";
/**
* 用户标识
* User identifier.
*/
String USER_KEY = "userId";
/**
* 菜单根节点标识
* Menu root-node identifier.
*/
Long MENU_ROOT = 0L;
/**
* 部门根节点标识
* Department root-node identifier.
*/
Long DEPT_ROOT = 0L;
/**
* 数据字典根节点标识
* Data-dictionary root-node identifier.
*/
Long DICT_ROOT = 0L;
/**
* 升序
* Ascending sort.
*/
String ASC = "asc";
/**
* 降序
* Descending sort.
*/
String DESC = "desc";
/**
* 创建时间字段名
* Create-time field name.
*/
String CREATE_DATE = "create_date";
/**
* 创建时间字段名
* Primary ID field name.
*/
String ID = "id";
/**
* 数据权限过滤
* Data-permission filter.
*/
String SQL_FILTER = "sqlFilter";
/**
* 当前页码
* Current page number.
*/
String PAGE = "page";
/**
* 每页显示记录数
* Page size.
*/
String LIMIT = "limit";
/**
* 排序字段
* Sort field.
*/
String ORDER_FIELD = "orderField";
/**
* 排序方式
* Sort direction.
*/
String ORDER = "order";
/**
* 请求头授权标识
* Authorization header name.
*/
String AUTHORIZATION = "Authorization";
/**
* 服务器密钥
* Server secret.
*/
String SERVER_SECRET = "server.secret";
/**
* SM2公钥
* SM2 public key.
*/
String SM2_PUBLIC_KEY = "server.public_key";
/**
* SM2私钥
* SM2 private key.
*/
String SM2_PRIVATE_KEY = "server.private_key";
/**
* websocket地址
* WebSocket URL.
*/
String SERVER_WEBSOCKET = "server.websocket";
/**
* mqtt gateway 配置
* MQTT gateway configuration.
*/
String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
/**
* ota地址
* OTA URL.
*/
String SERVER_OTA = "server.ota";
/**
* 是否允许用户注册
* Whether user registration is allowed.
*/
String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register";
/**
* 下发六位验证码时显示的控制面板地址
* Control-panel URL shown with the six-digit verification code.
*/
String SERVER_FRONTED_URL = "server.fronted_url";
/**
* 路径分割符
* Path separator.
*/
String FILE_EXTENSION_SEG = ".";
/**
* mcp接入点路径
* MCP endpoint path.
*/
String SERVER_MCP_ENDPOINT = "server.mcp_endpoint";
/**
* mcp接入点路径
* Voiceprint endpoint path.
*/
String SERVER_VOICE_PRINT = "server.voice_print";
/**
* mqtt密钥
* MQTT signature key.
*/
String SERVER_MQTT_SECRET = "server.mqtt_signature_key";
/**
* WebSocket认证开关
* WebSocket auth toggle.
*/
String SERVER_AUTH_ENABLED = "server.auth.enabled";
/**
* 无记忆
* No memory.
*/
String MEMORY_NO_MEM = "Memory_nomem";
/**
* 仅上报聊天记录(不总结记忆)
* Report chat history only, without memory summaries.
*/
String MEMORY_MEM_REPORT_ONLY = "Memory_mem_report_only";
@ -178,15 +178,15 @@ public interface Constant {
enum SysBaseParam {
/**
* ICP备案号
* ICP registration number.
*/
BEIAN_ICP_NUM("server.beian_icp_num"),
/**
* GA备案号
* GA registration number.
*/
BEIAN_GA_NUM("server.beian_ga_num"),
/**
* 系统名称
* System name.
*/
SERVER_NAME("server.name");
@ -202,23 +202,23 @@ public interface Constant {
}
/**
* 训练状态
* Training status.
*/
enum TrainStatus {
/**
* 未训练
* Not trained.
*/
NOT_TRAINED(0),
/**
* 训练中
* Training in progress.
*/
TRAINING(1),
/**
* 已训练
* Trained.
*/
TRAINED(2),
/**
* 训练失败
* Training failed.
*/
TRAIN_FAILED(3);
@ -234,31 +234,31 @@ public interface Constant {
}
/**
* 系统短信
* System SMS parameters
*/
enum SysMSMParam {
/**
* 阿里云授权keyID
* Twilio account SID
*/
ALIYUN_SMS_ACCESS_KEY_ID("aliyun.sms.access_key_id"),
TWILIO_SMS_ACCOUNT_SID("twilio.sms.account_sid"),
/**
* 阿里云授权密钥
* Twilio auth token
*/
ALIYUN_SMS_ACCESS_KEY_SECRET("aliyun.sms.access_key_secret"),
TWILIO_SMS_AUTH_TOKEN("twilio.sms.auth_token"),
/**
* 阿里云短信签名
* Twilio phone number (from)
*/
ALIYUN_SMS_SIGN_NAME("aliyun.sms.sign_name"),
TWILIO_SMS_PHONE_NUMBER("twilio.sms.phone_number"),
/**
* 阿里云短信模板
* Twilio SMS template message
*/
ALIYUN_SMS_SMS_CODE_TEMPLATE_CODE("aliyun.sms.sms_code_template_code"),
TWILIO_SMS_TEMPLATE_MESSAGE("twilio.sms.template_message"),
/**
* 单号码最大短信发送条数
* Max SMS per phone number per day
*/
SERVER_SMS_MAX_SEND_COUNT("server.sms_max_send_count"),
/**
* 是否开启手机注册
* Enable mobile registration
*/
SERVER_ENABLE_MOBILE_REGISTER("server.enable_mobile_register");
@ -274,19 +274,19 @@ public interface Constant {
}
/**
* 数据状态
* Data operation state.
*/
enum DataOperation {
/**
* 插入
* Inserted.
*/
INSERT("I"),
/**
* 已修改
* Updated.
*/
UPDATE("U"),
/**
* 已删除
* Deleted.
*/
DELETE("D");
@ -303,9 +303,9 @@ public interface Constant {
@Getter
enum ChatHistoryConfEnum {
IGNORE(0, "不记录"),
RECORD_TEXT(1, "记录文本"),
RECORD_TEXT_AUDIO(2, "文本音频都记录");
IGNORE(0, "Do not record"),
RECORD_TEXT(1, "Record text"),
RECORD_TEXT_AUDIO(2, "Record text and audio");
private final int code;
private final String name;
@ -317,21 +317,21 @@ public interface Constant {
}
/**
* 版本号
* Version number.
*/
public static final String VERSION = "0.9.2";
/**
* 无效固件URL
* Invalid firmware URL.
*/
String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL";
/**
* 字典类型
* Dictionary types.
*/
enum DictType {
/**
* 手机区号
* Phone country code.
*/
MOBILE_AREA("MOBILE_AREA");
@ -345,4 +345,4 @@ public interface Constant {
return value;
}
}
}
}

View file

@ -13,8 +13,8 @@ import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* 日期转换
* Copyright (c) 人人开源 All rights reserved.
* Date conversion
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Component
@ -53,11 +53,11 @@ public class DateConverter implements Converter<String, Date> {
}
/**
* 格式化日期
* Format date
*
* @param dateStr String 字符型日期
* @param format String 格式
* @return Date 日期
* @param dateStr String character date
* @param format String format
* @return Date date
*/
public Date parseDate(String dateStr, String format) {
Date date = null;

View file

@ -3,8 +3,8 @@ package xiaozhi.common.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 基础Dao
* Copyright (c) 人人开源 All rights reserved.
* Base Dao
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface BaseDao<T> extends BaseMapper<T> {

View file

@ -10,8 +10,8 @@ import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
/**
* 基础实体类,所有实体都需要继承
* Copyright (c) 人人开源 All rights reserved.
* Base entity class, all entities need to inherit from this
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@ -22,13 +22,13 @@ public abstract class BaseEntity implements Serializable {
@TableId
private Long id;
/**
* 创建者
* Creator
*/
@TableField(fill = FieldFill.INSERT)
private Long creator;
/**
* 创建时间
* Creation time
*/
@TableField(fill = FieldFill.INSERT)
private Date createDate;
}
}

View file

@ -1,11 +1,12 @@
package xiaozhi.common.exception;
/**
* 错误编码,由5位数字组成,前2位为模块编码,后3位为业务编码
* Error codes use five digits: the first two identify the module and the last
* three identify the business case.
* <p>
* 如:10001(10代表系统模块,001代表业务代码)
* Example: 10001 (10 = system module, 001 = business code)
* </p>
* Copyright (c) 人人开源 All rights reserved.
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface ErrorCode {
@ -44,7 +45,7 @@ public interface ErrorCode {
int DEL_MYSELF_ERROR = 10032;
int DEVICE_CAPTCHA_ERROR = 10033;
// 参数校验相关错误码
// Parameter validation error codes
int PARAM_VALUE_NULL = 10034;
int PARAM_TYPE_NULL = 10035;
int PARAM_TYPE_INVALID = 10036;
@ -56,7 +57,7 @@ public interface ErrorCode {
int OTA_DEVICE_NOT_FOUND = 10041;
int OTA_DEVICE_NEED_BIND = 10042;
// 新增错误编码
// Additional error codes
int DELETE_DATA_FAILED = 10043;
int USER_NOT_LOGIN = 10044;
int WEB_SOCKET_CONNECT_FAILED = 10045;
@ -67,7 +68,7 @@ public interface ErrorCode {
int TOKEN_GENERATE_ERROR = 10050;
int RESOURCE_NOT_FOUND = 10051;
// 新增错误编码
// Additional error codes
int DEFAULT_AGENT_NOT_FOUND = 10052;
int AGENT_NOT_FOUND = 10053;
int VOICEPRINT_API_NOT_CONFIGURED = 10054;
@ -80,180 +81,180 @@ public interface ErrorCode {
int ACTIVATION_CODE_EMPTY = 10061;
int ACTIVATION_CODE_ERROR = 10062;
int DEVICE_ALREADY_ACTIVATED = 10063;
// 默认模型删除错误
// Default model deletion error
int DEFAULT_MODEL_DELETE_ERROR = 10064;
// 登录相关错误码
int ADD_DATA_FAILED = 10065; // 新增数据失败
int UPDATE_DATA_FAILED = 10066; // 修改数据失败
int SMS_CAPTCHA_ERROR = 10067; // 短信验证码错误
int MOBILE_REGISTER_DISABLED = 10068; // 未开启手机注册
int USERNAME_NOT_PHONE = 10069; // 用户名不是手机号码
int PHONE_ALREADY_REGISTERED = 10070; // 手机号码已注册
int PHONE_NOT_REGISTERED = 10071; // 手机号码未注册
int USER_REGISTER_DISABLED = 10072; // 不允许用户注册
int RETRIEVE_PASSWORD_DISABLED = 10073; // 未开启找回密码功能
int PHONE_FORMAT_ERROR = 10074; // 手机号码格式不正确
int SMS_CODE_ERROR = 10075; // 手机验证码错误
// Login-related error codes
int ADD_DATA_FAILED = 10065; // Failed to add data
int UPDATE_DATA_FAILED = 10066; // Failed to update data
int SMS_CAPTCHA_ERROR = 10067; // SMS captcha verification failed
int MOBILE_REGISTER_DISABLED = 10068; // Mobile registration is disabled
int USERNAME_NOT_PHONE = 10069; // Username is not a phone number
int PHONE_ALREADY_REGISTERED = 10070; // Phone number is already registered
int PHONE_NOT_REGISTERED = 10071; // Phone number is not registered
int USER_REGISTER_DISABLED = 10072; // User registration is not allowed
int RETRIEVE_PASSWORD_DISABLED = 10073; // Password retrieval is disabled
int PHONE_FORMAT_ERROR = 10074; // Phone number format is invalid
int SMS_CODE_ERROR = 10075; // SMS verification code is invalid
// 字典类型相关错误码
int DICT_TYPE_NOT_EXIST = 10076; // 字典类型不存在
int DICT_TYPE_DUPLICATE = 10077; // 字典类型编码重复
// Dictionary type error codes
int DICT_TYPE_NOT_EXIST = 10076; // Dictionary type does not exist
int DICT_TYPE_DUPLICATE = 10077; // Dictionary type code is duplicated
// 资源处理相关错误码
int RESOURCE_READ_ERROR = 10078; // 读取资源失败
// Resource handling error codes
int RESOURCE_READ_ERROR = 10078; // Failed to read the resource
// 智能体相关错误码
int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM大模型和Intent意图识别,选择参数不匹配
// Agent-related error codes
int LLM_INTENT_PARAMS_MISMATCH = 10079; // Selected LLM and intent parameters do not match
// 声纹相关错误码
int VOICEPRINT_ALREADY_REGISTERED = 10080; // 此声音声纹已经注册
int VOICEPRINT_DELETE_ERROR = 10081; // 删除声纹出现错误
int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // 声纹修改不允许,声音已注册
int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // 修改声纹错误,请联系管理员
int VOICEPRINT_API_URI_ERROR = 10084; // 声纹接口地址错误
int VOICEPRINT_AUDIO_NOT_BELONG_AGENT = 10085; // 音频数据不属于智能体
int VOICEPRINT_AUDIO_EMPTY = 10086; // 音频数据为空
int VOICEPRINT_REGISTER_REQUEST_ERROR = 10087; // 声纹保存请求失败
int VOICEPRINT_REGISTER_PROCESS_ERROR = 10088; // 声纹保存处理失败
int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // 声纹注销请求失败
int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // 声纹注销处理失败
int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // 声纹识别请求失败
// Voiceprint-related error codes
int VOICEPRINT_ALREADY_REGISTERED = 10080; // This voiceprint is already registered
int VOICEPRINT_DELETE_ERROR = 10081; // Failed to delete the voiceprint
int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // Voiceprint updates are not allowed because the voice is registered
int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // Voiceprint update failed, please contact an administrator
int VOICEPRINT_API_URI_ERROR = 10084; // Voiceprint API address is invalid
int VOICEPRINT_AUDIO_NOT_BELONG_AGENT = 10085; // Audio data does not belong to the agent
int VOICEPRINT_AUDIO_EMPTY = 10086; // Audio data is empty
int VOICEPRINT_REGISTER_REQUEST_ERROR = 10087; // Voiceprint save request failed
int VOICEPRINT_REGISTER_PROCESS_ERROR = 10088; // Voiceprint save processing failed
int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // Voiceprint unregister request failed
int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // Voiceprint unregister processing failed
int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // Voiceprint identify request failed
int LLM_NOT_EXIST = 10092; // 设置的LLM不存在
int MODEL_REFERENCED_BY_AGENT = 10093; // 该模型配置已被智能体引用,无法删除
int LLM_REFERENCED_BY_INTENT = 10094; // 该LLM模型已被意图识别配置引用,无法删除
int LLM_NOT_EXIST = 10092; // Selected LLM does not exist
int MODEL_REFERENCED_BY_AGENT = 10093; // Model configuration is referenced by an agent and cannot be deleted
int LLM_REFERENCED_BY_INTENT = 10094; // LLM model is referenced by intent configuration and cannot be deleted
// 服务端管理相关错误码
int INVALID_SERVER_ACTION = 10095; // 无效服务端操作
int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // 未配置服务端WebSocket地址
int TARGET_WEBSOCKET_NOT_EXIST = 10097; // 目标WebSocket地址不存在
// Server management error codes
int INVALID_SERVER_ACTION = 10095; // Invalid server action
int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // Server WebSocket address is not configured
int TARGET_WEBSOCKET_NOT_EXIST = 10097; // Target WebSocket address does not exist
// 参数验证相关错误码
int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket地址列表不能为空
int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket地址不能使用localhost或127.0.0.1
int WEBSOCKET_URL_FORMAT_ERROR = 10100; // WebSocket地址格式不正确
int WEBSOCKET_CONNECTION_FAILED = 10101; // WebSocket连接测试失败
int OTA_URL_EMPTY = 10102; // OTA地址不能为空
int OTA_URL_LOCALHOST = 10103; // OTA地址不能使用localhost或127.0.0.1
int OTA_URL_PROTOCOL_ERROR = 10104; // OTA地址必须以http或https开头
int OTA_URL_FORMAT_ERROR = 10105; // OTA地址必须以/ota/结尾
int OTA_INTERFACE_ACCESS_FAILED = 10106; // OTA接口访问失败
int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA接口返回内容格式不正确
int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA接口验证失败
int MCP_URL_EMPTY = 10109; // MCP地址不能为空
int MCP_URL_LOCALHOST = 10110; // MCP地址不能使用localhost或127.0.0.1
int MCP_URL_INVALID = 10111; // 不是正确的MCP地址
int MCP_INTERFACE_ACCESS_FAILED = 10112; // MCP接口访问失败
int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP接口返回内容格式不正确
int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP接口验证失败
int VOICEPRINT_URL_EMPTY = 10115; // 声纹接口地址不能为空
int VOICEPRINT_URL_LOCALHOST = 10116; // 声纹接口地址不能使用localhost或127.0.0.1
int VOICEPRINT_URL_INVALID = 10117; // 不是正确的声纹接口地址
int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // 声纹接口地址必须以http或https开头
int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // 声纹接口访问失败
int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // 声纹接口返回内容格式不正确
int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // 声纹接口验证失败
int MQTT_SECRET_EMPTY = 10122; // mqtt密钥不能为空
int MQTT_SECRET_LENGTH_INSECURE = 10123; // mqtt密钥长度不安全
int MQTT_SECRET_CHARACTER_INSECURE = 10124; // mqtt密钥必须同时包含大小写字母
int MQTT_SECRET_WEAK_PASSWORD = 10125; // mqtt密钥包含弱密码
int DICT_LABEL_DUPLICATE = 10128; // 字典标签重复
int SM2_KEY_NOT_CONFIGURED = 10129; // SM2密钥未配置
int SM2_DECRYPT_ERROR = 10130; // SM2解密失败
int MODEL_TYPE_PROVIDE_CODE_NOT_NULL = 10131; // modelType和provideCode不能为空
// Parameter validation error codes
int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket address list cannot be empty
int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket address cannot use localhost or 127.0.0.1
int WEBSOCKET_URL_FORMAT_ERROR = 10100; // WebSocket address format is invalid
int WEBSOCKET_CONNECTION_FAILED = 10101; // WebSocket connection test failed
int OTA_URL_EMPTY = 10102; // OTA address cannot be empty
int OTA_URL_LOCALHOST = 10103; // OTA address cannot use localhost or 127.0.0.1
int OTA_URL_PROTOCOL_ERROR = 10104; // OTA address must start with http or https
int OTA_URL_FORMAT_ERROR = 10105; // OTA address must end with /ota/
int OTA_INTERFACE_ACCESS_FAILED = 10106; // Failed to access the OTA endpoint
int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA endpoint returned an invalid format
int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA endpoint validation failed
int MCP_URL_EMPTY = 10109; // MCP address cannot be empty
int MCP_URL_LOCALHOST = 10110; // MCP address cannot use localhost or 127.0.0.1
int MCP_URL_INVALID = 10111; // Invalid MCP address
int MCP_INTERFACE_ACCESS_FAILED = 10112; // Failed to access the MCP endpoint
int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP endpoint returned an invalid format
int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP endpoint validation failed
int VOICEPRINT_URL_EMPTY = 10115; // Voiceprint endpoint address cannot be empty
int VOICEPRINT_URL_LOCALHOST = 10116; // Voiceprint endpoint address cannot use localhost or 127.0.0.1
int VOICEPRINT_URL_INVALID = 10117; // Invalid voiceprint endpoint address
int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // Voiceprint endpoint must start with http or https
int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // Failed to access the voiceprint endpoint
int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // Voiceprint endpoint returned an invalid format
int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // Voiceprint endpoint validation failed
int MQTT_SECRET_EMPTY = 10122; // MQTT secret cannot be empty
int MQTT_SECRET_LENGTH_INSECURE = 10123; // MQTT secret length is insecure
int MQTT_SECRET_CHARACTER_INSECURE = 10124; // MQTT secret must contain both uppercase and lowercase letters
int MQTT_SECRET_WEAK_PASSWORD = 10125; // MQTT secret contains a weak password
int DICT_LABEL_DUPLICATE = 10128; // Dictionary label is duplicated
int SM2_KEY_NOT_CONFIGURED = 10129; // SM2 key is not configured
int SM2_DECRYPT_ERROR = 10130; // SM2 decryption failed
int MODEL_TYPE_PROVIDE_CODE_NOT_NULL = 10131; // modelType and provideCode cannot be empty
// 聊天记录相关错误码
int CHAT_HISTORY_NO_PERMISSION = 10132; // 没有权限查看该智能体的聊天记录
int CHAT_HISTORY_SESSION_ID_NOT_NULL = 10133; // 会话ID不能为空
int CHAT_HISTORY_AGENT_ID_NOT_NULL = 10134; // 智能体ID不能为空
int CHAT_HISTORY_DOWNLOAD_FAILED = 10135; // 聊天记录下载失败
int DOWNLOAD_LINK_EXPIRED = 10136; // 下载链接已过期或无效
int DOWNLOAD_LINK_INVALID = 10137; // 下载链接无效
int CHAT_ROLE_USER = 10138; // 用户角色
int CHAT_ROLE_AGENT = 10139; // 智能体角色
// Chat history error codes
int CHAT_HISTORY_NO_PERMISSION = 10132; // No permission to view this agent's chat history
int CHAT_HISTORY_SESSION_ID_NOT_NULL = 10133; // Session ID cannot be empty
int CHAT_HISTORY_AGENT_ID_NOT_NULL = 10134; // Agent ID cannot be empty
int CHAT_HISTORY_DOWNLOAD_FAILED = 10135; // Failed to download chat history
int DOWNLOAD_LINK_EXPIRED = 10136; // Download link has expired or is invalid
int DOWNLOAD_LINK_INVALID = 10137; // Download link is invalid
int CHAT_ROLE_USER = 10138; // User role
int CHAT_ROLE_AGENT = 10139; // Agent role
// 声音克隆相关错误码
int VOICE_CLONE_AUDIO_EMPTY = 10140; // 音频文件不能为空
int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // 只支持音频文件
int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // 音频文件大小不能超过10MB
int VOICE_CLONE_UPLOAD_FAILED = 10143; // 上传失败
int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // 声音克隆记录不存在
int VOICE_RESOURCE_INFO_EMPTY = 10145; // 音色资源信息不能为空
int VOICE_RESOURCE_PLATFORM_NAME_EMPTY = 10146; // 平台名称不能为空
int VOICE_RESOURCE_ID_EMPTY = 10147; // 音色ID不能为空
int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // 归属账号不能为空
int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // 删除的音色资源ID不能为空
int VOICE_RESOURCE_NO_PERMISSION = 10150; // 您没有权限操作该记录
int VOICE_CLONE_AUDIO_NOT_UPLOADED = 10151; // 请先上传音频文件
int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // 模型配置未找到
int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // 模型类型未找到
int VOICE_CLONE_TRAINING_FAILED = 10154; // 训练失败
int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // 火山引擎缺少配置
int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // 响应格式错误
int VOICE_CLONE_REQUEST_FAILED = 10157; // 请求失败
int VOICE_CLONE_PREFIX = 10158; // 复刻音色前缀
int VOICE_ID_ALREADY_EXISTS = 10159; // 音色ID已存在
int VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR = 10160; // 火山引擎音色ID格式错误
// Voice cloning error codes
int VOICE_CLONE_AUDIO_EMPTY = 10140; // Audio file cannot be empty
int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // Only audio files are supported
int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // Audio file size cannot exceed 10 MB
int VOICE_CLONE_UPLOAD_FAILED = 10143; // Upload failed
int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // Voice clone record does not exist
int VOICE_RESOURCE_INFO_EMPTY = 10145; // Voice resource information cannot be empty
int VOICE_RESOURCE_PLATFORM_NAME_EMPTY = 10146; // Platform name cannot be empty
int VOICE_RESOURCE_ID_EMPTY = 10147; // Voice ID cannot be empty
int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // Account ownership cannot be empty
int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // Voice resource ID to delete cannot be empty
int VOICE_RESOURCE_NO_PERMISSION = 10150; // You do not have permission to operate on this record
int VOICE_CLONE_AUDIO_NOT_UPLOADED = 10151; // Upload the audio file first
int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // Model configuration was not found
int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // Model type was not found
int VOICE_CLONE_TRAINING_FAILED = 10154; // Training failed
int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // Volcano Engine configuration is missing
int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // Response format is invalid
int VOICE_CLONE_REQUEST_FAILED = 10157; // Request failed
int VOICE_CLONE_PREFIX = 10158; // Voice clone prefix
int VOICE_ID_ALREADY_EXISTS = 10159; // Voice ID already exists
int VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR = 10160; // Volcano Engine voice ID format is invalid
// 设备相关错误码
int MAC_ADDRESS_ALREADY_EXISTS = 10161; // Mac地址已存在
// 模型相关错误码
int MODEL_PROVIDER_NOT_EXIST = 10162; // 供应器不存在
// Device-related error codes
int MAC_ADDRESS_ALREADY_EXISTS = 10161; // MAC address already exists
// Model-related error codes
int MODEL_PROVIDER_NOT_EXIST = 10162; // Provider does not exist
// 知识库相关错误码
int Knowledge_Base_RECORD_NOT_EXISTS = 10163; // 知识库记录不存在
int RAG_CONFIG_NOT_FOUND = 10164; // RAG配置未找到
int RAG_CONFIG_TYPE_ERROR = 10165; // RAG配置类型错误
int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // 默认RAG配置未找到
int RAG_API_ERROR = 10167; // RAG调用失败
int UPLOAD_FILE_ERROR = 10168; // 上传文件失败
int NO_PERMISSION = 10169; // 没有权限
int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // 同名知识库已存在
int RAG_API_ERROR_URL_NULL = 10171; // RAG配置中base_url为空,请完善配置
int RAG_API_ERROR_API_KEY_NULL = 10172; // RAG配置中api_key为空,请完善配置
int RAG_API_ERROR_API_KEY_INVALID = 10173; // RAG配置中api_key包含占位符,请替换为实际的API密钥
int RAG_API_ERROR_URL_INVALID = 10174; // RAG配置中base_url格式不正确,请检查协议是否正确
int RAG_DATASET_ID_NOT_NULL = 10176; // RAG配置中dataset_id不能为空
int RAG_MODEL_ID_NOT_NULL = 10177; // RAG配置中model_id不能为空
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // RAG配置中dataset_id和model_id不能为空
int RAG_FILE_NAME_NOT_NULL = 10179; // 文件名称不能为空
int RAG_FILE_CONTENT_EMPTY = 10180; // 文件内容不能为空
// Knowledge base error codes
int Knowledge_Base_RECORD_NOT_EXISTS = 10163; // Knowledge base record does not exist
int RAG_CONFIG_NOT_FOUND = 10164; // RAG configuration was not found
int RAG_CONFIG_TYPE_ERROR = 10165; // RAG configuration type is invalid
int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // Default RAG configuration was not found
int RAG_API_ERROR = 10167; // RAG call failed
int UPLOAD_FILE_ERROR = 10168; // File upload failed
int NO_PERMISSION = 10169; // No permission
int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // A knowledge base with the same name already exists
int RAG_API_ERROR_URL_NULL = 10171; // base_url is empty in the RAG configuration
int RAG_API_ERROR_API_KEY_NULL = 10172; // api_key is empty in the RAG configuration
int RAG_API_ERROR_API_KEY_INVALID = 10173; // api_key still contains a placeholder in the RAG configuration
int RAG_API_ERROR_URL_INVALID = 10174; // base_url format is invalid in the RAG configuration
int RAG_DATASET_ID_NOT_NULL = 10176; // dataset_id cannot be empty in the RAG configuration
int RAG_MODEL_ID_NOT_NULL = 10177; // model_id cannot be empty in the RAG configuration
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // dataset_id and model_id cannot both be empty
int RAG_FILE_NAME_NOT_NULL = 10179; // File name cannot be empty
int RAG_FILE_CONTENT_EMPTY = 10180; // File content cannot be empty
// 设备相关错误码(补充)
int MCA_NOT_NULL = 10175; // mac地址不能为空
// Additional device-related error codes
int MCA_NOT_NULL = 10175; // MAC address cannot be empty
// 音色克隆(补充)
int VOICE_CLONE_NAME_NOT_NULL = 10181; // 音色克隆名称不能为空
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // 音色克隆音频不存在
// Additional voice clone error codes
int VOICE_CLONE_NAME_NOT_NULL = 10181; // Voice clone name cannot be empty
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // Voice clone audio does not exist
// 智能体模板相关错误码(补充)
int AGENT_TEMPLATE_NOT_FOUND = 10183; // 默认智能体未找到
// Additional agent template error codes
int AGENT_TEMPLATE_NOT_FOUND = 10183; // Default agent was not found
// 知识库适配器相关错误码
int RAG_ADAPTER_TYPE_NOT_SUPPORTED = 10184; // 不支持的适配器类型
int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG配置验证失败
int RAG_ADAPTER_CREATION_FAILED = 10186; // 适配器创建失败
int RAG_ADAPTER_INIT_FAILED = 10187; // 适配器初始化失败
int RAG_ADAPTER_CONNECTION_FAILED = 10188; // 适配器连接测试失败
int RAG_ADAPTER_OPERATION_FAILED = 10189; // 适配器操作失败
int RAG_ADAPTER_NOT_FOUND = 10190; // 适配器未找到
int RAG_ADAPTER_CACHE_ERROR = 10191; // 适配器缓存错误
int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // 适配器类型未找到
// Knowledge base adapter error codes
int RAG_ADAPTER_TYPE_NOT_SUPPORTED = 10184; // Adapter type is not supported
int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG configuration validation failed
int RAG_ADAPTER_CREATION_FAILED = 10186; // Failed to create adapter
int RAG_ADAPTER_INIT_FAILED = 10187; // Failed to initialize adapter
int RAG_ADAPTER_CONNECTION_FAILED = 10188; // Adapter connection test failed
int RAG_ADAPTER_OPERATION_FAILED = 10189; // Adapter operation failed
int RAG_ADAPTER_NOT_FOUND = 10190; // Adapter was not found
int RAG_ADAPTER_CACHE_ERROR = 10191; // Adapter cache error
int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // Adapter type was not found
// 设备工具相关错误码
int DEVICE_ID_NOT_NULL = 10193; // 设备ID不能为空
int DEVICE_NOT_EXIST = 10194; // 设备不存在
int OTA_UPLOAD_COUNT_EXCEED = 10195; // OTA上传次数超过限制
// Device tool error codes
int DEVICE_ID_NOT_NULL = 10193; // Device ID cannot be empty
int DEVICE_NOT_EXIST = 10194; // Device does not exist
int OTA_UPLOAD_COUNT_EXCEED = 10195; // OTA upload count exceeded the limit
// 智能体标签相关错误码
int AGENT_TAG_NAME_DUPLICATE = 10196; // 标签名称已存在
int AGENT_TAG_NAME_EMPTY = 10197; // 标签名称不能为空
int AGENT_TAG_NOT_EXIST = 10198; // 标签不存在
// Agent tag error codes
int AGENT_TAG_NAME_DUPLICATE = 10196; // Tag name already exists
int AGENT_TAG_NAME_EMPTY = 10197; // Tag name cannot be empty
int AGENT_TAG_NOT_EXIST = 10198; // Tag does not exist
int RAG_DOCUMENT_PARSING_DELETE_ERROR = 10199; // 文档解析中,禁止删除
int RAG_DOCUMENT_PARSING_DELETE_ERROR = 10199; // Documents cannot be deleted while parsing is in progress
// 智能体MCP相关错误码
int MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION = 10200; // 没有权限查看该智能体的MCP接入点地址
int MCP_ACCESS_POINT_ADDRESS_NOT_CONFIGURED = 10201; // 请联系管理员进入参数管理配置mcp接入点地址
int MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION = 10202; // 没有权限查看该智能体的MCP工具列表
// Agent MCP error codes
int MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION = 10200; // No permission to view this agent's MCP access-point address
int MCP_ACCESS_POINT_ADDRESS_NOT_CONFIGURED = 10201; // MCP access-point address is not configured
int MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION = 10202; // No permission to view this agent's MCP tool list
}

View file

@ -3,8 +3,8 @@ package xiaozhi.common.exception;
import xiaozhi.common.utils.MessageUtils;
/**
* 自定义异常
* Copyright (c) 人人开源 All rights reserved.
* Custom exception
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class RenException extends RuntimeException {
@ -64,4 +64,4 @@ public class RenException extends RuntimeException {
this.code = code;
}
}
}

View file

@ -17,8 +17,8 @@ import xiaozhi.common.utils.MessageUtils;
import xiaozhi.common.utils.Result;
/**
* 异常处理器
* Copyright (c) 人人开源 All rights reserved.
* Exception handler
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Slf4j
@ -27,7 +27,7 @@ import xiaozhi.common.utils.Result;
public class RenExceptionHandler {
/**
* 处理自定义异常
* Handle custom exceptions
*/
@ExceptionHandler(RenException.class)
public Result<Void> handleRenException(RenException ex) {
@ -82,4 +82,4 @@ public class RenExceptionHandler {
return new Result<Void>().error(ErrorCode.PARAM_VALUE_NULL, errorMsg);
}
}
}

View file

@ -12,8 +12,8 @@ import xiaozhi.common.user.UserDetail;
import xiaozhi.modules.security.user.SecurityUser;
/**
* 公共字段,自动填充值
* Copyright (c) 人人开源 All rights reserved.
* Automatically fills common metadata fields.
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Component
@ -30,9 +30,9 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
UserDetail user = SecurityUser.getUser();
Date date = new Date();
// 创建者
// Creator
strictInsertFill(metaObject, CREATOR, Long.class, user.getId());
// 创建时间 - 支持createDate和createdAt两种字段名
// Created time. Support both createDate and createdAt field names.
if (metaObject.hasSetter(CREATE_DATE)) {
strictInsertFill(metaObject, CREATE_DATE, Date.class, date);
}
@ -40,9 +40,9 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
strictInsertFill(metaObject, "createdAt", Date.class, date);
}
// 更新者
// Updater
strictInsertFill(metaObject, UPDATER, Long.class, user.getId());
// 更新时间 - 支持updateDate和updatedAt两种字段名
// Updated time. Support both updateDate and updatedAt field names.
if (metaObject.hasSetter(UPDATE_DATE)) {
strictInsertFill(metaObject, UPDATE_DATE, Date.class, date);
}
@ -50,7 +50,7 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
strictInsertFill(metaObject, "updatedAt", Date.class, date);
}
// 数据标识
// Data operation marker
strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.INSERT.getValue());
}
@ -58,9 +58,9 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
public void updateFill(MetaObject metaObject) {
Date date = new Date();
// 更新者
// Updater
strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId());
// 更新时间 - 支持updateDate和updatedAt两种字段名
// Updated time. Support both updateDate and updatedAt field names.
if (metaObject.hasSetter(UPDATE_DATE)) {
strictUpdateFill(metaObject, UPDATE_DATE, Date.class, date);
}
@ -68,7 +68,7 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
strictUpdateFill(metaObject, "updatedAt", Date.class, date);
}
// 数据标识
// Data operation marker
strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.UPDATE.getValue());
}
}
}

View file

@ -21,8 +21,8 @@ import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
/**
* 数据过滤
* Copyright (c) 人人开源 All rights reserved.
* Data filtering
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class DataFilterInterceptor implements InnerInterceptor {
@ -32,15 +32,15 @@ public class DataFilterInterceptor implements InnerInterceptor {
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
ResultHandler resultHandler, BoundSql boundSql) {
DataScope scope = getDataScope(parameter);
// 不进行数据过滤
// Do not perform data filtering
if (scope == null || StrUtil.isBlank(scope.getSqlFilter())) {
return;
}
// 拼接新SQL
// Concatenate new SQL
String buildSql = getSelect(boundSql.getSql(), scope);
// 重写SQL
// Rewrite SQL
PluginUtils.mpBoundSql(boundSql).sql(buildSql);
}
@ -49,7 +49,7 @@ public class DataFilterInterceptor implements InnerInterceptor {
return null;
}
// 判断参数里是否有DataScope对象
// Check if parameter contains DataScope object
if (parameter instanceof Map) {
Map<?, ?> parameterMap = (Map<?, ?>) parameter;
for (Map.Entry<?, ?> entry : parameterMap.entrySet()) {

View file

@ -1,8 +1,8 @@
package xiaozhi.common.interceptor;
/**
* 数据范围
* Copyright (c) 人人开源 All rights reserved.
* Data scope
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class DataScope {
@ -24,4 +24,4 @@ public class DataScope {
public String toString() {
return this.sqlFilter;
}
}
}

View file

@ -7,27 +7,27 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 分页工具类
* Copyright (c) 人人开源 All rights reserved.
* Pagination utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@Schema(description = "分页数据")
@Schema(description = "Pagination data")
public class PageData<T> implements Serializable {
@Schema(description = "总记录数")
@Schema(description = "Total record count")
private int total;
@Schema(description = "列表数据")
@Schema(description = "List data")
private List<T> list;
/**
* 分页
* Pagination
*
* @param list 列表数据
* @param total 总记录数
* @param list List data
* @param total Total record count
*/
public PageData(List<T> list, long total) {
this.list = list;
this.total = (int) total;
}
}
}

View file

@ -6,20 +6,20 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 令牌信息
* Token information
*
* @author Jack
*/
@Data
@Schema(description = "令牌信息")
@Schema(description = "Token information")
public class TokenDTO implements Serializable {
@Schema(description = "密码")
@Schema(description = "Password")
private String token;
@Schema(description = "过期时间")
@Schema(description = "Expiration time")
private int expire;
@Schema(description = "客户端指纹")
@Schema(description = "Client fingerprint")
private String clientHash;
}

View file

@ -10,8 +10,8 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
import jakarta.annotation.Resource;
/**
* Redis配置
* Copyright (c) 人人开源 All rights reserved.
* Redis configuration
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Configuration
@ -30,4 +30,4 @@ public class RedisConfig {
return redisTemplate;
}
}
}

View file

@ -1,188 +1,188 @@
package xiaozhi.common.redis;
/**
* Redis Key 常量类
* Copyright (c) 人人开源 All rights reserved.
* Redis Key constant class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class RedisKeys {
/**
* 系统参数Key
* System parameter Key
*/
public static String getSysParamsKey() {
return "sys:params";
}
/**
* 验证码Key
* Verification code Key
*/
public static String getCaptchaKey(String uuid) {
return "sys:captcha:" + uuid;
}
/**
* 未注册设备验证码Key
* Unregistered device verification code Key
*/
public static String getDeviceCaptchaKey(String captcha) {
return "sys:device:captcha:" + captcha;
}
/**
* 用户id的Key
* User id Key
*/
public static String getUserIdKey(Long userid) {
return "sys:username:id:" + userid;
}
/**
* 模型名称的Key
* Model name Key
*/
public static String getModelNameById(String id) {
return "model:name:" + id;
}
/**
* 模型配置的Key
* Model configuration Key
*/
public static String getModelConfigById(String id) {
return "model:data:" + id;
}
/**
* 获取音色名称缓存key
* Get voice name cache key
*/
public static String getTimbreNameById(String id) {
return "timbre:name:" + id;
}
/**
* 获取设备数量缓存key
* Get device count cache key
*/
public static String getAgentDeviceCountById(String id) {
return "agent:device:count:" + id;
}
/**
* 获取智能体最后连接时间缓存key
* Get agent last connection time cache key
*/
public static String getAgentDeviceLastConnectedAtById(String id) {
return "agent:device:lastConnected:" + id;
}
/**
* 获取系统配置缓存key
* Get system configuration cache key
*/
public static String getServerConfigKey() {
return "server:config";
}
/**
* 获取音色详情缓存key
* Get voice details cache key
*/
public static String getTimbreDetailsKey(String id) {
return "timbre:details:" + id;
}
/**
* 获取版本号Key
* Get version number Key
*/
public static String getVersionKey() {
return "sys:version";
}
/**
* OTA固件ID的Key
* OTA firmware ID Key
*/
public static String getOtaIdKey(String uuid) {
return "ota:id:" + uuid;
}
/**
* OTA固件下载次数的Key
* OTA firmware download count Key
*/
public static String getOtaDownloadCountKey(String uuid) {
return "ota:download:count:" + uuid;
}
/**
* 获取字典数据的缓存key
* Get dictionary data cache key
*/
public static String getDictDataByTypeKey(String dictType) {
return "sys:dict:data:" + dictType;
}
/**
* 获取智能体音频ID的缓存key
* Get agent audio ID cache key
*/
public static String getAgentAudioIdKey(String uuid) {
return "agent:audio:id:" + uuid;
}
/**
* 获取短信验证码的缓存key
* Get SMS verification code cache key
*/
public static String getSMSValidateCodeKey(String phone) {
return "sms:Validate:Code:" + phone;
}
/**
* 获取短信验证码最后发送时间的缓存key
* Get SMS verification code last send time cache key
*/
public static String getSMSLastSendTimeKey(String phone) {
return "sms:Validate:Code:" + phone + ":last_send_time";
}
/**
* 获取短信验证码今日发送次数的缓存key
* Get SMS verification code today send count cache key
*/
public static String getSMSTodayCountKey(String phone) {
return "sms:Validate:Code:" + phone + ":today_count";
}
/**
* 聊天记录UUID映射的Key
* Cache key for chat history UUID mappings.
*/
public static String getChatHistoryKey(String uuid) {
return "agent:chat:history:" + uuid;
}
/**
* 获取音色克隆音频ID的缓存key
* Cache key for a voice clone audio ID.
*/
public static String getVoiceCloneAudioIdKey(String uuid) {
return "voiceClone:audio:id:" + uuid;
}
/**
* 获取知识库缓存key
* Cache key for a knowledge base.
*/
public static String getKnowledgeBaseCacheKey(String datasetId) {
return "knowledge:base:" + datasetId;
}
/**
* 获取临时注册设备标记key
* Cache key for temporary device registration markers.
*/
public static String getTmpRegisterMacKey(String deviceId) {
return "tmp_register_mac:" + deviceId;
}
/**
* OTA绑定设备
* Cache key for OTA device activation codes.
*/
public static String getOtaActivationCode(String activationCode) {
return "ota:activation:code:" + activationCode;
}
/**
* OTA获取设备mac相关信息
* Cache key for OTA device activation metadata.
*/
public static String getOtaDeviceActivationInfo(String deviceId) {
return "ota:activation:data:" + deviceId;
}
/**
* OTA上传次数
* Cache key for OTA upload count tracking.
*/
public static String getOtaUploadCountKey(Long username) {
return "ota:upload:count:" + username;

View file

@ -16,8 +16,8 @@ import jakarta.annotation.Resource;
import xiaozhi.common.utils.ResourcesUtils;
/**
* Redis工具类
* Copyright (c) 人人开源 All rights reserved.
* Redis utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Component
@ -29,19 +29,19 @@ public class RedisUtils {
private ResourcesUtils resourceUtils;
/**
* 默认过期时长为24小时,单位:秒
* Default expiration time is 24 hours, unit: seconds
*/
public final static long DEFAULT_EXPIRE = 60 * 60 * 24L;
/**
* 过期时长为1小时,单位:秒
* Expiration duration is 1 hour, unit: seconds
*/
public final static long HOUR_ONE_EXPIRE = (long) 60 * 60;
/**
* 过期时长为6小时,单位:秒
* Expiration duration is 6 hours, unit: seconds
*/
public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L;
/**
* 不设置过期时长
* Do not set expiration duration
*/
public final static long NOT_EXPIRE = -1L;
@ -153,39 +153,39 @@ public class RedisUtils {
/**
* 清空所有 Redis 数据库中的所有键
* Clear all keys in all Redis databases
*/
public void emptyAll() {
// Lua 脚本 FLUSHALL是redis清空所有库的命令
// Lua script FLUSHALL is redis command to clear all databases
String luaScript =resourceUtils.loadString("lua/emptyAll.lua");
// 创建 DefaultRedisScript 对象
// Create DefaultRedisScript object
DefaultRedisScript<Void> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(luaScript); // 设置 Lua 脚本内容
redisScript.setResultType(Void.class); // 设置返回值类型
redisScript.setScriptText(luaScript); // Set Lua script content
redisScript.setResultType(Void.class); // Set return value type
// 执行 Lua 脚本
List<String> keys = Collections.emptyList(); // 如果脚本不依赖 key,可以传入空列表
// Execute Lua script
List<String> keys = Collections.emptyList(); // If script doesn't depend on key, can pass empty list
redisTemplate.execute(redisScript, keys);
}
/**
* 获取在redis指定key的值,如果值为空,着设置key的默认值
* @param key redis的key
* @param defaultValue 默认值
* @param expiresInSecond 过期时间
* @return 返回key的值
* Get value for specified key in redis, if value is empty, set default value for key
* @param key Redis key
* @param defaultValue Default value
* @param expiresInSecond Expiration time
* @return Return key value
*/
public String getKeyOrCreate(String key, String defaultValue,Long expiresInSecond) {
// Lua 脚本
// Lua script
String luaScript = resourceUtils.loadString("lua/getKeyOrCreate.lua");
DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(luaScript);
redisScript.setResultType(String.class);
// 执行 Lua 脚本
// Execute Lua script
List<String> keys = Collections.singletonList(key);
return redisTemplate.execute(redisScript, keys, defaultValue,expiresInSecond);
}

View file

@ -6,8 +6,8 @@ import java.util.Collection;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
/**
* 基础服务接口,所有Service接口都要继承
* Copyright (c) 人人开源 All rights reserved.
* Base service interface, all Service interfaces should inherit from this
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface BaseService<T> {
@ -15,95 +15,95 @@ public interface BaseService<T> {
/**
* <p>
* 插入一条记录(选择字段,策略插入)
* Insert a record (selective fields, strategy insert)
* </p>
*
* @param entity 实体对象
* @param entity Entity object
*/
boolean insert(T entity);
/**
* <p>
* 插入(批量),该方法不支持 Oracle、SQL Server
* Insert (batch), this method does not support Oracle, SQL Server
* </p>
*
* @param entityList 实体对象集合
* @param entityList Entity object collection
*/
boolean insertBatch(Collection<T> entityList);
/**
* <p>
* 插入(批量),该方法不支持 Oracle、SQL Server
* Insert (batch), this method does not support Oracle, SQL Server
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 插入批次数量
* @param entityList Entity object collection
* @param batchSize Insert batch size
*/
boolean insertBatch(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 选择修改
* Update by ID
* </p>
*
* @param entity 实体对象
* @param entity Entity object
*/
boolean updateById(T entity);
/**
* <p>
* 根据 whereEntity 条件,更新记录
* Update records based on whereEntity condition
* </p>
*
* @param entity 实体对象
* @param updateWrapper 实体对象封装操作类
* @param entity Entity object
* @param updateWrapper Entity object wrapper operation class
* {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);
/**
* <p>
* 根据ID 批量更新
* Batch update by ID
* </p>
*
* @param entityList 实体对象集合
* @param entityList Entity object collection
*/
boolean updateBatchById(Collection<T> entityList);
/**
* <p>
* 根据ID 批量更新
* Batch update by ID
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 更新批次数量
* @param entityList Entity object collection
* @param batchSize Update batch size
*/
boolean updateBatchById(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 查询
* Query by ID
* </p>
*
* @param id 主键ID
* @param id Primary key ID
*/
T selectById(Serializable id);
/**
* <p>
* 根据 ID 删除
* Delete by ID
* </p>
*
* @param id 主键ID
* @param id Primary key ID
*/
boolean deleteById(Serializable id);
/**
* <p>
* 删除(根据ID 批量删除)
* Delete (batch delete by ID)
* </p>
*
* @param idList 主键ID列表
* @param idList Primary key ID list
*/
boolean deleteBatchIds(Collection<? extends Serializable> idList);
}
}

View file

@ -7,8 +7,8 @@ import java.util.Map;
import xiaozhi.common.page.PageData;
/**
* CRUD基础服务接口
* Copyright (c) 人人开源 All rights reserved.
* CRUD base service interface
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface CrudService<T, D> extends BaseService<T> {
@ -25,4 +25,4 @@ public interface CrudService<T, D> extends BaseService<T> {
void delete(Serializable[] ids);
}
}

View file

@ -32,8 +32,8 @@ import xiaozhi.common.service.BaseService;
import xiaozhi.common.utils.ConvertUtils;
/**
* 基础服务类,所有Service都要继承
* Copyright (c) 人人开源 All rights reserved.
* Base service class, all Services should inherit from this
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements BaseService<T> {
@ -42,20 +42,20 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
protected Log log = LogFactory.getLog(getClass());
/**
* 获取分页对象
* Get pagination object
*
* @param params 分页查询参数
* @param defaultOrderField 默认排序字段
* @param isAsc 排序方式
* @param params Pagination query parameters
* @param defaultOrderField Default sort field
* @param isAsc Sort order
* @see xiaozhi.common.constant.Constant
* params.put(Constant.PAGE, "1");
* params.put(Constant.LIMIT, "10");
* params.put(Constant.ORDER_FIELD, "field"); // 单个字段
* params.put(Constant.ORDER_FIELD, List.of("field1", "field2")); // 多个字段
* params.put(Constant.ORDER_FIELD, "field"); // Single field
* params.put(Constant.ORDER_FIELD, List.of("field1", "field2")); // Multiple fields
* params.put(Constant.ORDER, "asc");
*/
protected IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
// 分页参数
// Pagination parameters
long curPage = 1;
long limit = 10;
@ -66,26 +66,26 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
limit = Long.parseLong((String) params.get(Constant.LIMIT));
}
// 分页对象
// Pagination object
Page<T> page = new Page<>(curPage, limit);
// 分页参数
// Pagination parameters
params.put(Constant.PAGE, page);
// 排序字段
// Sort fields
Object orderField = params.get(Constant.ORDER_FIELD);
String order = (String) params.get(Constant.ORDER);
List<String> orderFields = new ArrayList<>();
// 处理排序字段
// Process sort fields
if (orderField instanceof String) {
orderFields.add((String) orderField);
} else if (orderField instanceof List) {
orderFields.addAll((List<String>) orderField);
}
// 有排序字段则排序
// Sort if there are sort fields
if (CollectionUtils.isNotEmpty(orderFields)) {
if (StringUtils.isNotBlank(order) && Constant.ASC.equalsIgnoreCase(order)) {
return page.addOrder(OrderItem.ascs(orderFields.toArray(new String[0])));
@ -94,7 +94,7 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
}
}
// 没有排序字段,使用默认排序
// No sort fields, use default sort
if (StringUtils.isNotBlank(defaultOrderField)) {
if (isAsc) {
page.addOrder(OrderItem.asc(defaultOrderField));
@ -129,13 +129,13 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
/**
* <p>
* 判断数据库操作是否成功
* Determine if database operation is successful
* </p>
* <p>
* 注意!! 该方法为 Integer 判断,不可传入 int 基本类型
* Note!! This method uses Integer for judgment, cannot pass int primitive type
* </p>
*
* @param result 数据库操作返回影响条数
* @param result Number of affected rows returned by database operation
* @return boolean
*/
protected static boolean retBool(Integer result) {
@ -168,7 +168,7 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
}
/**
* 批量插入
* Batch insert
*/
@Override
@Transactional(rollbackFor = Exception.class)
@ -178,7 +178,7 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
}
/**
* 执行批量操作
* Execute batch operations
*/
@SuppressWarnings("deprecation")
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
@ -227,4 +227,4 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
}
}
}

View file

@ -17,8 +17,8 @@ import xiaozhi.common.service.CrudService;
import xiaozhi.common.utils.ConvertUtils;
/**
* CRUD基础服务类
* Copyright (c) 人人开源 All rights reserved.
* CRUD base service class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T>
@ -58,7 +58,7 @@ public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends Bas
T entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
insert(entity);
// copy主键值到dto
// Copy primary key value to dto
BeanUtils.copyProperties(entity, dto);
}
@ -72,4 +72,4 @@ public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends Bas
public void delete(Serializable[] ids) {
baseDao.deleteBatchIds(Arrays.asList(ids));
}
}
}

View file

@ -5,8 +5,8 @@ import java.io.Serializable;
import lombok.Data;
/**
* 登录用户信息
* Copyright (c) 人人开源 All rights reserved.
* Login user information
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@ -16,4 +16,4 @@ public class UserDetail implements Serializable {
private Integer superAdmin;
private String token;
private Integer status;
}
}

View file

@ -12,15 +12,15 @@ public class AESUtils {
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
/**
* AES加密
* AES encryption
*
* @param key 密钥(16位、24位或32位)
* @param plainText 待加密字符串
* @return 加密后的Base64字符串
* @param key Key (16, 24 or 32 bits)
* @param plainText String to be encrypted
* @return Encrypted Base64 string
*/
public static String encrypt(String key, String plainText) {
try {
// 确保密钥长度为16、24或32位
// Ensure key length is 16, 24 or 32 bits
byte[] keyBytes = padKey(key.getBytes(StandardCharsets.UTF_8));
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
@ -30,20 +30,20 @@ public class AESUtils {
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException("AES加密失败", e);
throw new RuntimeException("AES encryption failed", e);
}
}
/**
* AES解密
* AES decryption
*
* @param key 密钥(16位、24位或32位)
* @param encryptedText 待解密的Base64字符串
* @return 解密后的字符串
* @param key Key (16, 24 or 32 bits)
* @param encryptedText Base64 string to be decrypted
* @return Decrypted string
*/
public static String decrypt(String key, String encryptedText) {
try {
// 确保密钥长度为16、24或32位
// Ensure key length is 16, 24 or 32 bits
byte[] keyBytes = padKey(key.getBytes(StandardCharsets.UTF_8));
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
@ -54,15 +54,15 @@ public class AESUtils {
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("AES解密失败", e);
throw new RuntimeException("AES decryption failed", e);
}
}
/**
* 填充密钥到指定长度(16、24或32位)
* Pad key to specified length (16, 24 or 32 bits)
*
* @param keyBytes 原始密钥字节数组
* @return 填充后的密钥字节数组
* @param keyBytes Original key byte array
* @return Padded key byte array
*/
private static byte[] padKey(byte[] keyBytes) {
int keyLength = keyBytes.length;
@ -70,7 +70,7 @@ public class AESUtils {
return keyBytes;
}
// 如果密钥长度不足,用0填充;如果超过,截取前32位
// If key length is insufficient, pad with 0; if exceeds, truncate to first 32 bits
byte[] paddedKey = new byte[32];
System.arraycopy(keyBytes, 0, paddedKey, 0, Math.min(keyLength, 32));
return paddedKey;

View file

@ -9,8 +9,8 @@ import org.springframework.beans.BeanUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 转换工具类
* Copyright (c) 人人开源 All rights reserved.
* Conversion utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Slf4j
@ -48,4 +48,4 @@ public class ConvertUtils {
return targetList;
}
}
}

View file

@ -8,38 +8,38 @@ import java.time.temporal.ChronoUnit;
import java.util.Date;
/**
* 日期处理
* Copyright (c) 人人开源 All rights reserved.
* Date processing
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class DateUtils {
/**
* 时间格式(yyyy-MM-dd)
* Time format (yyyy-MM-dd)
*/
public final static String DATE_PATTERN = "yyyy-MM-dd";
/**
* 时间格式(yyyy-MM-dd HH:mm:ss)
* Time format (yyyy-MM-dd HH:mm:ss)
*/
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public final static String DATE_TIME_MILLIS_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* 日期格式化 日期格式为:yyyy-MM-dd
* Date formatting with format: yyyy-MM-dd
*
* @param date 日期
* @return 返回yyyy-MM-dd格式日期
* @param date Date
* @return Returns date in yyyy-MM-dd format
*/
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
/**
* 日期格式化 日期格式为:yyyy-MM-dd
* Date formatting with format: yyyy-MM-dd
*
* @param date 日期
* @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
* @return 返回yyyy-MM-dd格式日期
* @param date Date
* @param pattern Format, e.g.: DateUtils.DATE_TIME_PATTERN
* @return Returns date in yyyy-MM-dd format
*/
public static String format(Date date, String pattern) {
if (date != null) {
@ -50,11 +50,11 @@ public class DateUtils {
}
/**
* 日期解析
* Date parsing
*
* @param date 日期
* @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
* @return 返回Date
* @param date Date
* @param pattern Format, e.g.: DateUtils.DATE_TIME_PATTERN
* @return Returns Date
*/
public static Date parse(String date, String pattern) {
try {
@ -79,7 +79,7 @@ public class DateUtils {
}
/**
* 获取简短的时间字符串:10秒前返回刚刚,多少秒前,几小时前,超过一周返回年月日时分秒
* Get short time string: returns "just now" for 10 seconds ago, "X seconds ago", "X hours ago", returns full date time for over a week
* @param date
* @return
*/
@ -87,29 +87,29 @@ public class DateUtils {
if (date == null) {
return null;
}
// 将 Date 转换为 Instant
// Convert Date to Instant
LocalDateTime localDateTime = date.toInstant()
// 获取系统默认时区
// Get system default timezone
.atZone(ZoneId.systemDefault())
// 转换为 LocalDateTime
// Convert to LocalDateTime
.toLocalDateTime();
// 当前时间
// Current time
LocalDateTime now = LocalDateTime.now();
// 时间差,单位为秒
// Time difference in seconds
long secondsBetween = ChronoUnit.SECONDS.between(localDateTime, now);
if (secondsBetween <= 10) {
return "刚刚";
return "just now";
} else if (secondsBetween < 60) {
return secondsBetween + "秒前";
return secondsBetween + " seconds ago";
} else if (secondsBetween < 60 * 60) {
return secondsBetween / 60 + "分钟前";
return secondsBetween / 60 + " minutes ago";
} else if (secondsBetween < 86400) {
return secondsBetween / 3600 + "小时前";
return secondsBetween / 3600 + " hours ago";
} else if (secondsBetween < 604800) {
return secondsBetween / 86400 + "天前";
return secondsBetween / 86400 + " days ago";
} else {
// 超过一周,显示完整日期时间
// Over a week, show full date time
return format(date,DATE_TIME_PATTERN);
}
}

View file

@ -6,38 +6,38 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 哈希加密算法的工具类
* Hash encryption algorithm utility class
* @author zjy
*/
@Slf4j
public class HashEncryptionUtil {
/**
* 使用md5进行加密
* @param context 被加密的内容
* @return 哈希值
* Encrypt using md5
* @param context Content to be encrypted
* @return Hash value
*/
public static String Md5hexDigest(String context){
return hexDigest(context,"MD5");
}
/**
* 指定哈希算法进行加密
* @param context 被加密的内容
* @param algorithm 哈希算法
* @return 哈希值
* Encrypt using specified hash algorithm
* @param context Content to be encrypted
* @param algorithm Hash algorithm
* @return Hash value
*/
public static String hexDigest(String context,String algorithm ){
// 获取MD5算法实例
// Get MD5 algorithm instance
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
log.error("加密失败的算法:{}",algorithm);
throw new RuntimeException("加密失败,"+ algorithm +"哈希算法系统不支持");
log.error("Encryption failed algorithm: {}",algorithm);
throw new RuntimeException("Encryption failed, system does not support "+ algorithm +" hash algorithm");
}
// 计算智能体id的MD5值
// Calculate MD5 value of agent id
byte[] messageDigest = md.digest(context.getBytes());
// 将字节数组转换为十六进制字符串
// Convert byte array to hexadecimal string
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xFF & b);

View file

@ -18,7 +18,7 @@ import xiaozhi.common.exception.RenException;
/**
* Http
* Copyright (c) 人人开源 All rights reserved.
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class HttpContextUtils {
@ -71,22 +71,22 @@ public class HttpContextUtils {
}
public static String getLanguage() {
// 默认语言
String defaultLanguage = "zh-CN";
// Default language
String defaultLanguage = "en-US";
// request
HttpServletRequest request = getHttpServletRequest();
if (request == null) {
return defaultLanguage;
}
// 请求语言
// Request language
defaultLanguage = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
return defaultLanguage;
}
/**
* 获取客户端的唯一标识
* Get client unique identifier
*
* @return
*/

View file

@ -6,17 +6,17 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
/**
* IP地址
* Copyright (c) 人人开源 All rights reserved.
* IP address
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Slf4j
public class IpUtils {
/**
* 获取IP地址
* Get IP address
* <p>
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
* When using reverse proxy software like Nginx, cannot get IP address through request.getRemoteAddr()
* If multiple levels of reverse proxy are used, X-Forwarded-For will contain multiple IP addresses, and the first non-unknown valid IP string in X-Forwarded-For is the real IP address
*/
public static String getIpAddr(HttpServletRequest request) {
String unknown = "unknown";

View file

@ -2,7 +2,7 @@ package xiaozhi.common.utils;
import lombok.Data;
/**
* JSON-RPC2.0 格式规范对象
* JSON-RPC2.0 format specification object
*/
@Data
public class JsonRpcTwo {

View file

@ -10,8 +10,8 @@ import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
/**
* JSON 工具类
* Copyright (c) 人人开源 All rights reserved.
* JSON utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class JsonUtils {

View file

@ -4,8 +4,8 @@ import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
/**
* 国际化
* Copyright (c) 人人开源 All rights reserved.
* Internationalization
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class MessageUtils {
@ -17,7 +17,7 @@ public class MessageUtils {
public static String getMessage(int code, String... params) {
if (messageSource == null) {
// 延迟初始化,确保Spring上下文已完全初始化
// Initialize lazily after the Spring context is fully ready.
messageSource = (MessageSource) SpringContextUtils.getBean("messageSource");
}
return messageSource.getMessage(code + "", params, LocaleContextHolder.getLocale());

View file

@ -3,7 +3,7 @@ package xiaozhi.common.utils;
import org.springframework.stereotype.Component;
/**
* 获取配置文件信息
* Get configuration file information
* Copyright xin-nan.com
*/
@Component

View file

@ -14,7 +14,7 @@ import java.io.IOException;
import java.io.InputStreamReader;
/**
* 资源处理工具
* Resource processing utility
*/
@AllArgsConstructor
@Slf4j
@ -23,9 +23,9 @@ public class ResourcesUtils {
private ResourceLoader resourceLoader;
/**
* 读取资源,返回字符串
* @param fileName 资源路径:resources下开始
* @return 字符串
* Read resource, return string
* @param fileName Resource path: starting from resources
* @return String
*/
public String loadString(String fileName) {
Resource resource = resourceLoader.getResource("classpath:" + fileName);
@ -37,7 +37,7 @@ public class ResourcesUtils {
luaScriptBuilder.append(line).append("\n");
}
} catch (IOException e){
log.error("方法:loadString()读取资源失败--{}",e.getMessage());
log.error("Method: loadString() failed to read resource--{}",e.getMessage());
throw new RenException(ErrorCode.RESOURCE_READ_ERROR);
}
return luaScriptBuilder.toString();

View file

@ -7,28 +7,28 @@ import lombok.Data;
import xiaozhi.common.exception.ErrorCode;
/**
* 响应数据
* Copyright (c) 人人开源 All rights reserved.
* Response data
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@Schema(description = "响应")
@Schema(description = "Response")
public class Result<T> implements Serializable {
/**
* 编码:0表示成功,其他值表示失败
* Code: 0 indicates success, other values indicate failure
*/
@Schema(description = "编码:0表示成功,其他值表示失败")
@Schema(description = "Code: 0 indicates success, other values indicate failure")
private int code = 0;
/**
* 消息内容
* Message content
*/
@Schema(description = "消息内容")
@Schema(description = "Message content")
private String msg = "success";
/**
* 响应数据
* Response data
*/
@Schema(description = "响应数据")
@Schema(description = "Response data")
private T data;
public Result<T> ok(T data) {
@ -60,4 +60,4 @@ public class Result<T> implements Serializable {
return this;
}
}
}

View file

@ -1,7 +1,7 @@
package xiaozhi.common.utils;
/**
* 返回响应体工具类
* Response body utility class
*/
public class ResultUtils
{

View file

@ -21,16 +21,16 @@ import java.util.HashMap;
import java.util.Map;
/**
* SM2加密工具类(采用十六进制格式,与chancheng-archive-service项目保持一致)
* SM2 encryption utility that uses hexadecimal encoding.
*/
public class SM2Utils {
/**
* 公钥常量
* Public-key map key.
*/
public static final String KEY_PUBLIC_KEY = "publicKey";
/**
* 私钥返回值常量
* Private-key map key.
*/
public static final String KEY_PRIVATE_KEY = "privateKey";
@ -39,78 +39,78 @@ public class SM2Utils {
}
/**
* SM2加密算法
* Encrypt plaintext with SM2.
*
* @param publicKey 十六进制公钥
* @param data 明文数据
* @return 十六进制密文
* @param publicKey hexadecimal public key
* @param data plaintext data
* @return hexadecimal ciphertext
*/
public static String encrypt(String publicKey, String data) {
try {
// 获取一条SM2曲线参数
// Load SM2 curve parameters.
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
// 构造ECC算法参数,曲线方程、椭圆曲线G点、大整数N
// Build ECC domain parameters.
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
//提取公钥点
// Extract the public-key point.
ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));
// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
// 02 or 03 indicates a compressed key, while 04 indicates an uncompressed key.
ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);
SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
// 设置sm2为加密模式
// Initialize SM2 in encryption mode.
sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
byte[] in = data.getBytes(StandardCharsets.UTF_8);
byte[] arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
return Hex.toHexString(arrayOfBytes);
} catch (Exception e) {
throw new RuntimeException("SM2加密失败", e);
throw new RuntimeException("SM2 encryption failed", e);
}
}
/**
* SM2解密算法
* Decrypt ciphertext with SM2.
*
* @param privateKey 十六进制私钥
* @param cipherData 十六进制密文数据
* @return 明文
* @param privateKey hexadecimal private key
* @param cipherData hexadecimal ciphertext
* @return plaintext
*/
public static String decrypt(String privateKey, String cipherData) {
try {
// 使用BC库加解密时密文以04开头,传入的密文前面没有04则补上
// Bouncy Castle expects ciphertext to start with 04, so prepend it when needed.
if (!cipherData.startsWith("04")) {
cipherData = "04" + cipherData;
}
byte[] cipherDataByte = Hex.decode(cipherData);
BigInteger privateKeyD = new BigInteger(privateKey, 16);
//获取一条SM2曲线参数
// Load SM2 curve parameters.
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
//构造domain参数
// Build domain parameters.
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
// 设置sm2为解密模式
// Initialize SM2 in decryption mode.
sm2Engine.init(false, privateKeyParameters);
byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
return new String(arrayOfBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("SM2解密失败", e);
throw new RuntimeException("SM2 decryption failed", e);
}
}
/**
* 生成密钥对
* Generate a key pair.
*/
public static Map<String, String> createKey() {
try {
ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
// 获取一个椭圆曲线类型的密钥对生成器
// Get an elliptic-curve key-pair generator.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
// 使用SM2参数初始化生成器
// Initialize the generator with SM2 parameters.
kpg.initialize(sm2Spec);
// 获取密钥对
// Generate the key pair.
KeyPair keyPair = kpg.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
BCECPublicKey p = (BCECPublicKey) publicKey;
@ -122,9 +122,9 @@ public class SM2Utils {
result.put(KEY_PRIVATE_KEY, Hex.toHexString(s.getD().toByteArray()));
return result;
} catch (Exception e) {
throw new RuntimeException("生成SM2密钥对失败", e);
throw new RuntimeException("Failed to generate SM2 key pair", e);
}
}
}
}

View file

@ -11,24 +11,24 @@ import org.apache.commons.lang3.StringUtils;
import cn.hutool.json.JSONObject;
/**
* 敏感数据处理工具类
* Utility helpers for sensitive data handling.
*/
public class SensitiveDataUtils {
// 敏感字段列表
// List of sensitive fields.
private static final Set<String> SENSITIVE_FIELDS = new HashSet<>(Arrays.asList(
"api_key", "personal_access_token", "access_token", "token",
"secret", "access_key_secret", "secret_key"));
/**
* 检查字段是否为敏感字段
* Check whether the field is sensitive.
*/
public static boolean isSensitiveField(String fieldName) {
return StringUtils.isNotBlank(fieldName) && SENSITIVE_FIELDS.contains(fieldName.toLowerCase());
}
/**
* 隐藏字符串中间部分
* Mask the middle section of a string.
*/
public static String maskMiddle(String value) {
if (StringUtils.isBlank(value) || value.length() == 1) {
@ -37,10 +37,10 @@ public class SensitiveDataUtils {
int length = value.length();
if (length <= 8) {
// 短字符串保留前2后2
// Short strings keep the first two and last two characters.
return value.substring(0, 2) + "****" + value.substring(length - 2);
} else {
// 长字符串保留前4后4
// Long strings keep the first four and last four characters.
int maskLength = length - 8;
StringBuilder maskBuilder = new StringBuilder();
for (int i = 0; i < maskLength; i++) {
@ -51,18 +51,18 @@ public class SensitiveDataUtils {
}
/**
* 判断字符串是否是被掩码处理过的值
* Check whether the string is already masked.
*/
public static boolean isMaskedValue(String value) {
if (StringUtils.isBlank(value)) {
return false;
}
// 掩码值至少包含4个连续的*
// A masked value should include at least four consecutive asterisks.
return value.contains("****");
}
/**
* 处理JSONObject中的敏感字段
* Mask sensitive fields in a JSONObject.
*/
public static JSONObject maskSensitiveFields(JSONObject jsonObject) {
if (jsonObject == null) {
@ -87,8 +87,8 @@ public class SensitiveDataUtils {
}
/**
* 比较两个JSONObject的敏感字段是否相同
* 特别针对api_key等敏感字段进行单独比较
* Compare the sensitive fields of two JSONObjects.
* This is primarily used for fields such as api_key.
*/
public static boolean isSensitiveDataEqual(JSONObject original, JSONObject updated) {
if (original == null && updated == null) {
@ -98,7 +98,7 @@ public class SensitiveDataUtils {
return false;
}
// 提取并比较特定敏感字段
// Extract and compare the supported sensitive fields.
return compareSpecificSensitiveFields(original, updated, "api_key") &&
compareSpecificSensitiveFields(original, updated, "personal_access_token") &&
compareSpecificSensitiveFields(original, updated, "access_token") &&
@ -109,24 +109,24 @@ public class SensitiveDataUtils {
}
/**
* 比较两个JSON对象中特定敏感字段是否相同
* 遍历整个JSON对象树,查找并比较指定敏感字段
* Compare a specific sensitive field across two JSON objects.
* Traverse the full JSON tree to find and compare the requested field.
*/
private static boolean compareSpecificSensitiveFields(JSONObject original, JSONObject updated, String fieldName) {
// 提取原始对象中的指定敏感字段
// Extract the target sensitive field from the original object.
Map<String, String> originalFields = new HashMap<>();
extractSpecificSensitiveField(original, originalFields, fieldName, "");
// 提取更新对象中的指定敏感字段
// Extract the target sensitive field from the updated object.
Map<String, String> updatedFields = new HashMap<>();
extractSpecificSensitiveField(updated, updatedFields, fieldName, "");
// 如果字段数量不同,说明有增删
// Different field counts mean entries were added or removed.
if (originalFields.size() != updatedFields.size()) {
return false;
}
// 比较每个字段的值
// Compare every field value.
for (Map.Entry<String, String> entry : originalFields.entrySet()) {
String key = entry.getKey();
String originalValue = entry.getValue();
@ -141,7 +141,7 @@ public class SensitiveDataUtils {
}
/**
* 递归提取JSON对象中指定名称的敏感字段
* Recursively extract sensitive fields with the requested name.
*/
private static void extractSpecificSensitiveField(JSONObject jsonObject, Map<String, String> fieldsMap,
String targetFieldName, String parentPath) {
@ -154,12 +154,12 @@ public class SensitiveDataUtils {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
// 递归处理嵌套JSON对象
// Recurse into nested JSON objects.
extractSpecificSensitiveField((JSONObject) value, fieldsMap, targetFieldName, fullPath);
} else if (value instanceof String && key.equalsIgnoreCase(targetFieldName)) {
// 找到目标敏感字段,保存其路径和值
// Found the target sensitive field. Save its path and value.
fieldsMap.put(fullPath, (String) value);
}
}
}
}
}

View file

@ -8,34 +8,34 @@ import xiaozhi.modules.security.service.CaptchaService;
import xiaozhi.modules.sys.service.SysParamsService;
/**
* SM2解密和验证码验证工具类
* 封装了重复的SM2解密、验证码提取和验证逻辑
* Utility for SM2 decryption and captcha validation.
* Encapsulates shared logic for decrypting SM2 payloads, extracting captchas, and validating them.
*/
public class Sm2DecryptUtil {
/**
* 验证码长度
* Captcha length.
*/
private static final int CAPTCHA_LENGTH = 5;
/**
* 解密SM2加密内容,提取验证码并验证
*
* @param encryptedPassword SM2加密的密码字符串
* @param captchaId 验证码ID
* @param captchaService 验证码服务
* @param sysParamsService 系统参数服务
* @return 解密后的实际密码
* Decrypt SM2-encrypted content, extract the captcha, and validate it.
*
* @param encryptedPassword SM2-encrypted password string
* @param captchaId captcha ID
* @param captchaService captcha service
* @param sysParamsService system-parameter service
* @return decrypted actual password
*/
public static String decryptAndValidateCaptcha(String encryptedPassword, String captchaId,
CaptchaService captchaService, SysParamsService sysParamsService) {
// 获取SM2私钥
// Load the SM2 private key.
String privateKeyStr = sysParamsService.getValue(Constant.SM2_PRIVATE_KEY, true);
if (StringUtils.isBlank(privateKeyStr)) {
throw new RenException(ErrorCode.SM2_KEY_NOT_CONFIGURED);
}
// 使用SM2私钥解密密码
// Decrypt the password with the SM2 private key.
String decryptedContent;
try {
decryptedContent = SM2Utils.decrypt(privateKeyStr, encryptedPassword);
@ -43,7 +43,7 @@ public class Sm2DecryptUtil {
throw new RenException(ErrorCode.SM2_DECRYPT_ERROR);
}
// 分离验证码和密码:前5位是验证码,后面是密码
// Split captcha and password: the first 5 characters are the captcha and the rest is the password.
if (decryptedContent.length() > CAPTCHA_LENGTH) {
String embeddedCaptcha = decryptedContent.substring(0, CAPTCHA_LENGTH);
String actualPassword = decryptedContent.substring(CAPTCHA_LENGTH);
@ -60,4 +60,4 @@ public class Sm2DecryptUtil {
throw new RenException(ErrorCode.SM2_DECRYPT_ERROR);
}
}
}
}

View file

@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring Context 工具类
* Spring Context utility class
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {

View file

@ -12,20 +12,20 @@ import java.util.Map;
import java.util.Set;
/**
* 通用工具类
* General utility helpers.
*/
public class ToolUtil {
private static final Logger logger = LoggerFactory.getLogger(ToolUtil.class);
/**
* 对象是否不为空(新增)
* Whether an object is not empty.
*/
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
/**
* 对象是否为空
* Whether an object is empty.
*/
public static boolean isEmpty(Object o) {
if (o == null) {
@ -64,7 +64,7 @@ public class ToolUtil {
}
/**
* 对象组中是否存在空对象
* Whether any object in the group is empty.
*/
public static boolean isOneEmpty(Object... os) {
for (Object o : os) {
@ -76,7 +76,7 @@ public class ToolUtil {
}
/**
* 对象组中是否全是空对象
* Whether all objects in the group are empty.
*/
public static boolean isAllEmpty(Object... os) {
for (Object o : os) {

View file

@ -7,24 +7,24 @@ import java.util.List;
import lombok.Data;
/**
* 树节点,所有需要实现树节点的,都需要继承该类
* Copyright (c) 人人开源 All rights reserved.
* Tree node, all classes that need to implement tree nodes should inherit from this class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
public class TreeNode<T> implements Serializable {
/**
* 主键
* Primary key
*/
private Long id;
/**
* 上级ID
* Parent ID
*/
private Long pid;
/**
* 子节点列表
* Child node list
*/
private List<T> children = new ArrayList<>();
}
}

View file

@ -8,17 +8,17 @@ import java.util.Map;
import xiaozhi.common.validator.AssertUtils;
/**
* 树形结构工具类,如:菜单、部门等
* Copyright (c) 人人开源 All rights reserved.
* Tree structure utility class, such as: menu, department, etc.
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class TreeUtils {
/**
* 根据pid,构建树节点
* Build tree nodes based on pid
*/
public static <T extends TreeNode<T>> List<T> build(List<T> treeNodes, Long pid) {
// pid不能为空
// pid cannot be null
AssertUtils.isNull(pid, "pid");
List<T> treeList = new ArrayList<>();
@ -32,7 +32,7 @@ public class TreeUtils {
}
/**
* 查找子节点
* Find child nodes
*/
private static <T extends TreeNode<T>> T findChildren(List<T> treeNodes, T rootNode) {
for (T treeNode : treeNodes) {
@ -44,12 +44,12 @@ public class TreeUtils {
}
/**
* 构建树节点
* Build tree nodes
*/
public static <T extends TreeNode<T>> List<T> build(List<T> treeNodes) {
List<T> result = new ArrayList<>();
// list转map
// Convert list to map
Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
for (T treeNode : treeNodes) {
nodeMap.put(treeNode.getId(), treeNode);
@ -68,4 +68,4 @@ public class TreeUtils {
return result;
}
}
}

View file

@ -12,8 +12,8 @@ import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
/**
* 校验工具类
* Copyright (c) 人人开源 All rights reserved.
* Validation utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class AssertUtils {
@ -87,4 +87,4 @@ public class AssertUtils {
throw new RenException(code, params);
}
}
}
}

View file

@ -15,8 +15,8 @@ import jakarta.validation.Validator;
import xiaozhi.common.exception.RenException;
/**
* hibernate-validator校验工具类
* 参考文档:http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/
* hibernate-validator validation utility class
* Reference documentation: http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/
*/
public class ValidatorUtils {
@ -28,10 +28,10 @@ public class ValidatorUtils {
}
/**
* 校验对象
* Validate object
*
* @param object 待校验对象
* @param groups 待校验的组
* @param object Object to be validated
* @param groups Groups to be validated
*/
public static void validateEntity(Object object, Class<?>... groups)
throws RenException {
@ -48,9 +48,9 @@ public class ValidatorUtils {
}
/**
* 国际手机号正则表达式
* 要求必须带国际区号,格式:+[国家代码][手机号]
* 例如:
* International phone number regular expression
* Must include international area code, format: +[country code][phone number]
* For example:
* - +8613800138000
* - +12345678900
* - +447123456789
@ -58,11 +58,11 @@ public class ValidatorUtils {
private static final String INTERNATIONAL_PHONE_REGEX = "^\\+[1-9]\\d{0,3}[1-9]\\d{4,14}$";
/**
* 校验手机号是否有效
* 要求必须带国际区号,格式:+[国家代码][手机号]
* 例如:+8613800138000
* Validate if phone number is valid
* Must include international area code, format: +[country code][phone number]
* For example: +8613800138000
*
* @param phone 手机号
* @param phone Phone number
* @return boolean
*/
public static boolean isValidPhone(String phone) {
@ -70,7 +70,7 @@ public class ValidatorUtils {
return false;
}
// 验证必须带国际区号的手机号格式
// Validate phone number format with international area code
Pattern pattern = Pattern.compile(INTERNATIONAL_PHONE_REGEX);
return pattern.matcher(phone).matches();
}

View file

@ -1,7 +1,7 @@
package xiaozhi.common.validator.group;
/**
* 新增 Group
* Add Group
*/
public interface AddGroup {

View file

@ -1,7 +1,7 @@
package xiaozhi.common.validator.group;
/**
* 默认 Group
* Default Group
*/
public interface DefaultGroup {

View file

@ -1,7 +1,7 @@
package xiaozhi.common.validator.group;
/**
* 修改 Group
* Update Group
*/
public interface UpdateGroup {

View file

@ -6,35 +6,35 @@ import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
/**
* SQL过滤
* Copyright (c) 人人开源 All rights reserved.
* SQL filtering
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class SqlFilter {
/**
* SQL注入过滤
* SQL injection filtering
*
* @param str 待验证的字符串
* @param str String to be validated
*/
public static String sqlInject(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
// 去掉'|"|;|\字符
// Remove '|"|;|\ characters
str = StringUtils.replace(str, "'", "");
str = StringUtils.replace(str, "\"", "");
str = StringUtils.replace(str, ";", "");
str = StringUtils.replace(str, "\\", "");
// 转换成小写
// Convert to lowercase
str = str.toLowerCase();
// 非法字符
// Illegal characters
String[] keywords = { "master", "truncate", "insert", "select", "delete", "update", "declare", "alter",
"drop" };
// 判断是否包含非法字符
// Check if contains illegal characters
for (String keyword : keywords) {
if (str.contains(keyword)) {
throw new RenException(ErrorCode.INVALID_SYMBOL);

View file

@ -10,8 +10,8 @@ import org.springframework.util.PathMatcher;
import jakarta.servlet.DispatcherType;
/**
* XSS 配置文件
* Copyright (c) 人人开源 All rights reserved.
* XSS configuration file
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Configuration

View file

@ -14,15 +14,19 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
/**
* XSS过滤
* Copyright (c) 人人开源 All rights reserved.
* XSS filtering
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@AllArgsConstructor
public class XssFilter implements Filter {
private final XssProperties properties;
private final PathMatcher pathMatcher;
public XssFilter(XssProperties properties, PathMatcher pathMatcher) {
this.properties = properties;
this.pathMatcher = pathMatcher;
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@ -32,7 +36,7 @@ public class XssFilter implements Filter {
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 放行
// Allow
if (shouldNotFilter(httpServletRequest)) {
chain.doFilter(request, response);
@ -43,7 +47,7 @@ public class XssFilter implements Filter {
}
private boolean shouldNotFilter(HttpServletRequest request) {
// 放行不过滤的URL
// Allow URLs that should not be filtered
return properties.getExcludeUrls().stream()
.anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getServletPath()));
}

View file

@ -17,8 +17,8 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
/**
* XSS过滤处理
* Copyright (c) 人人开源 All rights reserved.
* XSS filtering processing
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
@ -29,18 +29,18 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
@Override
public ServletInputStream getInputStream() throws IOException {
// 非json类型,直接返回
// Non-json type, return directly
if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
return super.getInputStream();
}
// 为空,直接返回
// If empty, return directly
String json = IoUtil.readUtf8(super.getInputStream());
if (StringUtils.isBlank(json)) {
return super.getInputStream();
}
// xss过滤
// XSS filtering
json = xssEncode(json);
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
return new ServletInputStream() {
@ -115,4 +115,4 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
return XssUtils.filter(input);
}
}
}

View file

@ -8,19 +8,23 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* XSS 配置项
* Copyright (c) 人人开源 All rights reserved.
* XSS configuration items
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@ConfigurationProperties(prefix = "renren.xss")
public class XssProperties {
/**
* 是否开启 XSS
* Whether to enable XSS
*/
private boolean enabled;
/**
* 排除的URL列表
* Excluded URL list
*/
private List<String> excludeUrls = Collections.emptyList();
public List<String> getExcludeUrls() {
return excludeUrls;
}
}

View file

@ -4,25 +4,25 @@ import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
/**
* XSS过滤工具类
* Copyright (c) 人人开源 All rights reserved.
* XSS filtering utility class
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class XssUtils extends Safelist {
/**
* XSS过滤
* XSS filtering
*/
public static String filter(String html) {
return Jsoup.clean(html, xssWhitelist());
}
/**
* XSS过滤白名单
* XSS filtering whitelist
*/
private static Safelist xssWhitelist() {
return new Safelist()
// 支持的标签
// Supported tags
.addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl",
"dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "ol", "p", "pre", "q",
"small",
@ -30,7 +30,7 @@ public class XssUtils extends Safelist {
"ul",
"embed", "object", "param", "span")
// 支持的标签属性
// Supported tag attributes
.addAttributes("a", "href", "class", "style", "target", "rel", "nofollow")
.addAttributes("blockquote", "cite")
.addAttributes("code", "class", "style")
@ -55,7 +55,7 @@ public class XssUtils extends Safelist {
.addAttributes("param", "name", "value")
.addAttributes("span", "class", "style")
// 标签属性对应的协议
// Protocols corresponding to tag attributes
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("img", "src", "http", "https")
.addProtocols("blockquote", "cite", "http", "https")

View file

@ -4,7 +4,7 @@ package xiaozhi.modules.agent.Enums;
import lombok.Getter;
/**
* 智能体聊天记录类型
* Agent chat history type
*/
@Getter
public enum AgentChatHistoryType {

View file

@ -7,16 +7,16 @@ import java.util.Map;
/**
* 小智MCP JSON-RPC 请求json
* XiaoZhi MCP JSON-RPC request json
*/
public class XiaoZhiMcpJsonRpcJson {
//小智初始化mcp请求json
//XiaoZhi initialize MCP request json
private static final String INITIALIZE_JSON;
//小智mcp初始化成功,返回通知请求json
//XiaoZhi MCP initialization successful, return notification request json
private static final String NOTIFICATIONS_INITIALIZED_JSON;
//小智mcp获取mcp工具集合请求json
//XiaoZhi MCP get MCP tool collection request json
private static final String TOOLS_LIST_REQUEST;
// 延迟加载
// Lazy loading
static {
INITIALIZE_JSON = JsonUtils.toJsonString(new JsonRpcTwo("initialize",
Map.of(

View file

@ -42,7 +42,7 @@ import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体聊天历史管理")
@Tag(name = "Agent Chat History Management")
@RequiredArgsConstructor
@RestController
@RequestMapping("/agent/chat-history")
@ -53,13 +53,13 @@ public class AgentChatHistoryController {
private final RedisUtils redisUtils;
/**
* 小智服务聊天上报请求
* XiaoZhi service chat report request
* <p>
* 小智服务聊天上报请求,包含Base64编码的音频数据和相关信息。
* XiaoZhi service chat report request, including Base64 encoded audio data and related information.
*
* @param request 包含上传文件及相关信息的请求对象
* @param request Request object containing uploaded file and related information
*/
@Operation(summary = "小智服务聊天上报请求")
@Operation(summary = "XiaoZhi service chat report request")
@PostMapping("/report")
public Result<Boolean> uploadFile(@Valid @RequestBody AgentChatHistoryReportDTO request) {
Boolean result = agentChatHistoryBizService.report(request);
@ -67,50 +67,50 @@ public class AgentChatHistoryController {
}
/**
* 获取聊天记录下载链接
*
* @param agentId 智能体ID
* @param sessionId 会话ID
* @return UUID作为下载标识
* Get a download link for chat history.
*
* @param agentId agent ID
* @param sessionId session ID
* @return UUID used as the download token
*/
@Operation(summary = "获取聊天记录下载链接")
@Operation(summary = "Get chat-history download link")
@RequiresPermissions("sys:role:normal")
@PostMapping("/getDownloadUrl/{agentId}/{sessionId}")
public Result<String> getDownloadUrl(@PathVariable("agentId") String agentId,
@PathVariable("sessionId") String sessionId) {
// 获取当前用户
// Resolve the current user.
UserDetail user = SecurityUser.getUser();
// 检查权限
// Validate permissions.
if (!agentService.checkAgentPermission(agentId, user.getId())) {
throw new RenException(ErrorCode.CHAT_HISTORY_NO_PERMISSION);
}
// 生成UUID
// Generate a UUID.
String uuid = UUID.randomUUID().toString();
// 存储agentId和sessionId到Redis,格式为agentId:sessionId
// Store agentId and sessionId in Redis as agentId:sessionId.
redisUtils.set(RedisKeys.getChatHistoryKey(uuid), agentId + ":" + sessionId);
return new Result<String>().ok(uuid);
}
/**
* 下载本会话聊天记录
*
* @param uuid 下载标识
* @param response HTTP响应
* Download chat history for the current session.
*
* @param uuid download token
* @param response HTTP response
*/
@Operation(summary = "下载本会话聊天记录")
@Operation(summary = "Download current-session chat history")
@GetMapping("/download/{uuid}/current")
public void downloadCurrentSession(@PathVariable("uuid") String uuid,
HttpServletResponse response) {
// 从Redis获取agentId和sessionId
// Load agentId and sessionId from Redis.
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
if (StringUtils.isBlank(agentSessionInfo)) {
throw new RenException(ErrorCode.DOWNLOAD_LINK_EXPIRED);
}
try {
// 解析agentId和sessionId
// Parse agentId and sessionId.
String[] parts = agentSessionInfo.split(":");
if (parts.length != 2) {
throw new RenException(ErrorCode.DOWNLOAD_LINK_INVALID);
@ -118,32 +118,32 @@ public class AgentChatHistoryController {
String agentId = parts[0];
String sessionId = parts[1];
// 执行下载
// Start the download.
downloadChatHistory(agentId, List.of(sessionId), response);
} finally {
// 下载完成后删除UUID,防止盗刷
// Remove the one-time token after download completes.
redisUtils.delete(RedisKeys.getChatHistoryKey(uuid));
}
}
/**
* 下载本会话及前20条会话聊天记录
*
* @param uuid 下载标识
* @param response HTTP响应
* Download the current session together with up to 20 earlier sessions.
*
* @param uuid download token
* @param response HTTP response
*/
@Operation(summary = "下载本会话及前20条会话聊天记录")
@Operation(summary = "Download current session with up to 20 previous sessions")
@GetMapping("/download/{uuid}/previous")
public void downloadCurrentSessionWithPrevious(@PathVariable("uuid") String uuid,
HttpServletResponse response) {
// 从Redis获取agentId和sessionId
// Load agentId and sessionId from Redis.
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
if (StringUtils.isBlank(agentSessionInfo)) {
throw new RenException(ErrorCode.DOWNLOAD_LINK_EXPIRED);
}
try {
// 解析agentId和sessionId
// Parse agentId and sessionId.
String[] parts = agentSessionInfo.split(":");
if (parts.length != 2) {
throw new RenException(ErrorCode.DOWNLOAD_LINK_INVALID);
@ -151,16 +151,16 @@ public class AgentChatHistoryController {
String agentId = parts[0];
String sessionId = parts[1];
// 获取所有会话列表
// Load the full session list.
Map<String, Object> params = Map.of(
"agentId", agentId,
Constant.PAGE, 1,
Constant.LIMIT, 1000 // 获取足够多的会话
Constant.LIMIT, 1000 // Load enough sessions for the export window.
);
PageData<AgentChatSessionDTO> sessionPage = agentChatHistoryService.getSessionListByAgentId(params);
List<AgentChatSessionDTO> allSessions = sessionPage.getList();
// 查找当前会话在列表中的位置
// Find the position of the current session in the list.
int currentIndex = -1;
for (int i = 0; i < allSessions.size(); i++) {
if (allSessions.get(i).getSessionId().equals(sessionId)) {
@ -169,50 +169,50 @@ public class AgentChatHistoryController {
}
}
// 如果找到了当前会话,收集当前会话及前20条会话ID
// If the current session was found, collect it and the next 20 sessions in the ordered list.
List<String> sessionIdsToDownload = new ArrayList<>();
if (currentIndex != -1) {
// 从当前会话开始,向后(数组后面)取最多20条会话(包括当前会话)
int endIndex = Math.min(allSessions.size() - 1, currentIndex + 20); // 确保不越界
// Start from the current session and include at most 20 later entries in the array.
int endIndex = Math.min(allSessions.size() - 1, currentIndex + 20); // Keep index bounds safe.
for (int i = currentIndex; i <= endIndex; i++) {
sessionIdsToDownload.add(allSessions.get(i).getSessionId());
}
}
// 如果没有找到当前会话,至少下载当前会话
// If the current session was not found, at least download that session.
if (sessionIdsToDownload.isEmpty()) {
sessionIdsToDownload.add(sessionId);
}
downloadChatHistory(agentId, sessionIdsToDownload, response);
} finally {
// 下载完成后删除UUID,防止盗刷
// Remove the one-time token after download completes.
redisUtils.delete(RedisKeys.getChatHistoryKey(uuid));
}
}
/**
* 下载指定会话的聊天记录
*
* @param agentId 智能体ID
* @param sessionIds 会话ID列表
* @param response HTTP响应
* Download chat history for the specified sessions.
*
* @param agentId agent ID
* @param sessionIds session ID list
* @param response HTTP response
*/
private void downloadChatHistory(String agentId, List<String> sessionIds, HttpServletResponse response) {
try {
// 设置响应头
// Set response headers.
response.setContentType("text/plain;charset=UTF-8");
String fileName = URLEncoder.encode("history.txt", StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 获取聊天记录并写入响应流
// Load chat history and stream it to the response.
try (OutputStream out = response.getOutputStream()) {
// 为每个会话生成聊天记录
// Emit history for each session.
for (String sessionId : sessionIds) {
// 获取该会话的所有聊天记录
// Load all chat messages for this session.
List<AgentChatHistoryDTO> chatHistoryList = agentChatHistoryService
.getChatHistoryBySessionId(agentId, sessionId);
// 从聊天记录中获取第一条消息的创建时间作为会话时间
// Use the first message timestamp as the session timestamp.
if (!chatHistoryList.isEmpty()) {
Date firstMessageTime = chatHistoryList.get(0).getCreatedAt();
String sessionTimeStr = DateUtils.format(firstMessageTime, DateUtils.DATE_TIME_PATTERN);
@ -231,7 +231,7 @@ public class AgentChatHistoryController {
out.write(line.getBytes(StandardCharsets.UTF_8));
}
// 会话之间添加空行分隔
// Separate sessions with a blank line.
if (sessionIds.indexOf(sessionId) < sessionIds.size() - 1) {
out.write("\n".getBytes(StandardCharsets.UTF_8));
}

View file

@ -58,7 +58,7 @@ import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体管理")
@Tag(name = "Agent Management")
@AllArgsConstructor
@RestController
@RequestMapping("/agent")
@ -75,24 +75,24 @@ public class AgentController {
private final AgentTagService agentTagService;
@GetMapping("/list")
@Operation(summary = "获取用户智能体列表")
@Operation(summary = "Get user agent list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentDTO>> getUserAgents(
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "searchType", defaultValue = "name") String searchType) {
UserDetail user = SecurityUser.getUser();
// 直接调用整合后的getUserAgents方法,无需再区分搜索和普通查询
// Call the unified getUserAgents method directly without splitting search and regular queries.
List<AgentDTO> agents = agentService.getUserAgents(user.getId(), keyword, searchType);
return new Result<List<AgentDTO>>().ok(agents);
}
@GetMapping("/all")
@Operation(summary = "智能体列表(管理员)")
@Operation(summary = "List agents (admin)")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<AgentEntity>> adminAgentList(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
@ -101,7 +101,7 @@ public class AgentController {
}
@GetMapping("/{id}")
@Operation(summary = "获取智能体详情")
@Operation(summary = "Get agent details")
@RequiresPermissions("sys:role:normal")
public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) {
AgentInfoVO agent = agentService.getAgentById(id);
@ -109,7 +109,7 @@ public class AgentController {
}
@PostMapping
@Operation(summary = "创建智能体")
@Operation(summary = "Create agent")
@RequiresPermissions("sys:role:normal")
public Result<String> save(@RequestBody @Valid AgentCreateDTO dto) {
String agentId = agentService.createAgent(dto);
@ -117,7 +117,7 @@ public class AgentController {
}
@PutMapping("/saveMemory/{macAddress}")
@Operation(summary = "根据设备id更新智能体")
@Operation(summary = "Update an agent by device ID")
public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) {
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
if (device == null) {
@ -130,23 +130,25 @@ public class AgentController {
}
@PostMapping("/chat-summary/{sessionId}/save")
@Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)")
@Operation(summary = "Generate and save a chat summary by session ID asynchronously")
public Result<Void> generateAndSaveChatSummary(@PathVariable String sessionId) {
try {
// 异步执行总结生成任务,立即返回成功响应
// Run the summary task asynchronously and return success immediately.
new Thread(() -> {
try {
agentChatSummaryService.generateAndSaveChatSummary(sessionId);
System.out.println("异步执行会话 " + sessionId + " 的聊天记录总结完成");
System.out.println("Asynchronous chat-summary generation completed for session " + sessionId);
} catch (Exception e) {
System.err.println("异步执行会话 " + sessionId + " 的聊天记录总结失败: " + e.getMessage());
System.err.println(
"Asynchronous chat-summary generation failed for session " + sessionId + ": "
+ e.getMessage());
}
}).start();
// 立即返回成功响应,不等待总结生成完成
// Return success immediately without waiting for summary generation to finish.
return new Result<Void>().ok(null);
} catch (Exception e) {
return new Result<Void>().error("启动异步总结生成任务失败: " + e.getMessage());
return new Result<Void>().error("Failed to start asynchronous chat-summary generation: " + e.getMessage());
}
}
@ -158,7 +160,7 @@ public class AgentController {
}
@PutMapping("/{id}")
@Operation(summary = "更新智能体")
@Operation(summary = "Update agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) {
agentService.updateAgentById(id, dto);
@ -166,24 +168,24 @@ public class AgentController {
}
@DeleteMapping("/{id}")
@Operation(summary = "删除智能体")
@Operation(summary = "Delete agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable String id) {
// 先删除关联的设备
// Delete related devices first.
deviceService.deleteByAgentId(id);
// 删除关联的聊天记录
// Delete related chat history.
agentChatHistoryService.deleteByAgentId(id, true, true);
// 删除关联的插件
// Delete related plugins.
agentPluginMappingService.deleteByAgentId(id);
// 删除关联的上下文源配置
// Delete related context-provider configuration.
agentContextProviderService.deleteByAgentId(id);
// 再删除智能体
// Delete the agent last.
agentService.deleteById(id);
return new Result<>();
}
@GetMapping("/template")
@Operation(summary = "智能体模板模板列表")
@Operation(summary = "List agent templates")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService
@ -192,11 +194,11 @@ public class AgentController {
}
@GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表")
@Operation(summary = "Get agent session list")
@RequiresPermissions("sys:role:normal")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<AgentChatSessionDTO>> getAgentSessions(
@PathVariable("id") String id,
@ -207,59 +209,59 @@ public class AgentController {
}
@GetMapping("/{id}/chat-history/{sessionId}")
@Operation(summary = "获取智能体聊天记录")
@Operation(summary = "Get agent chat history")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryDTO>> getAgentChatHistory(
@PathVariable("id") String id,
@PathVariable("sessionId") String sessionId) {
// 获取当前用户
// Resolve the current user.
UserDetail user = SecurityUser.getUser();
// 检查权限
// Validate access permissions.
if (!agentService.checkAgentPermission(id, user.getId())) {
return new Result<List<AgentChatHistoryDTO>>().error("没有权限查看该智能体的聊天记录");
return new Result<List<AgentChatHistoryDTO>>().error("You do not have permission to view this agent's chat history");
}
// 查询聊天记录
// Query chat history.
List<AgentChatHistoryDTO> result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId);
return new Result<List<AgentChatHistoryDTO>>().ok(result);
}
@GetMapping("/{id}/chat-history/user")
@Operation(summary = "获取智能体聊天记录(用户)")
@Operation(summary = "Get agent chat history (user)")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentId(
@PathVariable("id") String id) {
// 获取当前用户
// Resolve the current user.
UserDetail user = SecurityUser.getUser();
// 检查权限
// Validate access permissions.
if (!agentService.checkAgentPermission(id, user.getId())) {
return new Result<List<AgentChatHistoryUserVO>>().error("没有权限查看该智能体的聊天记录");
return new Result<List<AgentChatHistoryUserVO>>().error("You do not have permission to view this agent's chat history");
}
// 查询聊天记录
// Query chat history.
List<AgentChatHistoryUserVO> data = agentChatHistoryService.getRecentlyFiftyByAgentId(id);
return new Result<List<AgentChatHistoryUserVO>>().ok(data);
}
@GetMapping("/{id}/chat-history/audio")
@Operation(summary = "获取音频内容")
@Operation(summary = "Get audio content")
@RequiresPermissions("sys:role:normal")
public Result<String> getContentByAudioId(
@PathVariable("id") String id) {
// 查询聊天记录
// Query chat history.
String data = agentChatHistoryService.getContentByAudioId(id);
return new Result<String>().ok(data);
}
@PostMapping("/audio/{audioId}")
@Operation(summary = "获取音频下载ID")
@Operation(summary = "Get audio download ID")
@RequiresPermissions("sys:role:normal")
public Result<String> getAudioId(@PathVariable("audioId") String audioId) {
byte[] audioData = agentChatAudioService.getAudio(audioId);
if (audioData == null) {
return new Result<String>().error("音频不存在");
return new Result<String>().error("Audio was not found");
}
String uuid = UUID.randomUUID().toString();
redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId);
@ -267,7 +269,7 @@ public class AgentController {
}
@GetMapping("/play/{uuid}")
@Operation(summary = "播放音频")
@Operation(summary = "Play audio")
public ResponseEntity<byte[]> playAudio(@PathVariable("uuid") String uuid) {
String audioId = (String) redisUtils.get(RedisKeys.getAgentAudioIdKey(uuid));
@ -287,19 +289,19 @@ public class AgentController {
}
@PostMapping("/tag")
@Operation(summary = "创建标签")
@Operation(summary = "Create tag")
@RequiresPermissions("sys:role:normal")
public Result<AgentTagEntity> createTag(@RequestBody Map<String, String> params) {
String tagName = params.get("tagName");
if (StringUtils.isBlank(tagName)) {
return new Result<AgentTagEntity>().error("标签名称不能为空");
return new Result<AgentTagEntity>().error("Tag name cannot be empty");
}
AgentTagEntity tag = agentTagService.saveTag(tagName);
return new Result<AgentTagEntity>().ok(tag);
}
@GetMapping("/tag/list")
@Operation(summary = "获取所有标签列表")
@Operation(summary = "Get all tags")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTagDTO>> getAllTags() {
List<AgentTagDTO> tags = agentTagService.getAllTags();
@ -307,7 +309,7 @@ public class AgentController {
}
@DeleteMapping("/tag/{id}")
@Operation(summary = "删除标签")
@Operation(summary = "Delete tag")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteTag(@PathVariable String id) {
agentTagService.deleteTag(id);
@ -315,7 +317,7 @@ public class AgentController {
}
@GetMapping("/{id}/tags")
@Operation(summary = "获取智能体的标签")
@Operation(summary = "Get agent tags")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTagDTO>> getAgentTags(@PathVariable String id) {
List<AgentTagDTO> tags = agentTagService.getTagsByAgentId(id);
@ -323,7 +325,7 @@ public class AgentController {
}
@PutMapping("/{id}/tags")
@Operation(summary = "保存智能体的标签")
@Operation(summary = "Save agent tags")
@RequiresPermissions("sys:role:normal")
public Result<Void> saveAgentTags(@PathVariable String id, @RequestBody Map<String, Object> params) {
List<String> tagIds = (List<String>) params.get("tagIds");
@ -332,4 +334,4 @@ public class AgentController {
return new Result<Void>().ok(null);
}
}
}

View file

@ -18,7 +18,7 @@ import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体Mcp接入点管理")
@Tag(name = "Agent MCP Access Point Management")
@RequiredArgsConstructor
@RestController
@RequestMapping("/agent/mcp")
@ -27,19 +27,19 @@ public class AgentMcpAccessPointController {
private final AgentService agentService;
/**
* 获取智能体的Mcp接入点地址
*
* @param agentId 智能体id
* @return 返回错误提醒或者Mcp接入点地址
* Get the MCP access-point address for an agent.
*
* @param agentId agent ID
* @return error information or the MCP access-point address
*/
@Operation(summary = "获取智能体的Mcp接入点地址")
@Operation(summary = "Get agent MCP access-point address")
@GetMapping("/address/{agentId}")
@RequiresPermissions("sys:role:normal")
public Result<String> getAgentMcpAccessAddress(@PathVariable("agentId") String agentId) {
// 获取当前用户
// Resolve the current user.
UserDetail user = SecurityUser.getUser();
// 检查权限
// Validate permissions.
if (!agentService.checkAgentPermission(agentId, user.getId())) {
return new Result<String>().error(ErrorCode.MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION);
}
@ -50,14 +50,14 @@ public class AgentMcpAccessPointController {
return new Result<String>().ok(agentMcpAccessAddress);
}
@Operation(summary = "获取智能体的Mcp工具列表")
@Operation(summary = "Get agent MCP tools")
@GetMapping("/tools/{agentId}")
@RequiresPermissions("sys:role:normal")
public Result<List<String>> getAgentMcpToolsList(@PathVariable("agentId") String agentId) {
// 获取当前用户
// Resolve the current user.
UserDetail user = SecurityUser.getUser();
// 检查权限
// Validate permissions.
if (!agentService.checkAgentPermission(agentId, user.getId())) {
return new Result<List<String>>().error(ErrorCode.MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION);
}

View file

@ -33,7 +33,7 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.service.AgentTemplateService;
import xiaozhi.modules.agent.vo.AgentTemplateVO;
@Tag(name = "智能体模板管理")
@Tag(name = "Agent Template Management")
@AllArgsConstructor
@RestController
@RequestMapping("/agent/template")
@ -42,22 +42,22 @@ public class AgentTemplateController {
private final AgentTemplateService agentTemplateService;
@GetMapping("/page")
@Operation(summary = "获取模板分页列表")
@Operation(summary = "Get template paginated list")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = "agentName", description = "模板名称,模糊查询")
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Number of records per page", required = true),
@Parameter(name = "agentName", description = "Template name, fuzzy search")
})
public Result<PageData<AgentTemplateVO>> getAgentTemplatesPage(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
// 创建分页对象
// Create pagination object
int page = Integer.parseInt(params.getOrDefault(Constant.PAGE, "1").toString());
int limit = Integer.parseInt(params.getOrDefault(Constant.LIMIT, "10").toString());
Page<AgentTemplateEntity> pageInfo = new Page<>(page, limit);
// 创建查询条件
// Create query conditions
QueryWrapper<AgentTemplateEntity> wrapper = new QueryWrapper<>();
String agentName = (String) params.get("agentName");
if (agentName != null && !agentName.isEmpty()) {
@ -65,94 +65,94 @@ public class AgentTemplateController {
}
wrapper.orderByAsc("sort");
// 执行分页查询
// Execute paginated query
IPage<AgentTemplateEntity> pageResult = agentTemplateService.page(pageInfo, wrapper);
// 使用ConvertUtils转换为VO列表
// Use ConvertUtils to convert to VO list
List<AgentTemplateVO> voList = ConvertUtils.sourceToTarget(pageResult.getRecords(), AgentTemplateVO.class);
// 修复:使用构造函数创建PageData对象,而不是无参构造+setter
// Fix: Use constructor to create PageData object instead of no-arg constructor + setter
PageData<AgentTemplateVO> pageData = new PageData<>(voList, pageResult.getTotal());
return new Result<PageData<AgentTemplateVO>>().ok(pageData);
}
@GetMapping("/{id}")
@Operation(summary = "获取模板详情")
@Operation(summary = "Get template details")
@RequiresPermissions("sys:role:superAdmin")
public Result<AgentTemplateVO> getAgentTemplateById(@PathVariable("id") String id) {
AgentTemplateEntity template = agentTemplateService.getById(id);
if (template == null) {
return ResultUtils.error("模板不存在");
return ResultUtils.error("Template does not exist");
}
// 使用ConvertUtils转换为VO
// Use ConvertUtils to convert to VO
AgentTemplateVO vo = ConvertUtils.sourceToTarget(template, AgentTemplateVO.class);
return ResultUtils.success(vo);
}
@PostMapping
@Operation(summary = "创建模板")
@Operation(summary = "Create template")
@RequiresPermissions("sys:role:superAdmin")
public Result<AgentTemplateEntity> createAgentTemplate(@Valid @RequestBody AgentTemplateEntity template) {
// 设置排序值为下一个可用的序号
// Set sort value to next available sequence number
template.setSort(agentTemplateService.getNextAvailableSort());
boolean saved = agentTemplateService.save(template);
if (saved) {
return ResultUtils.success(template);
} else {
return ResultUtils.error("创建模板失败");
return ResultUtils.error("Failed to create template");
}
}
@PutMapping
@Operation(summary = "更新模板")
@Operation(summary = "Update template")
@RequiresPermissions("sys:role:superAdmin")
public Result<AgentTemplateEntity> updateAgentTemplate(@Valid @RequestBody AgentTemplateEntity template) {
boolean updated = agentTemplateService.updateById(template);
if (updated) {
return ResultUtils.success(template);
} else {
return ResultUtils.error("更新模板失败");
return ResultUtils.error("Failed to update template");
}
}
@DeleteMapping("/{id}")
@Operation(summary = "删除模板")
@Operation(summary = "Delete template")
@RequiresPermissions("sys:role:superAdmin")
public Result<String> deleteAgentTemplate(@PathVariable("id") String id) {
// 先查询要删除的模板信息,获取其排序值
// First query the template to be deleted to get its sort value
AgentTemplateEntity template = agentTemplateService.getById(id);
if (template == null) {
return ResultUtils.error("模板不存在");
return ResultUtils.error("Template does not exist");
}
Integer deletedSort = template.getSort();
// 执行删除操作
// Execute delete operation
boolean deleted = agentTemplateService.removeById(id);
if (deleted) {
// 删除成功后,重新排序剩余模板
// After successful deletion, reorder remaining templates
agentTemplateService.reorderTemplatesAfterDelete(deletedSort);
return ResultUtils.success("删除模板成功");
return ResultUtils.success("Template deleted successfully");
} else {
return ResultUtils.error("删除模板失败");
return ResultUtils.error("Failed to delete template");
}
}
// 添加新的批量删除方法,使用不同的URL
// Add new batch delete method using different URL
@PostMapping("/batch-remove")
@Operation(summary = "批量删除模板")
@Operation(summary = "Batch delete templates")
@RequiresPermissions("sys:role:superAdmin")
public Result<String> batchRemoveAgentTemplates(@RequestBody List<String> ids) {
boolean deleted = agentTemplateService.removeByIds(ids);
if (deleted) {
return ResultUtils.success("批量删除成功");
return ResultUtils.success("Batch delete successful");
} else {
return ResultUtils.error("批量删除模板失败");
return ResultUtils.error("Failed to batch delete templates");
}
}
}

View file

@ -27,7 +27,7 @@ import xiaozhi.modules.agent.vo.AgentVoicePrintVO;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
@Tag(name = "智能体声纹管理")
@Tag(name = "Agent Voiceprint Management")
@AllArgsConstructor
@RestController
@RequestMapping("/agent/voice-print")
@ -36,7 +36,7 @@ public class AgentVoicePrintController {
private final SysParamsService sysParamsService;
@PostMapping
@Operation(summary = "创建智能体的声纹")
@Operation(summary = "Create agent voiceprint")
@RequiresPermissions("sys:role:normal")
public Result<Void> save(@RequestBody @Valid AgentVoicePrintSaveDTO dto) {
boolean b = agentVoicePrintService.insert(dto);
@ -47,7 +47,7 @@ public class AgentVoicePrintController {
}
@PutMapping
@Operation(summary = "更新智能体的对应声纹")
@Operation(summary = "Update agent corresponding voiceprint")
@RequiresPermissions("sys:role:normal")
public Result<Void> update(@RequestBody @Valid AgentVoicePrintUpdateDTO dto) {
Long userId = SecurityUser.getUserId();
@ -59,11 +59,11 @@ public class AgentVoicePrintController {
}
@DeleteMapping("/{id}")
@Operation(summary = "删除智能体对应声纹")
@Operation(summary = "Delete agent corresponding voiceprint")
@RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable String id) {
Long userId = SecurityUser.getUserId();
// 先删除关联的设备
// First delete associated devices
boolean delete = agentVoicePrintService.delete(userId, id);
if (delete) {
return new Result<>();
@ -72,7 +72,7 @@ public class AgentVoicePrintController {
}
@GetMapping("/list/{id}")
@Operation(summary = "获取用户指定智能体声纹列表")
@Operation(summary = "Get user specified agent voiceprint list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentVoicePrintVO>> list(@PathVariable String id) {
String voiceprintUrl = sysParamsService.getValue("server.voice_print", true);

View file

@ -11,18 +11,18 @@ import xiaozhi.modules.agent.vo.AgentInfoVO;
@Mapper
public interface AgentDao extends BaseDao<AgentEntity> {
/**
* 获取智能体的设备数量
* Get device count for agent
*
* @param agentId 智能体ID
* @return 设备数量
* @param agentId Agent ID
* @return Device count
*/
Integer getDeviceCountByAgentId(@Param("agentId") String agentId);
/**
* 根据设备MAC地址查询对应设备的默认智能体信息
* Query default agent information for device by device MAC address
*
* @param macAddress 设备MAC地址
* @return 默认智能体信息
* @param macAddress Device MAC address
* @return Default agent information
*/
@Select(" SELECT a.* FROM ai_device d " +
" LEFT JOIN ai_agent a ON d.agent_id = a.id " +
@ -31,9 +31,9 @@ public interface AgentDao extends BaseDao<AgentEntity> {
AgentEntity getDefaultAgentByMacAddress(@Param("macAddress") String macAddress);
/**
* 根据id查询agent信息,包括插件信息
* Query agent information by ID, including plugin information
*
* @param agentId 智能体ID
* @param agentId Agent ID
*/
AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId);
}

View file

@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
/**
* @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Mapper
* @description Database operation Mapper for table [ai_agent_plugin_mapping(unique mapping table between Agent and plugins)]
* @createDate 2025-05-25 22:33:17
* @Entity xiaozhi.modules.agent.entity.AgentPluginMapping
*/

View file

@ -8,7 +8,7 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity;
/**
* @author chenerlei
* @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Mapper
* @description Database operation Mapper for table [ai_agent_template(agent configuration template table)]
* @createDate 2025-03-22 11:48:18
*/
@Mapper

View file

@ -8,7 +8,7 @@ import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
import xiaozhi.modules.agent.entity.AgentVoicePrintEntity;
/**
* {@link AgentChatHistoryEntity} 智能体聊天历史记录Dao对象
* {@link AgentChatHistoryEntity} Agent chat history record Dao object
*
* @author Goody
* @version 1.0, 2025/4/30

View file

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
/**
* {@link AgentChatAudioEntity} 智能体聊天音频数据Dao对象
* {@link AgentChatAudioEntity} Agent chat audio data Dao object
*
* @author Goody
* @version 1.0, 2025/5/8

View file

@ -10,7 +10,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
/**
* {@link AgentChatHistoryEntity} 智能体聊天历史记录Dao对象
* DAO for {@link AgentChatHistoryEntity}.
*
* @author Goody
* @version 1.0, 2025/4/30
@ -20,31 +20,31 @@ import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
public interface AiAgentChatHistoryDao extends BaseMapper<AgentChatHistoryEntity> {
/**
* 根据智能体ID删除聊天历史记录
* Delete chat history by agent ID.
*
* @param agentId 智能体ID
* @param agentId agent ID
*/
void deleteHistoryByAgentId(String agentId);
/**
* 根据智能体ID删除音频ID
* Delete audio IDs by agent ID.
*
* @param agentId 智能体ID
* @param agentId agent ID
*/
void deleteAudioIdByAgentId(String agentId);
/**
* 根据智能体ID获取所有音频ID列表
* Get all audio IDs by agent ID.
*
* @param agentId 智能体ID
* @return 音频ID列表
* @param agentId agent ID
* @return audio ID list
*/
List<String> getAudioIdsByAgentId(String agentId);
/**
* 批量删除音频
* Delete audio records in batch.
*
* @param audioIds 音频ID列表
* @param audioIds audio ID list
*/
void deleteAudioByIds(@Param("audioIds") List<String> audioIds);
}

View file

@ -6,23 +6,23 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 智能体聊天记录DTO
* Agent chat history DTO
*/
@Data
@Schema(description = "智能体聊天记录")
@Schema(description = "Agent chat history")
public class AgentChatHistoryDTO {
@Schema(description = "创建时间")
@Schema(description = "Creation time")
private Date createdAt;
@Schema(description = "消息类型: 1-用户, 2-智能体")
@Schema(description = "Message type: 1-user, 2-agent")
private Byte chatType;
@Schema(description = "聊天内容")
@Schema(description = "Chat content")
private String content;
@Schema(description = "音频ID")
@Schema(description = "Audio ID")
private String audioId;
@Schema(description = "MAC地址")
@Schema(description = "MAC address")
private String macAddress;
}

View file

@ -6,28 +6,28 @@ import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* 小智设备聊天上报请求
* XiaoZhi device chat report request
*
* @author Haotian
* @version 1.0, 2025/5/8
*/
@Data
@Schema(description = "小智设备聊天上报请求")
@Schema(description = "XiaoZhi device chat report request")
public class AgentChatHistoryReportDTO {
@Schema(description = "MAC地址", example = "00:11:22:33:44:55")
@Schema(description = "MAC address", example = "00:11:22:33:44:55")
@NotBlank
private String macAddress;
@Schema(description = "会话ID", example = "79578c31-f1fb-426a-900e-1e934215f05a")
@Schema(description = "Session ID", example = "79578c31-f1fb-426a-900e-1e934215f05a")
@NotBlank
private String sessionId;
@Schema(description = "消息类型: 1-用户, 2-智能体", example = "1")
@Schema(description = "Message type: 1-User, 2-Agent", example = "1")
@NotNull
private Byte chatType;
@Schema(description = "聊天内容", example = "你好呀")
@Schema(description = "Chat content", example = "Hello")
@NotBlank
private String content;
@Schema(description = "base64编码的opus音频数据", example = "")
@Schema(description = "Base64 encoded opus audio data", example = "")
private String audioBase64;
@Schema(description = "上报时间,十位时间戳,空时默认使用当前时间", example = "1745657732")
@Schema(description = "Report time, 10-digit timestamp, defaults to current time if empty", example = "1745657732")
private Long reportTime;
}

View file

@ -5,22 +5,22 @@ import java.time.LocalDateTime;
import lombok.Data;
/**
* 智能体会话列表DTO
* Agent session list DTO
*/
@Data
public class AgentChatSessionDTO {
/**
* 会话ID
* Session ID
*/
private String sessionId;
/**
* 会话时间
* Session time
*/
private LocalDateTime createdAt;
/**
* 聊天条数
* Chat count
*/
private Integer chatCount;

View file

@ -4,25 +4,25 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 智能体聊天记录总结DTO
* Agent chat-summary DTO.
*/
@Data
@Schema(description = "智能体聊天记录总结对象")
@Schema(description = "Agent chat-summary object")
public class AgentChatSummaryDTO {
@Schema(description = "会话ID")
@Schema(description = "Session ID")
private String sessionId;
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
@Schema(description = "总结内容")
@Schema(description = "Summary content")
private String summary;
@Schema(description = "总结状态")
@Schema(description = "Summary status")
private boolean success;
@Schema(description = "错误信息")
@Schema(description = "Error message")
private String errorMessage;
public AgentChatSummaryDTO() {
@ -42,4 +42,4 @@ public class AgentChatSummaryDTO {
this.success = false;
}
}
}

View file

@ -7,15 +7,15 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 智能体创建DTO
* 专用于新增智能体,不包含id、agentCode和sort字段,这些字段由系统自动生成/设置默认值
* Agent creation DTO
* Specifically for creating new agents, does not include id, agentCode and sort fields, these fields are automatically generated/set to default values by the system
*/
@Data
@Schema(description = "智能体创建对象")
@Schema(description = "Agent creation object")
public class AgentCreateDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "智能体名称", example = "客服助手")
@NotBlank(message = "智能体名称不能为空")
@Schema(description = "Agent name", example = "Customer Service Assistant")
@NotBlank(message = "Agent name cannot be empty")
private String agentName;
}

View file

@ -8,46 +8,46 @@ import lombok.Data;
import xiaozhi.modules.agent.dto.AgentTagDTO;
/**
* 智能体数据传输对象
* 用于在服务层和控制器层之间传递智能体相关的数据
* Agent data transfer object
* Used to pass agent-related data between service layer and controller layer
*/
@Data
@Schema(description = "智能体对象")
@Schema(description = "Agent object")
public class AgentDTO {
@Schema(description = "智能体编码", example = "AGT_1234567890")
@Schema(description = "Agent code", example = "AGT_1234567890")
private String id;
@Schema(description = "智能体名称", example = "客服助手")
@Schema(description = "Agent name", example = "Customer Service Assistant")
private String agentName;
@Schema(description = "语音合成模型名称", example = "tts_model_01")
@Schema(description = "TTS model name", example = "tts_model_01")
private String ttsModelName;
@Schema(description = "音色名称", example = "voice_01")
@Schema(description = "Voice name", example = "voice_01")
private String ttsVoiceName;
@Schema(description = "大语言模型名称", example = "llm_model_01")
@Schema(description = "LLM model name", example = "llm_model_01")
private String llmModelName;
@Schema(description = "视觉模型名称", example = "vllm_model_01")
@Schema(description = "Vision model name", example = "vllm_model_01")
private String vllmModelName;
@Schema(description = "记忆模型ID", example = "mem_model_01")
@Schema(description = "Memory model ID", example = "mem_model_01")
private String memModelId;
@Schema(description = "角色设定参数", example = "你是一个专业的客服助手,负责回答用户问题并提供帮助")
@Schema(description = "Role setting parameters", example = "You are a professional customer service assistant, responsible for answering user questions and providing help")
private String systemPrompt;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
@Schema(description = "Summary memory", example = "Build a growing dynamic memory network that retains key information in limited space while intelligently maintaining information evolution trajectories\n" +
"Based on conversation records, summarize important user information to provide more personalized service in future conversations", required = false)
private String summaryMemory;
@Schema(description = "最后连接时间", example = "2024-03-20 10:00:00")
@Schema(description = "Last connection time", example = "2024-03-20 10:00:00")
private Date lastConnectedAt;
@Schema(description = "设备数量", example = "10")
@Schema(description = "Device count", example = "10")
private Integer deviceCount;
@Schema(description = "标签列表")
@Schema(description = "Tag list")
private List<AgentTagDTO> tags;
}
}

View file

@ -6,14 +6,14 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 智能体记忆更新DTO
* Agent memory update DTO
*/
@Data
@Schema(description = "智能体记忆更新对象")
@Schema(description = "Agent memory update object")
public class AgentMemoryDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
@Schema(description = "Summary memory", example = "Build a growing dynamic memory network that retains key information in limited space while intelligently maintaining information evolution trajectory\n" +
"Summarize important user information based on conversation records to provide more personalized service in future conversations", required = false)
private String summaryMemory;
}

View file

@ -7,14 +7,14 @@ import java.io.Serializable;
import java.util.List;
@Data
@Schema(description = "智能体标签DTO")
@Schema(description = "Agent tag DTO")
public class AgentTagDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "标签ID")
@Schema(description = "Tag ID")
private String id;
@Schema(description = "标签名称")
@Schema(description = "Tag name")
private String tagName;
}

View file

@ -9,28 +9,28 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 智能体更新DTO
* 专用于更新智能体,id字段是必需的,用于标识要更新的智能体
* 其他字段均为非必填,只更新提供的字段
* Agent update DTO.
* Used specifically for agent updates. All fields are optional and only
* provided values will be updated.
*/
@Data
@Schema(description = "智能体更新对象")
@Schema(description = "Agent update object")
public class AgentUpdateDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "智能体编码", example = "AGT_1234567890", nullable = true)
@Schema(description = "Agent code", example = "AGT_1234567890", nullable = true)
private String agentCode;
@Schema(description = "智能体名称", example = "客服助手", nullable = true)
@Schema(description = "Agent name", example = "Support Assistant", nullable = true)
private String agentName;
@Schema(description = "语音识别模型标识", example = "asr_model_02", nullable = true)
@Schema(description = "ASR model ID", example = "asr_model_02", nullable = true)
private String asrModelId;
@Schema(description = "语音活动检测标识", example = "vad_model_02", nullable = true)
@Schema(description = "VAD model ID", example = "vad_model_02", nullable = true)
private String vadModelId;
@Schema(description = "大语言模型标识", example = "llm_model_02", nullable = true)
@Schema(description = "LLM model ID", example = "llm_model_02", nullable = true)
private String llmModelId;
@Schema(description = "小模型标识", example = "slm_model_02", nullable = true)
@ -39,64 +39,64 @@ public class AgentUpdateDTO implements Serializable {
@Schema(description = "VLLM模型标识", example = "vllm_model_02", required = false)
private String vllmModelId;
@Schema(description = "语音合成模型标识", example = "tts_model_02", required = false)
@Schema(description = "TTS model ID", example = "tts_model_02", required = false)
private String ttsModelId;
@Schema(description = "音色标识", example = "voice_02", nullable = true)
@Schema(description = "Voice ID", example = "voice_02", nullable = true)
private String ttsVoiceId;
@Schema(description = "音色语言", example = "普通话", nullable = true)
@Schema(description = "Voice language", example = "English", nullable = true)
private String ttsLanguage;
@Schema(description = "TTS音量", example = "50", nullable = true)
@Schema(description = "TTS volume", example = "50", nullable = true)
private Integer ttsVolume;
@Schema(description = "TTS语速", example = "50", nullable = true)
@Schema(description = "TTS speed", example = "50", nullable = true)
private Integer ttsRate;
@Schema(description = "TTS音调", example = "50", nullable = true)
@Schema(description = "TTS pitch", example = "50", nullable = true)
private Integer ttsPitch;
@Schema(description = "记忆模型标识", example = "mem_model_02", nullable = true)
@Schema(description = "Memory model ID", example = "mem_model_02", nullable = true)
private String memModelId;
@Schema(description = "意图模型标识", example = "intent_model_02", nullable = true)
@Schema(description = "Intent model ID", example = "intent_model_02", nullable = true)
private String intentModelId;
@Schema(description = "插件函数信息", nullable = true)
@Schema(description = "Plugin function information", nullable = true)
private List<FunctionInfo> functions;
@Schema(description = "角色设定参数", example = "你是一个专业的客服助手,负责回答用户问题并提供帮助", nullable = true)
@Schema(description = "System prompt", example = "You are a professional support assistant who helps answer user questions.", nullable = true)
private String systemPrompt;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n"
+ "根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", nullable = true)
@Schema(description = "Summary memory", example = "Build a growing memory graph that preserves key information while tracking how it evolves over time.\n"
+ "Summarize the user's important details from the conversation so future interactions can be more personalized.", nullable = true)
private String summaryMemory;
@Schema(description = "聊天记录配置(0不记录 1仅记录文本 2记录文本和语音)", example = "3", nullable = true)
@Schema(description = "Chat-history mode (0 disabled, 1 text only, 2 text and audio)", example = "2", nullable = true)
private Integer chatHistoryConf;
@Schema(description = "语言编码", example = "zh_CN", nullable = true)
@Schema(description = "Language code", example = "en_US", nullable = true)
private String langCode;
@Schema(description = "交互语种", example = "中文", nullable = true)
@Schema(description = "Interaction language", example = "English", nullable = true)
private String language;
@Schema(description = "排序", example = "1", nullable = true)
@Schema(description = "Sort order", example = "1", nullable = true)
private Integer sort;
@Schema(description = "上下文源配置", nullable = true)
@Schema(description = "Context-provider configuration", nullable = true)
private List<ContextProviderDTO> contextProviders;
@Data
@Schema(description = "插件函数信息")
@Schema(description = "Plugin function information")
public static class FunctionInfo implements Serializable {
@Schema(description = "插件ID", example = "plugin_01")
@Schema(description = "Plugin ID", example = "plugin_01")
private String pluginId;
@Schema(description = "函数参数信息", nullable = true)
@Schema(description = "Function parameter information", nullable = true)
private HashMap<String, Object> paramInfo;
private static final long serialVersionUID = 1L;
}
}
}

View file

@ -3,26 +3,26 @@ package xiaozhi.modules.agent.dto;
import lombok.Data;
/**
* 保存智能体声纹的dto
* DTO for saving agent voiceprint
*
* @author zjy
*/
@Data
public class AgentVoicePrintSaveDTO {
/**
* 关联的智能体id
* Associated agent id
*/
private String agentId;
/**
* 音频文件id
* Audio file id
*/
private String audioId;
/**
* 声纹来源的人姓名
* Name of the person whose voiceprint this is from
*/
private String sourceName;
/**
* 描述声纹来源的人
* Description of the person whose voiceprint this is from
*/
private String introduce;
}

View file

@ -3,26 +3,26 @@ package xiaozhi.modules.agent.dto;
import lombok.Data;
/**
* 修改智能体声纹的dto
* DTO for updating agent voiceprint
*
* @author zjy
*/
@Data
public class AgentVoicePrintUpdateDTO {
/**
* 智能体声纹id
* Agent voiceprint id
*/
private String id;
/**
* 音频文件id
* Audio file id
*/
private String audioId;
/**
* 声纹来源的人姓名
* Name of the person whose voiceprint this is from
*/
private String sourceName;
/**
* 描述声纹来源的人
* Description of the person whose voiceprint this is from
*/
private String introduce;
}

View file

@ -7,13 +7,13 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "上下文源配置DTO")
@Schema(description = "Context-provider DTO")
public class ContextProviderDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "URL地址")
@Schema(description = "URL")
private String url;
@Schema(description = "请求头")
@Schema(description = "Request headers")
private Map<String, Object> headers;
}

View file

@ -5,17 +5,17 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 声纹识别接口返回的对象
* Object returned by voiceprint recognition interface
*/
@Data
public class IdentifyVoicePrintResponse {
/**
* 最匹配的声纹id
* Most matching voiceprint id
*/
@JsonProperty("speaker_id")
private String speakerId;
/**
* 声纹的分数
* Voiceprint score
*/
private Double score;
}

View file

@ -3,7 +3,7 @@ package xiaozhi.modules.agent.dto;
import lombok.Data;
/**
* MCP JSON-RPC 响应 DTO
* MCP JSON-RPC response DTO
*/
@Data
public class McpJsonRpcResponse {

View file

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 智能体聊天音频数据表
* Agent chat audio data table
*
* @author Goody
* @version 1.0, 2025/5/8
@ -17,13 +17,13 @@ import lombok.Data;
@TableName("ai_agent_chat_audio")
public class AgentChatAudioEntity {
/**
* 主键ID
* Primary key ID
*/
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 音频opus数据
* Audio opus data
*/
private byte[] audio;
}

View file

@ -13,7 +13,7 @@ import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 智能体聊天记录表
* Agent chat history table
*
* @author Goody
* @version 1.0, 2025/4/30
@ -26,55 +26,55 @@ import lombok.NoArgsConstructor;
@TableName(value = "ai_agent_chat_history")
public class AgentChatHistoryEntity {
/**
* 主键ID
* Primary key ID
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* MAC地址
* MAC address
*/
@TableField(value = "mac_address")
private String macAddress;
/**
* 智能体id
* Agent ID
*/
@TableField(value = "agent_id")
private String agentId;
/**
* 会话ID
* Session ID
*/
@TableField(value = "session_id")
private String sessionId;
/**
* 消息类型: 1-用户, 2-智能体
* Message type: 1-user, 2-agent
*/
@TableField(value = "chat_type")
private Byte chatType;
/**
* 聊天内容
* Chat content
*/
@TableField(value = "content")
private String content;
/**
* 音频base64数据
* Audio base64 data
*/
@TableField(value = "audio_id")
private String audioId;
/**
* 创建时间
* Creation time
*/
@TableField(value = "created_at")
private Date createdAt;
/**
* 更新时间
* Update time
*/
@TableField(value = "updated_at")
private Date updatedAt;

View file

@ -15,29 +15,29 @@ import xiaozhi.modules.agent.dto.ContextProviderDTO;
@Data
@TableName(value = "ai_agent_context_provider", autoResultMap = true)
@Schema(description = "智能体上下文源配置")
@Schema(description = "Agent context-provider configuration")
public class AgentContextProviderEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "主键")
@Schema(description = "Primary key")
private String id;
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
@Schema(description = "上下文源配置")
@Schema(description = "Context-provider configuration")
@TableField(typeHandler = JacksonTypeHandler.class)
private List<ContextProviderDTO> contextProviders;
@Schema(description = "创建者")
@Schema(description = "Created by")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Created at")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Updated at")
private Date updatedAt;
}

View file

@ -12,29 +12,29 @@ import lombok.Data;
@Data
@TableName("ai_agent")
@Schema(description = "智能体信息")
@Schema(description = "Agent information")
public class AgentEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "智能体唯一标识")
@Schema(description = "Unique agent ID")
private String id;
@Schema(description = "所属用户ID")
@Schema(description = "Owner user ID")
private Long userId;
@Schema(description = "智能体编码")
@Schema(description = "Agent code")
private String agentCode;
@Schema(description = "智能体名称")
@Schema(description = "Agent name")
private String agentName;
@Schema(description = "语音识别模型标识")
@Schema(description = "ASR model ID")
private String asrModelId;
@Schema(description = "语音活动检测标识")
@Schema(description = "VAD model ID")
private String vadModelId;
@Schema(description = "大语言模型标识")
@Schema(description = "LLM model ID")
private String llmModelId;
@Schema(description = "小模型标识")
@ -43,58 +43,58 @@ public class AgentEntity {
@Schema(description = "VLLM模型标识")
private String vllmModelId;
@Schema(description = "语音合成模型标识")
@Schema(description = "TTS model ID")
private String ttsModelId;
@Schema(description = "音色标识")
@Schema(description = "Voice ID")
private String ttsVoiceId;
@Schema(description = "音色语言")
@Schema(description = "Voice language")
private String ttsLanguage;
@Schema(description = "TTS音量")
@Schema(description = "TTS volume")
private Integer ttsVolume;
@Schema(description = "TTS语速")
@Schema(description = "TTS speed")
private Integer ttsRate;
@Schema(description = "TTS音调")
@Schema(description = "TTS pitch")
private Integer ttsPitch;
@Schema(description = "记忆模型标识")
@Schema(description = "Memory model ID")
private String memModelId;
@Schema(description = "意图模型标识")
@Schema(description = "Intent model ID")
private String intentModelId;
@Schema(description = "聊天记录配置(0不记录 1仅记录文本 2记录文本和语音)")
@Schema(description = "Chat-history mode (0 disabled, 1 text only, 2 text and audio)")
private Integer chatHistoryConf;
@Schema(description = "角色设定参数")
@Schema(description = "System prompt")
private String systemPrompt;
@Schema(description = "总结记忆", example = "构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹\n" +
"根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务", required = false)
@Schema(description = "Summary memory", example = "Build a growing memory graph that preserves key information while tracking how it evolves over time.\n" +
"Summarize the user's important details from the conversation so future interactions can be more personalized.", required = false)
private String summaryMemory;
@Schema(description = "语言编码")
@Schema(description = "Language code")
private String langCode;
@Schema(description = "交互语种")
@Schema(description = "Interaction language")
private String language;
@Schema(description = "排序")
@Schema(description = "Sort order")
private Integer sort;
@Schema(description = "创建者")
@Schema(description = "Created by")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Created at")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Updated at")
private Date updatedAt;
}
}

View file

@ -11,42 +11,42 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* Agent与插件的唯一映射表
* Unique mapping table between Agent and plugins
*
* @TableName ai_agent_plugin_mapping
*/
@Data
@TableName(value = "ai_agent_plugin_mapping")
@Schema(description = "Agent与插件的唯一映射表")
@Schema(description = "Unique mapping table between Agent and plugins")
public class AgentPluginMapping implements Serializable {
/**
* 主键
* Primary key
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "映射信息主键ID")
@Schema(description = "Mapping information primary key ID")
private Long id;
/**
* 智能体ID
* Agent ID
*/
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
/**
* 插件ID
* Plugin ID
*/
@Schema(description = "插件ID")
@Schema(description = "Plugin ID")
private String pluginId;
/**
* 插件参数(Json)格式
* Plugin parameters (JSON format)
*/
@Schema(description = "插件参数(Json)格式")
@Schema(description = "Plugin parameters (JSON format)")
private String paramInfo;
// 冗余字段,用于方便在根据id查询插件时,对照查出插件的Provider_code,详见dao层xml文件
// Redundant field for convenience when querying plugins by id, to find the plugin's Provider_code, see dao layer xml file
@TableField(exist = false)
@Schema(description = "插件provider_code, 对应表ai_model_provider")
@Schema(description = "Plugin provider_code, corresponds to table ai_model_provider")
private String providerCode;
@TableField(exist = false)

View file

@ -11,31 +11,31 @@ import lombok.Data;
@Data
@TableName("ai_agent_tag")
@Schema(description = "智能体标签")
@Schema(description = "Agent tag")
public class AgentTagEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "主键")
@Schema(description = "Primary key")
private String id;
@Schema(description = "标签名称")
@Schema(description = "Tag name")
private String tagName;
@Schema(description = "排序")
@Schema(description = "Sort order")
private Integer sort;
@Schema(description = "创建者")
@Schema(description = "Created by")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Created at")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Updated at")
private Date updatedAt;
@Schema(description = "删除标记")
@Schema(description = "Deleted flag")
private Integer deleted;
}

View file

@ -11,31 +11,31 @@ import lombok.Data;
@Data
@TableName("ai_agent_tag_relation")
@Schema(description = "智能体标签关联")
@Schema(description = "Agent tag relation")
public class AgentTagRelationEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "主键")
@Schema(description = "Primary key")
private String id;
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
@Schema(description = "标签ID")
@Schema(description = "Tag ID")
private String tagId;
@Schema(description = "排序")
@Schema(description = "Sort order")
private Integer sort;
@Schema(description = "创建者")
@Schema(description = "Created by")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Created at")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Updated at")
private Date updatedAt;
}

View file

@ -12,138 +12,138 @@ import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 智能体配置模板表
*
* Agent configuration template table.
*
* @TableName ai_agent_template
*/
@TableName(value = "ai_agent_template")
@Data
public class AgentTemplateEntity implements Serializable {
/**
* 智能体唯一标识
* Unique agent ID.
*/
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 智能体编码
* Agent code.
*/
private String agentCode;
/**
* 智能体名称
* Agent name.
*/
private String agentName;
/**
* 语音识别模型标识
* ASR model ID.
*/
private String asrModelId;
/**
* 语音活动检测标识
* VAD model ID.
*/
private String vadModelId;
/**
* 大语言模型标识
* LLM model ID.
*/
private String llmModelId;
/**
* VLLM模型标识
* VLLM model ID.
*/
private String vllmModelId;
/**
* 语音合成模型标识
* TTS model ID.
*/
private String ttsModelId;
/**
* 音色标识
* Voice ID.
*/
private String ttsVoiceId;
/**
* 音色语言
* Voice language.
*/
private String ttsLanguage;
/**
* TTS音量
* TTS volume.
*/
private Integer ttsVolume;
/**
* TTS语速
* TTS speed.
*/
private Integer ttsRate;
/**
* TTS音调
* TTS pitch.
*/
private Integer ttsPitch;
/**
* 记忆模型标识
* Memory model ID.
*/
private String memModelId;
/**
* 意图模型标识
* Intent model ID.
*/
private String intentModelId;
/**
* 聊天记录配置(0不记录 1仅记录文本 2记录文本和语音)
* Chat-history mode (0 disabled, 1 text only, 2 text and audio).
*/
private Integer chatHistoryConf;
/**
* 角色设定参数
* System prompt.
*/
private String systemPrompt;
/**
* 总结记忆
* Summary memory.
*/
private String summaryMemory;
/**
* 语言编码
* Language code.
*/
private String langCode;
/**
* 交互语种
* Interaction language.
*/
private String language;
/**
* 排序权重
* Sort weight.
*/
private Integer sort;
/**
* 创建者 ID
* Creator ID.
*/
private Long creator;
/**
* 创建时间
* Created at.
*/
private Date createdAt;
/**
* 更新者 ID
* Updated by.
*/
private Long updater;
/**
* 更新时间
* Updated at.
*/
private Date updatedAt;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
}

View file

@ -11,7 +11,7 @@ import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 智能体声纹表
* Agent voiceprint table
*
* @author zjy
*/
@ -19,45 +19,45 @@ import lombok.Data;
@Data
public class AgentVoicePrintEntity {
/**
* 主键id
* Primary key id
*/
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 关联的智能体id
* Associated agent id
*/
private String agentId;
/**
* 关联的音频id
* Associated audio id
*/
private String audioId;
/**
* 声纹来源的人姓名
* Name of the person whose voiceprint this is from
*/
private String sourceName;
/**
* 描述声纹来源的人
* Description of the person whose voiceprint this is from
*/
private String introduce;
/**
* 创建者
* Creator
*/
@TableField(fill = FieldFill.INSERT)
private Long creator;
/**
* 创建时间
* Creation time
*/
@TableField(fill = FieldFill.INSERT)
private Date createDate;
/**
* 更新者
* Updater
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updater;
/**
* 更新时间
* Update time
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate;

View file

@ -5,7 +5,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
/**
* 智能体聊天音频数据表处理service
* Agent chat audio data table processing service
*
* @author Goody
* @version 1.0, 2025/5/8
@ -13,18 +13,18 @@ import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
*/
public interface AgentChatAudioService extends IService<AgentChatAudioEntity> {
/**
* 保存音频数据
* Save audio data
*
* @param audioData 音频数据
* @return 音频ID
* @param audioData Audio data
* @return Audio ID
*/
String saveAudio(byte[] audioData);
/**
* 获取音频数据
* Get audio data
*
* @param audioId 音频ID
* @return 音频数据
* @param audioId Audio ID
* @return Audio data
*/
byte[] getAudio(String audioId);
}

View file

@ -12,7 +12,7 @@ import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
/**
* 智能体聊天记录表处理service
* Agent chat history table processing service
*
* @author Goody
* @version 1.0, 2025/4/30
@ -21,54 +21,62 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
public interface AgentChatHistoryService extends IService<AgentChatHistoryEntity> {
/**
* 根据智能体ID获取会话列表
* Get session list by agent ID
*
* @param params 查询参数,包含agentId、page、limit
* @return 分页的会话列表
* @param params Query parameters, including agentId, page, limit
* @return Paginated session list
*/
PageData<AgentChatSessionDTO> getSessionListByAgentId(Map<String, Object> params);
/**
* 根据会话ID获取聊天记录列表
* Get chat record list by session ID
*
* @param agentId 智能体ID
* @param sessionId 会话ID
* @return 聊天记录列表
* @param agentId Agent ID
* @param sessionId Session ID
* @return Chat record list
*/
List<AgentChatHistoryDTO> getChatHistoryBySessionId(String agentId, String sessionId);
/**
* 根据智能体ID删除聊天记录
* Delete chat records by agent ID
*
* @param agentId 智能体ID
* @param deleteAudio 是否删除音频
* @param deleteText 是否删除文本
* @param agentId Agent ID
* @param deleteAudio Whether to delete audio
* @param deleteText Whether to delete text
*/
void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText);
/**
* 根据智能体ID获取最近50条用户的聊天记录数据(带音频数据)
* Delete chat session by agent ID and session ID
*
* @param agentId 智能体id
* @return 聊天记录列表(只有用户)
* @param agentId Agent ID
* @param sessionId Session ID
*/
void deleteBySessionId(String agentId, String sessionId);
/**
* Get recent 50 user chat records by agent ID (with audio data)
*
* @param agentId Agent ID
* @return Chat record list (user only)
*/
List<AgentChatHistoryUserVO> getRecentlyFiftyByAgentId(String agentId);
/**
* 根据音频数据ID获取聊天内容
* Get chat content by audio data ID
*
* @param audioId 音频id
* @return 聊天内容
* @param audioId Audio ID
* @return Chat content
*/
String getContentByAudioId(String audioId);
/**
* 查询此音频id是否属于此智能体
* Check if this audio ID belongs to this agent
*
* @param audioId 音频id
* @param agentId 音频id
* @return T:属于 F:不属于
* @param audioId Audio ID
* @param agentId Agent ID
* @return T: belongs F: does not belong
*/
boolean isAudioOwnedByAgent(String audioId,String agentId);
}

View file

@ -1,15 +1,15 @@
package xiaozhi.modules.agent.service;
/**
* 智能体聊天记录总结服务接口
* Agent chat-summary service interface.
*/
public interface AgentChatSummaryService {
/**
* 根据会话ID生成聊天记录总结并保存到智能体记忆
*
* @param sessionId 会话ID
* @return 保存结果
* Generate a chat summary by session ID and save it to agent memory.
*
* @param sessionId session ID
* @return save result
*/
boolean generateAndSaveChatSummary(String sessionId);
@ -20,4 +20,4 @@ public interface AgentChatSummaryService {
* @return 是否成功
*/
boolean generateAndSaveChatTitle(String sessionId);
}
}

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