diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 484c28dc0..dce0d9fa4 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -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 \ No newline at end of file diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml index b3798571c..7bb9016ca 100644 --- a/main/manager-api/pom.xml +++ b/main/manager-api/pom.xml @@ -6,7 +6,7 @@ jar 0.0.1 xiaozhi-esp32-api - 小智后台管理系统 + Xiaozhi Backend Management System org.springframework.boot @@ -30,8 +30,7 @@ 1.6.2 33.0.0-jre 4.20.0 - 4.1.0 - 3.4.0 + 8.31.1 @@ -70,7 +69,7 @@ - + com.github.whvcse easy-captcha @@ -158,7 +157,7 @@ spring-boot-configuration-processor true - + com.mysql mysql-connector-j @@ -193,13 +192,13 @@ jsoup ${jsoup.version} - + com.github.xingfudeshi knife4j-openapi3-jakarta-spring-boot-starter ${knife4j.version} - + org.bouncycastle bcprov-jdk18on @@ -211,7 +210,7 @@ springdoc-openapi-starter-webmvc-ui ${springdoc.version} - + org.apache.commons commons-lang3 @@ -220,32 +219,33 @@ org.projectlombok lombok + 1.18.36 true com.fasterxml.jackson.datatype jackson-datatype-jsr310 - + - com.aliyun - dysmsapi20170525 - ${aliyun-sms-version} + com.twilio.sdk + twilio + ${twilio-version} - + - com.squareup.okio - okio - ${okio-version} + com.h2database + h2 + test - + - public - aliyun nexus - https://maven.aliyun.com/repository/public/ + central + Maven Central + https://repo1.maven.org/maven2/ true @@ -253,9 +253,9 @@ - public - aliyun nexus - https://maven.aliyun.com/repository/public/ + central + Maven Central + https://repo1.maven.org/maven2/ true @@ -270,12 +270,36 @@ org.springframework.boot spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 21 + 21 + + + org.projectlombok + lombok + 1.18.36 + + + org.apache.maven.plugins maven-surefire-plugin - true + false diff --git a/main/manager-api/rule/doc/test-validation/knowledge-module-full-integration-test-report.md b/main/manager-api/rule/doc/test-validation/knowledge-module-full-integration-test-report.md new file mode 100644 index 000000000..8a81c7ad3 --- /dev/null +++ b/main/manager-api/rule/doc/test-validation/knowledge-module-full-integration-test-report.md @@ -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` 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* diff --git a/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java b/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java index 9bd6cb9db..d021e1a32 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java +++ b/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java @@ -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"; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java b/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java index 6f6f778da..c2ca1df21 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java +++ b/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java @@ -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) diff --git a/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java b/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java index d4233e72b..4df49df41 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java +++ b/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/AsyncConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/AsyncConfig.java index d0cc2dfce..44b57d297 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/AsyncConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/AsyncConfig.java @@ -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); } } }); diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java index 250e0d070..950a35976 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/RestTemplateConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/RestTemplateConfig.java index 6608032b6..d36fbc48c 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/RestTemplateConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/RestTemplateConfig.java @@ -7,7 +7,7 @@ import org.springframework.web.client.RestTemplate; import java.time.Duration; /** - * RestTemplate配置 + * RestTemplate configuration */ @Configuration public class RestTemplateConfig { diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java index cbdb5a198..a464a7de0 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java @@ -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")); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index 370295016..0e2acb4f5 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -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; } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java b/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java index fd0f74c29..cc43903df 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java +++ b/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java @@ -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 { } /** - * 格式化日期 + * 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; diff --git a/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java b/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java index d65e78305..b08e15c79 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java +++ b/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java @@ -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 extends BaseMapper { diff --git a/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java b/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java index ce267babc..a5d07dd20 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java @@ -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; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java index 820f40893..343cf3323 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java @@ -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. *

- * 如:10001(10代表系统模块,001代表业务代码) + * Example: 10001 (10 = system module, 001 = business code) *

- * 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 } diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java b/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java index 4ac47b818..c979fe9d3 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java b/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java index e016bc095..75092117c 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java @@ -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 handleRenException(RenException ex) { @@ -82,4 +82,4 @@ public class RenExceptionHandler { return new Result().error(ErrorCode.PARAM_VALUE_NULL, errorMsg); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java index 95add2f06..d45ba6e6d 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java +++ b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java @@ -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()); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java index 0457686b1..b1bae90e5 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java +++ b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java @@ -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()) { diff --git a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java index b59de67b0..de73f3f09 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java +++ b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java b/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java index 83e93c119..7d60fd945 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java +++ b/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java @@ -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 implements Serializable { - @Schema(description = "总记录数") + @Schema(description = "Total record count") private int total; - @Schema(description = "列表数据") + @Schema(description = "List data") private List list; /** - * 分页 + * Pagination * - * @param list 列表数据 - * @param total 总记录数 + * @param list List data + * @param total Total record count */ public PageData(List list, long total) { this.list = list; this.total = (int) total; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java b/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java index cce1a6df8..78974d423 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java index 703a84925..bc108f173 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java index 6691e395c..144f79b3c 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java index c81677e99..eb4327ca9 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java @@ -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 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 keys = Collections.emptyList(); // 如果脚本不依赖 key,可以传入空列表 + // Execute Lua script + List 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 redisScript = new DefaultRedisScript<>(); redisScript.setScriptText(luaScript); redisScript.setResultType(String.class); - // 执行 Lua 脚本 + // Execute Lua script List keys = Collections.singletonList(key); return redisTemplate.execute(redisScript, keys, defaultValue,expiresInSecond); } diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java b/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java index 2feaefd11..2aaa2e95f 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java @@ -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 { @@ -15,95 +15,95 @@ public interface BaseService { /** *

- * 插入一条记录(选择字段,策略插入) + * Insert a record (selective fields, strategy insert) *

* - * @param entity 实体对象 + * @param entity Entity object */ boolean insert(T entity); /** *

- * 插入(批量),该方法不支持 Oracle、SQL Server + * Insert (batch), this method does not support Oracle, SQL Server *

* - * @param entityList 实体对象集合 + * @param entityList Entity object collection */ boolean insertBatch(Collection entityList); /** *

- * 插入(批量),该方法不支持 Oracle、SQL Server + * Insert (batch), this method does not support Oracle, SQL Server *

* - * @param entityList 实体对象集合 - * @param batchSize 插入批次数量 + * @param entityList Entity object collection + * @param batchSize Insert batch size */ boolean insertBatch(Collection entityList, int batchSize); /** *

- * 根据 ID 选择修改 + * Update by ID *

* - * @param entity 实体对象 + * @param entity Entity object */ boolean updateById(T entity); /** *

- * 根据 whereEntity 条件,更新记录 + * Update records based on whereEntity condition *

* - * @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 updateWrapper); /** *

- * 根据ID 批量更新 + * Batch update by ID *

* - * @param entityList 实体对象集合 + * @param entityList Entity object collection */ boolean updateBatchById(Collection entityList); /** *

- * 根据ID 批量更新 + * Batch update by ID *

* - * @param entityList 实体对象集合 - * @param batchSize 更新批次数量 + * @param entityList Entity object collection + * @param batchSize Update batch size */ boolean updateBatchById(Collection entityList, int batchSize); /** *

- * 根据 ID 查询 + * Query by ID *

* - * @param id 主键ID + * @param id Primary key ID */ T selectById(Serializable id); /** *

- * 根据 ID 删除 + * Delete by ID *

* - * @param id 主键ID + * @param id Primary key ID */ boolean deleteById(Serializable id); /** *

- * 删除(根据ID 批量删除) + * Delete (batch delete by ID) *

* - * @param idList 主键ID列表 + * @param idList Primary key ID list */ boolean deleteBatchIds(Collection idList); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java b/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java index 51f16bcb7..ab4b73beb 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java @@ -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 extends BaseService { @@ -25,4 +25,4 @@ public interface CrudService extends BaseService { void delete(Serializable[] ids); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java index 9d06c09a7..33d0f5d35 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java @@ -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, T> implements BaseService { @@ -42,20 +42,20 @@ public abstract class BaseServiceImpl, 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 getPage(Map params, String defaultOrderField, boolean isAsc) { - // 分页参数 + // Pagination parameters long curPage = 1; long limit = 10; @@ -66,26 +66,26 @@ public abstract class BaseServiceImpl, T> implements Bas limit = Long.parseLong((String) params.get(Constant.LIMIT)); } - // 分页对象 + // Pagination object Page 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 orderFields = new ArrayList<>(); - // 处理排序字段 + // Process sort fields if (orderField instanceof String) { orderFields.add((String) orderField); } else if (orderField instanceof List) { orderFields.addAll((List) 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, 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, T> implements Bas /** *

- * 判断数据库操作是否成功 + * Determine if database operation is successful *

*

- * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型 + * Note!! This method uses Integer for judgment, cannot pass int primitive type *

* - * @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, T> implements Bas } /** - * 批量插入 + * Batch insert */ @Override @Transactional(rollbackFor = Exception.class) @@ -178,7 +178,7 @@ public abstract class BaseServiceImpl, T> implements Bas } /** - * 执行批量操作 + * Execute batch operations */ @SuppressWarnings("deprecation") protected boolean executeBatch(Collection list, int batchSize, BiConsumer consumer) { @@ -227,4 +227,4 @@ public abstract class BaseServiceImpl, T> implements Bas public boolean deleteBatchIds(Collection idList) { return SqlHelper.retBool(baseDao.deleteBatchIds(idList)); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java index 9a1bf39ed..3b9d0fe97 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java @@ -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, T, D> extends BaseServiceImpl @@ -58,7 +58,7 @@ public abstract class CrudServiceImpl, 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, T, D> extends Bas public void delete(Serializable[] ids) { baseDao.deleteBatchIds(Arrays.asList(ids)); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java b/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java index 0aa9210ba..17a349436 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java +++ b/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java @@ -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; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/AESUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/AESUtils.java index 660e3cba4..f4a73dda8 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/AESUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/AESUtils.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java index 07ade50f3..cee35f6be 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java index 800733c11..b4b4992e2 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java @@ -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); } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java b/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java index 79b051927..dd0c26305 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java @@ -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); diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java index 0e46acf16..8152e50a8 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java @@ -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 */ diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java index fef7972f2..972518662 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java @@ -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 *

- * 使用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"; diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java index c522a61dc..8632a992b 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java @@ -2,7 +2,7 @@ package xiaozhi.common.utils; import lombok.Data; /** - * JSON-RPC2.0 格式规范对象 + * JSON-RPC2.0 format specification object */ @Data public class JsonRpcTwo { diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java index 288dae9ab..21d1bf211 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java @@ -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 { diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java index abcc2cb3d..76b552d6d 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java @@ -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()); diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java index 1064299be..f07560272 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java @@ -3,7 +3,7 @@ package xiaozhi.common.utils; import org.springframework.stereotype.Component; /** - * 获取配置文件信息 + * Get configuration file information * Copyright xin-nan.com */ @Component diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ResourcesUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ResourcesUtils.java index cf2d0bcc5..b7f7fa724 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/ResourcesUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/ResourcesUtils.java @@ -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(); diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java index 9c326af70..bffc1ddaf 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java @@ -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 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 ok(T data) { @@ -60,4 +60,4 @@ public class Result implements Serializable { return this; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ResultUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ResultUtils.java index 3f9fe27dc..4927bc7dc 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/ResultUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/ResultUtils.java @@ -1,7 +1,7 @@ package xiaozhi.common.utils; /** - * 返回响应体工具类 + * Response body utility class */ public class ResultUtils { diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SM2Utils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SM2Utils.java index cf0ed9c5b..669dfb62e 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/SM2Utils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SM2Utils.java @@ -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 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); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java index 4d5715cc1..5b5f6c60e 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java @@ -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 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 originalFields = new HashMap<>(); extractSpecificSensitiveField(original, originalFields, fieldName, ""); - // 提取更新对象中的指定敏感字段 + // Extract the target sensitive field from the updated object. Map 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 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 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); } } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/Sm2DecryptUtil.java b/main/manager-api/src/main/java/xiaozhi/common/utils/Sm2DecryptUtil.java index 332e9c808..c7fd127b7 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/Sm2DecryptUtil.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/Sm2DecryptUtil.java @@ -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); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java index 52aec0b72..2c7d08eca 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java @@ -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 { diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java index 408889651..c0e278662 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java @@ -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) { diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java index 5fdb5985e..34a319a11 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java @@ -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 implements Serializable { /** - * 主键 + * Primary key */ private Long id; /** - * 上级ID + * Parent ID */ private Long pid; /** - * 子节点列表 + * Child node list */ private List children = new ArrayList<>(); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java index e76190eba..d98b4fa7a 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java @@ -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 > List build(List treeNodes, Long pid) { - // pid不能为空 + // pid cannot be null AssertUtils.isNull(pid, "pid"); List treeList = new ArrayList<>(); @@ -32,7 +32,7 @@ public class TreeUtils { } /** - * 查找子节点 + * Find child nodes */ private static > T findChildren(List treeNodes, T rootNode) { for (T treeNode : treeNodes) { @@ -44,12 +44,12 @@ public class TreeUtils { } /** - * 构建树节点 + * Build tree nodes */ public static > List build(List treeNodes) { List result = new ArrayList<>(); - // list转map + // Convert list to map Map nodeMap = new LinkedHashMap<>(treeNodes.size()); for (T treeNode : treeNodes) { nodeMap.put(treeNode.getId(), treeNode); @@ -68,4 +68,4 @@ public class TreeUtils { return result; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java b/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java index c86aa5176..3c10f5e42 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java @@ -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); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java b/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java index 364da0d99..a805ca980 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java @@ -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(); } diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java index fd8290fde..7ed4977e6 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java @@ -1,7 +1,7 @@ package xiaozhi.common.validator.group; /** - * 新增 Group + * Add Group */ public interface AddGroup { diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java index 60ddb7305..587d7b7de 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java @@ -1,7 +1,7 @@ package xiaozhi.common.validator.group; /** - * 默认 Group + * Default Group */ public interface DefaultGroup { diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java index 220fda333..454adc7ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java @@ -1,7 +1,7 @@ package xiaozhi.common.validator.group; /** - * 修改 Group + * Update Group */ public interface UpdateGroup { diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java b/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java index 2bf4ab928..10032392e 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java @@ -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); diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java index e4b654659..fab433bd6 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java @@ -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 diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java index db7699897..3ddf27cbf 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java @@ -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())); } diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java index ecb364061..4ae15f44a 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java @@ -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); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java index 5d9b8b01d..bea09b819 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java @@ -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 excludeUrls = Collections.emptyList(); + + public List getExcludeUrls() { + return excludeUrls; + } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java index 165883924..e0bdbd2c6 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java @@ -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") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java index 49ed2dce7..caffb793b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java @@ -4,7 +4,7 @@ package xiaozhi.modules.agent.Enums; import lombok.Getter; /** - * 智能体聊天记录类型 + * Agent chat history type */ @Getter public enum AgentChatHistoryType { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java index 114b1ab95..926f01c02 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java @@ -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( diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java index 49096d43e..7b2f31cba 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java @@ -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 *

- * 小智服务聊天上报请求,包含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 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 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().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 params = Map.of( "agentId", agentId, Constant.PAGE, 1, - Constant.LIMIT, 1000 // 获取足够多的会话 + Constant.LIMIT, 1000 // Load enough sessions for the export window. ); PageData sessionPage = agentChatHistoryService.getSessionListByAgentId(params); List 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 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 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 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)); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 77907cc5b..7f3e2de36 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -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> 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 agents = agentService.getUserAgents(user.getId(), keyword, searchType); return new Result>().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> adminAgentList( @Parameter(hidden = true) @RequestParam Map params) { @@ -101,7 +101,7 @@ public class AgentController { } @GetMapping("/{id}") - @Operation(summary = "获取智能体详情") + @Operation(summary = "Get agent details") @RequiresPermissions("sys:role:normal") public Result 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 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 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 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().ok(null); } catch (Exception e) { - return new Result().error("启动异步总结生成任务失败: " + e.getMessage()); + return new Result().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 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 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> templateList() { List 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> 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> 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>().error("没有权限查看该智能体的聊天记录"); + return new Result>().error("You do not have permission to view this agent's chat history"); } - // 查询聊天记录 + // Query chat history. List result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId); return new Result>().ok(result); } @GetMapping("/{id}/chat-history/user") - @Operation(summary = "获取智能体聊天记录(用户)") + @Operation(summary = "Get agent chat history (user)") @RequiresPermissions("sys:role:normal") public Result> 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>().error("没有权限查看该智能体的聊天记录"); + return new Result>().error("You do not have permission to view this agent's chat history"); } - // 查询聊天记录 + // Query chat history. List data = agentChatHistoryService.getRecentlyFiftyByAgentId(id); return new Result>().ok(data); } @GetMapping("/{id}/chat-history/audio") - @Operation(summary = "获取音频内容") + @Operation(summary = "Get audio content") @RequiresPermissions("sys:role:normal") public Result getContentByAudioId( @PathVariable("id") String id) { - // 查询聊天记录 + // Query chat history. String data = agentChatHistoryService.getContentByAudioId(id); return new Result().ok(data); } @PostMapping("/audio/{audioId}") - @Operation(summary = "获取音频下载ID") + @Operation(summary = "Get audio download ID") @RequiresPermissions("sys:role:normal") public Result getAudioId(@PathVariable("audioId") String audioId) { byte[] audioData = agentChatAudioService.getAudio(audioId); if (audioData == null) { - return new Result().error("音频不存在"); + return new Result().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 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 createTag(@RequestBody Map params) { String tagName = params.get("tagName"); if (StringUtils.isBlank(tagName)) { - return new Result().error("标签名称不能为空"); + return new Result().error("Tag name cannot be empty"); } AgentTagEntity tag = agentTagService.saveTag(tagName); return new Result().ok(tag); } @GetMapping("/tag/list") - @Operation(summary = "获取所有标签列表") + @Operation(summary = "Get all tags") @RequiresPermissions("sys:role:normal") public Result> getAllTags() { List 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 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> getAgentTags(@PathVariable String id) { List 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 saveAgentTags(@PathVariable String id, @RequestBody Map params) { List tagIds = (List) params.get("tagIds"); @@ -332,4 +334,4 @@ public class AgentController { return new Result().ok(null); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java index c805a4e78..96e3d1b35 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java @@ -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 getAgentMcpAccessAddress(@PathVariable("agentId") String agentId) { - // 获取当前用户 + // Resolve the current user. UserDetail user = SecurityUser.getUser(); - // 检查权限 + // Validate permissions. if (!agentService.checkAgentPermission(agentId, user.getId())) { return new Result().error(ErrorCode.MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION); } @@ -50,14 +50,14 @@ public class AgentMcpAccessPointController { return new Result().ok(agentMcpAccessAddress); } - @Operation(summary = "获取智能体的Mcp工具列表") + @Operation(summary = "Get agent MCP tools") @GetMapping("/tools/{agentId}") @RequiresPermissions("sys:role:normal") public Result> getAgentMcpToolsList(@PathVariable("agentId") String agentId) { - // 获取当前用户 + // Resolve the current user. UserDetail user = SecurityUser.getUser(); - // 检查权限 + // Validate permissions. if (!agentService.checkAgentPermission(agentId, user.getId())) { return new Result>().error(ErrorCode.MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentTemplateController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentTemplateController.java index 9c8366ed6..52e16d9a6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentTemplateController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentTemplateController.java @@ -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> getAgentTemplatesPage( @Parameter(hidden = true) @RequestParam Map 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 pageInfo = new Page<>(page, limit); - // 创建查询条件 + // Create query conditions QueryWrapper 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 pageResult = agentTemplateService.page(pageInfo, wrapper); - // 使用ConvertUtils转换为VO列表 + // Use ConvertUtils to convert to VO list List voList = ConvertUtils.sourceToTarget(pageResult.getRecords(), AgentTemplateVO.class); - // 修复:使用构造函数创建PageData对象,而不是无参构造+setter + // Fix: Use constructor to create PageData object instead of no-arg constructor + setter PageData pageData = new PageData<>(voList, pageResult.getTotal()); return new Result>().ok(pageData); } @GetMapping("/{id}") - @Operation(summary = "获取模板详情") + @Operation(summary = "Get template details") @RequiresPermissions("sys:role:superAdmin") public Result 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 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 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 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 batchRemoveAgentTemplates(@RequestBody List 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"); } } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java index 9b7555eb4..d94242d9e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java @@ -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 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 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 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(@PathVariable String id) { String voiceprintUrl = sysParamsService.getValue("server.voice_print", true); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java index 03e569cdc..98a80b761 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java @@ -11,18 +11,18 @@ import xiaozhi.modules.agent.vo.AgentInfoVO; @Mapper public interface AgentDao extends BaseDao { /** - * 获取智能体的设备数量 + * 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 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); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentPluginMappingMapper.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentPluginMappingMapper.java index 2fe817533..4bba45590 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentPluginMappingMapper.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentPluginMappingMapper.java @@ -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 */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentTemplateDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentTemplateDao.java index 48d95bef0..ab5ceea2b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentTemplateDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentTemplateDao.java @@ -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 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java index 1a5ee3649..7abd198df 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java @@ -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 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatAudioDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatAudioDao.java index 355b25acf..a12935c84 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatAudioDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatAudioDao.java @@ -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 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatHistoryDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatHistoryDao.java index 7c9bf1eb4..2ea59741d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatHistoryDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AiAgentChatHistoryDao.java @@ -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 { /** - * 根据智能体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 getAudioIdsByAgentId(String agentId); /** - * 批量删除音频 + * Delete audio records in batch. * - * @param audioIds 音频ID列表 + * @param audioIds audio ID list */ void deleteAudioByIds(@Param("audioIds") List audioIds); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryDTO.java index fd49e52b4..0499c090d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryDTO.java @@ -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; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryReportDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryReportDTO.java index ae58783f3..601c01b6f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryReportDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatHistoryReportDTO.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSessionDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSessionDTO.java index 841b69768..41bc97783 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSessionDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSessionDTO.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSummaryDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSummaryDTO.java index f6fbe6605..34eb29681 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSummaryDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentChatSummaryDTO.java @@ -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; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentCreateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentCreateDTO.java index 59e770075..2fca17b20 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentCreateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentCreateDTO.java @@ -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; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java index 77028f2a1..5e360d6d6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java @@ -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 tags; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java index ed210c60a..556b4437e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java @@ -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; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentTagDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentTagDTO.java index 5dfc5f520..6cfb3ae33 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentTagDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentTagDTO.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java index 13d95ddc5..462f3aab6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java @@ -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 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 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 paramInfo; private static final long serialVersionUID = 1L; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java index 0ff3b0cad..61192e188 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java index 60643e294..c79c52c73 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/ContextProviderDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/ContextProviderDTO.java index 0b8edfd8d..33706f2d1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/ContextProviderDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/ContextProviderDTO.java @@ -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 headers; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java index 14ce57c2b..e7eeb3d29 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcResponse.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcResponse.java index 1bd667e6d..e1bfc6416 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcResponse.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcResponse.java @@ -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 { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatAudioEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatAudioEntity.java index ac30d9d49..1dc255881 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatAudioEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatAudioEntity.java @@ -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; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatHistoryEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatHistoryEntity.java index 679c814ab..90ed90aab 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatHistoryEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentChatHistoryEntity.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java index 937556efc..d01fb7881 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java @@ -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 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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentEntity.java index ce752b01e..40f69d381 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentEntity.java @@ -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; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentPluginMapping.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentPluginMapping.java index ae99b0ebf..9514699f6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentPluginMapping.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentPluginMapping.java @@ -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) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagEntity.java index 82555c3eb..68c1b48ba 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagEntity.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagRelationEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagRelationEntity.java index cc345d71e..4fe05e3b7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagRelationEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTagRelationEntity.java @@ -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; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java index b06cda917..045ded778 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java @@ -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; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java index 4998b2888..bc917df37 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java @@ -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; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java index 04be9f360..805c13ba1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java @@ -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 { /** - * 保存音频数据 + * 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); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java index 459b5a5a1..9b1d01924 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java @@ -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 { /** - * 根据智能体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 getSessionListByAgentId(Map 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 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 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); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatSummaryService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatSummaryService.java index 336058490..82f45e18d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatSummaryService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatSummaryService.java @@ -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); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentContextProviderService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentContextProviderService.java index da759971c..ff4b5cf8b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentContextProviderService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentContextProviderService.java @@ -5,21 +5,24 @@ import xiaozhi.modules.agent.entity.AgentContextProviderEntity; public interface AgentContextProviderService extends BaseService { /** - * 根据智能体ID获取上下文源配置 - * @param agentId 智能体ID - * @return 上下文源配置实体 + * Get context-provider configuration by agent ID. + * + * @param agentId agent ID + * @return context-provider configuration entity */ AgentContextProviderEntity getByAgentId(String agentId); /** - * 保存或更新上下文源配置 - * @param entity 实体 + * Save or update context-provider configuration. + * + * @param entity entity to persist */ void saveOrUpdateByAgentId(AgentContextProviderEntity entity); /** - * 根据智能体ID删除上下文源配置 - * @param agentId 智能体ID + * Delete context-provider configuration by agent ID. + * + * @param agentId agent ID */ void deleteByAgentId(String agentId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentMcpAccessPointService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentMcpAccessPointService.java index 336ade653..0c232873b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentMcpAccessPointService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentMcpAccessPointService.java @@ -4,22 +4,22 @@ package xiaozhi.modules.agent.service; import java.util.List; /** - * 智能体Mcp接入点处理service + * Agent MCP access point processing service * * @author zjy */ public interface AgentMcpAccessPointService { /** - * 获取智能体的mcp接入点地址 - * @param id 智能体id - * @return mcp接入点地址 + * Get agent MCP access point address + * @param id Agent id + * @return MCP access point address */ String getAgentMcpAccessAddress(String id); /** - * 获取智能体的mcp接入点已有的工具列表 - * @param id 智能体id - * @return 工具列表 + * Get the existing tool list for the agent's MCP access point + * @param id Agent id + * @return Tool list */ List getAgentMcpToolsList(String id); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java index 79d97d2ed..c0e993463 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java @@ -7,13 +7,13 @@ import com.baomidou.mybatisplus.extension.service.IService; import xiaozhi.modules.agent.entity.AgentPluginMapping; /** - * @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service + * @description Database operation Service for table [ai_agent_plugin_mapping(unique mapping table between Agent and plugins)] * @createDate 2025-05-25 22:33:17 */ public interface AgentPluginMappingService extends IService { /** - * 根据智能体id获取插件参数 + * Get plugin parameters by agent id * * @param agentId * @return @@ -21,7 +21,7 @@ public interface AgentPluginMappingService extends IService List agentPluginParamsByAgentId(String agentId); /** - * 根据智能体id删除插件参数 + * Delete plugin parameters by agent id * * @param agentId */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index 22e8a2e07..c235c23a2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -12,7 +12,7 @@ import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.vo.AgentInfoVO; /** - * 智能体表处理service + * Agent service interface. * * @author Goody * @version 1.0, 2025/4/30 @@ -20,84 +20,84 @@ import xiaozhi.modules.agent.vo.AgentInfoVO; */ public interface AgentService extends BaseService { /** - * 获取管理员智能体列表 + * Get the admin-facing agent list. * - * @param params 查询参数 - * @return 分页数据 + * @param params query parameters + * @return paginated data */ PageData adminAgentList(Map params); /** - * 根据ID获取智能体 + * Get an agent by ID. * - * @param id 智能体ID - * @return 智能体实体 + * @param id agent ID + * @return agent details */ AgentInfoVO getAgentById(String id); /** - * 插入智能体 + * Insert an agent. * - * @param entity 智能体实体 - * @return 是否成功 + * @param entity agent entity + * @return whether the operation succeeded */ boolean insert(AgentEntity entity); /** - * 根据用户ID删除智能体 + * Delete agents by user ID. * - * @param userId 用户ID + * @param userId user ID */ void deleteAgentByUserId(Long userId); /** - * 获取用户智能体列表 + * Get a user's agents. * - * @param userId 用户ID - * @param keyword 搜索关键词 - * @param searchType 搜索类型(name - 按名称搜索,mac - 按MAC地址搜索) - * @return 智能体列表 + * @param userId user ID + * @param keyword search keyword + * @param searchType search type: `name` for agent name, `mac` for MAC address + * @return agent list */ List getUserAgents(Long userId, String keyword, String searchType); /** - * 根据智能体ID获取设备数量 + * Get the number of devices linked to an agent. * - * @param agentId 智能体ID - * @return 设备数量 + * @param agentId agent ID + * @return device count */ Integer getDeviceCountByAgentId(String agentId); /** - * 根据设备MAC地址查询对应设备的默认智能体信息 + * Get the default agent linked to a device MAC address. * - * @param macAddress 设备MAC地址 - * @return 默认智能体信息,不存在时返回null + * @param macAddress device MAC address + * @return default agent info, or {@code null} if none exists */ AgentEntity getDefaultAgentByMacAddress(String macAddress); /** - * 检查用户是否有权限访问智能体 + * Check whether a user can access an agent. * - * @param agentId 智能体ID - * @param userId 用户ID - * @return 是否有权限 + * @param agentId agent ID + * @param userId user ID + * @return whether access is allowed */ boolean checkAgentPermission(String agentId, Long userId); /** - * 更新智能体 + * Update an agent. * - * @param agentId 智能体ID - * @param dto 更新智能体所需的信息 + * @param agentId agent ID + * @param dto updated agent data */ void updateAgentById(String agentId, AgentUpdateDTO dto); /** - * 创建智能体 + * Create an agent. * - * @param dto 创建智能体所需的信息 - * @return 创建的智能体ID + * @param dto agent data needed for creation + * @return created agent ID */ String createAgent(AgentCreateDTO dto); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java index b10a67f99..092f02b89 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java @@ -6,37 +6,37 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity; /** * @author chenerlei - * @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service + * @description Database operation Service for table [ai_agent_template(agent configuration template table)] * @createDate 2025-03-22 11:48:18 */ public interface AgentTemplateService extends IService { /** - * 获取默认模板 + * Get default template * - * @return 默认模板实体 + * @return Default template entity */ AgentTemplateEntity getDefaultTemplate(); /** - * 更新默认模板中的模型ID + * Update model ID in default template * - * @param modelType 模型类型 - * @param modelId 模型ID + * @param modelType Model type + * @param modelId Model ID */ void updateDefaultTemplateModelId(String modelType, String modelId); /** - * 删除模板后重新排序剩余模板 + * Reorder remaining templates after deleting a template * - * @param deletedSort 被删除模板的排序值 + * @param deletedSort Sort value of the deleted template */ void reorderTemplatesAfterDelete(Integer deletedSort); /** - * 获取下一个可用的排序序号(寻找最小的未使用序号) + * Get next available sort number (find smallest unused number) * - * @return 下一个可用的排序序号 + * @return Next available sort number */ Integer getNextAvailableSort(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java index c9d38abd4..4f5328075 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java @@ -7,43 +7,43 @@ import xiaozhi.modules.agent.dto.AgentVoicePrintUpdateDTO; import xiaozhi.modules.agent.vo.AgentVoicePrintVO; /** - * 智能体声纹处理service + * Agent voiceprint processing service * * @author zjy */ public interface AgentVoicePrintService { /** - * 添加智能体新的声纹 + * Add new voiceprint for agent * - * @param dto 保存智能体声纹的数据 - * @return T:成功 F:失败 + * @param dto Data for saving agent voiceprint + * @return T: success F: failure */ boolean insert(AgentVoicePrintSaveDTO dto); /** - * 删除智能体的指的声纹 + * Delete specified voiceprint of agent * - * @param userId 当前登录的用户id - * @param voicePrintId 声纹id - * @return 是否成功 T:成功 F:失败 + * @param userId Current logged in user id + * @param voicePrintId Voiceprint id + * @return Whether successful T: success F: failure */ boolean delete(Long userId, String voicePrintId); /** - * 获取指定智能体的所有声纹数据 + * Get all voiceprint data for specified agent * - * @param userId 当前登录的用户id - * @param agentId 智能体id - * @return 声纹数据集合 + * @param userId Current logged in user ID + * @param agentId Agent ID + * @return Voiceprint data collection */ List list(Long userId, String agentId); /** - * 更新智能体的指的声纹数据 + * Update specified voiceprint data for agent * - * @param userId 当前登录的用户id - * @param dto 修改的声纹的数据 - * @return 是否成功 T:成功 F:失败 + * @param userId Current logged in user ID + * @param dto Modified voiceprint data + * @return Whether successful T: success F: failure */ boolean update(Long userId, AgentVoicePrintUpdateDTO dto); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/AgentChatHistoryBizService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/AgentChatHistoryBizService.java index 191b231b4..d176602bc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/AgentChatHistoryBizService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/AgentChatHistoryBizService.java @@ -3,7 +3,7 @@ package xiaozhi.modules.agent.service.biz; import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO; /** - * 智能体聊天历史业务逻辑层 + * Agent chat history business logic layer * * @author Goody * @version 1.0, 2025/4/30 @@ -12,11 +12,11 @@ import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO; public interface AgentChatHistoryBizService { /** - * 聊天上报方法 + * Chat report method * - * @param agentChatHistoryReportDTO 包含聊天上报所需信息的输入对象 - * 例如:设备MAC地址、文件类型、内容等 - * @return 上传结果,true表示成功,false表示失败 + * @param agentChatHistoryReportDTO Input object containing information required for chat report + * For example: device MAC address, file type, content, etc. + * @return Upload result, true means success, false means failure */ Boolean report(AgentChatHistoryReportDTO agentChatHistoryReportDTO); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/impl/AgentChatHistoryBizServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/impl/AgentChatHistoryBizServiceImpl.java index ac1b5d065..23cd9534e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/impl/AgentChatHistoryBizServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/biz/impl/AgentChatHistoryBizServiceImpl.java @@ -42,10 +42,10 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic private final DeviceService deviceService; /** - * 处理聊天记录上报,包括文件上传和相关信息记录 + * Process a chat-history report, including audio upload and related metadata persistence. * - * @param report 包含聊天上报所需信息的输入对象 - * @return 上传结果,true表示成功,false表示失败 + * @param report chat-history report payload + * @return upload result, true for success and false for failure */ @Override @Transactional(rollbackFor = Exception.class) @@ -54,9 +54,10 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic Byte chatType = report.getChatType(); Long reportTimeMillis = null != report.getReportTime() ? report.getReportTime() : System.currentTimeMillis(); - log.info("小智设备聊天上报请求: macAddress={}, type={} reportTime={}", macAddress, chatType, reportTimeMillis); + log.info("Device chat-history report received: macAddress={}, type={} reportTime={}", macAddress, chatType, + reportTimeMillis); - // 根据设备MAC地址查询对应的默认智能体,判断是否需要上报 + // Resolve the default agent linked to the device MAC address. AgentEntity agentEntity = agentService.getDefaultAgentByMacAddress(macAddress); if (agentEntity == null) { return Boolean.FALSE; @@ -72,22 +73,22 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic saveChatText(report, agentId, macAddress, audioId, reportTimeMillis); } - // 更新设备最后对话时间 + // Update the last conversation timestamp for the agent/device pair. redisUtils.set(RedisKeys.getAgentDeviceLastConnectedAtById(agentId), new Date()); - // 更新设备最后连接时间 + // Update the device last-connection time. DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); if (device != null) { deviceService.updateDeviceConnectionInfo(agentId, device.getId(), null); } else { - log.warn("聊天记录上报时,未找到mac地址为 {} 的设备", macAddress); + log.warn("No device was found for macAddress {} while processing chat-history reporting", macAddress); } return Boolean.TRUE; } /** - * base64解码report.getOpusDataBase64(),存入ai_agent_chat_audio表 + * Decode Base64 audio data and persist it in ai_agent_chat_audio. */ private String saveChatAudio(AgentChatHistoryReportDTO report) { String audioId = null; @@ -96,9 +97,9 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic try { byte[] audioData = Base64.getDecoder().decode(report.getAudioBase64()); audioId = agentChatAudioService.saveAudio(audioData); - log.info("音频数据保存成功,audioId={}", audioId); + log.info("Audio data saved successfully, audioId={}", audioId); } catch (Exception e) { - log.error("音频数据保存失败", e); + log.error("Failed to save audio data", e); return null; } } @@ -106,11 +107,11 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic } /** - * 组装上报数据 + * Build and persist the reported chat record. */ private void saveChatText(AgentChatHistoryReportDTO report, String agentId, String macAddress, String audioId, Long reportTime) { - // 构建聊天记录实体 + // Build the chat-history entity. AgentChatHistoryEntity entity = AgentChatHistoryEntity.builder() .macAddress(macAddress) .agentId(agentId) @@ -119,12 +120,12 @@ public class AgentChatHistoryBizServiceImpl implements AgentChatHistoryBizServic .content(report.getContent()) .audioId(audioId) .createdAt(new Date(reportTime)) - // NOTE(haotian): 2025/5/26 updateAt可以不设置,重点是createAt,而且这样可以看到上报延迟 + // NOTE(haotian): createAt matters most here, and leaving updateAt unset makes reporting delay easier to see. .build(); - // 保存数据 + // Persist the chat-history record. agentChatHistoryService.save(entity); - log.info("设备 {} 对应智能体 {} 上报成功", macAddress, agentId); + log.info("Chat-history reporting succeeded for device {} and agent {}", macAddress, agentId); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java index efcae485b..457faab85 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java @@ -9,7 +9,7 @@ import xiaozhi.modules.agent.entity.AgentChatAudioEntity; import xiaozhi.modules.agent.service.AgentChatAudioService; /** - * 智能体聊天音频数据表处理service {@link AgentChatAudioService} impl + * Agent chat audio data table processing service {@link AgentChatAudioService} impl * * @author Goody * @version 1.0, 2025/5/8 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java index 9cfece89b..e839f4a99 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java @@ -31,7 +31,7 @@ import xiaozhi.modules.agent.service.AgentChatTitleService; import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; /** - * 智能体聊天记录表处理service {@link AgentChatHistoryService} impl + * Chat-history service implementation for agents. * * @author Goody * @version 1.0, 2025/4/30 @@ -50,14 +50,14 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl wrapper = new QueryWrapper<>(); wrapper.select("session_id", "MAX(created_at) as created_at", "COUNT(*) as chat_count") .eq("agent_id", agentId) .groupBy("session_id") .orderByDesc("created_at"); - // 执行分页查询 + // Run the paginated query. Page> pageParam = new Page<>(page, limit); IPage> result = this.baseMapper.selectMapsPage(pageParam, wrapper); @@ -75,16 +75,16 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl getChatHistoryBySessionId(String agentId, String sessionId) { - // 构建查询条件 + // Build query conditions. QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("agent_id", agentId) .eq("session_id", sessionId) .orderByAsc("created_at"); - // 查询聊天记录 + // Query chat history. List historyList = list(wrapper); - // 转换为DTO + // Convert to DTOs. return ConvertUtils.sourceToTarget(historyList, AgentChatHistoryDTO.class); } @@ -92,10 +92,10 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl audioIds = baseMapper.getAudioIdsByAgentId(agentId); if (ToolUtil.isNotEmpty(audioIds)) { - // 每批删除1000条 + // Delete 1000 rows per batch. List> batch = ListUtil.split(audioIds, 1000); batch.forEach(dataList -> { baseMapper.deleteAudioByIds(dataList); @@ -108,29 +108,35 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(AgentChatHistoryEntity::getAgentId, agentId) + .eq(AgentChatHistoryEntity::getSessionId, sessionId); + baseMapper.delete(wrapper); } @Override public List getRecentlyFiftyByAgentId(String agentId) { - // 构建查询条件(不添加按照创建时间排序,数据本来就是主键越大创建时间越大 - // 不添加这样可以减少排序全部数据在分页的全盘扫描消耗) + // Build query conditions without sorting by created_at. + // In practice a larger primary key means a later creation time, which is cheaper to paginate. LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.select(AgentChatHistoryEntity::getContent, AgentChatHistoryEntity::getAudioId) .eq(AgentChatHistoryEntity::getAgentId, agentId) .eq(AgentChatHistoryEntity::getChatType, AgentChatHistoryType.USER.getValue()) .isNotNull(AgentChatHistoryEntity::getAudioId) - // 添加此行,确保查询结果按照创建时间降序排列 - // 使用id的原因:数据形式,id越大的创建时间就越晚,所以使用id的结果和创建时间降序排列结果一样 - // id作为降序排列的优势,性能高,有主键索引,不用在排序的时候重新进行排除扫描比较 + // Use descending ID order because it aligns with creation time and is index-friendly. .orderByDesc(AgentChatHistoryEntity::getId); - // 构建分页查询,查询前50页数据 + // Query the most recent 50 records. Page pageParam = new Page<>(0, 50); IPage result = this.baseMapper.selectPage(pageParam, wrapper); return result.getRecords().stream().map(item -> { AgentChatHistoryUserVO vo = ConvertUtils.sourceToTarget(item, AgentChatHistoryUserVO.class); - // 处理 content 字段,确保只返回聊天内容 + // Normalize content so only the chat text is returned. if (vo != null && vo.getContent() != null) { vo.setContent(extractContentFromString(vo.getContent())); } @@ -139,20 +145,19 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl jsonMap = JsonUtils.parseObject(content, Map.class); if (jsonMap != null && jsonMap.containsKey("content")) { @@ -160,10 +165,10 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl() .eq(AgentChatHistoryEntity::getAudioId, audioId) .eq(AgentChatHistoryEntity::getAgentId, agentId)); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatSummaryServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatSummaryServiceImpl.java index a3b78b186..b1baa87b1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatSummaryServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatSummaryServiceImpl.java @@ -32,8 +32,8 @@ import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; /** - * 智能体聊天记录总结服务实现类 - * 实现Python端mem_local_short.py中的总结逻辑 + * Agent chat-history summary service implementation. + * Mirrors the summary logic from the Python mem_local_short.py flow. */ @Service @RequiredArgsConstructor @@ -48,45 +48,47 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { private final LLMService llmService; private final ModelConfigService modelConfigService; - // 总结规则常量 - private static final int MAX_SUMMARY_LENGTH = 1800; // 最大总结长度 + // Summary rules and limits. + private static final int MAX_SUMMARY_LENGTH = 1800; // Maximum summary length. private static final Pattern JSON_PATTERN = Pattern.compile("\\{.*?\\}", Pattern.DOTALL); - private static final Pattern DEVICE_CONTROL_PATTERN = Pattern.compile("设备控制|设备操作|控制设备|设备状态", + private static final Pattern DEVICE_CONTROL_PATTERN = Pattern.compile("device control|device operation|control device|device status", Pattern.CASE_INSENSITIVE); - private static final Pattern WEATHER_PATTERN = Pattern.compile("天气|温度|湿度|降雨|气象", Pattern.CASE_INSENSITIVE); - private static final Pattern DATE_PATTERN = Pattern.compile("日期|时间|星期|月份|年份", Pattern.CASE_INSENSITIVE); + private static final Pattern WEATHER_PATTERN = Pattern.compile("weather|temperature|humidity|rain|forecast", Pattern.CASE_INSENSITIVE); + private static final Pattern DATE_PATTERN = Pattern.compile("date|time|day of week|month|year", Pattern.CASE_INSENSITIVE); + private static final String SERVICE_UNAVAILABLE = "Service temporarily unavailable"; + private static final String SUMMARY_GENERATION_FAILED = "Summary generation failed"; private AgentChatSummaryDTO generateChatSummary(String sessionId) { try { - System.out.println("开始生成会话 " + sessionId + " 的聊天记录总结"); + System.out.println("Starting chat summary generation for session " + sessionId); - // 1. 根据sessionId获取聊天记录 + // 1. Load chat history by sessionId. List chatHistory = getChatHistoryBySessionId(sessionId); if (chatHistory == null || chatHistory.isEmpty()) { - return new AgentChatSummaryDTO(sessionId, "未找到该会话的聊天记录"); + return new AgentChatSummaryDTO(sessionId, "No chat history was found for this session"); } - // 2. 获取智能体信息 + // 2. Resolve the agent information. String agentId = getAgentIdFromSession(sessionId, chatHistory); if (StringUtils.isBlank(agentId)) { - return new AgentChatSummaryDTO(sessionId, "无法获取智能体信息"); + return new AgentChatSummaryDTO(sessionId, "Unable to determine the agent information"); } - // 3. 提取关键对话内容 + // 3. Extract meaningful conversation content. List meaningfulMessages = extractMeaningfulMessages(chatHistory); if (meaningfulMessages.isEmpty()) { - return new AgentChatSummaryDTO(sessionId, "没有有效的对话内容可总结"); + return new AgentChatSummaryDTO(sessionId, "There is no meaningful conversation content to summarize"); } - // 4. 生成总结(generateSummaryFromMessages方法已包含长度限制逻辑) + // 4. Generate the summary. Length enforcement happens downstream. String summary = generateSummaryFromMessages(meaningfulMessages, agentId); - log.info("成功生成会话 {} 的聊天记录总结,长度: {} 字符", sessionId, summary.length()); + log.info("Generated a chat summary for session {} with length {} characters", sessionId, summary.length()); return new AgentChatSummaryDTO(sessionId, agentId, summary); } catch (Exception e) { - log.error("生成会话 {} 的聊天记录总结时发生错误: {}", sessionId, e.getMessage()); - return new AgentChatSummaryDTO(sessionId, "生成总结时发生错误: " + e.getMessage()); + log.error("Failed to generate a chat summary for session {}: {}", sessionId, e.getMessage()); + return new AgentChatSummaryDTO(sessionId, "An error occurred while generating the summary: " + e.getMessage()); } } @@ -95,7 +97,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { try { DeviceEntity device = getDeviceBySessionId(sessionId); if (device == null) { - log.info("未找到与会话 {} 关联的设备", sessionId); + log.info("No device was found for session {}", sessionId); return false; } @@ -130,7 +132,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { return true; } catch (Exception e) { - log.error("保存会话 {} 的聊天记录总结时发生错误: {}", sessionId, e.getMessage()); + log.error("Failed to save the chat summary for session {}: {}", sessionId, e.getMessage()); return false; } } @@ -228,29 +230,28 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { } /** - * 根据会话ID获取聊天记录 + * Load chat history by session ID. */ private List getChatHistoryBySessionId(String sessionId) { try { - // 这里需要根据sessionId获取聊天记录 - // 由于现有接口需要agentId,我们需要先找到关联的agentId + // The existing interface requires agentId, so resolve the related agent first. String agentId = findAgentIdBySessionId(sessionId); if (StringUtils.isBlank(agentId)) { return null; } return agentChatHistoryService.getChatHistoryBySessionId(agentId, sessionId); } catch (Exception e) { - log.error("获取会话 {} 的聊天记录失败: {}", sessionId, e.getMessage()); + log.error("Failed to load chat history for session {}: {}", sessionId, e.getMessage()); return null; } } /** - * 根据会话ID查找关联的智能体ID + * Find the agent ID linked to a session ID. */ private String findAgentIdBySessionId(String sessionId) { try { - // 查询该会话的第一条记录获取agentId + // Use the first record in the session to resolve the agent ID. QueryWrapper wrapper = new QueryWrapper<>(); wrapper.select("agent_id") .eq("session_id", sessionId) @@ -259,27 +260,27 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { AgentChatHistoryEntity entity = agentChatHistoryService.getOne(wrapper); return entity != null ? entity.getAgentId() : null; } catch (Exception e) { - log.error("根据会话ID {} 查找智能体ID失败: {}", sessionId, e.getMessage()); + log.error("Failed to find the agent ID for session {}: {}", sessionId, e.getMessage()); return null; } } /** - * 从会话中获取智能体ID + * Get the agent ID for the session. */ private String getAgentIdFromSession(String sessionId, List chatHistory) { - // 直接从数据库查询智能体ID + // Resolve the agent ID directly from the database. return findAgentIdBySessionId(sessionId); } /** - * 提取有意义的对话内容(只提取用户消息,排除AI回复) + * Extract meaningful conversation content from user messages only. */ private List extractMeaningfulMessages(List chatHistory) { List meaningfulMessages = new ArrayList<>(); for (AgentChatHistoryDTO message : chatHistory) { - // 只处理用户消息(chatType = 1) + // Only process user messages (chatType = 1). if (message.getChatType() != null && message.getChatType() == 1) { String content = extractContentFromMessage(message); if (isMeaningfulMessage(content)) { @@ -292,7 +293,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { } /** - * 从消息中提取内容(处理JSON格式) + * Extract content from a message, including JSON payloads. */ private String extractContentFromMessage(AgentChatHistoryDTO message) { String content = message.getContent(); @@ -300,11 +301,11 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { return ""; } - // 处理JSON格式内容(与前端ChatHistoryDialog.vue逻辑一致) + // Handle JSON-formatted content in a way that stays aligned with ChatHistoryDialog.vue. Matcher matcher = JSON_PATTERN.matcher(content); if (matcher.find()) { String jsonContent = matcher.group(); - // 简化处理:提取JSON中的文本内容 + // Simplified extraction: pull text content from the JSON body. return extractTextFromJson(jsonContent); } @@ -312,10 +313,10 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { } /** - * 从JSON中提取文本内容 + * Extract text content from JSON. */ private String extractTextFromJson(String jsonContent) { - // 简化处理:提取"content"字段的值 + // Simplified extraction: read the content field. Pattern contentPattern = Pattern.compile("\"content\"\s*:\s*\"([^\"]*)\""); Matcher matcher = contentPattern.matcher(jsonContent); if (matcher.find()) { @@ -325,62 +326,62 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { } /** - * 判断是否为有意义的消息 + * Determine whether a message is meaningful for summarization. */ private boolean isMeaningfulMessage(String content) { if (StringUtils.isBlank(content)) { return false; } - // 排除设备控制信息 + // Exclude device-control instructions. if (DEVICE_CONTROL_PATTERN.matcher(content).find()) { return false; } - // 排除日期天气等无关内容 + // Exclude weather, date, and similar low-value content. if (WEATHER_PATTERN.matcher(content).find() || DATE_PATTERN.matcher(content).find()) { return false; } - // 排除过短的消息 + // Exclude overly short messages. return content.length() >= 5; } /** - * 从消息生成总结 + * Generate a summary from the extracted messages. */ private String generateSummaryFromMessages(List messages, String agentId) { if (messages.isEmpty()) { - return "本次对话内容较少,没有需要总结的重要信息。"; + return "This conversation did not contain enough important information to summarize."; } - // 构建完整的对话内容 + // Build the full conversation body. StringBuilder conversation = new StringBuilder(); for (int i = 0; i < messages.size(); i++) { - conversation.append("消息").append(i + 1).append(": ").append(messages.get(i)).append("\n"); + conversation.append("Message ").append(i + 1).append(": ").append(messages.get(i)).append("\n"); } try { - // 获取当前智能体的历史记忆 + // Load current summary memory for the agent. String historyMemory = getCurrentAgentMemory(agentId); - // 调用LLM服务进行智能总结,传递agentId以获取正确的模型配置 + // Call the LLM service and pass agentId so the correct model configuration is used. String summary = callJavaLLMForSummaryWithHistory(conversation.toString(), historyMemory, agentId); - // 应用总结规则:限制最大长度 + // Apply the maximum summary length rule. if (summary.length() > MAX_SUMMARY_LENGTH) { summary = summary.substring(0, MAX_SUMMARY_LENGTH) + "..."; } return summary; } catch (Exception e) { - log.error("调用Java端LLM服务失败: {}", e.getMessage()); - throw new RuntimeException("LLM服务不可用,无法生成聊天总结"); + log.error("Java-side LLM summary generation failed: {}", e.getMessage()); + throw new RuntimeException("The LLM service is unavailable, so the chat summary could not be generated"); } } /** - * 获取当前智能体的历史记忆 + * Load the current summary memory for the agent. */ private String getCurrentAgentMemory(String agentId) { try { @@ -388,22 +389,22 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { return null; } - // 获取智能体信息 + // Load agent information. AgentInfoVO agentInfo = agentService.getAgentById(agentId); if (agentInfo == null) { return null; } - // 返回智能体的当前总结记忆 + // Return the current summary memory for the agent. return agentInfo.getSummaryMemory(); } catch (Exception e) { - log.error("获取智能体历史记忆失败,agentId: {}, 错误: {}", agentId, e.getMessage()); + log.error("Failed to load agent history memory, agentId={}, error={}", agentId, e.getMessage()); return null; } } /** - * 调用Java端LLM服务进行智能总结(支持历史记忆合并) + * Call the Java-side LLM service to generate a summary with history merging support. */ private String callJavaLLMForSummaryWithHistory(String conversation, String historyMemory, String agentId) { try { @@ -416,20 +417,22 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { String summary = llmService.generateSummaryWithHistory(conversation, historyMemory, null, modelId); - if (StringUtils.isNotBlank(summary) && !summary.equals("服务暂不可用") && !summary.equals("总结生成失败")) { + if (StringUtils.isNotBlank(summary) + && !summary.equals(SERVICE_UNAVAILABLE) + && !summary.equals(SUMMARY_GENERATION_FAILED)) { return summary; } - throw new RuntimeException("Java端LLM服务返回异常: " + summary); + throw new RuntimeException("The Java-side LLM service returned an invalid response: " + summary); } catch (Exception e) { - log.error("调用Java端LLM服务异常,agentId: {}, 错误: {}", agentId, e.getMessage()); + log.error("Java-side LLM summary call failed, agentId={}, error={}", agentId, e.getMessage()); throw e; } } /** - * 调用Java端LLM服务进行智能总结 + * Call the Java-side LLM service to generate a summary. */ private String callJavaLLMForSummary(String conversation, String agentId) { try { @@ -442,20 +445,22 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { String summary = llmService.generateSummaryWithModel(conversation, modelId); - if (StringUtils.isNotBlank(summary) && !summary.equals("服务暂不可用") && !summary.equals("总结生成失败")) { + if (StringUtils.isNotBlank(summary) + && !summary.equals(SERVICE_UNAVAILABLE) + && !summary.equals(SUMMARY_GENERATION_FAILED)) { return summary; } - throw new RuntimeException("Java端LLM服务返回异常: " + summary); + throw new RuntimeException("The Java-side LLM service returned an invalid response: " + summary); } catch (Exception e) { - log.error("调用Java端LLM服务异常,agentId: {}, 错误: {}", agentId, e.getMessage()); + log.error("Java-side LLM summary call failed, agentId={}, error={}", agentId, e.getMessage()); throw e; } } /** - * 获取记忆总结的LLM模型ID + * Return the LLM model ID used for memory summarization. */ private String getMemorySummaryModelId(String agentId) { try { @@ -463,46 +468,47 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { return null; } - // 获取智能体信息 + // Load agent information. AgentInfoVO agentInfo = agentService.getAgentById(agentId); if (agentInfo == null) { return null; } - // 获取智能体的记忆模型ID + // Read the agent's memory model ID. String memModelId = agentInfo.getMemModelId(); if (StringUtils.isBlank(memModelId)) { return null; } - // 获取记忆模型配置 + // Load the memory model configuration. ModelConfigEntity memModelConfig = modelConfigService.getModelByIdFromCache(memModelId); if (memModelConfig == null || memModelConfig.getConfigJson() == null) { return null; } - // 从记忆模型配置中提取对应的LLM模型ID + // Extract the linked LLM model ID from the memory model configuration. Map configMap = memModelConfig.getConfigJson(); String llmModelId = (String) configMap.get("llm"); if (StringUtils.isBlank(llmModelId)) { - // 如果记忆模型没有配置独立的LLM,则使用智能体的默认LLM模型 + // Fall back to the agent's default LLM model when the memory model does not specify one. return agentInfo.getLlmModelId(); } return llmModelId; } catch (Exception e) { - log.error("获取记忆总结LLM模型ID失败,agentId: {}, 错误: {}", agentId, e.getMessage()); + log.error("Failed to load the memory-summary LLM model ID, agentId={}, error={}", + agentId, e.getMessage()); return null; } } /** - * 根据会话ID获取设备信息 + * Load device information by session ID. */ private DeviceEntity getDeviceBySessionId(String sessionId) { try { - // 查询该会话的第一条记录获取macAddress + // Use the first session record to resolve the MAC address. QueryWrapper wrapper = new QueryWrapper<>(); wrapper.select("mac_address") .eq("session_id", sessionId) @@ -514,8 +520,8 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService { } return null; } catch (Exception e) { - log.error("根据会话ID {} 查找设备信息失败: {}", sessionId, e.getMessage()); + log.error("Failed to load device information for session {}: {}", sessionId, e.getMessage()); return null; } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java index f1cdf94c8..31ace32d9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java @@ -31,21 +31,21 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic @Override public String getAgentMcpAccessAddress(String id) { - // 获取到mcp的地址 + // Get MCP address String url = sysParamsService.getValue(Constant.SERVER_MCP_ENDPOINT, true); if (StringUtils.isBlank(url) || "null".equals(url)) { return null; } URI uri = getURI(url); - // 获取智能体mcp的url前缀 + // Get agent MCP URL prefix String agentMcpUrl = getAgentMcpUrl(uri); - // 获取密钥 + // Get secret key String key = getSecretKey(uri); - // 获取加密的token + // Get encrypted token String encryptToken = encryptToken(id, key); - // 对token进行URL编码 + // URL encode the token String encodedToken = URLEncoder.encode(encryptToken, StandardCharsets.UTF_8); - // 返回智能体Mcp路径的格式 + // Return agent MCP path format agentMcpUrl = "%s/mcp/?token=%s".formatted(agentMcpUrl, encodedToken); return agentMcpUrl; } @@ -57,11 +57,11 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic return List.of(); } - // 将 /mcp 替换为 /call + // Replace /mcp with /call wsUrl = wsUrl.replace("/mcp/", "/call/"); try { - // 创建 WebSocket 连接,增加超时时间到15秒 + // Create WebSocket connection, increase timeout to 15 seconds try (WebSocketClientManager client = WebSocketClientManager.build( new WebSocketClientManager.Builder() .uri(wsUrl) @@ -69,167 +69,167 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic .connectTimeout(8, TimeUnit.SECONDS) .maxSessionDuration(10, TimeUnit.SECONDS))) { - // 步骤1: 发送初始化消息并等待响应 - log.info("发送MCP初始化消息,智能体ID: {}", id); + // Step 1: Send initialization message and wait for response + log.info("Sending MCP initialization message, Agent ID: {}", id); client.sendText(XiaoZhiMcpJsonRpcJson.getInitializeJson()); - // 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动 + // Wait for initialization response (id=1) - Remove fixed delay, change to response-driven List initResponses = client.listenerWithoutClose(response -> { try { Map jsonMap = JsonUtils.parseObject(response, Map.class); if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { - // 检查是否有result字段,表示初始化成功 + // Check if there is a result field, indicating successful initialization return jsonMap.containsKey("result") && !jsonMap.containsKey("error"); } return false; } catch (Exception e) { - log.warn("解析初始化响应失败: {}", response, e); + log.warn("Failed to parse initialization response: {}", response, e); return false; } }); - // 验证初始化响应 + // Validate initialization response boolean initSucceeded = false; for (String response : initResponses) { try { Map jsonMap = JsonUtils.parseObject(response, Map.class); if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { if (jsonMap.containsKey("result")) { - log.info("MCP初始化成功,智能体ID: {}", id); + log.info("MCP initialization successful, Agent ID: {}", id); initSucceeded = true; break; } else if (jsonMap.containsKey("error")) { - log.error("MCP初始化失败,智能体ID: {}, 错误: {}", id, jsonMap.get("error")); + log.error("MCP initialization failed, Agent ID: {}, Error: {}", id, jsonMap.get("error")); return List.of(); } } } catch (Exception e) { - log.warn("处理初始化响应失败: {}", response, e); + log.warn("Failed to process initialization response: {}", response, e); } } if (!initSucceeded) { - log.error("未收到有效的MCP初始化响应,智能体ID: {}", id); + log.error("No valid MCP initialization response received, Agent ID: {}", id); return List.of(); } - // 步骤2: 发送初始化完成通知 - 只有在收到initialize响应后才发送 - log.info("发送MCP初始化完成通知,智能体ID: {}", id); + // Step 2: Send initialization complete notification - only send after receiving initialize response + log.info("Sending MCP initialization complete notification, Agent ID: {}", id); client.sendText(XiaoZhiMcpJsonRpcJson.getNotificationsInitializedJson()); - // 步骤3: 发送工具列表请求 - 立即发送,无需额外延迟 - log.info("发送MCP工具列表请求,智能体ID: {}", id); + // Step 3: Send tools list request - send immediately, no additional delay needed + log.info("Sending MCP tools list request, Agent ID: {}", id); client.sendText(XiaoZhiMcpJsonRpcJson.getToolsListJson()); - // 等待工具列表响应 (id=2) + // Wait for tools list response (id=2) List toolsResponses = client.listener(response -> { try { Map jsonMap = JsonUtils.parseObject(response, Map.class); return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id")); } catch (Exception e) { - log.warn("解析工具列表响应失败: {}", response, e); + log.warn("Failed to parse tools list response: {}", response, e); return false; } }); - // 处理工具列表响应 + // Process tools list response for (String response : toolsResponses) { try { Map jsonMap = JsonUtils.parseObject(response, Map.class); if (jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"))) { - // 检查是否有result字段 + // Check if there is a result field Object resultObj = jsonMap.get("result"); if (resultObj instanceof Map) { Map resultMap = (Map) resultObj; Object toolsObj = resultMap.get("tools"); if (toolsObj instanceof List) { List> toolsList = (List>) toolsObj; - // 提取工具名称列表 + // Extract tool name list List result = toolsList.stream() .map(tool -> (String) tool.get("name")) .filter(name -> name != null) .sorted() .collect(Collectors.toList()); - log.info("成功获取MCP工具列表,智能体ID: {}, 工具数量: {}", id, result.size()); + log.info("Successfully obtained MCP tools list, Agent ID: {}, Tool count: {}", id, result.size()); return result; } } else if (jsonMap.containsKey("error")) { - log.error("获取工具列表失败,智能体ID: {}, 错误: {}", id, jsonMap.get("error")); + log.error("Failed to get tools list, Agent ID: {}, Error: {}", id, jsonMap.get("error")); return List.of(); } } } catch (Exception e) { - log.warn("处理工具列表响应失败: {}", response, e); + log.warn("Failed to process tools list response: {}", response, e); } } - log.warn("未找到有效的工具列表响应,智能体ID: {}", id); + log.warn("No valid tools list response found, Agent ID: {}", id); return List.of(); } } catch (Exception e) { - log.error("获取智能体 MCP 工具列表失败,智能体ID: {},错误原因:{}", id, e.getMessage()); + log.error("Failed to get agent MCP tools list, Agent ID: {}, Error reason: {}", id, e.getMessage()); return List.of(); } } /** - * 获取URI对象 + * Get URI object * - * @param url 路径 - * @return URI对象 + * @param url path + * @return URI object */ private static URI getURI(String url) { try { return new URI(url); } catch (URISyntaxException e) { - log.error("路径格式不正确路径:{},\n错误信息:{}", url, e.getMessage()); - throw new RuntimeException("mcp的地址存在错误,请进入参数管理修改mcp接入点地址"); + log.error("Incorrect path format: {}, \nError message: {}", url, e.getMessage()); + throw new RuntimeException("MCP address has errors, please go to parameter management to modify MCP access point address"); } } /** - * 获取密钥 + * Get secret key * - * @param uri mcp地址 - * @return 密钥 + * @param uri MCP address + * @return secret key */ private static String getSecretKey(URI uri) { - // 获取参数 + // Get parameters String query = uri.getQuery(); - // 获取aes加密密钥 + // Get AES encryption key String str = "key="; return query.substring(query.indexOf(str) + str.length()); } /** - * 获取智能体mcp接入点url + * Get agent MCP access point URL * - * @param uri mcp地址 - * @return 智能体mcp接入点url + * @param uri MCP address + * @return Agent MCP access point URL */ private String getAgentMcpUrl(URI uri) { - // 获取协议 + // Get protocol String wsScheme = (uri.getScheme().equals("https")) ? "wss" : "ws"; - // 获取主机,端口,路径 + // Get host, port, path String path = uri.getSchemeSpecificPart(); - // 获取到最后一个/前的path + // Get path before the last / path = path.substring(0, path.lastIndexOf("/")); return wsScheme + ":" + path; } /** - * 获取对智能体id加密的token + * Get encrypted token for agent ID * - * @param agentId 智能体id - * @param key 加密密钥 - * @return 加密后token + * @param agentId Agent ID + * @param key Encryption key + * @return Encrypted token */ private static String encryptToken(String agentId, String key) { - // 使用md5对智能体id进行加密 + // Use MD5 to encrypt agent ID String md5 = HashEncryptionUtil.Md5hexDigest(agentId); - // aes需要加密文本 + // AES needs encrypted text String json = "{\"agentId\": \"%s\"}".formatted(md5); - // 加密后成token值 + // Encrypt to token value return AESUtils.encrypt(key, json); } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java index 6d839d9c5..0afd3c0c5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java @@ -23,7 +23,7 @@ import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; /** - * @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service实现 + * @description Database operation Service implementation for table [ai_agent_plugin_mapping(unique mapping table between Agent and plugins)] * @createDate 2025-05-25 22:33:17 */ @Service @@ -43,7 +43,7 @@ public class AgentPluginMappingServiceImpl extends ServiceImpl= 0; i--) { AgentPluginMapping mapping = list.get(i); if (StringUtils.isBlank(mapping.getProviderCode())) { - // 查询知识库插件参数 + // Load knowledge-base plugin parameters. KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseService.selectById(mapping.getPluginId()); if (knowledgeBaseEntity == null) { list.remove(i); @@ -85,9 +85,9 @@ public class AgentPluginMappingServiceImpl extends ServiceImpl implements AgentService { - private final AgentDao agentDao; - private final AgentTagDao agentTagDao; - private final TimbreService timbreModelService; - private final ModelConfigService modelConfigService; - private final RedisUtils redisUtils; - private final DeviceService deviceService; - private final AgentPluginMappingService agentPluginMappingService; - private final AgentChatHistoryService agentChatHistoryService; - private final AgentTemplateService agentTemplateService; - private final ModelProviderService modelProviderService; - private final AgentContextProviderService agentContextProviderService; - private final AgentTagService agentTagService; - - @Override - public PageData adminAgentList(Map params) { - IPage page = agentDao.selectPage( - getPage(params, "agent_name", true), - new QueryWrapper<>()); - return new PageData<>(page.getRecords(), page.getTotal()); - } - - @Override - public AgentInfoVO getAgentById(String id) { - AgentInfoVO agent = agentDao.selectAgentInfoById(id); - - if (agent == null) { - throw new RenException(ErrorCode.AGENT_NOT_FOUND); - } - - if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { - agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.IGNORE.getCode()); - } - if (agent.getChatHistoryConf() == null) { - agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode()); - } - - // 查询上下文源配置 - AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(id); - if (contextProviderEntity != null) { - agent.setContextProviders(contextProviderEntity.getContextProviders()); - } - - // 无需额外查询插件列表,已通过SQL查询出来 - return agent; - } - - @Override - public boolean insert(AgentEntity entity) { - // 如果ID为空,自动生成一个UUID作为ID - if (entity.getId() == null || entity.getId().trim().isEmpty()) { - entity.setId(UUID.randomUUID().toString().replace("-", "")); - } - - // 如果智能体编码为空,自动生成一个带前缀的编码 - if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) { - entity.setAgentCode("AGT_" + System.currentTimeMillis()); - } - - // 如果排序字段为空,设置默认值0 - if (entity.getSort() == null) { - entity.setSort(0); - } - - return super.insert(entity); - } - - @Override - public void deleteAgentByUserId(Long userId) { - UpdateWrapper wrapper = new UpdateWrapper<>(); - wrapper.eq("user_id", userId); - baseDao.delete(wrapper); - } - - @Override - public List getUserAgents(Long userId, String keyword, String searchType) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("user_id", userId).orderByDesc("created_at"); - - // 如果有搜索关键词,根据搜索类型添加相应的查询条件 - if (StringUtils.isNotBlank(keyword)) { - if ("mac".equals(searchType)) { - // 按MAC地址搜索:先搜索设备,再获取对应的智能体 - List devices = Optional - .ofNullable(deviceService.searchDevicesByMacAddress(keyword, userId)).orElseGet(ArrayList::new); - // 获取设备对应的智能体ID列表 - List agentIds = devices.stream() - .map(DeviceEntity::getAgentId) - .distinct() - .collect(Collectors.toList()); - if (ToolUtil.isNotEmpty(agentIds)) { - queryWrapper.in("id", agentIds); - } else { - return new ArrayList<>(); - } - } else { - // 按名称搜索(默认):同时搜索智能体名称和标签名 - List tagAgentIds = agentTagService.getAgentIdsByTagName(keyword); - if (ToolUtil.isNotEmpty(tagAgentIds)) { - queryWrapper.and(wrapper -> wrapper - .like("agent_name", keyword) - .or() - .in("id", tagAgentIds)); - } else { - queryWrapper.like("agent_name", keyword); - } - } - } - - // 执行查询 - List agentEntities = baseDao.selectList(queryWrapper); - - // 转换为DTO并设置所有必要字段 - return agentEntities.stream().map(this::buildAgentDTO).collect(Collectors.toList()); - } - - /** - * 将AgentEntity转换为AgentDTO - */ - private AgentDTO buildAgentDTO(AgentEntity agent) { - AgentDTO dto = new AgentDTO(); - dto.setId(agent.getId()); - dto.setAgentName(agent.getAgentName()); - dto.setSystemPrompt(agent.getSystemPrompt()); - - // 获取 TTS 模型名称 - dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); - - // 获取 LLM 模型名称 - dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); - - // 获取 VLLM 模型名称 - dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId())); - - // 获取记忆模型名称 - dto.setMemModelId(agent.getMemModelId()); - - // 获取 TTS 音色名称 - dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); - - // 获取智能体最近的最后连接时长 - dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId())); - - // 获取设备数量 - dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); - - // 获取标签列表 - List tags = agentTagDao.selectByAgentId(agent.getId()); - if (ToolUtil.isNotEmpty(tags)) { - dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList())); - } - - return dto; - } - - private AgentTagDTO convertTagToDTO(AgentTagEntity entity) { - AgentTagDTO dto = new AgentTagDTO(); - dto.setId(entity.getId()); - dto.setTagName(entity.getTagName()); - return dto; - } - - @Override - public Integer getDeviceCountByAgentId(String agentId) { - if (StringUtils.isBlank(agentId)) { - return 0; - } - - // 先从Redis中获取 - Integer cachedCount = (Integer) redisUtils.get(RedisKeys.getAgentDeviceCountById(agentId)); - if (cachedCount != null) { - return cachedCount; - } - - // 如果Redis中没有,则从数据库查询 - Integer deviceCount = agentDao.getDeviceCountByAgentId(agentId); - - // 将结果存入Redis - if (deviceCount != null) { - redisUtils.set(RedisKeys.getAgentDeviceCountById(agentId), deviceCount, 60); - } - - return deviceCount != null ? deviceCount : 0; - } - - @Override - public AgentEntity getDefaultAgentByMacAddress(String macAddress) { - if (StringUtils.isEmpty(macAddress)) { - return null; - } - return agentDao.getDefaultAgentByMacAddress(macAddress); - } - - @Override - public boolean checkAgentPermission(String agentId, Long userId) { - if (SecurityUser.getUser() == null || SecurityUser.getUser().getId() == null) { - return false; - } - // 获取智能体信息 - AgentEntity agent = getAgentById(agentId); - if (agent == null) { - return false; - } - - // 如果是超级管理员,直接返回true - if (SecurityUser.getUser().getSuperAdmin() == SuperAdminEnum.YES.value()) { - return true; - } - - // 检查是否是智能体的所有者 - return userId.equals(agent.getUserId()); - } - - // 根据id更新智能体信息 - @Override - @Transactional(rollbackFor = Exception.class) - public void updateAgentById(String agentId, AgentUpdateDTO dto) { - // 先查询现有实体 - AgentEntity existingEntity = this.getAgentById(agentId); - if (existingEntity == null) { - throw new RenException(ErrorCode.AGENT_NOT_FOUND); - } - - // 只更新提供的非空字段 - if (dto.getAgentName() != null) { - existingEntity.setAgentName(dto.getAgentName()); - } - if (dto.getAgentCode() != null) { - existingEntity.setAgentCode(dto.getAgentCode()); - } - if (dto.getAsrModelId() != null) { - existingEntity.setAsrModelId(dto.getAsrModelId()); - } - if (dto.getVadModelId() != null) { - existingEntity.setVadModelId(dto.getVadModelId()); - } - if (dto.getLlmModelId() != null) { - existingEntity.setLlmModelId(dto.getLlmModelId()); - } - if (dto.getSlmModelId() != null) { - existingEntity.setSlmModelId(dto.getSlmModelId()); - } - if (dto.getVllmModelId() != null) { - existingEntity.setVllmModelId(dto.getVllmModelId()); - } - if (dto.getTtsModelId() != null) { - existingEntity.setTtsModelId(dto.getTtsModelId()); - } - if (dto.getTtsVoiceId() != null) { - existingEntity.setTtsVoiceId(dto.getTtsVoiceId()); - } - if (dto.getTtsLanguage() != null) { - existingEntity.setTtsLanguage(dto.getTtsLanguage()); - } - if (dto.getTtsVolume() != null) { - existingEntity.setTtsVolume(dto.getTtsVolume()); - } - if (dto.getTtsRate() != null) { - existingEntity.setTtsRate(dto.getTtsRate()); - } - if (dto.getTtsPitch() != null) { - existingEntity.setTtsPitch(dto.getTtsPitch()); - } - if (dto.getMemModelId() != null) { - existingEntity.setMemModelId(dto.getMemModelId()); - } - if (dto.getIntentModelId() != null) { - existingEntity.setIntentModelId(dto.getIntentModelId()); - } - if (dto.getSystemPrompt() != null) { - existingEntity.setSystemPrompt(dto.getSystemPrompt()); - } - if (dto.getSummaryMemory() != null) { - existingEntity.setSummaryMemory(dto.getSummaryMemory()); - } - if (dto.getChatHistoryConf() != null) { - existingEntity.setChatHistoryConf(dto.getChatHistoryConf()); - } - if (dto.getLangCode() != null) { - existingEntity.setLangCode(dto.getLangCode()); - } - if (dto.getLanguage() != null) { - existingEntity.setLanguage(dto.getLanguage()); - } - if (dto.getSort() != null) { - existingEntity.setSort(dto.getSort()); - } - - // 更新函数插件信息 - List functions = dto.getFunctions(); - if (functions != null) { - // 1. 收集本次提交的 pluginId - List newPluginIds = functions.stream() - .map(AgentUpdateDTO.FunctionInfo::getPluginId) - .toList(); - - // 2. 查询当前agent现有的所有映射 - List existing = agentPluginMappingService.list( - new QueryWrapper() - .eq("agent_id", agentId)); - Map existMap = existing.stream() - .collect(Collectors.toMap(AgentPluginMapping::getPluginId, Function.identity())); - - // 3. 构造所有要 保存或更新 的实体 - List allToPersist = functions.stream().map(info -> { - AgentPluginMapping m = new AgentPluginMapping(); - m.setAgentId(agentId); - m.setPluginId(info.getPluginId()); - m.setParamInfo(JsonUtils.toJsonString(info.getParamInfo())); - AgentPluginMapping old = existMap.get(info.getPluginId()); - if (old != null) { - // 已存在,设置id表示更新 - m.setId(old.getId()); - } - return m; - }).toList(); - - // 4. 拆分:已有ID的走更新,无ID的走插入 - List toUpdate = allToPersist.stream() - .filter(m -> m.getId() != null) - .toList(); - List toInsert = allToPersist.stream() - .filter(m -> m.getId() == null) - .toList(); - - if (!toUpdate.isEmpty()) { - agentPluginMappingService.updateBatchById(toUpdate); - } - if (!toInsert.isEmpty()) { - agentPluginMappingService.saveBatch(toInsert); - } - - // 5. 删除本次不在提交列表里的插件映射 - List toDelete = existing.stream() - .filter(old -> !newPluginIds.contains(old.getPluginId())) - .map(AgentPluginMapping::getId) - .toList(); - if (!toDelete.isEmpty()) { - agentPluginMappingService.removeBatchByIds(toDelete); - } - } - - // 设置更新者信息 - UserDetail user = SecurityUser.getUser(); - existingEntity.setUpdater(user.getId()); - existingEntity.setUpdatedAt(new Date()); - - // 更新记忆策略 - // 删除所有记录 - if (existingEntity.getMemModelId() != null && existingEntity.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { - agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, true); - existingEntity.setSummaryMemory(""); - // 删除记忆 - } else if (existingEntity.getMemModelId() != null - && existingEntity.getMemModelId().equals(Constant.MEMORY_MEM_REPORT_ONLY)) { - existingEntity.setSummaryMemory(""); - } - - // 更新上下文源配置 - if (dto.getContextProviders() != null) { - AgentContextProviderEntity contextEntity = new AgentContextProviderEntity(); - contextEntity.setAgentId(agentId); - contextEntity.setContextProviders(dto.getContextProviders()); - agentContextProviderService.saveOrUpdateByAgentId(contextEntity); - } - - boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId()); - if (!b) { - throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); - } - this.updateById(existingEntity); - } - - /** - * 验证大语言模型和意图识别的参数是否符合匹配 - * - * @param llmModelId 大语言模型id - * @param intentModelId 意图识别id - * @return T 匹配 : F 不匹配 - */ - private boolean validateLLMIntentParams(String llmModelId, String intentModelId) { - if (StringUtils.isBlank(llmModelId)) { - return true; - } - ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId); - String type = llmModelData.getConfigJson().get("type").toString(); - // 如果查询大语言模型是openai或者ollama,意图识别选参数都可以 - if ("openai".equals(type) || "ollama".equals(type)) { - return true; - } - // 除了openai和ollama的类型,不可以选择id为Intent_function_call(函数调用)的意图识别 - return !"Intent_function_call".equals(intentModelId); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public String createAgent(AgentCreateDTO dto) { - // 转换为实体 - AgentEntity entity = ConvertUtils.sourceToTarget(dto, AgentEntity.class); - - // 获取默认模板 - AgentTemplateEntity template = agentTemplateService.getDefaultTemplate(); - if (template != null) { - // 设置模板中的默认值 - entity.setAsrModelId(template.getAsrModelId()); - entity.setVadModelId(template.getVadModelId()); - entity.setLlmModelId(template.getLlmModelId()); - entity.setVllmModelId(template.getVllmModelId()); - entity.setTtsModelId(template.getTtsModelId()); - - if (template.getTtsVoiceId() == null && template.getTtsModelId() != null) { - ModelConfigEntity ttsModel = modelConfigService.selectById(template.getTtsModelId()); - if (ttsModel != null && ttsModel.getConfigJson() != null) { - Map config = ttsModel.getConfigJson(); - String voice = (String) config.get("voice"); - if (StringUtils.isBlank(voice)) { - voice = (String) config.get("speaker"); - } - VoiceDTO timbre = timbreModelService.getByVoiceCode(template.getTtsModelId(), voice); - if (timbre != null) { - template.setTtsVoiceId(timbre.getId()); - } - } - } - - entity.setTtsVoiceId(template.getTtsVoiceId()); - entity.setMemModelId(template.getMemModelId()); - entity.setIntentModelId(template.getIntentModelId()); - entity.setSystemPrompt(template.getSystemPrompt()); - entity.setSummaryMemory(template.getSummaryMemory()); - - // 根据记忆模型类型设置默认的chatHistoryConf值 - if (template.getMemModelId() != null) { - if (template.getMemModelId().equals("Memory_nomem")) { - // 无记忆功能的模型,默认不记录聊天记录 - entity.setChatHistoryConf(0); - } else { - // 有记忆功能的模型,默认记录文本和语音 - entity.setChatHistoryConf(2); - } - } else { - entity.setChatHistoryConf(template.getChatHistoryConf()); - } - - entity.setLangCode(template.getLangCode()); - entity.setLanguage(template.getLanguage()); - } - - if (entity.getSlmModelId() == null) { - String defaultSlmModelId = getDefaultLLMModelId(); - if (defaultSlmModelId != null) { - entity.setSlmModelId(defaultSlmModelId); - } - } - - // 设置用户ID和创建者信息 - UserDetail user = SecurityUser.getUser(); - entity.setUserId(user.getId()); - entity.setCreator(user.getId()); - entity.setCreatedAt(new Date()); - - // 保存智能体 - insert(entity); - - // 设置默认插件 - List toInsert = new ArrayList<>(); - // 播放音乐、查天气、查新闻 - String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_WEATHER", - "SYSTEM_PLUGIN_NEWS_NEWSNOW" }; - for (String pluginId : pluginIds) { - ModelProviderDTO provider = modelProviderService.getById(pluginId); - if (provider == null) { - continue; - } - AgentPluginMapping mapping = new AgentPluginMapping(); - mapping.setPluginId(pluginId); - - Map paramInfo = new HashMap<>(); - List> fields = JsonUtils.parseObject(provider.getFields(), List.class); - if (fields != null) { - for (Map field : fields) { - paramInfo.put((String) field.get("key"), field.get("default")); - } - } - mapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); - mapping.setAgentId(entity.getId()); - toInsert.add(mapping); - } - // 保存默认插件 - agentPluginMappingService.saveBatch(toInsert); - return entity.getId(); - } - - private String getDefaultLLMModelId() { - try { - List llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); - if (llmConfigs == null || llmConfigs.isEmpty()) { - return null; - } - - for (ModelConfigEntity config : llmConfigs) { - if (config.getIsDefault() != null && config.getIsDefault() == 1) { - return config.getId(); - } - } - - return llmConfigs.get(0).getId(); - } catch (Exception e) { - return null; - } - } - -} \ No newline at end of file +package xiaozhi.modules.agent.service.impl; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; + +import lombok.AllArgsConstructor; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.common.utils.ToolUtil; +import xiaozhi.modules.agent.dao.AgentDao; +import xiaozhi.modules.agent.dao.AgentTagDao; +import xiaozhi.modules.agent.dto.AgentCreateDTO; +import xiaozhi.modules.agent.dto.AgentDTO; +import xiaozhi.modules.agent.dto.AgentTagDTO; +import xiaozhi.modules.agent.dto.AgentUpdateDTO; +import xiaozhi.modules.agent.entity.AgentContextProviderEntity; +import xiaozhi.modules.agent.entity.AgentEntity; +import xiaozhi.modules.agent.entity.AgentPluginMapping; +import xiaozhi.modules.agent.entity.AgentTagEntity; +import xiaozhi.modules.agent.entity.AgentTemplateEntity; +import xiaozhi.modules.agent.service.AgentChatHistoryService; +import xiaozhi.modules.agent.service.AgentContextProviderService; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.agent.service.AgentTagService; +import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.agent.vo.AgentInfoVO; +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.model.dto.ModelProviderDTO; +import xiaozhi.modules.model.dto.VoiceDTO; +import xiaozhi.modules.model.entity.ModelConfigEntity; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.model.service.ModelProviderService; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.enums.SuperAdminEnum; +import xiaozhi.modules.timbre.service.TimbreService; + +@Service +@AllArgsConstructor +public class AgentServiceImpl extends BaseServiceImpl implements AgentService { + private final AgentDao agentDao; + private final AgentTagDao agentTagDao; + private final TimbreService timbreModelService; + private final ModelConfigService modelConfigService; + private final RedisUtils redisUtils; + private final DeviceService deviceService; + private final AgentPluginMappingService agentPluginMappingService; + private final AgentChatHistoryService agentChatHistoryService; + private final AgentTemplateService agentTemplateService; + private final ModelProviderService modelProviderService; + private final AgentContextProviderService agentContextProviderService; + private final AgentTagService agentTagService; + + @Override + public PageData adminAgentList(Map params) { + IPage page = agentDao.selectPage( + getPage(params, "agent_name", true), + new QueryWrapper<>()); + return new PageData<>(page.getRecords(), page.getTotal()); + } + + @Override + public AgentInfoVO getAgentById(String id) { + AgentInfoVO agent = agentDao.selectAgentInfoById(id); + + if (agent == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + + if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { + agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.IGNORE.getCode()); + } + if (agent.getChatHistoryConf() == null) { + agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode()); + } + + // Load context-provider configuration. + AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(id); + if (contextProviderEntity != null) { + agent.setContextProviders(contextProviderEntity.getContextProviders()); + } + + // Plugin data is already loaded through SQL and does not need an extra query. + return agent; + } + + @Override + public boolean insert(AgentEntity entity) { + // Auto-generate a UUID when the ID is empty. + if (entity.getId() == null || entity.getId().trim().isEmpty()) { + entity.setId(UUID.randomUUID().toString().replace("-", "")); + } + + // Auto-generate an agent code with a prefix when missing. + if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) { + entity.setAgentCode("AGT_" + System.currentTimeMillis()); + } + + // Default the sort field to 0 when it is empty. + if (entity.getSort() == null) { + entity.setSort(0); + } + + return super.insert(entity); + } + + @Override + public void deleteAgentByUserId(Long userId) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("user_id", userId); + baseDao.delete(wrapper); + } + + @Override + public List getUserAgents(Long userId, String keyword, String searchType) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId).orderByDesc("created_at"); + + // Apply keyword filtering based on the selected search type. + if (StringUtils.isNotBlank(keyword)) { + if ("mac".equals(searchType)) { + // Search by MAC address: find devices first, then resolve their agents. + List devices = Optional + .ofNullable(deviceService.searchDevicesByMacAddress(keyword, userId)).orElseGet(ArrayList::new); + // Collect the agent IDs linked to those devices. + List agentIds = devices.stream() + .map(DeviceEntity::getAgentId) + .distinct() + .collect(Collectors.toList()); + if (ToolUtil.isNotEmpty(agentIds)) { + queryWrapper.in("id", agentIds); + } else { + return new ArrayList<>(); + } + } else { + // Default name search: match both agent names and tag names. + List tagAgentIds = agentTagService.getAgentIdsByTagName(keyword); + if (ToolUtil.isNotEmpty(tagAgentIds)) { + queryWrapper.and(wrapper -> wrapper + .like("agent_name", keyword) + .or() + .in("id", tagAgentIds)); + } else { + queryWrapper.like("agent_name", keyword); + } + } + } + + // Run the query. + List agentEntities = baseDao.selectList(queryWrapper); + + // Convert to DTOs and populate the required fields. + return agentEntities.stream().map(this::buildAgentDTO).collect(Collectors.toList()); + } + + /** + * Convert AgentEntity to AgentDTO. + */ + private AgentDTO buildAgentDTO(AgentEntity agent) { + AgentDTO dto = new AgentDTO(); + dto.setId(agent.getId()); + dto.setAgentName(agent.getAgentName()); + dto.setSystemPrompt(agent.getSystemPrompt()); + + // Load the TTS model name. + dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); + + // Load the LLM model name. + dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); + + // Load the VLLM model name. + dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId())); + + // Keep the memory model identifier. + dto.setMemModelId(agent.getMemModelId()); + + // Load the TTS voice name. + dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); + + // Load the agent's most recent device connection time. + dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId())); + + // Load the device count. + dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); + + // Load the tag list. + List tags = agentTagDao.selectByAgentId(agent.getId()); + if (ToolUtil.isNotEmpty(tags)) { + dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList())); + } + + return dto; + } + + private AgentTagDTO convertTagToDTO(AgentTagEntity entity) { + AgentTagDTO dto = new AgentTagDTO(); + dto.setId(entity.getId()); + dto.setTagName(entity.getTagName()); + return dto; + } + + @Override + public Integer getDeviceCountByAgentId(String agentId) { + if (StringUtils.isBlank(agentId)) { + return 0; + } + + // Check Redis first. + Integer cachedCount = (Integer) redisUtils.get(RedisKeys.getAgentDeviceCountById(agentId)); + if (cachedCount != null) { + return cachedCount; + } + + // Fall back to the database if Redis has no cached value. + Integer deviceCount = agentDao.getDeviceCountByAgentId(agentId); + + // Cache the result in Redis. + if (deviceCount != null) { + redisUtils.set(RedisKeys.getAgentDeviceCountById(agentId), deviceCount, 60); + } + + return deviceCount != null ? deviceCount : 0; + } + + @Override + public AgentEntity getDefaultAgentByMacAddress(String macAddress) { + if (StringUtils.isEmpty(macAddress)) { + return null; + } + return agentDao.getDefaultAgentByMacAddress(macAddress); + } + + @Override + public boolean checkAgentPermission(String agentId, Long userId) { + if (SecurityUser.getUser() == null || SecurityUser.getUser().getId() == null) { + return false; + } + // Load agent information. + AgentEntity agent = getAgentById(agentId); + if (agent == null) { + return false; + } + + // Super admins always have access. + if (SecurityUser.getUser().getSuperAdmin() == SuperAdminEnum.YES.value()) { + return true; + } + + // Otherwise the caller must own the agent. + return userId.equals(agent.getUserId()); + } + + // Update agent information by ID. + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAgentById(String agentId, AgentUpdateDTO dto) { + // Load the existing entity first. + AgentEntity existingEntity = this.getAgentById(agentId); + if (existingEntity == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + + // Only update non-null fields from the request. + if (dto.getAgentName() != null) { + existingEntity.setAgentName(dto.getAgentName()); + } + if (dto.getAgentCode() != null) { + existingEntity.setAgentCode(dto.getAgentCode()); + } + if (dto.getAsrModelId() != null) { + existingEntity.setAsrModelId(dto.getAsrModelId()); + } + if (dto.getVadModelId() != null) { + existingEntity.setVadModelId(dto.getVadModelId()); + } + if (dto.getLlmModelId() != null) { + existingEntity.setLlmModelId(dto.getLlmModelId()); + } + if (dto.getSlmModelId() != null) { + existingEntity.setSlmModelId(dto.getSlmModelId()); + } + if (dto.getVllmModelId() != null) { + existingEntity.setVllmModelId(dto.getVllmModelId()); + } + if (dto.getTtsModelId() != null) { + existingEntity.setTtsModelId(dto.getTtsModelId()); + } + if (dto.getTtsVoiceId() != null) { + existingEntity.setTtsVoiceId(dto.getTtsVoiceId()); + } + if (dto.getTtsLanguage() != null) { + existingEntity.setTtsLanguage(dto.getTtsLanguage()); + } + if (dto.getTtsVolume() != null) { + existingEntity.setTtsVolume(dto.getTtsVolume()); + } + if (dto.getTtsRate() != null) { + existingEntity.setTtsRate(dto.getTtsRate()); + } + if (dto.getTtsPitch() != null) { + existingEntity.setTtsPitch(dto.getTtsPitch()); + } + if (dto.getMemModelId() != null) { + existingEntity.setMemModelId(dto.getMemModelId()); + } + if (dto.getIntentModelId() != null) { + existingEntity.setIntentModelId(dto.getIntentModelId()); + } + if (dto.getSystemPrompt() != null) { + existingEntity.setSystemPrompt(dto.getSystemPrompt()); + } + if (dto.getSummaryMemory() != null) { + existingEntity.setSummaryMemory(dto.getSummaryMemory()); + } + if (dto.getChatHistoryConf() != null) { + existingEntity.setChatHistoryConf(dto.getChatHistoryConf()); + } + if (dto.getLangCode() != null) { + existingEntity.setLangCode(dto.getLangCode()); + } + if (dto.getLanguage() != null) { + existingEntity.setLanguage(dto.getLanguage()); + } + if (dto.getSort() != null) { + existingEntity.setSort(dto.getSort()); + } + + // Update function-plugin mappings. + List functions = dto.getFunctions(); + if (functions != null) { + // 1. Collect submitted plugin IDs. + List newPluginIds = functions.stream() + .map(AgentUpdateDTO.FunctionInfo::getPluginId) + .toList(); + + // 2. Load all current mappings for this agent. + List existing = agentPluginMappingService.list( + new QueryWrapper() + .eq("agent_id", agentId)); + Map existMap = existing.stream() + .collect(Collectors.toMap(AgentPluginMapping::getPluginId, Function.identity())); + + // 3. Build entities to save or update. + List allToPersist = functions.stream().map(info -> { + AgentPluginMapping m = new AgentPluginMapping(); + m.setAgentId(agentId); + m.setPluginId(info.getPluginId()); + m.setParamInfo(JsonUtils.toJsonString(info.getParamInfo())); + AgentPluginMapping old = existMap.get(info.getPluginId()); + if (old != null) { + // Existing mappings carry their ID so they are updated instead of inserted. + m.setId(old.getId()); + } + return m; + }).toList(); + + // 4. Split the set into updates and inserts. + List toUpdate = allToPersist.stream() + .filter(m -> m.getId() != null) + .toList(); + List toInsert = allToPersist.stream() + .filter(m -> m.getId() == null) + .toList(); + + if (!toUpdate.isEmpty()) { + agentPluginMappingService.updateBatchById(toUpdate); + } + if (!toInsert.isEmpty()) { + agentPluginMappingService.saveBatch(toInsert); + } + + // 5. Remove plugin mappings that are no longer part of the submission. + List toDelete = existing.stream() + .filter(old -> !newPluginIds.contains(old.getPluginId())) + .map(AgentPluginMapping::getId) + .toList(); + if (!toDelete.isEmpty()) { + agentPluginMappingService.removeBatchByIds(toDelete); + } + } + + // Set updater metadata. + UserDetail user = SecurityUser.getUser(); + existingEntity.setUpdater(user.getId()); + existingEntity.setUpdatedAt(new Date()); + + // Apply the memory-strategy cleanup rules. + // Delete all history when memory is disabled or report-only. + if (existingEntity.getMemModelId() == null || existingEntity.getMemModelId().equals(Constant.MEMORY_NO_MEM) + || existingEntity.getMemModelId().equals(Constant.MEMORY_MEM_REPORT_ONLY)) { + agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, true); + existingEntity.setSummaryMemory(""); + } else if (existingEntity.getChatHistoryConf() != null && existingEntity.getChatHistoryConf() == 1) { + // Delete audio data only. + agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, false); + } + + // Update context-provider configuration. + if (dto.getContextProviders() != null) { + AgentContextProviderEntity contextEntity = new AgentContextProviderEntity(); + contextEntity.setAgentId(agentId); + contextEntity.setContextProviders(dto.getContextProviders()); + agentContextProviderService.saveOrUpdateByAgentId(contextEntity); + } + + boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId()); + if (!b) { + throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); + } + this.updateById(existingEntity); + } + + /** + * Validate whether the LLM and intent-recognition parameters are compatible. + * + * @param llmModelId LLM model ID + * @param intentModelId intent-recognition model ID + * @return true when compatible, false otherwise + */ + private boolean validateLLMIntentParams(String llmModelId, String intentModelId) { + if (StringUtils.isBlank(llmModelId)) { + return true; + } + ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId); + String type = llmModelData.getConfigJson().get("type").toString(); + // OpenAI and Ollama can work with any intent-recognition selection. + if ("openai".equals(type) || "ollama".equals(type)) { + return true; + } + // Other model types cannot use the Intent_function_call intent option. + return !"Intent_function_call".equals(intentModelId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public String createAgent(AgentCreateDTO dto) { + // Convert the request to an entity. + AgentEntity entity = ConvertUtils.sourceToTarget(dto, AgentEntity.class); + + // Load the default template. + AgentTemplateEntity template = agentTemplateService.getDefaultTemplate(); + if (template != null) { + // Apply template defaults. + entity.setAsrModelId(template.getAsrModelId()); + entity.setVadModelId(template.getVadModelId()); + entity.setLlmModelId(template.getLlmModelId()); + entity.setVllmModelId(template.getVllmModelId()); + entity.setTtsModelId(template.getTtsModelId()); + + if (template.getTtsVoiceId() == null && template.getTtsModelId() != null) { + ModelConfigEntity ttsModel = modelConfigService.selectById(template.getTtsModelId()); + if (ttsModel != null && ttsModel.getConfigJson() != null) { + Map config = ttsModel.getConfigJson(); + String voice = (String) config.get("voice"); + if (StringUtils.isBlank(voice)) { + voice = (String) config.get("speaker"); + } + VoiceDTO timbre = timbreModelService.getByVoiceCode(template.getTtsModelId(), voice); + if (timbre != null) { + template.setTtsVoiceId(timbre.getId()); + } + } + } + + entity.setTtsVoiceId(template.getTtsVoiceId()); + entity.setMemModelId(template.getMemModelId()); + entity.setIntentModelId(template.getIntentModelId()); + entity.setSystemPrompt(template.getSystemPrompt()); + entity.setSummaryMemory(template.getSummaryMemory()); + + // Set the default chatHistoryConf based on the memory model type. + if (template.getMemModelId() != null) { + if (template.getMemModelId().equals("Memory_nomem")) { + // Models without memory do not record chat history by default. + entity.setChatHistoryConf(0); + } else { + // Models with memory record both text and audio by default. + entity.setChatHistoryConf(2); + } + } else { + entity.setChatHistoryConf(template.getChatHistoryConf()); + } + + entity.setLangCode(template.getLangCode()); + entity.setLanguage(template.getLanguage()); + } + + if (entity.getSlmModelId() == null) { + String defaultSlmModelId = getDefaultLLMModelId(); + if (defaultSlmModelId != null) { + entity.setSlmModelId(defaultSlmModelId); + } + } + + // Set owner and creator metadata. + UserDetail user = SecurityUser.getUser(); + entity.setUserId(user.getId()); + entity.setCreator(user.getId()); + entity.setCreatedAt(new Date()); + + // Save the agent. + insert(entity); + + // Set default plugins. + List toInsert = new ArrayList<>(); + // Music playback, weather lookup, and news lookup. + String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_WEATHER", + "SYSTEM_PLUGIN_NEWS_NEWSNOW" }; + for (String pluginId : pluginIds) { + ModelProviderDTO provider = modelProviderService.getById(pluginId); + if (provider == null) { + continue; + } + AgentPluginMapping mapping = new AgentPluginMapping(); + mapping.setPluginId(pluginId); + + Map paramInfo = new HashMap<>(); + List> fields = JsonUtils.parseObject(provider.getFields(), List.class); + if (fields != null) { + for (Map field : fields) { + paramInfo.put((String) field.get("key"), field.get("default")); + } + } + mapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); + mapping.setAgentId(entity.getId()); + toInsert.add(mapping); + } + // Save the default plugins. + agentPluginMappingService.saveBatch(toInsert); + return entity.getId(); + } + + private String getDefaultLLMModelId() { + try { + List llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); + if (llmConfigs == null || llmConfigs.isEmpty()) { + return null; + } + + for (ModelConfigEntity config : llmConfigs) { + if (config.getIsDefault() != null && config.getIsDefault() == 1) { + return config.getId(); + } + } + + return llmConfigs.get(0).getId(); + } catch (Exception e) { + return null; + } + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java index 321b5cb27..20c1d6cbf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java @@ -17,7 +17,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; /** * @author chenerlei - * @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service实现 + * @description Database operation Service implementation for table [ai_agent_template(agent configuration template table)] * @createDate 2025-03-22 11:48:18 */ @Service @@ -25,9 +25,9 @@ public class AgentTemplateServiceImpl extends ServiceImpl wrapper = new LambdaQueryWrapper<>(); @@ -37,15 +37,15 @@ public class AgentTemplateServiceImpl extends ServiceImpl updateWrapper = new UpdateWrapper<>(); updateWrapper.gt("sort", deletedSort) .setSql("sort = sort - 1"); - // 执行批量更新,将这些记录的排序值减1 + // Execute batch update to decrease sort value by 1 for these records this.update(updateWrapper); } @Override public Integer getNextAvailableSort() { - // 查询所有已存在的排序值并按升序排序 + // Query all existing sort values and sort them in ascending order List sortValues = baseMapper.selectList(new QueryWrapper()) .stream() .map(AgentTemplateEntity::getSort) @@ -104,22 +104,22 @@ public class AgentTemplateServiceImpl extends ServiceImpl expectedSort) { - // 找到空缺的序号 + // Found a gap in sequence numbers return expectedSort; } expectedSort = sort + 1; } - // 如果没有空缺,返回最大序号+1 + // If no gaps found, return max sequence number + 1 return expectedSort; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java index 088e46635..d075089cc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java @@ -52,9 +52,9 @@ public class AgentVoicePrintServiceImpl extends ServiceImpl RECOGNITION) { - // 根据识别出的声纹ID查询对应的用户信息 + // Query corresponding user information based on recognized voiceprint ID AgentVoicePrintEntity existingVoicePrint = baseMapper.selectById(response.getSpeakerId()); - String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "未知用户"; + String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "Unknown user"; throw new RenException(ErrorCode.VOICEPRINT_ALREADY_REGISTERED, existingUserName); } AgentVoicePrintEntity entity = ConvertUtils.sourceToTarget(dto, AgentVoicePrintEntity.class); - // 开启事务 + // Start transaction return Boolean.TRUE.equals(transactionTemplate.execute(status -> { try { - // 保存声纹信息 + // Save voiceprint information int row = baseMapper.insert(entity); - // 插入一条数据,影响的数据不等于1说明出现了,保存问题回滚 + // Insert one record, if affected rows != 1, indicates save problem, rollback if (row != 1) { - status.setRollbackOnly(); // 标记事务回滚 + status.setRollbackOnly(); // Mark transaction rollback return false; } - // 发送注册声纹请求 + // Send voiceprint registration request registerVoicePrint(entity.getId(), resource); return true; } catch (RenException e) { - status.setRollbackOnly(); // 标记事务回滚 + status.setRollbackOnly(); // Mark transaction rollback throw e; } catch (Exception e) { - status.setRollbackOnly(); // 标记事务回滚 - log.error("保存声纹错误原因:{}", e.getMessage()); + status.setRollbackOnly(); // Mark transaction rollback + log.error("Save voiceprint error reason: {}", e.getMessage()); throw new RenException(ErrorCode.VOICE_PRINT_SAVE_ERROR); } })); @@ -108,32 +108,32 @@ public class AgentVoicePrintServiceImpl extends ServiceImpl { try { - // 删除声纹,按照指定当前登录用户和智能体 + // Delete voiceprint, according to specified current logged-in user and agent int row = baseMapper.delete(new LambdaQueryWrapper() .eq(AgentVoicePrintEntity::getId, voicePrintId) .eq(AgentVoicePrintEntity::getCreator, userId)); if (row != 1) { - status.setRollbackOnly(); // 标记事务回滚 + status.setRollbackOnly(); // Mark transaction rollback return false; } return true; } catch (Exception e) { - status.setRollbackOnly(); // 标记事务回滚 - log.error("删除声纹存在错误原因:{}", e.getMessage()); + status.setRollbackOnly(); // Mark transaction rollback + log.error("Delete voiceprint error reason: {}", e.getMessage()); throw new RenException(ErrorCode.VOICEPRINT_DELETE_ERROR); } })); - // 数据库声纹数据删除成功才继续执行删除声纹服务的数据 + // Continue to delete voiceprint service data only after database voiceprint data deletion succeeds if(b){ taskExecutor.execute(()-> { try { cancelVoicePrint(voicePrintId); }catch (RuntimeException e) { - log.error("删除声纹存在运行时错误原因:{},id:{}", e.getMessage(),voicePrintId); + log.error("Delete voiceprint runtime error reason: {}, id: {}", e.getMessage(),voicePrintId); } }); } @@ -142,12 +142,12 @@ public class AgentVoicePrintServiceImpl extends ServiceImpl list(Long userId, String agentId) { - // 按照指定当前登录用户和智能体查找数据 + // Search data by current logged-in user and agent List list = baseMapper.selectList(new LambdaQueryWrapper() .eq(AgentVoicePrintEntity::getAgentId, agentId) .eq(AgentVoicePrintEntity::getCreator, userId)); return list.stream().map(entity -> { - // 遍历转换成AgentVoicePrintVO类型 + // Iterate and convert to AgentVoicePrintVO type return ConvertUtils.sourceToTarget(entity, AgentVoicePrintVO.class); }).toList(); @@ -162,79 +162,79 @@ public class AgentVoicePrintServiceImpl extends ServiceImpl RECOGNITION) { - // 判断返回的id如果不是要修改的声纹id,说明这个声纹id,现在要注册的声音已经存在且不是原来的声纹,不允许修改 + // If returned id is not the voiceprint id to be modified, it means the voiceprint id already exists and is not the original voiceprint, modification not allowed if (!response.getSpeakerId().equals(dto.getId())) { - // 根据识别出的声纹ID查询对应的用户信息 + // Query corresponding user information based on recognized voiceprint ID AgentVoicePrintEntity existingVoicePrint = baseMapper.selectById(response.getSpeakerId()); - String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "未知用户"; + String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "Unknown user"; throw new RenException(ErrorCode.VOICEPRINT_UPDATE_NOT_ALLOWED, existingUserName); } } } else { resource = null; } - // 开启事务 + // Start transaction return Boolean.TRUE.equals(transactionTemplate.execute(status -> { try { AgentVoicePrintEntity entity = ConvertUtils.sourceToTarget(dto, AgentVoicePrintEntity.class); int row = baseMapper.updateById(entity); if (row != 1) { - status.setRollbackOnly(); // 标记事务回滚 + status.setRollbackOnly(); // Mark transaction rollback return false; } if (resource != null) { String id = entity.getId(); - // 先注销之前这个声纹id上的声纹向量 + // First cancel the previous voiceprint vector on this voiceprint id cancelVoicePrint(id); - // 发送注册声纹请求 + // Send voiceprint registration request registerVoicePrint(id, resource); } return true; } catch (RenException e) { - status.setRollbackOnly(); // 标记事务回滚 + status.setRollbackOnly(); // Mark transaction rollback throw e; } catch (Exception e) { - status.setRollbackOnly(); // 标记事务回滚 - log.error("修改声纹错误原因:{}", e.getMessage()); + status.setRollbackOnly(); // Mark transaction rollback + log.error("Voiceprint modification error reason: {}", e.getMessage()); throw new RenException(ErrorCode.VOICEPRINT_UPDATE_ADMIN_ERROR); } })); } /** - * 获取生纹接口URI对象 + * Get voiceprint interface URI object * - * @return URI对象 + * @return URI object */ private URI getVoicePrintURI() { - // 获取声纹接口地址 + // Get voiceprint interface address String voicePrint = sysParamsService.getValue(Constant.SERVER_VOICE_PRINT, true); try { return new URI(voicePrint); } catch (URISyntaxException e) { - log.error("路径格式不正确路径:{},\n错误信息:{}", voicePrint, e.getMessage()); + log.error("Incorrect path format path: {}, \nError message:{}", voicePrint, e.getMessage()); throw new RenException(ErrorCode.VOICEPRINT_API_URI_ERROR); } } /** - * 获取声纹地址基础路径 + * Get voiceprint address base path * - * @param uri 声纹地址uri - * @return 基础路径 + * @param uri Voiceprint address uri + * @return Base path */ private String getBaseUrl(URI uri) { String protocol = uri.getScheme(); @@ -248,160 +248,160 @@ public class AgentVoicePrintServiceImpl extends ServiceImpl body = new LinkedMultiValueMap<>(); body.add("speaker_id", id); body.add("file", resource); - // 创建请求头 + // Create request headers HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorization(uri)); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - // 创建请求体 + // Create request body HttpEntity> requestEntity = new HttpEntity<>(body, headers); - // 发送 POST 请求 + // Send POST request ResponseEntity response = restTemplate.postForEntity(requestUrl, requestEntity, String.class); if (response.getStatusCode() != HttpStatus.OK) { - log.error("声纹注册失败,请求路径:{}", requestUrl); + log.error("Voiceprint registration failed, request path: {}", requestUrl); throw new RenException(ErrorCode.VOICEPRINT_REGISTER_REQUEST_ERROR); } - // 检查响应内容 + // Check response content String responseBody = response.getBody(); if (responseBody == null || !responseBody.contains("true")) { - log.error("声纹注册失败,请求处理失败内容:{}", responseBody == null ? "空内容" : responseBody); + log.error("Voiceprint registration failed, request processing failed content: {}", responseBody == null ? "Empty content" : responseBody); throw new RenException(ErrorCode.VOICEPRINT_REGISTER_PROCESS_ERROR); } } /** - * 发送注销声纹的请求 + * Send voiceprint cancellation request * - * @param voicePrintId 声纹id + * @param voicePrintId Voiceprint ID */ private void cancelVoicePrint(String voicePrintId) { URI uri = getVoicePrintURI(); String baseUrl = getBaseUrl(uri); String requestUrl = baseUrl + "/voiceprint/" + voicePrintId; - // 创建请求头 + // Create request headers HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorization(uri)); - // 创建请求体 + // Create request body HttpEntity> requestEntity = new HttpEntity<>(headers); - // 发送 POST 请求 + // Send POST request ResponseEntity response = restTemplate.exchange(requestUrl, HttpMethod.DELETE, requestEntity, String.class); if (response.getStatusCode() != HttpStatus.OK) { - log.error("声纹注销失败,请求路径:{}", requestUrl); + log.error("Voiceprint cancellation failed, request path: {}", requestUrl); throw new RenException(ErrorCode.VOICEPRINT_UNREGISTER_REQUEST_ERROR); } - // 检查响应内容 + // Check response content String responseBody = response.getBody(); if (responseBody == null || !responseBody.contains("true")) { - log.error("声纹注销失败,请求处理失败内容:{}", responseBody == null ? "空内容" : responseBody); + log.error("Voiceprint cancellation failed, request processing failed content: {}", responseBody == null ? "Empty content" : responseBody); throw new RenException(ErrorCode.VOICEPRINT_UNREGISTER_PROCESS_ERROR); } } /** - * 发送识别声纹http请求 + * Send voiceprint identification HTTP request * - * @param agentId 智能体id - * @param resource 声纹音频资源 - * @return 返回识别数据 + * @param agentId Agent ID + * @param resource Voiceprint audio resource + * @return Return identification data */ private IdentifyVoicePrintResponse identifyVoicePrint(String agentId, ByteArrayResource resource) { - // 获取该智能体所有注册的声纹 + // Get all registered voiceprints for this agent List agentVoicePrintList = baseMapper .selectList(new LambdaQueryWrapper() .select(AgentVoicePrintEntity::getId) .eq(AgentVoicePrintEntity::getAgentId, agentId)); - // 声纹数量为0,说明还没注册过声纹不需要发生识别请求 + // Voiceprint count is 0, means no voiceprints registered yet, no need to send identification request if (agentVoicePrintList.isEmpty()) { return null; } - // 处理声纹接口地址,获取前缀 + // Process voiceprint interface address, get prefix URI uri = getVoicePrintURI(); String baseUrl = getBaseUrl(uri); String requestUrl = baseUrl + "/voiceprint/identify"; - // 创建请求体 + // Create request body MultiValueMap body = new LinkedMultiValueMap<>(); - // 创建speaker_id参数 + // Create speaker_id parameter String speakerIds = agentVoicePrintList.stream() .map(AgentVoicePrintEntity::getId) .collect(Collectors.joining(",")); body.add("speaker_ids", speakerIds); body.add("file", resource); - // 创建请求头 + // Create request headers HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorization(uri)); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - // 创建请求体 + // Create request body HttpEntity> requestEntity = new HttpEntity<>(body, headers); - // 发送 POST 请求 + // Send POST request ResponseEntity response = restTemplate.postForEntity(requestUrl, requestEntity, String.class); if (response.getStatusCode() != HttpStatus.OK) { - log.error("声纹识别请求失败,请求路径:{}", requestUrl); + log.error("Voiceprint identification request failed, request path: {}", requestUrl); throw new RenException(ErrorCode.VOICEPRINT_IDENTIFY_REQUEST_ERROR); } - // 检查响应内容 + // Check response content String responseBody = response.getBody(); if (responseBody != null) { return JsonUtils.parseObject(responseBody, IdentifyVoicePrintResponse.class); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java index cec0427bc..b5e0c8db5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java @@ -4,13 +4,13 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 智能体用户个人聊天数据的VO + * Agent user personal chat data VO */ @Data public class AgentChatHistoryUserVO { - @Schema(description = "聊天内容") + @Schema(description = "Chat content") private String content; - @Schema(description = "音频ID") + @Schema(description = "Audio ID") private String audioId; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java index 3da8b71cd..1d67444aa 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java @@ -12,17 +12,17 @@ import xiaozhi.modules.agent.entity.AgentPluginMapping; import java.util.List; /** - * Agent信息返回体VO - * 这里直接extend了Agent实体类AgentEntity,后续需要规范返回字段可以copy字段出来 + * Agent information response body VO + * This directly extends the Agent entity class AgentEntity, fields can be copied out later if return fields need to be standardized */ @EqualsAndHashCode(callSuper = true) @Data public class AgentInfoVO extends AgentEntity { - @Schema(description = "插件列表Id") + @Schema(description = "Plugin list ID") @TableField(typeHandler = JacksonTypeHandler.class) private List functions; - @Schema(description = "上下文源配置") + @Schema(description = "Context-provider configuration") private List contextProviders; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentTemplateVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentTemplateVO.java index a5302e5b6..fd178174a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentTemplateVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentTemplateVO.java @@ -7,9 +7,9 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity; @Data @EqualsAndHashCode(callSuper = true) public class AgentTemplateVO extends AgentTemplateEntity { - // 角色音色 + // Character voice private String ttsModelName; - // 角色模型 + // Character model private String llmModelName; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java index b647e8b8f..1e7214926 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java @@ -5,29 +5,29 @@ import lombok.Data; import java.util.Date; /** - * 展示智能体声纹列表VO + * VO for displaying agent voiceprint list */ @Data public class AgentVoicePrintVO { /** - * 主键id + * Primary key 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; /** - * 创建时间 + * Creation time */ private Date createDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java b/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java index f21795a3e..83b88e999 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java @@ -15,28 +15,28 @@ import xiaozhi.modules.config.dto.AgentModelsDTO; import xiaozhi.modules.config.service.ConfigService; /** - * xiaozhi-server 配置获取 + * xiaozhi-server configuration retrieval * * @since 1.0.0 */ @RestController @RequestMapping("config") -@Tag(name = "参数管理") +@Tag(name = "Parameter Management") @AllArgsConstructor public class ConfigController { private final ConfigService configService; @PostMapping("server-base") - @Operation(summary = "服务端获取配置接口") + @Operation(summary = "Server configuration retrieval interface") public Result getConfig() { Object config = configService.getConfig(true); return new Result().ok(config); } @PostMapping("agent-models") - @Operation(summary = "获取智能体模型") + @Operation(summary = "Get agent models") public Result getAgentModels(@Valid @RequestBody AgentModelsDTO dto) { - // 效验数据 + // Validate data ValidatorUtils.validateEntity(dto); Object models = configService.getAgentModels(dto.getMacAddress(), dto.getSelectedModule()); return new Result().ok(models); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/dto/AgentModelsDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/config/dto/AgentModelsDTO.java index 47c08a818..50b55d1c3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/dto/AgentModelsDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/dto/AgentModelsDTO.java @@ -8,18 +8,18 @@ import jakarta.validation.constraints.NotNull; import lombok.Data; @Data -@Schema(description = "获取智能体模型配置DTO") +@Schema(description = "Get agent model configuration DTO") public class AgentModelsDTO { - @NotBlank(message = "设备MAC地址不能为空") - @Schema(description = "设备MAC地址") + @NotBlank(message = "Device MAC address cannot be empty") + @Schema(description = "Device MAC address") private String macAddress; - @NotBlank(message = "客户端ID不能为空") - @Schema(description = "客户端ID") + @NotBlank(message = "Client ID cannot be empty") + @Schema(description = "Client ID") private String clientId; - @NotNull(message = "客户端已实例化的模型不能为空") - @Schema(description = "客户端已实例化的模型") + @NotNull(message = "Client instantiated models cannot be empty") + @Schema(description = "Client instantiated models") private Map selectedModule; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/init/SystemInitConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/config/init/SystemInitConfig.java index e47cd0c75..59e460fd9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/init/SystemInitConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/init/SystemInitConfig.java @@ -2,7 +2,7 @@ package xiaozhi.modules.config.init; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; +import org.springframework.core.env.Environment; import jakarta.annotation.PostConstruct; import xiaozhi.common.constant.Constant; @@ -12,7 +12,6 @@ import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.sys.service.SysParamsService; @Configuration -@DependsOn("liquibase") public class SystemInitConfig { @Autowired @@ -24,14 +23,22 @@ public class SystemInitConfig { @Autowired private RedisUtils redisUtils; + @Autowired + private Environment environment; + @PostConstruct public void init() { - // 检查版本号 + // Skip Redis operations during testing + if (environment.acceptsProfiles("test")) { + return; + } + + // Check version number String redisVersion = (String) redisUtils.get(RedisKeys.getVersionKey()); if (!Constant.VERSION.equals(redisVersion)) { - // 如果版本不一致,清空Redis + // If version is inconsistent, clear Redis redisUtils.emptyAll(); - // 存储新版本号 + // Store new version number redisUtils.set(RedisKeys.getVersionKey(), Constant.VERSION); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java index 93845e8ec..9fe0acc1f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java @@ -4,19 +4,19 @@ import java.util.Map; public interface ConfigService { /** - * 获取服务器配置 + * Get server configuration * - * @param isCache 是否缓存 - * @return 配置信息 + * @param isCache Whether to cache + * @return Configuration information */ Object getConfig(Boolean isCache); /** - * 获取智能体模型配置 + * Get agent model configuration * - * @param macAddress MAC地址 - * @param selectedModule 客户端已实例化的模型 - * @return 模型配置信息 + * @param macAddress MAC address + * @param selectedModule Client instantiated models + * @return Model configuration information */ Map getAgentModels(String macAddress, Map selectedModule); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 278d4299c..d3150994e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -62,24 +62,24 @@ public class ConfigServiceImpl implements ConfigService { @Override public Object getConfig(Boolean isCache) { if (isCache) { - // 先从Redis获取配置 + // Check Redis first. Object cachedConfig = redisUtils.get(RedisKeys.getServerConfigKey()); if (cachedConfig != null) { return cachedConfig; } } - // 构建配置信息 + // Build the config payload. Map result = new HashMap<>(); buildConfig(result); - // 查询默认智能体 + // Load the default agent template. AgentTemplateEntity agent = agentTemplateService.getDefaultTemplate(); if (agent == null) { throw new RenException(ErrorCode.AGENT_TEMPLATE_NOT_FOUND); } - // 构建模块配置 + // Build module configuration. buildModuleConfig( null, null, @@ -103,7 +103,7 @@ public class ConfigServiceImpl implements ConfigService { result, isCache); - // 将配置存入Redis + // Cache the generated config in Redis. redisUtils.set(RedisKeys.getServerConfigKey(), result); return result; @@ -111,19 +111,19 @@ public class ConfigServiceImpl implements ConfigService { @Override public Map getAgentModels(String macAddress, Map selectedModule) { - // 检查是否为管理控制台请求 + // Check whether this request comes from the admin console. String redisKey = RedisKeys.getTmpRegisterMacKey(macAddress); Object isAdminRequest = redisUtils.get(redisKey); if (isAdminRequest != null && "true".equals(isAdminRequest)) { - // 管理控制台请求,返回getConfig的结果 - redisUtils.delete(redisKey); // 使用后清理 + // Admin-console requests reuse the server config response. + redisUtils.delete(redisKey); // Clean up after use. return (Map) getConfig(true); } - // 根据MAC地址查找设备 + // Look up the device by MAC address. DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); if (device == null) { - // 如果设备,去redis里看看有没有需要连接的设备 + // Check Redis for pending bind information. String cachedCode = deviceService.geCodeByDeviceId(macAddress); if (StringUtils.isNotBlank(cachedCode)) { throw new RenException(ErrorCode.OTA_DEVICE_NEED_BIND, cachedCode); @@ -131,12 +131,12 @@ public class ConfigServiceImpl implements ConfigService { throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND); } - // 获取智能体信息 + // Load the agent configuration. AgentEntity agent = agentService.getAgentById(device.getAgentId()); if (agent == null) { throw new RenException(ErrorCode.AGENT_NOT_FOUND); } - // 获取音色信息 + // Load timbre / voice information. String voice = null; String referenceAudio = null; String referenceText = null; @@ -146,27 +146,27 @@ public class ConfigServiceImpl implements ConfigService { voice = timbre.getTtsVoice(); referenceAudio = timbre.getReferenceAudio(); referenceText = timbre.getReferenceText(); - // 优先使用用户选择的语言,如果没有则使用音色支持的第一个语言 + // Prefer the user-selected language, otherwise use the first supported language. if (StringUtils.isNotBlank(agent.getTtsLanguage())) { language = agent.getTtsLanguage(); } else if (StringUtils.isNotBlank(timbre.getLanguages())) { - language = timbre.getLanguages().split("、")[0].trim(); + language = timbre.getLanguages().split("[、,]")[0].trim(); } } else { VoiceCloneEntity voice_print = cloneVoiceService.selectById(agent.getTtsVoiceId()); if (voice_print != null) { voice = voice_print.getVoiceId(); - // 优先使用用户选择的语言,如果没有则使用默认值 - language = StringUtils.isNotBlank(agent.getTtsLanguage()) ? agent.getTtsLanguage() : "普通话"; + // Prefer the user-selected language, otherwise use an English-first default. + language = StringUtils.isNotBlank(agent.getTtsLanguage()) ? agent.getTtsLanguage() : "English"; } } - // 构建返回数据 + // Build the response payload. Map result = new HashMap<>(); - // 获取单台设备每天最多输出字数 + // Device-level daily output limit. String deviceMaxOutputSize = sysParamsService.getValue("device_max_output_size", true); result.put("device_max_output_size", deviceMaxOutputSize); - // 获取聊天记录配置 + // Chat-history configuration. Integer chatHistoryConf = agent.getChatHistoryConf(); if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { chatHistoryConf = Constant.ChatHistoryConfEnum.IGNORE.getCode(); @@ -176,7 +176,7 @@ public class ConfigServiceImpl implements ConfigService { chatHistoryConf = Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode(); } result.put("chat_history_conf", chatHistoryConf); - // 如果客户端已实例化模型,则不返回 + // Skip returning models already instantiated by the client. String alreadySelectedVadModelId = selectedModule.get("VAD"); if (alreadySelectedVadModelId != null && alreadySelectedVadModelId.equals(agent.getVadModelId())) { agent.setVadModelId(null); @@ -186,7 +186,7 @@ public class ConfigServiceImpl implements ConfigService { agent.setAsrModelId(null); } - // 添加函数调用参数信息 + // Add function-call parameter metadata. if (!Objects.equals(agent.getIntentModelId(), "Intent_nointent")) { String agentId = agent.getId(); List pluginMappings = agentPluginMappingService.agentPluginParamsByAgentId(agentId); @@ -198,7 +198,7 @@ public class ConfigServiceImpl implements ConfigService { result.put("plugins", pluginParams); } } - // 获取mcp接入点地址 + // MCP endpoint address. String mcpEndpoint = agentMcpAccessPointService.getAgentMcpAccessAddress(agent.getId()); if (StringUtils.isNotBlank(mcpEndpoint) && mcpEndpoint.startsWith("ws")) { mcpEndpoint = mcpEndpoint.replace("/mcp/", "/call/"); @@ -212,10 +212,10 @@ public class ConfigServiceImpl implements ConfigService { result.put("context_providers", contextProviderEntity.getContextProviders()); } - // 获取声纹信息 + // Voiceprint configuration. buildVoiceprintConfig(agent.getId(), result); - // 构建模块配置 + // Build module configuration. buildModuleConfig( agent.getAgentName(), agent.getSystemPrompt(), @@ -243,21 +243,21 @@ public class ConfigServiceImpl implements ConfigService { } /** - * 构建配置信息 + * Build the config payload. * - * @param config 系统参数列表 - * @return 配置信息 + * @param config system-parameter map + * @return config payload */ private Object buildConfig(Map config) { - // 查询所有系统参数 + // Query every system parameter. List paramsList = sysParamsService.list(new HashMap<>()); for (SysParamsDTO param : paramsList) { String[] keys = param.getParamCode().split("\\."); Map current = config; - // 遍历除最后一个key之外的所有key + // Walk every key except the final one. for (int i = 0; i < keys.length - 1; i++) { String key = keys[i]; if (!current.containsKey(key)) { @@ -266,16 +266,16 @@ public class ConfigServiceImpl implements ConfigService { current = (Map) current.get(key); } - // 处理最后一个key + // Handle the final key. String lastKey = keys[keys.length - 1]; String value = param.getParamValue(); - // 根据valueType转换值 + // Convert the value based on valueType. switch (param.getValueType().toLowerCase()) { case "number": try { double doubleValue = Double.parseDouble(value); - // 如果数值是整数形式,则转换为Integer + // Preserve integer-shaped values as Integer. if (doubleValue == (int) doubleValue) { current.put(lastKey, (int) doubleValue); } else { @@ -289,7 +289,7 @@ public class ConfigServiceImpl implements ConfigService { current.put(lastKey, Boolean.parseBoolean(value)); break; case "array": - // 将分号分隔的字符串转换为数字数组 + // Convert semicolon-delimited strings into arrays. List list = new ArrayList<>(); for (String num : value.split(";")) { if (StringUtils.isNotBlank(num)) { @@ -314,26 +314,26 @@ public class ConfigServiceImpl implements ConfigService { } /** - * 构建声纹配置信息 + * Build voiceprint configuration. * - * @param agentId 智能体ID - * @param result 结果Map + * @param agentId agent ID + * @param result result map */ private void buildVoiceprintConfig(String agentId, Map result) { try { - // 获取声纹接口地址 + // Voiceprint API endpoint. String voiceprintUrl = sysParamsService.getValue(Constant.SERVER_VOICE_PRINT, true); if (StringUtils.isBlank(voiceprintUrl) || "null".equals(voiceprintUrl)) { return; } - // 获取智能体关联的声纹信息(不需要用户权限验证) + // Voiceprints linked to the agent without user-permission checks. List voiceprints = getVoiceprintsByAgentId(agentId); if (voiceprints == null || voiceprints.isEmpty()) { return; } - // 构建speakers列表 + // Build the `speakers` list. List speakers = new ArrayList<>(); for (AgentVoicePrintVO voiceprint : voiceprints) { String speakerStr = String.format("%s,%s,%s", @@ -343,19 +343,19 @@ public class ConfigServiceImpl implements ConfigService { speakers.add(speakerStr); } - // 构建声纹配置 + // Build the final voiceprint config object. Map voiceprintConfig = new HashMap<>(); voiceprintConfig.put("url", voiceprintUrl); voiceprintConfig.put("speakers", speakers); - // 获取声纹识别相似度阈值,默认0.4 + // Voiceprint similarity threshold, default 0.4. String thresholdStr = sysParamsService.getValue("server.voiceprint_similarity_threshold", true); if (StringUtils.isNotBlank(thresholdStr) && !"null".equals(thresholdStr)) { try { double threshold = Double.parseDouble(thresholdStr); voiceprintConfig.put("similarity_threshold", threshold); } catch (NumberFormatException e) { - // 如果解析失败,使用默认值0.4 + // Fall back to 0.4 if parsing fails. voiceprintConfig.put("similarity_threshold", 0.4); } } else { @@ -364,16 +364,16 @@ public class ConfigServiceImpl implements ConfigService { result.put("voiceprint", voiceprintConfig); } catch (Exception e) { - // 声纹配置获取失败时不影响其他功能 - System.err.println("获取声纹配置失败: " + e.getMessage()); + // Voiceprint config failures should not break other features. + System.err.println("Failed to load voiceprint config: " + e.getMessage()); } } /** - * 获取智能体关联的声纹信息 + * Get the voiceprints linked to an agent. * - * @param agentId 智能体ID - * @return 声纹信息列表 + * @param agentId agent ID + * @return voiceprint list */ private List getVoiceprintsByAgentId(String agentId) { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); @@ -384,19 +384,19 @@ public class ConfigServiceImpl implements ConfigService { } /** - * 构建模块配置 + * Build module configuration. * - * @param prompt 提示词 - * @param voice 音色 - * @param referenceAudio 参考音频路径 - * @param referenceText 参考文本 - * @param vadModelId VAD模型ID - * @param asrModelId ASR模型ID - * @param llmModelId LLM模型ID - * @param ttsModelId TTS模型ID - * @param memModelId 记忆模型ID - * @param intentModelId 意图模型ID - * @param result 结果Map + * @param prompt prompt text + * @param voice voice ID + * @param referenceAudio reference-audio path + * @param referenceText reference text + * @param vadModelId VAD model ID + * @param asrModelId ASR model ID + * @param llmModelId LLM model ID + * @param ttsModelId TTS model ID + * @param memModelId memory model ID + * @param intentModelId intent model ID + * @param result result map */ private void buildModuleConfig( String assistantName, @@ -432,7 +432,7 @@ public class ConfigServiceImpl implements ConfigService { if (modelIds[i] == null) { continue; } - // 关键:第三个参数传false,确保获取原始密钥 + // Important: pass `false` so we fetch the raw unmasked secret values. ModelConfigEntity model = modelConfigService.getModelByIdFromCache(modelIds[i]); if (model == null) { continue; @@ -440,7 +440,7 @@ public class ConfigServiceImpl implements ConfigService { Map typeConfig = new HashMap<>(); if (model.getConfigJson() != null) { typeConfig.put(model.getId(), model.getConfigJson()); - // 如果是TTS类型,添加private_voice属性 + // For TTS, inject private-voice and related runtime fields. if ("TTS".equals(modelTypes[i])) { if (voice != null) ((Map) model.getConfigJson()).put("private_voice", voice); @@ -457,7 +457,6 @@ public class ConfigServiceImpl implements ConfigService { if (ttsPitch != null) ((Map) model.getConfigJson()).put("ttsPitch", ttsPitch); - // 火山引擎声音克隆需要替换resource_id Map map = (Map) model.getConfigJson(); if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(map.get("type"))) { // 如果voice是”S_”开头的,使用seed-icl-1.0 @@ -466,7 +465,7 @@ public class ConfigServiceImpl implements ConfigService { } } } - // 如果是Intent类型,且type=intent_llm,则给他添加附加模型 + // For Intent with `intent_llm`, attach its backing LLM model. if ("Intent".equals(modelTypes[i])) { Map map = (Map) model.getConfigJson(); if ("intent_llm".equals(map.get("type"))) { @@ -494,18 +493,16 @@ public class ConfigServiceImpl implements ConfigService { } } } - // 如果是LLM类型,且intentLLMModelId不为空,则添加附加模型 + // For LLM, include any linked helper LLM models when needed. if ("LLM".equals(modelTypes[i])) { if (StringUtils.isNotBlank(intentLLMModelId)) { if (!typeConfig.containsKey(intentLLMModelId)) { - // 修改这里:添加isMaskSensitive=false参数 ModelConfigEntity intentLLM = modelConfigService.getModelByIdFromCache(intentLLMModelId); typeConfig.put(intentLLM.getId(), intentLLM.getConfigJson()); } } if (StringUtils.isNotBlank(memLocalShortLLMModelId)) { if (!typeConfig.containsKey(memLocalShortLLMModelId)) { - // 修改这里:添加isMaskSensitive=false参数 ModelConfigEntity memLocalShortLLM = modelConfigService .getModelByIdFromCache(memLocalShortLLMModelId); typeConfig.put(memLocalShortLLM.getId(), memLocalShortLLM.getConfigJson()); @@ -529,7 +526,7 @@ public class ConfigServiceImpl implements ConfigService { result.put("selected_module", selectedModule); if (StringUtils.isNotBlank(prompt)) { - prompt = prompt.replace("{{assistant_name}}", StringUtils.isBlank(assistantName) ? "小智" : assistantName); + prompt = prompt.replace("{{assistant_name}}", StringUtils.isBlank(assistantName) ? "Xiaozhi" : assistantName); } result.put("prompt", prompt); result.put("summaryMemory", summaryMemory); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index 629ba80f8..c3df96c29 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -32,7 +32,7 @@ import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.service.SysParamsService; -@Tag(name = "设备管理") +@Tag(name = "Device Management") @RestController @RequestMapping("/device") public class DeviceController { @@ -47,7 +47,7 @@ public class DeviceController { } @PostMapping("/bind/{agentId}/{deviceCode}") - @Operation(summary = "绑定设备") + @Operation(summary = "Bind device") @RequiresPermissions("sys:role:normal") public Result bindDevice(@PathVariable String agentId, @PathVariable String deviceCode) { deviceService.deviceActivation(agentId, deviceCode); @@ -55,13 +55,13 @@ public class DeviceController { } @PostMapping("/register") - @Operation(summary = "注册设备") + @Operation(summary = "Register device") public Result registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) { String macAddress = deviceRegisterDTO.getMacAddress(); if (StringUtils.isBlank(macAddress)) { return new Result().error(ErrorCode.MCA_NOT_NULL); } - // 生成六位验证码 + // Generate a six-digit verification code. String code; String key; String existsMac = null; @@ -76,7 +76,7 @@ public class DeviceController { } @GetMapping("/bind/{agentId}") - @Operation(summary = "获取已绑定设备") + @Operation(summary = "Get bound devices") @RequiresPermissions("sys:role:normal") public Result> getUserDevices(@PathVariable String agentId) { UserDetail user = SecurityUser.getUser(); @@ -85,18 +85,18 @@ public class DeviceController { } @PostMapping("/bind/{agentId}") - @Operation(summary = "设备在线接口") + @Operation(summary = "Device online endpoint") @RequiresPermissions("sys:role:normal") public Result forwardToMqttGateway(@PathVariable String agentId, @RequestBody String requestBody) { try { return new Result().ok(deviceService.getDeviceOnlineData(agentId)); } catch (Exception e) { - return new Result().error("转发请求失败: " + e.getMessage()); + return new Result().error("Failed to forward request: " + e.getMessage()); } } @PostMapping("/unbind") - @Operation(summary = "解绑设备") + @Operation(summary = "Unbind device") @RequiresPermissions("sys:role:normal") public Result unbindDevice(@RequestBody DeviceUnBindDTO unDeviveBind) { UserDetail user = SecurityUser.getUser(); @@ -105,16 +105,16 @@ public class DeviceController { } @PutMapping("/update/{id}") - @Operation(summary = "更新设备信息") + @Operation(summary = "Update device information") @RequiresPermissions("sys:role:normal") public Result updateDeviceInfo(@PathVariable String id, @Valid @RequestBody DeviceUpdateDTO deviceUpdateDTO) { DeviceEntity entity = deviceService.selectById(id); if (entity == null) { - return new Result().error("设备不存在"); + return new Result().error("Device does not exist"); } UserDetail user = SecurityUser.getUser(); if (!entity.getUserId().equals(user.getId())) { - return new Result().error("设备不存在"); + return new Result().error("Device does not exist"); } BeanUtils.copyProperties(deviceUpdateDTO, entity); deviceService.updateById(entity); @@ -122,7 +122,7 @@ public class DeviceController { } @PostMapping("/manual-add") - @Operation(summary = "手动添加设备") + @Operation(summary = "Manually add device") @RequiresPermissions("sys:role:normal") public Result manualAddDevice(@RequestBody @Valid DeviceManualAddDTO dto) { UserDetail user = SecurityUser.getUser(); @@ -131,7 +131,7 @@ public class DeviceController { } @PostMapping("/tools/list/{deviceId}") - @Operation(summary = "获取设备工具列表") + @Operation(summary = "Get device tools") @RequiresPermissions("sys:role:normal") public Result getDeviceTools(@PathVariable String deviceId) { Object toolsData = deviceService.getDeviceTools(deviceId); @@ -143,7 +143,7 @@ public class DeviceController { } @PostMapping("/tools/call/{deviceId}") - @Operation(summary = "调用设备工具") + @Operation(summary = "Call device tool") @RequiresPermissions("sys:role:normal") public Result callDeviceTool(@PathVariable String deviceId, @Valid @RequestBody DeviceToolsCallReqDTO request) { @@ -159,4 +159,4 @@ public class DeviceController { response.setMsg("Tools called successfully"); return response.ok(result); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java index 4a4bfee89..448985402 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java @@ -30,7 +30,7 @@ import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.sys.service.SysParamsService; -@Tag(name = "设备管理", description = "OTA 相关接口") +@Tag(name = "Device Management", description = "OTA related interfaces") @Slf4j @RestController @RequiredArgsConstructor @@ -39,12 +39,12 @@ public class OTAController { private final DeviceService deviceService; private final SysParamsService sysParamsService; - @Operation(summary = "OTA版本和设备激活状态检查") + @Operation(summary = "OTA version and device activation status check") @PostMapping public ResponseEntity checkOTAVersion( @RequestBody DeviceReportReqDTO deviceReportReqDTO, - @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, - @Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) { + @Parameter(name = "Device-Id", description = "Device unique identifier", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, + @Parameter(name = "Client-Id", description = "Client identifier", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) { if (StringUtils.isBlank(deviceId)) { return createResponse(DeviceReportRespDTO.createError("Device ID is required")); } @@ -52,18 +52,18 @@ public class OTAController { clientId = deviceId; } boolean macAddressValid = isMacAddressValid(deviceId); - // 设备Id和Mac地址应是一致的, 并且必须需要application字段 + // Device ID and MAC address should be consistent, and application field is required if (!macAddressValid) { return createResponse(DeviceReportRespDTO.createError("Invalid device ID")); } return createResponse(deviceService.checkDeviceActive(deviceId, clientId, deviceReportReqDTO)); } - @Operation(summary = "设备快速检查激活状态") + @Operation(summary = "Quick device activation status check") @PostMapping("activate") public ResponseEntity activateDevice( - @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, - @Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) { + @Parameter(name = "Device-Id", description = "Device unique identifier", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, + @Parameter(name = "Client-Id", description = "Client identifier", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) { if (StringUtils.isBlank(deviceId)) { return ResponseEntity.status(202).build(); } @@ -79,17 +79,17 @@ public class OTAController { public ResponseEntity getOTA() { String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false); if (StringUtils.isBlank(mqttUdpConfig)) { - return ResponseEntity.ok("OTA接口不正常,缺少mqtt_gateway地址,请登录智控台,在参数管理找到【server.mqtt_gateway】配置"); + return ResponseEntity.ok("OTA interface abnormal, missing mqtt_gateway address, please login to control panel and configure [server.mqtt_gateway] in parameter management"); } String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { - return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置"); + return ResponseEntity.ok("OTA interface abnormal, missing websocket address, please login to control panel and configure [server.websocket] in parameter management"); } String otaUrl = sysParamsService.getValue(Constant.SERVER_OTA, true); if (StringUtils.isBlank(otaUrl) || otaUrl.equals("null")) { - return ResponseEntity.ok("OTA接口不正常,缺少ota地址,请登录智控台,在参数管理找到【server.ota】配置"); + return ResponseEntity.ok("OTA interface abnormal, missing ota address, please login to control panel and configure [server.ota] in parameter management"); } - return ResponseEntity.ok("OTA接口运行正常,websocket集群数量:" + wsUrl.split(";").length); + return ResponseEntity.ok("OTA interface running normally, websocket cluster count: " + wsUrl.split(";").length); } @SneakyThrows @@ -106,7 +106,7 @@ public class OTAController { } /** - * 简单判断mac地址是否有效(非严格) + * Simple MAC address validation (non-strict) * * @param macAddress * @return @@ -115,7 +115,7 @@ public class OTAController { if (StringUtils.isBlank(macAddress)) { return false; } - // MAC地址通常为12位十六进制数字,可以包含冒号或连字符分隔符 + // MAC address is typically 12 hexadecimal digits, can contain colon or hyphen separators String macPattern = "^([0-9A-Za-z]{2}[:-]){5}([0-9A-Za-z]{2})$"; return macAddress.matches(macPattern); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java index cfdf3913a..2bd98efc6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java @@ -50,7 +50,7 @@ import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.enums.SuperAdminEnum; import xiaozhi.modules.sys.service.SysParamsService; -@Tag(name = "固件升级管理", description = "OTA 相关接口") +@Tag(name = "Firmware Upgrade Management", description = "OTA-related endpoints") @Slf4j @RestController @RequiredArgsConstructor @@ -62,10 +62,10 @@ public class OTAMagController { private final SysParamsService sysParamsService; @GetMapping - @Operation(summary = "分页查询 OTA 固件信息") + @Operation(summary = "List OTA firmware with pagination") @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) }) @RequiresPermissions("sys:role:superAdmin") public Result> page(@Parameter(hidden = true) @RequestParam Map params) { @@ -75,7 +75,7 @@ public class OTAMagController { } @GetMapping("{id}") - @Operation(summary = "信息 OTA 固件信息") + @Operation(summary = "Get OTA firmware details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") String id) { OtaEntity data = otaService.selectById(id); @@ -83,20 +83,20 @@ public class OTAMagController { } @PostMapping - @Operation(summary = "保存 OTA 固件信息") + @Operation(summary = "Save OTA firmware") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody OtaEntity entity) { if (entity == null) { - return new Result().error("固件信息不能为空"); + return new Result().error("Firmware data cannot be empty"); } if (StringUtils.isBlank(entity.getFirmwareName())) { - return new Result().error("固件名称不能为空"); + return new Result().error("Firmware name cannot be empty"); } if (StringUtils.isBlank(entity.getType())) { - return new Result().error("固件类型不能为空"); + return new Result().error("Firmware type cannot be empty"); } if (StringUtils.isBlank(entity.getVersion())) { - return new Result().error("版本号不能为空"); + return new Result().error("Version cannot be empty"); } try { otaService.save(entity); @@ -107,22 +107,22 @@ public class OTAMagController { } @DeleteMapping("/{id}") - @Operation(summary = "OTA 删除") + @Operation(summary = "Delete OTA firmware") @RequiresPermissions("sys:role:superAdmin") public Result delete(@PathVariable("id") String[] ids) { if (ids == null || ids.length == 0) { - return new Result().error("删除的固件ID不能为空"); + return new Result().error("Firmware IDs to delete cannot be empty"); } otaService.delete(ids); return new Result(); } @PutMapping("/{id}") - @Operation(summary = "修改 OTA 固件信息") + @Operation(summary = "Update OTA firmware") @RequiresPermissions("sys:role:superAdmin") public Result update(@PathVariable("id") String id, @RequestBody OtaEntity entity) { if (entity == null) { - return new Result<>().error("固件信息不能为空"); + return new Result<>().error("Firmware data cannot be empty"); } entity.setId(id); try { @@ -134,7 +134,7 @@ public class OTAMagController { } @GetMapping("/getDownloadUrl/{id}") - @Operation(summary = "获取 OTA 固件下载链接") + @Operation(summary = "Get OTA firmware download link") @RequiresPermissions("sys:role:superAdmin") public Result getDownloadUrl(@PathVariable("id") String id) { String uuid = UUID.randomUUID().toString(); @@ -143,18 +143,18 @@ public class OTAMagController { } @GetMapping("/download/{uuid}") - @Operation(summary = "下载固件文件") + @Operation(summary = "Download firmware file") public ResponseEntity downloadFirmware(@PathVariable("uuid") String uuid) { String id = (String) redisUtils.get(RedisKeys.getOtaIdKey(uuid)); if (StringUtils.isBlank(id)) { return ResponseEntity.notFound().build(); } - // 检查下载次数 + // Check the download count. String downloadCountKey = RedisKeys.getOtaDownloadCountKey(uuid); Integer downloadCount = (Integer) Optional.ofNullable(redisUtils.get(downloadCountKey)).orElse(0); - // 如果下载次数超过3次,返回404 + // Return 404 after three downloads. if (downloadCount >= 3) { redisUtils.delete(List.of(downloadCountKey, RedisKeys.getOtaIdKey(uuid))); logger.warn("Download limit exceeded for UUID: {}", uuid); @@ -164,7 +164,7 @@ public class OTAMagController { redisUtils.set(downloadCountKey, downloadCount + 1); try { - // 获取固件信息 + // Load firmware information. OtaEntity otaEntity = null; if (id.indexOf("file:") == 0) { id = id.substring(5); @@ -181,16 +181,16 @@ public class OTAMagController { return ResponseEntity.notFound().build(); } - // 获取文件路径 - 确保路径是绝对路径或正确的相对路径 + // Resolve the firmware path, handling both absolute and relative paths. String firmwarePath = otaEntity.getFirmwarePath(); String originalFilename = otaEntity.getType() + "_" + otaEntity.getVersion(); Path path; - // 检查是否是绝对路径 + // Check whether the path is absolute. if (Paths.get(firmwarePath).isAbsolute()) { path = Paths.get(firmwarePath); } else { - // 如果是相对路径,则从当前工作目录解析 + // Resolve relative paths from the current working directory. path = Paths.get(System.getProperty("user.dir"), firmwarePath); } @@ -198,7 +198,7 @@ public class OTAMagController { id, firmwarePath, path.toAbsolutePath()); if (!Files.exists(path) || !Files.isRegularFile(path)) { - // 尝试直接从firmware目录下查找文件名 + // Fall back to searching by file name under the firmware directory. String fileName = new File(firmwarePath).getName(); Path altPath = Paths.get(System.getProperty("user.dir"), "firmware", fileName); @@ -213,17 +213,17 @@ public class OTAMagController { } } - // 读取文件内容 + // Read the file contents. byte[] fileContent = Files.readAllBytes(path); - // 设置响应头 + // Set response headers. if (firmwarePath.contains(".")) { String extension = firmwarePath.substring(firmwarePath.lastIndexOf(".")); originalFilename += extension; } - // 清理文件名,移除不安全字符 + // Sanitize the file name by removing unsafe characters. String safeFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_"); logger.info("Providing download for firmware ID: {}, filename: {}, size: {} bytes", @@ -243,58 +243,58 @@ public class OTAMagController { } @PostMapping("/upload") - @Operation(summary = "上传固件文件") + @Operation(summary = "Upload firmware file") @RequiresPermissions("sys:role:superAdmin") public Result uploadFirmware(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { - return new Result().error("上传文件不能为空"); + return new Result().error("Uploaded file cannot be empty"); } - // 检查文件扩展名 + // Validate the file extension. String originalFilename = file.getOriginalFilename(); if (originalFilename == null) { - return new Result().error("文件名不能为空"); + return new Result().error("File name cannot be empty"); } String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); if (!extension.equals(".bin") && !extension.equals(".apk")) { - return new Result().error("只允许上传.bin和.apk格式的文件"); + return new Result().error("Only .bin and .apk files are allowed"); } try { - // 计算文件的MD5值 + // Compute the file MD5 hash. String md5 = calculateMD5(file); - // 设置存储路径 + // Prepare the upload path. String uploadDir = "uploadfile"; Path uploadPath = Paths.get(uploadDir); - // 如果目录不存在,创建目录 + // Create the directory if it does not exist. if (!Files.exists(uploadPath)) { Files.createDirectories(uploadPath); } - // 使用MD5作为文件名,固定使用.bin扩展名 + // Use the MD5 as the file name and keep the original extension. String uniqueFileName = md5 + extension; Path filePath = uploadPath.resolve(uniqueFileName); - // 检查文件是否已存在 + // Reuse the existing file if it was already uploaded. if (Files.exists(filePath)) { return new Result().ok(filePath.toString()); } - // 保存文件 + // Save the file. Files.copy(file.getInputStream(), filePath); - // 返回文件路径 + // Return the file path. return new Result().ok(filePath.toString()); } catch (IOException | NoSuchAlgorithmException e) { - return new Result().error("文件上传失败:" + e.getMessage()); + return new Result().error("File upload failed: " + e.getMessage()); } } @PostMapping("/uploadAssetsBin") - @Operation(summary = "上传资源固件文件") + @Operation(summary = "Upload asset firmware file") @RequiresPermissions("sys:role:normal") public Result uploadAssetsBin(@RequestParam("file") MultipartFile file) { String otaUrl = sysParamsService.getValue(Constant.SERVER_OTA, true); @@ -302,24 +302,24 @@ public class OTAMagController { return new Result().error(ErrorCode.OTA_URL_EMPTY); } logger.info("username:{},uploadAssetsBin size: {}", SecurityUser.getUser().getUsername(), file.getSize()); - // 验证文件大小 (资源固件最大20MB) + // Validate file size, capped at 20 MB for asset firmware. if (file.getSize() > 20 * 1024 * 1024) { return new Result().error(ErrorCode.VOICE_CLONE_AUDIO_TOO_LARGE); } - // 普通用户只能每天上传50次 + // Non-admin users can upload at most 50 times per day. if (SecurityUser.getUser().getSuperAdmin() == SuperAdminEnum.NO.value()) { String uploadCountKey = RedisKeys.getOtaUploadCountKey(SecurityUser.getUser().getId()); Integer uploadCount = (Integer) Optional.ofNullable(redisUtils.get(uploadCountKey)).orElse(0); if (uploadCount >= 50) { return new Result().error(ErrorCode.OTA_UPLOAD_COUNT_EXCEED); } - // 增加上传次数 + // Increment the daily upload count. redisUtils.increment(RedisKeys.getOtaUploadCountKey(SecurityUser.getUser().getId()), RedisUtils.DEFAULT_EXPIRE); } Result result = uploadFirmware(file); - // 生成资源文件路径 + // Build the asset download URL. if (StringUtils.isNotBlank(result.getData())) { String uuid = UUID.randomUUID().toString(); redisUtils.set(RedisKeys.getOtaIdKey(uuid), "file:" + result.getData()); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java index f3fdb7a3e..cf8d0bf46 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java @@ -11,9 +11,9 @@ import xiaozhi.modules.device.entity.DeviceEntity; @Mapper public interface DeviceDao extends BaseMapper { /** - * 获取此智能体全部设备的最后连接时间 + * Get last connection time for all devices of this agent * - * @param agentId 智能体id + * @param agentId Agent id * @return */ Date getAllLastConnectedAtByAgentId(String agentId); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java index 975f69be1..4afcb40cb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java @@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import xiaozhi.modules.device.entity.OtaEntity; /** - * OTA固件管理 + * OTA firmware management */ @Mapper public interface OtaDao extends BaseMapper { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceBindDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceBindDTO.java index 3413c31b4..e902cc7ee 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceBindDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceBindDTO.java @@ -5,23 +5,23 @@ import lombok.AllArgsConstructor; import lombok.Data; /** - * 设备绑定的DTO + * Device binding DTO * * @author zjy * @since 2025-3-28 */ @Data @AllArgsConstructor -@Schema(description = "设备连接头信息") +@Schema(description = "Device connection header information") public class DeviceBindDTO { - @Schema(description = "mac地址") + @Schema(description = "MAC address") private String macAddress; - @Schema(description = "所属用户id") + @Schema(description = "Associated user ID") private Long userId; - @Schema(description = "智能体id") + @Schema(description = "Agent ID") private String agentId; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceManualAddDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceManualAddDTO.java index 369726b00..082c95b8f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceManualAddDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceManualAddDTO.java @@ -5,7 +5,7 @@ import lombok.Data; @Data public class DeviceManualAddDTO { private String agentId; - private String board; // 设备型号 - private String appVersion; // 固件版本 - private String macAddress; // Mac地址 + private String board; // Device model + private String appVersion; // Firmware version + private String macAddress; // MAC address } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java index 26bccbfd1..656024b73 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java @@ -5,23 +5,23 @@ import jakarta.validation.constraints.Min; import lombok.Data; /** - * 查询所有设备的DTO + * DTO for querying all devices * * @author zjy * @since 2025-3-21 */ @Data -@Schema(description = "查询所有设备的DTO") +@Schema(description = "DTO for querying all devices") public class DevicePageUserDTO { - @Schema(description = "设备关键词") + @Schema(description = "Device keyword") private String keywords; - @Schema(description = "页数") + @Schema(description = "Page number") @Min(value = 0, message = "{page.number}") private String page; - @Schema(description = "显示列数") + @Schema(description = "Number of items per page") @Min(value = 0, message = "{limit.number}") private String limit; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java index ce37c517a..f76360c76 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java @@ -7,17 +7,17 @@ import lombok.Getter; import lombok.Setter; /** - * 设备注册头信息 + * Device registration header information * * @author zjy * @since 2025-3-28 */ @Setter @Getter -@Schema(description = "设备注册头信息") +@Schema(description = "Device registration header information") public class DeviceRegisterDTO implements Serializable { - @Schema(description = "mac地址") + @Schema(description = "MAC address") private String macAddress; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportReqDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportReqDTO.java index fec5a297c..bea0d79c8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportReqDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportReqDTO.java @@ -10,139 +10,139 @@ import java.util.List; @Setter @Getter -@Schema(description = "设备固件信息上报求请求体") +@Schema(description = "Device firmware information report request body") public class DeviceReportReqDTO implements Serializable { private static final long serialVersionUID = 1L; - // region 实体属性 - @Schema(description = "板子固件版本号") + // region Entity properties + @Schema(description = "Board firmware version") private Integer version; - @Schema(description = "闪存大小(单位:字节)") + @Schema(description = "Flash size (unit: bytes)") @JsonProperty("flash_size") private Integer flashSize; - @Schema(description = "最小空闲堆内存(字节)") + @Schema(description = "Minimum free heap memory (bytes)") @JsonProperty("minimum_free_heap_size") private Integer minimumFreeHeapSize; - @Schema(description = "设备 MAC 地址") + @Schema(description = "Device MAC address") @JsonProperty("mac_address") private String macAddress; - @Schema(description = "设备唯一标识 UUID") + @Schema(description = "Device unique identifier UUID") private String uuid; - @Schema(description = "芯片型号名称") + @Schema(description = "Chip model name") @JsonProperty("chip_model_name") private String chipModelName; - @Schema(description = "芯片详细信息") + @Schema(description = "Chip detailed information") @JsonProperty("chip_info") private ChipInfo chipInfo; - @Schema(description = "应用程序信息") + @Schema(description = "Application information") private Application application; - @Schema(description = "分区表列表") + @Schema(description = "Partition table list") @JsonProperty("partition_table") private List partitionTable; - @Schema(description = "当前运行的 OTA 分区信息") + @Schema(description = "Currently running OTA partition information") private OtaInfo ota; - @Schema(description = "板子配置信息") + @Schema(description = "Board configuration information") private BoardInfo board; // endregion @Getter @Setter - @Schema(description = "芯片信息") + @Schema(description = "Chip information") public static class ChipInfo { - @Schema(description = "芯片模型代码") + @Schema(description = "Chip model code") private Integer model; - @Schema(description = "核心数") + @Schema(description = "Number of cores") private Integer cores; - @Schema(description = "硬件修订版本") + @Schema(description = "Hardware revision version") private Integer revision; - @Schema(description = "芯片功能标志位") + @Schema(description = "Chip feature flags") private Integer features; } @Getter @Setter - @Schema(description = "板子编译信息") + @Schema(description = "Board compilation information") public static class Application { - @Schema(description = "名称") + @Schema(description = "Name") private String name; - @Schema(description = "应用版本号") + @Schema(description = "Application version number") private String version; - @Schema(description = "编译时间(UTC ISO格式)") + @Schema(description = "Compilation time (UTC ISO format)") @JsonProperty("compile_time") private String compileTime; - @Schema(description = "ESP-IDF 版本号") + @Schema(description = "ESP-IDF version number") @JsonProperty("idf_version") private String idfVersion; - @Schema(description = "ELF 文件 SHA256 校验") + @Schema(description = "ELF file SHA256 checksum") @JsonProperty("elf_sha256") private String elfSha256; } @Getter @Setter - @Schema(description = "分区信息") + @Schema(description = "Partition information") public static class Partition { - @Schema(description = "分区标签名") + @Schema(description = "Partition label name") private String label; - @Schema(description = "分区类型") + @Schema(description = "Partition type") private Integer type; - @Schema(description = "子类型") + @Schema(description = "Subtype") private Integer subtype; - @Schema(description = "起始地址") + @Schema(description = "Start address") private Integer address; - @Schema(description = "分区大小") + @Schema(description = "Partition size") private Integer size; } @Getter @Setter - @Schema(description = "OTA信息") + @Schema(description = "OTA information") public static class OtaInfo { - @Schema(description = "当前OTA标签") + @Schema(description = "Current OTA label") private String label; } @Getter @Setter - @Schema(description = "板子连接和网络信息") + @Schema(description = "Board connection and network information") public static class BoardInfo { - @Schema(description = "板子类型") + @Schema(description = "Board type") private String type; - @Schema(description = "连接的 Wi-Fi SSID") + @Schema(description = "Connected Wi-Fi SSID") private String ssid; - @Schema(description = "Wi-Fi 信号强度(RSSI)") + @Schema(description = "Wi-Fi signal strength (RSSI)") private Integer rssi; - @Schema(description = "Wi-Fi 信道") + @Schema(description = "Wi-Fi channel") private Integer channel; - @Schema(description = "IP 地址") + @Schema(description = "IP address") private String ip; - @Schema(description = "MAC 地址") + @Schema(description = "MAC address") private String mac; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index 85c8972af..5cd150e3a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -6,32 +6,32 @@ import lombok.Getter; import lombok.Setter; @Data -@Schema(description = "设备OTA检测版本返回体,包含激活码要求") +@Schema(description = "Device OTA version-check response, including activation requirements") public class DeviceReportRespDTO { - @Schema(description = "服务器时间") + @Schema(description = "Server time") private ServerTime server_time; - @Schema(description = "激活码") + @Schema(description = "Activation data") private Activation activation; - @Schema(description = "错误信息") + @Schema(description = "Error message") private String error; - @Schema(description = "固件版本信息") + @Schema(description = "Firmware information") private Firmware firmware; - @Schema(description = "WebSocket配置") + @Schema(description = "WebSocket configuration") private Websocket websocket; - @Schema(description = "MQTT Gateway配置") + @Schema(description = "MQTT gateway configuration") private MQTT mqtt; @Getter @Setter public static class Firmware { - @Schema(description = "版本号") + @Schema(description = "Version") private String version; - @Schema(description = "下载地址") + @Schema(description = "Download URL") private String url; } @@ -44,52 +44,52 @@ public class DeviceReportRespDTO { @Setter @Getter public static class Activation { - @Schema(description = "激活码") + @Schema(description = "Activation code") private String code; - @Schema(description = "激活码信息: 激活地址") + @Schema(description = "Activation message, usually the activation URL") private String message; - @Schema(description = "挑战码") + @Schema(description = "Challenge code") private String challenge; } @Getter @Setter public static class ServerTime { - @Schema(description = "时间戳") + @Schema(description = "Timestamp") private Long timestamp; - @Schema(description = "时区") + @Schema(description = "Time zone") private String timeZone; - @Schema(description = "时区偏移量,单位为分钟") + @Schema(description = "Time-zone offset in minutes") private Integer timezone_offset; } @Getter @Setter public static class Websocket { - @Schema(description = "WebSocket服务器地址") + @Schema(description = "WebSocket server URL") private String url; - @Schema(description = "WebSocket 认证 token") + @Schema(description = "WebSocket authentication token") private String token; } @Getter @Setter public static class MQTT { - @Schema(description = "MQTT 配置网址") + @Schema(description = "MQTT endpoint URL") private String endpoint; - @Schema(description = "MQTT 客户端唯一标识符") + @Schema(description = "Unique MQTT client identifier") private String client_id; - @Schema(description = "MQTT 认证用户名") + @Schema(description = "MQTT authentication username") private String username; - @Schema(description = "MQTT 认证密码") + @Schema(description = "MQTT authentication password") private String password; - @Schema(description = "ESP32 发布消息的主题") + @Schema(description = "Topic published by ESP32") private String publish_topic; - @Schema(description = "ESP32 订阅的主题") + @Schema(description = "Topic subscribed to by ESP32") private String subscribe_topic; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceToolsCallReqDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceToolsCallReqDTO.java index 777bee03e..3bf1cf59d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceToolsCallReqDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceToolsCallReqDTO.java @@ -8,8 +8,8 @@ import lombok.Data; @Data public class DeviceToolsCallReqDTO { - @NotBlank(message = "工具名称不能为空") + @NotBlank(message = "Tool name cannot be empty") private String name; private Map arguments; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java index f18df5d4e..8f4a30b5f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java @@ -7,14 +7,14 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 设备解绑表单 + * Device unbind form */ @Data -@Schema(description = "设备解绑表单") +@Schema(description = "Device unbind form") public class DeviceUnBindDTO implements Serializable { - @Schema(description = "设备ID") - @NotBlank(message = "设备ID不能为空") + @Schema(description = "Device ID") + @NotBlank(message = "Device ID cannot be empty") private String deviceId; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUpdateDTO.java index 2e9a47936..6bd5e1fa1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUpdateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUpdateDTO.java @@ -8,19 +8,19 @@ import lombok.Data; import java.io.Serializable; /** - * 设备更新DTO + * Device update DTO */ @Data public class DeviceUpdateDTO implements Serializable { /** - * 自动更新状态 + * Auto update status */ @Max(1) @Min(0) private Integer autoUpdate; /** - * 设备别名 + * Device alias */ @Size(max = 64) private String alias; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java index 8ebdf9344..ca284e057 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java @@ -15,53 +15,53 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("ai_device") -@Schema(description = "设备信息") +@Schema(description = "Device information") public class DeviceEntity { @TableId(type = IdType.ASSIGN_UUID) @Schema(description = "ID") private String id; - @Schema(description = "关联用户ID") + @Schema(description = "Associated user ID") private Long userId; - @Schema(description = "MAC地址") + @Schema(description = "MAC address") private String macAddress; - @Schema(description = "最后连接时间") + @Schema(description = "Last connection time") private Date lastConnectedAt; - @Schema(description = "自动更新开关(0关闭/1开启)") + @Schema(description = "Auto update switch (0 off/1 on)") private Integer autoUpdate; - @Schema(description = "设备硬件型号") + @Schema(description = "Device hardware model") private String board; - @Schema(description = "设备别名") + @Schema(description = "Device alias") private String alias; - @Schema(description = "智能体ID") + @Schema(description = "Agent ID") private String agentId; - @Schema(description = "固件版本号") + @Schema(description = "Firmware version") private String appVersion; - @Schema(description = "排序") + @Schema(description = "Sort") private Integer sort; - @Schema(description = "更新者") + @Schema(description = "Updater") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") @TableField(fill = FieldFill.UPDATE) private Date updateDate; - @Schema(description = "创建者") + @Schema(description = "Creator") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @TableField(fill = FieldFill.INSERT) private Date createDate; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java index b93c608bd..afe1bc25b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java @@ -15,47 +15,47 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("ai_ota") -@Schema(description = "固件信息") +@Schema(description = "Firmware information") public class OtaEntity { @TableId(type = IdType.ASSIGN_UUID) @Schema(description = "ID") private String id; - @Schema(description = "固件名称") + @Schema(description = "Firmware name") private String firmwareName; - @Schema(description = "固件类型") + @Schema(description = "Firmware type") private String type; - @Schema(description = "版本号") + @Schema(description = "Version number") private String version; - @Schema(description = "文件大小(字节)") + @Schema(description = "File size (bytes)") private Long size; - @Schema(description = "备注/说明") + @Schema(description = "Remarks/Description") private String remark; - @Schema(description = "固件路径") + @Schema(description = "Firmware path") private String firmwarePath; - @Schema(description = "排序") + @Schema(description = "Sort order") private Integer sort; - @Schema(description = "更新者") + @Schema(description = "Updater") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") @TableField(fill = FieldFill.UPDATE) private Date updateDate; - @Schema(description = "创建者") + @Schema(description = "Creator") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @TableField(fill = FieldFill.INSERT) private Date createDate; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index ecbf719ca..d85934cfc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -15,122 +15,122 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO; public interface DeviceService extends BaseService { /** - * 获取设备在线数据 + * Get device online data. */ String getDeviceOnlineData(String agentId); /** - * 检查设备是否激活 + * Check whether a device is activated. */ DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId, DeviceReportReqDTO deviceReport); /** - * 获取用户指定智能体的设备列表, + * Get the devices linked to a user's specific agent. */ List getUserDevices(Long userId, String agentId); /** - * 解绑设备 + * Unbind a device. */ void unbindDevice(Long userId, String deviceId); /** - * 设备激活 + * Activate a device. */ Boolean deviceActivation(String agentId, String activationCode); /** - * 删除此用户的所有设备 - * - * @param userId 用户id + * Delete all devices owned by a user. + * + * @param userId user ID */ void deleteByUserId(Long userId); /** - * 删除指定智能体关联的所有设备 - * - * @param agentId 智能体id + * Delete all devices linked to a specific agent. + * + * @param agentId agent ID */ void deleteByAgentId(String agentId); /** - * 获取指定用户的设备数量 - * - * @param userId 用户id - * @return 设备数量 + * Get the number of devices owned by a specific user. + * + * @param userId user ID + * @return device count */ Long selectCountByUserId(Long userId); /** - * 分页获取全部设备信息 + * Get all device information with pagination. * - * @param dto 分页查找参数 - * @return 用户列表分页数据 + * @param dto pagination query parameters + * @return paginated device data */ PageData page(DevicePageUserDTO dto); /** - * 根据MAC地址获取设备信息 - * - * @param macAddress MAC地址 - * @return 设备信息 + * Get device information by MAC address. + * + * @param macAddress MAC address + * @return device information */ DeviceEntity getDeviceByMacAddress(String macAddress); /** - * 根据设备ID获取激活码 - * - * @param deviceId 设备ID - * @return 激活码 + * Get the activation code for a device ID. + * + * @param deviceId device ID + * @return activation code */ String geCodeByDeviceId(String deviceId); /** - * 获取这个智能体设备理的最近的最后连接时间 - * - * @param agentId 智能体id - * @return 返回设备最近的最后连接时间 + * Get the latest connection time across devices linked to an agent. + * + * @param agentId agent ID + * @return most recent connection time */ Date getLatestLastConnectionTime(String agentId); /** - * 手动添加设备 + * Add a device manually. */ void manualAddDevice(Long userId, DeviceManualAddDTO dto); /** - * 更新设备连接信息 + * Update device connection information. */ void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion); /** - * 生成WebSocket认证token + * Generate a WebSocket authentication token. * - * @param clientId 客户端ID - * @param username 用户名(通常为deviceId) - * @return 认证token字符串 - * @throws Exception 生成token时的异常 + * @param clientId client ID + * @param username username, usually the device ID + * @return authentication token string + * @throws Exception exception thrown while generating the token */ String generateWebSocketToken(String clientId, String username) throws Exception; /** - * 根据MAC地址搜索设备 + * Search devices by MAC address. * - * @param macAddress MAC地址关键词 - * @param userId 用户ID - * @return 设备列表 + * @param macAddress MAC-address keyword + * @param userId user ID + * @return device list */ List searchDevicesByMacAddress(String macAddress, Long userId); /** - * 获取设备工具列表 + * Get the list of device tools. */ Object getDeviceTools(String deviceId); /** - * 调用设备工具 + * Invoke a device tool. */ Object callDeviceTool(String deviceId, String toolName, Map arguments); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java index cd35f6ae4..75c9de0c5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java @@ -7,7 +7,7 @@ import xiaozhi.common.service.BaseService; import xiaozhi.modules.device.entity.OtaEntity; /** - * OTA固件管理 + * OTA firmware management */ public interface OtaService extends BaseService { PageData page(Map params); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index adabbd95a..d0289f6ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -95,7 +95,7 @@ public class DeviceServiceImpl extends BaseServiceImpl redisUtils.set(RedisKeys.getAgentDeviceLastConnectedAtById(agentId), new Date()); } } catch (Exception e) { - log.error("异步更新设备连接信息失败", e); + log.error("Failed to update device connection info asynchronously", e); } } @@ -120,7 +120,7 @@ public class DeviceServiceImpl extends BaseServiceImpl if (!activationCode.equals(cachedCode)) { throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR); } - // 检查设备有没有被激活 + // Check whether the device has already been activated. if (selectById(deviceId) != null) { throw new RenException(ErrorCode.DEVICE_ALREADY_ACTIVATED); } @@ -149,51 +149,51 @@ public class DeviceServiceImpl extends BaseServiceImpl deviceEntity.setLastConnectedAt(currentTime); deviceDao.insert(deviceEntity); - // 清理redis缓存、清除智能体设备数量缓存 + // Clear Redis cache entries and the cached agent device count. redisUtils.delete(List.of(cacheDeviceKey, deviceKey, RedisKeys.getAgentDeviceCountById(agentId))); return true; } /** - * 获取设备在线数据 + * Get device online data. */ @Override public String getDeviceOnlineData(String agentId) { - // 从系统参数中获取MQTT网关地址 + // Read the MQTT gateway address from system parameters. String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) { return ""; } - // 构建完整的URL + // Build the full URL. String url = StrUtil.format("http://{}/api/devices/status", mqttGatewayUrl); - // 获取当前用户的设备列表 + // Load the current user's device list. UserDetail user = SecurityUser.getUser(); List devices = getUserDevices(user.getId(), agentId); - // 构建deviceIds数组 + // Build the deviceIds array. Set deviceIds = devices.stream().map(o -> { String macAddress = Optional.ofNullable(o.getMacAddress()).orElse("unknown").replace(":", "_"); String groupId = Optional.ofNullable(o.getBoard()).orElse("GID_default").replace(":", "_"); return StrUtil.format("{}@@@{}@@@{}", groupId, macAddress, macAddress); }).collect(Collectors.toSet()); - // 构建请求入参 + // Build request parameters. Map> params = MapUtil .builder(new HashMap>()) .put("clientIds", deviceIds).build(); if (ToolUtil.isNotEmpty(deviceIds)) { - // 发送请求 + // Send the request. String resultMessage = HttpRequest.post(url) .header(Header.CONTENT_TYPE, ContentType.JSON.getValue()) .header(Header.AUTHORIZATION, "Bearer " + generateBearerToken()) .body(JSONUtil.toJsonStr(params)) - .timeout(10000) // 超时,毫秒 + .timeout(10000) // Timeout in milliseconds. .execute().body(); return resultMessage; } - // 返回响应 + // Return the response body. return ""; } @@ -204,14 +204,15 @@ public class DeviceServiceImpl extends BaseServiceImpl DeviceEntity deviceById = getDeviceByMacAddress(macAddress); - // 设备未绑定,则返回当前上传的固件信息(不更新)以此兼容旧固件版本 + // If the device is not bound, return the uploaded firmware information unchanged + // to stay compatible with older firmware versions. if (deviceById == null) { DeviceReportRespDTO.Firmware firmware = new DeviceReportRespDTO.Firmware(); firmware.setVersion(deviceReport.getApplication().getVersion()); firmware.setUrl(Constant.INVALID_FIRMWARE_URL); response.setFirmware(firmware); } else { - // 只有在设备已绑定且autoUpdate不为0的情况下才返回固件升级信息 + // Only return firmware upgrade information when the device is bound and autoUpdate is enabled. if (deviceById.getAutoUpdate() != 0) { String type = deviceReport.getBoard() == null ? null : deviceReport.getBoard().getType(); DeviceReportRespDTO.Firmware firmware = buildFirmwareInfo(type, @@ -220,20 +221,20 @@ public class DeviceServiceImpl extends BaseServiceImpl } } - // 添加WebSocket配置 + // Add WebSocket configuration. DeviceReportRespDTO.Websocket websocket = new DeviceReportRespDTO.Websocket(); - // 从系统参数获取WebSocket URL,如果未配置则使用默认值 + // Read the WebSocket URL from system parameters and fall back to the default if needed. String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); - // 检查是否启用认证并生成token + // Check whether authentication is enabled and generate a token if needed. String authEnabled = sysParamsService.getValue(Constant.SERVER_AUTH_ENABLED, true); if ("true".equalsIgnoreCase(authEnabled)) { try { - // 生成token + // Generate the token. String token = generateWebSocketToken(clientId, macAddress); websocket.setToken(token); } catch (Exception e) { - log.error("生成WebSocket token失败: {}", e.getMessage()); + log.error("Failed to generate the WebSocket token: {}", e.getMessage()); websocket.setToken(""); } } else { @@ -241,24 +242,24 @@ public class DeviceServiceImpl extends BaseServiceImpl } if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { - log.error("WebSocket地址未配置,请登录智控台,在参数管理找到【server.websocket】配置"); + log.error("WebSocket address is not configured. Set server.websocket in system parameters."); wsUrl = "ws://xiaozhi.server.com:8000/xiaozhi/v1/"; websocket.setUrl(wsUrl); } else { String[] wsUrls = wsUrl.split("\\;"); if (wsUrls.length > 0) { - // 随机选择一个WebSocket URL + // Select a WebSocket URL at random. websocket.setUrl(wsUrls[RandomUtil.randomInt(0, wsUrls.length)]); } else { - log.error("WebSocket地址未配置,请登录智控台,在参数管理找到【server.websocket】配置"); + log.error("WebSocket address is not configured. Set server.websocket in system parameters."); websocket.setUrl("ws://xiaozhi.server.com:8000/xiaozhi/v1/"); } } response.setWebsocket(websocket); - // 添加MQTT UDP配置 - // 从系统参数获取MQTT Gateway地址,仅在配置有效时使用 + // Add MQTT UDP configuration. + // Only use the MQTT gateway address when the system parameter is valid. String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, true); if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty()) { try { @@ -270,19 +271,19 @@ public class DeviceServiceImpl extends BaseServiceImpl response.setMqtt(mqtt); } } catch (Exception e) { - log.error("生成MQTT配置失败: {}", e.getMessage()); + log.error("Failed to build MQTT configuration: {}", e.getMessage()); } } if (deviceById != null) { - // 如果设备存在,则异步更新上次连接时间和版本信息 + // If the device exists, asynchronously update the last connection time and version. String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion() : null; - // 通过Spring代理调用异步方法 + // Invoke the async method through the Spring proxy. ((DeviceServiceImpl) AopContext.currentProxy()).updateDeviceConnectionInfo(deviceById.getAgentId(), deviceById.getId(), appVersion); } else { - // 如果设备不存在,则生成激活码 + // If the device does not exist yet, generate an activation code. DeviceReportRespDTO.Activation code = buildActivation(macAddress, deviceReport); response.setActivation(code); } @@ -300,13 +301,13 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public void unbindDevice(Long userId, String deviceId) { - // 先查询设备信息,获取agentId + // Load the device first so we can clear the agent cache if needed. DeviceEntity device = baseDao.selectById(deviceId); if (device == null) { return; } if (StringUtils.isNotBlank(device.getAgentId())) { - // 清除智能体设备数量缓存 + // Clear the cached agent device count. redisUtils.delete(RedisKeys.getAgentDeviceCountById(device.getAgentId())); } @@ -344,21 +345,21 @@ public class DeviceServiceImpl extends BaseServiceImpl params.put(Constant.LIMIT, dto.getLimit()); IPage page = baseDao.selectPage( getPage(params, "mac_address", true), - // 定义查询条件 + // Define query conditions. new QueryWrapper() - // 必须设备关键词查找 + // Filter by device keyword when provided. .like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords())); - // 循环处理page获取回来的数据,返回需要的字段 + // Transform the paged records to the response fields we need. List list = page.getRecords().stream().map(device -> { UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); - // 把最后修改的时间,改为简短描述的时间 + // Convert the last update time to a short display string. vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate())); sysUserUtilService.assignUsername(device.getUserId(), vo::setBindUserName); vo.setDeviceType(device.getBoard()); return vo; }).toList(); - // 计算页数 + // Return the paged result. return new PageData<>(list, page.getTotal()); } @@ -395,7 +396,7 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public Date getLatestLastConnectionTime(String agentId) { - // 查询是否有缓存时间,有则返回 + // Return the cached timestamp if it already exists. Date cachedDate = (Date) redisUtils.get(RedisKeys.getAgentDeviceLastConnectedAtById(agentId)); if (cachedDate != null) { return cachedDate; @@ -443,11 +444,11 @@ public class DeviceServiceImpl extends BaseServiceImpl dataMap.put("deviceId", deviceId); dataMap.put("activation_code", newCode); - // 写入主数据 key + // Write the primary activation payload key. String dataKey = getDeviceCacheKey(deviceId); redisUtils.set(dataKey, dataMap); - // 写入反查激活码 key + // Write the reverse lookup key for the activation code. String codeKey = RedisKeys.getOtaActivationCode(newCode); redisUtils.set(codeKey, deviceId); } @@ -467,18 +468,18 @@ public class DeviceServiceImpl extends BaseServiceImpl String downloadUrl = null; if (ota != null) { - // 如果设备没有版本信息,或者OTA版本比设备版本新,则返回下载地址 + // Return the download URL when the device has no version info or the OTA version is newer. if (compareVersions(ota.getVersion(), currentVersion) > 0) { String otaUrl = sysParamsService.getValue(Constant.SERVER_OTA, true); if (StringUtils.isBlank(otaUrl) || otaUrl.equals("null")) { - log.error("OTA地址未配置,请登录智控台,在参数管理找到【server.ota】配置"); - // 尝试从请求中获取 + log.error("OTA address is not configured. Set server.ota in system parameters."); + // Try to derive it from the current request. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()) .getRequest(); otaUrl = request.getRequestURL().toString(); } - // 将URL中的/ota/替换为/otaMag/download/ + // Replace /ota/ with /otaMag/download/ in the URL. String uuid = UUID.randomUUID().toString(); redisUtils.set(RedisKeys.getOtaIdKey(uuid), ota.getId()); downloadUrl = otaUrl.replace("/ota/", "/otaMag/download/") + uuid; @@ -491,11 +492,11 @@ public class DeviceServiceImpl extends BaseServiceImpl } /** - * 比较两个版本号 + * Compare two version strings. * - * @param version1 版本1 - * @param version2 版本2 - * @return 如果version1 > version2返回1,version1 < version2返回-1,相等返回0 + * @param version1 version 1 + * @param version2 version 2 + * @return 1 when version1 > version2, -1 when version1 < version2, otherwise 0 */ private static int compareVersions(String version1, String version2) { if (version1 == null || version2 == null) { @@ -521,7 +522,7 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public void manualAddDevice(Long userId, DeviceManualAddDTO dto) { - // 检查mac是否已存在 + // Check whether the MAC address already exists. QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("mac_address", dto.getMacAddress()); DeviceEntity exist = baseDao.selectOne(wrapper); @@ -544,7 +545,7 @@ public class DeviceServiceImpl extends BaseServiceImpl entity.setAutoUpdate(1); baseDao.insert(entity); - // 添加:清除智能体设备数量缓存 + // Clear the cached agent device count after adding the device. redisUtils.delete(RedisKeys.getAgentDeviceCountById(dto.getAgentId())); } @@ -557,11 +558,11 @@ public class DeviceServiceImpl extends BaseServiceImpl } /** - * 生成MQTT密码签名 + * Generate the MQTT password signature. * - * @param content 签名内容 (clientId + '|' + username) - * @param secretKey 密钥 - * @return Base64编码的HMAC-SHA256签名 + * @param content signing content (clientId + '|' + username) + * @param secretKey secret key + * @return Base64-encoded HMAC-SHA256 signature */ private String generatePasswordSignature(String content, String secretKey) throws Exception { Mac hmac = Mac.getInstance("HmacSHA256"); @@ -572,63 +573,64 @@ public class DeviceServiceImpl extends BaseServiceImpl } /** - * 生成WebSocket认证token 遵循Python端AuthManager的实现逻辑:token = signature.timestamp + * Generate a WebSocket authentication token following the Python AuthManager format: + * token = signature.timestamp * - * @param clientId 客户端ID - * @param username 用户名 (通常为deviceId/macAddress) - * @return 认证token字符串 + * @param clientId client ID + * @param username username, usually deviceId/macAddress + * @return authentication token string */ public String generateWebSocketToken(String clientId, String username) throws NoSuchAlgorithmException, InvalidKeyException { - // 从系统参数获取密钥 + // Load the secret from system parameters. String secretKey = sysParamsService.getValue(Constant.SERVER_SECRET, false); if (StringUtils.isBlank(secretKey)) { - throw new IllegalStateException("WebSocket认证密钥未配置(server.secret)"); + throw new IllegalStateException("WebSocket authentication secret is not configured (server.secret)"); } - // 获取当前时间戳(秒) + // Current timestamp in seconds. long timestamp = System.currentTimeMillis() / 1000; - // 构建签名内容: clientId|username|timestamp + // Build signing content: clientId|username|timestamp String content = String.format("%s|%s|%d", clientId, username, timestamp); - // 生成HMAC-SHA256签名 + // Generate the HMAC-SHA256 signature. Mac hmac = Mac.getInstance("HmacSHA256"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); hmac.init(keySpec); byte[] signature = hmac.doFinal(content.getBytes(StandardCharsets.UTF_8)); - // Base64 URL-safe编码签名(去除填充符=) + // Encode the signature as URL-safe Base64 without padding. String signatureBase64 = Base64.getUrlEncoder().withoutPadding().encodeToString(signature); - // 返回格式: signature.timestamp + // Return signature.timestamp return String.format("%s.%d", signatureBase64, timestamp); } /** - * 构建MQTT配置信息 + * Build the MQTT configuration payload. * - * @param macAddress MAC地址 - * @param groupId 分组ID - * @return MQTT配置对象 + * @param macAddress MAC address + * @param groupId group ID + * @return MQTT configuration object */ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String groupId) throws Exception { - // 从环境变量或系统参数获取签名密钥 + // Load the signing key from system parameters. String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", true); if (StringUtils.isBlank(signatureKey)) { - log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成"); + log.warn("MQTT_SIGNATURE_KEY is missing, skipping MQTT configuration generation"); return null; } - // 构建客户端ID格式:groupId@@@macAddress@@@uuid + // Build the client ID using groupId@@@macAddress@@@uuid. String groupIdSafeStr = groupId.replace(":", "_"); String deviceIdSafeStr = macAddress.replace(":", "_"); String mqttClientId = String.format("%s@@@%s@@@%s", groupIdSafeStr, deviceIdSafeStr, deviceIdSafeStr); - // 构建用户数据(包含IP等信息) + // Build user data, including IP information when available. Map userData = new HashMap<>(); - // 尝试获取客户端IP + // Try to read the client IP address. try { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); @@ -641,14 +643,14 @@ public class DeviceServiceImpl extends BaseServiceImpl userData.put("ip", "unknown"); } - // 将用户数据编码为Base64 JSON + // Encode the user data JSON as Base64. String userDataJson = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(userData); String username = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8)); - // 生成密码签名 + // Generate the password signature. String password = generatePasswordSignature(mqttClientId + "|" + username, signatureKey); - // 构建MQTT配置 + // Build the MQTT configuration object. DeviceReportRespDTO.MQTT mqtt = new DeviceReportRespDTO.MQTT(); mqtt.setClient_id(mqttClientId); mqtt.setUsername(username); @@ -660,7 +662,7 @@ public class DeviceServiceImpl extends BaseServiceImpl } /** - * 生成BearerToken + * Generate a bearer token. */ private String generateBearerToken() { try { @@ -677,48 +679,48 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public Object getDeviceTools(String deviceId) { - // 从系统参数中获取MQTT网关地址 + // Read the MQTT gateway address from system parameters. String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) { return null; } - // 获取设备信息 + // Load the device record. DeviceEntity device = baseDao.selectById(deviceId); if (device == null) { return null; } - // 检查设备是否属于当前用户 + // Ensure the device belongs to the current user. UserDetail user = SecurityUser.getUser(); if (!device.getUserId().equals(user.getId())) { return null; } - // 构建clientId + // Build the clientId. String macAddress = Optional.ofNullable(device.getMacAddress()).orElse("unknown").replace(":", "_"); String groupId = Optional.ofNullable(device.getBoard()).orElse("GID_default").replace(":", "_"); String clientId = StrUtil.format("{}@@@{}@@@{}", groupId, macAddress, macAddress); - // 构建完整的URL + // Build the full URL. String url = StrUtil.format("http://{}/api/commands/{}", mqttGatewayUrl, clientId); - // 存储所有工具列表 + // Store every tool returned across pages. List allTools = new ArrayList<>(); String cursor = null; - // 循环获取分页数据 + // Fetch paginated results until there is no next cursor. while (true) { - // 构建params + // Build params. Map paramsMap = MapUtil.builder(new HashMap()) .put("withUserTools", true) .build(); - // 如果有cursor,添加到请求参数中 + // Add the cursor when the API returned one. if (StringUtils.isNotBlank(cursor)) { paramsMap.put("cursor", cursor); } - // 构建请求体 + // Build the request body. Map payload = MapUtil .builder(new HashMap()) .put("jsonrpc", "2.0") @@ -733,15 +735,15 @@ public class DeviceServiceImpl extends BaseServiceImpl .put("payload", payload) .build(); - // 发送请求 + // Send the request. String resultMessage = HttpRequest.post(url) .header(Header.CONTENT_TYPE, ContentType.JSON.getValue()) .header(Header.AUTHORIZATION, "Bearer " + generateBearerToken()) .body(JSONUtil.toJsonStr(requestBody)) - .timeout(10000) // 超时,毫秒 + .timeout(10000) // Timeout in milliseconds. .execute().body(); - // 解析响应 + // Parse the response. if (StringUtils.isBlank(resultMessage)) { break; } @@ -756,22 +758,22 @@ public class DeviceServiceImpl extends BaseServiceImpl break; } - // 获取当前页的工具列表 + // Collect the tools from the current page. JSONArray tools = data.getJSONArray("tools"); if (tools != null && !tools.isEmpty()) { allTools.addAll(tools); } - // 获取下一页的cursor + // Read the next-page cursor. String nextCursor = data.getStr("nextCursor"); if (StringUtils.isBlank(nextCursor)) { - // 没有下一页了 + // No more pages. break; } cursor = nextCursor; } - // 构建返回结果 + // Build the final response. if (allTools.isEmpty()) { return null; } @@ -783,33 +785,33 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public Object callDeviceTool(String deviceId, String toolName, Map arguments) { - // 从系统参数中获取MQTT网关地址 + // Read the MQTT gateway address from system parameters. String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) { return null; } - // 获取设备信息 + // Load the device record. DeviceEntity device = baseDao.selectById(deviceId); if (device == null) { return null; } - // 检查设备是否属于当前用户 + // Ensure the device belongs to the current user. UserDetail user = SecurityUser.getUser(); if (!device.getUserId().equals(user.getId())) { return null; } - // 构建clientId + // Build the clientId. String macAddress = Optional.ofNullable(device.getMacAddress()).orElse("unknown").replace(":", "_"); String groupId = Optional.ofNullable(device.getBoard()).orElse("GID_default").replace(":", "_"); String clientId = StrUtil.format("{}@@@{}@@@{}", groupId, macAddress, macAddress); - // 构建完整的URL + // Build the full URL. String url = StrUtil.format("http://{}/api/commands/{}", mqttGatewayUrl, clientId); - // 构建请求体 + // Build the request body. Map params = MapUtil .builder(new HashMap()) .put("name", toolName) @@ -830,15 +832,15 @@ public class DeviceServiceImpl extends BaseServiceImpl .put("payload", payload) .build(); - // 发送请求 + // Send the request. String resultMessage = HttpRequest.post(url) .header(Header.CONTENT_TYPE, ContentType.JSON.getValue()) .header(Header.AUTHORIZATION, "Bearer " + generateBearerToken()) .body(JSONUtil.toJsonStr(requestBody)) - .timeout(10000) // 超时,毫秒 + .timeout(10000) // Timeout in milliseconds. .execute().body(); - // 解析响应 + // Parse the response. if (StringUtils.isNotBlank(resultMessage)) { cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(resultMessage); if (jsonObject.getBool("success", false)) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java index 5e22265f0..856d00145 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java @@ -40,14 +40,14 @@ public class OtaServiceImpl extends BaseServiceImpl implement @Override public void update(OtaEntity entity) { - // 检查是否存在相同类型和版本的固件(排除当前记录) + // Check if firmware with same type and version exists (excluding current record) QueryWrapper queryWrapper = new QueryWrapper() .eq("type", entity.getType()) .eq("version", entity.getVersion()) - .ne("id", entity.getId()); // 排除当前记录 + .ne("id", entity.getId()); // Exclude current record if (baseDao.selectCount(queryWrapper) > 0) { - throw new RuntimeException("已存在相同类型和版本的固件,请修改后重试"); + throw new RuntimeException("Firmware with same type and version already exists, please modify and retry"); } entity.setUpdateDate(new Date()); @@ -63,7 +63,7 @@ public class OtaServiceImpl extends BaseServiceImpl implement public boolean save(OtaEntity entity) { QueryWrapper queryWrapper = new QueryWrapper() .eq("type", entity.getType()); - // 同类固件只保留最新的一条 + // Keep only the latest firmware of the same type List otaList = baseDao.selectList(queryWrapper); if (otaList != null && otaList.size() > 0) { OtaEntity otaBefore = otaList.get(0); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java index e3a5d8fd1..74bbcce7c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java @@ -4,28 +4,28 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "用户显示设备列表VO") +@Schema(description = "User display device list VO") public class UserShowDeviceListVO { - @Schema(description = "app版本") + @Schema(description = "App version") private String appVersion; - @Schema(description = "绑定用户名称") + @Schema(description = "Bound user name") private String bindUserName; - @Schema(description = "设备型号") + @Schema(description = "Device model") private String deviceType; - @Schema(description = "设备唯一标识符") + @Schema(description = "Device unique identifier") private String id; - @Schema(description = "mac地址") + @Schema(description = "MAC address") private String macAddress; - @Schema(description = "开启OTA") + @Schema(description = "Enable OTA") private Integer otaUpgrade; - @Schema(description = "最近对话时间") + @Schema(description = "Recent conversation time") private String recentChatTime; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/KnowledgeBaseConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/KnowledgeBaseConfig.java index 3b34d348a..997520bdf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/KnowledgeBaseConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/KnowledgeBaseConfig.java @@ -5,18 +5,19 @@ import org.springframework.context.annotation.Configuration; import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapterFactory; /** - * 知识库配置类 - * 配置知识库相关的Bean + * Knowledge-base configuration class. + * Registers beans used by the knowledge-base module. */ @Configuration public class KnowledgeBaseConfig { /** - * 提供KnowledgeBaseAdapterFactory的Bean实例 - * @return KnowledgeBaseAdapterFactory实例 + * Provide the KnowledgeBaseAdapterFactory bean. + * + * @return KnowledgeBaseAdapterFactory instance */ @Bean public KnowledgeBaseAdapterFactory knowledgeBaseAdapterFactory() { return new KnowledgeBaseAdapterFactory(); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/RAGTaskConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/RAGTaskConfig.java index 0cd1492e6..d89c3210d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/RAGTaskConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/config/RAGTaskConfig.java @@ -1,13 +1,15 @@ package xiaozhi.modules.knowledge.config; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.EnableScheduling; /** - * 知识库模块定时任务配置 - * 启用 Spring Schedule 能力 + * Scheduled-task configuration for the knowledge-base module. + * Enables Spring scheduling support. */ @Configuration +@Profile("!test") @EnableScheduling public class RAGTaskConfig { } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java index 10aafdae8..ade6bc704 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java @@ -33,40 +33,40 @@ import xiaozhi.modules.security.user.SecurityUser; @AllArgsConstructor @RestController @RequestMapping("/datasets") -@Tag(name = "知识库管理") +@Tag(name = "Knowledge Base Management") public class KnowledgeBaseController { private final KnowledgeBaseService knowledgeBaseService; private final KnowledgeManagerService knowledgeManagerService; @GetMapping - @Operation(summary = "分页查询知识库列表") + @Operation(summary = "List knowledge bases with pagination") @RequiresPermissions("sys:role:normal") public Result> getPageList( @RequestParam(required = false) String name, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer page_size) { - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); KnowledgeBaseDTO knowledgeBaseDTO = new KnowledgeBaseDTO(); knowledgeBaseDTO.setName(name); - knowledgeBaseDTO.setCreator(currentUserId); // 设置创建者ID,用于权限过滤 + knowledgeBaseDTO.setCreator(currentUserId); // Restrict results to knowledge bases owned by the current user. PageData pageData = knowledgeBaseService.getPageList(knowledgeBaseDTO, page, page_size); return new Result>().ok(pageData); } @GetMapping("/{dataset_id}") - @Operation(summary = "根据知识库ID获取知识库详情") + @Operation(summary = "Get knowledge-base details by ID") @RequiresPermissions("sys:role:normal") public Result getByDatasetId(@PathVariable("dataset_id") String datasetId) { - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); KnowledgeBaseDTO knowledgeBaseDTO = knowledgeBaseService.getByDatasetId(datasetId); - // 检查权限:用户只能查看自己创建的知识库 + // Users may only view knowledge bases they created. if (knowledgeBaseDTO.getCreator() == null || !knowledgeBaseDTO.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } @@ -75,7 +75,7 @@ public class KnowledgeBaseController { } @PostMapping - @Operation(summary = "创建知识库") + @Operation(summary = "Create knowledge base") @RequiresPermissions("sys:role:normal") public Result save(@RequestBody @Validated KnowledgeBaseDTO knowledgeBaseDTO) { KnowledgeBaseDTO resp = knowledgeBaseService.save(knowledgeBaseDTO); @@ -83,22 +83,22 @@ public class KnowledgeBaseController { } @PutMapping("/{dataset_id}") - @Operation(summary = "更新知识库") + @Operation(summary = "Update knowledge base") @RequiresPermissions("sys:role:normal") public Result update(@PathVariable("dataset_id") String datasetId, @RequestBody @Validated KnowledgeBaseDTO knowledgeBaseDTO) { - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); - // 先获取现有知识库信息以检查权限 + // Load the existing knowledge base to validate permissions. KnowledgeBaseDTO existingKnowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); - // 检查权限:用户只能更新自己创建的知识库 + // Users may only update knowledge bases they created. if (existingKnowledgeBase.getCreator() == null || !existingKnowledgeBase.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } - // [FIX] 注入 ID,防止 Service 层找不到记录 + // Inject the existing ID so the service layer updates the correct record. knowledgeBaseDTO.setId(existingKnowledgeBase.getId()); knowledgeBaseDTO.setDatasetId(datasetId); KnowledgeBaseDTO resp = knowledgeBaseService.update(knowledgeBaseDTO); @@ -106,47 +106,47 @@ public class KnowledgeBaseController { } @DeleteMapping("/{dataset_id}") - @Operation(summary = "删除单个知识库") - @Parameter(name = "dataset_id", description = "知识库ID", required = true) + @Operation(summary = "Delete a single knowledge base") + @Parameter(name = "dataset_id", description = "Knowledge-base ID", required = true) @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable("dataset_id") String datasetId) { - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); - // 先获取现有知识库信息以检查权限 + // Load the existing knowledge base to validate permissions. KnowledgeBaseDTO existingKnowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); - // 检查权限:用户只能删除自己创建的知识库 + // Users may only delete knowledge bases they created. if (existingKnowledgeBase.getCreator() == null || !existingKnowledgeBase.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } - // [Architecture Fix] 通过编排层级联删除,防止孤儿数据并解决循环依赖 + // Use the orchestration layer for cascading deletes to avoid orphaned data and circular dependencies. knowledgeManagerService.deleteDatasetWithFiles(datasetId); return new Result<>(); } @DeleteMapping("/batch") - @Operation(summary = "批量删除知识库") - @Parameter(name = "ids", description = "知识库ID列表,用逗号分隔", required = true) + @Operation(summary = "Delete knowledge bases in batch") + @Parameter(name = "ids", description = "Comma-separated knowledge-base IDs", required = true) @RequiresPermissions("sys:role:normal") public Result deleteBatch(@RequestParam("ids") String ids) { if (StringUtils.isBlank(ids)) { throw new RenException(ErrorCode.PARAMS_GET_ERROR); } - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); List idList = Arrays.asList(ids.split(",")); List knowledgeBaseDTOs = Optional.ofNullable(knowledgeBaseService.getByDatasetIdList(idList)) .orElseGet(ArrayList::new); if (ToolUtil.isNotEmpty(knowledgeBaseDTOs)) { knowledgeBaseDTOs.forEach(item -> { - // 检查权限:用户只能删除自己创建的知识库 + // Users may only delete knowledge bases they created. if (item.getCreator() == null || !item.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } - // [Architecture Fix] 通过编排层级联删除 + // Use the orchestration layer for cascading deletes. knowledgeManagerService.deleteDatasetWithFiles(item.getDatasetId()); }); } @@ -154,10 +154,10 @@ public class KnowledgeBaseController { } @GetMapping("/rag-models") - @Operation(summary = "获取RAG模型列表") + @Operation(summary = "Get RAG model list") @RequiresPermissions("sys:role:normal") public Result> getRAGModels() { List result = knowledgeBaseService.getRAGModels(); return new Result>().ok(result); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java index 22d2f3d2b..33a951a62 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java @@ -30,32 +30,32 @@ import xiaozhi.modules.security.user.SecurityUser; @AllArgsConstructor @RestController @RequestMapping("/datasets/{dataset_id}") -@Tag(name = "知识库文档管理") +@Tag(name = "Knowledge Base Document Management") public class KnowledgeFilesController { private final KnowledgeFilesService knowledgeFilesService; private final KnowledgeBaseService knowledgeBaseService; /** - * 验证当前用户是否有权限操作指定知识库 - * - * @param datasetId 知识库ID + * Verify whether the current user can operate on the specified knowledge base. + * + * @param datasetId knowledge-base ID */ private void validateKnowledgeBasePermission(String datasetId) { - // 获取当前登录用户ID + // Resolve the current user ID. Long currentUserId = SecurityUser.getUserId(); - // 获取知识库信息 + // Load knowledge-base details. KnowledgeBaseDTO knowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); - // 检查权限:用户只能操作自己创建的知识库 + // Users may operate only on knowledge bases they created. if (knowledgeBase.getCreator() == null || !knowledgeBase.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } } @GetMapping("/documents") - @Operation(summary = "分页查询文档列表") + @Operation(summary = "List documents with pagination") @RequiresPermissions("sys:role:normal") public Result> getPageList( @PathVariable("dataset_id") String datasetId, @@ -63,10 +63,10 @@ public class KnowledgeFilesController { @RequestParam(required = false) String status, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer page_size) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); - // 组装参数 + // Build query parameters. KnowledgeFilesDTO knowledgeFilesDTO = new KnowledgeFilesDTO(); knowledgeFilesDTO.setDatasetId(datasetId); knowledgeFilesDTO.setName(name); @@ -76,16 +76,16 @@ public class KnowledgeFilesController { } @GetMapping("/documents/status/{status}") - @Operation(summary = "根据状态分页查询文档列表") + @Operation(summary = "List documents by status with pagination") @RequiresPermissions("sys:role:normal") public Result> getPageListByStatus( @PathVariable("dataset_id") String datasetId, @PathVariable("status") String status, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer page_size) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); - // 组装参数 + // Build query parameters. KnowledgeFilesDTO knowledgeFilesDTO = new KnowledgeFilesDTO(); knowledgeFilesDTO.setDatasetId(datasetId); knowledgeFilesDTO.setStatus(status); @@ -94,7 +94,7 @@ public class KnowledgeFilesController { } @PostMapping("/documents") - @Operation(summary = "上传文档到知识库") + @Operation(summary = "Upload a document to a knowledge base") @RequiresPermissions("sys:role:normal") public Result uploadDocument( @PathVariable("dataset_id") String datasetId, @@ -104,7 +104,7 @@ public class KnowledgeFilesController { @RequestParam(required = false) String metaFields, @RequestParam(required = false) String parserConfig) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); KnowledgeFilesDTO resp = knowledgeFilesService.uploadDocument(datasetId, file, name, @@ -115,11 +115,11 @@ public class KnowledgeFilesController { } @DeleteMapping("/documents") - @Operation(summary = "批量删除文档") + @Operation(summary = "Delete documents in batch") @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable("dataset_id") String datasetId, @RequestBody DocumentDTO.BatchIdReq req) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); knowledgeFilesService.deleteDocuments(datasetId, req); @@ -127,11 +127,11 @@ public class KnowledgeFilesController { } @DeleteMapping("/documents/{document_id}") - @Operation(summary = "删除单个文档") + @Operation(summary = "Delete a single document") @RequiresPermissions("sys:role:normal") public Result deleteSingle(@PathVariable("dataset_id") String datasetId, @PathVariable("document_id") String documentId) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); DocumentDTO.BatchIdReq req = new DocumentDTO.BatchIdReq(); @@ -141,64 +141,64 @@ public class KnowledgeFilesController { } @PostMapping("/chunks") - @Operation(summary = "解析文档(切块)") + @Operation(summary = "Parse and chunk documents") @RequiresPermissions("sys:role:normal") public Result parseDocuments(@PathVariable("dataset_id") String datasetId, @RequestBody Map> requestBody) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); List documentIds = requestBody.get("document_ids"); if (documentIds == null || documentIds.isEmpty()) { - return new Result().error("document_ids参数不能为空"); + return new Result().error("The document_ids parameter cannot be empty"); } boolean success = knowledgeFilesService.parseDocuments(datasetId, documentIds); if (success) { return new Result(); } else { - return new Result().error("文档解析失败,文档可能正在处理中"); + return new Result().error("Document parsing failed, and the document may still be processing"); } } @GetMapping("/documents/{document_id}/chunks") - @Operation(summary = "列出指定文档的切片") + @Operation(summary = "List chunks for a specific document") @RequiresPermissions("sys:role:normal") public Result listChunks( @PathVariable("dataset_id") String datasetId, @PathVariable("document_id") String documentId, @ParameterObject ChunkDTO.ListReq req) { - // 验证权限 (内部已包含知识库存在性校验与归属权校验) + // Validate permissions. This also checks knowledge-base existence and ownership. validateKnowledgeBasePermission(datasetId); - // 设置默认值 + // Apply defaults. if (req.getPage() == null) req.setPage(1); if (req.getPageSize() == null) req.setPageSize(50); - // 调用服务层获取强类型切片列表 + // Delegate to the service layer and return a strongly typed chunk list. ChunkDTO.ListVO result = knowledgeFilesService.listChunks(datasetId, documentId, req); return new Result().ok(result); } @PostMapping("/retrieval-test") - @Operation(summary = "召回测试") + @Operation(summary = "Run retrieval test") @RequiresPermissions("sys:role:normal") public Result retrievalTest( @PathVariable("dataset_id") String datasetId, @RequestBody RetrievalDTO.TestReq req) { - // 验证知识库权限 + // Validate knowledge-base permissions. validateKnowledgeBasePermission(datasetId); - // 业务下沉逻辑:如果未指定知识库ID,则设为当前路径中的 datasetId + // Default to the current dataset when no dataset IDs are provided. if (req.getDatasetIds() == null || req.getDatasetIds().isEmpty()) { req.setDatasetIds(java.util.Arrays.asList(datasetId)); } - // [Reinforce] 强管控分页参数,防止 RAGFlow 端出现 Negative Slicing 报错 + // Clamp pagination parameters to prevent negative slicing errors on the RAGFlow side. if (req.getPage() == null || req.getPage() < 1) { req.setPage(1); } @@ -206,13 +206,13 @@ public class KnowledgeFilesController { req.setPageSize(100); } - // 调用检索服务,返回强类型聚合对象 + // Call the retrieval service and return a strongly typed aggregate result. RetrievalDTO.ResultVO result = knowledgeFilesService.retrievalTest(req); return new Result().ok(result); } /** - * 解析JSON字符串为Map对象 + * Parse a JSON string into a map. */ private Map parseJsonMap(String jsonString) { try { @@ -220,7 +220,7 @@ public class KnowledgeFilesController { return objectMapper.readValue(jsonString, new TypeReference>() { }); } catch (Exception e) { - throw new RuntimeException("解析JSON字符串失败: " + jsonString, e); + throw new RuntimeException("Failed to parse JSON string: " + jsonString, e); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/DocumentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/DocumentDao.java index 29f82bf82..2ba6bdb1d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/DocumentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/DocumentDao.java @@ -5,7 +5,7 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.knowledge.entity.DocumentEntity; /** - * 文档 DAO + * Document DAO. */ @Mapper public interface DocumentDao extends BaseDao { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java index d09579196..e8f27809b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java @@ -7,29 +7,29 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; /** - * 知识库知识库 + * Knowledge-base DAO. */ @Mapper public interface KnowledgeBaseDao extends BaseDao { /** - * 根据知识库ID删除相关的插件映射记录 - * - * @param knowledgeBaseId 知识库ID + * Delete plugin-mapping records related to a knowledge base. + * + * @param knowledgeBaseId knowledge-base ID */ void deletePluginMappingByKnowledgeBaseId(@Param("knowledgeBaseId") String knowledgeBaseId); /** - * 通用维度原子更新知识库统计信息 - * - * @param datasetId 数据集ID - * @param docDelta 文档数增量 - * @param chunkDelta 分块数增量 - * @param tokenDelta Token数增量 + * Atomically update knowledge-base statistics. + * + * @param datasetId dataset ID + * @param docDelta document-count delta + * @param chunkDelta chunk-count delta + * @param tokenDelta token-count delta */ void updateStatsAfterChange(@Param("datasetId") String datasetId, @Param("docDelta") Integer docDelta, @Param("chunkDelta") Long chunkDelta, @Param("tokenDelta") Long tokenDelta); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_API_Classification.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_API_Classification.md new file mode 100644 index 000000000..5595a79b5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_API_Classification.md @@ -0,0 +1,41 @@ +# RAGFlow API Classification + +## Overview + +RAGFlow exposes two broad API families: + +- External APIs under `/api/v1`, authenticated with API keys. +- Internal console APIs under `/v1/`, authenticated with user + sessions or cookies. + +## External API Families + +| Family | Example paths | Purpose | +|---|---|---| +| Agents | `/api/v1/agents`, `/api/v1/agents//sessions` | Agent lifecycle, session management, completions | +| Chats | `/api/v1/chats`, `/api/v1/chats//completions` | Chat assistant lifecycle and inference | +| Datasets | `/api/v1/datasets`, `/api/v1/datasets//documents` | Knowledge base and document management | +| Files | `/api/v1/file/upload`, `/api/v1/file/list` | File storage and logical folder operations | +| SearchBot | `/api/v1/searchbots/ask`, `/api/v1/searchbots/mindmap` | Embedded search experiences | +| Session utilities | `/api/v1/sessions/ask`, `/api/v1/sessions/related_questions` | Testing and debugging helpers | +| Dify compatibility | `/api/v1/dify/retrieval` | Dify-style retrieval payloads | +| OpenAI compatibility | `/api/v1/chats_openai/...`, `/api/v1/agents_openai/...` | OpenAI-style request and stream formats | + +## Internal API Families + +| Family | Example paths | Purpose | +|---|---|---| +| User | `/v1/user/login`, `/v1/user/info` | Authentication and profile operations | +| API token | `/v1/api/new_token` | Console token generation | +| Conversation | `/v1/conversation/set`, `/v1/conversation/completion` | Internal chat testing | +| Knowledge base | `/v1/kb/list`, `/v1/kb/create` | Console KB management | +| Document | `/v1/document/upload`, `/v1/document/parse` | Console-side document operations | + +## Practical Guidance + +- Prefer the external APIs for system-to-system integrations. +- Prefer OpenAI-compatible endpoints when the client already speaks the OpenAI + chat protocol. +- Prefer SearchBot endpoints for embedded retrieval-centric experiences. +- Treat the internal `/v1` endpoints as console-oriented and subject to more UI + coupling. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Dify_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Dify_Reference.md new file mode 100644 index 000000000..716452adf --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Dify_Reference.md @@ -0,0 +1,77 @@ +# RAGFlow Agent and Dify Compatibility Reference + +## Dify-Compatible Retrieval + +### `retrieval` + +- Method: `POST` +- Path: `/api/v1/dify/retrieval` +- Purpose: Accept a Dify-style retrieval payload and return matching records. + +Common request fields: + +- `knowledge_id` +- `query` +- `use_kg` +- `retrieval_setting` +- `metadata_condition` + +Common response fields: + +- `records[].content` +- `records[].score` +- `records[].title` +- `records[].metadata` + +## Agent Sessions + +### `create_agent_session` + +- Method: `POST` +- Path: `/api/v1/agents//sessions` +- Purpose: Create a new agent session container. +- Optional query field: `user_id` + +### `list_agent_session` + +- Method: `GET` +- Path: `/api/v1/agents//sessions` +- Purpose: List sessions for a specific agent. +- Common query fields: `page`, `page_size`, `orderby`, `desc`, `id`, `user_id`, + `dsl` + +### `delete_agent_session` + +- Method: `DELETE` +- Path: `/api/v1/agents//sessions` +- Purpose: Delete one or more sessions. +- Common body field: `ids` + +## Agent Completions + +### `agent_completions` + +- Method: `POST` +- Path: `/api/v1/agents//completions` +- Purpose: Run an agent session and stream or return a response. + +Common request fields: + +- `session_id` +- `question` +- `stream` +- `quote` + +### `agents_completion_openai_compatibility` + +- Method: `POST` +- Path: `/api/v1/agents_openai//chat/completions` +- Purpose: Offer an OpenAI-style chat completion surface for an agent-backed + workflow. + +## Notes + +- The downstream branch should prefer neutral examples and avoid locale-specific + assumptions. +- If upstream expands the payload schema, update this summary rather than + restoring a large translated document. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Reference.md new file mode 100644 index 000000000..889ec7c0d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Agent_Reference.md @@ -0,0 +1,68 @@ +# RAGFlow Agent API Reference + +## Scope + +This document summarizes the external Agent management surface under +`/api/v1/agents`. + +## Endpoints + +### `list_agents` + +- Method: `GET` +- Path: `/api/v1/agents` +- Purpose: List tenant-visible agents with optional filtering by `id` or + `title`. +- Common query fields: `page`, `page_size`, `orderby`, `desc`, `id`, `title` + +### `create_agent` + +- Method: `POST` +- Path: `/api/v1/agents` +- Purpose: Create a new agent definition. +- Typical body fields: `title`, `dsl`, `description`, `avatar` + +### `update_agent` + +- Method: `PUT` +- Path: `/api/v1/agents/` +- Purpose: Update an existing agent. +- Typical body fields: `title`, `dsl`, `description`, `avatar` + +### `delete_agent` + +- Method: `DELETE` +- Path: `/api/v1/agents/` +- Purpose: Permanently delete an agent. + +### `webhook` + +- Method: `POST` or configured method +- Path: `/api/v1/webhook_test/` +- Purpose: Exercise a webhook-enabled agent flow from an external trigger. + +### `webhook_trace` + +- Method: `POST` or configured method +- Path: `/api/v1/webhook_trace/` +- Purpose: Inspect webhook execution traces for debugging. + +## Returned Data + +Typical agent records include: + +- `id` +- `title` +- `description` +- `dsl` +- `user_id` +- `avatar` +- `canvas_category` +- `create_time` +- `update_time` + +## Notes + +- Agents are orchestration-oriented and usually contain graph-style DSL. +- The downstream branch should keep provider-neutral examples and + English-first descriptions. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Completion_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Completion_Reference.md new file mode 100644 index 000000000..749b53165 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Completion_Reference.md @@ -0,0 +1,76 @@ +# RAGFlow Chat Completion Reference + +## Native Chat Completion + +### `chat_completion` + +- Method: `POST` +- Path: `/api/v1/chats//completions` +- Purpose: Run a chat assistant against a specific session. + +Common request fields: + +- `session_id` +- `question` +- `stream` +- `quote` +- `doc_ids` +- `metadata_condition` + +Response modes: + +- `text/event-stream` for SSE chunking +- `application/json` for non-stream replies + +Common response fields: + +- `answer` +- `reference` + +## OpenAI-Compatible Chat Completion + +### `chat_completion_openai_like` + +- Method: `POST` +- Path: `/api/v1/chats_openai//chat/completions` +- Purpose: Offer an OpenAI-style chat completion facade over a chat assistant. + +Common request fields: + +- `model` +- `messages` +- `stream` + +Common response shape: + +- OpenAI chunk stream when `stream=true` +- OpenAI chat completion object when `stream=false` + +## Embedded Chatbot Completion + +### `chatbot_completions` + +- Method: `POST` +- Path: `/api/v1/chatbots//completions` +- Purpose: Support embedded chatbot windows for end-user experiences. + +Common request fields: + +- `question` +- `stream` +- `quote` + +## Embedded Chatbot Metadata + +### `chatbots_inputs` + +- Method: `GET` +- Path: `/api/v1/chatbots//info` +- Purpose: Return chatbot metadata such as title, avatar, and prologue. + +## Notes + +- Prefer the OpenAI-compatible endpoint when the client stack already expects + the OpenAI protocol. +- Prefer the native endpoint when downstream needs explicit reference metadata + and RAGFlow-native semantics. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Reference.md new file mode 100644 index 000000000..0a8a90d98 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Reference.md @@ -0,0 +1,67 @@ +# RAGFlow Chat API Reference + +## Scope + +This document covers the chat assistant management endpoints under `/api/v1/chats`. + +## Endpoints + +### `create` + +- Method: `POST` +- Path: `/api/v1/chats` +- Purpose: Create a chat assistant. + +Typical body fields: + +- `name` +- `avatar` +- `description` +- `prompt_config` +- `dataset_ids` + +### `list_chat` + +- Method: `GET` +- Path: `/api/v1/chats` +- Purpose: List chat assistants with paging and filters. + +Common query fields: + +- `page` +- `page_size` +- `orderby` +- `desc` +- `id` +- `name` + +### `update` + +- Method: `PUT` +- Path: `/api/v1/chats/` +- Purpose: Update a chat assistant definition. + +### `delete_chats` + +- Method: `DELETE` +- Path: `/api/v1/chats` +- Purpose: Delete one or more chat assistants. +- Common body field: `ids` + +## Typical Returned Fields + +- `id` +- `name` +- `description` +- `avatar` +- `dataset_ids` +- `prompt_config` +- `llm_setting` +- `create_time` +- `update_time` + +## Notes + +- Chat assistants represent assistant-style conversational apps rather than + graph-driven agents. +- Completion and session operations are documented separately. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Session_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Session_Reference.md new file mode 100644 index 000000000..f350e3a9a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Chat_Session_Reference.md @@ -0,0 +1,71 @@ +# RAGFlow Chat Session API Reference + +## Scope + +This document covers the session lifecycle for chat assistants. + +## Endpoints + +### `create` + +- Method: `POST` +- Path: `/api/v1/chats//sessions` +- Purpose: Create a new chat session. + +Common request fields: + +- `name` +- `user_id` + +### `list_session` + +- Method: `GET` +- Path: `/api/v1/chats//sessions` +- Purpose: List sessions under a chat assistant. + +Common query fields: + +- `page` +- `page_size` +- `orderby` +- `desc` +- `name` +- `id` +- `user_id` + +### `update` + +- Method: `PUT` +- Path: `/api/v1/chats//sessions/` +- Purpose: Rename or otherwise update session metadata. + +Typical body field: + +- `name` + +### `delete` + +- Method: `DELETE` +- Path: `/api/v1/chats//sessions` +- Purpose: Delete selected sessions or, if supported upstream, all sessions + under a chat assistant. + +Common body field: + +- `ids` + +## Typical Returned Fields + +- `id` +- `chat_id` +- `name` +- `user_id` +- `messages` +- `create_time` +- `update_time` + +## Notes + +- The prologue or starter message is usually injected automatically from the + chat assistant definition. +- Session history is the foundation for subsequent chat completion calls. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Dataset_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Dataset_Reference.md new file mode 100644 index 000000000..23ea74b3a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Dataset_Reference.md @@ -0,0 +1,106 @@ +# RAGFlow Dataset API Reference + +## Scope + +Datasets are the top-level knowledge base objects in RAGFlow. + +## Core Endpoints + +### `create` + +- Method: `POST` +- Path: `/api/v1/datasets` +- Purpose: Create a dataset. + +Typical body fields: + +- `name` +- `description` +- `embedding_model` +- `permission` + +### `list_datasets` + +- Method: `GET` +- Path: `/api/v1/datasets` +- Purpose: List datasets with filters and paging. + +Common query fields: + +- `page` +- `page_size` +- `orderby` +- `desc` +- `id` +- `name` + +### `update` + +- Method: `PUT` +- Path: `/api/v1/datasets/` +- Purpose: Update dataset metadata and settings. + +### `delete` + +- Method: `DELETE` +- Path: `/api/v1/datasets` +- Purpose: Delete one or more datasets. + +Common body field: + +- `ids` + +## Graph and Advanced Retrieval Endpoints + +### `knowledge_graph` + +- Method: `GET` +- Path: `/api/v1/datasets//knowledge_graph` +- Purpose: Return knowledge graph data for a dataset. + +### `delete_knowledge_graph` + +- Method: `DELETE` +- Path: `/api/v1/datasets//knowledge_graph` +- Purpose: Remove graph artifacts for a dataset. + +### `run_graphrag` + +- Method: `POST` +- Path: `/api/v1/datasets//run_graphrag` +- Purpose: Start a GraphRAG job. + +### `run_raptor` + +- Method: `POST` +- Path: `/api/v1/datasets//run_raptor` +- Purpose: Start a Raptor job. + +### `trace_graphrag` + +- Method: `GET` +- Path: `/api/v1/datasets//trace_graphrag` +- Purpose: Inspect GraphRAG execution state. + +### `trace_raptor` + +- Method: `GET` +- Path: `/api/v1/datasets//trace_raptor` +- Purpose: Inspect Raptor execution state. + +## Typical Returned Fields + +- `id` +- `name` +- `description` +- `document_count` +- `chunk_count` +- `embedding_model` +- `permission` +- `create_time` +- `update_time` + +## Notes + +- Dataset behavior is tightly connected to the document endpoints. +- Keep downstream examples provider-neutral and infrastructure-neutral. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Document_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Document_Reference.md new file mode 100644 index 000000000..ae86ae660 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Document_Reference.md @@ -0,0 +1,125 @@ +# RAGFlow Document API Reference + +## Scope + +This document summarizes document ingestion, chunk management, and retrieval +testing under a dataset. + +## Core Document Endpoints + +### `upload` + +- Method: `POST` +- Path: `/api/v1/datasets//documents` +- Purpose: Upload one or more documents into a dataset. + +### `list_docs` + +- Method: `GET` +- Path: `/api/v1/datasets//documents` +- Purpose: List documents and parsing status. + +Common query fields: + +- `page` +- `page_size` +- `orderby` +- `desc` +- `keywords` +- `run` +- `create_time_from` +- `create_time_to` + +### `update_doc` + +- Method: `PUT` +- Path: `/api/v1/datasets//documents/` +- Purpose: Update parsing configuration or metadata for a document. + +### `delete` + +- Method: `DELETE` +- Path: `/api/v1/datasets//documents` +- Purpose: Delete one or more documents. + +### `download` + +- Method: `GET` +- Path: `/api/v1/datasets//documents/` +- Purpose: Download the original stored document. + +## Parsing and Chunk Endpoints + +### `parse` + +- Method: `POST` +- Path: `/api/v1/datasets//chunks` +- Purpose: Start document parsing or chunk generation jobs. + +### `stop_parsing` + +- Method: `DELETE` +- Path: `/api/v1/datasets//chunks` +- Purpose: Cancel parsing jobs. + +### `list_chunks` + +- Method: `GET` +- Path: `/api/v1/datasets//documents//chunks` +- Purpose: List generated chunks for a document. + +### `add_chunk` + +- Method: `POST` +- Path: `/api/v1/datasets//documents//chunks` +- Purpose: Add a manual chunk. + +### `update_chunk` + +- Method: `PUT` +- Path: `/api/v1/datasets//documents//chunks/` +- Purpose: Update a specific chunk. + +### `rm_chunk` + +- Method: `DELETE` +- Path: `/api/v1/datasets//documents//chunks` +- Purpose: Remove selected chunks. + +## Metadata and Retrieval + +### `metadata_summary` + +- Method: `GET` +- Path: `/api/v1/datasets//metadata/summary` +- Purpose: Return metadata facets or summary statistics. + +### `metadata_batch_update` + +- Method: `POST` +- Path: `/api/v1/datasets//metadata/update` +- Purpose: Update metadata across multiple records. + +### `retrieval_test` + +- Method: `POST` +- Path: `/api/v1/retrieval` +- Purpose: Run retrieval only, without a final LLM answer. + +## Typical Returned Fields + +- `id` +- `dataset_id` +- `name` +- `type` +- `run` +- `parser_config` +- `token_count` +- `chunk_count` +- `create_time` +- `update_time` + +## Notes + +- Parsing configuration is a major source of upstream churn, so keep this + document summary-based rather than exhaustive. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_External_API_By_File.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_External_API_By_File.md new file mode 100644 index 000000000..773e83ec0 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_External_API_By_File.md @@ -0,0 +1,93 @@ +# RAGFlow External API Reference by Source File + +## `api/apps/sdk/agents.py` + +- `list_agents` -> `/api/v1/agents` +- `create_agent` -> `/api/v1/agents` +- `update_agent` -> `/api/v1/agents/` +- `delete_agent` -> `/api/v1/agents/` +- `webhook` -> `/api/v1/webhook_test/` +- `webhook_trace` -> `/api/v1/webhook_trace/` + +## `api/apps/sdk/chat.py` + +- `create` -> `/api/v1/chats` +- `delete_chats` -> `/api/v1/chats` +- `list_chat` -> `/api/v1/chats` +- `update` -> `/api/v1/chats/` + +## `api/apps/sdk/dataset.py` + +- `create` -> `/api/v1/datasets` +- `delete` -> `/api/v1/datasets` +- `list_datasets` -> `/api/v1/datasets` +- `update` -> `/api/v1/datasets/` +- `knowledge_graph` -> `/api/v1/datasets//knowledge_graph` +- `delete_knowledge_graph` -> `/api/v1/datasets//knowledge_graph` +- `run_graphrag` -> `/api/v1/datasets//run_graphrag` +- `run_raptor` -> `/api/v1/datasets//run_raptor` +- `trace_graphrag` -> `/api/v1/datasets//trace_graphrag` +- `trace_raptor` -> `/api/v1/datasets//trace_raptor` + +## `api/apps/sdk/dify_retrieval.py` + +- `retrieval` -> `/api/v1/dify/retrieval` + +## `api/apps/sdk/doc.py` + +- `parse` -> `/api/v1/datasets//chunks` +- `stop_parsing` -> `/api/v1/datasets//chunks` +- `upload` -> `/api/v1/datasets//documents` +- `list_docs` -> `/api/v1/datasets//documents` +- `delete` -> `/api/v1/datasets//documents` +- `update_doc` -> `/api/v1/datasets//documents/` +- `download` -> `/api/v1/datasets//documents/` +- `list_chunks` -> `/api/v1/datasets//documents//chunks` +- `add_chunk` -> `/api/v1/datasets//documents//chunks` +- `update_chunk` -> `/api/v1/datasets//documents//chunks/` +- `rm_chunk` -> `/api/v1/datasets//documents//chunks` +- `metadata_summary` -> `/api/v1/datasets//metadata/summary` +- `metadata_batch_update` -> `/api/v1/datasets//metadata/update` +- `retrieval_test` -> `/api/v1/retrieval` + +## `api/apps/sdk/files.py` + +- `get_all_parent_folders` -> `/api/v1/file/all_parent_folder` +- `convert` -> `/api/v1/file/convert` +- `create` -> `/api/v1/file/create` +- `download_attachment` -> `/api/v1/file/download/` +- `get` -> `/api/v1/file/get/` +- `list_files` -> `/api/v1/file/list` +- `move` -> `/api/v1/file/mv` +- `get_parent_folder` -> `/api/v1/file/parent_folder` +- `rename` -> `/api/v1/file/rename` +- `rm` -> `/api/v1/file/rm` +- `get_root_folder` -> `/api/v1/file/root_folder` +- `upload` -> `/api/v1/file/upload` + +## `api/apps/sdk/session.py` + +- `agent_bot_completions` -> `/api/v1/agentbots//completions` +- `begin_inputs` -> `/api/v1/agentbots//inputs` +- `agent_completions` -> `/api/v1/agents//completions` +- `create_agent_session` -> `/api/v1/agents//sessions` +- `list_agent_session` -> `/api/v1/agents//sessions` +- `delete_agent_session` -> `/api/v1/agents//sessions` +- `agents_completion_openai_compatibility` -> + `/api/v1/agents_openai//chat/completions` +- `chatbot_completions` -> `/api/v1/chatbots//completions` +- `chatbots_inputs` -> `/api/v1/chatbots//info` +- `chat_completion` -> `/api/v1/chats//completions` +- `create` -> `/api/v1/chats//sessions` +- `list_session` -> `/api/v1/chats//sessions` +- `delete` -> `/api/v1/chats//sessions` +- `update` -> `/api/v1/chats//sessions/` +- `chat_completion_openai_like` -> + `/api/v1/chats_openai//chat/completions` +- `ask_about_embedded` -> `/api/v1/searchbots/ask` +- `detail_share_embedded` -> `/api/v1/searchbots/detail` +- `mindmap` -> `/api/v1/searchbots/mindmap` +- `related_questions_embedded` -> `/api/v1/searchbots/related_questions` +- `retrieval_test_embedded` -> `/api/v1/searchbots/retrieval_test` +- `ask_about` -> `/api/v1/sessions/ask` +- `related_questions` -> `/api/v1/sessions/related_questions` diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_File_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_File_Reference.md new file mode 100644 index 000000000..382ae5d0e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_File_Reference.md @@ -0,0 +1,118 @@ +# RAGFlow File API Reference + +## Scope + +This document covers the logical file-management endpoints exposed under +`/api/v1/file`. + +## Endpoints + +### `upload` + +- Method: `POST` +- Path: `/api/v1/file/upload` +- Content type: `multipart/form-data` +- Purpose: Upload one or more files to a logical folder. + +Common fields: + +- `file` +- `parent_id` + +### `create` + +- Method: `POST` +- Path: `/api/v1/file/create` +- Purpose: Create a logical folder. + +Common fields: + +- `name` +- `parent_id` +- `type` + +### `list_files` + +- Method: `GET` +- Path: `/api/v1/file/list` +- Purpose: List files and folders under a parent folder. + +Common query fields: + +- `parent_id` +- `keywords` +- `page` +- `page_size` +- `orderby` +- `desc` + +### `get` + +- Method: `GET` +- Path: `/api/v1/file/get/` +- Purpose: Return a file stream for direct download. + +### `download_attachment` + +- Method: `GET` +- Path: `/api/v1/file/download/` +- Purpose: Download a stored attachment by storage key or attachment id. + +### `rename` + +- Method: `POST` +- Path: `/api/v1/file/rename` +- Purpose: Rename a file or folder. + +### `move` + +- Method: `POST` +- Path: `/api/v1/file/mv` +- Purpose: Move files or folders to another parent folder. + +### `rm` + +- Method: `DELETE` +- Path: `/api/v1/file/rm` +- Purpose: Delete files or folders. + +### `get_root_folder` + +- Method: `GET` +- Path: `/api/v1/file/root_folder` +- Purpose: Return the root logical folder. + +### `get_parent_folder` + +- Method: `GET` +- Path: `/api/v1/file/parent_folder` +- Purpose: Return a folder's direct parent. + +### `get_all_parent_folders` + +- Method: `GET` +- Path: `/api/v1/file/all_parent_folder` +- Purpose: Return the ancestor chain for breadcrumb navigation. + +### `convert` + +- Method: `POST` +- Path: `/api/v1/file/convert` +- Purpose: Convert uploaded files into dataset documents. + +## Typical Returned Fields + +- `id` +- `parent_id` +- `name` +- `location` +- `type` +- `size` +- `source_type` +- `create_time` +- `update_time` + +## Notes + +- The file APIs are storage-oriented and separate from dataset parsing. +- Folder operations are logical and may map to object storage behind the scenes. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_SearchBot_AgentBot_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_SearchBot_AgentBot_Reference.md new file mode 100644 index 000000000..9454ff078 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_SearchBot_AgentBot_Reference.md @@ -0,0 +1,68 @@ +# RAGFlow SearchBot and AgentBot Reference + +## SearchBot Endpoints + +### `ask_about_embedded` + +- Method: `POST` +- Path: `/api/v1/searchbots/ask` +- Purpose: Run a retrieval-focused SearchBot query for embedded use cases. + +Common request fields: + +- `question` +- `kb_ids` +- `search_id` + +### `mindmap` + +- Method: `POST` +- Path: `/api/v1/searchbots/mindmap` +- Purpose: Return a mind-map structure for a query. + +### `related_questions_embedded` + +- Method: `POST` +- Path: `/api/v1/searchbots/related_questions` +- Purpose: Suggest related questions for an embedded search experience. + +### `detail_share_embedded` + +- Method: `GET` +- Path: `/api/v1/searchbots/detail` +- Purpose: Return SearchBot configuration details used by citation or sidebar + displays. + +### `retrieval_test_embedded` + +- Method: `POST` +- Path: `/api/v1/searchbots/retrieval_test` +- Purpose: Return retrieval chunks directly for testing. + +## AgentBot Endpoints + +### `begin_inputs` + +- Method: `GET` +- Path: `/api/v1/agentbots//inputs` +- Purpose: Return the prologue and input schema required before an embedded + agent run starts. + +### `agent_bot_completions` + +- Method: `POST` +- Path: `/api/v1/agentbots//completions` +- Purpose: Execute an embedded agent interaction. + +Common request fields: + +- `question` +- `inputs` +- `stream` + +## Notes + +- SearchBot is retrieval-first. +- AgentBot is workflow-first. +- Both surfaces are common entry points for external embedded experiences, so + examples should remain English-first and provider-neutral. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Session_Extras_Reference.md b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Session_Extras_Reference.md new file mode 100644 index 000000000..899a0b30e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/doc/RAGFlow_Session_Extras_Reference.md @@ -0,0 +1,60 @@ +# RAGFlow Session Extras Reference + +## `detail_share_embedded` + +- Method: `GET` +- Path: `/api/v1/searchbots/detail` +- Purpose: Return SearchBot details that help the frontend display citation or + source context. + +Common query field: + +- `search_id` + +## `retrieval_test_embedded` + +- Method: `POST` +- Path: `/api/v1/searchbots/retrieval_test` +- Purpose: Run retrieval-only testing for a SearchBot configuration. + +Common request fields: + +- `kb_id` +- `question` +- `page` +- `size` +- `doc_ids` +- `similarity_threshold` +- `top_k` +- `highlight` + +## `ask_about` + +- Method: `POST` +- Path: `/api/v1/sessions/ask` +- Purpose: Run an internal session question directly against selected datasets. + +Common request fields: + +- `question` +- `dataset_ids` + +## `related_questions` + +- Method: `POST` +- Path: `/api/v1/sessions/related_questions` +- Purpose: Generate related-question suggestions in internal or testing + scenarios. + +Common request fields: + +- `question` +- `dataset_ids` +- `industry` + +## Notes + +- These endpoints are useful for internal testing, preview tools, and source + explanation flows. +- Keep downstream references concise; this file is meant to reduce integration + friction, not mirror every upstream response field verbatim. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/DocumentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/DocumentDTO.java index 44b805821..f2ec22df1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/DocumentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/DocumentDTO.java @@ -8,61 +8,61 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 文档 DTO + * Document DTO. */ @Data -@Schema(description = "知识库文档") +@Schema(description = "Knowledge-base document") public class DocumentDTO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "本地ID") + @Schema(description = "Local ID") private String id; - @Schema(description = "知识库ID") + @Schema(description = "Knowledge-base ID") private String datasetId; - @Schema(description = "RAGFlow文档ID") + @Schema(description = "RAGFlow document ID") private String documentId; - @Schema(description = "文档名称") + @Schema(description = "Document name") private String name; - @Schema(description = "文件大小") + @Schema(description = "File size") private Long size; - @Schema(description = "文件类型") + @Schema(description = "File type") private String type; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") private String chunkMethod; - @Schema(description = "解析配置") + @Schema(description = "Parser configuration") private Map parserConfig; - @Schema(description = "处理状态 (1:解析中 3:成功 4:失败)") + @Schema(description = "Processing status (1 running, 3 success, 4 failure)") private Integer status; - @Schema(description = "错误信息") + @Schema(description = "Error message") private String error; - @Schema(description = "分块数量") + @Schema(description = "Chunk count") private Integer chunkCount; - @Schema(description = "Token数量") + @Schema(description = "Token count") private Long tokenCount; - @Schema(description = "是否启用") + @Schema(description = "Enabled flag") private Integer enabled; - @Schema(description = "创建时间") + @Schema(description = "Created at") private Date createdAt; - @Schema(description = "更新时间") + @Schema(description = "Updated at") private Date updatedAt; - @Schema(description = "上传进度 (虚拟字段)") + @Schema(description = "Upload progress (virtual field)") private Double progress; - @Schema(description = "缩略图/预览图 (虚拟字段)") + @Schema(description = "Thumbnail or preview image (virtual field)") private String thumbnail; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java index 39e89de86..0b2258f1a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java @@ -8,63 +8,63 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "知识库知识库") +@Schema(description = "Knowledge-base DTO") public class KnowledgeBaseDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - @Schema(description = "唯一标识") + @Schema(description = "Unique ID") private String id; - @Schema(description = "知识库ID") + @Schema(description = "Knowledge-base ID") private String datasetId; - @Schema(description = "RAG模型配置ID") + @Schema(description = "RAG model configuration ID") private String ragModelId; - @Schema(description = "知识库名称") + @Schema(description = "Knowledge-base name") private String name; - @Schema(description = "知识库头像(Base64)") + @Schema(description = "Knowledge-base avatar in Base64") private String avatar; - @Schema(description = "知识库描述") + @Schema(description = "Knowledge-base description") private String description; - @Schema(description = "嵌入模型名称") + @Schema(description = "Embedding model name") private String embeddingModel; - @Schema(description = "权限设置: me/team") + @Schema(description = "Permission setting, for example me or team") private String permission; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") private String chunkMethod; - @Schema(description = "解析器配置(JSON String)") + @Schema(description = "Parser configuration as JSON") private String parserConfig; - @Schema(description = "分块总数") + @Schema(description = "Total chunk count") private Long chunkCount; - @Schema(description = "总Token数") + @Schema(description = "Total token count") private Long tokenNum; - @Schema(description = "状态(0:禁用 1:启用)") + @Schema(description = "Status flag (0 disabled, 1 enabled)") private Integer status; - @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 = "Document count") private Integer documentCount; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java index 1fa4db1cd..d297ee403 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java @@ -10,82 +10,82 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @Data -@Schema(description = "知识库文档") +@Schema(description = "Knowledge-base document") @JsonIgnoreProperties(ignoreUnknown = true) public class KnowledgeFilesDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - @Schema(description = "唯一标识") + @Schema(description = "Unique ID") private String id; - @Schema(description = "文档ID") + @Schema(description = "Document ID") private String documentId; - @Schema(description = "知识库ID") + @Schema(description = "Knowledge-base ID") private String datasetId; - @Schema(description = "文档名称") + @Schema(description = "Document name") private String name; - @Schema(description = "文档类型") + @Schema(description = "Document type") private String fileType; - @Schema(description = "文件大小(字节)") + @Schema(description = "File size in bytes") private Long fileSize; - @Schema(description = "文件路径") + @Schema(description = "File path") private String filePath; - @Schema(description = "解析进度 (0.0 ~ 1.0)") + @Schema(description = "Parse progress (0.0 to 1.0)") private Double progress; - @Schema(description = "缩略图 (Base64 或 URL)") + @Schema(description = "Thumbnail (Base64 or URL)") private String thumbnail; - @Schema(description = "解析耗时 (单位: 秒)") + @Schema(description = "Parse duration in seconds") private Double processDuration; - @Schema(description = "来源类型 (local, s3, url 等)") + @Schema(description = "Source type (local, s3, url, and so on)") private String sourceType; - @Schema(description = "元数据字段 (Map 格式)") + @Schema(description = "Metadata fields as a map") private Map metaFields; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") private String chunkMethod; - @Schema(description = "解析器配置") + @Schema(description = "Parser configuration") private Map parserConfig; - @Schema(description = "可用状态 (1: 启用/正常, 0: 禁用/失效)") + @Schema(description = "Availability status (1 enabled/healthy, 0 disabled/invalid)") private String status; - @Schema(description = "运行状态 (UNSTART/RUNNING/CANCEL/DONE/FAIL)") + @Schema(description = "Run state (UNSTART/RUNNING/CANCEL/DONE/FAIL)") private String run; - @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 = "Chunk count") private Integer chunkCount; - @Schema(description = "Token数量") + @Schema(description = "Token count") private Long tokenCount; - @Schema(description = "解析错误信息") + @Schema(description = "Parse error message") private String error; - // 文档解析状态常量定义 + // Document parse-status constants. private static final Integer STATUS_UNSTART = 0; private static final Integer STATUS_RUNNING = 1; private static final Integer STATUS_CANCEL = 2; @@ -93,14 +93,14 @@ public class KnowledgeFilesDTO implements Serializable { private static final Integer STATUS_FAIL = 4; /** - * 获取文档解析状态码(基于run字段转换) + * Get the parse status code derived from the run field. */ public Integer getParseStatusCode() { if (run == null) { return STATUS_UNSTART; } - // RAGFlow根据run字段的值直接映射到对应的状态码 + // RAGFlow maps the run field directly to a local status code. switch (run.toUpperCase()) { case "RUNNING": return STATUS_RUNNING; @@ -116,4 +116,4 @@ public class KnowledgeFilesDTO implements Serializable { } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/agent/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/agent/AgentDTO.java index 171e981a8..c7b5a0a22 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/agent/AgentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/agent/AgentDTO.java @@ -8,31 +8,31 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.*; -@Schema(description = "智能体 (Agent) 管理聚合 DTO") +@Schema(description = "Aggregate DTOs for agent management") public class AgentDTO { - // ========== 1. Agent 管理 (CRUD) - 对应 RAGFlow_Agent接口详解 ========== + // ========== 1. Agent management (CRUD) ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Agent 创建请求") + @Schema(description = "Agent create request") public static class CreateReq implements Serializable { - @Schema(description = "Agent 标题", requiredMode = Schema.RequiredMode.REQUIRED, example = "My Agent") - @NotBlank(message = "Agent 标题不能为空") + @Schema(description = "Agent title", requiredMode = Schema.RequiredMode.REQUIRED, example = "My Agent") + @NotBlank(message = "Agent title cannot be empty") @JsonProperty("title") private String title; - @Schema(description = "DSL 定义 (画布 JSON)", requiredMode = Schema.RequiredMode.REQUIRED) - @NotNull(message = "DSL 定义不能为空") + @Schema(description = "DSL definition as canvas JSON", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "DSL definition cannot be empty") @JsonProperty("dsl") private Map dsl; - @Schema(description = "描述", example = "这是一个测试 Agent") + @Schema(description = "Description", example = "This is a test agent") @JsonProperty("description") private String description; - @Schema(description = "头像 URL", example = "http://example.com/avatar.png") + @Schema(description = "Avatar URL", example = "http://example.com/avatar.png") @JsonProperty("avatar") private String avatar; } @@ -41,21 +41,21 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Agent 更新请求") + @Schema(description = "Agent update request") public static class UpdateReq implements Serializable { - @Schema(description = "Agent 标题", example = "Updated Agent") + @Schema(description = "Agent title", example = "Updated Agent") @JsonProperty("title") private String title; - @Schema(description = "DSL 定义 (画布 JSON)") + @Schema(description = "DSL definition as canvas JSON") @JsonProperty("dsl") private Map dsl; - @Schema(description = "描述") + @Schema(description = "Description") @JsonProperty("description") private String description; - @Schema(description = "头像 URL") + @Schema(description = "Avatar URL") @JsonProperty("avatar") private String avatar; } @@ -64,33 +64,33 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Agent 列表请求") + @Schema(description = "Agent list request") public static class ListReq implements Serializable { - @Schema(description = "页码", defaultValue = "1") + @Schema(description = "Page number", defaultValue = "1") @JsonProperty("page") @Builder.Default private Integer page = 1; - @Schema(description = "每页大小", defaultValue = "10") + @Schema(description = "Page size", defaultValue = "10") @JsonProperty("page_size") @Builder.Default private Integer pageSize = 10; - @Schema(description = "排序字段", defaultValue = "update_time") + @Schema(description = "Sort field", defaultValue = "update_time") @JsonProperty("orderby") @Builder.Default private String orderby = "update_time"; - @Schema(description = "是否降序", defaultValue = "true") + @Schema(description = "Whether sorting is descending", defaultValue = "true") @JsonProperty("desc") @Builder.Default private Boolean desc = true; - @Schema(description = "Agent ID 过滤") + @Schema(description = "Filter by agent ID") @JsonProperty("id") private String id; - @Schema(description = "标题模糊搜索") + @Schema(description = "Fuzzy search by title") @JsonProperty("title") private String title; } @@ -99,58 +99,58 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Agent 响应对象") + @Schema(description = "Agent response object") public static class AgentVO implements Serializable { @Schema(description = "Agent ID") @JsonProperty("id") private String id; - @Schema(description = "标题") + @Schema(description = "Title") @JsonProperty("title") private String title; - @Schema(description = "描述") + @Schema(description = "Description") @JsonProperty("description") private String description; - @Schema(description = "头像") + @Schema(description = "Avatar") @JsonProperty("avatar") private String avatar; - @Schema(description = "DSL 定义") + @Schema(description = "DSL definition") @JsonProperty("dsl") private Map dsl; - @Schema(description = "创建者 ID") + @Schema(description = "Creator ID") @JsonProperty("user_id") private String userId; - @Schema(description = "画布分类") + @Schema(description = "Canvas category") @JsonProperty("canvas_category") private String canvasCategory; - @Schema(description = "创建时间 (时间戳)") + @Schema(description = "Creation time as a timestamp") @JsonProperty("create_time") private Long createTime; - @Schema(description = "更新时间 (时间戳)") + @Schema(description = "Update time as a timestamp") @JsonProperty("update_time") private Long updateTime; } - // ========== 2. Webhook 调试与追踪 - 对应 RAGFlow_Agent接口详解 ========== + // ========== 2. Webhook debugging and tracing ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Webhook 触发请求 (参数动态)") + @Schema(description = "Webhook trigger request") public static class WebhookTriggerReq implements Serializable { - @Schema(description = "输入变量", requiredMode = Schema.RequiredMode.REQUIRED) - @NotNull(message = "输入变量不能为空") + @Schema(description = "Input variables", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "Input variables cannot be empty") @JsonProperty("inputs") private Map inputs; - @Schema(description = "查询词", example = "Hello") + @Schema(description = "Query text", example = "Hello") @JsonProperty("query") private String query; } @@ -159,9 +159,9 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Webhook 追踪请求") + @Schema(description = "Webhook trace request") public static class WebhookTraceReq implements Serializable { - @Schema(description = "时间戳游标", example = "1700000000.0") + @Schema(description = "Timestamp cursor", example = "1700000000.0") @JsonProperty("since_ts") private Double sinceTs; @@ -174,21 +174,21 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Webhook 追踪响应") + @Schema(description = "Webhook trace response") public static class WebhookTraceVO implements Serializable { @Schema(description = "Webhook ID") @JsonProperty("webhook_id") private String webhookId; - @Schema(description = "是否结束") + @Schema(description = "Whether the trace is finished") @JsonProperty("finished") private Boolean finished; - @Schema(description = "下一次查询的时间戳游标") + @Schema(description = "Timestamp cursor for the next query") @JsonProperty("next_since_ts") private Double nextSinceTs; - @Schema(description = "事件列表") + @Schema(description = "Event list") @JsonProperty("events") private List events; @@ -196,30 +196,30 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "追踪事件项") + @Schema(description = "Trace event item") public static class TraceEvent implements Serializable { - @Schema(description = "时间戳") + @Schema(description = "Timestamp") @JsonProperty("ts") private Double ts; - @Schema(description = "事件类型") + @Schema(description = "Event type") @JsonProperty("event") private String event; - @Schema(description = "事件数据") + @Schema(description = "Event data") @JsonProperty("data") private Object data; } } - // ========== 3. Agent 会话 (Session) - 对应 RAGFlow_Agent_Dify接口详解 ========== + // ========== 3. Agent sessions ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Session 创建请求") + @Schema(description = "Session create request") public static class SessionCreateReq implements Serializable { - @Schema(description = "用户 ID") + @Schema(description = "User ID") @JsonProperty("user_id") private String userId; } @@ -228,24 +228,24 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Session 列表请求") + @Schema(description = "Session list request") public static class SessionListReq implements Serializable { - @Schema(description = "页码", defaultValue = "1") + @Schema(description = "Page number", defaultValue = "1") @JsonProperty("page") @Builder.Default private Integer page = 1; - @Schema(description = "每页大小", defaultValue = "10") + @Schema(description = "Page size", defaultValue = "10") @JsonProperty("page_size") @Builder.Default private Integer pageSize = 10; - @Schema(description = "排序字段", defaultValue = "create_time") + @Schema(description = "Sort field", defaultValue = "create_time") @JsonProperty("orderby") @Builder.Default private String orderby = "create_time"; - @Schema(description = "是否降序", defaultValue = "true") + @Schema(description = "Whether sorting is descending", defaultValue = "true") @JsonProperty("desc") @Builder.Default private Boolean desc = true; @@ -254,11 +254,11 @@ public class AgentDTO { @JsonProperty("id") private String id; - @Schema(description = "用户 ID") + @Schema(description = "User ID") @JsonProperty("user_id") private String userId; - @Schema(description = "是否返回 DSL") + @Schema(description = "Whether to return DSL") @JsonProperty("dsl") @Builder.Default private Boolean dsl = false; @@ -268,11 +268,11 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Session 批量删除请求") + @Schema(description = "Session batch-delete request") public static class SessionBatchDeleteReq implements Serializable { - @Schema(description = "会话 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Session ID list", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("ids") - @NotEmpty(message = "ID列表不能为空") + @NotEmpty(message = "ID list cannot be empty") private List ids; } @@ -280,7 +280,7 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Session 响应对象") + @Schema(description = "Session response object") public static class SessionVO implements Serializable { @Schema(description = "Session ID") @JsonProperty("id") @@ -290,45 +290,45 @@ public class AgentDTO { @JsonProperty("agent_id") private String agentId; - @Schema(description = "用户 ID") + @Schema(description = "User ID") @JsonProperty("user_id") private String userId; - @Schema(description = "来源") + @Schema(description = "Source") @JsonProperty("source") private String source; - @Schema(description = "DSL 定义") + @Schema(description = "DSL definition") @JsonProperty("dsl") private Map dsl; - @Schema(description = "消息列表") + @Schema(description = "Message list") @JsonProperty("messages") private List> messages; } - // ========== 4. Agent 对话 (Completion) - 对应 RAGFlow_Agent_Dify接口详解 ========== + // ========== 4. Agent conversation (Completion) ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Completion 对话请求") + @Schema(description = "Completion conversation request") public static class CompletionReq implements Serializable { - @Schema(description = "会话 ID", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "会话 ID 不能为空") + @Schema(description = "Session ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Session ID cannot be empty") @JsonProperty("session_id") private String sessionId; - @Schema(description = "用户问题") + @Schema(description = "User question") @JsonProperty("question") private String question; - @Schema(description = "是否流式返回", defaultValue = "true") + @Schema(description = "Whether to stream the response", defaultValue = "true") @JsonProperty("stream") @Builder.Default private Boolean stream = true; - @Schema(description = "是否返回追踪信息", defaultValue = "false") + @Schema(description = "Whether to return trace information", defaultValue = "false") @JsonProperty("return_trace") @Builder.Default private Boolean returnTrace = false; @@ -338,49 +338,49 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Completion 对话响应") + @Schema(description = "Completion conversation response") public static class CompletionVO implements Serializable { - @Schema(description = "会话 ID") + @Schema(description = "Session ID") @JsonProperty("id") private String id; - @Schema(description = "回复内容") + @Schema(description = "Reply content") @JsonProperty("content") private String content; - @Schema(description = "引用来源") + @Schema(description = "Reference sources") @JsonProperty("reference") private Map reference; - @Schema(description = "追踪信息") + @Schema(description = "Trace information") @JsonProperty("trace") private List trace; } - // ========== 5. Dify 兼容检索 - 对应 RAGFlow_Agent_Dify接口详解 ========== + // ========== 5. Dify-compatible retrieval ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Dify 兼容检索请求") + @Schema(description = "Dify-compatible retrieval request") public static class DifyRetrievalReq implements Serializable { - @Schema(description = "知识库 ID") + @Schema(description = "Knowledge-base ID") @JsonProperty("knowledge_id") private String knowledgeId; - @Schema(description = "查询词") + @Schema(description = "Query") @JsonProperty("query") private String query; - @Schema(description = "检索设置") + @Schema(description = "Retrieval settings") @JsonProperty("retrieval_setting") private Map retrievalSetting; - @Schema(description = "元数据过滤条件") + @Schema(description = "Metadata filter conditions") @JsonProperty("metadata_condition") private Map metadataCondition; - @Schema(description = "是否使用知识图谱") + @Schema(description = "Whether to use the knowledge graph") @JsonProperty("use_kg") private Boolean useKg; } @@ -389,9 +389,9 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "Dify 兼容检索响应") + @Schema(description = "Dify-compatible retrieval response") public static class DifyRetrievalVO implements Serializable { - @Schema(description = "检索结果列表") + @Schema(description = "Retrieval result list") @JsonProperty("records") private List records; @@ -399,21 +399,21 @@ public class AgentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "检索记录") + @Schema(description = "Retrieval record") public static class Record implements Serializable { - @Schema(description = "内容") + @Schema(description = "Content") @JsonProperty("content") private String content; - @Schema(description = "相似度分数") + @Schema(description = "Similarity score") @JsonProperty("score") private Double score; - @Schema(description = "标题") + @Schema(description = "Title") @JsonProperty("title") private String title; - @Schema(description = "元数据") + @Schema(description = "Metadata") @JsonProperty("metadata") private Map metadata; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/bot/BotDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/bot/BotDTO.java index 53d4ac431..e8e9333e8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/bot/BotDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/bot/BotDTO.java @@ -8,29 +8,29 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.*; -@Schema(description = "外部机器人 (Bot) 聚合 DTO") +@Schema(description = "External bot aggregate DTO") public class BotDTO { - // ========== 1. SearchBot (检索机器人) ========== + // ========== 1. SearchBot ========== - // 对应 /api/v1/searchbots/ask + // Maps to /api/v1/searchbots/ask @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "SearchBot 提问请求") + @Schema(description = "SearchBot ask request") public static class SearchAskReq implements Serializable { - @Schema(description = "用户问题", requiredMode = Schema.RequiredMode.REQUIRED, example = "What is RAG?") - @NotBlank(message = "问题不能为空") + @Schema(description = "User question", requiredMode = Schema.RequiredMode.REQUIRED, example = "What is RAG?") + @NotBlank(message = "Question cannot be empty") @JsonProperty("question") private String question; - @Schema(description = "是否返回引用", defaultValue = "false") + @Schema(description = "Whether to return references", defaultValue = "false") @JsonProperty("quote") @Builder.Default private Boolean quote = false; - @Schema(description = "是否流式返回", defaultValue = "true") + @Schema(description = "Whether to stream the response", defaultValue = "true") @JsonProperty("stream") @Builder.Default private Boolean stream = true; @@ -40,50 +40,50 @@ public class BotDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "SearchBot 提问响应") + @Schema(description = "SearchBot ask response") public static class SearchAskVO implements Serializable { - @Schema(description = "回答内容") + @Schema(description = "Answer content") @JsonProperty("answer") private String answer; - @Schema(description = "引用来源 (Value 结构通常对应 RetrievalDTO.HitVO)") + @Schema(description = "Reference sources, usually aligned with RetrievalDTO.HitVO") @JsonProperty("reference") private Map reference; } - // 对应 /api/v1/searchbots/related_questions + // Maps to /api/v1/searchbots/related_questions @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "相关问题请求") + @Schema(description = "Related-question request") public static class RelatedQuestionReq implements Serializable { - @Schema(description = "用户问题", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "问题不能为空") + @Schema(description = "User question", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Question cannot be empty") @JsonProperty("question") private String question; } - // 对应 /api/v1/searchbots/mindmap + // Maps to /api/v1/searchbots/mindmap @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "思维导图请求") + @Schema(description = "Mind-map request") public static class MindMapReq implements Serializable { - @Schema(description = "用户问题", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "问题不能为空") + @Schema(description = "User question", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Question cannot be empty") @JsonProperty("question") private String question; } - // ========== 2. AgentBot (嵌入式 Agent) ========== + // ========== 2. AgentBot ========== - // 对应 /api/v1/agentbots/{id}/inputs + // Maps to /api/v1/agentbots/{id}/inputs @Data @Builder @AllArgsConstructor - @Schema(description = "AgentBot 输入参数请求") + @Schema(description = "AgentBot input-definition request") public static class AgentInputsReq implements Serializable { } @@ -91,35 +91,35 @@ public class BotDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "AgentBot 输入参数定义响应") + @Schema(description = "AgentBot input-definition response") public static class AgentInputsVO implements Serializable { - @Schema(description = "表单变量定义列表") + @Schema(description = "Form variable definition list") @JsonProperty("variables") private List> variables; } - // 对应 /api/v1/agentbots/{id}/completions + // Maps to /api/v1/agentbots/{id}/completions @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "AgentBot 对话请求") + @Schema(description = "AgentBot conversation request") public static class AgentCompletionReq implements Serializable { - @Schema(description = "输入参数值") + @Schema(description = "Input parameter values") @JsonProperty("inputs") private Map inputs; - @Schema(description = "用户查询", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "查询内容不能为空") + @Schema(description = "User query", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Query content cannot be empty") @JsonProperty("question") private String question; - @Schema(description = "是否流式返回", defaultValue = "true") + @Schema(description = "Whether to stream the response", defaultValue = "true") @JsonProperty("stream") @Builder.Default private Boolean stream = true; - @Schema(description = "会话 ID") + @Schema(description = "Session ID") @JsonProperty("session_id") private String sessionId; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatCompletionRequest.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatCompletionRequest.java index 681b13d37..709130478 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatCompletionRequest.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatCompletionRequest.java @@ -10,41 +10,41 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 聊天对话请求 DTO (OpenAI 兼容格式) + * Chat completion request DTO in an OpenAI-compatible format. */ @Data -@Schema(description = "聊天对话请求") +@Schema(description = "Chat completion request") public class ChatCompletionRequest implements Serializable { - @Schema(description = "模型标识 (对应 agent_id 或 bot_id)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Model identifier, usually agent_id or bot_id", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("model") private String model; - @Schema(description = "对话消息列表", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Conversation message list", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("messages") private List messages; - @Schema(description = "是否流式返回", defaultValue = "false") + @Schema(description = "Whether to stream the response", defaultValue = "false") @JsonProperty("stream") private Boolean stream = false; - @Schema(description = "温度系数 (0-1)", defaultValue = "0.7") + @Schema(description = "Temperature from 0 to 1", defaultValue = "0.7") @JsonProperty("temperature") private Double temperature; - @Schema(description = "Session ID (可选,用于延续会话)") + @Schema(description = "Optional session ID used to continue a conversation") @JsonProperty("session_id") private String sessionId; - @Schema(description = "其他RAGFlow特定参数 (可选)") + @Schema(description = "Additional optional RAGFlow-specific parameters") private Map extra; @Data public static class Message implements Serializable { - @Schema(description = "角色 (system, user, assistant)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Role, such as system, user, or assistant", requiredMode = Schema.RequiredMode.REQUIRED) private String role; - @Schema(description = "内容", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Message content", requiredMode = Schema.RequiredMode.REQUIRED) private String content; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatDTO.java index d7ca8d60a..03fe6cadc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/chat/ChatDTO.java @@ -9,514 +9,516 @@ import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.*; /** - * 对话管理聚合 DTO + * Aggregate DTOs for chat management. *

- * 容器类,内含对话助手、会话和消息的所有请求/响应对象。 + * Container for assistant, session, and message request/response objects. *

*/ -@Schema(description = "对话管理聚合 DTO") +@Schema(description = "Aggregate DTOs for chat management") public class ChatDTO { - // ========== 1. 对话助手 (Assistant/Bot) 相关 ========== + // ========== 1. Assistant/Bot ========== /** - * 提示词配置 + * Prompt configuration. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "提示词配置") + @Schema(description = "Prompt configuration") public static class PromptConfig implements Serializable { - @Schema(description = "系统提示词", example = "你是一个专业的客服助手...") + @Schema(description = "System prompt", example = "You are a professional support assistant...") @JsonProperty("prompt") private String systemPrompt; - @Schema(description = "开场白", example = "您好,我是您的智能助手,请问有什么可以帮您?") + @Schema(description = "Opening message", example = "Hello, I am your assistant. How can I help?") private String opener; - @Schema(description = "空结果回复", example = "抱歉,我没有找到相关信息。") + @Schema(description = "Reply when no result is found", example = "Sorry, I could not find relevant information.") @JsonProperty("empty_response") private String emptyResponse; - @Schema(description = "是否展示引用", example = "true") + @Schema(description = "Whether to show citations", example = "true") @JsonProperty("show_quote") private Boolean quote; - @Schema(description = "是否启用 TTS", example = "false") + @Schema(description = "Whether TTS is enabled", example = "false") private Boolean tts; - @Schema(description = "相似度阈值 (0.0 - 1.0)", example = "0.2") + @Schema(description = "Similarity threshold (0.0 - 1.0)", example = "0.2") @JsonProperty("similarity_threshold") private Float similarityThreshold; - @Schema(description = "关键词相似度权重 (0.0 - 1.0)", example = "0.7") + @Schema(description = "Keyword similarity weight (0.0 - 1.0)", example = "0.7") @JsonProperty("keywords_similarity_weight") private Float vectorSimilarityWeight; - @Schema(description = "检索 Top N", example = "6") + @Schema(description = "Top N retrieval count", example = "6") @JsonProperty("top_n") private Integer topK; - @Schema(description = "Rerank 模型", example = "rerank_model_001") + @Schema(description = "Rerank model", example = "rerank_model_001") @JsonProperty("rerank_model") private String rerankId; - @Schema(description = "是否启用多轮对话优化", example = "false") + @Schema(description = "Whether multi-turn refinement is enabled", example = "false") @JsonProperty("refine_multiturn") private Boolean refineMultigraph; - @Schema(description = "变量列表") + @Schema(description = "Variable list") private List> variables; } /** - * LLM 配置 + * LLM configuration. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "LLM 模型配置") + @Schema(description = "LLM model configuration") public static class LLMConfig implements Serializable { - @NotBlank(message = "模型名称不能为空") - @Schema(description = "模型名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "gpt-4") + @NotBlank(message = "Model name cannot be empty") + @Schema(description = "Model name", requiredMode = Schema.RequiredMode.REQUIRED, example = "gpt-4") @JsonProperty("model_name") private String modelName; - @Schema(description = "温度参数 (0.0 - 2.0)", example = "0.7") + @Schema(description = "Temperature (0.0 - 2.0)", example = "0.7") private Float temperature; - @Schema(description = "Top P 采样", example = "0.9") + @Schema(description = "Top-p sampling", example = "0.9") @JsonProperty("top_p") private Float topP; - @Schema(description = "最大 Token 数", example = "4096") + @Schema(description = "Maximum token count", example = "4096") @JsonProperty("max_tokens") private Integer maxTokens; - @Schema(description = "存在惩罚", example = "0.0") + @Schema(description = "Presence penalty", example = "0.0") @JsonProperty("presence_penalty") private Float presencePenalty; - @Schema(description = "频率惩罚", example = "0.0") + @Schema(description = "Frequency penalty", example = "0.0") @JsonProperty("frequency_penalty") private Float frequencyPenalty; } /** - * 创建助手请求 + * Create assistant request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "创建助手请求") + @Schema(description = "Create assistant request") public static class AssistantCreateReq implements Serializable { - @NotBlank(message = "助手名称不能为空") - @Schema(description = "助手名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "智能客服助手") + @NotBlank(message = "Assistant name cannot be empty") + @Schema(description = "Assistant name", requiredMode = Schema.RequiredMode.REQUIRED, + example = "Support Assistant") private String name; - @Schema(description = "助手头像 (Base64 编码)", example = "") + @Schema(description = "Assistant avatar in Base64", example = "") private String avatar; - @Schema(description = "关联的知识库 ID 列表", example = "[\"kb_001\", \"kb_002\"]") + @Schema(description = "Associated knowledge base ID list", example = "[\"kb_001\", \"kb_002\"]") @JsonProperty("dataset_ids") private List datasetIds; - @Schema(description = "助手描述", example = "这是一个智能客服助手") + @Schema(description = "Assistant description", example = "This is an intelligent support assistant") private String description; - @Schema(description = "LLM 模型配置") + @Schema(description = "LLM model configuration") @JsonProperty("llm") private LLMConfig llm; - @Schema(description = "提示词配置") + @Schema(description = "Prompt configuration") @JsonProperty("prompt") private PromptConfig promptConfig; } /** - * 更新助手请求 + * Update assistant request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "更新助手请求") + @Schema(description = "Update assistant request") public static class AssistantUpdateReq implements Serializable { - @Schema(description = "助手名称", example = "智能客服助手 V2") + @Schema(description = "Assistant name", example = "Support Assistant V2") private String name; - @Schema(description = "助手头像 (Base64 编码)", example = "") + @Schema(description = "Assistant avatar in Base64", example = "") private String avatar; - @Schema(description = "关联的知识库 ID 列表", example = "[\"kb_001\", \"kb_002\"]") + @Schema(description = "Associated knowledge base ID list", example = "[\"kb_001\", \"kb_002\"]") @JsonProperty("dataset_ids") private List datasetIds; - @Schema(description = "助手描述", example = "这是一个智能客服助手") + @Schema(description = "Assistant description", example = "This is an intelligent support assistant") private String description; - @Schema(description = "LLM 模型配置") + @Schema(description = "LLM model configuration") @JsonProperty("llm") private LLMConfig llm; - @Schema(description = "提示词配置") + @Schema(description = "Prompt configuration") @JsonProperty("prompt") private PromptConfig promptConfig; } /** - * 查询助手列表请求 + * List assistant request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "查询助手列表请求") + @Schema(description = "List assistant request") public static class AssistantListReq implements Serializable { - @Schema(description = "页码 (从 1 开始)", example = "1") + @Schema(description = "Page number, starting from 1", example = "1") private Integer page; - @Schema(description = "每页数量", example = "30") + @Schema(description = "Page size", example = "30") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "按名称过滤 (模糊匹配)", example = "客服") + @Schema(description = "Filter by name using fuzzy matching", example = "support") private String name; - @Schema(description = "排序字段: create_time / update_time", example = "create_time") + @Schema(description = "Sort field: create_time / update_time", example = "create_time") private String orderby; - @Schema(description = "是否降序", example = "true") + @Schema(description = "Whether sorting is descending", example = "true") private Boolean desc; - @Schema(description = "按 ID 精确筛选", example = "assistant_001") + @Schema(description = "Exact filter by ID", example = "assistant_001") private String id; } /** - * 助手详情 VO + * Assistant details. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "助手详情 VO") + @Schema(description = "Assistant details") public static class AssistantVO implements Serializable { - @Schema(description = "助手 ID", example = "assistant_001") + @Schema(description = "Assistant ID", example = "assistant_001") private String id; - @Schema(description = "租户 ID", example = "tenant_001") + @Schema(description = "Tenant ID", example = "tenant_001") @JsonProperty("tenant_id") private String tenantId; - @Schema(description = "助手名称", example = "智能客服助手") + @Schema(description = "Assistant name", example = "Support Assistant") private String name; - @Schema(description = "助手头像", example = "") + @Schema(description = "Assistant avatar", example = "") private String avatar; - @Schema(description = "关联的知识库 ID 列表") + @Schema(description = "Associated knowledge base ID list") @JsonProperty("dataset_ids") private List datasetIds; - @Schema(description = "关联的知识库列表 (详情)") + @Schema(description = "Associated knowledge base details") private List datasets; - @Schema(description = "助手描述") + @Schema(description = "Assistant description") private String description; - @Schema(description = "LLM 模型配置") + @Schema(description = "LLM model configuration") @JsonProperty("llm") private LLMConfig llm; - @Schema(description = "提示词配置") + @Schema(description = "Prompt configuration") @JsonProperty("prompt") private PromptConfig promptConfig; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; } /** - * 删除助手请求 + * Delete assistant request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "删除助手请求") + @Schema(description = "Delete assistant request") public static class AssistantDeleteReq implements Serializable { - @Schema(description = "要删除的助手 ID 列表", example = "[\"assistant_001\", \"assistant_002\"]") + @Schema(description = "Assistant ID list to delete", example = "[\"assistant_001\", \"assistant_002\"]") private List ids; } - // ========== 2. 会话 (Session) 相关 ========== + // ========== 2. Sessions ========== /** - * 创建会话请求 + * Create session request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "创建会话请求") + @Schema(description = "Create session request") public static class SessionCreateReq implements Serializable { - @Schema(description = "会话名称", example = "技术咨询会话") + @Schema(description = "Session name", example = "Technical consultation") private String name; - @Schema(description = "用户 ID", example = "user_001") + @Schema(description = "User ID", example = "user_001") @JsonProperty("user_id") private String userId; } /** - * 更新会话请求 + * Update session request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "更新会话请求") + @Schema(description = "Update session request") public static class SessionUpdateReq implements Serializable { - @Schema(description = "会话名称", example = "技术咨询会话 - 更新") + @Schema(description = "Session name", example = "Technical consultation - updated") private String name; } /** - * 查询会话列表请求 + * List session request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "查询会话列表请求") + @Schema(description = "List session request") public static class SessionListReq implements Serializable { - @Schema(description = "助手 ID", example = "assistant_001") + @Schema(description = "Assistant ID", example = "assistant_001") @JsonProperty("assistant_id") private String assistantId; - @Schema(description = "页码 (从 1 开始)", example = "1") + @Schema(description = "Page number, starting from 1", example = "1") private Integer page; - @Schema(description = "每页数量", example = "30") + @Schema(description = "Page size", example = "30") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "按名称过滤", example = "技术") + @Schema(description = "Filter by name", example = "technical") private String name; - @Schema(description = "排序字段", example = "create_time") + @Schema(description = "Sort field", example = "create_time") private String orderby; - @Schema(description = "是否降序", example = "true") + @Schema(description = "Whether sorting is descending", example = "true") private Boolean desc; - @Schema(description = "会话 ID 精确筛选", example = "session_001") + @Schema(description = "Exact session ID filter", example = "session_001") private String id; - @Schema(description = "用户标识筛选", example = "user_001") + @Schema(description = "User identifier filter", example = "user_001") @JsonProperty("user_id") private String userId; } /** - * 会话详情 VO + * Session details. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "会话详情 VO") + @Schema(description = "Session details") public static class SessionVO implements Serializable { - @Schema(description = "会话 ID", example = "session_001") + @Schema(description = "Session ID", example = "session_001") private String id; - @Schema(description = "助手 ID", example = "assistant_001") + @Schema(description = "Assistant ID", example = "assistant_001") @JsonProperty("chat_id") private String chatId; - @Schema(description = "助手 ID (兼容旧版)", example = "assistant_001") + @Schema(description = "Assistant ID for backward compatibility", example = "assistant_001") @JsonProperty("assistant_id") private String assistantId; - @Schema(description = "会话名称", example = "技术咨询会话") + @Schema(description = "Session name", example = "Technical consultation") private String name; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; - @Schema(description = "创建日期", example = "2024-05-01 10:00:00") + @Schema(description = "Creation date", example = "2024-05-01 10:00:00") @JsonProperty("create_date") private String createDate; - @Schema(description = "更新日期", example = "2024-05-01 10:00:00") + @Schema(description = "Update date", example = "2024-05-01 10:00:00") @JsonProperty("update_date") private String updateDate; - @Schema(description = "用户 ID", example = "user_001") + @Schema(description = "User ID", example = "user_001") @JsonProperty("user_id") private String userId; - @Schema(description = "对话历史消息列表") + @Schema(description = "Conversation history message list") private List> messages; } /** - * 删除会话请求 + * Delete session request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "删除会话请求") + @Schema(description = "Delete session request") public static class SessionDeleteReq implements Serializable { - @Schema(description = "要删除的会话 ID 列表", example = "[\"session_001\", \"session_002\"]") + @Schema(description = "Session ID list to delete", example = "[\"session_001\", \"session_002\"]") private List ids; } - // ========== 3. 消息/对话 (Completion) 相关 ========== + // ========== 3. Messages and completions ========== /** - * 发送消息请求 + * Send-message request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "发送消息请求") + @Schema(description = "Send-message request") public static class CompletionReq implements Serializable { - @NotBlank(message = "问题内容不能为空") - @Schema(description = "用户问题", requiredMode = Schema.RequiredMode.REQUIRED, example = "请介绍一下你们的产品") + @NotBlank(message = "Question content cannot be empty") + @Schema(description = "User question", requiredMode = Schema.RequiredMode.REQUIRED, + example = "Please introduce your product") private String question; - @Schema(description = "是否使用流式响应 (SSE)", example = "true") + @Schema(description = "Whether to use streaming response (SSE)", example = "true") @Builder.Default private Boolean stream = true; - @NotBlank(message = "会话 ID 不能为空") - @Schema(description = "会话 ID (可选,不传则创建新会话)", example = "session_001") + @NotBlank(message = "Session ID cannot be empty") + @Schema(description = "Session ID. Creates a new session when omitted", example = "session_001") @JsonProperty("session_id") private String sessionId; - @Schema(description = "是否展示引用", example = "true") + @Schema(description = "Whether to show citations", example = "true") private Boolean quote; - @Schema(description = "指定检索的文档 ID 列表 (逗号分隔)", example = "doc_001,doc_002") + @Schema(description = "Comma-separated document ID list for retrieval", example = "doc_001,doc_002") @JsonProperty("doc_ids") private String docIds; - @Schema(description = "元数据过滤条件") + @Schema(description = "Metadata filter conditions") @JsonProperty("metadata_condition") private Map metadataCondition; } /** - * 消息响应 VO + * Message response. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "消息响应 VO") + @Schema(description = "Message response") public static class CompletionVO implements Serializable { - @Schema(description = "AI 回答内容") + @Schema(description = "AI answer content") private String answer; - @Schema(description = "引用信息") + @Schema(description = "Citation information") private Reference reference; - @Schema(description = "会话 ID", example = "session_001") + @Schema(description = "Session ID", example = "session_001") @JsonProperty("session_id") private String sessionId; - @Schema(description = "任务 ID (用于流式响应追踪)", example = "task_001") + @Schema(description = "Task ID used for streaming-response tracking", example = "task_001") @JsonProperty("task_id") private String taskId; /** - * 引用信息 (检索命中结果) + * Citation information based on retrieval hits. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "引用信息") + @Schema(description = "Citation information") public static class Reference implements Serializable { - @Schema(description = "命中的文档块列表") + @Schema(description = "Matched document chunk list") private List chunks; - @Schema(description = "文档聚合信息") + @Schema(description = "Aggregated document information") @JsonProperty("doc_aggs") private List docAggs; } /** - * 文档聚合信息 + * Aggregated document information. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文档聚合信息") + @Schema(description = "Aggregated document information") public static class DocAgg implements Serializable { - @Schema(description = "文档 ID", example = "doc_001") + @Schema(description = "Document ID", example = "doc_001") @JsonProperty("doc_id") private String docId; - @Schema(description = "文档名称", example = "产品手册.pdf") + @Schema(description = "Document name", example = "product-manual.pdf") @JsonProperty("doc_name") private String docName; - @Schema(description = "命中次数", example = "3") + @Schema(description = "Hit count", example = "3") private Integer count; } } /** - * 简易知识库 VO (用于 Assistant 列表) + * Simplified knowledge base information for assistant lists. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "简易知识库 VO") + @Schema(description = "Simplified knowledge base information") public static class SimpleDatasetVO implements Serializable { - @Schema(description = "知识库 ID") + @Schema(description = "Knowledge base ID") private String id; - @Schema(description = "知识库名称") + @Schema(description = "Knowledge base name") private String name; - @Schema(description = "头像") + @Schema(description = "Avatar") private String avatar; - @Schema(description = "分块数量") + @Schema(description = "Chunk count") @JsonProperty("chunk_num") private Integer chunkNum; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/common/CommonDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/common/CommonDTO.java index ec3b597e6..fc195636a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/common/CommonDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/common/CommonDTO.java @@ -8,23 +8,23 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.*; -@Schema(description = "通用扩展功能 DTO") +@Schema(description = "Common extension DTO") public class CommonDTO { - // ========== 1. 引用详情 (detail_share_embedded) ========== + // ========== 1. Reference details (detail_share_embedded) ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "引用详情请求") + @Schema(description = "Reference-detail request") public static class ReferenceDetailReq implements Serializable { - @Schema(description = "切片 ID", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "切片 ID 不能为空") + @Schema(description = "Chunk ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Chunk ID cannot be empty") @JsonProperty("chunk_id") private String chunkId; - @Schema(description = "知识库 ID") + @Schema(description = "Knowledge-base ID") @JsonProperty("knowledge_id") private String knowledgeId; } @@ -33,47 +33,47 @@ public class CommonDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "引用详情响应") + @Schema(description = "Reference-detail response") public static class ReferenceDetailVO implements Serializable { - @Schema(description = "切片 ID") + @Schema(description = "Chunk ID") @JsonProperty("chunk_id") private String chunkId; - @Schema(description = "完整内容") + @Schema(description = "Full content") @JsonProperty("content_with_weight") private String contentWithWeight; - @Schema(description = "文档名称") + @Schema(description = "Document name") @JsonProperty("doc_name") private String docName; - @Schema(description = "图片 ID 列表") + @Schema(description = "Image ID list") @JsonProperty("img_id") - private String imageId; // 注意:RAGFlow 有时返回 String 有时返回 List,需根据实际情况确认,暂定 String 用于 ID + private String imageId; // RAGFlow sometimes returns a String and sometimes a List; kept as String for now. - @Schema(description = "文档 ID") + @Schema(description = "Document ID") @JsonProperty("doc_id") private String docId; } - // ========== 2. 通用问答 (ask_about) - 调试用 ========== + // ========== 2. Generic Q&A (ask_about) for debugging ========== @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "通用问答请求 (调试用)") + @Schema(description = "Generic Q&A request for debugging") public static class AskAboutReq implements Serializable { - @Schema(description = "用户问题", requiredMode = Schema.RequiredMode.REQUIRED, example = "What is this dataset about?") - @NotBlank(message = "问题不能为空") + @Schema(description = "User question", requiredMode = Schema.RequiredMode.REQUIRED, example = "What is this dataset about?") + @NotBlank(message = "Question cannot be empty") @JsonProperty("question") private String question; - @Schema(description = "数据集 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED) - @NotEmpty(message = "数据集列表不能为空") + @Schema(description = "Dataset ID list", requiredMode = Schema.RequiredMode.REQUIRED) + @NotEmpty(message = "Dataset list cannot be empty") @JsonProperty("dataset_ids") private List datasetIds; } - // 响应通常复用 String 或者简单的 Map 结构,视具体实现而定,暂不定义专用 VO + // Responses usually reuse String or a simple Map structure, so no dedicated VO is defined here yet. } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/dataset/DatasetDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/dataset/DatasetDTO.java index e800a17bb..c60d3908b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/dataset/DatasetDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/dataset/DatasetDTO.java @@ -11,122 +11,124 @@ import com.fasterxml.jackson.annotation.JsonInclude; import jakarta.validation.constraints.*; /** - * 知识库管理聚合 DTO + * Aggregate DTOs for knowledge base management. *

- * 容器类,内含知识库模块所有请求/响应对象的静态内部类定义。 + * Container for request/response types used by the knowledge base module. *

*/ -@Schema(description = "知识库管理聚合 DTO") +@Schema(description = "Aggregate DTOs for knowledge base management") @JsonIgnoreProperties(ignoreUnknown = true) public class DatasetDTO { - // ========== 通用内部类 ========== + // ========== Shared nested types ========== /** - * 解析器配置 + * Parser configuration. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "解析器配置") + @Schema(description = "Parser configuration") @JsonIgnoreProperties(ignoreUnknown = true) public static class ParserConfig implements Serializable { - @Schema(description = "分块 token 数量", example = "128") + @Schema(description = "Chunk token count", example = "128") @JsonProperty("chunk_token_num") private Integer chunkTokenNum; - @Schema(description = "分隔符", example = "\\n!?;。;!?") + @Schema(description = "Delimiter", example = "\\n!?;.;!?") private String delimiter; - @Schema(description = "布局识别模型: DeepDOC / Simple", example = "DeepDOC") + @Schema(description = "Layout recognition model: DeepDOC / Simple", example = "DeepDOC") @JsonProperty("layout_recognize") private String layoutRecognize; - @Schema(description = "是否将 Excel 转为 HTML", example = "false") + @Schema(description = "Whether to convert Excel files to HTML", example = "false") private Boolean html4excel; - @Schema(description = "自动生成关键词数量 (0 表示关闭)", example = "0") + @Schema(description = "Auto-generated keyword count (0 disables it)", example = "0") @JsonProperty("auto_keywords") private Integer autoKeywords; - @Schema(description = "自动生成问题数量 (0 表示关闭)", example = "0") + @Schema(description = "Auto-generated question count (0 disables it)", example = "0") @JsonProperty("auto_questions") private Integer autoQuestions; } - // ========== 请求类 ========== + // ========== Requests ========== /** - * 创建知识库请求 (映射接口 1: create) + * Create knowledge base request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "创建知识库请求") + @Schema(description = "Create knowledge base request") @JsonIgnoreProperties(ignoreUnknown = true) public static class CreateReq implements Serializable { - @NotBlank(message = "知识库名称不能为空") - @Schema(description = "知识库名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "my_dataset") + @NotBlank(message = "Knowledge base name cannot be empty") + @Schema(description = "Knowledge base name", requiredMode = Schema.RequiredMode.REQUIRED, example = "my_dataset") private String name; - @Schema(description = "知识库头像 (Base64 编码)", example = "") + @Schema(description = "Knowledge base avatar in Base64", example = "") private String avatar; - @Schema(description = "知识库描述", example = "用于存储产品文档") + @Schema(description = "Knowledge base description", example = "Used to store product documents") private String description; - @Schema(description = "嵌入模型名称", example = "BAAI/bge-large-zh-v1.5") + @Schema(description = "Embedding model name", example = "text-embedding-3-large") @JsonProperty("embedding_model") private String embeddingModel; - @Schema(description = "权限设置: me / team", example = "me") + @Schema(description = "Permission setting: me / team", example = "me") private String permission; - @Schema(description = "分块方法: naive / manual / qa / table / paper / book / laws / presentation / picture / one / knowledge_graph / email", example = "naive") + @Schema(description = "Chunking method: naive / manual / qa / table / paper / book / laws / presentation / picture / one / knowledge_graph / email", + example = "naive") @JsonProperty("chunk_method") private String chunkMethod; - @Schema(description = "解析器配置") + @Schema(description = "Parser configuration") @JsonProperty("parser_config") private ParserConfig parserConfig; } /** - * 更新知识库请求 (映射接口 4: update) + * Update knowledge base request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "更新知识库请求") + @Schema(description = "Update knowledge base request") @JsonIgnoreProperties(ignoreUnknown = true) public static class UpdateReq implements Serializable { - @Schema(description = "知识库名称", example = "updated_dataset") + @Schema(description = "Knowledge base name", example = "updated_dataset") private String name; - @Schema(description = "知识库头像 (Base64 编码)", example = "") + @Schema(description = "Knowledge base avatar in Base64", example = "") private String avatar; - @Schema(description = "知识库描述", example = "更新后的描述") + @Schema(description = "Knowledge base description", example = "Updated description") private String description; - @Schema(description = "权限设置: me / team", example = "team") + @Schema(description = "Permission setting: me / team", example = "team") private String permission; - @Schema(description = "嵌入模型名称", example = "BAAI/bge-large-zh-v1.5") + @Schema(description = "Embedding model name", example = "text-embedding-3-large") @JsonProperty("embedding_model") private String embeddingModel; - @Schema(description = "分块方法: naive / manual / qa / table / paper / book / laws / presentation / picture / one / knowledge_graph / email", example = "naive") + @Schema(description = "Chunking method: naive / manual / qa / table / paper / book / laws / presentation / picture / one / knowledge_graph / email", + example = "naive") @JsonProperty("chunk_method") private String chunkMethod; - @Schema(description = "解析器配置") + @Schema(description = "Parser configuration") @JsonProperty("parser_config") private ParserConfig parserConfig; @@ -136,313 +138,314 @@ public class DatasetDTO { } /** - * 查询知识库列表请求 (映射接口 3: list_datasets) + * List knowledge bases request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "查询知识库列表请求") + @Schema(description = "List knowledge bases request") @JsonIgnoreProperties(ignoreUnknown = true) public static class ListReq implements Serializable { - @Schema(description = "页码 (从 1 开始)", example = "1") + @Schema(description = "Page number, starting from 1", example = "1") private Integer page; - @Schema(description = "每页数量", example = "30") + @Schema(description = "Page size", example = "30") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "排序字段: create_time / update_time", example = "create_time") + @Schema(description = "Sort field: create_time / update_time", example = "create_time") private String orderby; - @Schema(description = "是否降序", example = "true") + @Schema(description = "Whether sorting is descending", example = "true") private Boolean desc; - @Schema(description = "按名称过滤 (模糊匹配)", example = "my_dataset") + @Schema(description = "Filter by name using fuzzy matching", example = "my_dataset") private String name; - @Schema(description = "按知识库 ID 过滤", example = "abc123") + @Schema(description = "Filter by knowledge base ID", example = "abc123") private String id; } /** - * 批量删除知识库请求 (映射接口 2: delete) + * Bulk delete knowledge bases request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "批量删除知识库请求") + @Schema(description = "Bulk delete knowledge bases request") public static class BatchIdReq implements Serializable { - @NotNull(message = "知识库 ID 列表不能为空") - @Size(min = 1, message = "至少需要一个知识库 ID") - @Schema(description = "知识库 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"id1\", \"id2\"]") + @NotNull(message = "Knowledge base ID list cannot be empty") + @Size(min = 1, message = "At least one knowledge base ID is required") + @Schema(description = "Knowledge base ID list", requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"id1\", \"id2\"]") private List ids; } /** - * 运行 GraphRAG 请求 + * Run GraphRAG request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "运行 GraphRAG 请求") + @Schema(description = "Run GraphRAG request") public static class RunGraphRagReq implements Serializable { - @Schema(description = "实体类型列表", example = "[\"person\", \"organization\"]") + @Schema(description = "Entity type list", example = "[\"person\", \"organization\"]") @JsonProperty("entity_types") private List entityTypes; - @Schema(description = "构建方法: light / fast / full", example = "light") + @Schema(description = "Build method: light / fast / full", example = "light") private String method; } /** - * 运行 RAPTOR 请求 + * Run RAPTOR request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "运行 RAPTOR 请求") + @Schema(description = "Run RAPTOR request") public static class RunRaptorReq implements Serializable { - @Schema(description = "最大聚类数", example = "64") + @Schema(description = "Maximum cluster count", example = "64") @JsonProperty("max_cluster") private Integer maxCluster; - @Schema(description = "自定义提示词", example = "请总结以下内容...") + @Schema(description = "Custom prompt", example = "Please summarize the following content...") private String prompt; } /** - * 异步任务 ID 响应 VO (映射接口 7/8: run_graphrag/run_raptor) + * Async task ID response. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "异步任务 ID 响应") + @Schema(description = "Async task ID response") @JsonIgnoreProperties(ignoreUnknown = true) public static class TaskIdVO implements Serializable { - @Schema(description = "GraphRAG 任务 ID", example = "task_uuid_12345678") + @Schema(description = "GraphRAG task ID", example = "task_uuid_12345678") @JsonProperty("graphrag_task_id") private String graphragTaskId; - @Schema(description = "RAPTOR 任务 ID", example = "task_uuid_87654321") + @Schema(description = "RAPTOR task ID", example = "task_uuid_87654321") @JsonProperty("raptor_task_id") private String raptorTaskId; } - // ========== 响应类 ========== + // ========== Responses ========== /** - * 知识库详情 VO (映射接口 1/3 的返回数据项) + * Knowledge base details. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "知识库详情 VO") + @Schema(description = "Knowledge base details") @JsonIgnoreProperties(ignoreUnknown = true) public static class InfoVO implements Serializable { - @Schema(description = "知识库 ID", example = "abc123") + @Schema(description = "Knowledge base ID", example = "abc123") private String id; - @Schema(description = "知识库名称", example = "my_dataset") + @Schema(description = "Knowledge base name", example = "my_dataset") private String name; - @Schema(description = "知识库头像 (Base64 编码)", example = "") + @Schema(description = "Knowledge base avatar in Base64", example = "") private String avatar; - @Schema(description = "租户 ID", example = "tenant_001") + @Schema(description = "Tenant ID", example = "tenant_001") @JsonProperty("tenant_id") private String tenantId; - @Schema(description = "知识库描述", example = "用于存储产品文档") + @Schema(description = "Knowledge base description", example = "Used to store product documents") private String description; - @Schema(description = "嵌入模型名称", example = "BAAI/bge-large-zh-v1.5") + @Schema(description = "Embedding model name", example = "text-embedding-3-large") @JsonProperty("embedding_model") private String embeddingModel; - @Schema(description = "权限设置: me / team", example = "me") + @Schema(description = "Permission setting: me / team", example = "me") private String permission; - @Schema(description = "分块方法", example = "naive") + @Schema(description = "Chunking method", example = "naive") @JsonProperty("chunk_method") private String chunkMethod; - @Schema(description = "解析器配置") + @Schema(description = "Parser configuration") @JsonProperty("parser_config") private ParserConfig parserConfig; - @Schema(description = "分块总数", example = "1024") + @Schema(description = "Total chunk count", example = "1024") @JsonProperty("chunk_count") private Long chunkCount; - @Schema(description = "文档总数", example = "50") + @Schema(description = "Total document count", example = "50") @JsonProperty("document_count") private Long documentCount; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; - @Schema(description = "总 Token 数", example = "102400") + @Schema(description = "Total token count", example = "102400") @JsonProperty("token_num") private Long tokenNum; - @Schema(description = "创建日期 (格式: yyyy-MM-dd HH:mm:ss)") + @Schema(description = "Creation date in yyyy-MM-dd HH:mm:ss format") @JsonProperty("create_date") private String createDate; - @Schema(description = "最后更新日期 (格式: yyyy-MM-dd HH:mm:ss)") + @Schema(description = "Last update date in yyyy-MM-dd HH:mm:ss format") @JsonProperty("update_date") private String updateDate; } /** - * 批量操作响应 VO + * Batch operation response. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "批量操作响应 VO") + @Schema(description = "Batch operation response") public static class BatchOperationVO implements Serializable { - @Schema(description = "成功操作数量", example = "5") + @Schema(description = "Successful operation count", example = "5") @JsonProperty("success_count") private Integer successCount; - @Schema(description = "错误列表") + @Schema(description = "Error list") private List errors; } - // ========== 知识图谱相关 ========== + // ========== Knowledge-graph types ========== /** - * 知识图谱数据 VO (映射接口 5: knowledge_graph) + * Knowledge-graph data response mapped from the knowledge_graph endpoint. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "知识图谱数据 VO") + @Schema(description = "Knowledge-graph data response") public static class GraphVO implements Serializable { - @Schema(description = "图谱节点列表") + @Schema(description = "Graph node list") private List nodes; - @Schema(description = "图谱边列表") + @Schema(description = "Graph edge list") private List edges; - @Schema(description = "思维导图数据") + @Schema(description = "Mind-map data") @JsonProperty("mind_map") private Map mindMap; /** - * 图谱节点 + * Graph node. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "图谱节点") + @Schema(description = "Graph node") @JsonIgnoreProperties(ignoreUnknown = true) public static class Node implements Serializable { - @Schema(description = "节点 ID", example = "node_001") + @Schema(description = "Node ID", example = "node_001") private String id; - @Schema(description = "节点标签", example = "产品") + @Schema(description = "Node label", example = "Product") private String label; - @Schema(description = "PageRank 值", example = "0.85") + @Schema(description = "PageRank value", example = "0.85") private Double pagerank; - @Schema(description = "节点颜色", example = "#FF5733") + @Schema(description = "Node color", example = "#FF5733") private String color; - @Schema(description = "节点图片 URL", example = "https://example.com/icon.png") + @Schema(description = "Node image URL", example = "https://example.com/icon.png") private String img; } /** - * 图谱边 + * Graph edge. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "图谱边") + @Schema(description = "Graph edge") @JsonIgnoreProperties(ignoreUnknown = true) public static class Edge implements Serializable { - @Schema(description = "源节点 ID", example = "node_001") + @Schema(description = "Source node ID", example = "node_001") private String source; - @Schema(description = "目标节点 ID", example = "node_002") + @Schema(description = "Target node ID", example = "node_002") private String target; - @Schema(description = "边权重", example = "0.75") + @Schema(description = "Edge weight", example = "0.75") private Double weight; - @Schema(description = "边标签 (关系描述)", example = "属于") + @Schema(description = "Edge label describing the relationship", example = "belongs_to") private String label; } } - // ========== 异步任务追踪 (GraphRAG/RAPTOR) ========== + // ========== Async task tracing (GraphRAG/RAPTOR) ========== /** - * 异步任务追踪 VO (映射接口 9/10: 任务进度返回) + * Async task-trace response mapped from task-progress endpoints. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "异步任务追踪 VO") + @Schema(description = "Async task-trace response") @JsonIgnoreProperties(ignoreUnknown = true) public static class TaskTraceVO implements Serializable { - @Schema(description = "任务 ID", example = "task_001") + @Schema(description = "Task ID", example = "task_001") private String id; - @Schema(description = "文档 ID", example = "doc_001") + @Schema(description = "Document ID", example = "doc_001") @JsonProperty("doc_id") private String docId; - @Schema(description = "起始页码", example = "1") + @Schema(description = "Starting page number", example = "1") @JsonProperty("from_page") private Integer fromPage; - @Schema(description = "结束页码", example = "10") + @Schema(description = "Ending page number", example = "10") @JsonProperty("to_page") private Integer toPage; - @Schema(description = "进度百分比 (0.0 - 1.0)", example = "0.75") + @Schema(description = "Progress percentage from 0.0 to 1.0", example = "0.75") private Double progress; - @Schema(description = "进度消息", example = "正在处理第 5 页...") + @Schema(description = "Progress message", example = "Processing page 5...") @JsonProperty("progress_msg") private String progressMsg; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/ChunkDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/ChunkDTO.java index 376b08bfd..3bae1df1a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/ChunkDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/ChunkDTO.java @@ -9,174 +9,174 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.*; /** - * 切片管理聚合 DTO + * Chunk-management aggregate DTO. */ -@Schema(description = "切片管理聚合 DTO") +@Schema(description = "Chunk-management aggregate DTO") @JsonIgnoreProperties(ignoreUnknown = true) public class ChunkDTO { /** - * 新增切片请求参数 + * Add-chunk request. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "新增切片请求参数") + @Schema(description = "Add-chunk request") @JsonIgnoreProperties(ignoreUnknown = true) public static class AddReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片内容", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "切片内容不能为空") + @Schema(description = "Chunk content", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Chunk content cannot be empty") private String content; - @Schema(description = "重要关键词列表") + @Schema(description = "Important keyword list") @JsonProperty("important_keywords") private List importantKeywords; - @Schema(description = "预设问题列表") + @Schema(description = "Preset question list") private List questions; } /** - * 更新切片请求参数 + * Update-chunk request. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "更新切片请求参数") + @Schema(description = "Update-chunk request") @JsonIgnoreProperties(ignoreUnknown = true) public static class UpdateReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "新的切片内容") + @Schema(description = "Updated chunk content") private String content; - @Schema(description = "更新关键词列表 (覆盖原有列表)") + @Schema(description = "Updated keyword list that replaces the existing one") @JsonProperty("important_keywords") private List importantKeywords; - @Schema(description = "启用/禁用 (true: 启用, false: 禁用)") + @Schema(description = "Availability flag (true enabled, false disabled)") private Boolean available; } /** - * 获取切片列表请求参数 + * Chunk-list request. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "获取切片列表请求参数") + @Schema(description = "Chunk-list request") @JsonIgnoreProperties(ignoreUnknown = true) public static class ListReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "页码 (默认 1)") + @Schema(description = "Page number, default 1") private Integer page; - @Schema(description = "每页数量 (默认 30)") + @Schema(description = "Page size, default 30") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "搜索关键词 (全文检索)") + @Schema(description = "Search keywords for full-text retrieval") private String keywords; - @Schema(description = "精确切片 ID") + @Schema(description = "Exact chunk ID") private String id; } /** - * 批量删除切片请求参数 + * Batch chunk-delete request. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "批量删除切片请求参数") + @Schema(description = "Batch chunk-delete request") @JsonIgnoreProperties(ignoreUnknown = true) public static class RemoveReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Chunk ID list", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("chunk_ids") - @NotEmpty(message = "切片ID列表不能为空") + @NotEmpty(message = "Chunk ID list cannot be empty") private List chunkIds; } /** - * 文档切片信息 VO + * Document chunk info view object. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "文档切片信息") + @Schema(description = "Document chunk information") @JsonIgnoreProperties(ignoreUnknown = true) public static class InfoVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片 ID (通常为 document_id + 索引)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Chunk ID, usually document_id plus an index", requiredMode = Schema.RequiredMode.REQUIRED) private String id; - @Schema(description = "切片文本内容 (全文检索的主要对象)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Chunk text content used for full-text retrieval", requiredMode = Schema.RequiredMode.REQUIRED) private String content; - @Schema(description = "所属文档 ID", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Owning document ID", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("document_id") private String documentId; - @Schema(description = "文档名称 / 关键词") + @Schema(description = "Document name or keyword") @JsonProperty("docnm_kwd") private String docnmKwd; - @Schema(description = "重要关键词列表 (用于关键词增强检索)") + @Schema(description = "Important keyword list used for enhanced keyword retrieval") @JsonProperty("important_keywords") private List importantKeywords; - @Schema(description = "预设问题列表 (用于 Q&A 模式增强)") + @Schema(description = "Preset question list used to enhance Q&A mode") private List questions; - @Schema(description = "关联的图片 ID") + @Schema(description = "Linked image ID") @JsonProperty("image_id") private String imageId; - @Schema(description = "所属知识库 ID") + @Schema(description = "Owning knowledge-base ID") @JsonProperty("dataset_id") private String datasetId; - @Schema(description = "切片是否可用 (true: 参与检索, false: 被禁用)") + @Schema(description = "Whether the chunk is available for retrieval") private Boolean available; - @Schema(description = "切片在原文中的位置索引列表 (RAGFlow返回嵌套数组, 如 [[start, end, filename]])") + @Schema(description = "Chunk positions in the source text, as nested arrays such as [[start, end, filename]]") private List> positions; - @Schema(description = "Token ID 列表") + @Schema(description = "Token ID list") @JsonProperty("token") private List token; } /** - * 分片列表聚合响应 + * Chunk-list aggregate response. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "分片列表聚合响应") + @Schema(description = "Chunk-list aggregate response") @JsonIgnoreProperties(ignoreUnknown = true) public static class ListVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片信息列表") + @Schema(description = "Chunk information list") private List chunks; - @Schema(description = "关联的文档详细信息") + @Schema(description = "Linked document details") private DocumentDTO.InfoVO doc; - @Schema(description = "总记录数") + @Schema(description = "Total record count") private Long total; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/DocumentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/DocumentDTO.java index b8176065a..42b7a45dd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/DocumentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/DocumentDTO.java @@ -11,325 +11,328 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.*; /** - * 文档管理聚合 DTO + * Aggregate DTOs for document management. */ -@Schema(description = "文档管理聚合 DTO") +@Schema(description = "Aggregate DTOs for document management") @JsonIgnoreProperties(ignoreUnknown = true) public class DocumentDTO { /** - * 上传文档请求参数 + * Upload document request parameters. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "上传文档请求参数") + @Schema(description = "Upload document request parameters") @JsonIgnoreProperties(ignoreUnknown = true) public static class UploadReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "知识库 ID (必须指定归属)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Knowledge base ID", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("dataset_id") - @NotBlank(message = "知识库ID不能为空") + @NotBlank(message = "Knowledge base ID cannot be empty") private String datasetId; - @Schema(description = "文件名 (如果指定,则覆盖原始文件名)") + @Schema(description = "File name. Overrides the original file name when provided") private String name; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") @JsonProperty("chunk_method") private DocumentDTO.InfoVO.ChunkMethod chunkMethod; - @Schema(description = "解析参数配置") + @Schema(description = "Parser configuration") @JsonProperty("parser_config") private DocumentDTO.InfoVO.ParserConfig parserConfig; - @Schema(description = "虚拟文件夹路径 (默认为 /)") + @Schema(description = "Virtual folder path (defaults to /)") @JsonProperty("parent_path") private String parentPath; - @Schema(description = "元数据字段") + @Schema(description = "Metadata fields") @JsonProperty("meta") private Map metaFields; - @Schema(description = "文件二进制流 (支持 PDF, DOCX, TXT, MD 等多种格式)", requiredMode = Schema.RequiredMode.REQUIRED) - @NotNull(message = "上传文件不能为空") + @Schema(description = "File binary stream (supports PDF, DOCX, TXT, MD, and more)", + requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "Upload file cannot be empty") private org.springframework.web.multipart.MultipartFile file; } /** - * 更新文档请求参数 + * Update document request parameters. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "更新文档请求参数") + @Schema(description = "Update document request parameters") @JsonIgnoreProperties(ignoreUnknown = true) public static class UpdateReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "新文档名称 (必须包含文件后缀,且不能更改原始类型)") + @Schema(description = "New document name. Must include the file extension and keep the original type") private String name; - @Schema(description = "启用/禁用状态 (true: 启用, false: 禁用; 禁用后不参与检索)") + @Schema(description = "Enabled state. Disabled documents are excluded from retrieval") private Boolean enabled; - @Schema(description = "新解析方法 (修改此项会重置解析状态)") + @Schema(description = "New parsing method. Changing this resets the parsing state") @JsonProperty("chunk_method") private InfoVO.ChunkMethod chunkMethod; - @Schema(description = "新解析器详细配置 (应与 chunk_method 配套使用)") + @Schema(description = "New parser configuration that should match chunk_method") @JsonProperty("parser_config") private InfoVO.ParserConfig parserConfig; } /** - * 获取文档列表请求参数 + * List document request parameters. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "获取文档列表请求参数") + @Schema(description = "List document request parameters") @JsonIgnoreProperties(ignoreUnknown = true) public static class ListReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "页码 (默认: 1)") + @Schema(description = "Page number (default: 1)") private Integer page; - @Schema(description = "每页数量 (默认: 30)") + @Schema(description = "Page size (default: 30)") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "排序字段 (可选: create_time, name, size; 默认: create_time)") + @Schema(description = "Sort field (create_time, name, size; default: create_time)") private String orderby; - @Schema(description = "是否降序排列 (true: 最新/最大在前; false: 最旧/最小在前; 默认: true)") + @Schema(description = "Whether sorting is descending (default: true)") private Boolean desc; - @Schema(description = "精确筛选: 文档 ID") + @Schema(description = "Exact filter: document ID") private String id; - @Schema(description = "精确筛选: 文档完整名称 (含后缀)") + @Schema(description = "Exact filter: full document name including extension") private String name; - @Schema(description = "模糊搜索: 文档名称关键词") + @Schema(description = "Fuzzy search: document name keywords") private String keywords; - @Schema(description = "筛选: 文件后缀列表 (如 ['pdf', 'docx'])") + @Schema(description = "Filter by file suffix list, for example ['pdf', 'docx']") private List suffix; - @Schema(description = "筛选: 运行状态列表") + @Schema(description = "Filter by run-status list") private List run; - @Schema(description = "筛选: 起始创建时间 (时间戳, 毫秒)") + @Schema(description = "Filter by start creation time in milliseconds") @JsonProperty("create_time_from") private Long createTimeFrom; - @Schema(description = "筛选: 结束创建时间 (时间戳, 毫秒)") + @Schema(description = "Filter by end creation time in milliseconds") @JsonProperty("create_time_to") private Long createTimeTo; } /** - * 批量文档操作请求参数 (用于删除、解析等) + * Batch document operation request parameters, used for delete, parse, and similar actions. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "批量文档操作请求参数") + @Schema(description = "Batch document operation request parameters") @JsonIgnoreProperties(ignoreUnknown = true) public static class BatchIdReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "文档 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED) - @JsonProperty("ids") // 为了兼容性,也可以考虑支持 document_ids,但这里统一叫 ids + @Schema(description = "Document ID list", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("ids") // Kept as ids for consistency, while remaining compatible with document_ids. @JsonAlias("document_ids") - @NotEmpty(message = "文档ID列表不能为空") + @NotEmpty(message = "Document ID list cannot be empty") private List ids; } /** - * 知识库文档信息 VO + * Knowledge-base document information. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "知识库文档信息") + @Schema(description = "Knowledge-base document information") @JsonIgnoreProperties(ignoreUnknown = true) public static class InfoVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "文档 ID (唯一标识)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Document ID", requiredMode = Schema.RequiredMode.REQUIRED) private String id; - @Schema(description = "文档缩略图 URL (Base64 或 链接)") + @Schema(description = "Document thumbnail URL, either Base64 or a link") private String thumbnail; - @Schema(description = "所属知识库 ID", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Knowledge base ID", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("dataset_id") private String datasetId; - @Schema(description = "文档解析方法 (决定了文档如何被切片)") + @Schema(description = "Document parsing method that determines how chunks are created") @JsonProperty("chunk_method") private ChunkMethod chunkMethod; - @Schema(description = "关联的 ETL Pipeline ID (如有)") + @Schema(description = "Related ETL pipeline ID when available") @JsonProperty("pipeline_id") private String pipelineId; - @Schema(description = "文档解析器的详细配置") + @Schema(description = "Detailed document parser configuration") @JsonProperty("parser_config") private ParserConfig parserConfig; - @Schema(description = "来源类型 (如 local, s3, url 等)") + @Schema(description = "Source type such as local, s3, or url") @JsonProperty("source_type") private String sourceType; - @Schema(description = "文档文件类型 (如 pdf, docx, txt)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Document file type such as pdf, docx, or txt", + requiredMode = Schema.RequiredMode.REQUIRED) private String type; - @Schema(description = "创建者用户 ID") + @Schema(description = "Creator user ID") @JsonProperty("created_by") private String createdBy; - @Schema(description = "文档名称 (包含扩展名)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Document name including extension", requiredMode = Schema.RequiredMode.REQUIRED) private String name; - @Schema(description = "文件存储路径或位置标识") + @Schema(description = "File storage path or location identifier") private String location; - @Schema(description = "文件大小 (单位: Bytes)") + @Schema(description = "File size in bytes") private Long size; - @Schema(description = "包含的 Token 总数 (解析后统计)") + @Schema(description = "Total token count after parsing") @JsonProperty("token_count") private Long tokenCount; - @Schema(description = "包含的切片 (Chunk) 总数") + @Schema(description = "Total chunk count") @JsonProperty("chunk_count") private Long chunkCount; - @Schema(description = "解析进度 (0.0 ~ 1.0, 1.0 表示完成)") + @Schema(description = "Parsing progress from 0.0 to 1.0") private Double progress; - @Schema(description = "当前进度描述或错误信息") + @Schema(description = "Current progress description or error message") @JsonProperty("progress_msg") private String progressMsg; - @Schema(description = "开始处理的时间戳 (RAGFlow返回RFC1123格式)") + @Schema(description = "Processing start time. RAGFlow returns this in RFC1123 format") @JsonProperty("process_begin_at") private String processBeginAt; - @Schema(description = "处理总耗时 (单位: 秒)") + @Schema(description = "Total processing duration in seconds") @JsonProperty("process_duration") private Double processDuration; - @Schema(description = "自定义元数据字段 (Key-Value 键值对)") + @Schema(description = "Custom metadata key-value pairs") @JsonProperty("meta_fields") private Map metaFields; - @Schema(description = "文件后缀名 (不含点)") + @Schema(description = "File suffix without the leading dot") private String suffix; - @Schema(description = "文档解析运行状态") + @Schema(description = "Document parsing run status") private RunStatus run; - @Schema(description = "文档可用状态 (1: 启用/正常, 0: 禁用/失效)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Document availability status: 1 for enabled, 0 for disabled", + requiredMode = Schema.RequiredMode.REQUIRED) private String status; - @Schema(description = "创建时间 (时间戳, 毫秒)", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Creation time in milliseconds", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("create_time") private Long createTime; - @Schema(description = "创建日期 (RAGFlow返回RFC1123格式)") + @Schema(description = "Creation date. RAGFlow returns this in RFC1123 format") @JsonProperty("create_date") private String createDate; - @Schema(description = "最后更新时间 (时间戳, 毫秒)") + @Schema(description = "Last update time in milliseconds") @JsonProperty("update_time") private Long updateTime; - @Schema(description = "最后更新日期 (RAGFlow返回RFC1123格式)") + @Schema(description = "Last update date. RAGFlow returns this in RFC1123 format") @JsonProperty("update_date") private String updateDate; /** - * 解析方法枚举 (ChunkMethod) + * Chunking method enumeration. */ public enum ChunkMethod { - @Schema(description = "通用模式: 适用于大多数纯文本或混合文档") + @Schema(description = "General mode for most plain-text or mixed documents") @JsonProperty("naive") NAIVE, - @Schema(description = "手动模式: 允许用户手动编辑切片") + @Schema(description = "Manual mode that allows users to edit chunks directly") @JsonProperty("manual") MANUAL, - @Schema(description = "问答模式: 专门优化 Q&A 格式的文档") + @Schema(description = "Q&A mode optimized for question-and-answer documents") @JsonProperty("qa") QA, - @Schema(description = "表格模式: 专门优化 Excel 或 CSV 等表格数据") + @Schema(description = "Table mode optimized for Excel, CSV, and similar tabular data") @JsonProperty("table") TABLE, - @Schema(description = "论文模式: 针对学术论文排版优化") + @Schema(description = "Paper mode optimized for academic paper layouts") @JsonProperty("paper") PAPER, - @Schema(description = "书籍模式: 针对书籍章节结构优化") + @Schema(description = "Book mode optimized for chapter-based book structures") @JsonProperty("book") BOOK, - @Schema(description = "法律法规模式: 针对法律条文结构优化") + @Schema(description = "Legal mode optimized for statutes and legal clauses") @JsonProperty("laws") LAWS, - @Schema(description = "演示文稿模式: 针对 PPT 等演示文件优化") + @Schema(description = "Presentation mode optimized for slide decks such as PPT") @JsonProperty("presentation") PRESENTATION, - @Schema(description = "图片模式: 针对图片内容进行 OCR 和描述") + @Schema(description = "Picture mode that performs OCR and image description") @JsonProperty("picture") PICTURE, - @Schema(description = "整体模式: 将整个文档作为一个切片") + @Schema(description = "Single-chunk mode that keeps the whole document together") @JsonProperty("one") ONE, - @Schema(description = "知识图谱模式: 提取实体关系构建图谱") + @Schema(description = "Knowledge graph mode that extracts entities and relationships") @JsonProperty("knowledge_graph") KNOWLEDGE_GRAPH, - @Schema(description = "邮件模式: 针对邮件格式优化") + @Schema(description = "Email mode optimized for email-style content") @JsonProperty("email") EMAIL; } /** - * 运行状态枚举 (RunStatus) + * Run status enumeration. */ public enum RunStatus { - @Schema(description = "未开始: 等待解析队列") + @Schema(description = "Not started yet and waiting in the parsing queue") @JsonProperty("UNSTART") UNSTART, - @Schema(description = "进行中: 正在解析或索引") + @Schema(description = "Currently parsing or indexing") @JsonProperty("RUNNING") RUNNING, - @Schema(description = "已取消: 用户手动取消") + @Schema(description = "Canceled manually by the user") @JsonProperty("CANCEL") CANCEL, - @Schema(description = "已完成: 解析成功") + @Schema(description = "Completed successfully") @JsonProperty("DONE") DONE, - @Schema(description = "失败: 解析过程中出错") + @Schema(description = "Failed during parsing") @JsonProperty("FAIL") FAIL; } /** - * 布局识别模型枚举 + * Layout recognition model enumeration. */ public enum LayoutRecognize { - @Schema(description = "深度文档理解模型: 适合复杂排版") + @Schema(description = "Deep document understanding model for complex layouts") @JsonProperty("DeepDOC") DeepDOC, - @Schema(description = "简单规则模型: 适合纯文本") + @Schema(description = "Simple rule-based model for plain text") @JsonProperty("Simple") Simple; } @@ -338,42 +341,42 @@ public class DocumentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "文档解析器参数配置") + @Schema(description = "Document parser configuration") @JsonIgnoreProperties(ignoreUnknown = true) public static class ParserConfig implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片最大 Token 数 (建议值: 512, 1024, 2048)") + @Schema(description = "Maximum tokens per chunk (recommended: 512, 1024, 2048)") @JsonProperty("chunk_token_num") private Integer chunkTokenNum; - @Schema(description = "分段分隔符 (支持转义字符, 如 \\n)") + @Schema(description = "Chunk delimiter (supports escape sequences such as \\n)") private String delimiter; - @Schema(description = "布局识别模型 (DeepDOC/Simple)") + @Schema(description = "Layout recognition model (DeepDOC/Simple)") @JsonProperty("layout_recognize") private LayoutRecognize layoutRecognize; - @Schema(description = "是否将 Excel 转换为 HTML 表格") + @Schema(description = "Whether Excel content should be converted to HTML tables") @JsonProperty("html4excel") private Boolean html4excel; - @Schema(description = "自动提取关键词数量 (0 表示不提取)") + @Schema(description = "Number of auto-generated keywords (0 disables extraction)") @JsonProperty("auto_keywords") private Integer autoKeywords; - @Schema(description = "自动生成问题数量 (0 表示不生成)") + @Schema(description = "Number of auto-generated questions (0 disables generation)") @JsonProperty("auto_questions") private Integer autoQuestions; - @Schema(description = "自动生成标签数量") + @Schema(description = "Number of auto-generated tags") @JsonProperty("topn_tags") private Integer topnTags; - @Schema(description = "RAPTOR 高级索引配置") + @Schema(description = "Advanced RAPTOR index configuration") private RaptorConfig raptor; - @Schema(description = "GraphRAG 知识图谱配置") + @Schema(description = "GraphRAG knowledge graph configuration") @JsonProperty("graphrag") private GraphRagConfig graphRag; @@ -381,11 +384,11 @@ public class DocumentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "RAPTOR (递归摘要索引) 配置") + @Schema(description = "RAPTOR recursive summary index configuration") @JsonIgnoreProperties(ignoreUnknown = true) public static class RaptorConfig implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "是否启用 RAPTOR 索引") + @Schema(description = "Whether RAPTOR indexing is enabled") @JsonProperty("use_raptor") private Boolean useRaptor; } @@ -394,11 +397,11 @@ public class DocumentDTO { @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "GraphRAG (图增强检索) 配置") + @Schema(description = "GraphRAG graph-enhanced retrieval configuration") @JsonIgnoreProperties(ignoreUnknown = true) public static class GraphRagConfig implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "是否启用 GraphRAG 索引") + @Schema(description = "Whether GraphRAG indexing is enabled") @JsonProperty("use_graphrag") private Boolean useGraphRag; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/RetrievalDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/RetrievalDTO.java index 318401874..9ffa31719 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/RetrievalDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/document/RetrievalDTO.java @@ -11,297 +11,297 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.*; /** - * 检索与元数据管理聚合 DTO + * Aggregate DTOs for retrieval and metadata management. */ -@Schema(description = "检索与元数据管理聚合 DTO") +@Schema(description = "Aggregate DTOs for retrieval and metadata management") @JsonIgnoreProperties(ignoreUnknown = true) public class RetrievalDTO { /** - * 文档聚合信息 (VO) + * Aggregated document information. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "文档聚合信息") + @Schema(description = "Aggregated document information") @JsonIgnoreProperties(ignoreUnknown = true) public static class DocAggVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "文档名称") + @Schema(description = "Document name") @JsonProperty("doc_name") private String docName; - @Schema(description = "文档 ID") + @Schema(description = "Document ID") @JsonProperty("doc_id") private String docId; - @Schema(description = "数量") + @Schema(description = "Count") private Integer count; } /** - * 检索测试请求参数 + * Retrieval test request parameters. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "检索测试请求参数") + @Schema(description = "Retrieval test request parameters") @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public static class TestReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "知识库 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Knowledge base ID list", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("dataset_ids") - @NotEmpty(message = "知识库ID列表不能为空") + @NotEmpty(message = "Knowledge base ID list cannot be empty") private List datasetIds; - @Schema(description = "文档 ID 列表 (可选,用于限定检索范围)") + @Schema(description = "Optional document ID list used to restrict retrieval scope") @JsonProperty("document_ids") private List documentIds; - @Schema(description = "检索问题", requiredMode = Schema.RequiredMode.REQUIRED) - @NotBlank(message = "检索问题不能为空") + @Schema(description = "Retrieval question", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "Retrieval question cannot be empty") private String question; - @Schema(description = "页码 (默认 1)") + @Schema(description = "Page number (default: 1)") private Integer page; - @Schema(description = "每页数量 (默认 10)") + @Schema(description = "Page size (default: 10)") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "相似度阈值 (默认 0.2)") + @Schema(description = "Similarity threshold (default: 0.2)") @JsonProperty("similarity_threshold") private Float similarityThreshold; - @Schema(description = "向量相似度权重 (默认 0.3)") + @Schema(description = "Vector similarity weight (default: 0.3)") @JsonProperty("vector_similarity_weight") private Float vectorSimilarityWeight; - @Schema(description = "返回 Top K 切片 (默认 1024)") + @Schema(description = "Top-K chunks to return (default: 1024)") @JsonProperty("top_k") private Integer topK; - @Schema(description = "重排序模型 ID") + @Schema(description = "Rerank model ID") @JsonProperty("rerank_id") private String rerankId; - @Schema(description = "是否高亮关键词") + @Schema(description = "Whether keywords should be highlighted") private Boolean highlight; - @Schema(description = "是否启用关键词检索") + @Schema(description = "Whether keyword retrieval is enabled") private Boolean keyword; - @Schema(description = "跨语言翻译列表 (可选)") + @Schema(description = "Optional cross-language translation list") @JsonProperty("cross_languages") private List crossLanguages; - @Schema(description = "元数据过滤条件 (JSON 对象)") + @Schema(description = "Metadata filter conditions as a JSON object") @JsonProperty("metadata_condition") private Map metadataCondition; } /** - * 检索命中结果 (VO) + * Retrieval hit details. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "检索命中切片详情") + @Schema(description = "Retrieval hit details") @JsonIgnoreProperties(ignoreUnknown = true) public static class HitVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "切片 ID", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Chunk ID", requiredMode = Schema.RequiredMode.REQUIRED) private String id; - @Schema(description = "切片内容", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Chunk content", requiredMode = Schema.RequiredMode.REQUIRED) private String content; - @Schema(description = "所属文档 ID", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Owning document ID", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("document_id") private String documentId; - @Schema(description = "所属知识库 ID") + @Schema(description = "Owning knowledge base ID") @JsonProperty("dataset_id") private String datasetId; - @Schema(description = "文档名称") + @Schema(description = "Document name") @JsonProperty("document_name") private String documentName; - @Schema(description = "文档关键词") + @Schema(description = "Document keywords") @JsonProperty("document_keyword") private String documentKeyword; - @Schema(description = "综合相似度", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Overall similarity score", requiredMode = Schema.RequiredMode.REQUIRED) private Float similarity; - @Schema(description = "向量相似度") + @Schema(description = "Vector similarity score") @JsonProperty("vector_similarity") private Float vectorSimilarity; - @Schema(description = "关键词相似度") + @Schema(description = "Keyword similarity score") @JsonProperty("term_similarity") private Float termSimilarity; - @Schema(description = "索引位置") + @Schema(description = "Index position") private Integer index; - @Schema(description = "高亮内容") + @Schema(description = "Highlighted content") private String highlight; - @Schema(description = "重要关键词列表") + @Schema(description = "Important keyword list") @JsonProperty("important_keywords") private List importantKeywords; - @Schema(description = "预设问题列表") + @Schema(description = "Preset question list") private List questions; - @Schema(description = "图片 ID") + @Schema(description = "Image ID") @JsonProperty("image_id") private String imageId; - @Schema(description = "位置索引 (RAGFlow返回嵌套数组, 如 [[start, end, filename]])") + @Schema(description = "Position index. RAGFlow returns nested arrays such as [[start, end, filename]]") private Object positions; } /** - * 知识库元数据摘要 (VO) + * Knowledge base metadata summary. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "知识库元数据摘要信息") + @Schema(description = "Knowledge base metadata summary") @JsonIgnoreProperties(ignoreUnknown = true) public static class MetaSummaryVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "文档总数", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Total document count", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("total_doc_count") private Long totalDocCount; - @Schema(description = "Token 总数", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Total token count", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("total_token_count") private Long totalTokenCount; - @Schema(description = "文件类型分布 (key: 文件后缀, value: 数量)") + @Schema(description = "File type distribution keyed by suffix") @JsonProperty("file_type_distribution") private Map fileTypeDistribution; - @Schema(description = "文状态分布 (key: 状态码, value: 数量)") + @Schema(description = "Document status distribution keyed by status code") @JsonProperty("status_distribution") private Map statusDistribution; - @Schema(description = "自定义元数据统计 (key: 字段名, value: 数量/值)") + @Schema(description = "Custom metadata statistics keyed by field name") @JsonProperty("custom_metadata") private Map customMetadata; } /** - * 批量更新元数据请求参数 + * Batch metadata update request parameters. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "批量更新元数据请求参数") + @Schema(description = "Batch metadata update request parameters") @JsonIgnoreProperties(ignoreUnknown = true) public static class MetaBatchReq implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "筛选器: 用于指定要更新的文档范围 (默认全部)") + @Schema(description = "Selector used to specify which documents should be updated") private Selector selector; - @Schema(description = "新增或更新的元数据列表") + @Schema(description = "Metadata entries to add or update") private List updates; - @Schema(description = "需要删除的元数据键列表") + @Schema(description = "Metadata keys to delete") private List deletes; /** - * 文档筛选器 + * Document selector. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "元数据更新筛选器") + @Schema(description = "Metadata update selector") @JsonIgnoreProperties(ignoreUnknown = true) public static class Selector implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "指定文档 ID 列表") + @Schema(description = "Explicit document ID list") @JsonProperty("document_ids") private List documentIds; - @Schema(description = "元数据条件匹配 (key: 字段名, value: 匹配值)") + @Schema(description = "Metadata condition match keyed by field name") @JsonProperty("metadata_condition") private Map metadataCondition; } /** - * 更新项 + * Update item. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "元数据更新项") + @Schema(description = "Metadata update item") @JsonIgnoreProperties(ignoreUnknown = true) public static class UpdateItem implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "元数据键名", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Metadata key", requiredMode = Schema.RequiredMode.REQUIRED) private String key; - @Schema(description = "元数据值", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Metadata value", requiredMode = Schema.RequiredMode.REQUIRED) private Object value; } /** - * 删除项 + * Delete item. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "元数据删除项") + @Schema(description = "Metadata delete item") @JsonIgnoreProperties(ignoreUnknown = true) public static class DeleteItem implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "需删除的元数据键名", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Metadata key to delete", requiredMode = Schema.RequiredMode.REQUIRED) private String key; } } /** - * 召回测试结果聚合响应 + * Retrieval-test aggregate response. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor - @Schema(description = "召回测试结果聚合响应") + @Schema(description = "Retrieval-test aggregate response") @JsonIgnoreProperties(ignoreUnknown = true) public static class ResultVO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "检索命中的切片列表") + @Schema(description = "Retrieved chunk-hit list") private List chunks; - @Schema(description = "文档分布统计") + @Schema(description = "Document distribution summary") @JsonProperty("doc_aggs") private List docAggs; - @Schema(description = "总命中记录数") + @Schema(description = "Total hit count") private Long total; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/file/FileDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/file/FileDTO.java index 816ed8ee6..fb9ed6c65 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/file/FileDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/file/FileDTO.java @@ -9,354 +9,359 @@ import jakarta.validation.constraints.*; import org.springframework.web.multipart.MultipartFile; /** - * 文件管理聚合 DTO + * Aggregate DTOs for file management. *

- * 容器类,内含文件模块所有请求/响应对象的静态内部类定义。 + * Container for request/response objects used by the file module. *

*/ -@Schema(description = "文件管理聚合 DTO") +@Schema(description = "Aggregate DTOs for file management") public class FileDTO { - // ========== 请求类 ========== + // ========== Requests ========== /** - * 文件上传请求 (对应接口 1: upload) + * File upload request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文件上传请求") + @Schema(description = "File upload request") public static class UploadReq implements Serializable { - @NotNull(message = "文件不能为空") - @Schema(description = "上传的文件", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "File cannot be empty") + @Schema(description = "Uploaded file", requiredMode = Schema.RequiredMode.REQUIRED) private MultipartFile file; - @Schema(description = "父文件夹 ID (为空则上传到根目录)", example = "folder_001") + @Schema(description = "Parent folder ID. Uploads to the root when empty", example = "folder_001") @JsonProperty("parent_id") private String parentId; } /** - * 新建文件夹请求 (对应接口 2: create) + * Create folder request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "新建文件夹请求") + @Schema(description = "Create folder request") public static class CreateReq implements Serializable { - @NotBlank(message = "文件夹名称不能为空") - @Schema(description = "文件夹名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "新建文件夹") + @NotBlank(message = "Folder name cannot be empty") + @Schema(description = "Folder name", requiredMode = Schema.RequiredMode.REQUIRED, example = "New Folder") private String name; - @Schema(description = "父文件夹 ID (为空则创建在根目录)", example = "folder_001") + @Schema(description = "Parent folder ID. Creates in the root when empty", example = "folder_001") @JsonProperty("parent_id") private String parentId; - @NotBlank(message = "类型不能为空") - @Schema(description = "类型: FOLDER", requiredMode = Schema.RequiredMode.REQUIRED, example = "FOLDER") + @NotBlank(message = "Type cannot be empty") + @Schema(description = "Type: FOLDER", requiredMode = Schema.RequiredMode.REQUIRED, example = "FOLDER") @Builder.Default private String type = "FOLDER"; } /** - * 重命名请求 (对应接口 6: rename) + * Rename request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "重命名请求") + @Schema(description = "Rename request") public static class RenameReq implements Serializable { - @NotBlank(message = "文件 ID 不能为空") - @Schema(description = "文件/文件夹 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "file_001") + @NotBlank(message = "File ID cannot be empty") + @Schema(description = "File or folder ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "file_001") @JsonProperty("file_id") private String fileId; - @NotBlank(message = "新名称不能为空") - @Schema(description = "新名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "重命名后的文件") + @NotBlank(message = "New name cannot be empty") + @Schema(description = "New name", requiredMode = Schema.RequiredMode.REQUIRED, example = "renamed-file") private String name; } /** - * 移动请求 (对应接口 7: move) + * Move request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "移动请求") + @Schema(description = "Move request") public static class MoveReq implements Serializable { - @NotEmpty(message = "源文件 ID 列表不能为空") - @Schema(description = "源文件/文件夹 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"file_001\", \"file_002\"]") + @NotEmpty(message = "Source file ID list cannot be empty") + @Schema(description = "Source file or folder ID list", requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"file_001\", \"file_002\"]") @JsonProperty("src_file_ids") private List srcFileIds; - @NotBlank(message = "目标文件夹 ID 不能为空") - @Schema(description = "目标文件夹 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "folder_002") + @NotBlank(message = "Destination folder ID cannot be empty") + @Schema(description = "Destination folder ID", requiredMode = Schema.RequiredMode.REQUIRED, + example = "folder_002") @JsonProperty("dest_file_id") private String destFileId; } /** - * 批量删除请求 (对应接口 8: rm) + * Bulk delete request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "批量删除请求") + @Schema(description = "Bulk delete request") public static class RemoveReq implements Serializable { - @NotEmpty(message = "文件 ID 列表不能为空") - @Schema(description = "文件/文件夹 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"file_001\", \"file_002\"]") + @NotEmpty(message = "File ID list cannot be empty") + @Schema(description = "File or folder ID list", requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"file_001\", \"file_002\"]") @JsonProperty("file_ids") private List fileIds; } /** - * 导入知识库请求 (对应接口 9: convert) + * Convert-to-knowledge-base request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "导入知识库请求") + @Schema(description = "Convert-to-knowledge-base request") public static class ConvertReq implements Serializable { - @NotEmpty(message = "文件 ID 列表不能为空") - @Schema(description = "文件 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"file_001\", \"file_002\"]") + @NotEmpty(message = "File ID list cannot be empty") + @Schema(description = "File ID list", requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"file_001\", \"file_002\"]") @JsonProperty("file_ids") private List fileIds; - @NotEmpty(message = "知识库 ID 列表不能为空") - @Schema(description = "目标知识库 ID 列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"kb_001\"]") + @NotEmpty(message = "Knowledge base ID list cannot be empty") + @Schema(description = "Target knowledge base ID list", requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"kb_001\"]") @JsonProperty("kb_ids") private List kbIds; } /** - * 列表查询请求 (对应接口 3: list_files) + * List query request. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "列表查询请求") + @Schema(description = "List query request") public static class ListReq implements Serializable { - @Schema(description = "父文件夹 ID (为空则查询根目录)", example = "folder_001") + @Schema(description = "Parent folder ID. Queries the root directory when empty", example = "folder_001") @JsonProperty("parent_id") private String parentId; - @Schema(description = "关键词搜索", example = "文档") + @Schema(description = "Keyword search", example = "document") private String keywords; - @Schema(description = "页码 (从 1 开始)", example = "1") + @Schema(description = "Page number, starting from 1", example = "1") private Integer page; - @Schema(description = "每页数量", example = "30") + @Schema(description = "Page size", example = "30") @JsonProperty("page_size") private Integer pageSize; - @Schema(description = "排序字段: create_time / update_time / name / size", example = "create_time") + @Schema(description = "Sort field: create_time / update_time / name / size", example = "create_time") private String orderby; - @Schema(description = "是否降序", example = "true") + @Schema(description = "Whether sorting is descending", example = "true") private Boolean desc; } - // ========== 响应类 ========== + // ========== Responses ========== /** - * 文件/文件夹基础信息 VO + * Basic file or folder information. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文件/文件夹基础信息") + @Schema(description = "Basic file or folder information") public static class InfoVO implements Serializable { - @Schema(description = "文件/文件夹 ID", example = "file_001") + @Schema(description = "File or folder ID", example = "file_001") private String id; - @Schema(description = "父文件夹 ID", example = "folder_001") + @Schema(description = "Parent folder ID", example = "folder_001") @JsonProperty("parent_id") private String parentId; - @Schema(description = "租户 ID", example = "tenant_001") + @Schema(description = "Tenant ID", example = "tenant_001") @JsonProperty("tenant_id") private String tenantId; - @Schema(description = "创建者 ID", example = "user_001") + @Schema(description = "Creator ID", example = "user_001") @JsonProperty("created_by") private String createdBy; - @Schema(description = "类型: FOLDER / FILE", example = "FOLDER") + @Schema(description = "Type: FOLDER / FILE", example = "FOLDER") private String type; - @Schema(description = "名称", example = "我的文件夹") + @Schema(description = "Name", example = "My Folder") private String name; - @Schema(description = "路径位置", example = "/root/folder") + @Schema(description = "Path location", example = "/root/folder") private String location; - @Schema(description = "文件大小 (字节)", example = "1024") + @Schema(description = "File size in bytes", example = "1024") private Long size; - @Schema(description = "来源类型", example = "local") + @Schema(description = "Source type", example = "local") @JsonProperty("source_type") private String sourceType; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "创建日期 (格式化)", example = "2024-01-15 10:30:00") + @Schema(description = "Formatted creation date", example = "2024-01-15 10:30:00") @JsonProperty("create_date") private String createDate; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; - @Schema(description = "更新日期 (格式化)", example = "2024-01-15 11:00:00") + @Schema(description = "Formatted update date", example = "2024-01-15 11:00:00") @JsonProperty("update_date") private String updateDate; - @Schema(description = "文件扩展名", example = "pdf") + @Schema(description = "File extension", example = "pdf") private String extension; } /** - * 列表响应 VO (对应接口 3: list_files) + * List response. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文件列表响应") + @Schema(description = "File list response") public static class ListVO implements Serializable { - @Schema(description = "总记录数", example = "100") + @Schema(description = "Total record count", example = "100") private Long total; - @Schema(description = "当前父文件夹信息") + @Schema(description = "Current parent folder information") @JsonProperty("parent_folder") private InfoVO parentFolder; - @Schema(description = "文件/文件夹列表") + @Schema(description = "List of files and folders") private List files; - @Schema(description = "面包屑导航路径") + @Schema(description = "Breadcrumb navigation path") private List breadcrumb; } /** - * 转换结果项 VO (对应接口 9: convert) + * Conversion result item. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文件转换结果项") + @Schema(description = "File conversion result item") public static class ConvertVO implements Serializable { - @Schema(description = "转换记录 ID", example = "convert_001") + @Schema(description = "Conversion record ID", example = "convert_001") private String id; - @Schema(description = "源文件 ID", example = "file_001") + @Schema(description = "Source file ID", example = "file_001") @JsonProperty("file_id") private String fileId; - @Schema(description = "目标文档 ID", example = "doc_001") + @Schema(description = "Target document ID", example = "doc_001") @JsonProperty("document_id") private String documentId; - @Schema(description = "创建时间 (时间戳)", example = "1700000000000") + @Schema(description = "Creation time as a timestamp", example = "1700000000000") @JsonProperty("create_time") private Long createTime; - @Schema(description = "创建日期 (格式化)", example = "2024-01-15 10:30:00") + @Schema(description = "Formatted creation date", example = "2024-01-15 10:30:00") @JsonProperty("create_date") private String createDate; - @Schema(description = "更新时间 (时间戳)", example = "1700000001000") + @Schema(description = "Update time as a timestamp", example = "1700000001000") @JsonProperty("update_time") private Long updateTime; - @Schema(description = "更新日期 (格式化)", example = "2024-01-15 11:00:00") + @Schema(description = "Formatted update date", example = "2024-01-15 11:00:00") @JsonProperty("update_date") private String updateDate; } /** - * 转换状态 VO (对应接口 10: get_convert_status) + * Conversion status. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "文件转换状态") + @Schema(description = "File conversion status") public static class ConvertStatusVO implements Serializable { - @Schema(description = "转换状态: pending / processing / completed / failed", example = "completed") + @Schema(description = "Conversion status: pending / processing / completed / failed", example = "completed") private String status; - @Schema(description = "转换进度 (0.0 - 1.0)", example = "1.0") + @Schema(description = "Conversion progress (0.0 - 1.0)", example = "1.0") private Float progress; - @Schema(description = "状态消息", example = "转换完成") + @Schema(description = "Status message", example = "Conversion completed") private String message; } /** - * 面包屑 VO (对应接口 12: all_parent_folder) + * Breadcrumb data. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "面包屑导航 (所有父文件夹)") + @Schema(description = "Breadcrumb navigation") public static class BreadcrumbVO implements Serializable { - @Schema(description = "父文件夹列表 (从根到当前的路径)") + @Schema(description = "Parent folder list from root to current path") @JsonProperty("parent_folders") private List parentFolders; } /** - * 根目录信息 VO (对应接口 10: get_root_folder) + * Root folder information. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "根目录信息") + @Schema(description = "Root folder information") public static class RootFolderVO implements Serializable { - @Schema(description = "根文件夹信息") + @Schema(description = "Root folder information") @JsonProperty("root_folder") private InfoVO rootFolder; } /** - * 父目录信息 VO (对应接口 11: get_parent_folder) + * Parent folder information. */ @Data @NoArgsConstructor @AllArgsConstructor @Builder - @Schema(description = "父目录信息") + @Schema(description = "Parent folder information") public static class ParentFolderVO implements Serializable { - @Schema(description = "父文件夹信息") + @Schema(description = "Parent folder information") @JsonProperty("parent_folder") private InfoVO parentFolder; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/DocumentEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/DocumentEntity.java index 1c248884e..513859711 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/DocumentEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/DocumentEntity.java @@ -13,85 +13,85 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 文档表 (Shadow DB for RAGFlow Documents) - * 对应表名: ai_knowledge_document + * Document shadow table for RAGFlow documents. + * Backed by table: ai_knowledge_document. */ @Data @TableName(value = "ai_rag_knowledge_document", autoResultMap = true) -@Schema(description = "知识库文档表") +@Schema(description = "Knowledge-base document table") public class DocumentEntity implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "本地唯一ID") + @Schema(description = "Local unique ID") private String id; - @Schema(description = "知识库ID (关联 ai_rag_dataset.dataset_id)") + @Schema(description = "Knowledge-base ID linked to ai_rag_dataset.dataset_id") private String datasetId; - @Schema(description = "RAGFlow文档ID (远程ID)") + @Schema(description = "Remote RAGFlow document ID") private String documentId; - @Schema(description = "文档名称") + @Schema(description = "Document name") private String name; - @Schema(description = "文件大小(Bytes)") + @Schema(description = "File size in bytes") private Long size; - @Schema(description = "文件类型(pdf/doc/txt等)") + @Schema(description = "File type such as pdf, doc, or txt") private String type; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") private String chunkMethod; - @Schema(description = "解析配置(JSON String)") + @Schema(description = "Parser configuration as JSON") private String parserConfig; - @Schema(description = "可用状态 (1: 启用/正常, 0: 禁用/失效)") + @Schema(description = "Availability status (1 enabled/healthy, 0 disabled/invalid)") private String status; - @Schema(description = "运行状态 (UNSTART/RUNNING/CANCEL/DONE/FAIL)") + @Schema(description = "Run state (UNSTART/RUNNING/CANCEL/DONE/FAIL)") private String run; - @Schema(description = "解析进度 (0.0 ~ 1.0)") + @Schema(description = "Parse progress (0.0 to 1.0)") private Double progress; - @Schema(description = "缩略图 (Base64 或 URL)") + @Schema(description = "Thumbnail (Base64 or URL)") private String thumbnail; - @Schema(description = "解析耗时 (单位: 秒)") + @Schema(description = "Parse duration in seconds") private Double processDuration; - @Schema(description = "自定义元数据 (JSON 格式)") + @Schema(description = "Custom metadata in JSON format") private String metaFields; - @Schema(description = "来源类型 (local, s3, url 等)") + @Schema(description = "Source type such as local, s3, or url") private String sourceType; - @Schema(description = "解析错误信息") + @Schema(description = "Parse error message") private String error; - @Schema(description = "分块数量") + @Schema(description = "Chunk count") private Integer chunkCount; - @Schema(description = "Token数量") + @Schema(description = "Token count") private Long tokenCount; - @Schema(description = "是否启用 (0:禁用 1:启用)") + @Schema(description = "Enabled flag (0 disabled, 1 enabled)") private Integer enabled; - @Schema(description = "创建者") + @Schema(description = "Created by") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Created at") @TableField(fill = FieldFill.INSERT) private Date createdAt; - @Schema(description = "更新时间") + @Schema(description = "Updated at") @TableField(fill = FieldFill.UPDATE) private Date updatedAt; - @Schema(description = "最新同步时间") + @Schema(description = "Last synchronization time") private Date lastSyncAt; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java index 8afaa0b13..6215dbe83 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java @@ -13,69 +13,69 @@ import lombok.Data; @Data @TableName(value = "ai_rag_dataset", autoResultMap = true) -@Schema(description = "知识库知识库表") +@Schema(description = "Knowledge-base table") public class KnowledgeBaseEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "唯一标识") + @Schema(description = "Unique ID") private String id; - @Schema(description = "知识库ID") + @Schema(description = "Knowledge-base ID") private String datasetId; // @Deprecated - @Schema(description = "RAG模型配置ID (连接RAGFlow的凭证指针)") + @Schema(description = "RAG model configuration ID used as the RAGFlow credential pointer") private String ragModelId; - @Schema(description = "租户ID") + @Schema(description = "Tenant ID") private String tenantId; - @Schema(description = "知识库名称") + @Schema(description = "Knowledge-base name") private String name; - @Schema(description = "知识库头像(Base64)") + @Schema(description = "Knowledge-base avatar in Base64") private String avatar; - @Schema(description = "知识库描述") + @Schema(description = "Knowledge-base description") private String description; - @Schema(description = "嵌入模型名称") + @Schema(description = "Embedding model name") private String embeddingModel; - @Schema(description = "权限设置: me/team") + @Schema(description = "Permission setting, for example me or team") private String permission; - @Schema(description = "分块方法") + @Schema(description = "Chunking method") private String chunkMethod; - @Schema(description = "解析器配置(JSON String)") + @Schema(description = "Parser configuration as JSON") private String parserConfig; - @Schema(description = "分块总数") + @Schema(description = "Total chunk count") private Long chunkCount; - @Schema(description = "文档总数") + @Schema(description = "Total document count") private Long documentCount; - @Schema(description = "总Token数") + @Schema(description = "Total token count") private Long tokenNum; - @Schema(description = "状态(0:禁用 1:启用)") + @Schema(description = "Status flag (0 disabled, 1 enabled)") private Integer status; - @Schema(description = "创建者") + @Schema(description = "Created by") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Created at") @TableField(fill = FieldFill.INSERT) private Date createdAt; - @Schema(description = "更新者") + @Schema(description = "Updated by") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Updated at") @TableField(fill = FieldFill.UPDATE) private Date updatedAt; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapter.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapter.java index 2c45e797d..b3914a484 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapter.java @@ -13,70 +13,68 @@ import xiaozhi.modules.knowledge.dto.document.RetrievalDTO; import java.util.function.Consumer; /** - * 知识库API适配器抽象基类 - * 定义通用的知识库操作接口,支持多种后端API实现 + * Abstract base class for knowledge-base API adapters. + * Defines the common operations shared by multiple backend implementations. */ public abstract class KnowledgeBaseAdapter { /** - * 获取适配器类型标识 + * Return the adapter type identifier. * - * @return 适配器类型(如:ragflow, milvus, pinecone等) + * @return adapter type, for example ragflow, milvus, or pinecone */ public abstract String getAdapterType(); /** - * 初始化适配器配置 + * Initialize the adapter configuration. * - * @param config 配置参数 + * @param config configuration values */ public abstract void initialize(Map config); /** - * 验证配置是否有效 + * Validate the adapter configuration. * - * @param config 配置参数 - * @return 验证结果 + * @param config configuration values + * @return validation result */ public abstract boolean validateConfig(Map config); /** - * 分页查询文档列表 + * Query the document list with pagination. * - * @param datasetId 知识库ID - * @param queryParams 查询参数 - * @param page 页码 - * @param limit 每页数量 - * @return 分页数据 + * @param datasetId knowledge base ID + * @param req query parameters + * @return paged result */ public abstract PageData getDocumentList(String datasetId, DocumentDTO.ListReq req); /** - * 根据文档ID获取文档详情 + * Load document details by document ID. * - * @param datasetId 知识库ID - * @param documentId 文档ID - * @return 文档详情 (强类型 InfoVO) + * @param datasetId knowledge base ID + * @param documentId document ID + * @return document details as a strongly typed InfoVO */ public abstract DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId); /** - * 上传文档到知识库 + * Upload a document to the knowledge base. * - * @param req 上传请求参数 - * @return 上传的文档信息 + * @param req upload request parameters + * @return uploaded document information */ public abstract KnowledgeFilesDTO uploadDocument(DocumentDTO.UploadReq req); /** - * 根据状态分页查询文档列表 + * Query the document list by status with pagination. * - * @param datasetId 知识库ID - * @param status 文档解析状态 - * @param page 页码 - * @param limit 每页数量 - * @return 分页数据 + * @param datasetId knowledge base ID + * @param status document parsing status + * @param page page number + * @param limit page size + * @return paged result */ public abstract PageData getDocumentListByStatus(String datasetId, Integer status, @@ -84,93 +82,93 @@ public abstract class KnowledgeBaseAdapter { Integer limit); /** - * 删除文档 (支持批量删除) + * Delete one or more documents. * - * @param datasetId 知识库ID - * @param req 包含文档ID列表的请求对象 + * @param datasetId knowledge base ID + * @param req request object containing document IDs */ public abstract void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req); /** - * 解析文档(切块) + * Parse documents into chunks. * - * @param datasetId 知识库ID - * @param documentIds 文档ID列表 - * @return 解析结果 + * @param datasetId knowledge base ID + * @param documentIds document ID list + * @return parse result */ public abstract boolean parseDocuments(String datasetId, List documentIds); /** - * 列出指定文档的切片 + * List chunks for the specified document. * - * @param datasetId 知识库ID - * @param documentId 文档ID - * @param req 列表请求参数 (分页、关键词等) - * @return 切片列表VO + * @param datasetId knowledge base ID + * @param documentId document ID + * @param req list request parameters such as paging and keywords + * @return chunk list response */ public abstract ChunkDTO.ListVO listChunks(String datasetId, String documentId, ChunkDTO.ListReq req); /** - * 召回测试 - 从知识库中检索相关切片 + * Run a retrieval test against the knowledge base. * - * @param req 检索测试请求参数 - * @return 召回测试结果 + * @param req retrieval test request + * @return retrieval test result */ public abstract RetrievalDTO.ResultVO retrievalTest( RetrievalDTO.TestReq req); /** - * 测试连接 + * Test the backend connection. * - * @return 连接测试结果 + * @return connection test result */ public abstract boolean testConnection(); /** - * 获取适配器状态信息 + * Return adapter status information. * - * @return 状态信息 + * @return status information */ public abstract Map getStatus(); /** - * 获取支持的配置参数 + * Return supported configuration parameters. * - * @return 配置参数说明 + * @return configuration description */ public abstract Map getSupportedConfig(); /** - * 获取默认配置 + * Return default configuration values. * - * @return 默认配置 + * @return default configuration */ public abstract Map getDefaultConfig(); /** - * 创建数据集 + * Create a dataset. * - * @param req 创建参数 - * @return 数据集详情 + * @param req creation parameters + * @return dataset details */ public abstract DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req); /** - * 更新数据集 + * Update a dataset. * - * @param datasetId 数据集ID - * @param req 更新参数 - * @return 数据集详情 + * @param datasetId dataset ID + * @param req update parameters + * @return dataset details */ public abstract DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req); /** - * 删除数据集 + * Delete one or more datasets. * - * @param req 删除请求参数(包含ID列表) - * @return 批量操作结果 + * @param req delete request parameters containing IDs + * @return batch operation result */ public abstract DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req); @@ -194,31 +192,31 @@ public abstract class KnowledgeBaseAdapter { /** * 发送流式请求 (SSE) * - * @param endpoint API端点 - * @param body 请求体 - * @param onData 数据回调 + * @param endpoint API endpoint + * @param body request body + * @param onData data callback */ public abstract void postStream(String endpoint, Object body, Consumer onData); /** - * SearchBot 提问 + * Ask SearchBot. * - * @param config RAG配置 - * @param body 请求体 - * @param onData 数据回调 - * @return 响应对象 + * @param config RAG configuration + * @param body request body + * @param onData data callback + * @return response object */ public abstract Object postSearchBotAsk(Map config, Object body, Consumer onData); /** - * AgentBot 对话 + * Run an AgentBot completion. * - * @param config RAG配置 + * @param config RAG configuration * @param agentId Agent ID - * @param body 请求体 - * @param onData 数据回调 + * @param body request body + * @param onData data callback */ public abstract void postAgentBotCompletion(Map config, String agentId, Object body, Consumer onData); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactory.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactory.java index 4655de07d..c710c9478 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactory.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactory.java @@ -10,115 +10,115 @@ import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; /** - * 知识库适配器工厂类 - * 负责创建和管理不同类型的知识库API适配器 + * Factory for knowledge-base adapters. + * Responsible for creating and managing different knowledge-base API adapter types. */ @Slf4j public class KnowledgeBaseAdapterFactory { - // 注册的适配器类型映射 + // Registered adapter type mapping. private static final Map> adapterRegistry = new HashMap<>(); - // 适配器实例缓存 + // Adapter instance cache. private static final Map adapterCache = new ConcurrentHashMap<>(); - // 最大缓存实例数,防止内存泄露 (Issue 9) + // Maximum cache size to guard against memory leaks (Issue 9). private static final int MAX_CACHE_SIZE = 50; static { - // 注册内置适配器类型 + // Register built-in adapter types. registerAdapter("ragflow", xiaozhi.modules.knowledge.rag.impl.RAGFlowAdapter.class); - // 可以在这里注册更多适配器类型 + // Additional adapter types can be registered here later. } /** - * 注册新的适配器类型 + * Register a new adapter type. * - * @param adapterType 适配器类型标识 - * @param adapterClass 适配器类 + * @param adapterType adapter type identifier + * @param adapterClass adapter class */ public static void registerAdapter(String adapterType, Class adapterClass) { if (adapterRegistry.containsKey(adapterType)) { - log.warn("适配器类型 '{}' 已存在,将被覆盖", adapterType); + log.warn("Adapter type '{}' already exists and will be overwritten", adapterType); } adapterRegistry.put(adapterType, adapterClass); - log.info("注册适配器类型: {} -> {}", adapterType, adapterClass.getSimpleName()); + log.info("Registered adapter type: {} -> {}", adapterType, adapterClass.getSimpleName()); } /** - * 获取适配器实例 + * Return an adapter instance. * - * @param adapterType 适配器类型 - * @param config 配置参数 - * @return 适配器实例 + * @param adapterType adapter type + * @param config configuration values + * @return adapter instance */ public static KnowledgeBaseAdapter getAdapter(String adapterType, Map config) { String cacheKey = buildCacheKey(adapterType, config); - // 检查缓存中是否已存在实例 + // Reuse a cached instance when available. if (adapterCache.containsKey(cacheKey)) { - log.debug("从缓存获取适配器实例: {}", cacheKey); + log.debug("Loaded adapter instance from cache: {}", cacheKey); return adapterCache.get(cacheKey); } - // 创建新的适配器实例 + // Create a new adapter instance. KnowledgeBaseAdapter adapter = createAdapter(adapterType, config); - // 缓存适配器实例 (带容量限制检查) + // Cache the adapter instance with a capacity guard. if (adapterCache.size() >= MAX_CACHE_SIZE) { - log.warn("适配器缓存已达上限 ({}),执行内存保护性清除", MAX_CACHE_SIZE); - // 简单处理:直接清空,生产环境下建议使用 LRU + log.warn("Adapter cache reached its limit ({}), clearing it as a memory-safety fallback", MAX_CACHE_SIZE); + // Simple fallback: clear the cache. An LRU strategy would be better in production. adapterCache.clear(); } adapterCache.put(cacheKey, adapter); - log.info("创建并缓存适配器实例: {}", cacheKey); + log.info("Created and cached adapter instance: {}", cacheKey); return adapter; } /** - * 获取适配器实例(无配置) + * Return an adapter instance without explicit configuration. * - * @param adapterType 适配器类型 - * @return 适配器实例 + * @param adapterType adapter type + * @return adapter instance */ public static KnowledgeBaseAdapter getAdapter(String adapterType) { return getAdapter(adapterType, null); } /** - * 获取所有已注册的适配器类型 + * Return all registered adapter types. * - * @return 适配器类型集合 + * @return registered adapter types */ public static Set getRegisteredAdapterTypes() { return adapterRegistry.keySet(); } /** - * 检查适配器类型是否已注册 + * Check whether an adapter type is registered. * - * @param adapterType 适配器类型 - * @return 是否已注册 + * @param adapterType adapter type + * @return whether the adapter type is registered */ public static boolean isAdapterTypeRegistered(String adapterType) { return adapterRegistry.containsKey(adapterType); } /** - * 清除适配器缓存 + * Clear the adapter cache. */ public static void clearCache() { int cacheSize = adapterCache.size(); adapterCache.clear(); - log.info("清除适配器缓存,共清除 {} 个实例", cacheSize); + log.info("Cleared the adapter cache and removed {} instances", cacheSize); } /** - * 移除特定适配器类型的缓存 + * Remove cached instances for a specific adapter type. * - * @param adapterType 适配器类型 + * @param adapterType adapter type */ public static void removeCacheByType(String adapterType) { int removedCount = 0; @@ -128,13 +128,13 @@ public class KnowledgeBaseAdapterFactory { removedCount++; } } - log.info("移除适配器类型 '{}' 的缓存,共移除 {} 个实例", adapterType, removedCount); + log.info("Removed {} cached instances for adapter type '{}'", removedCount, adapterType); } /** - * 获取适配器工厂状态信息 + * Return adapter-factory status information. * - * @return 状态信息 + * @return status information */ public static Map getFactoryStatus() { Map status = new HashMap<>(); @@ -145,62 +145,62 @@ public class KnowledgeBaseAdapterFactory { } /** - * 创建适配器实例 + * Create an adapter instance. * - * @param adapterType 适配器类型 - * @param config 配置参数 - * @return 适配器实例 + * @param adapterType adapter type + * @param config configuration values + * @return adapter instance */ private static KnowledgeBaseAdapter createAdapter(String adapterType, Map config) { if (!adapterRegistry.containsKey(adapterType)) { throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, - "不支持的适配器类型: " + adapterType); + "Unsupported adapter type: " + adapterType); } try { Class adapterClass = adapterRegistry.get(adapterType); KnowledgeBaseAdapter adapter = adapterClass.getDeclaredConstructor().newInstance(); - // 初始化适配器 + // Initialize the adapter. if (config != null) { adapter.initialize(config); - // 验证配置 + // Validate the configuration. if (!adapter.validateConfig(config)) { throw new RenException(ErrorCode.RAG_CONFIG_VALIDATION_FAILED, - "适配器配置验证失败: " + adapterType); + "Adapter configuration validation failed: " + adapterType); } } - log.info("成功创建适配器实例: {}", adapterType); + log.info("Successfully created adapter instance: {}", adapterType); return adapter; } catch (Exception e) { - log.error("创建适配器实例失败: {}", adapterType, e); + log.error("Failed to create adapter instance: {}", adapterType, e); throw new RenException(ErrorCode.RAG_ADAPTER_CREATION_FAILED, - "创建适配器失败: " + adapterType + ", 错误: " + e.getMessage()); + "Failed to create adapter: " + adapterType + ", error: " + e.getMessage()); } } /** - * 构建缓存键 + * Build the cache key. * - * @param adapterType 适配器类型 - * @param config 配置参数 - * @return 缓存键 + * @param adapterType adapter type + * @param config configuration values + * @return cache key */ private static String buildCacheKey(String adapterType, Map config) { if (config == null || config.isEmpty()) { return adapterType + "@default"; } - // 基于配置参数生成缓存键 + // Build the key from the configuration values. StringBuilder keyBuilder = new StringBuilder(adapterType + "@"); - // 使用配置的哈希值作为缓存键的一部分 + // Use the configuration hash as part of the cache key. int configHash = config.hashCode(); keyBuilder.append(configHash); return keyBuilder.toString(); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/RAGFlowClient.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/RAGFlowClient.java index 9f204e986..711908da6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/RAGFlowClient.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/RAGFlowClient.java @@ -37,7 +37,7 @@ import xiaozhi.common.exception.RenException; /** * RAGFlow HTTP Client - * 统一处理HTTP通信、鉴权、超时与错误解析 + * Handles HTTP communication, authentication, timeouts, and error parsing. */ @Slf4j public class RAGFlowClient { @@ -47,7 +47,7 @@ public class RAGFlowClient { private final RestTemplate restTemplate; private final ObjectMapper objectMapper; - // 默认超时时间 (秒) + // Default timeout in seconds. private static final int DEFAULT_TIMEOUT = 30; public RAGFlowClient(String baseUrl, String apiKey) { @@ -58,25 +58,26 @@ public class RAGFlowClient { this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; this.apiKey = apiKey; this.objectMapper = new ObjectMapper(); - // [Reinforce] 兼容 RAGFlow 返回的 RFC 1123 日期格式 (如: Tue, 10 Feb 2026 10:27:35 GMT) + // Support RFC 1123 dates returned by RAGFlow, such as Tue, 10 Feb 2026 10:27:35 GMT. this.objectMapper .setDateFormat(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)); this.objectMapper.setTimeZone(TimeZone.getTimeZone("GMT")); - // 优先从 Spring 上下文中获取池化的 RestTemplate Bean (Issue 3: 连接池化) + // Prefer a pooled RestTemplate bean from the Spring context when available. RestTemplate pooledTemplate = null; try { pooledTemplate = xiaozhi.common.utils.SpringContextUtils.getBean(RestTemplate.class); } catch (Exception e) { - log.warn("无法从 SpringContext 获取池化 RestTemplate,将退化为简单连接模式: {}", e.getMessage()); + log.warn("Unable to load pooled RestTemplate from SpringContext, falling back to simple connection mode: {}", + e.getMessage()); } if (false) { // Force new RestTemplate for debugging this.restTemplate = pooledTemplate; - log.debug("RAGFlowClient 已成功挂载全局池化 RestTemplate"); + log.debug("RAGFlowClient attached the global pooled RestTemplate successfully"); } else { - // 兜底方案:配置超时并创建简单 RestTemplate - log.info("RAGFlowClient 初始化: 使用独立 RestTemplate (Debug Mode)"); + // Fallback path: configure timeouts and create a simple RestTemplate. + log.info("RAGFlowClient initialized with an independent RestTemplate (debug mode)"); SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(timeoutSeconds * 1000); factory.setReadTimeout(timeoutSeconds * 1000); @@ -85,7 +86,7 @@ public class RAGFlowClient { } /** - * 发送 GET 请求 + * Send a GET request. */ public Map get(String endpoint, Map queryParams) { String url = buildUrl(endpoint, queryParams); @@ -94,7 +95,7 @@ public class RAGFlowClient { } /** - * 发送 POST 请求 (JSON) + * Send a POST request with JSON. */ public Map post(String endpoint, Object body) { String url = buildUrl(endpoint, null); @@ -109,7 +110,7 @@ public class RAGFlowClient { } /** - * 发送 DELETE 请求 + * Send a DELETE request. */ public Map delete(String endpoint, Object body) { String url = buildUrl(endpoint, null); @@ -118,7 +119,7 @@ public class RAGFlowClient { } /** - * 发送 PUT 请求 + * Send a PUT request. */ public Map put(String endpoint, Object body) { String url = buildUrl(endpoint, null); @@ -127,7 +128,7 @@ public class RAGFlowClient { } /** - * 发送 Multipart 请求 (文件上传) + * Send a multipart request for file upload. */ public Map postMultipart(String endpoint, MultiValueMap parts) { String url = buildUrl(endpoint, null); @@ -136,7 +137,7 @@ public class RAGFlowClient { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setBearerAuth(apiKey); - // 为了防止中文文件名乱码,某些环境可能需要设置 Charset,但在 Multipart 中通常由 Part header 控制 + // Some environments may require charset handling for non-ASCII file names, but multipart usually relies on part headers. HttpEntity> requestEntity = new HttpEntity<>(parts, headers); @@ -147,7 +148,7 @@ public class RAGFlowClient { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(apiKey); - // 强制 UTF-8 + // Force UTF-8. headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); HttpEntity requestEntity = new HttpEntity<>(body, headers); @@ -178,12 +179,8 @@ public class RAGFlowClient { throw new RenException(ErrorCode.RAG_API_ERROR, msg != null ? msg : "Unknown RAGFlow Error"); } - // 返回 data 字段,如果 data 不存在则返回整个 map (视具体情况,通常 RAGFlow 返回 code=0, data=...) - // 兼容性处理:如果 external caller 需要 check code,这里已经 check 过了。 - // 统一返回 wrap 了 code 的 map 还是只返回 data? - // 根据分析报告,旧逻辑 check code==0 后取 data. - // 这里我们返回整个 Map,让 Adapter 决定怎么取,或者我们直接在这里剥离? - // 建议:为了灵活性,返回全量 Map,但在 Client 层做 code!=0 的抛错。 + // Return the full response map after validating code != 0 here. + // This keeps the client flexible while centralizing business-error handling. return map; } catch (RenException re) { @@ -213,24 +210,24 @@ public class RAGFlowClient { StandardCharsets.UTF_8.name())) .append("&"); } catch (UnsupportedEncodingException e) { - log.warn("参数编码失败: k={}, v={}", k, v); + log.warn("Failed to encode query parameter: k={}, v={}", k, v); sb.append(k).append("=").append(v).append("&"); } } }); - // 移除最后一个 & + // Remove the trailing ampersand. sb.setLength(sb.length() - 1); } return sb.toString(); } /** - * 发送流式 POST 请求 (SSE) - * 使用 Java 21 HttpClient 实现 + * Send a streaming POST request using SSE. + * Implemented with the Java 21 HttpClient. * - * @param endpoint API端点 - * @param body 请求体 - * @param onData 数据回调(每收到一行数据调用一次) + * @param endpoint API endpoint + * @param body request body + * @param onData callback invoked for each received line */ public void postStream(String endpoint, Object body, Consumer onData) { try { @@ -250,7 +247,7 @@ public class RAGFlowClient { .POST(HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8)) .build(); - // 发送请求并处理流式响应 + // Send the request and process the streaming response. httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()) .body() .transferTo(new OutputStream() { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java index 13a6decfa..32a6af768 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java @@ -32,11 +32,11 @@ import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapter; import xiaozhi.modules.knowledge.rag.RAGFlowClient; /** - * RAGFlow知识库适配器实现 + * RAGFlow knowledge-base adapter implementation. *

- * 重构说明 (Refactoring Note): - * 本类已升级为使用 {@link RAGFlowClient} 统一处理 HTTP 通信。 - * 解决了旧代码中 Timeout 缺失、Error Handling 分散的问题。 + * Refactoring note: + * This class now uses {@link RAGFlowClient} to centralize HTTP communication + * and fix the old scattered timeout and error-handling behavior. *

*/ @Slf4j @@ -46,7 +46,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { private Map config; private ObjectMapper objectMapper; - // Client 实例,初始化时创建 + // Client instance created during initialization. private RAGFlowClient client; public RAGFlowAdapter() { @@ -66,18 +66,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { String baseUrl = getConfigValue(config, "base_url", "baseUrl"); String apiKey = getConfigValue(config, "api_key", "apiKey"); - // 初始化 Client,默认超时 30s,可通过 config 扩展 + // Initialize the client. Default timeout is 30 seconds and can be overridden in config. int timeout = 30; Object timeoutObj = getConfigValue(config, "timeout", "timeout"); if (timeoutObj != null) { try { timeout = Integer.parseInt(timeoutObj.toString()); } catch (Exception e) { - log.warn("解析超时配置失败,使用默认值 30s"); + log.warn("Failed to parse the timeout configuration, using the default value of 30s"); } } this.client = new RAGFlowClient(baseUrl, apiKey, timeout); - log.info("RAGFlow适配器初始化完成,Client已就绪"); + log.info("RAGFlow adapter initialization completed and the client is ready"); } @Override @@ -97,7 +97,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_NULL); } - if (apiKey.contains("你")) { + if (apiKey.contains("your")) { throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_INVALID); } @@ -109,7 +109,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 辅助方法:支持多种键名获取配置(兼容 camelCase 和 snake_case) + * Helper: read config values using either camelCase or snake_case keys. */ private String getConfigValue(Map config, String snakeKey, String camelKey) { if (config.containsKey(snakeKey)) { @@ -122,15 +122,15 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 辅助方法:确保 Client 已初始化 + * Helper: ensure the client has been initialized. */ private RAGFlowClient getClient() { if (this.client == null) { - // 尝试重新初始化 + // Attempt to initialize again. if (this.config != null) { initialize(this.config); } else { - throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "适配器未初始化"); // 应该抛出 RuntimeException + throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "Adapter has not been initialized"); } } return this.client; @@ -146,9 +146,9 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public PageData getDocumentList(String datasetId, DocumentDTO.ListReq req) { try { - log.info("=== [RAGFlow] 获取文档列表: datasetId={} ===", datasetId); + log.info("=== [RAGFlow] Loading document list: datasetId={} ===", datasetId); - // 使用 Jackson 将 DTO 转为 Map 作为查询参数 + // Convert the DTO to a query-parameter map through Jackson. @SuppressWarnings("unchecked") Map params = objectMapper.convertValue(req, Map.class); @@ -159,7 +159,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { req.getPageSize() != null ? req.getPageSize() : 10); } catch (Exception e) { - log.error("获取文档列表失败", e); + log.error("Failed to load the document list", e); throw convertToRenException(e); } } @@ -167,7 +167,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId) { try { - log.info("=== [RAGFlow] 获取文档详情: datasetId={}, documentId={} ===", datasetId, documentId); + log.info("=== [RAGFlow] Loading document details: datasetId={}, documentId={} ===", datasetId, documentId); DocumentDTO.ListReq req = DocumentDTO.ListReq.builder() .id(documentId) .page(1) @@ -188,7 +188,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("获取文档详情失败: documentId={}", documentId, e); + log.error("Failed to load document details: documentId={}", documentId, e); throw convertToRenException(e); } } @@ -198,7 +198,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { String datasetId = req.getDatasetId(); MultipartFile file = req.getFile(); try { - log.info("=== [RAGFlow] 上传文档: datasetId={} ===", datasetId); + log.info("=== [RAGFlow] Uploading document: datasetId={} ===", datasetId); MultiValueMap body = new LinkedMultiValueMap<>(); body.add("file", new MultipartFileResource(file)); @@ -210,7 +210,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { body.add("meta", objectMapper.writeValueAsString(req.getMetaFields())); } if (req.getChunkMethod() != null) { - // 将枚举值转为 RAGFlow 期待的字符串(如 NAIVE -> naive) + // Convert the enum to the lowercase string expected by RAGFlow, for example NAIVE -> naive. body.add("chunk_method", req.getChunkMethod().name().toLowerCase()); } if (req.getParserConfig() != null) { @@ -227,7 +227,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { return parseUploadResponse(dataObj, datasetId, file); } catch (Exception e) { - log.error("文档上传失败", e); + log.error("Document upload failed", e); throw convertToRenException(e); } } @@ -269,11 +269,11 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req) { try { - log.info("=== [RAGFlow] 批量删除文档: datasetId={}, count={} ===", datasetId, + log.info("=== [RAGFlow] Bulk deleting documents: datasetId={}, count={} ===", datasetId, req.getIds() != null ? req.getIds().size() : 0); getClient().delete("/api/v1/datasets/" + datasetId + "/documents", req); } catch (Exception e) { - log.error("批量删除文档失败: datasetId={}", datasetId, e); + log.error("Bulk document deletion failed: datasetId={}", datasetId, e); throw convertToRenException(e); } } @@ -281,14 +281,14 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public boolean parseDocuments(String datasetId, List documentIds) { try { - log.info("=== [RAGFlow] 解析文档 ==="); + log.info("=== [RAGFlow] Parsing documents ==="); Map body = new HashMap<>(); body.put("document_ids", documentIds); getClient().post("/api/v1/datasets/" + datasetId + "/chunks", body); return true; } catch (Exception e) { - log.error("解析文档失败", e); + log.error("Document parsing failed", e); throw convertToRenException(e); } } @@ -296,7 +296,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public ChunkDTO.ListVO listChunks(String datasetId, String documentId, ChunkDTO.ListReq req) { try { - // [提灯重构] 使用 objectMapper 动态转换查询参数,消除硬编码 + // [Refactor] Convert query parameters dynamically with objectMapper to avoid hard-coded mapping. Map params = objectMapper.convertValue(req, new TypeReference>() { }); @@ -305,7 +305,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { Object dataObj = response.get("data"); if (dataObj == null) { - log.warn("[RAGFlow] listChunks 响应 data 为空, docId={}", documentId); + log.warn("[RAGFlow] listChunks returned an empty data payload, docId={}", documentId); return ChunkDTO.ListVO.builder() .chunks(new ArrayList<>()) .total(0L) @@ -318,7 +318,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return result; } catch (Exception e) { - log.error("获取切片失败: docId={}", documentId, e); + log.error("Failed to load chunks: docId={}", documentId, e); throw convertToRenException(e); } } @@ -326,18 +326,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) { try { - // [Production Reinforce] 参数防御性对齐:RAGFlow Python 端对 0 或负数分页敏感 - // 解决 ValueError('Search does not support negative slicing.') + // [Production Reinforce] Normalize paging defensively because the Python side is sensitive + // to zero or negative slicing and can raise ValueError. if (req.getPage() != null && req.getPage() < 1) { req.setPage(1); } if (req.getPageSize() != null && req.getPageSize() < 1) { - req.setPageSize(10); // 默认 10 条 + req.setPageSize(10); // Default to 10 rows. } if (req.getTopK() != null && req.getTopK() < 1) { - req.setTopK(1024); // RAGFlow 内部默认 TopK + req.setTopK(1024); // Internal RAGFlow default TopK. } - // 相似度阈值归一化 (0.0 ~ 1.0) + // Normalize the similarity threshold to the 0.0 to 1.0 range. if (req.getSimilarityThreshold() != null) { if (req.getSimilarityThreshold() < 0f) req.setSimilarityThreshold(0.2f); @@ -345,12 +345,12 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { req.setSimilarityThreshold(1.0f); } - // [提灯重构] 直接透传强类型 DTO,由 getClient 处理序列化 + // [Refactor] Pass the strongly typed DTO directly and let getClient handle serialization. Map response = getClient().post("/api/v1/retrieval", req); Object dataObj = response.get("data"); if (dataObj == null) { - log.warn("[RAGFlow] retrievalTest 响应 data 为空"); + log.warn("[RAGFlow] retrievalTest returned an empty data payload"); return RetrievalDTO.ResultVO.builder() .chunks(new ArrayList<>()) .docAggs(new ArrayList<>()) @@ -364,7 +364,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return result; } catch (Exception e) { - log.error("召回测试失败", e); + log.error("Retrieval test failed", e); throw convertToRenException(e); } } @@ -375,7 +375,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { getClient().get("/api/v1/health", null); return true; } catch (Exception e) { - log.error("连接测试失败: {}", e.getMessage()); + log.error("Connection test failed: {}", e.getMessage()); return false; } } @@ -384,7 +384,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { public Map getStatus() { Map status = new HashMap<>(); status.put("adapterType", getAdapterType()); - status.put("configKeys", config != null ? config.keySet() : "未配置"); + status.put("configKeys", config != null ? config.keySet() : "not configured"); status.put("connectionTest", testConnection()); status.put("lastChecked", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); return status; @@ -393,9 +393,9 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public Map getSupportedConfig() { Map supportedConfig = new HashMap<>(); - supportedConfig.put("base_url", "RAGFlow API基础URL"); - supportedConfig.put("api_key", "RAGFlow API密钥"); - supportedConfig.put("timeout", "请求超时时间(毫秒)"); + supportedConfig.put("base_url", "RAGFlow API base URL"); + supportedConfig.put("api_key", "RAGFlow API key"); + supportedConfig.put("timeout", "Request timeout in milliseconds"); return supportedConfig; } @@ -409,8 +409,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req) { try { - // [Production Fix] 强化默认值处理,防止 RAGFlow API 因空字符串或缺失字段报错 (Code 101) - // 解决 "Field: - Message: " 等校验失败 + // [Production Fix] Strengthen default handling so the RAGFlow API does not fail + // when fields are empty or missing. if (StringUtils.isBlank(req.getPermission())) { req.setPermission("me"); } @@ -418,33 +418,33 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { req.setChunkMethod("naive"); } - // 🤖 自动补全嵌入模型:优先使用请求传参,其次使用配置中的默认模型 + // Auto-fill the embedding model. Prefer the request value, then the configured default. if (StringUtils.isBlank(req.getEmbeddingModel())) { String defaultModel = (String) getConfigValue(config, "embedding_model", "embeddingModel"); if (StringUtils.isNotBlank(defaultModel)) { - log.info("RAGFlow: 使用配置中的默认嵌入模型: {}", defaultModel); + log.info("RAGFlow: using the configured default embedding model: {}", defaultModel); req.setEmbeddingModel(defaultModel); } - // 若配置中也无默认值,则留空由 RAGFlow 服务端自行兜底(或抛出业务异常) + // If there is no configured default, leave it empty and let the server decide. } - // 🖼️ 自动补全头像:若为空则提供一个 1x1 透明像素,防止 RAGFlow 校验 MIME Prefix 失败 + // Auto-fill avatar with a 1x1 transparent pixel when empty so MIME-prefix validation passes. if (StringUtils.isBlank(req.getAvatar())) { req.setAvatar( "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="); } - // 直接将强类型请求对象传给 Client,Jackson 会处理 JsonProperty 映射 + // Pass the strongly typed request object directly. Jackson will handle JsonProperty mapping. Map response = getClient().post("/api/v1/datasets", req); - // 安全地获取 data 并通过 DatasetDTO.InfoVO 进行全量映射 + // Safely read data and map it fully through DatasetDTO.InfoVO. Object dataObj = response.get("data"); if (dataObj != null) { return objectMapper.convertValue(dataObj, DatasetDTO.InfoVO.class); } throw new RenException(ErrorCode.RAG_API_ERROR, "Invalid response from createDataset: missing data object"); } catch (Exception e) { - log.error("创建数据集失败", e); + log.error("Dataset creation failed", e); throw convertToRenException(e); } } @@ -452,7 +452,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) { try { - // RAGFlow API 更新建议路径带 ID + // The recommended RAGFlow update path includes the dataset ID. Map response = getClient().put("/api/v1/datasets/" + datasetId, req); Object dataObj = response.get("data"); @@ -461,7 +461,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("更新数据集失败", e); + log.error("Dataset update failed", e); throw convertToRenException(e); } } @@ -469,7 +469,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) { try { - // RAGFlow 批量删除接口使用 DELETE /api/v1/datasets + // RAGFlow uses DELETE /api/v1/datasets for bulk dataset removal. Map response = getClient().delete("/api/v1/datasets", req); Object dataObj = response.get("data"); @@ -478,7 +478,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("批量删除数据集失败", e); + log.error("Bulk dataset deletion failed", e); throw convertToRenException(e); } } @@ -527,7 +527,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { try { getClient().postStream(endpoint, body, onData); } catch (Exception e) { - log.error("流式请求失败", e); + log.error("Streaming request failed", e); throw convertToRenException(e); } } @@ -535,20 +535,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public Object postSearchBotAsk(Map config, Object body, Consumer onData) { - // SearchBot 实际上是 Dataset 检索的一种封装,或者是未公开的 API? - // 假设 RAGFlow 没有显式的 /searchbots 接口供 SDK 调用,而是 Dataset Retrieval 或者 Chat。 - // 但根据 BotDTO,它是 /api/v1/searchbots/ask (假设) - // 这里的 config 可能是覆盖用的,或者我们只是用 adapter 实例已有的 client。 - // 但 Bot 可能使用不同的 API Key?通常 Adapter 实例绑定了一个 Key。 - // 如果 Bot 使用系统 Key,则直接用 getClient()。 + // SearchBot is effectively a dataset-search wrapper, or possibly a not-yet-public API. + // Assume there is no dedicated SDK route beyond retrieval/chat behavior. + // BotDTO implies a /api/v1/searchbots/ask endpoint. + // The config may override defaults, but in practice this adapter usually uses its own client. + // If SearchBot should use a different key later, that can be revisited. - // 暂时假设 endpoint /api/v1/searchbots/ask 存在(或者类似的) - // 如果是流式: + // For now assume /api/v1/searchbots/ask or an equivalent endpoint exists. try { getClient().postStream("/api/v1/searchbots/ask", body, onData); return null; } catch (Exception e) { - log.error("SearchBot Ask 失败", e); + log.error("SearchBot ask failed", e); throw convertToRenException(e); } } @@ -556,17 +554,17 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public void postAgentBotCompletion(Map config, String agentId, Object body, Consumer onData) { - // AgentBot 对应 /api/v1/agentbots/{id}/completions + // AgentBot maps to /api/v1/agentbots/{id}/completions. try { getClient().postStream("/api/v1/agentbots/" + agentId + "/completions", body, onData); } catch (Exception e) { - log.error("AgentBot Completion 失败", e); + log.error("AgentBot completion failed", e); throw convertToRenException(e); } } - // 复用原有的辅助解析方法,保持兼容 - // [Bug Fix] 不再吞掉反序列化异常,避免上层误判"文档已删除" + // Reuse the existing helper parsing path to preserve compatibility. + // [Bug Fix] Do not swallow deserialization errors, or upper layers may misclassify the document as deleted. private PageData parseDocumentListResponse(Object dataObj, long curPage, long pageSize) { if (dataObj == null) { return new PageData<>(new ArrayList<>(), 0); @@ -575,18 +573,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { Map dataMap = (Map) dataObj; List> documents = (List>) dataMap.get("docs"); if (documents == null || documents.isEmpty()) { - // RAGFlow 明确返回了空文档列表,这是合法的"真空" + // RAGFlow explicitly returned an empty document list. That is a valid empty state. return new PageData<>(new ArrayList<>(), 0); } List list = new ArrayList<>(); for (Object docObj : documents) { try { - // 单文档转换容错:一个文档反序列化失败不影响其他文档 + // Be tolerant per document so one deserialization failure does not block the rest. DocumentDTO.InfoVO info = objectMapper.convertValue(docObj, DocumentDTO.InfoVO.class); list.add(mapToKnowledgeFilesDTO(info, null)); } catch (Exception e) { - log.warn("[RAGFlow] 单文档 DTO 转换失败,跳过该文档: {}", e.getMessage()); + log.warn("[RAGFlow] Single-document DTO conversion failed, skipping that document: {}", e.getMessage()); } } @@ -601,7 +599,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { private KnowledgeFilesDTO parseUploadResponse(Object dataObj, String datasetId, MultipartFile file) { KnowledgeFilesDTO result = null; - // 尝试从响应数据中提取文档ID (documentId) + // Try to extract documentId from the response payload. if (dataObj != null) { try { DocumentDTO.InfoVO info = null; @@ -618,13 +616,13 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { result = mapToKnowledgeFilesDTO(info, datasetId); } } catch (Exception e) { - log.warn("解析上传响应数据失败: {}", e.getMessage()); + log.warn("Failed to parse upload response data: {}", e.getMessage()); } } if (result == null) { - log.error("未能从RAGFlow响应中提取到documentId,响应内容: {}", dataObj); - // 这里应该返回一个最小化的包含基础信息的 DTO 而不是 null,防止上游 NPE + log.error("Could not extract documentId from the RAGFlow response, payload: {}", dataObj); + // Return a minimal DTO instead of null so upstream callers do not hit NPEs. result = new KnowledgeFilesDTO(); result.setDatasetId(datasetId); result.setName(file.getOriginalFilename()); @@ -636,8 +634,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 将 RAGFlow 的强类型 InfoVO 映射到内部使用的 KnowledgeFilesDTO - * 确保所有可用字段(名称、大小、状态、配置等)都得到全量同步 + * Map RAGFlow's strongly typed InfoVO to the internal KnowledgeFilesDTO. + * Keep all available fields in sync, including names, sizes, status, and parser config. */ private KnowledgeFilesDTO mapToKnowledgeFilesDTO(DocumentDTO.InfoVO info, String datasetId) { KnowledgeFilesDTO dto = new KnowledgeFilesDTO(); @@ -650,7 +648,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { dto.setName(info.getName()); dto.setFileSize(info.getSize()); - // 状态映射 + // Status mapping. if (info.getRun() != null) { dto.setRun(info.getRun().name()); } @@ -658,10 +656,10 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { if (StringUtils.isNotBlank(info.getStatus())) { dto.setStatus(info.getStatus()); } else { - dto.setStatus("1"); // 默认启用 + dto.setStatus("1"); // Enabled by default. } - // 时间同步 + // Timestamp synchronization. if (info.getCreateTime() != null) { dto.setCreatedAt(new Date(info.getCreateTime())); } @@ -669,16 +667,16 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { dto.setUpdatedAt(new Date(info.getUpdateTime())); } - // 核心元数据补齐 (Issue 1) + // Fill the core metadata fields (Issue 1). dto.setProgress(info.getProgress()); dto.setThumbnail(info.getThumbnail()); dto.setProcessDuration(info.getProcessDuration()); dto.setSourceType(info.getSourceType()); dto.setChunkCount(info.getChunkCount() != null ? info.getChunkCount().intValue() : 0); dto.setTokenCount(info.getTokenCount()); - dto.setError(info.getProgressMsg()); // 将进度描述映射为错误信息提示 + dto.setError(info.getProgressMsg()); // Reuse the progress message as the error hint field. - // 扩展字段同步 + // Synchronize extended fields. dto.setMetaFields(info.getMetaFields()); if (info.getChunkMethod() != null) { dto.setChunkMethod(info.getChunkMethod().name().toLowerCase()); @@ -722,4 +720,4 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { return !multipartFile.isEmpty(); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java index 2053562d0..fbdde1df6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java @@ -10,97 +10,97 @@ import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; import xiaozhi.modules.model.entity.ModelConfigEntity; /** - * 知识库知识库服务接口 + * Knowledge-base service interface. */ public interface KnowledgeBaseService extends BaseService { /** - * 分页查询知识库列表 - * - * @param knowledgeBaseDTO 查询条件 - * @param page 页码 - * @param limit 每页数量 - * @return 分页数据 + * Query knowledge bases with pagination. + * + * @param knowledgeBaseDTO query filters + * @param page page number + * @param limit page size + * @return paginated data */ PageData getPageList(KnowledgeBaseDTO knowledgeBaseDTO, Integer page, Integer limit); /** - * 根据ID获取知识库详情 - * - * @param id 知识库ID - * @return 知识库详情 + * Get knowledge-base details by ID. + * + * @param id knowledge-base ID + * @return knowledge-base details */ KnowledgeBaseDTO getById(String id); /** - * 新增知识库 - * - * @param knowledgeBaseDTO 知识库信息 - * @return 新增的知识库 + * Create a knowledge base. + * + * @param knowledgeBaseDTO knowledge-base data + * @return created knowledge base */ KnowledgeBaseDTO save(KnowledgeBaseDTO knowledgeBaseDTO); /** - * 更新知识库 - * - * @param knowledgeBaseDTO 知识库信息 - * @return 更新的知识库 + * Update a knowledge base. + * + * @param knowledgeBaseDTO knowledge-base data + * @return updated knowledge base */ KnowledgeBaseDTO update(KnowledgeBaseDTO knowledgeBaseDTO); /** - * 根据知识库ID查询知识库 - * - * @param datasetId 知识库ID - * @return 知识库详情 + * Get a knowledge base by dataset ID. + * + * @param datasetId knowledge-base ID + * @return knowledge-base details */ KnowledgeBaseDTO getByDatasetId(String datasetId); /** - * 根据知识库ID集合查询知识库 + * Get knowledge bases by a list of dataset IDs. * - * @param datasetIdList 知识库ID集合 - * @return 知识库详情 + * @param datasetIdList knowledge-base ID list + * @return knowledge-base details */ List getByDatasetIdList(List datasetIdList); /** - * 根据知识库ID删除知识库 - * - * @param datasetId 知识库ID + * Delete a knowledge base by dataset ID. + * + * @param datasetId knowledge-base ID */ void deleteByDatasetId(String datasetId); /** - * 获取RAG配置信息 - * - * @param ragModelId RAG模型配置ID - * @return RAG配置信息 + * Get RAG configuration details. + * + * @param ragModelId RAG model configuration ID + * @return RAG configuration */ Map getRAGConfig(String ragModelId); /** - * 根据知识库ID获取对应的RAG配置 - * - * @param datasetId 知识库ID - * @return RAG配置 + * Get the RAG configuration for a knowledge base by dataset ID. + * + * @param datasetId knowledge-base ID + * @return RAG configuration */ Map getRAGConfigByDatasetId(String datasetId); /** - * 获取RAG模型列表 - * - * @return RAG模型列表 + * Get the list of RAG models. + * + * @return RAG model list */ List getRAGModels(); /** - * 更新知识库统计信息 (用于被文件服务回调) - * - * @param datasetId 知识库ID - * @param docDelta 文档数增量 - * @param chunkDelta 分块数增量 - * @param tokenDelta Token数增量 + * Update knowledge-base statistics. + * + * @param datasetId knowledge-base ID + * @param docDelta document-count delta + * @param chunkDelta chunk-count delta + * @param tokenDelta token-count delta */ void updateStatistics(String datasetId, Integer docDelta, Long chunkDelta, Long tokenDelta); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java index f832c1b13..edd26463f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java @@ -12,112 +12,112 @@ import xiaozhi.modules.knowledge.dto.document.RetrievalDTO; import xiaozhi.modules.knowledge.dto.document.DocumentDTO; /** - * 知识库文档服务接口 + * Knowledge-base document service interface. */ public interface KnowledgeFilesService { /** - * 分页查询文档列表 - * - * @param knowledgeFilesDTO 查询条件 - * @param page 页码 - * @param limit 每页数量 - * @return 分页数据 + * Query the document list with pagination. + * + * @param knowledgeFilesDTO query filters + * @param page page number + * @param limit page size + * @return paginated document data */ PageData getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit); /** - * 根据文档ID和知识库ID获取文档详情 - * - * @param documentId 文档ID - * @param datasetId 知识库ID - * @return 文档详情 (强类型 InfoVO) + * Get document details by document ID and knowledge-base ID. + * + * @param documentId document ID + * @param datasetId knowledge-base ID + * @return document details as a strongly typed InfoVO */ DocumentDTO.InfoVO getByDocumentId(String documentId, String datasetId); /** - * 上传文档到知识库 - * - * @param datasetId 知识库ID - * @param file 上传的文件 - * @param name 文档名称 - * @param metaFields 元数据字段 - * @param chunkMethod 分块方法 - * @param parserConfig 解析器配置 - * @return 上传的文档信息 + * Upload a document to a knowledge base. + * + * @param datasetId knowledge-base ID + * @param file uploaded file + * @param name document name + * @param metaFields metadata fields + * @param chunkMethod chunking method + * @param parserConfig parser configuration + * @return uploaded document information */ KnowledgeFilesDTO uploadDocument(String datasetId, MultipartFile file, String name, Map metaFields, String chunkMethod, Map parserConfig); /** - * 批量删除文档 - * - * @param datasetId 知识库ID - * @param req 删除请求参数 (含文档ID列表) + * Delete documents in batch. + * + * @param datasetId knowledge-base ID + * @param req delete request containing document IDs */ void deleteDocuments(String datasetId, DocumentDTO.BatchIdReq req); /** - * 获取RAG配置信息 - * - * @param ragModelId RAG模型配置ID - * @return RAG配置信息 + * Get RAG configuration details. + * + * @param ragModelId RAG model configuration ID + * @return RAG configuration */ Map getRAGConfig(String ragModelId); /** - * 解析文档(切块) - * - * @param datasetId 知识库ID - * @param documentIds 文档ID列表 - * @return 解析结果 + * Parse and chunk documents. + * + * @param datasetId knowledge-base ID + * @param documentIds document ID list + * @return parse result */ boolean parseDocuments(String datasetId, List documentIds); /** - * 列出指定文档的切片 - * - * @param datasetId 知识库ID - * @param documentId 文档ID - * @param req 切片列表请求参数 - * @return 切片列表信息 + * List chunks for a specific document. + * + * @param datasetId knowledge-base ID + * @param documentId document ID + * @param req chunk-list request + * @return chunk list information */ ChunkDTO.ListVO listChunks(String datasetId, String documentId, ChunkDTO.ListReq req); /** - * 召回测试 - * - * @param req 检索测试请求参数 - * @return 召回测试结果 + * Run a retrieval test. + * + * @param req retrieval-test request + * @return retrieval-test result */ RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req); /** - * 保存文档影子记录 + * Save a shadow record for a document. */ boolean saveDocumentShadow(String datasetId, KnowledgeFilesDTO result, String originalName, String chunkMethod, Map parserConfig); /** - * 批量删除文档影子记录并同步统计数据 - * - * @param documentIds 文档ID列表 - * @param datasetId 数据集ID - * @param chunkDelta 待扣减的总分块数 - * @param tokenDelta 待扣减的总Token数 + * Delete document shadow records in batch and sync aggregate stats. + * + * @param documentIds document ID list + * @param datasetId dataset ID + * @param chunkDelta total chunk count to subtract + * @param tokenDelta total token count to subtract */ void deleteDocumentShadows(List documentIds, String datasetId, Long chunkDelta, Long tokenDelta); /** - * 根据数据集ID清理所有关联文档 (级联删除专用) - * - * @param datasetId 数据集ID + * Remove all documents linked to a dataset. + * + * @param datasetId dataset ID */ void deleteDocumentsByDatasetId(String datasetId); /** - * 同步所有处于 RUNNING 状态的文档 (供定时任务调用) + * Synchronize all documents currently in RUNNING state. */ void syncRunningDocuments(); @@ -129,4 +129,4 @@ public interface KnowledgeFilesService { * @return 新同步的文档数量 */ int syncDocumentsFromRAG(String datasetId); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeManagerService.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeManagerService.java index 940479f36..c05aa7f59 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeManagerService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeManagerService.java @@ -3,22 +3,22 @@ package xiaozhi.modules.knowledge.service; import java.util.List; /** - * 知识库模块领域编排服务 - * 用于处理跨 KnowledgeBase 和 KnowledgeFiles 的复杂业务流程,彻底解决 Service 间的循环依赖问题。 + * Domain orchestration service for the knowledge-base module. + * Handles cross-service workflows between KnowledgeBase and KnowledgeFiles. */ public interface KnowledgeManagerService { /** - * 级联删除知识库及其下属所有文档 (包括本地 DB 和 RAGFlow 远程数据) - * - * @param datasetId 知识库 ID + * Cascade-delete a knowledge base and all of its documents, including local DB and remote RAGFlow data. + * + * @param datasetId knowledge-base ID */ void deleteDatasetWithFiles(String datasetId); /** - * 批量级联删除知识库 - * - * @param datasetIds 知识库 ID 列表 + * Cascade-delete knowledge bases in batch. + * + * @param datasetIds knowledge-base ID list */ void batchDeleteDatasetsWithFiles(List datasetIds); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java index 94958bd1f..a12ae6df9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java @@ -38,8 +38,8 @@ import java.util.List; import java.util.Map; /** - * 知识库服务实现类 (Refactored) - * 集成 RAGFlow Adapter 与 Shadow DB 模式 + * Knowledge-base service implementation. + * Integrates the RAGFlow adapter with the shadow-database model. */ @Service @AllArgsConstructor @@ -185,7 +185,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl() .eq("dataset_id", datasetId) @@ -207,13 +207,13 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl models = getRAGModels(); if (models != null && !models.isEmpty()) { dto.setRagModelId(models.get(0).getId()); } else { - throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "未指定且无可用默认 RAG 模型"); + throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "No RAG model was specified and no default RAG model is available"); } } @@ -226,21 +226,19 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl() @@ -313,13 +310,12 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl().eq("dataset_id", datasetId)); - // 1. 恢复 404 校验:找不到记录抛异常 + // Restore strict not-found behavior: throw when no record is found. if (entity == null) { - log.warn("记录不存在,datasetId: {}", datasetId); + log.warn("Record does not exist for datasetId {}", datasetId); throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); } - log.info("找到记录: ID={}, datasetId={}, ragModelId={}", + log.info("Found record: ID={}, datasetId={}, ragModelId={}", entity.getId(), entity.getDatasetId(), entity.getRagModelId()); // 2. RAG Delete (Strict Mode) - // 恢复严格一致性:RAG 删除失败则抛出异常,触发事务回滚,不允许已删除本地但保留远程的脏数据 + // Enforce strict consistency: if remote delete fails, roll back instead of leaving stale remote data behind. boolean apiDeleteSuccess = false; if (StringUtils.isNotBlank(entity.getRagModelId()) && StringUtils.isNotBlank(entity.getDatasetId())) { try { @@ -399,26 +395,26 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl 0 ? "成功" : "失败"); + log.info("Local database delete result: {}", deleteCount > 0 ? "success" : "failure"); redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId())); } } @@ -428,7 +424,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); queryWrapper.in("dataset_id", datasetIdList).or().in("id", datasetIdList); List list = knowledgeBaseDao.selectList(queryWrapper); @@ -453,7 +449,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit) { - log.info("=== 开始获取知识库文档列表 (Local-First 优化版) ==="); + log.info("=== Loading knowledge base documents (local-first mode) ==="); String datasetId = knowledgeFilesDTO.getDatasetId(); if (StringUtils.isBlank(datasetId)) { throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL); @@ -100,30 +100,30 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl iPage = documentDao.selectPage(pageParams, queryWrapper); - // 3. 手动转换 DTO + // 3. Convert records to DTOs manually. List dtoList = new ArrayList<>(); for (DocumentEntity entity : iPage.getRecords()) { dtoList.add(convertEntityToDTO(entity)); } PageData pageData = new PageData<>(dtoList, iPage.getTotal()); - // 4. 动态状态同步 (带限流与保护) - // [Bug Fix] P1: 扩大同步白名单,CANCEL/FAIL 也允许低频同步以支持自愈 + // 4. Dynamically sync status with rate limiting and protection. + // [Bug Fix] P1: extend the sync whitelist so CANCEL/FAIL can self-heal at a low frequency. if (pageData.getList() != null && !pageData.getList().isEmpty()) { KnowledgeBaseAdapter adapter = null; for (KnowledgeFilesDTO dto : pageData.getList()) { String runStatus = dto.getRun(); - // 高优先级同步: RUNNING/UNSTART (5秒冷却) + // High-priority sync: RUNNING/UNSTART (5-second cooldown) boolean isActiveSync = "RUNNING".equals(runStatus) || "UNSTART".equals(runStatus); - // 低频自愈同步: CANCEL/FAIL (60秒冷却), 防止错误状态永久锁死 + // Low-frequency recovery sync: CANCEL/FAIL (60-second cooldown) to avoid permanent stale states. boolean isRecoverySync = "CANCEL".equals(runStatus) || "FAIL".equals(runStatus); boolean needSync = isActiveSync || isRecoverySync; if (needSync) { - // 限流保护:活跃状态 5 秒冷却,自愈状态 60 秒冷却 + // Rate-limit protection: 5 seconds for active states, 60 seconds for recovery states. long cooldownMs = isActiveSync ? 5000 : 60000; DocumentEntity localEntity = documentDao.selectOne(new QueryWrapper() .eq("document_id", dto.getDocumentId())); @@ -134,52 +134,54 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); } catch (Exception e) { - log.warn("同步中断:无法初始化适配器, {}", e.getMessage()); + log.warn("Sync aborted because the adapter could not be initialized: {}", e.getMessage()); break; } } - // [关键修复] 记录同步前的 Token 数,用于计算增量 + // [Critical fix] Track the previous token count so we can compute deltas. Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; syncDocumentStatusWithRAG(dto, adapter); - // 计算增量并更新知识库统计 (与定时任务保持一致) + // Update knowledge base statistics using the same delta logic as the scheduled job. Long newTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; Long tokenDelta = newTokenCount - oldTokenCount; if (tokenDelta != 0) { knowledgeBaseService.updateStatistics(datasetId, 0, 0L, tokenDelta); - log.info("懒加载同步: 修正知识库统计, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta); + log.info("Lazy sync corrected knowledge base stats, docId={}, tokenDelta={}", + dto.getDocumentId(), tokenDelta); } } } } - log.info("获取文档列表成功,总数: {}", pageData.getTotal()); + log.info("Knowledge document list loaded successfully, total={}", pageData.getTotal()); return pageData; } /** - * 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType) + * Convert a local record entity to a DTO and manually align mismatched fields + * (size -> fileSize, type -> fileType). */ private KnowledgeFilesDTO convertEntityToDTO(DocumentEntity entity) { if (entity == null) { return null; } KnowledgeFilesDTO dto = new KnowledgeFilesDTO(); - // 1. 基础字段拷贝 + // 1. Copy base fields. BeanUtils.copyProperties(entity, dto); - // Issue 2: 修正 ID 语义。前端习惯使用 id 作为操作主键。 - // 在该模块中,应始终将远程 documentId 映射为 DTO 的 id,确保前端在详情/删除等操作时 ID 一致。 + // Issue 2: normalize ID semantics. The frontend expects id to be the primary action key. + // In this module the remote documentId should always be mapped to DTO.id. dto.setId(entity.getDocumentId()); - // 2. 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType) + // 2. Align mismatched fields manually. dto.setFileSize(entity.getSize()); dto.setFileType(entity.getType()); dto.setRun(entity.getRun()); @@ -187,25 +189,26 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl>() { })); } catch (Exception e) { - log.warn("反序列化 MetaFields 失败, entityId: {}, error: {}", entity.getId(), e.getMessage()); + log.warn("Failed to deserialize MetaFields, entityId={}, error={}", entity.getId(), e.getMessage()); } } - // 4. 解析配置 JSON 反序列化 + // 4. Deserialize parser config JSON. if (StringUtils.isNotBlank(entity.getParserConfig())) { try { dto.setParserConfig(objectMapper.readValue(entity.getParserConfig(), new com.fasterxml.jackson.core.type.TypeReference>() { })); } catch (Exception e) { - log.warn("反序列化 ParserConfig 失败, entityId: {}, error: {}", entity.getId(), e.getMessage()); + log.warn("Failed to deserialize ParserConfig, entityId={}, error={}", entity.getId(), + e.getMessage()); } } return dto; @@ -213,12 +216,11 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl updateWrapper = new UpdateWrapper() .set("status", remoteStatus) .set("run", remoteDto.getRun()) @@ -275,43 +277,43 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl() .set("run", "CANCEL") - .set("error", "文档在远程服务中已被删除") + .set("error", "The document was deleted from the remote service") .set("updated_at", new Date()) .set("last_sync_at", new Date()) .eq("document_id", documentId)); } } catch (Exception e) { - // [Bug Fix] P2: 适配器调用异常时不标记 CANCEL,避免因网络/反序列化问题导致误判 - // 仅记录日志,等下次同步周期重试 - log.warn("同步文档状态时适配器调用失败(不标记CANCEL), documentId: {}, error: {}", + // [Bug Fix] P2: do not mark CANCEL when the adapter call itself fails. + // Just log the issue and let the next sync cycle retry. + log.warn("Adapter call failed while syncing document status (CANCEL not applied), documentId={}, error={}", documentId, e.getMessage()); } } @@ -322,38 +324,38 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); - // 提取适配器类型 + // Extract the adapter type. String adapterType = extractAdapterType(ragConfig); - // 使用适配器工厂获取适配器实例 + // Resolve the adapter from the factory. KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig); - // 使用适配器获取文档详情 + // Fetch document details through the adapter. DocumentDTO.InfoVO info = adapter.getDocumentById(datasetId, documentId); if (info != null) { - log.info("获取文档详情成功,documentId: {}", documentId); + log.info("Document details loaded successfully, documentId={}", documentId); return info; } else { throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); } } catch (Exception e) { - log.error("根据documentId获取文档失败: {}", e.getMessage(), e); + log.error("Failed to load document by documentId: {}", e.getMessage(), e); String errorMessage = e.getMessage() != null ? e.getMessage() : "null"; if (e instanceof RenException) { throw (RenException) e; } throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); } finally { - log.info("=== 根据documentId获取文档操作结束 ==="); + log.info("=== Finished loading document by documentId ==="); } } @@ -365,21 +367,21 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); - // 构造强类型请求 DTO + // Build the strongly typed upload request DTO. DocumentDTO.UploadReq uploadReq = DocumentDTO.UploadReq.builder() .datasetId(datasetId) .file(file) @@ -387,32 +389,32 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl Enum) + // Convert the chunking method from String to Enum. if (StringUtils.isNotBlank(chunkMethod)) { try { uploadReq.setChunkMethod(DocumentDTO.InfoVO.ChunkMethod.valueOf(chunkMethod.toUpperCase())); } catch (Exception e) { - log.warn("无效的分块方法: {}, 将使用后台默认配置", chunkMethod); + log.warn("Invalid chunking method {}, falling back to the backend default", chunkMethod); } } - // 转换解析配置 (Map -> DTO) + // Convert parser configuration from Map to DTO. if (parserConfig != null && !parserConfig.isEmpty()) { uploadReq.setParserConfig(objectMapper.convertValue(parserConfig, DocumentDTO.InfoVO.ParserConfig.class)); } - // 执行远程上传 (耗时 IO,在事务之外) + // Perform the remote upload outside the transaction because it is slow I/O. KnowledgeFilesDTO result = adapter.uploadDocument(uploadReq); if (result == null || StringUtils.isBlank(result.getDocumentId())) { - throw new RenException(ErrorCode.RAG_API_ERROR, "远程上传成功但未返回有效 DocumentID"); + throw new RenException(ErrorCode.RAG_API_ERROR, "Remote upload succeeded but did not return a valid DocumentID"); } - // 2. 本地持久化 (通过 self 调用以激活 @Transactional 代理) - log.info("2. 同步保存本地影子记录: documentId={}", result.getDocumentId()); + // 2. Persist local shadow data through self to activate the transactional proxy. + log.info("2. Saving the local shadow record: documentId={}", result.getDocumentId()); self.saveDocumentShadow(datasetId, result, fileName, chunkMethod, parserConfig); - log.info("=== 文档上传与影子记录保存成功 ==="); + log.info("=== Document upload and shadow-record save completed successfully ==="); return result; } @@ -437,7 +439,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl documentIds = req.getIds(); - log.info("=== 开始批量删除文档: datasetId={}, count={} ===", datasetId, documentIds.size()); + log.info("=== Starting bulk document deletion: datasetId={}, count={} ===", datasetId, documentIds.size()); - // 1. 批量权限与状态预审 + // 1. Pre-check permissions and document states in bulk. List entities = documentDao.selectList( new QueryWrapper() .eq("dataset_id", datasetId) .in("document_id", documentIds)); if (entities.size() != documentIds.size()) { - log.warn("部分文档不存在或归属权异常: 预期={}, 实际={}", documentIds.size(), entities.size()); + log.warn("Some documents are missing or ownership is invalid: expected={}, actual={}", + documentIds.size(), entities.size()); throw new RenException(ErrorCode.NO_PERMISSION); } @@ -509,68 +512,70 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); - // 3. 执行远程删除 + // 3. Execute the remote deletion. try { adapter.deleteDocument(datasetId, req); - log.info("远程批量删除请求成功"); + log.info("Remote bulk delete request completed successfully"); } catch (Exception e) { - log.warn("远程删除请求部分或全部失败: {}", e.getMessage()); + log.warn("Remote delete request partially or fully failed: {}", e.getMessage()); } - // 4. 原子化清理本地影子记录并同步统计数据 + // 4. Atomically clean local shadow records and sync statistics. self.deleteDocumentShadows(documentIds, datasetId, totalChunkDelta, totalTokenDelta); - // 5. 清理缓存 + // 5. Clear caches. try { String cacheKey = RedisKeys.getKnowledgeBaseCacheKey(datasetId); redisUtils.delete(cacheKey); - log.info("已驱逐数据集缓存: {}", cacheKey); + log.info("Evicted dataset cache: {}", cacheKey); } catch (Exception e) { - log.warn("驱逐 Redis 缓存失败: {}", e.getMessage()); + log.warn("Failed to evict the Redis cache: {}", e.getMessage()); } - log.info("=== 批量文档清理完成 ==="); + log.info("=== Bulk document cleanup completed ==="); } /** - * 批量原子化删除影子记录并同步父表统计 + * Delete shadow records atomically in bulk and sync parent-table statistics. */ @Transactional(rollbackFor = Exception.class) public void deleteDocumentShadows(List documentIds, String datasetId, Long chunkDelta, Long tokenDelta) { - // 1. 物理删除记录 + // 1. Physically delete the records. int deleted = documentDao.delete( new QueryWrapper() .eq("dataset_id", datasetId) .in("document_id", documentIds)); if (deleted > 0) { - // 2. 同步更新数据集统计信息 + // 2. Update dataset statistics in sync. knowledgeBaseService.updateStatistics(datasetId, -documentIds.size(), -chunkDelta, -tokenDelta); - log.info("已同步扣减数据集统计: datasetId={}, chunks={}, tokens={}", datasetId, chunkDelta, tokenDelta); + log.info("Decremented dataset statistics in sync: datasetId={}, chunks={}, tokens={}", + datasetId, chunkDelta, tokenDelta); } } /** - * 获取文件类型 - 支持RAG四种文档格式类型 + * Determine the file type. Supports the main RAG document format families. */ private String getFileType(String fileName) { if (StringUtils.isBlank(fileName)) { - log.warn("文件名为空,返回unknown类型"); + log.warn("File name is empty, returning the unknown type"); return "unknown"; } @@ -579,57 +584,57 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl 0 && lastDotIndex < fileName.length() - 1) { String extension = fileName.substring(lastDotIndex + 1).toLowerCase(); - // 文档格式类型 + // Document file types. String[] documentTypes = { "pdf", "doc", "docx", "txt", "md", "mdx" }; String[] spreadsheetTypes = { "csv", "xls", "xlsx" }; String[] presentationTypes = { "ppt", "pptx" }; - // 检查文档类型 + // Check document file types. for (String type : documentTypes) { if (type.equals(extension)) { return "document"; } } - // 检查表格类型 + // Check spreadsheet file types. for (String type : spreadsheetTypes) { if (type.equals(extension)) { return "spreadsheet"; } } - // 检查幻灯片类型 + // Check presentation file types. for (String type : presentationTypes) { if (type.equals(extension)) { return "presentation"; } } - // 返回原始扩展名作为文件类型 + // Fall back to the original extension as the file type. return extension; } return "unknown"; } catch (Exception e) { - log.error("获取文件类型失败: ", e); + log.error("Failed to determine file type", e); return "unknown"; } } /** - * 从RAG配置中提取适配器类型 + * Extract the adapter type from RAG configuration. */ private String extractAdapterType(Map config) { if (config == null) { throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND); } - // 从配置中提取type字段 + // Extract the type field from the configuration. String adapterType = (String) config.get("type"); if (StringUtils.isBlank(adapterType)) { throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_FOUND); } - // 验证适配器类型是否已注册 + // Verify that the adapter type is registered. if (!KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(adapterType)) { - throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, "适配器类型未注册: " + adapterType); + throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, "Adapter type is not registered: " + adapterType); } return adapterType; @@ -641,27 +646,28 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); - // 提取适配器类型 + // Extract the adapter type. String adapterType = extractAdapterType(ragConfig); - // 获取知识库适配器 + // Resolve the knowledge-base adapter. KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig); - log.debug("解析文档参数: documentIds: {}", documentIds); + log.debug("Document parse parameters: documentIds={}", documentIds); - // 调用适配器解析文档 + // Parse the documents through the adapter. boolean result = adapter.parseDocuments(datasetId, documentIds); if (result) { - log.info("文档解析命令发送成功,准备同步本地影子库状态,datasetId: {}, documentIds: {}", datasetId, documentIds); - // 指令成功后立即更新本地影子状态为 RUNNING 和 解析中(1),确保 Local-First 列表能立即反馈 + log.info("Document parse command sent successfully, syncing local shadow state next, datasetId={}, documentIds={}", + datasetId, documentIds); + // Update local shadow state immediately so the Local-First list reflects progress right away. documentDao.update(null, new UpdateWrapper() .set("run", "RUNNING") .set("status", "1") @@ -669,23 +675,23 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); @@ -703,27 +709,27 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(req.getDatasetIds().get(0)); @@ -731,24 +737,24 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl list = documentDao .selectList(new QueryWrapper().eq("dataset_id", datasetId)); if (list == null || list.isEmpty()) @@ -756,7 +762,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl docIds = list.stream().map(DocumentEntity::getDocumentId).toList(); - // 封包调用现有删除逻辑 (含 RAG 物理删除) + // Reuse the existing delete flow, including remote RAG deletion. DocumentDTO.BatchIdReq req = DocumentDTO.BatchIdReq.builder().ids(docIds).build(); this.deleteDocuments(datasetId, req); } @@ -924,56 +930,57 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl runningDocs = documentDao.selectList( new QueryWrapper() .eq("run", "RUNNING") - .eq("status", "1") // 仅同步启用的文档 + .eq("status", "1") // Sync enabled documents only. ); if (runningDocs == null || runningDocs.isEmpty()) { return; } - log.info("定时任务: 发现 {} 个文档正在解析中,开始同步...", runningDocs.size()); + log.info("Scheduled task: found {} documents currently being parsed, starting sync...", runningDocs.size()); - // 2. 按 DatasetID 分组,复用 Adapter + // 2. Group by dataset ID so adapters can be reused. Map> groupedDocs = runningDocs.stream() .collect(Collectors.groupingBy(DocumentEntity::getDatasetId)); groupedDocs.forEach((datasetId, docs) -> { KnowledgeBaseAdapter adapter = null; try { - // 初始化 Adapter (每个数据集只初始化一次) + // Initialize the adapter once per dataset. Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); } catch (Exception e) { - log.warn("无法为数据集 {} 初始化适配器,跳过同步: {}", datasetId, e.getMessage()); + log.warn("Unable to initialize adapter for dataset {}, skipping sync: {}", datasetId, e.getMessage()); return; } for (DocumentEntity doc : docs) { try { - // 构造临时 DTO 传给同步方法 + // Build a temporary DTO for the sync method. KnowledgeFilesDTO dto = convertEntityToDTO(doc); - // 记录同步前的 Token 数 + // Record the token count before sync. Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; syncDocumentStatusWithRAG(dto, adapter); - // 3. [关键修复] 计算增量并更新知识库统计 + // 3. Compute the delta and update knowledge-base statistics. Long newTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; Long tokenDelta = newTokenCount - oldTokenCount; - // 仅当状态变为 SUCCESS 且 Token 数有变化时更新统计 + // Update stats only when the token count actually changes. if (tokenDelta != 0) { knowledgeBaseService.updateStatistics(datasetId, 0, 0L, tokenDelta); - log.info("定时任务: 同步修正知识库统计, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta); + log.info("Scheduled task: synced and corrected knowledge-base stats, docId={}, tokenDelta={}", + dto.getDocumentId(), tokenDelta); } } catch (Exception e) { - log.error("同步文档 {} 失败: {}", doc.getDocumentId(), e.getMessage()); + log.error("Failed to sync document {}: {}", doc.getDocumentId(), e.getMessage()); } } }); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeManagerServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeManagerServiceImpl.java index 541d4605c..4c102934e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeManagerServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeManagerServiceImpl.java @@ -21,17 +21,17 @@ public class KnowledgeManagerServiceImpl implements KnowledgeManagerService { @Override @Transactional(rollbackFor = Exception.class) public void deleteDatasetWithFiles(String datasetId) { - log.info("=== 级联删除开始: datasetId={} ===", datasetId); + log.info("=== Cascade delete started: datasetId={} ===", datasetId); - // 1. 先调用文件服务,清理该数据集下的所有文档记录 (含 RAGFlow 端) - log.info("Step 1: 清理关联文档..."); + // 1. Clean all documents under the dataset, including remote RAGFlow data. + log.info("Step 1: Cleaning related documents..."); knowledgeFilesService.deleteDocumentsByDatasetId(datasetId); - // 2. 再调用知识库服务,彻底注销数据集 (含 RAGFlow 端) - log.info("Step 2: 删除数据集主体..."); + // 2. Remove the dataset itself, including remote RAGFlow data. + log.info("Step 2: Deleting the dataset..."); knowledgeBaseService.deleteByDatasetId(datasetId); - log.info("=== 级联删除成功: datasetId={} ===", datasetId); + log.info("=== Cascade delete completed successfully: datasetId={} ===", datasetId); } @Override @@ -39,7 +39,7 @@ public class KnowledgeManagerServiceImpl implements KnowledgeManagerService { public void batchDeleteDatasetsWithFiles(List datasetIds) { if (datasetIds == null || datasetIds.isEmpty()) return; - log.info("=== 批量级联删除开始: count={} ===", datasetIds.size()); + log.info("=== Batch cascade delete started: count={} ===", datasetIds.size()); for (String id : datasetIds) { deleteDatasetWithFiles(id); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/task/DocumentStatusSyncTask.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/task/DocumentStatusSyncTask.java index fb975a1eb..1edd86e54 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/task/DocumentStatusSyncTask.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/task/DocumentStatusSyncTask.java @@ -8,13 +8,13 @@ import lombok.extern.slf4j.Slf4j; import xiaozhi.modules.knowledge.service.KnowledgeFilesService; /** - * 知识库文档状态同步定时任务 - * - * 作用: - * 1. 自动扫描处于 "RUNNING" (解析中) 状态的文档 - * 2. 调用 RAGFlow 接口获取最新状态 - * 3. 状态翻转 (RUNNING -> SUCCESS/FAIL) 时,同步更新数据库 - * 4. [关键] 解析成功时,补偿更新知识库的统计信息 (TokenCount) + * Scheduled task that synchronizes knowledge-base document status. + * + * Responsibilities: + * 1. Scan documents currently in RUNNING state. + * 2. Query RAGFlow for the latest status. + * 3. Update the database when status changes from RUNNING to SUCCESS or FAIL. + * 4. Reconcile knowledge-base statistics such as token count after successful parsing. */ @Component @AllArgsConstructor @@ -24,16 +24,16 @@ public class DocumentStatusSyncTask { private final KnowledgeFilesService knowledgeFilesService; /** - * 每 30 秒执行一次同步 - * 采用 fixedDelay,确保上一次执行完 30 秒后才开始下一次,防止积压 + * Run synchronization every 30 seconds. + * fixedDelay ensures the next run starts 30 seconds after the previous one finishes. */ @Scheduled(fixedDelay = 30000) public void syncRunningDocuments() { try { - // log.debug("开始执行文档状态同步任务..."); + // log.debug("Starting document-status sync task..."); knowledgeFilesService.syncRunningDocuments(); } catch (Exception e) { - log.error("文档状态同步任务异常", e); + log.error("Document-status sync task failed", e); } } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/LLMService.java b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/LLMService.java index 4436f1ca5..3954e510f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/LLMService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/LLMService.java @@ -1,70 +1,70 @@ package xiaozhi.modules.llm.service; /** - * LLM服务接口 - * 支持多种大模型调用 + * LLM service interface. + * Supports multiple large-model backends. */ public interface LLMService { /** - * 生成聊天记录总结 - * - * @param conversation 对话内容 - * @param promptTemplate 提示词模板 - * @return 总结结果 + * Generate a chat-history summary. + * + * @param conversation conversation content + * @param promptTemplate prompt template + * @return summary result */ String generateSummary(String conversation, String promptTemplate); /** - * 生成聊天记录总结(使用默认提示词) - * - * @param conversation 对话内容 - * @return 总结结果 + * Generate a chat-history summary using the default prompt template. + * + * @param conversation conversation content + * @return summary result */ String generateSummary(String conversation); /** - * 生成聊天记录总结(指定模型ID) - * - * @param conversation 对话内容 - * @param modelId 模型ID - * @return 总结结果 + * Generate a chat-history summary with a specific model ID. + * + * @param conversation conversation content + * @param modelId model ID + * @return summary result */ String generateSummaryWithModel(String conversation, String modelId); /** - * 生成聊天记录总结(指定模型ID和提示词模板) - * - * @param conversation 对话内容 - * @param promptTemplate 提示词模板 - * @param modelId 模型ID - * @return 总结结果 + * Generate a chat-history summary with a specific model ID and prompt template. + * + * @param conversation conversation content + * @param promptTemplate prompt template + * @param modelId model ID + * @return summary result */ String generateSummary(String conversation, String promptTemplate, String modelId); /** - * 生成聊天记录总结(包含历史记忆合并) - * - * @param conversation 对话内容 - * @param historyMemory 历史记忆 - * @param promptTemplate 提示词模板 - * @param modelId 模型ID - * @return 总结结果 + * Generate a chat-history summary with historical memory merging. + * + * @param conversation conversation content + * @param historyMemory historical memory + * @param promptTemplate prompt template + * @param modelId model ID + * @return summary result */ String generateSummaryWithHistory(String conversation, String historyMemory, String promptTemplate, String modelId); /** - * 检查服务是否可用 - * - * @return 是否可用 + * Check whether the service is available. + * + * @return whether the service is available */ boolean isAvailable(); /** - * 检查指定模型的服务是否可用 - * - * @param modelId 模型ID - * @return 是否可用 + * Check whether the service is available for the specified model. + * + * @param modelId model ID + * @return whether the service is available */ boolean isAvailable(String modelId); @@ -76,4 +76,4 @@ public interface LLMService { * @return 标题(约15字) */ String generateTitle(String conversation, String modelId); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java index 585826f34..782440283 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java @@ -23,8 +23,8 @@ import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; /** - * OpenAI风格API的LLM服务实现 - * 支持阿里云、DeepSeek、ChatGLM等兼容OpenAI API的模型 + * LLM service implementation for OpenAI-style APIs. + * Supports providers that expose OpenAI-compatible chat-completions endpoints. */ @Slf4j @Service @@ -35,7 +35,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { private final RestTemplate restTemplate = new RestTemplate(); - private static final String DEFAULT_SUMMARY_PROMPT = "你是一个经验丰富的记忆总结者,擅长将对话内容进行总结摘要,遵循以下规则:\n1、总结用户的重要信息,以便在未来的对话中提供更个性化的服务\n2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字,否则不要遗忘、不要压缩用户的历史记忆\n3、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中\n4、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后续对话,这些信息不需要加入到总结中\n5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中\n6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的\n7、只需要返回总结摘要,严格控制在1800字内\n8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容\n9、如果提供了历史记忆,请将新对话内容与历史记忆进行智能合并,保留有价值的历史信息,同时添加新的重要信息\n\n历史记忆:\n{history_memory}\n\n新对话内容:\n{conversation}"; + private static final String DEFAULT_SUMMARY_PROMPT = "You are an experienced memory summarizer. Summarize the conversation using these rules:\n1. Capture important user information so future conversations can be more personalized.\n2. Do not repeat points or discard earlier memory unless it already exceeds 1800 characters.\n3. Do not include device-control details such as volume changes, music playback, weather checks, exits, or other actions unrelated to the user.\n4. Do not store transient details like today's date, time, or weather when they are unrelated to the user's actual events.\n5. Do not include device-operation outcomes, failures, or meaningless filler.\n6. If the conversation contains nothing meaningful, returning the original history is acceptable.\n7. Return only the summary and keep it strictly within 1800 characters.\n8. Do not include code, XML, explanations, annotations, or examples that are not part of the conversation itself.\n9. If historical memory is provided, merge it intelligently with the new conversation while preserving valuable prior information.\n\nHistorical memory:\n{history_memory}\n\nNew conversation:\n{conversation}"; private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}"; @@ -52,24 +52,24 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { @Override public String generateSummary(String conversation, String promptTemplate, String modelId) { if (!isAvailable()) { - log.warn("LLM服务不可用,无法生成总结"); - return "LLM服务不可用,无法生成总结"; + log.warn("LLM service is unavailable, so the summary could not be generated"); + return "The LLM service is unavailable, so the summary could not be generated"; } try { - // 从智控台获取LLM模型配置 + // Load the LLM model configuration from the management console. ModelConfigEntity llmConfig; if (modelId != null && !modelId.trim().isEmpty()) { - // 通过具体模型ID获取配置 + // Load configuration for the specific model ID. llmConfig = modelConfigService.getModelByIdFromCache(modelId); } else { - // 保持向后兼容,使用默认配置 + // Preserve backward compatibility by falling back to the default model. llmConfig = getDefaultLLMConfig(); } if (llmConfig == null || llmConfig.getConfigJson() == null) { - log.error("未找到可用的LLM模型配置,modelId: {}", modelId); - return "未找到可用的LLM模型配置"; + log.error("No available LLM model configuration was found, modelId: {}", modelId); + return "No available LLM model configuration was found"; } JSONObject configJson = llmConfig.getConfigJson(); @@ -80,15 +80,15 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { Integer maxTokens = configJson.getInt("max_tokens"); if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) { - log.error("LLM配置不完整,baseUrl或apiKey为空"); - return "LLM配置不完整,无法生成总结"; + log.error("LLM configuration is incomplete because baseUrl or apiKey is empty"); + return "LLM configuration is incomplete, so the summary could not be generated"; } - // 构建提示词 + // Build the prompt. String prompt = (promptTemplate != null ? promptTemplate : DEFAULT_SUMMARY_PROMPT).replace("{conversation}", conversation); - // 构建请求体 + // Build the request body. Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); @@ -102,14 +102,14 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { requestBody.put("temperature", temperature != null ? temperature : 0.7); requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000); - // 发送HTTP请求 + // Send the HTTP request. HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer " + apiKey); HttpEntity> entity = new HttpEntity<>(requestBody, headers); - // 构建完整的API URL + // Build the full API URL. String apiUrl = baseUrl; if (!apiUrl.endsWith("/chat/completions")) { if (!apiUrl.endsWith("/")) { @@ -130,13 +130,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return messageObj.getStr("content"); } } else { - log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody()); + log.error("LLM API call failed, status: {}, response: {}", response.getStatusCode(), response.getBody()); } } catch (Exception e) { - log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e); + log.error("An exception occurred while generating the summary through the LLM service, modelId: {}", modelId, e); } - return "生成总结失败,请稍后重试"; + return "Summary generation failed, please try again later"; } @Override @@ -148,24 +148,24 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { public String generateSummaryWithHistory(String conversation, String historyMemory, String promptTemplate, String modelId) { if (!isAvailable()) { - log.warn("LLM服务不可用,无法生成总结"); - return "LLM服务不可用,无法生成总结"; + log.warn("LLM service is unavailable, so the summary could not be generated"); + return "The LLM service is unavailable, so the summary could not be generated"; } try { - // 从智控台获取LLM模型配置 + // Load the LLM model configuration from the management console. ModelConfigEntity llmConfig; if (modelId != null && !modelId.trim().isEmpty()) { - // 通过具体模型ID获取配置 + // Load configuration for the specific model ID. llmConfig = modelConfigService.getModelByIdFromCache(modelId); } else { - // 保持向后兼容,使用默认配置 + // Preserve backward compatibility by falling back to the default model. llmConfig = getDefaultLLMConfig(); } if (llmConfig == null || llmConfig.getConfigJson() == null) { - log.error("未找到可用的LLM模型配置,modelId: {}", modelId); - return "未找到可用的LLM模型配置"; + log.error("No available LLM model configuration was found, modelId: {}", modelId); + return "No available LLM model configuration was found"; } JSONObject configJson = llmConfig.getConfigJson(); @@ -174,16 +174,16 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String apiKey = configJson.getStr("api_key"); if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) { - log.error("LLM配置不完整,baseUrl或apiKey为空"); - return "LLM配置不完整,无法生成总结"; + log.error("LLM configuration is incomplete because baseUrl or apiKey is empty"); + return "LLM configuration is incomplete, so the summary could not be generated"; } - // 构建提示词,包含历史记忆 + // Build the prompt including historical memory. String prompt = (promptTemplate != null ? promptTemplate : DEFAULT_SUMMARY_PROMPT) - .replace("{history_memory}", historyMemory != null ? historyMemory : "无历史记忆") + .replace("{history_memory}", historyMemory != null ? historyMemory : "No historical memory") .replace("{conversation}", conversation); - // 构建请求体 + // Build the request body. Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); @@ -197,14 +197,14 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { requestBody.put("temperature", 0.2); requestBody.put("max_tokens", 2000); - // 发送HTTP请求 + // Send the HTTP request. HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer " + apiKey); HttpEntity> entity = new HttpEntity<>(requestBody, headers); - // 构建完整的API URL + // Build the full API URL. String apiUrl = baseUrl; if (!apiUrl.endsWith("/chat/completions")) { if (!apiUrl.endsWith("/")) { @@ -225,13 +225,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return messageObj.getStr("content"); } } else { - log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody()); + log.error("LLM API call failed, status: {}, response: {}", response.getStatusCode(), response.getBody()); } } catch (Exception e) { - log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e); + log.error("An exception occurred while generating the summary through the LLM service, modelId: {}", modelId, e); } - return "生成总结失败,请稍后重试"; + return "Summary generation failed, please try again later"; } @Override @@ -249,7 +249,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return baseUrl != null && !baseUrl.trim().isEmpty() && apiKey != null && !apiKey.trim().isEmpty(); } catch (Exception e) { - log.error("检查LLM服务可用性时发生异常:", e); + log.error("An exception occurred while checking LLM service availability", e); return false; } } @@ -261,10 +261,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return isAvailable(); } - // 通过具体模型ID获取配置 + // Load configuration for the specific model ID. ModelConfigEntity modelConfig = modelConfigService.getModelByIdFromCache(modelId); if (modelConfig == null || modelConfig.getConfigJson() == null) { - log.warn("未找到指定的LLM模型配置,modelId: {}", modelId); + log.warn("The specified LLM model configuration was not found, modelId: {}", modelId); return false; } @@ -275,23 +275,23 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return baseUrl != null && !baseUrl.trim().isEmpty() && apiKey != null && !apiKey.trim().isEmpty(); } catch (Exception e) { - log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e); + log.error("An exception occurred while checking LLM service availability, modelId: {}", modelId, e); return false; } } /** - * 从智控台获取默认的LLM模型配置 + * Get the default LLM model configuration from the management console. */ private ModelConfigEntity getDefaultLLMConfig() { try { - // 获取所有启用的LLM模型配置 + // Load all enabled LLM model configurations. List llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); if (llmConfigs == null || llmConfigs.isEmpty()) { return null; } - // 优先返回默认配置,如果没有默认配置则返回第一个启用的配置 + // Prefer the default configuration, otherwise return the first enabled one. for (ModelConfigEntity config : llmConfigs) { if (config.getIsDefault() != null && config.getIsDefault() == 1) { return config; @@ -300,7 +300,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return llmConfigs.get(0); } catch (Exception e) { - log.error("获取LLM模型配置时发生异常:", e); + log.error("An exception occurred while loading LLM model configuration", e); return null; } } @@ -391,4 +391,4 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return null; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index 2119f3c9c..3228c5fc7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -35,7 +35,7 @@ import xiaozhi.modules.timbre.service.TimbreService; @AllArgsConstructor @RestController @RequestMapping("/models") -@Tag(name = "模型配置") +@Tag(name = "Model Configuration") public class ModelController { private final ModelProviderService modelProviderService; @@ -45,7 +45,7 @@ public class ModelController { private final AgentTemplateService agentTemplateService; @GetMapping("/names") - @Operation(summary = "获取所有模型名称") + @Operation(summary = "Get all model names") @RequiresPermissions("sys:role:normal") public Result> getModelNames(@RequestParam String modelType, @RequestParam(required = false) String modelName) { @@ -54,7 +54,7 @@ public class ModelController { } @GetMapping("/llm/names") - @Operation(summary = "获取LLM模型信息") + @Operation(summary = "Get LLM model information") @RequiresPermissions("sys:role:normal") public Result> getLlmModelCodeList(@RequestParam(required = false) String modelName) { List llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName); @@ -62,7 +62,7 @@ public class ModelController { } @GetMapping("/{modelType}/provideTypes") - @Operation(summary = "获取模型供应器列表") + @Operation(summary = "Get model provider list") @RequiresPermissions("sys:role:superAdmin") public Result> getModelProviderList(@PathVariable String modelType) { List modelProviderDTOS = modelProviderService.getListByModelType(modelType); @@ -70,7 +70,7 @@ public class ModelController { } @GetMapping("/list") - @Operation(summary = "获取模型配置列表") + @Operation(summary = "Get model configuration list") @RequiresPermissions("sys:role:superAdmin") public Result> getModelConfigList( @RequestParam(required = true) String modelType, @@ -82,7 +82,7 @@ public class ModelController { } @PostMapping("/{modelType}/{provideCode}") - @Operation(summary = "新增模型配置") + @Operation(summary = "Add model configuration") @RequiresPermissions("sys:role:superAdmin") public Result addModelConfig(@PathVariable String modelType, @PathVariable String provideCode, @@ -93,7 +93,7 @@ public class ModelController { } @PutMapping("/{modelType}/{provideCode}/{id}") - @Operation(summary = "编辑模型配置") + @Operation(summary = "Edit model configuration") @RequiresPermissions("sys:role:superAdmin") public Result editModelConfig(@PathVariable String modelType, @PathVariable String provideCode, @@ -105,7 +105,7 @@ public class ModelController { } @DeleteMapping("/{id}") - @Operation(summary = "删除模型配置") + @Operation(summary = "Delete model configuration") @RequiresPermissions("sys:role:superAdmin") public Result deleteModelConfig(@PathVariable String id) { modelConfigService.delete(id); @@ -113,7 +113,7 @@ public class ModelController { } @GetMapping("/{id}") - @Operation(summary = "获取模型配置") + @Operation(summary = "Get model configuration") @RequiresPermissions("sys:role:superAdmin") public Result getModelConfig(@PathVariable String id) { ModelConfigEntity item = modelConfigService.selectById(id); @@ -122,18 +122,18 @@ public class ModelController { } @PutMapping("/enable/{id}/{status}") - @Operation(summary = "启用/关闭模型配置") + @Operation(summary = "Enable/disable model configuration") @RequiresPermissions("sys:role:superAdmin") public Result enableModelConfig(@PathVariable String id, @PathVariable Integer status) { ModelConfigEntity entity = modelConfigService.selectById(id); if (entity == null) { - return new Result().error("模型配置不存在"); + return new Result().error("Model configuration does not exist"); } - // 不能关闭默认模型 + // Do not allow disabling the default model. if (status == 0 && entity.getIsDefault() > 0) { - return new Result().error("默认模型配置不允许关闭"); + return new Result().error("The default model configuration cannot be disabled"); } - // 不更新ConfigJson字段 + // Do not update the ConfigJson field. entity.setConfigJson(null); entity.setIsEnabled(status); modelConfigService.updateById(entity); @@ -141,22 +141,22 @@ public class ModelController { } @PutMapping("/default/{id}") - @Operation(summary = "设置默认模型") + @Operation(summary = "Set default model") @RequiresPermissions("sys:role:superAdmin") public Result setDefaultModel(@PathVariable String id) { ModelConfigEntity entity = modelConfigService.selectById(id); if (entity == null) { - return new Result().error("模型配置不存在"); + return new Result().error("Model configuration does not exist"); } - // 将其他模型设置为非默认 + // Set other models to non-default modelConfigService.setDefaultModel(entity.getModelType(), 0); entity.setIsEnabled(1); entity.setIsDefault(1); - // 不更新ConfigJson字段 + // Do not update the ConfigJson field. entity.setConfigJson(null); modelConfigService.updateById(entity); - // 更新模板表中对应的模型ID + // Update corresponding model ID in template table agentTemplateService.updateDefaultTemplateModelId(entity.getModelType(), entity.getId()); configService.getConfig(false); @@ -164,7 +164,7 @@ public class ModelController { } @GetMapping("/{modelId}/voices") - @Operation(summary = "获取模型音色") + @Operation(summary = "Get model voices") @RequiresPermissions("sys:role:normal") public Result> getVoiceList(@PathVariable String modelId, @RequestParam(required = false) String voiceName) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java index 24a7c7ca8..966f35c1c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java @@ -26,13 +26,13 @@ import xiaozhi.modules.model.service.ModelProviderService; @AllArgsConstructor @RestController @RequestMapping("/models/provider") -@Tag(name = "模型供应器") +@Tag(name = "Model Provider") public class ModelProviderController { private final ModelProviderService modelProviderService; @GetMapping - @Operation(summary = "获取模型供应器列表") + @Operation(summary = "Get model provider list") @RequiresPermissions("sys:role:superAdmin") public Result> getListPage(ModelProviderDTO modelProviderDTO, @RequestParam(required = true, defaultValue = "0") String page, @@ -42,7 +42,7 @@ public class ModelProviderController { } @PostMapping - @Operation(summary = "新增模型供应器") + @Operation(summary = "Add model provider") @RequiresPermissions("sys:role:superAdmin") public Result add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) { ModelProviderDTO resp = modelProviderService.add(modelProviderDTO); @@ -50,7 +50,7 @@ public class ModelProviderController { } @PutMapping - @Operation(summary = "修改模型供应器") + @Operation(summary = "Update model provider") @RequiresPermissions("sys:role:superAdmin") public Result edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) { ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO); @@ -58,16 +58,16 @@ public class ModelProviderController { } @PostMapping("/delete") - @Operation(summary = "删除模型供应器") + @Operation(summary = "Delete model provider") @RequiresPermissions("sys:role:superAdmin") - @Parameter(name = "ids", description = "ID数组", required = true) + @Parameter(name = "ids", description = "ID array", required = true) public Result delete(@RequestBody List ids) { modelProviderService.delete(ids); return new Result<>(); } @GetMapping("/plugin/names") - @Tag(name = "获取插件名称列表") + @Tag(name = "Get plugin name list") public Result> getPluginNameList() { return ResultUtils.success(modelProviderService.getPluginList()); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dao/ModelConfigDao.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dao/ModelConfigDao.java index 70c6abc44..c6576bd96 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dao/ModelConfigDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dao/ModelConfigDao.java @@ -18,7 +18,7 @@ public interface ModelConfigDao extends BaseDao { List getModelCodeList(@Param("modelType") String modelType, @Param("modelName") String modelName); /** - * 获取符合条件的TTS平台列表(id和modelName) + * Get the list of matching TTS platforms with id and modelName. */ List> getTtsPlatformList(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java index 3995ceb83..a3ad9a260 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java @@ -4,7 +4,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; /** - * LLM的模型的基础展示数据 + * Basic display data for LLM models */ @EqualsAndHashCode(callSuper = true) @Data diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java index eb1197b14..f9e52de5f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java @@ -7,36 +7,36 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "模型供应器/商") +@Schema(description = "Model provider payload") public class ModelConfigBodyDTO { @Serial private static final long serialVersionUID = 1L; - @Schema(description = "模型ID,未填写将自动生成") + @Schema(description = "Model ID. Generated automatically when omitted") private String id; - @Schema(description = "模型编码(如AliLLM、DoubaoTTS)") + @Schema(description = "Model code, for example AliLLM or OpenAITTS") private String modelCode; - @Schema(description = "模型名称") + @Schema(description = "Model name") private String modelName; - @Schema(description = "是否默认配置(0否 1是)") + @Schema(description = "Default flag (0 no, 1 yes)") private Integer isDefault; - @Schema(description = "是否启用") + @Schema(description = "Enabled flag") private Integer isEnabled; - @Schema(description = "模型配置(JSON格式)") + @Schema(description = "Model configuration in JSON format") private JSONObject configJson; - @Schema(description = "官方文档链接") + @Schema(description = "Official documentation link") private String docLink; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort order") private Integer sort; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java index ed73e1ff8..aa82b1043 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java @@ -8,39 +8,39 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "模型供应器/商") +@Schema(description = "Model provider/vendor") public class ModelConfigDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - @Schema(description = "主键") + @Schema(description = "Primary key") private String id; - @Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)") + @Schema(description = "Model type (Memory/ASR/VAD/LLM/TTS)") private String modelType; - @Schema(description = "模型编码(如AliLLM、DoubaoTTS)") + @Schema(description = "Model code (e.g., AliLLM, AliBLTTS)") private String modelCode; - @Schema(description = "模型名称") + @Schema(description = "Model name") private String modelName; - @Schema(description = "是否默认配置(0否 1是)") + @Schema(description = "Is default configuration (0=no 1=yes)") private Integer isDefault; - @Schema(description = "是否启用") + @Schema(description = "Is enabled") private Integer isEnabled; - @Schema(description = "模型配置(JSON格式)") + @Schema(description = "Model configuration (JSON format)") private JSONObject configJson; - @Schema(description = "官方文档链接") + @Schema(description = "Official documentation link") private String docLink; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort order") private Integer sort; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderDTO.java index 317820d55..485893781 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderDTO.java @@ -14,46 +14,46 @@ import lombok.Data; import xiaozhi.common.validator.group.UpdateGroup; @Data -@Schema(description = "模型供应器/商") +@Schema(description = "Model provider/vendor") public class ModelProviderDTO implements Serializable { - @Schema(description = "主键") - @NotBlank(message = "id不能为空", groups = UpdateGroup.class) + @Schema(description = "Primary key") + @NotBlank(message = "ID cannot be empty", groups = UpdateGroup.class) private String id; - @Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)") - @NotBlank(message = "modelType不能为空") + @Schema(description = "Model type (Memory/ASR/VAD/LLM/TTS)") + @NotBlank(message = "Model type cannot be empty") private String modelType; - @Schema(description = "供应器类型") - @NotBlank(message = "providerCode不能为空") + @Schema(description = "Provider type") + @NotBlank(message = "Provider code cannot be empty") private String providerCode; - @Schema(description = "供应器名称") - @NotBlank(message = "name不能为空") + @Schema(description = "Provider name") + @NotBlank(message = "Name cannot be empty") private String name; - @Schema(description = "供应器字段列表(JSON格式)") + @Schema(description = "Provider field list (JSON format)") @TableField(typeHandler = JacksonTypeHandler.class) - @NotBlank(message = "fields(JSON格式)不能为空") + @NotBlank(message = "Fields (JSON format) cannot be empty") private String fields; - @Schema(description = "排序") - @NotNull(message = "sort不能为空") + @Schema(description = "Sort order") + @NotNull(message = "Sort cannot be empty") private Integer sort; - @Schema(description = "更新者") + @Schema(description = "Updater") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") @TableField(fill = FieldFill.UPDATE) private Date updateDate; - @Schema(description = "创建者") + @Schema(description = "Creator") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @TableField(fill = FieldFill.INSERT) private Date createDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java index 9bc4fa8ff..4ae9b9007 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java @@ -10,35 +10,35 @@ import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor -@Schema(description = "音色信息") +@Schema(description = "Voice information") public class VoiceDTO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "音色ID") + @Schema(description = "Voice ID") private String id; - @Schema(description = "音色名称") + @Schema(description = "Voice name") private String name; - @Schema(description = "音频播放地址") + @Schema(description = "Audio preview URL") private String voiceDemo; - @Schema(description = "语言类型") + @Schema(description = "Language type") private String languages; - @Schema(description = "是否为克隆音色") + @Schema(description = "Whether this voice is a clone") private Boolean isClone; - // 添加双参数构造函数,保持向后兼容 + // Two-argument constructor kept for backward compatibility. public VoiceDTO(String id, String name) { this.id = id; this.name = name; this.voiceDemo = null; this.languages = null; - this.isClone = false; // 默认不是克隆音色 + this.isClone = false; // Default to a standard voice. } - // 添加三参数构造函数,用于普通音色 + // Three-argument constructor for standard voices. public VoiceDTO(String id, String name, String voiceDemo) { this.id = id; this.name = name; @@ -47,4 +47,4 @@ public class VoiceDTO implements Serializable { this.isClone = false; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java index aba2c8f2e..aa0a4b780 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java @@ -13,53 +13,53 @@ import lombok.Data; @Data @TableName(value = "ai_model_config", autoResultMap = true) -@Schema(description = "模型配置表") +@Schema(description = "Model configuration table") public class ModelConfigEntity { - @Schema(description = "主键") + @Schema(description = "Primary key") private String id; - @Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)") + @Schema(description = "Model type, such as Memory, ASR, VAD, LLM, or TTS") private String modelType; - @Schema(description = "模型编码(如AliLLM、DoubaoTTS)") + @Schema(description = "Model code, for example AliLLM or OpenAITTS") private String modelCode; - @Schema(description = "模型名称") + @Schema(description = "Model name") private String modelName; - @Schema(description = "是否默认配置(0否 1是)") + @Schema(description = "Default flag (0 no, 1 yes)") private Integer isDefault; - @Schema(description = "是否启用") + @Schema(description = "Enabled flag") private Integer isEnabled; @TableField(typeHandler = JacksonTypeHandler.class) - @Schema(description = "模型配置(JSON格式)") + @Schema(description = "Model configuration in JSON format") private JSONObject configJson; - @Schema(description = "官方文档链接") + @Schema(description = "Official documentation link") private String docLink; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort order") private Integer sort; - @Schema(description = "更新者") + @Schema(description = "Updated by") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Updated at") @TableField(fill = FieldFill.UPDATE) private Date updateDate; - @Schema(description = "创建者") + @Schema(description = "Created by") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Created at") @TableField(fill = FieldFill.INSERT) private Date createDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelProviderEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelProviderEntity.java index 00904759b..083340bde 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelProviderEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelProviderEntity.java @@ -11,37 +11,37 @@ import lombok.Data; @Data @TableName("ai_model_provider") -@Schema(description = "模型供应器表") +@Schema(description = "Model provider table") public class ModelProviderEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "主键") + @Schema(description = "Primary key") private String id; - @Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)") + @Schema(description = "Model type (Memory/ASR/VAD/LLM/TTS)") private String modelType; - @Schema(description = "供应器类型,如 openai、") + @Schema(description = "Provider type, such as openai") private String providerCode; - @Schema(description = "供应器名称") + @Schema(description = "Provider name") private String name; - @Schema(description = "供应器字段列表(JSON格式)") + @Schema(description = "Provider field list (JSON format)") private String fields; - @Schema(description = "排序") + @Schema(description = "Sort order") private Integer sort; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation time") private Date createDate; - @Schema(description = "更新者") + @Schema(description = "Updater") private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updateDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java index 9ae10761b..d45856408 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java @@ -26,41 +26,41 @@ public interface ModelConfigService extends BaseService { void delete(String id); /** - * 根据ID获取模型名称 - * - * @param id 模型ID - * @return 模型名称 + * Get a model name by ID. + * + * @param id model ID + * @return model name */ String getModelNameById(String id); /** - * 根据ID获取模型配置 - * - * @param id 模型ID - * @return 模型配置实体 + * Get a model configuration by ID from cache. + * + * @param id model ID + * @return model configuration entity */ ModelConfigEntity getModelByIdFromCache(String id); /** - * 设置默认模型 + * Set the default model. * - * @param modelType 模型类型 - * @param isDefault 是否默认(1:是,0:否) + * @param modelType model type + * @param isDefault whether it is the default model, 1 for yes and 0 for no */ void setDefaultModel(String modelType, int isDefault); /** - * 获取符合条件的TTS平台列表 + * Get the list of matching TTS platforms. * - * @return TTS平台列表(id和modelName) + * @return TTS platform list containing id and modelName */ List> getTtsPlatformList(); /** - * 根据模型类型获取所有启用的模型配置 + * Get all enabled model configurations for a model type. * - * @param modelType 模型类型(如:LLM, TTS, ASR等) - * @return 启用的模型配置列表 + * @param modelType model type such as LLM, TTS, or ASR + * @return enabled model configuration list */ List getEnabledModelsByType(String modelType); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java index a49ce69cf..00d3ca5b2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java @@ -1,7 +1,6 @@ package xiaozhi.modules.model.service.impl; import java.io.Serializable; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -13,13 +12,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator; import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.metadata.OrderItem; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; - import cn.hutool.core.collection.CollectionUtil; import cn.hutool.json.JSONObject; import lombok.AllArgsConstructor; -import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; @@ -39,6 +34,7 @@ import xiaozhi.modules.model.dto.ModelProviderDTO; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; +import xiaozhi.modules.model.support.ProviderPolicy; @Service @AllArgsConstructor @@ -57,9 +53,12 @@ public class ModelConfigServiceImpl extends BaseServiceImpl filtered = entities.stream() + .filter(ProviderPolicy::isAllowedModelConfig) + .collect(Collectors.toList()); + return ConvertUtils.sourceToTarget(filtered, ModelBasicInfoDTO.class); } @Override @@ -71,62 +70,74 @@ public class ModelConfigServiceImpl extends BaseServiceImpl { - LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO(); - dto.setId(item.getId()); - dto.setModelName(item.getModelName()); - String type = item.getConfigJson().getOrDefault("type", "").toString(); - dto.setType(type); - return dto; - }).toList(); + return entities.stream() + .filter(ProviderPolicy::isAllowedModelConfig) + .map(item -> { + LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO(); + dto.setId(item.getId()); + dto.setModelName(item.getModelName()); + String type = item.getConfigJson().getOrDefault("type", "").toString(); + dto.setType(type); + return dto; + }) + .toList(); } @Override public PageData getPageList(String modelType, String modelName, String page, String limit) { - Map params = new HashMap<>(); - params.put(Constant.PAGE, page); - params.put(Constant.LIMIT, limit); - long curPage = Long.parseLong(page); long pageSize = Long.parseLong(limit); - Page pageInfo = new Page<>(curPage, pageSize); - // 添加排序规则:先按is_enabled降序,再按sort升序 - pageInfo.addOrder(OrderItem.desc("is_enabled"), OrderItem.asc("sort")); + QueryWrapper wrapper = new QueryWrapper() + .eq("model_type", modelType) + .like(StringUtils.isNotBlank(modelName), "model_name", modelName) + .orderByDesc("is_enabled") + .orderByAsc("sort"); - IPage modelConfigEntityIPage = modelConfigDao.selectPage( - pageInfo, - new QueryWrapper() - .eq("model_type", modelType) - .like(StringUtils.isNotBlank(modelName), "model_name", modelName)); + List allRecords = modelConfigDao.selectList(wrapper); + List filteredRecords = allRecords.stream() + .filter(ProviderPolicy::isAllowedModelConfig) + .collect(Collectors.toList()); - return getPageData(modelConfigEntityIPage, ModelConfigDTO.class); + int total = filteredRecords.size(); + int fromIndex = (int) Math.min((curPage - 1) * pageSize, total); + int toIndex = (int) Math.min(fromIndex + pageSize, total); + List pageRecords = filteredRecords.subList(fromIndex, toIndex); + + for (ModelConfigEntity entity : pageRecords) { + if (entity.getConfigJson() != null) { + entity.setConfigJson(maskSensitiveFields(entity.getConfigJson())); + } + } + + List dtoList = ConvertUtils.sourceToTarget(pageRecords, ModelConfigDTO.class); + return new PageData<>(dtoList, total); } @Override public ModelConfigDTO edit(String modelType, String provideCode, String id, ModelConfigBodyDTO modelConfigBodyDTO) { - // 1. 参数验证 + // 1. Validate parameters. validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO); - // 2. 验证模型提供者 + // 2. Validate the model provider. validateModelProvider(modelType, provideCode); - // 3. 获取原始配置(不经过敏感数据处理) + // 3. Load the original config without masking sensitive data. ModelConfigEntity originalEntity = getOriginalConfigFromDb(id); - // 4. 验证LLM配置 + // 4. Validate LLM config constraints. validateLlmConfiguration(modelConfigBodyDTO); - // 5. 准备更新实体并处理敏感数据 + // 5. Prepare the updated entity and preserve sensitive fields correctly. ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id); - // 6. 执行数据库更新 + // 6. Persist the database update. modelConfigDao.updateById(modelConfigEntity); - // 7. 清除缓存 + // 7. Clear cache entries. clearModelCache(id); - // 8. 返回处理后的数据(包含敏感数据掩码) + // 8. Return the masked response DTO. return buildResponseDTO(modelConfigEntity); } @@ -228,7 +239,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl() .eq("model_type", modelType)); - // 清除相关缓存 + // Clear related caches. clearModelCacheByType(modelType); } /** - * 验证模型提供者 + * Validate the model provider. */ private void validateModelProvider(String modelType, String provideCode) { List providerList = modelProviderService.getList(modelType, provideCode); @@ -291,7 +302,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl entities = modelConfigDao.selectList( @@ -453,7 +464,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl agents = agentDao.selectList( @@ -480,7 +491,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl> getTtsPlatformList() { @@ -505,7 +516,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl getEnabledModelsByType(String modelType) { @@ -519,6 +530,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl getPluginList() { - // 1. 获取插件列表 + // 1. Fetch plugin list LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(ModelProviderEntity::getModelType, "Plugin"); - List providerEntities = modelProviderDao.selectList(queryWrapper); + List providerEntities = modelProviderDao.selectList(queryWrapper) + .stream() + .filter(ProviderPolicy::isAllowedProvider) + .collect(Collectors.toList()); List resultList = ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); - // 2. 获取当前用户的知识库列表并追加到结果中 + // 2. Append knowledge bases owned by the current user UserDetail userDetail = SecurityUser.getUser(); if (userDetail != null && userDetail.getId() != null) { - // 查询当前用户的知识库 + // Query knowledge bases for the current user LambdaQueryWrapper kbQueryWrapper = new LambdaQueryWrapper<>(); kbQueryWrapper.eq(KnowledgeBaseEntity::getCreator, userDetail.getId()); - kbQueryWrapper.eq(KnowledgeBaseEntity::getStatus, 1); // 只获取启用状态的知识库 + kbQueryWrapper.eq(KnowledgeBaseEntity::getStatus, 1); // Only enabled knowledge bases List knowledgeBases = knowledgeBaseDao.selectList(kbQueryWrapper); - // 将知识库转换为ModelProviderDTO格式并添加到结果列表 + // Convert knowledge bases to ModelProviderDTO and append to the list for (KnowledgeBaseEntity kb : knowledgeBases) { ModelProviderDTO dto = new ModelProviderDTO(); dto.setId(kb.getId()); dto.setModelType("Rag"); - dto.setName("[知识库]" + kb.getName()); - dto.setProviderCode("ragflow"); // 假设所有RAG都使用ragflow + dto.setName("[Knowledge Base] " + kb.getName()); + dto.setProviderCode("ragflow"); // Assume all RAG uses ragflow dto.setFields("[]"); dto.setSort(0); dto.setCreateDate(kb.getCreatedAt()); @@ -86,7 +85,10 @@ public class ModelProviderServiceImpl extends BaseServiceImpl queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.in(ModelProviderEntity::getId, ids); queryWrapper.eq(ModelProviderEntity::getModelType, "Plugin"); - List providerEntities = modelProviderDao.selectList(queryWrapper); + List providerEntities = modelProviderDao.selectList(queryWrapper) + .stream() + .filter(ProviderPolicy::isAllowedProvider) + .collect(Collectors.toList()); return ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); } @@ -96,21 +98,15 @@ public class ModelProviderServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); queryWrapper.eq("model_type", StringUtils.isBlank(modelType) ? "" : modelType); queryWrapper.orderByAsc("sort"); - List providerEntities = modelProviderDao.selectList(queryWrapper); + List providerEntities = modelProviderDao.selectList(queryWrapper) + .stream() + .filter(ProviderPolicy::isAllowedProvider) + .collect(Collectors.toList()); return ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); } @Override public PageData getListPage(ModelProviderDTO modelProviderDTO, String page, String limit) { - - Map params = new HashMap(); - params.put(Constant.PAGE, page); - params.put(Constant.LIMIT, limit); - params.put(Constant.ORDER_FIELD, List.of("model_type", "sort")); - params.put(Constant.ORDER, "asc"); - - IPage pageParam = getPage(params, null, true); - QueryWrapper wrapper = new QueryWrapper(); if (StringUtils.isNotBlank(modelProviderDTO.getModelType())) { @@ -122,7 +118,21 @@ public class ModelProviderServiceImpl extends BaseServiceImpl allRecords = modelProviderDao.selectList(wrapper); + List filteredRecords = allRecords.stream() + .filter(ProviderPolicy::isAllowedProvider) + .collect(Collectors.toList()); + + long currentPage = Long.parseLong(page); + long pageSize = Long.parseLong(limit); + int total = filteredRecords.size(); + int fromIndex = (int) Math.min((currentPage - 1) * pageSize, total); + int toIndex = (int) Math.min(fromIndex + pageSize, total); + + List pageRecords = filteredRecords.subList(fromIndex, toIndex); + return new PageData<>(ConvertUtils.sourceToTarget(pageRecords, ModelProviderDTO.class), total); } @Override @@ -132,7 +142,7 @@ public class ModelProviderServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); queryWrapper.eq("model_type", StringUtils.isBlank(modelType) ? "" : modelType); queryWrapper.eq("provider_code", StringUtils.isBlank(providerCode) ? "" : providerCode); - List providerEntities = modelProviderDao.selectList(queryWrapper); + List providerEntities = modelProviderDao.selectList(queryWrapper) + .stream() + .filter(ProviderPolicy::isAllowedProvider) + .collect(Collectors.toList()); return ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/support/ProviderPolicy.java b/main/manager-api/src/main/java/xiaozhi/modules/model/support/ProviderPolicy.java new file mode 100644 index 000000000..a31422b3d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/support/ProviderPolicy.java @@ -0,0 +1,100 @@ +package xiaozhi.modules.model.support; + +import java.util.Locale; +import java.util.Set; + +import cn.hutool.json.JSONObject; +import xiaozhi.modules.model.entity.ModelConfigEntity; +import xiaozhi.modules.model.entity.ModelProviderEntity; + +public final class ProviderPolicy { + private static final Set DISALLOWED_TOKENS = Set.of( + "aliyun", + "bailian", + "dashscope", + "qwen", + "xunfei", + "iflytek", + "doubao", + "volc", + "huoshan", + "tencent", + "coze", + "baidu", + "wenxin", + "qianfan", + "spark", + "minimax", + "moonshot", + "zhipu", + "baichuan", + "deepseek", + "funasr" + ); + + private ProviderPolicy() { + } + + public static boolean isAllowedProvider(ModelProviderEntity provider) { + if (provider == null) { + return false; + } + if (containsDisallowedToken(provider.getProviderCode())) { + return false; + } + if (containsDisallowedToken(provider.getName())) { + return false; + } + if (containsDisallowedToken(provider.getId())) { + return false; + } + return true; + } + + public static boolean isAllowedModelConfig(ModelConfigEntity config) { + if (config == null) { + return false; + } + if (containsDisallowedToken(config.getModelCode())) { + return false; + } + if (containsDisallowedToken(config.getModelName())) { + return false; + } + if (containsDisallowedToken(config.getId())) { + return false; + } + if (containsDisallowedToken(config.getDocLink())) { + return false; + } + JSONObject configJson = config.getConfigJson(); + if (configJson != null) { + String type = configJson.getStr("type"); + if (containsDisallowedToken(type)) { + return false; + } + String baseUrl = configJson.getStr("base_url"); + if (containsDisallowedToken(baseUrl)) { + return false; + } + } + return true; + } + + public static boolean isAllowedProviderCode(String providerCode) { + return !containsDisallowedToken(providerCode); + } + + private static boolean containsDisallowedToken(String value) { + if (value == null || value.isBlank()) { + return false; + } + String normalized = value.toLowerCase(Locale.ROOT); + for (String token : DISALLOWED_TOKENS) { + if (normalized.contains(token)) { + return true; + } + } + return false; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java index d74ed08ba..90b41317f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java @@ -6,8 +6,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.DelegatingFilterProxy; /** - * Filter配置 - * Copyright (c) 人人开源 All rights reserved. + * Filter configuration + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ @Configuration @@ -17,7 +17,7 @@ public class FilterConfig { public FilterRegistrationBean shiroFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(new DelegatingFilterProxy("shiroFilter")); - // 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 + // This value defaults to false, indicating lifecycle managed by SpringApplicationContext, setting to true means managed by ServletContainer registration.addInitParameter("targetFilterLifecycle", "true"); registration.setEnabled(true); registration.setOrder(Integer.MAX_VALUE - 1); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index 80b93c6d0..b263220f2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -22,8 +22,8 @@ import xiaozhi.modules.security.secret.ServerSecretFilter; import xiaozhi.modules.sys.service.SysParamsService; /** - * Shiro的配置文件 - * Copyright (c) 人人开源 All rights reserved. + * Shiro configuration file + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ @Configuration @@ -57,19 +57,19 @@ public class ShiroConfig { shiroFilter.setShiroFilterConfiguration(config); Map filters = new HashMap<>(); - // oauth过滤 + // oauth filter filters.put("oauth2", new Oauth2Filter()); - // 服务密钥过滤 + // Service secret filter filters.put("server", new ServerSecretFilter(sysParamsService)); shiroFilter.setFilters(filters); - // 添加Shiro的内置过滤器 + // Add Shiro built-in filters /* - * anon:无需认证就可以访问 - * authc:必须认证了才能让问 - * user:必须拥有,记住我功能,才能访问 - * perms:拥有对某个资源的权限才能访问 - * role:拥有某个角色权限才能访问 + * anon: Can access without authentication + * authc: Must be authenticated to access + * user: Must have remember me functionality to access + * perms: Must have permission to a resource to access + * role: Must have a role permission to access */ Map filterMap = new LinkedHashMap<>(); filterMap.put("/ota/**", "anon"); @@ -85,7 +85,7 @@ public class ShiroConfig { filterMap.put("/user/pub-config", "anon"); filterMap.put("/user/register", "anon"); filterMap.put("/user/retrieve-password", "anon"); - // 将config路径使用server服务过滤器 + // Use server service filter for config path filterMap.put("/config/**", "server"); filterMap.put("/agent/chat-history/report", "server"); filterMap.put("/agent/chat-history/download/**", "anon"); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java index 8004eb9fc..92bc23544 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java @@ -1,8 +1,10 @@ package xiaozhi.modules.security.config; import java.text.SimpleDateFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.TimeZone; import jakarta.servlet.http.HttpServletRequest; @@ -37,6 +39,19 @@ import xiaozhi.common.utils.DateUtils; @Configuration public class WebMvcConfig implements WebMvcConfigurer { + private static final Locale DEFAULT_LOCALE = Locale.US; + private static final Map SUPPORTED_LOCALES = createSupportedLocales(); + + private static Map createSupportedLocales() { + Map locales = new LinkedHashMap<>(); + locales.put("en-us", Locale.US); + locales.put("en-gb", Locale.UK); + locales.put("de-de", Locale.GERMANY); + locales.put("vi-vn", Locale.forLanguageTag("vi-VN")); + locales.put("pt-br", Locale.forLanguageTag("pt-BR")); + return locales; + } + @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") @@ -48,15 +63,15 @@ public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List> converters) { - // 特殊用途的转换器 + // Specialized converters. converters.add(new ByteArrayHttpMessageConverter()); converters.add(new ResourceHttpMessageConverter()); - // 通用转换器 + // General-purpose converters. converters.add(new StringHttpMessageConverter()); converters.add(new AllEncompassingFormHttpMessageConverter()); - // JSON 转换器 + // JSON converter. converters.add(jackson2HttpMessageConverter()); } @@ -65,13 +80,13 @@ public class WebMvcConfig implements WebMvcConfigurer { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); - // 忽略未知属性 + // Ignore unknown properties. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // 设置时区 + // Set the default timezone. mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); - // 配置Java8日期时间序列化 + // Configure Java 8 date/time serialization. JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(java.time.LocalDateTime.class, new LocalDateTimeSerializer( java.time.format.DateTimeFormatter.ofPattern(DateUtils.DATE_TIME_PATTERN))); @@ -87,11 +102,11 @@ public class WebMvcConfig implements WebMvcConfigurer { new LocalTimeDeserializer(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"))); mapper.registerModule(javaTimeModule); - // 配置java.util.Date的序列化和反序列化 + // Configure java.util.Date serialization and deserialization. SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN); mapper.setDateFormat(dateFormat); - // Long类型转String类型 + // Serialize Long values as strings. SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); @@ -102,7 +117,7 @@ public class WebMvcConfig implements WebMvcConfigurer { } /** - * 国际化配置 - 根据请求头中的Accept-Language设置语言环境 + * Internationalization configuration based on the Accept-Language request header. */ @Bean public LocaleResolver localeResolver() { @@ -111,46 +126,33 @@ public class WebMvcConfig implements WebMvcConfigurer { public Locale resolveLocale(HttpServletRequest request) { String acceptLanguage = request.getHeader("Accept-Language"); if (acceptLanguage == null || acceptLanguage.isEmpty()) { - return Locale.getDefault(); + return DEFAULT_LOCALE; } - // 解析Accept-Language请求头中的首选语言 - String[] languages = acceptLanguage.split(","); - if (languages.length > 0) { - // 提取第一个语言代码,去除可能的质量值(q=...) - String[] parts = languages[0].split(";" + "\\s*"); - String primaryLanguage = parts[0].trim(); + for (String languageEntry : acceptLanguage.split(",")) { + String languageTag = languageEntry.split(";" + "\\s*")[0].trim().toLowerCase(Locale.ROOT); + Locale exactMatch = SUPPORTED_LOCALES.get(languageTag); + if (exactMatch != null) { + return exactMatch; + } - // 根据前端发送的语言代码直接创建Locale对象 - if (primaryLanguage.equals("zh-CN")) { - return Locale.SIMPLIFIED_CHINESE; - } else if (primaryLanguage.equals("zh-TW")) { - return Locale.TRADITIONAL_CHINESE; - } else if (primaryLanguage.equals("en-US")) { - return Locale.US; - } else if (primaryLanguage.equals("de-DE")) { + if (languageTag.startsWith("en")) { + return DEFAULT_LOCALE; + } + if (languageTag.startsWith("de")) { return Locale.GERMANY; - } else if (primaryLanguage.equals("vi-VN")) { - return Locale.forLanguageTag("vi-VN"); - } else if (primaryLanguage.startsWith("zh")) { - // 对于其他中文变体,默认使用简体中文 - return Locale.SIMPLIFIED_CHINESE; - } else if (primaryLanguage.startsWith("en")) { - // 对于其他英文变体,默认使用美式英语 - return Locale.US; - } else if (primaryLanguage.startsWith("de")) { - // 对于其他德语变体,默认使用德语 - return Locale.GERMANY; - } else if (primaryLanguage.startsWith("vi")) { - // 对于其他越南语变体,默认使用越南语 + } + if (languageTag.startsWith("vi")) { return Locale.forLanguageTag("vi-VN"); } + if (languageTag.startsWith("pt")) { + return Locale.forLanguageTag("pt-BR"); + } } - // 如果没有匹配的语言,使用默认语言 - return Locale.getDefault(); + return DEFAULT_LOCALE; } }; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java index 1ab9809dd..482e004b2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -44,13 +44,13 @@ import xiaozhi.modules.sys.service.SysUserService; import xiaozhi.modules.sys.vo.SysDictDataItem; /** - * 登录控制层 + * Login controller. */ @Slf4j @AllArgsConstructor @RestController @RequestMapping("/user") -@Tag(name = "登录管理") +@Tag(name = "Login Management") public class LoginController { private final SysUserService sysUserService; private final SysUserTokenService sysUserTokenService; @@ -59,18 +59,18 @@ public class LoginController { private final SysDictDataService sysDictDataService; @GetMapping("/captcha") - @Operation(summary = "验证码") + @Operation(summary = "Captcha") public void captcha(HttpServletResponse response, String uuid) throws IOException { - // uuid不能为空 + // uuid is required. AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL); - // 生成验证码 + // Generate the captcha. captchaService.create(response, uuid); } @PostMapping("/smsVerification") - @Operation(summary = "短信验证码") + @Operation(summary = "SMS Verification Code") public Result smsVerification(@RequestBody SmsVerificationDTO dto) { - // 验证图形验证码 + // Validate the image captcha first. boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), false); if (!validate) { throw new RenException(ErrorCode.SMS_CAPTCHA_ERROR); @@ -81,29 +81,29 @@ public class LoginController { if (!isMobileRegister) { throw new RenException(ErrorCode.MOBILE_REGISTER_DISABLED); } - // 发送短信验证码 + // Send the SMS verification code. captchaService.sendSMSValidateCode(dto.getPhone()); return new Result<>(); } @PostMapping("/login") - @Operation(summary = "登录") + @Operation(summary = "Login") public Result login(@RequestBody LoginDTO login) { String password = login.getPassword(); - // 使用工具类解密并验证验证码 + // Decrypt the password and validate the captcha. String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha( password, login.getCaptchaId(), captchaService, sysParamsService); login.setPassword(actualPassword); - // 按照用户名获取用户 + // Load the user by username. SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername()); - // 判断用户是否存在 + // Ensure the user exists. if (userDTO == null) { throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR); } - // 判断密码是否正确,不一样则进入if + // Ensure the password matches. if (!PasswordUtils.matches(login.getPassword(), userDTO.getPassword())) { throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR); } @@ -111,7 +111,7 @@ public class LoginController { } @PostMapping("/register") - @Operation(summary = "注册") + @Operation(summary = "Register") public Result register(@RequestBody LoginDTO login) { if (!sysUserService.getAllowUserRegister()) { throw new RenException(ErrorCode.USER_REGISTER_DISABLED); @@ -119,30 +119,30 @@ public class LoginController { String password = login.getPassword(); - // 使用工具类解密并验证验证码 + // Decrypt the password and validate the captcha. String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha( password, login.getCaptchaId(), captchaService, sysParamsService); login.setPassword(actualPassword); - // 是否开启手机注册 + // Check whether mobile registration is enabled. Boolean isMobileRegister = sysParamsService .getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class); boolean validate; if (isMobileRegister) { - // 验证用户是否是手机号码 + // Validate that the username is a phone number. boolean validPhone = ValidatorUtils.isValidPhone(login.getUsername()); if (!validPhone) { throw new RenException(ErrorCode.USERNAME_NOT_PHONE); } - // 验证短信验证码是否正常 + // Validate the SMS verification code. validate = captchaService.validateSMSValidateCode(login.getUsername(), login.getMobileCaptcha(), false); if (!validate) { throw new RenException(ErrorCode.SMS_CODE_ERROR); } } - // 按照用户名获取用户 + // Load the user by username. SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername()); if (userDTO != null) { throw new RenException(ErrorCode.PHONE_ALREADY_REGISTERED); @@ -155,7 +155,7 @@ public class LoginController { } @GetMapping("/info") - @Operation(summary = "用户信息获取") + @Operation(summary = "Get User Info") public Result info() { UserDetail user = SecurityUser.getUser(); Result result = new Result<>(); @@ -164,9 +164,9 @@ public class LoginController { } @PutMapping("/change-password") - @Operation(summary = "修改用户密码") + @Operation(summary = "Change Password") public Result changePassword(@RequestBody PasswordDTO passwordDTO) { - // 判断非空 + // Validate required fields. ValidatorUtils.validateEntity(passwordDTO); Long userId = SecurityUser.getUserId(); sysUserTokenService.changePassword(userId, passwordDTO); @@ -174,37 +174,37 @@ public class LoginController { } @PutMapping("/retrieve-password") - @Operation(summary = "找回密码") + @Operation(summary = "Retrieve Password") public Result retrievePassword(@RequestBody RetrievePasswordDTO dto) { - // 是否开启手机注册 + // Check whether mobile registration is enabled. Boolean isMobileRegister = sysParamsService .getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class); if (!isMobileRegister) { throw new RenException(ErrorCode.RETRIEVE_PASSWORD_DISABLED); } - // 判断非空 + // Validate required fields. ValidatorUtils.validateEntity(dto); - // 验证用户是否是手机号码 + // Validate that the phone number format is supported. boolean validPhone = ValidatorUtils.isValidPhone(dto.getPhone()); if (!validPhone) { throw new RenException(ErrorCode.PHONE_FORMAT_ERROR); } - // 按照用户名获取用户 + // Load the user by username. SysUserDTO userDTO = sysUserService.getByUsername(dto.getPhone()); if (userDTO == null) { throw new RenException(ErrorCode.PHONE_NOT_REGISTERED); } - // 验证短信验证码是否正常 + // Validate the SMS verification code. boolean validate = captchaService.validateSMSValidateCode(dto.getPhone(), dto.getCode(), false); - // 判断是否通过验证 + // Stop if validation fails. if (!validate) { throw new RenException(ErrorCode.SMS_CODE_ERROR); } String password = dto.getPassword(); - // 使用工具类解密并验证验证码 + // Decrypt the password and validate the captcha. String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha( password, dto.getCaptchaId(), captchaService, sysParamsService); @@ -215,7 +215,7 @@ public class LoginController { } @GetMapping("/pub-config") - @Operation(summary = "公共配置") + @Operation(summary = "Public Config") public Result> pubConfig() { Map config = new HashMap<>(); config.put("enableMobileRegister", sysParamsService @@ -229,14 +229,14 @@ public class LoginController { config.put("beianGaNum", sysParamsService.getValue(Constant.SysBaseParam.BEIAN_GA_NUM.getValue(), true)); config.put("name", sysParamsService.getValue(Constant.SysBaseParam.SERVER_NAME.getValue(), true)); - // SM2公钥 + // SM2 public key String publicKey = sysParamsService.getValue(Constant.SM2_PUBLIC_KEY, true); if (StringUtils.isBlank(publicKey)) { throw new RenException(ErrorCode.SM2_KEY_NOT_CONFIGURED); } config.put("sm2PublicKey", publicKey); - // 获取system-web.menu参数配置 + // Load the system-web.menu parameter. String menuConfig = sysParamsService.getValue("system-web.menu", true); if (StringUtils.isNotBlank(menuConfig)) { config.put("systemWebMenu", JsonUtils.parseObject(menuConfig, Object.class)); @@ -244,4 +244,4 @@ public class LoginController { return new Result>().ok(config); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java index 05f946d32..9087c2a71 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java @@ -9,8 +9,8 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.security.entity.SysUserTokenEntity; /** - * 系统用户Token - * Copyright (c) 人人开源 All rights reserved. + * System user Token + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ @Mapper diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java index df13f23df..ff62e562d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java @@ -7,25 +7,25 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 登录表单 + * Login form DTO. */ @Data -@Schema(description = "登录表单") +@Schema(description = "Login form") public class LoginDTO implements Serializable { - @Schema(description = "手机号码") + @Schema(description = "Phone number or username") @NotBlank(message = "{sysuser.username.require}") private String username; - @Schema(description = "密码") + @Schema(description = "Password") @NotBlank(message = "{sysuser.password.require}") private String password; - @Schema(description = "手机验证码") + @Schema(description = "Mobile verification code") private String mobileCaptcha; - @Schema(description = "唯一标识") + @Schema(description = "Captcha identifier") @NotBlank(message = "{sysuser.uuid.require}") private String captchaId; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/SmsVerificationDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/SmsVerificationDTO.java index 425ef0597..d73a6bcf5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/SmsVerificationDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/SmsVerificationDTO.java @@ -7,22 +7,22 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 短信验证码请求DTO + * SMS verification code request DTO */ @Data -@Schema(description = "短信验证码请求") +@Schema(description = "SMS verification code request") public class SmsVerificationDTO implements Serializable { private static final long serialVersionUID = 1L; - @Schema(description = "手机号码") + @Schema(description = "Mobile number") @NotBlank(message = "{sysuser.username.require}") private String phone; - @Schema(description = "验证码") + @Schema(description = "Verification code") @NotBlank(message = "{sysuser.captcha.require}") private String captcha; - @Schema(description = "唯一标识") + @Schema(description = "Unique identifier") @NotBlank(message = "{sysuser.uuid.require}") private String captchaId; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java index 2346b5e49..65e46f3e8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java @@ -11,7 +11,7 @@ import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** - * 系统用户Token + * System user token */ @Data @TableName("sys_user_token") @@ -23,23 +23,23 @@ public class SysUserTokenEntity implements Serializable { @TableId private Long id; /** - * 用户ID + * User ID */ private Long userId; /** - * 用户token + * User token */ private String token; /** - * 过期时间 + * Expiration time */ private Date expireDate; /** - * 更新时间 + * Update time */ private Date updateDate; /** - * 创建时间 + * Creation time */ @TableField(fill = FieldFill.INSERT) private Date createDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java index 59d7e09e6..b014657c4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java @@ -22,8 +22,8 @@ import xiaozhi.common.utils.MessageUtils; import xiaozhi.common.utils.Result; /** - * oauth2过滤器 - * Copyright (c) 人人开源 All rights reserved. + * oauth2 filter + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public class Oauth2Filter extends AuthenticatingFilter { @@ -32,7 +32,7 @@ public class Oauth2Filter extends AuthenticatingFilter { @Override protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { - // 获取请求token + // Get request token String token = getRequestToken((HttpServletRequest) request); if (StringUtils.isBlank(token)) { @@ -54,7 +54,7 @@ public class Oauth2Filter extends AuthenticatingFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { - // 获取请求token,如果token不存在,直接返回401 + // Get request token, if token does not exist, return 401 directly String token = getRequestToken((HttpServletRequest) request); if (StringUtils.isBlank(token)) { @@ -83,7 +83,7 @@ public class Oauth2Filter extends AuthenticatingFilter { httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); try { - // 使用国际化消息替代直接使用异常消息 + // Use internationalized messages instead of direct exception messages Result r = new Result().error(ErrorCode.UNAUTHORIZED); String json = JsonUtils.toJsonString(r); @@ -95,15 +95,15 @@ public class Oauth2Filter extends AuthenticatingFilter { } /** - * 获取请求的token + * Get request token */ private String getRequestToken(HttpServletRequest httpRequest) { String token = null; - // 从header中获取token + // Get token from header String authorization = httpRequest.getHeader(Constant.AUTHORIZATION); if (StringUtils.isNotBlank(authorization) && authorization.startsWith("Bearer ")) { token = authorization.replace("Bearer ", ""); } return token; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java index 27c3bc494..02c2fab6a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java @@ -30,8 +30,8 @@ import xiaozhi.modules.sys.entity.SysUserEntity; import xiaozhi.modules.sys.enums.SuperAdminEnum; /** - * 认证 - * Copyright (c) 人人开源 All rights reserved. + * Authentication + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ @Component @@ -48,13 +48,13 @@ public class Oauth2Realm extends AuthorizingRealm { } /** - * 授权(验证权限时调用) + * Authorization (called when verifying permissions) */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { UserDetail user = (UserDetail) principals.getPrimaryPrincipal(); - // 用户权限列表 + // User permission list Set permsSet = new HashSet<>(); if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) { @@ -70,30 +70,30 @@ public class Oauth2Realm extends AuthorizingRealm { } /** - * 认证(登录时调用) + * Authentication (called during login) */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String accessToken = (String) token.getPrincipal(); - // 根据accessToken,查询用户信息 + // Query user information based on accessToken SysUserTokenEntity tokenEntity = shiroService.getByToken(accessToken); - // token失效 + // Token expired if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) { throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID)); } - // 查询用户信息 + // Query user information SysUserEntity userEntity = shiroService.getUser(tokenEntity.getUserId()); - // 转换成UserDetail对象 + // Convert to UserDetail object UserDetail userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class); userDetail.setToken(accessToken); - // 账号锁定 + // Account locked if (userDetail.getStatus() == null) { - logger.error("账号状态异常,status 不能为空"); + logger.error("Account status abnormal, status cannot be empty"); throw new DisabledAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_DISABLE)); } @@ -105,4 +105,4 @@ public class Oauth2Realm extends AuthorizingRealm { return info; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java index 62adc903c..af6938b98 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java @@ -4,7 +4,7 @@ import org.apache.shiro.authc.AuthenticationToken; /** * token - * Copyright (c) 人人开源 All rights reserved. + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public class Oauth2Token implements AuthenticationToken { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java index 17ea9beb6..2c18dc57e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java @@ -7,8 +7,8 @@ import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; /** - * 生成token - * Copyright (c) 人人开源 All rights reserved. + * Generate token + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public class TokenGenerator { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java index 9144b3801..683f06301 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java @@ -1,29 +1,29 @@ package xiaozhi.modules.security.password; /** - * 密码工具类 - * Copyright (c) 人人开源 All rights reserved. + * Password utility class + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public class PasswordUtils { private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); /** - * 加密 + * Encrypt * - * @param str 字符串 - * @return 返回加密字符串 + * @param str String + * @return Returns encrypted string */ public static String encode(String str) { return passwordEncoder.encode(str); } /** - * 比较密码是否相等 + * Compare if passwords are equal * - * @param str 明文密码 - * @param password 加密后密码 - * @return true:成功 false:失败 + * @param str Plain text password + * @param password Encrypted password + * @return true: success false: failure */ public static boolean matches(String str, String password) { return passwordEncoder.matches(str, password); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java index b2a18547e..edc461876 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java @@ -20,7 +20,7 @@ import xiaozhi.common.utils.Result; import xiaozhi.modules.sys.service.SysParamsService; /** - * Config API 过滤器 + * Config API filter */ @Slf4j @RequiredArgsConstructor @@ -29,7 +29,7 @@ public class ServerSecretFilter extends AuthenticatingFilter { @Override protected ServerSecretToken createToken(ServletRequest request, ServletResponse response) { - // 获取请求token + // Get request token String token = getRequestToken((HttpServletRequest) request); if (StringUtils.isBlank(token)) { @@ -42,7 +42,7 @@ public class ServerSecretFilter extends AuthenticatingFilter { @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { - // 对OPTIONS请求放行 + // Allow OPTIONS requests if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) { return true; } @@ -51,19 +51,19 @@ public class ServerSecretFilter extends AuthenticatingFilter { @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { - // 获取token并校验 + // Get token and validate String token = getRequestToken((HttpServletRequest) servletRequest); if (StringUtils.isBlank(token)) { - // token为空,返回401 - this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "服务器密钥不能为空"); + // Token is empty, return 401 + this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "Server secret cannot be empty"); return false; } - // 验证token是否匹配 + // Verify if token matches String serverSecret = getServerSecret(); if (StringUtils.isBlank(serverSecret) || !serverSecret.equals(token)) { - // token无效,返回401 - this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "无效的服务器密钥"); + // Token is invalid, return 401 + this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "Invalid server secret"); return false; } @@ -71,7 +71,7 @@ public class ServerSecretFilter extends AuthenticatingFilter { } /** - * 发送未授权响应 + * Send unauthorized response */ private void sendUnauthorizedResponse(HttpServletResponse response, String message) { response.setContentType("application/json;charset=utf-8"); @@ -82,16 +82,16 @@ public class ServerSecretFilter extends AuthenticatingFilter { String json = JsonUtils.toJsonString(new Result().error(ErrorCode.UNAUTHORIZED, message)); response.getWriter().print(json); } catch (IOException e) { - log.error("响应输出失败", e); + log.error("Response output failed", e); } } /** - * 获取请求的token + * Get request token */ private String getRequestToken(HttpServletRequest httpRequest) { String token = null; - // 从header中获取token + // Get token from header String authorization = httpRequest.getHeader("Authorization"); if (StringUtils.isNotBlank(authorization) && authorization.startsWith("Bearer ")) { token = authorization.replace("Bearer ", ""); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java index 0db9d296e..032146bdf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java @@ -5,41 +5,41 @@ import java.io.IOException; import jakarta.servlet.http.HttpServletResponse; /** - * 验证码 - * Copyright (c) 人人开源 All rights reserved. + * Captcha + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public interface CaptchaService { /** - * 图片验证码 + * Image captcha */ void create(HttpServletResponse response, String uuid) throws IOException; /** - * 验证码效验 + * Captcha validation * * @param uuid uuid - * @param code 验证码 - * @param delete 是否删除验证码 - * @return true:成功 false:失败 + * @param code verification code + * @param delete whether to delete verification code + * @return true: success false: failure */ boolean validate(String uuid, String code, Boolean delete); /** - * 发送短信验证码 + * Send SMS verification code * - * @param phone 手机 + * @param phone mobile phone */ void sendSMSValidateCode(String phone); /** - * 验证短信验证码 + * Validate SMS verification code * - * @param phone 手机 - * @param code 验证码 - * @param delete 是否删除验证码 - * @return true:成功 false:失败 + * @param phone mobile phone + * @param code verification code + * @param delete whether to delete verification code + * @return true: success false: failure */ boolean validateSMSValidateCode(String phone, String code, Boolean delete); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java index b9d188895..bba05978f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java @@ -4,8 +4,8 @@ import xiaozhi.modules.security.entity.SysUserTokenEntity; import xiaozhi.modules.sys.entity.SysUserEntity; /** - * shiro相关接口 - * Copyright (c) 人人开源 All rights reserved. + * Shiro related interfaces + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public interface ShiroService { @@ -13,7 +13,7 @@ public interface ShiroService { SysUserTokenEntity getByToken(String token); /** - * 根据用户ID,查询用户 + * Query user by user ID * * @param userId */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java index d1d094d40..058a27721 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java @@ -8,34 +8,34 @@ import xiaozhi.modules.sys.dto.PasswordDTO; import xiaozhi.modules.sys.dto.SysUserDTO; /** - * 用户Token - * Copyright (c) 人人开源 All rights reserved. + * User Token + * Copyright (c) Renren Open Source All rights reserved. * Website: https://www.renren.io */ public interface SysUserTokenService extends BaseService { /** - * 生成token + * Generate token * - * @param userId 用户ID + * @param userId User ID */ Result createToken(Long userId); SysUserDTO getUserByToken(String token); /** - * 退出 + * Logout * - * @param userId 用户ID + * @param userId User ID */ void logout(Long userId); /** - * 修改密码 + * Change password * * @param userId * @param passwordDTO */ void changePassword(Long userId, PasswordDTO passwordDTO); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java index 0d3666db2..d24306fd3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -25,7 +25,7 @@ import xiaozhi.modules.sms.service.SmsService; import xiaozhi.modules.sys.service.SysParamsService; /** - * 验证码 + * Captcha */ @Service public class CaptchaServiceImpl implements CaptchaService { @@ -38,7 +38,7 @@ public class CaptchaServiceImpl implements CaptchaService { @Value("${renren.redis.open}") private boolean open; /** - * Local Cache 5分钟过期 + * Local Cache expires in 5 minutes */ Cache localCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterAccess(5, TimeUnit.MINUTES).build(); @@ -50,13 +50,13 @@ public class CaptchaServiceImpl implements CaptchaService { response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); - // 生成验证码 + // Generate captcha SpecCaptcha captcha = new SpecCaptcha(150, 40); captcha.setLen(5); captcha.setCharType(Captcha.TYPE_DEFAULT); captcha.out(response.getOutputStream()); - // 保存到缓存 + // Save to cache setCache(uuid, captcha.text()); } @@ -65,10 +65,10 @@ public class CaptchaServiceImpl implements CaptchaService { if (StringUtils.isBlank(code)) { return false; } - // 获取验证码 + // Get captcha String captcha = getCache(uuid, delete); - // 效验成功 + // Validation successful if (code.equalsIgnoreCase(captcha)) { return true; } @@ -78,9 +78,9 @@ public class CaptchaServiceImpl implements CaptchaService { @Override public void sendSMSValidateCode(String phone) { - // 检查发送间隔 + // Check send interval String lastSendTimeKey = RedisKeys.getSMSLastSendTimeKey(phone); - // 获取是否发送过,如果没有设置最后发送时间(60秒) + // Check if sent before, if not set last send time (60 seconds) String lastSendTime = redisUtils .getKeyOrCreate(lastSendTimeKey, String.valueOf(System.currentTimeMillis()), 60L); @@ -93,19 +93,19 @@ public class CaptchaServiceImpl implements CaptchaService { } } - // 检查今日发送次数 + // Check today send count String todayCountKey = RedisKeys.getSMSTodayCountKey(phone); Integer todayCount = (Integer) redisUtils.get(todayCountKey); if (todayCount == null) { todayCount = 0; } - // 获取最大发送次数限制 + // Get maximum send count limit Integer maxSendCount = sysParamsService.getValueObject( Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue(), Integer.class); if (maxSendCount == null) { - maxSendCount = 5; // 默认值 + maxSendCount = 5; // Default value } if (todayCount >= maxSendCount) { @@ -115,17 +115,17 @@ public class CaptchaServiceImpl implements CaptchaService { String key = RedisKeys.getSMSValidateCodeKey(phone); String validateCodes = generateValidateCode(6); - // 设置验证码 + // Set verification code setCache(key, validateCodes); - // 更新今日发送次数 + // Update today's send count if (todayCount == 0) { redisUtils.increment(todayCountKey, RedisUtils.DEFAULT_EXPIRE); } else { redisUtils.increment(todayCountKey); } - // 发送验证码短信 + // Send verification code SMS smsService.sendVerificationCodeSms(phone, validateCodes); } @@ -136,13 +136,13 @@ public class CaptchaServiceImpl implements CaptchaService { } /** - * 生成指定数量的随机数验证码 + * Generate random number verification code of specified quantity * - * @param length 数量 - * @return 随机码 + * @param length Quantity + * @return Random code */ private String generateValidateCode(Integer length) { - String chars = "0123456789"; // 字符范围可以自定义:数字 + String chars = "0123456789"; // Character range can be customized: numbers Random random = new Random(); StringBuilder code = new StringBuilder(); for (int i = 0; i < length; i++) { @@ -154,7 +154,7 @@ public class CaptchaServiceImpl implements CaptchaService { private void setCache(String key, String value) { if (open) { key = RedisKeys.getCaptchaKey(key); - // 设置5分钟过期 + // Set 5 minutes expiration redisUtils.set(key, value, 300); } else { localCache.put(key, value); @@ -165,7 +165,7 @@ public class CaptchaServiceImpl implements CaptchaService { if (open) { key = RedisKeys.getCaptchaKey(key); String captcha = (String) redisUtils.get(key); - // 删除验证码 + // Delete verification code if (captcha != null && delete) { redisUtils.delete(key); } @@ -174,7 +174,7 @@ public class CaptchaServiceImpl implements CaptchaService { } String captcha = localCache.getIfPresent(key); - // 删除验证码 + // Delete verification code if (captcha != null) { localCache.invalidate(key); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java index 7f0d311a0..73f24c720 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java @@ -27,24 +27,24 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl createToken(Long userId) { - // 用户token + // User token String token; - // 当前时间 + // Current time Date now = new Date(); - // 过期时间 + // Expiration time Date expireTime = new Date(now.getTime() + EXPIRE * 1000); - // 判断是否生成过token + // Check if token has been generated SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId); if (tokenEntity == null) { - // 生成一个token + // Generate a token token = TokenGenerator.generateValue(); tokenEntity = new SysUserTokenEntity(); @@ -53,12 +53,12 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl> pageUser( @Parameter(hidden = true) @RequestParam Map params) { @@ -63,7 +63,7 @@ public class AdminController { } @PutMapping("/users/{id}") - @Operation(summary = "重置密码") + @Operation(summary = "Reset password") @RequiresPermissions("sys:role:superAdmin") public Result update( @PathVariable Long id) { @@ -72,7 +72,7 @@ public class AdminController { } @DeleteMapping("/users/{id}") - @Operation(summary = "用户删除") + @Operation(summary = "Delete user") @RequiresPermissions("sys:role:superAdmin") public Result delete(@PathVariable Long id) { sysUserService.deleteById(id); @@ -80,21 +80,21 @@ public class AdminController { } @PutMapping("/users/changeStatus/{status}") - @Operation(summary = "批量修改用户状态") + @Operation(summary = "Batch update user status") @RequiresPermissions("sys:role:superAdmin") - @Parameter(name = "status", description = "用户状态", required = true) + @Parameter(name = "status", description = "User status", required = true) public Result changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) { sysUserService.changeStatus(status, userIds); return new Result(); } @GetMapping("/device/all") - @Operation(summary = "分页查找设备") + @Operation(summary = "Search devices with pagination") @RequiresPermissions("sys:role:superAdmin") @Parameters({ - @Parameter(name = "keywords", description = "设备关键词", required = false), - @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), - @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true), + @Parameter(name = "keywords", description = "Device keywords", required = false), + @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), }) public Result> pageDevice( @Parameter(hidden = true) @RequestParam Map params) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java index b467630d6..e475fb5ec 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java @@ -35,11 +35,11 @@ import xiaozhi.modules.device.service.DeviceService; import xiaozhi.common.redis.RedisUtils; /** - * 服务端管理控制器 + * Server side management controller */ @RestController @RequestMapping("/admin/server") -@Tag(name = "服务端管理") +@Tag(name = "Server Management") @AllArgsConstructor public class ServerSideManageController { private final SysParamsService sysParamsService; @@ -48,11 +48,11 @@ public class ServerSideManageController { private static final ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); - // 忽略json字符串中存在,但pojo中不存在对应字段的情况 + // Ignore cases where fields exist in JSON string but not in POJO objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } - @Operation(summary = "获取Ws服务端列表") + @Operation(summary = "Get WS server list") @GetMapping("/server-list") @RequiresPermissions("sys:role:superAdmin") public Result> getWsServerList() { @@ -63,9 +63,9 @@ public class ServerSideManageController { return new Result>().ok(Arrays.asList(wsText.split(";"))); } - @Operation(summary = "通知python服务端更新配置") + @Operation(summary = "Notify Python server to update configuration") @PostMapping("/emit-action") - @LogOperation("通知python服务端更新配置") + @LogOperation("Notify Python server to update configuration") @RequiresPermissions("sys:role:superAdmin") public Result emitServerAction(@RequestBody @Valid EmitSeverActionDTO emitSeverActionDTO) { if (emitSeverActionDTO.getAction() == null) { @@ -77,7 +77,7 @@ public class ServerSideManageController { } String targetWs = emitSeverActionDTO.getTargetWs(); String[] wsList = wsText.split(";"); - // 找到需要发起的 + // Find what needs to be initiated if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) { throw new RenException(ErrorCode.TARGET_WEBSOCKET_NOT_EXIST); } @@ -94,7 +94,7 @@ public class ServerSideManageController { String clientId = UUID.randomUUID().toString(); String redisKey = xiaozhi.common.redis.RedisKeys.getTmpRegisterMacKey(deviceId); - redisUtils.set(redisKey, "true", 300); // 5分钟有效期 + redisUtils.set(redisKey, "true", 300); // Valid for 5 minutes. WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); headers.add("device-id", deviceId); @@ -112,12 +112,12 @@ public class ServerSideManageController { .uri(targetWsUri) .headers(headers) .build()) { - // 如果连接成功则发送一个json数据包并等待服务端响应 + // If connection successful, send a JSON data packet and wait for server response client.sendJson( ServerActionPayloadDTO.build( actionEnum, Map.of("secret", serverSK))); - // 等待服务端响应并持续监听信息 + // Wait for server response and continue listening for messages client.listener((jsonText) -> { if (StringUtils.isBlank(jsonText)) { return false; @@ -131,7 +131,7 @@ public class ServerSideManageController { } }); } catch (Exception e) { - // 捕获全部错误,由全局异常处理器返回 + // Catch all errors, return by global exception handler throw new RenException(ErrorCode.WEB_SOCKET_CONNECT_FAILED); } return true; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java index 30187fe8a..fb5b63f13 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java @@ -29,7 +29,7 @@ import xiaozhi.modules.sys.vo.SysDictDataItem; import xiaozhi.modules.sys.vo.SysDictDataVO; /** - * 字典数据管理 + * Dictionary data management * * @author czc * @since 2025-04-30 @@ -37,22 +37,22 @@ import xiaozhi.modules.sys.vo.SysDictDataVO; @AllArgsConstructor @RestController @RequestMapping("/admin/dict/data") -@Tag(name = "字典数据管理") +@Tag(name = "Dictionary Data Management") public class SysDictDataController { private final SysDictDataService sysDictDataService; @GetMapping("/page") - @Operation(summary = "分页查询字典数据") + @Operation(summary = "Paginated query dictionary data") @RequiresPermissions("sys:role:superAdmin") - @Parameters({ @Parameter(name = "dictTypeId", description = "字典类型ID", required = true), - @Parameter(name = "dictLabel", description = "数据标签"), @Parameter(name = "dictValue", description = "数据值"), - @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), - @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true) }) + @Parameters({ @Parameter(name = "dictTypeId", description = "Dictionary type ID", required = true), + @Parameter(name = "dictLabel", description = "Data label"), @Parameter(name = "dictValue", description = "Data value"), + @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) }) public Result> page(@Parameter(hidden = true) @RequestParam Map params) { ValidatorUtils.validateEntity(params); - // 强制校验dictTypeId是否存在 + // Force validation of whether dictTypeId exists if (!params.containsKey("dictTypeId") || StringUtils.isEmpty(String.valueOf(params.get("dictTypeId")))) { - return new Result>().error("dictTypeId不能为空"); + return new Result>().error("dictTypeId cannot be empty"); } PageData page = sysDictDataService.page(params); @@ -60,7 +60,7 @@ public class SysDictDataController { } @GetMapping("/{id}") - @Operation(summary = "获取字典数据详情") + @Operation(summary = "Get dictionary data details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysDictDataVO vo = sysDictDataService.get(id); @@ -68,7 +68,7 @@ public class SysDictDataController { } @PostMapping("/save") - @Operation(summary = "新增字典数据") + @Operation(summary = "Add dictionary data") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysDictDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -77,7 +77,7 @@ public class SysDictDataController { } @PutMapping("/update") - @Operation(summary = "修改字典数据") + @Operation(summary = "Update dictionary data") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysDictDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -86,16 +86,16 @@ public class SysDictDataController { } @PostMapping("/delete") - @Operation(summary = "删除字典数据") + @Operation(summary = "Delete dictionary data") @RequiresPermissions("sys:role:superAdmin") - @Parameter(name = "ids", description = "ID数组", required = true) + @Parameter(name = "ids", description = "ID array", required = true) public Result delete(@RequestBody Long[] ids) { sysDictDataService.delete(ids); return new Result<>(); } @GetMapping("/type/{dictType}") - @Operation(summary = "获取字典数据列表") + @Operation(summary = "Get dictionary data list") @RequiresPermissions("sys:role:normal") public Result> getDictDataByType(@PathVariable("dictType") String dictType) { List list = sysDictDataService.getDictDataByType(dictType); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java index f16409b03..59997dfb9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java @@ -26,7 +26,7 @@ import xiaozhi.modules.sys.service.SysDictTypeService; import xiaozhi.modules.sys.vo.SysDictTypeVO; /** - * 字典类型管理 + * Dictionary type management * * @author czc * @since 2025-04-30 @@ -34,17 +34,17 @@ import xiaozhi.modules.sys.vo.SysDictTypeVO; @AllArgsConstructor @RestController @RequestMapping("/admin/dict/type") -@Tag(name = "字典类型管理") +@Tag(name = "Dictionary Type Management") public class SysDictTypeController { private final SysDictTypeService sysDictTypeService; @GetMapping("/page") - @Operation(summary = "分页查询字典类型") + @Operation(summary = "Paginated query dictionary types") @RequiresPermissions("sys:role:superAdmin") - @Parameters({ @Parameter(name = "dictType", description = "字典类型编码"), - @Parameter(name = "dictName", description = "字典类型名称"), - @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), - @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true) }) + @Parameters({ @Parameter(name = "dictType", description = "Dictionary type code"), + @Parameter(name = "dictName", description = "Dictionary type name"), + @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) }) public Result> page(@Parameter(hidden = true) @RequestParam Map params) { ValidatorUtils.validateEntity(params); PageData page = sysDictTypeService.page(params); @@ -52,7 +52,7 @@ public class SysDictTypeController { } @GetMapping("/{id}") - @Operation(summary = "获取字典类型详情") + @Operation(summary = "Get dictionary type details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysDictTypeVO vo = sysDictTypeService.get(id); @@ -60,10 +60,10 @@ public class SysDictTypeController { } @PostMapping("/save") - @Operation(summary = "保存字典类型") + @Operation(summary = "Save dictionary type") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysDictTypeDTO dto) { - // 参数校验 + // Parameter validation ValidatorUtils.validateEntity(dto); sysDictTypeService.save(dto); @@ -71,10 +71,10 @@ public class SysDictTypeController { } @PutMapping("/update") - @Operation(summary = "修改字典类型") + @Operation(summary = "Update dictionary type") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysDictTypeDTO dto) { - // 参数校验 + // Parameter validation ValidatorUtils.validateEntity(dto); sysDictTypeService.update(dto); @@ -82,9 +82,9 @@ public class SysDictTypeController { } @PostMapping("/delete") - @Operation(summary = "删除字典类型") + @Operation(summary = "Delete dictionary type") @RequiresPermissions("sys:role:superAdmin") - @Parameter(name = "ids", description = "ID数组", required = true) + @Parameter(name = "ids", description = "ID array", required = true) public Result delete(@RequestBody Long[] ids) { sysDictTypeService.delete(ids); return new Result<>(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java index 26e6d245e..2259bfc1b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java @@ -39,14 +39,14 @@ import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.utils.WebSocketValidator; /** - * 参数管理 + * Parameter management * * @author Mark sunlightcs@gmail.com * @since 1.0.0 */ @RestController @RequestMapping("admin/params") -@Tag(name = "参数管理") +@Tag(name = "Parameter Management") @AllArgsConstructor public class SysParamsController { private final SysParamsService sysParamsService; @@ -54,13 +54,13 @@ public class SysParamsController { private final RestTemplate restTemplate; @GetMapping("page") - @Operation(summary = "分页") + @Operation(summary = "Pagination") @Parameters({ - @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", in = ParameterIn.QUERY, required = true, ref = "int"), - @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"), - @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"), - @Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"), - @Parameter(name = "paramCode", description = "参数编码或参数备注", in = ParameterIn.QUERY, ref = "String") + @Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", in = ParameterIn.QUERY, required = true, ref = "int"), + @Parameter(name = Constant.LIMIT, description = "Number of records per page", in = ParameterIn.QUERY, required = true, ref = "int"), + @Parameter(name = Constant.ORDER_FIELD, description = "Sort field", in = ParameterIn.QUERY, ref = "String"), + @Parameter(name = Constant.ORDER, description = "Sort order, optional values (asc, desc)", in = ParameterIn.QUERY, ref = "String"), + @Parameter(name = "paramCode", description = "Parameter code or parameter remark", in = ParameterIn.QUERY, ref = "String") }) @RequiresPermissions("sys:role:superAdmin") public Result> page(@Parameter(hidden = true) @RequestParam Map params) { @@ -70,7 +70,7 @@ public class SysParamsController { } @GetMapping("{id}") - @Operation(summary = "信息") + @Operation(summary = "Information") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysParamsDTO data = sysParamsService.get(id); @@ -79,11 +79,11 @@ public class SysParamsController { } @PostMapping - @Operation(summary = "保存") - @LogOperation("保存") + @Operation(summary = "Save") + @LogOperation("Save") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysParamsDTO dto) { - // 效验数据 + // Validate data ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class); sysParamsService.save(dto); @@ -92,26 +92,26 @@ public class SysParamsController { } @PutMapping - @Operation(summary = "修改") - @LogOperation("修改") + @Operation(summary = "Update") + @LogOperation("Update") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysParamsDTO dto) { - // 效验数据 + // Validate data ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); - // 验证WebSocket地址列表 + // Validate WebSocket address list validateWebSocketUrls(dto.getParamCode(), dto.getParamValue()); - // 验证OTA地址 + // Validate OTA address validateOtaUrl(dto.getParamCode(), dto.getParamValue()); - // 验证MCP地址 + // Validate MCP address validateMcpUrl(dto.getParamCode(), dto.getParamValue()); - // 验证声纹地址 + // Validate voiceprint address validateVoicePrint(dto.getParamCode(), dto.getParamValue()); - // 校验mqtt密钥长度 + // Validate MQTT secret length validateMqttSecretLength(dto.getParamCode(), dto.getParamValue()); sysParamsService.update(dto); @@ -120,10 +120,10 @@ public class SysParamsController { } /** - * 验证WebSocket地址列表 + * Validate WebSocket address list * - * @param urls WebSocket地址列表,以分号分隔 - * @return 验证结果 + * @param urls WebSocket address list, separated by semicolons + * @return Validation result */ private void validateWebSocketUrls(String paramCode, String urls) { if (!paramCode.equals(Constant.SERVER_WEBSOCKET)) { @@ -135,17 +135,17 @@ public class SysParamsController { } for (String url : wsUrls) { if (StringUtils.isNotBlank(url)) { - // 检查是否包含localhost或127.0.0.1 + // Check if contains localhost or 127.0.0.1 if (url.contains("localhost") || url.contains("127.0.0.1")) { throw new RenException(ErrorCode.WEBSOCKET_URL_LOCALHOST); } - // 验证WebSocket地址格式 + // Validate WebSocket address format if (!WebSocketValidator.validateUrlFormat(url)) { throw new RenException(ErrorCode.WEBSOCKET_URL_FORMAT_ERROR); } - // 测试WebSocket连接 + // Test WebSocket connection if (!WebSocketValidator.testConnection(url)) { throw new RenException(ErrorCode.WEBSOCKET_CONNECTION_FAILED); } @@ -154,11 +154,11 @@ public class SysParamsController { } @PostMapping("/delete") - @Operation(summary = "删除") - @LogOperation("删除") + @Operation(summary = "Delete") + @LogOperation("Delete") @RequiresPermissions("sys:role:superAdmin") public Result delete(@RequestBody String[] ids) { - // 效验数据 + // Validate data AssertUtils.isArrayEmpty(ids, "id"); sysParamsService.delete(ids); @@ -167,7 +167,7 @@ public class SysParamsController { } /** - * 验证OTA地址 + * Validate OTA address */ private void validateOtaUrl(String paramCode, String url) { if (!paramCode.equals(Constant.SERVER_OTA)) { @@ -177,12 +177,12 @@ public class SysParamsController { return; } - // 检查是否包含localhost或127.0.0.1 + // Check if contains localhost or 127.0.0.1 if (url.contains("localhost") || url.contains("127.0.0.1")) { throw new RenException(ErrorCode.OTA_URL_LOCALHOST); } - // 验证URL格式 + // Validate URL format if (!url.toLowerCase().startsWith("http")) { throw new RenException(ErrorCode.OTA_URL_PROTOCOL_ERROR); } @@ -191,12 +191,12 @@ public class SysParamsController { } try { - // 发送GET请求 + // Send GET request ResponseEntity response = restTemplate.getForEntity(url, String.class); if (response.getStatusCode() != HttpStatus.OK) { throw new RenException(ErrorCode.OTA_INTERFACE_ACCESS_FAILED); } - // 检查响应内容是否包含OTA相关信息 + // Check if response content contains OTA related information String body = response.getBody(); if (body == null || !body.contains("OTA")) { throw new RenException(ErrorCode.OTA_INTERFACE_FORMAT_ERROR); @@ -221,12 +221,12 @@ public class SysParamsController { } try { - // 发送GET请求 + // Send GET request ResponseEntity response = restTemplate.getForEntity(url, String.class); if (response.getStatusCode() != HttpStatus.OK) { throw new RenException(ErrorCode.MCP_INTERFACE_ACCESS_FAILED); } - // 检查响应内容是否包含mcp相关信息 + // Check if response content contains MCP related information String body = response.getBody(); if (body == null || !body.contains("success")) { throw new RenException(ErrorCode.MCP_INTERFACE_FORMAT_ERROR); @@ -236,7 +236,7 @@ public class SysParamsController { } } - // 验证声纹接口地址是否正常 + // Validate if voiceprint interface address is normal private void validateVoicePrint(String paramCode, String url) { if (!paramCode.equals(Constant.SERVER_VOICE_PRINT)) { return; @@ -250,17 +250,17 @@ public class SysParamsController { if (!url.toLowerCase().contains("key")) { throw new RenException(ErrorCode.VOICEPRINT_URL_INVALID); } - // 验证URL格式 + // Validate URL format if (!url.toLowerCase().startsWith("http")) { throw new RenException(ErrorCode.VOICEPRINT_URL_PROTOCOL_ERROR); } try { - // 发送GET请求 + // Send GET request ResponseEntity response = restTemplate.getForEntity(url, String.class); if (response.getStatusCode() != HttpStatus.OK) { throw new RenException(ErrorCode.VOICEPRINT_INTERFACE_ACCESS_FAILED); } - // 检查响应内容 + // Check response content String body = response.getBody(); if (body == null || !body.contains("healthy")) { throw new RenException(ErrorCode.VOICEPRINT_INTERFACE_FORMAT_ERROR); @@ -270,7 +270,7 @@ public class SysParamsController { } } - // 校验mqtt密钥长度和复杂度 + // Validate MQTT secret length and complexity private void validateMqttSecretLength(String paramCode, String secret) { if (!paramCode.equals(Constant.SERVER_MQTT_SECRET)) { return; @@ -281,11 +281,11 @@ public class SysParamsController { if (secret.length() < 8) { throw new RenException(ErrorCode.MQTT_SECRET_LENGTH_INSECURE); } - // 检查是否同时包含大小写字母 + // Check if contains both uppercase and lowercase letters if (!secret.matches(".*[a-z].*") || !secret.matches(".*[A-Z].*")) { throw new RenException(ErrorCode.MQTT_SECRET_CHARACTER_INSECURE); } - // 不允许包含弱密码 + // Weak passwords are not allowed String[] weakPasswords = { "test", "1234", "admin", "password", "qwerty", "xiaozhi" }; for (String weakPassword : weakPasswords) { if (secret.toLowerCase().contains(weakPassword)) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java index f91da6a3a..697bcce6d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java @@ -10,7 +10,7 @@ import xiaozhi.modules.sys.entity.SysDictDataEntity; import xiaozhi.modules.sys.vo.SysDictDataItem; /** - * 字典数据 + * Dictionary data */ @Mapper public interface SysDictDataDao extends BaseDao { @@ -18,15 +18,15 @@ public interface SysDictDataDao extends BaseDao { List getDictDataByType(String dictType); /** - * 根据字典类型ID获取字典类型编码 + * Get dictionary type code based on dictionary type ID * - * @param dictTypeId 字典类型ID - * @return 字典类型编码 + * @param dictTypeId Dictionary type ID + * @return Dictionary type code */ String getTypeByTypeId(Long dictTypeId); /** - * 根据字典数据ID集合获取字典类型编码集合 + * Get dictionary-type codes by dictionary-data ID list. */ List getDictTypesByIdList(@Param("dictDataIdList") List dictDataIdList); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java index 6c271e314..db18d3959 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java @@ -6,7 +6,7 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.sys.entity.SysDictTypeEntity; /** - * 字典类型 + * Dictionary type */ @Mapper public interface SysDictTypeDao extends BaseDao { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java index 6eebc8be8..2d75afe91 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java @@ -9,31 +9,31 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.sys.entity.SysParamsEntity; /** - * 参数管理 + * Parameter management */ @Mapper public interface SysParamsDao extends BaseDao { /** - * 根据参数编码,查询value + * Query value based on parameter code * - * @param paramCode 参数编码 - * @return 参数值 + * @param paramCode Parameter code + * @return Parameter value */ String getValueByCode(String paramCode); /** - * 获取参数编码列表 + * Get parameter code list * * @param ids ids - * @return 返回参数编码列表 + * @return Return parameter code list */ List getParamCodeList(String[] ids); /** - * 根据参数编码,更新value + * Update value based on parameter code * - * @param paramCode 参数编码 - * @param paramValue 参数值 + * @param paramCode Parameter code + * @param paramValue Parameter value */ int updateValueByCode(@Param("paramCode") String paramCode, @Param("paramValue") String paramValue); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java index fb2a24926..9b936f99a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java @@ -6,7 +6,7 @@ import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.sys.entity.SysUserEntity; /** - * 系统用户 + * System user */ @Mapper public interface SysUserDao extends BaseDao { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java index a9d960a1d..42de9851f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java @@ -5,23 +5,23 @@ import jakarta.validation.constraints.Min; import lombok.Data; /** - * 管理员分页用户的参数DTO + * Admin paginated user parameter DTO * * @author zjy * @since 2025-3-21 */ @Data -@Schema(description = "管理员分页用户的参数DTO") +@Schema(description = "Admin paginated user parameter DTO") public class AdminPageUserDTO { - @Schema(description = "手机号码") + @Schema(description = "Mobile number") private String mobile; - @Schema(description = "页数") + @Schema(description = "Page number") @Min(value = 0, message = "{sort.number}") private String page; - @Schema(description = "显示列数") + @Schema(description = "Display column count") @Min(value = 0, message = "{sort.number}") private String limit; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/EmitSeverActionDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/EmitSeverActionDTO.java index 6de89aab2..5a8db06b6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/EmitSeverActionDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/EmitSeverActionDTO.java @@ -9,18 +9,18 @@ import lombok.NoArgsConstructor; import xiaozhi.modules.sys.enums.ServerActionEnum; /** - * 发送python服务端操作DTO + * Send Python server action DTO */ @Data @NoArgsConstructor @AllArgsConstructor public class EmitSeverActionDTO { - @Schema(description = "目标ws地址") - @NotEmpty(message = "目标ws地址不能为空") + @Schema(description = "Target WS address") + @NotEmpty(message = "Target WS address cannot be empty") private String targetWs; - @Schema(description = "指定操作") - @NotNull(message = "操作不能为空") + @Schema(description = "Specify operation") + @NotNull(message = "Operation cannot be empty") private ServerActionEnum action; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java index 4aabb10e0..791952938 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java @@ -7,17 +7,17 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 修改密码 + * Change password */ @Data -@Schema(description = "修改密码") +@Schema(description = "Change password") public class PasswordDTO implements Serializable { - @Schema(description = "原密码") + @Schema(description = "Original password") @NotBlank(message = "{sysuser.password.require}") private String password; - @Schema(description = "新密码") + @Schema(description = "New password") @NotBlank(message = "{sysuser.password.require}") private String newPassword; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/RetrievePasswordDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/RetrievePasswordDTO.java index 5475cf67a..59dcab9dc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/RetrievePasswordDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/RetrievePasswordDTO.java @@ -7,28 +7,28 @@ import lombok.Data; import java.io.Serializable; /** - * 找回密码DTO + * Retrieve password DTO */ @Data -@Schema(description = "找回密码") +@Schema(description = "Retrieve password") public class RetrievePasswordDTO implements Serializable { - @Schema(description = "手机号码") + @Schema(description = "Mobile number") @NotBlank(message = "{sysuser.password.require}") private String phone; - @Schema(description = "验证码") + @Schema(description = "Verification code") @NotBlank(message = "{sysuser.password.require}") private String code; - @Schema(description = "新密码") + @Schema(description = "New password") @NotBlank(message = "{sysuser.password.require}") private String password; - @Schema(description = "图形验证码ID") + @Schema(description = "Image captcha ID") @NotBlank(message = "{sysuser.uuid.require}") private String captchaId; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionPayloadDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionPayloadDTO.java index fb1427f9a..d03f09da2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionPayloadDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionPayloadDTO.java @@ -6,21 +6,21 @@ import xiaozhi.modules.sys.enums.ServerActionEnum; import java.util.Map; /** - * 服务端动作DTO + * Server action DTO */ @Data public class ServerActionPayloadDTO { /** - * 类型(智控台发往服务端的都是server) + * Type (all sent from smart control panel to server are server) */ private String type; /** - * 动作 + * Action */ private ServerActionEnum action; /** - * 内容 + * Content */ private Map content; @@ -31,6 +31,6 @@ public class ServerActionPayloadDTO serverActionPayloadDTO.setType("server"); return serverActionPayloadDTO; } - // 私有化 + // Private constructor private ServerActionPayloadDTO() {} } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionResponseDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionResponseDTO.java index 6286b74ac..70d279fdb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionResponseDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ServerActionResponseDTO.java @@ -6,7 +6,7 @@ import xiaozhi.modules.sys.enums.ServerActionResponseEnum; import java.util.Map; /** - * 服务端动作响应体 + * Server action response body */ @Data public class ServerActionResponseDTO @@ -14,7 +14,7 @@ public class ServerActionResponseDTO private ServerActionResponseEnum status; private String message; private String type; - private Map content; // 后续这个字段可以移除,并把这个类作为基类,针对业务写自己的content类型 + private Map content; // This field can be removed later, and this class can be used as base class, writing own content type for business public static final String DEFAULT_TYPE_FORM_SERVER = "server"; public static Boolean isSuccess(ServerActionResponseDTO actionResponseDTO) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java index c18dbf8f2..f3064f6f1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java @@ -18,10 +18,10 @@ import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.UpdateGroup; /** - * 字典数据 + * Dictionary data */ @Data -@Schema(description = "字典数据") +@Schema(description = "Dictionary data") public class SysDictDataDTO implements Serializable { @Schema(description = "id") @@ -29,30 +29,30 @@ public class SysDictDataDTO implements Serializable { @NotNull(message = "{id.require}", groups = UpdateGroup.class) private Long id; - @Schema(description = "字典类型ID") + @Schema(description = "Dictionary type ID") @NotNull(message = "{sysdict.type.require}", groups = DefaultGroup.class) private Long dictTypeId; - @Schema(description = "字典标签") + @Schema(description = "Dictionary label") @NotBlank(message = "{sysdict.label.require}", groups = DefaultGroup.class) private String dictLabel; - @Schema(description = "字典值") + @Schema(description = "Dictionary value") private String dictValue; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort order") @Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class) private Integer sort; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date createDate; - @Schema(description = "更新时间") + @Schema(description = "Update time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java index 912c817cb..564f4bdce 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java @@ -18,10 +18,10 @@ import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.UpdateGroup; /** - * 字典类型 + * Dictionary type */ @Data -@Schema(description = "字典类型") +@Schema(description = "Dictionary type") public class SysDictTypeDTO implements Serializable { @Schema(description = "id") @@ -29,27 +29,27 @@ public class SysDictTypeDTO implements Serializable { @NotNull(message = "{id.require}", groups = UpdateGroup.class) private Long id; - @Schema(description = "字典类型") + @Schema(description = "Dictionary type") @NotBlank(message = "{sysdict.type.require}", groups = DefaultGroup.class) private String dictType; - @Schema(description = "字典名称") + @Schema(description = "Dictionary name") @NotBlank(message = "{sysdict.name.require}", groups = DefaultGroup.class) private String dictName; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort order") @Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class) private Integer sort; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date createDate; - @Schema(description = "更新时间") + @Schema(description = "Update time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java index a6f27b722..bbde616fe 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java @@ -18,10 +18,10 @@ import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.UpdateGroup; /** - * 参数管理 + * Parameter management */ @Data -@Schema(description = "参数管理") +@Schema(description = "Parameter management") public class SysParamsDTO implements Serializable { @Schema(description = "id") @@ -29,28 +29,28 @@ public class SysParamsDTO implements Serializable { @NotNull(message = "{id.require}", groups = UpdateGroup.class) private Long id; - @Schema(description = "参数编码") + @Schema(description = "Parameter code") @NotBlank(message = "{sysparams.paramcode.require}", groups = DefaultGroup.class) private String paramCode; - @Schema(description = "参数值") + @Schema(description = "Parameter value") @NotBlank(message = "{sysparams.paramvalue.require}", groups = DefaultGroup.class) private String paramValue; - @Schema(description = "值类型") + @Schema(description = "Value type") @NotBlank(message = "{sysparams.valuetype.require}", groups = DefaultGroup.class) @Pattern(regexp = "^(string|number|boolean|array|json)$", message = "{sysparams.valuetype.pattern}", groups = DefaultGroup.class) private String valueType; - @Schema(description = "备注") + @Schema(description = "Remarks") private String remark; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date createDate; - @Schema(description = "更新时间") + @Schema(description = "Update time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java index ff0663410..abf3c073b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java @@ -21,67 +21,67 @@ import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.UpdateGroup; /** - * 用户管理 + * User management */ @Data -@Schema(description = "用户管理") +@Schema(description = "User management") public class SysUserDTO implements Serializable { @Schema(description = "id") @Null(message = "{id.null}", groups = AddGroup.class) @NotNull(message = "{id.require}", groups = UpdateGroup.class) private Long id; - @Schema(description = "用户名", required = true) + @Schema(description = "Username", required = true) @NotBlank(message = "{sysuser.username.require}", groups = DefaultGroup.class) private String username; - @Schema(description = "密码") + @Schema(description = "Password") @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @NotBlank(message = "{sysuser.password.require}", groups = AddGroup.class) private String password; - @Schema(description = "姓名", required = true) + @Schema(description = "Name", required = true) @NotBlank(message = "{sysuser.realname.require}", groups = DefaultGroup.class) private String realName; - @Schema(description = "头像") + @Schema(description = "Avatar") private String headUrl; - @Schema(description = "性别 0:男 1:女 2:保密", required = true) + @Schema(description = "Gender 0: Male 1: Female 2: Private", required = true) @Range(min = 0, max = 2, message = "{sysuser.gender.range}", groups = DefaultGroup.class) private Integer gender; - @Schema(description = "邮箱") + @Schema(description = "Email") @Email(message = "{sysuser.email.error}", groups = DefaultGroup.class) private String email; - @Schema(description = "手机号") + @Schema(description = "Mobile number") private String mobile; - @Schema(description = "部门ID", required = true) + @Schema(description = "Department ID", required = true) @NotNull(message = "{sysuser.deptId.require}", groups = DefaultGroup.class) private Long deptId; - @Schema(description = "状态 0:停用 1:正常", required = true) + @Schema(description = "Status 0: Disabled 1: Normal", required = true) @Range(min = 0, max = 1, message = "{sysuser.status.range}", groups = DefaultGroup.class) private Integer status; - @Schema(description = "创建时间") + @Schema(description = "Creation time") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) private Date createDate; - @Schema(description = "超级管理员 0:否 1:是") + @Schema(description = "Super administrator 0: No 1: Yes") @JsonProperty(access = JsonProperty.Access.READ_ONLY) private Integer superAdmin; - @Schema(description = "角色ID列表") + @Schema(description = "Role ID list") private List roleIdList; - @Schema(description = "岗位ID列表") + @Schema(description = "Position ID list") private List postIdList; - @Schema(description = "部门名称") + @Schema(description = "Department name") private String deptName; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java index 16d3dcae8..a41dd04dd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java @@ -11,39 +11,39 @@ import lombok.EqualsAndHashCode; import xiaozhi.common.entity.BaseEntity; /** - * 数据字典 + * Data dictionary */ @Data @EqualsAndHashCode(callSuper = false) @TableName("sys_dict_data") public class SysDictDataEntity extends BaseEntity { /** - * 字典类型ID + * Dictionary type ID */ private Long dictTypeId; /** - * 字典标签 + * Dictionary label */ private String dictLabel; /** - * 字典值 + * Dictionary value */ private String dictValue; /** - * 备注 + * Remark */ private String remark; /** - * 排序 + * Sort order */ private Integer sort; /** - * 更新者 + * Updater */ @TableField(fill = FieldFill.INSERT_UPDATE) private Long updater; /** - * 更新时间 + * Update time */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java index 350d857bd..ac5d66874 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java @@ -11,35 +11,35 @@ import lombok.EqualsAndHashCode; import xiaozhi.common.entity.BaseEntity; /** - * 字典类型 + * Dictionary type */ @Data @EqualsAndHashCode(callSuper = false) @TableName("sys_dict_type") public class SysDictTypeEntity extends BaseEntity { /** - * 字典类型编码 + * Dictionary type code */ private String dictType; /** - * 字典名称 + * Dictionary name */ private String dictName; /** - * 备注 + * Remark */ private String remark; /** - * 排序 + * Sort order */ private Integer sort; /** - * 更新者 + * Updater */ @TableField(fill = FieldFill.INSERT_UPDATE) private Long updater; /** - * 更新时间 + * Update time */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java index c51c46fab..19fbe285b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java @@ -11,39 +11,39 @@ import lombok.EqualsAndHashCode; import xiaozhi.common.entity.BaseEntity; /** - * 参数管理 + * Parameter management */ @Data @EqualsAndHashCode(callSuper = false) @TableName("sys_params") public class SysParamsEntity extends BaseEntity { /** - * 参数编码 + * Parameter code */ private String paramCode; /** - * 参数值 + * Parameter value */ private String paramValue; /** - * 值类型:string-字符串,number-数字,boolean-布尔,array-数组 + * Value type: string-text, number-numeric, boolean-boolean, array-array */ private String valueType; /** - * 类型 0:系统参数 1:非系统参数 + * Type 0: System parameter 1: Non-system parameter */ private Integer paramType; /** - * 备注 + * Remark */ private String remark; /** - * 更新者 + * Updater */ @TableField(fill = FieldFill.INSERT_UPDATE) private Long updater; /** - * 更新时间 + * Update time */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java index 23043a370..39fd5ae08 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java @@ -11,35 +11,35 @@ import lombok.EqualsAndHashCode; import xiaozhi.common.entity.BaseEntity; /** - * 系统用户 + * System user */ @Data @EqualsAndHashCode(callSuper = false) @TableName("sys_user") public class SysUserEntity extends BaseEntity { /** - * 用户名 + * Username */ private String username; /** - * 密码 + * Password */ private String password; /** - * 超级管理员 0:否 1:是 + * Super admin 0: No 1: Yes */ private Integer superAdmin; /** - * 状态 0:停用 1:正常 + * Status 0: Disabled 1: Normal */ private Integer status; /** - * 更新者 + * Updater */ @TableField(fill = FieldFill.INSERT_UPDATE) private Long updater; /** - * 更新时间 + * Update time */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java index ec3ce2f5e..2ac593af4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** - * 服务端动作枚举 + * Server action enumeration */ public enum ServerActionEnum { RESTART("restart"), diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionResponseEnum.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionResponseEnum.java index 040b2085b..be26f0183 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionResponseEnum.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionResponseEnum.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** - * 服务端调用响应枚举 + * Server action response enumeration */ public enum ServerActionResponseEnum { SUCCESS("success"), FAIL("fail"); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java index 655f46e68..c66f9c836 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java @@ -1,7 +1,7 @@ package xiaozhi.modules.sys.enums; /** - * 超级管理员枚举 + * Super admin enumeration */ public enum SuperAdminEnum { YES(1), diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java index 2e2bdb428..75730b512 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java @@ -7,7 +7,7 @@ import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; /** - * 参数管理 + * Parameter management */ @AllArgsConstructor @Component diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java index ea898447f..3d458f3b6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java @@ -11,59 +11,59 @@ import xiaozhi.modules.sys.vo.SysDictDataItem; import xiaozhi.modules.sys.vo.SysDictDataVO; /** - * 数据字典 + * Data dictionary */ public interface SysDictDataService extends BaseService { /** - * 分页查询数据字典信息 + * Paginated query data dictionary information * - * @param params 查询参数,包含分页信息和查询条件 - * @return 返回数据字典的分页查询结果 + * @param params Query parameters, including pagination info and query conditions + * @return Return paginated query results of data dictionary */ PageData page(Map params); /** - * 根据ID获取数据字典实体 + * Get data dictionary entity by ID * - * @param id 数据字典实体的唯一标识 - * @return 返回数据字典实体的详细信息 + * @param id Unique identifier of data dictionary entity + * @return Return detailed information of data dictionary entity */ SysDictDataVO get(Long id); /** - * 保存新的数据字典项 + * Save new data dictionary item * - * @param dto 数据字典项的保存数据传输对象 + * @param dto Data transfer object for saving data dictionary item */ void save(SysDictDataDTO dto); /** - * 更新数据字典项 + * Update data dictionary item * - * @param dto 数据字典项的更新数据传输对象 + * @param dto Update data transfer object for data dictionary item */ void update(SysDictDataDTO dto); /** - * 删除数据字典项 + * Delete data dictionary item * - * @param ids 要删除的数据字典项的ID数组 + * @param ids Array of IDs of data dictionary items to delete */ void delete(Long[] ids); /** - * 根据字典类型ID删除对应的字典数据 + * Delete corresponding dictionary data based on dictionary type ID * - * @param dictTypeId 字典类型ID + * @param dictTypeId Dictionary type ID */ void deleteByTypeId(Long dictTypeId); /** - * 根据字典类型获取字典数据列表 + * Get dictionary data list based on dictionary type * - * @param dictType 字典类型 - * @return 返回字典数据列表 + * @param dictType Dictionary type + * @return Return dictionary data list */ List getDictDataByType(String dictType); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java index 697b2d10d..4a7e11f2d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java @@ -10,51 +10,51 @@ import xiaozhi.modules.sys.entity.SysDictTypeEntity; import xiaozhi.modules.sys.vo.SysDictTypeVO; /** - * 数据字典 + * Data dictionary */ public interface SysDictTypeService extends BaseService { /** - * 分页查询字典类型信息 + * Paginated query dictionary type information * - * @param params 查询参数,包含分页信息和查询条件 - * @return 返回分页的字典类型数据 + * @param params Query parameters, including pagination info and query conditions + * @return Return paginated dictionary type data */ PageData page(Map params); /** - * 根据ID获取字典类型信息 + * Get dictionary type information by ID * - * @param id 字典类型ID - * @return 返回字典类型对象 + * @param id Dictionary type ID + * @return Return dictionary type object */ SysDictTypeVO get(Long id); /** - * 保存字典类型信息 + * Save dictionary type information * - * @param dto 字典类型数据传输对象 + * @param dto Dictionary type data transfer object */ void save(SysDictTypeDTO dto); /** - * 更新字典类型信息 + * Update dictionary type information * - * @param dto 字典类型数据传输对象 + * @param dto Dictionary type data transfer object */ void update(SysDictTypeDTO dto); /** - * 删除字典类型信息 + * Delete dictionary type information * - * @param ids 要删除的字典类型ID数组 + * @param ids Array of dictionary type IDs to delete */ void delete(Long[] ids); /** - * 列出所有字典类型信息 + * List all dictionary type information * - * @return 返回字典类型列表 + * @return Return dictionary type list */ List list(Map params); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java index ac67a2760..3879583f4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java @@ -9,7 +9,7 @@ import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.entity.SysParamsEntity; /** - * 参数管理 + * Parameter management */ public interface SysParamsService extends BaseService { @@ -26,31 +26,31 @@ public interface SysParamsService extends BaseService { void delete(String[] ids); /** - * 根据参数编码,获取参数的value值 + * Get parameter value based on parameter code * - * @param paramCode 参数编码 - * @param fromCache 是否从缓存中获取 + * @param paramCode Parameter code + * @param fromCache Whether to get from cache */ String getValue(String paramCode, Boolean fromCache); /** - * 根据参数编码,获取value的Object对象 + * Get Object object of value based on parameter code * - * @param paramCode 参数编码 - * @param clazz Object对象 + * @param paramCode Parameter code + * @param clazz Object class */ T getValueObject(String paramCode, Class clazz); /** - * 根据参数编码,更新value + * Update value based on parameter code * - * @param paramCode 参数编码 - * @param paramValue 参数值 + * @param paramCode Parameter code + * @param paramValue Parameter value */ int updateValueByCode(String paramCode, String paramValue); /** - * 初始化服务器密钥 + * Initialize server secret key */ void initServerSecret(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java index 7a35da321..bf700683e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java @@ -9,7 +9,7 @@ import xiaozhi.modules.sys.entity.SysUserEntity; import xiaozhi.modules.sys.vo.AdminPageUserVO; /** - * 系统用户 + * System User */ public interface SysUserService extends BaseService { @@ -20,56 +20,56 @@ public interface SysUserService extends BaseService { void save(SysUserDTO dto); /** - * 删除指定用户,且有关联的数据设备和智能体 + * Delete specified user and associated data devices and agents * * @param ids */ void deleteById(Long ids); /** - * 验证是否允许修改密码更改 + * Verify if password change is allowed * - * @param userId 用户id - * @param passwordDTO 验证密码的参数 + * @param userId User ID + * @param passwordDTO Password verification parameters */ void changePassword(Long userId, PasswordDTO passwordDTO); /** - * 直接修改密码,不需要验证 + * Directly modify password without verification * - * @param userId 用户id - * @param password 密码 + * @param userId User ID + * @param password Password */ void changePasswordDirectly(Long userId, String password); /** - * 重置密码 + * Reset password * - * @param userId 用户id - * @return 随机生成符合规范的密码 + * @param userId User ID + * @return Randomly generated password that meets specifications */ String resetPassword(Long userId); /** - * 管理员分页用户信息 + * Administrator paginated user information * - * @param dto 分页查找参数 - * @return 用户列表分页数据 + * @param dto Pagination search parameters + * @return User list pagination data */ PageData page(AdminPageUserDTO dto); /** - * 批量修改用户状态 + * Batch modify user status * - * @param status 用户状态 - * @param userIds 用户ID数组 + * @param status User status + * @param userIds User ID array */ void changeStatus(Integer status, String[] userIds); /** - * 获取是否允许用户注册 + * Get whether user registration is allowed * - * @return 是否允许用户注册 + * @return Whether user registration is allowed */ boolean getAllowUserRegister(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java index 0fa3fc4ae..0e46c24e3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java @@ -4,16 +4,16 @@ package xiaozhi.modules.sys.service; import java.util.function.Consumer; /** - * 定义一个系统用户工具类,避免和用户模块循环依赖 - * 如用户和设备互相依赖,用户需要获取所有设备,设备又需要获取每个设备的用户名 + * Define a system user utility class to avoid circular dependency with user module + * For example, user and device depend on each other, user needs to get all devices, device needs to get username for each device * @author zjy * @since 2025-4-2 */ public interface SysUserUtilService { /** - * 赋值用户名 - * @param userId 用户id - * @param setter 赋值方法 + * Assign username + * @param userId User id + * @param setter Setter method */ void assignUsername( Long userId, Consumer setter); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/TokenService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/TokenService.java index d3839f703..74de1a404 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/TokenService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/TokenService.java @@ -2,7 +2,7 @@ package xiaozhi.modules.sys.service; public interface TokenService { /** - * 生成token + * Generate token * * @param userId * @return diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java index 0449061b0..d66cce572 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java @@ -31,7 +31,7 @@ import xiaozhi.modules.sys.vo.SysDictDataItem; import xiaozhi.modules.sys.vo.SysDictDataVO; /** - * 字典类型 + * Dictionary-data service implementation. */ @Service @AllArgsConstructor @@ -74,13 +74,13 @@ public class SysDictDataServiceImpl extends BaseServiceImpl idList = Arrays.asList(ids); if (ToolUtil.isNotEmpty(idList)) { - //批量删除redis字典 + // Delete cached dictionary entries in batch. List redisKeyList = new ArrayList<>(); - //批量获取字典类型 + // Load dictionary types in batch. List dictTypeList = Optional.ofNullable(baseDao.getDictTypesByIdList(idList)).orElseGet(ArrayList::new); dictTypeList.forEach(dictType -> redisKeyList.add(RedisKeys.getDictDataByTypeKey(dictType))); if (ToolUtil.isNotEmpty(redisKeyList)) { - //清除缓存 + // Clear cache entries. redisUtils.delete(redisKeyList); } - //批量删除字典数据 + // Delete dictionary rows in batch. deleteBatchIds(Arrays.asList(ids)); } } @@ -127,19 +127,19 @@ public class SysDictDataServiceImpl extends BaseServiceImpl sysDictDataList) { - // 收集所有用户 ID + // Collect all user IDs. Set userIds = sysDictDataList.stream().flatMap(vo -> Stream.of(vo.getCreator(), vo.getUpdater())) .filter(Objects::nonNull).collect(Collectors.toSet()); - // 设置更新者和创建者名称 + // Populate creator and updater names. if (!userIds.isEmpty()) { List sysUserEntities = sysUserDao.selectBatchIds(userIds); - // 把List转成Map,Map + // Convert the list to a Map. Map userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId, SysUserEntity::getUsername, (existing, replacement) -> existing)); @@ -168,21 +168,21 @@ public class SysDictDataServiceImpl extends BaseServiceImpl cachedData = (List) redisUtils.get(key); if (cachedData != null) { return cachedData; } - // 如果缓存中没有,则从数据库获取 + // Load from the database when the cache misses. List data = baseDao.getDictDataByType(dictType); - // 存入Redis缓存 + // Store in Redis. if (data != null) { redisUtils.set(key, data); } return data; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java index 8bb393fd4..9d1b6a024 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java @@ -32,7 +32,7 @@ import xiaozhi.modules.sys.service.SysDictTypeService; import xiaozhi.modules.sys.vo.SysDictTypeVO; /** - * 字典类型 + * Dictionary Type */ @Service @AllArgsConstructor @@ -76,7 +76,7 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl list(Map params) { List entityList = baseDao.selectList(getWrapper(params)); List sysDictTypeVOList = ConvertUtils.sourceToTarget(entityList, SysDictTypeVO.class); - // 设置用户名 + // Set username setUserName(sysDictTypeVOList); return sysDictTypeVOList; } /** - * 设置用户名 + * Set username * - * @param sysDictTypeList 字典类型集合 + * @param sysDictTypeList Dictionary type collection */ private void setUserName(List sysDictTypeList) { - // 收集所有用户 ID + // Collect all user IDs Set userIds = sysDictTypeList.stream().flatMap(vo -> Stream.of(vo.getCreator(), vo.getUpdater())) .filter(Objects::nonNull).collect(Collectors.toSet()); - // 设置更新者和创建者名称 + // Set updater and creator names if (!userIds.isEmpty()) { List sysUserEntities = sysUserDao.selectBatchIds(userIds); - // 把List转成Map,Map + // Convert List to Map, Map Map userNameMap = sysUserEntities.stream().collect(Collectors.toMap(SysUserEntity::getId, SysUserEntity::getUsername, (existing, replacement) -> existing)); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java index b22dd2b90..b9ce33a94 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java @@ -29,7 +29,7 @@ import xiaozhi.modules.sys.redis.SysParamsRedis; import xiaozhi.modules.sys.service.SysParamsService; /** - * 参数管理 + * Parameter Management */ @AllArgsConstructor @Service @@ -94,7 +94,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl paramCodeList = baseDao.getParamCodeList(ids); String[] paramCodes = paramCodeList.toArray(new String[paramCodeList.size()]); if (paramCodes.length > 0) { sysParamsRedis.delete(paramCodes); } - // 删除 + // Delete deleteBatchIds(Arrays.asList(ids)); } @@ -201,62 +201,62 @@ public class SysParamsServiceImpl extends BaseServiceImpl keyPair = SM2Utils.createKey(); String newPublicKey = keyPair.get(SM2Utils.KEY_PUBLIC_KEY); String newPrivateKey = keyPair.get(SM2Utils.KEY_PRIVATE_KEY); - // 更新数据库中的密钥对 + // Persist the generated key pair. updateValueByCode(Constant.SM2_PUBLIC_KEY, newPublicKey); updateValueByCode(Constant.SM2_PRIVATE_KEY, newPrivateKey); } } /** - * 检测短信参数是否符合要求 + * Check if SMS parameters meet requirements * - * @param paramCode 参数编码 - * @param paramValue 参数值 - * @return 是否通过 + * @param paramCode Parameter code + * @param paramValue Parameter value + * @return Whether passed */ private boolean detectingSMSParameters(String paramCode, String paramValue) { - // 判断是否是开启手机注册的参数编码,如果不是参数编码,着不需要检测其他短信参数,直接返回true + // Check if it is the parameter code for enabling phone registration, if not parameter code, no need to check other SMS parameters, return true directly if (!Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue().equals(paramCode)) { return true; } - // 判断是否为关闭,如果是关闭短信注册,着不需要检测其他短信参数,直接返回true + // Check if it is disabled, if SMS registration is disabled, no need to check other SMS parameters, return true directly if ("false".equalsIgnoreCase(paramValue)) { return true; } - // 检测短信关联参数是否为空 + // Check if SMS related parameters are empty ArrayList list = new ArrayList(); list.add(Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue()); - list.add(Constant.SysMSMParam.ALIYUN_SMS_ACCESS_KEY_ID.getValue()); - list.add(Constant.SysMSMParam.ALIYUN_SMS_ACCESS_KEY_SECRET.getValue()); - list.add(Constant.SysMSMParam.ALIYUN_SMS_SIGN_NAME.getValue()); - list.add(Constant.SysMSMParam.ALIYUN_SMS_SMS_CODE_TEMPLATE_CODE.getValue()); + list.add(Constant.SysMSMParam.TWILIO_SMS_ACCOUNT_SID.getValue()); + list.add(Constant.SysMSMParam.TWILIO_SMS_AUTH_TOKEN.getValue()); + list.add(Constant.SysMSMParam.TWILIO_SMS_PHONE_NUMBER.getValue()); + list.add(Constant.SysMSMParam.TWILIO_SMS_TEMPLATE_MESSAGE.getValue()); StringBuilder str = new StringBuilder(); list.forEach(item -> { if (!StringUtils.isNoneBlank(item)) { @@ -264,10 +264,10 @@ public class SysParamsServiceImpl extends BaseServiceImpl().like(StringUtils.isNotBlank(dto.getMobile()), "username", dto.getMobile())); - // 循环处理page获取回来的数据,返回需要的字段 + // Loop through page data and return required fields List list = page.getRecords().stream().map(user -> { AdminPageUserVO adminPageUserVO = new AdminPageUserVO(); adminPageUserVO.setUserid(user.getId().toString()); @@ -180,7 +180,7 @@ public class SysUserServiceImpl extends BaseServiceImpl listener(Predicate predicate) throws InterruptedException, TimeoutException, ExecutionException { @@ -183,10 +183,10 @@ public class WebSocketClientManager implements Closeable { } /** - * 同步接收多条消息,直到 predicate 为 true 或超时抛异常; - * 不自动关闭连接,适用于需要在同一连接上发送多个消息的场景 + * Synchronously receive multiple messages until predicate is true or timeout throws exception; + * Do not automatically close connection, suitable for scenarios requiring multiple messages on same connection * - * @return 返回监听期间的所有消息列表 + * @return Return list of all messages during listening period */ public List listenerWithoutClose(Predicate predicate) throws InterruptedException, TimeoutException, ExecutionException { @@ -199,7 +199,7 @@ public class WebSocketClientManager implements Closeable { } /** - * 注册文本回调 + * Register text callback */ public WebSocketClientManager onText(Consumer c) { this.onText = c; @@ -207,7 +207,7 @@ public class WebSocketClientManager implements Closeable { } /** - * 注册二进制回调 + * Register binary callback */ public WebSocketClientManager onBinary(Consumer c) { this.onBinary = c; @@ -215,7 +215,7 @@ public class WebSocketClientManager implements Closeable { } /** - * 注册错误回调 + * Register error callback */ public WebSocketClientManager onError(Consumer c) { this.onError = c; @@ -223,7 +223,7 @@ public class WebSocketClientManager implements Closeable { } /** - * 关闭会话,try-with-resources / finally 自动调用 + * Close session, automatically called by try-with-resources / finally */ @Override public void close() { @@ -235,7 +235,7 @@ public class WebSocketClientManager implements Closeable { } textMessageQueue.clear(); binaryMessageQueue.clear(); - errorFuture.completeExceptionally(new IOException("WebSocket 已关闭")); + errorFuture.completeExceptionally(new IOException("WebSocket is closed")); } private class InternalHandler extends AbstractWebSocketHandler { @@ -248,54 +248,54 @@ public class WebSocketClientManager implements Closeable { } /** - * 连接建立时回调 + * Callback when connection is established */ @Override public void afterConnectionEstablished(WebSocketSession session) { - // 保存会话 + // Save session WebSocketClientManager.this.session = session; this.stopWatch.start(); - log.info("ws连接成功, 目标URI: {}, 连接时间: {}", targetUri, + log.info("WebSocket connection successful, target URI: {}, connection time: {}", targetUri, DateUtils.getDateTimeNow(DateUtils.DATE_TIME_MILLIS_PATTERN)); } /** - * 处理文本消息 + * Handle text messages */ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); - // 入队 + // Enqueue textMessageQueue.offer(payload); - // 回调用户注册的 onText + // Callback user registered onText if (onText != null) { CALLBACK_EXECUTOR.submit(() -> onText.accept(payload)); } } /** - * 处理二进制消息 + * Handle binary messages */ @Override protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception { ByteBuffer buf = message.getPayload(); byte[] data = new byte[buf.remaining()]; buf.get(data); - // 入队 + // Enqueue binaryMessageQueue.offer(data); - // 回调用户注册的 onBinary + // Callback user registered onBinary if (onBinary != null) { CALLBACK_EXECUTOR.submit(() -> onBinary.accept(data)); } } /** - * 传输错误时回调 + * Callback when transmission error occurs */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { super.handleTransportError(session, exception); - // 保持原有逻辑:完成 errorFuture、回调 onError、关闭会话、异步通知连接失败 + // Maintain original logic: complete errorFuture, callback onError, close session, async notify connection failure errorFuture.completeExceptionally(exception); if (onError != null) { CALLBACK_EXECUTOR.submit(() -> onError.accept(exception)); @@ -304,7 +304,7 @@ public class WebSocketClientManager implements Closeable { } /** - * 连接关闭时回调 + * Callback when connection closes */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { @@ -312,7 +312,7 @@ public class WebSocketClientManager implements Closeable { if (stopWatch.isRunning()) { stopWatch.stop(); } - log.info("ws连接关闭, 目标URI: {}, 关闭时间: {}, 连接总时长: {}s,断开原因:{}", + log.info("WebSocket connection closed, target URI: {}, close time: {}, total connection duration: {}s, disconnect reason: {}", targetUri, DateUtils.getDateTimeNow(DateUtils.DATE_TIME_MILLIS_PATTERN), DateUtils.millsToSecond(stopWatch.getTotalTimeMillis()),status); } @@ -320,17 +320,17 @@ public class WebSocketClientManager implements Closeable { } public static class Builder { - private String uri; // 目标 WS URI - private long connectTimeout = 3; // 请求连接等待时间 - private TimeUnit connectUnit = TimeUnit.SECONDS; // 请求连接等待时间单位 - private long maxSessionDuration = 5; // 最大连线时间,默认5秒 - private TimeUnit maxSessionDurationUnit = TimeUnit.SECONDS; // 最大连线时间单位 - private int queueCapacity = 100; // 消息队列容量 - private int bufferSize = 8 * 1024; //默认 8kb - private WebSocketHttpHeaders headers; // 请求头 + private String uri; // Target WS URI + private long connectTimeout = 3; // Request connection wait time + private TimeUnit connectUnit = TimeUnit.SECONDS; // Request connection wait time unit + private long maxSessionDuration = 5; // Maximum connection time, default 5 seconds + private TimeUnit maxSessionDurationUnit = TimeUnit.SECONDS; // Maximum connection time unit + private int queueCapacity = 100; // message queue capacity + private int bufferSize = 8 * 1024; // Default 8kb + private WebSocketHttpHeaders headers; // Request headers /** - * 目标 WS URI + * Target WS URI */ public Builder uri(String uri) { this.uri = Objects.requireNonNull(uri); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java index d9563c297..e35bcc9d6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java @@ -20,13 +20,13 @@ public class WebSocketTestHandler implements WebSocketHandler { try { session.close(); } catch (Exception e) { - // 忽略关闭异常 + // Ignore close exception } } @Override public void handleMessage(WebSocketSession session, WebSocketMessage message) { - // 不需要处理消息 + // No need to process message } @Override @@ -36,7 +36,7 @@ public class WebSocketTestHandler implements WebSocketHandler { @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { - // 连接关闭时不做任何处理 + // No processing when connection is closed } @Override diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java index 39bbe01f5..a57d2562b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java @@ -15,15 +15,15 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; public class WebSocketValidator { private static final Logger logger = LoggerFactory.getLogger(WebSocketValidator.class); - // WebSocket URL正则表达式 + // WebSocket URL regular expression private static final Pattern WS_URL_PATTERN = Pattern .compile("^wss?://[\\w.-]+(?:\\.[\\w.-]+)*(?::\\d+)?(?:/[\\w.-]*)*$"); /** - * 验证WebSocket地址格式 + * Validate WebSocket address format * - * @param url WebSocket地址 - * @return 是否有效 + * @param url WebSocket address + * @return Whether valid */ public static boolean validateUrlFormat(String url) { if (StringUtils.isBlank(url)) { @@ -33,10 +33,10 @@ public class WebSocketValidator { } /** - * 测试WebSocket连接 + * Test WebSocket connection * - * @param url WebSocket地址 - * @return 是否可连接 + * @param url WebSocket address + * @return Whether connectable */ public static boolean testConnection(String url) { if (!validateUrlFormat(url)) { @@ -50,10 +50,10 @@ public class WebSocketValidator { client.execute(new WebSocketTestHandler(future), headers, URI.create(url)); - // 等待最多5秒获取连接结果 + // Wait up to 5 seconds to get connection result return future.get(5, TimeUnit.SECONDS); } catch (Exception e) { - logger.error("WebSocket连接测试失败: {}", url, e); + logger.error("WebSocket connection test failed: {}", url, e); return false; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java index 9f832372a..ab2fe0cb7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java @@ -6,7 +6,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 管理员分页展示用户的VO + * Admin paginated user display VO * @ zjy * * @since 2025-3-25 @@ -14,18 +14,18 @@ import lombok.Data; @Data public class AdminPageUserVO { - @Schema(description = "设备数量") + @Schema(description = "Device Count") private String deviceCount; - @Schema(description = "手机号码") + @Schema(description = "Mobile Number") private String mobile; - @Schema(description = "状态") + @Schema(description = "Status") private Integer status; - @Schema(description = "用户id") + @Schema(description = "User ID") private String userid; - @Schema(description = "注册时间") + @Schema(description = "Registration Time") private Date createDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataItem.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataItem.java index f6c81500e..f9e2e4845 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataItem.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataItem.java @@ -6,15 +6,15 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 字典数据VO + * Dictionary Data VO */ @Data -@Schema(description = "字典数据项") +@Schema(description = "Dictionary Data Item") public class SysDictDataItem implements Serializable { - @Schema(description = "字典标签") + @Schema(description = "Dictionary Label") private String name; - @Schema(description = "字典值") + @Schema(description = "Dictionary Value") private String key; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataVO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataVO.java index 40025b704..d9623c6ef 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictDataVO.java @@ -7,44 +7,44 @@ import java.io.Serializable; import java.util.Date; /** - * 字典数据VO + * Dictionary Data VO */ @Data -@Schema(description = "字典数据VO") +@Schema(description = "Dictionary Data VO") public class SysDictDataVO implements Serializable { - @Schema(description = "主键") + @Schema(description = "Primary Key") private Long id; - @Schema(description = "字典类型ID") + @Schema(description = "Dictionary Type ID") private Long dictTypeId; - @Schema(description = "字典标签") + @Schema(description = "Dictionary Label") private String dictLabel; - @Schema(description = "字典值") + @Schema(description = "Dictionary Value") private String dictValue; - @Schema(description = "备注") + @Schema(description = "Remark") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort Order") private Integer sort; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建者名称") + @Schema(description = "Creator Name") private String creatorName; - @Schema(description = "创建时间") + @Schema(description = "Create Time") private Date createDate; - @Schema(description = "更新者") + @Schema(description = "Updater") private Long updater; - @Schema(description = "更新者名称") + @Schema(description = "Updater Name") private String updaterName; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updateDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictTypeVO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictTypeVO.java index 5e5844f3c..9a7298606 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictTypeVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/SysDictTypeVO.java @@ -7,41 +7,41 @@ import java.io.Serializable; import java.util.Date; /** - * 字典类型VO + * Dictionary Type VO */ @Data -@Schema(description = "字典类型VO") +@Schema(description = "Dictionary Type VO") public class SysDictTypeVO implements Serializable { - @Schema(description = "主键") + @Schema(description = "Primary Key") private Long id; - @Schema(description = "字典类型") + @Schema(description = "Dictionary Type") private String dictType; - @Schema(description = "字典名称") + @Schema(description = "Dictionary Name") private String dictName; - @Schema(description = "备注") + @Schema(description = "Remark") private String remark; - @Schema(description = "排序") + @Schema(description = "Sort Order") private Integer sort; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建者名称") + @Schema(description = "Creator name") private String creatorName; - @Schema(description = "创建时间") + @Schema(description = "Creation time") private Date createDate; - @Schema(description = "更新者") + @Schema(description = "Updater") private Long updater; - @Schema(description = "更新者名称") + @Schema(description = "Updater name") private String updaterName; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updateDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java index ff420c02d..be449d18a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java @@ -27,7 +27,7 @@ import xiaozhi.modules.timbre.service.TimbreService; import xiaozhi.modules.timbre.vo.TimbreDetailsVO; /** - * 音色控制层 + * Timbre Controller Layer * * @author zjy * @since 2025-3-21 @@ -35,18 +35,18 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO; @AllArgsConstructor @RestController @RequestMapping("/ttsVoice") -@Tag(name = "音色管理") +@Tag(name = "Timbre Management") public class TimbreController { private final TimbreService timbreService; @GetMapping - @Operation(summary = "分页查找") + @Operation(summary = "Paginated Search") @RequiresPermissions("sys:role:superAdmin") @Parameters({ - @Parameter(name = "ttsModelId", description = "对应 TTS 模型主键", required = true), - @Parameter(name = "name", description = "音色名称"), - @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), - @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true), + @Parameter(name = "ttsModelId", description = "Corresponding TTS Model Primary Key", required = true), + @Parameter(name = "name", description = "Timbre Name"), + @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), }) public Result> page( @Parameter(hidden = true) @RequestParam Map params) { @@ -62,7 +62,7 @@ public class TimbreController { } @PostMapping - @Operation(summary = "音色保存") + @Operation(summary = "Save Timbre") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody TimbreDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -71,7 +71,7 @@ public class TimbreController { } @PutMapping("/{id}") - @Operation(summary = "音色修改") + @Operation(summary = "Update Timbre") @RequiresPermissions("sys:role:superAdmin") public Result update( @PathVariable String id, @@ -82,7 +82,7 @@ public class TimbreController { } @PostMapping("/delete") - @Operation(summary = "音色删除") + @Operation(summary = "Timbre Deletion") @RequiresPermissions("sys:role:superAdmin") public Result delete(@RequestBody String[] ids) { timbreService.delete(ids); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dao/TimbreDao.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dao/TimbreDao.java index 3656b4ea6..fcc9395da 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dao/TimbreDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dao/TimbreDao.java @@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import xiaozhi.modules.timbre.entity.TimbreEntity; /** - * 音色持久层定义 + * Timbre persistence layer definition * * @author zjy * @since 2025-3-21 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java index 202c4eafb..ab52ba651 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java @@ -6,44 +6,44 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 音色表数据DTO + * Timbre table data DTO * * @author zjy * @since 2025-3-21 */ @Data -@Schema(description = "音色表信息") +@Schema(description = "Timbre Table Information") public class TimbreDataDTO { - @Schema(description = "语言") + @Schema(description = "Language") @NotBlank(message = "{timbre.languages.require}") private String languages; - @Schema(description = "音色名称") + @Schema(description = "Timbre Name") @NotBlank(message = "{timbre.name.require}") private String name; - @Schema(description = "备注") + @Schema(description = "Remark") private String remark; - @Schema(description = "参考音频路径") + @Schema(description = "Reference Audio Path") private String referenceAudio; - @Schema(description = "參考文本") + @Schema(description = "Reference Text") private String referenceText; - @Schema(description = "排序") + @Schema(description = "Sort Order") @Min(value = 0, message = "{sort.number}") private long sort; - @Schema(description = "对应 TTS 模型主键") + @Schema(description = "Corresponding TTS Model Primary Key") @NotBlank(message = "{timbre.ttsModelId.require}") private String ttsModelId; - @Schema(description = "音色编码") + @Schema(description = "Timbre Code") @NotBlank(message = "{timbre.ttsVoice.require}") private String ttsVoice; - @Schema(description = "音频播放地址") + @Schema(description = "Audio Playback URL") private String voiceDemo; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbrePageDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbrePageDTO.java index 9c2aaf247..3ae866734 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbrePageDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbrePageDTO.java @@ -5,25 +5,25 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 音色分页参数DTO + * Timbre pagination parameters DTO * * @author zjy * @since 2025-3-21 */ @Data -@Schema(description = "音色分页参数") +@Schema(description = "Timbre pagination parameters") public class TimbrePageDTO { - @Schema(description = "对应 TTS 模型主键") + @Schema(description = "Corresponding TTS Model Primary Key") @NotBlank(message = "{timbre.ttsModelId.require}") private String ttsModelId; - @Schema(description = "音色名称") + @Schema(description = "Timbre Name") private String name; - @Schema(description = "页数") + @Schema(description = "Page Number") private String page; - @Schema(description = "显示列数") + @Schema(description = "Display Column Count") private String limit; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java index 508c3f32e..44960a2d6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java @@ -11,7 +11,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; /** - * 音色表实体类 + * Timbre table entity class * * @author zjy * @since 2025-3-21 @@ -19,52 +19,52 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("ai_tts_voice") -@Schema(description = "音色信息") +@Schema(description = "Timbre Information") public class TimbreEntity { @Schema(description = "id") private String id; - @Schema(description = "语言") + @Schema(description = "Language") private String languages; - @Schema(description = "音色名称") + @Schema(description = "Timbre Name") private String name; - @Schema(description = "备注") + @Schema(description = "Remark") private String remark; - @Schema(description = "参考音频路径") + @Schema(description = "Reference Audio Path") private String referenceAudio; - @Schema(description = "參考文本") + @Schema(description = "Reference Text") private String referenceText; - @Schema(description = "排序") + @Schema(description = "Sort Order") private long sort; - @Schema(description = "对应 TTS 模型主键") + @Schema(description = "Corresponding TTS Model Primary Key") private String ttsModelId; - @Schema(description = "音色编码") + @Schema(description = "Timbre Code") private String ttsVoice; - @Schema(description = "音频播放地址") + @Schema(description = "Audio Playback URL") private String voiceDemo; - @Schema(description = "更新者") + @Schema(description = "Updater") @TableField(fill = FieldFill.UPDATE) private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update Time") @TableField(fill = FieldFill.UPDATE) private Date updateDate; - @Schema(description = "创建者") + @Schema(description = "Creator") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Create Time") @TableField(fill = FieldFill.INSERT) private Date createDate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java index d8025b3c2..b9d9fa3ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java @@ -11,66 +11,66 @@ import xiaozhi.modules.timbre.entity.TimbreEntity; import xiaozhi.modules.timbre.vo.TimbreDetailsVO; /** - * 音色的业务层的定义 + * Timbre business layer definition * * @author zjy * @since 2025-3-21 */ public interface TimbreService extends BaseService { /** - * 分页获取音色指定tts的下的音色 + * Get paginated timbres under specified TTS * - * @param dto 分页查找参数 - * @return 音色列表分页数据 + * @param dto Pagination search parameters + * @return Paginated timbre list data */ PageData page(TimbrePageDTO dto); /** - * 获取音色指定id的详情信息 + * Get timbre details by specified ID * - * @param timbreId 音色表id - * @return 音色信息 + * @param timbreId Timbre table ID + * @return Timbre information */ TimbreDetailsVO get(String timbreId); /** - * 保存音色信息 + * Save timbre information * - * @param dto 需要保存数据 + * @param dto Data to be saved */ void save(TimbreDataDTO dto); /** - * 保存音色信息 + * Save timbre information * - * @param timbreId 需要修改的id - * @param dto 需要修改的数据 + * @param timbreId ID that needs to be modified + * @param dto Data that needs to be modified */ void update(String timbreId, TimbreDataDTO dto); /** - * 批量删除音色 + * Batch delete timbres * - * @param ids 需要被删除的音色id列表 + * @param ids List of timbre IDs to be deleted */ void delete(String[] ids); List getVoiceNames(String ttsModelId, String voiceName); /** - * 根据ID获取音色名称 + * Get timbre name by ID * - * @param id 音色ID - * @return 音色名称 + * @param id Timbre ID + * @return Timbre name */ String getTimbreNameById(String id); /** - * 根据音色编码获取音色信息 - * - * @param ttsModelId 音色模型ID - * @param voiceCode 音色编码 - * @return 音色信息 + * Get voice information by voice code. + * + * @param ttsModelId voice model ID + * @param voiceCode voice code + * @return voice information */ VoiceDTO getByVoiceCode(String ttsModelId, String voiceCode); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java index 165824f67..8b124d18e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java @@ -32,8 +32,8 @@ import xiaozhi.modules.voiceclone.dao.VoiceCloneDao; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; /** - * 音色的业务层的实现 - * + * Timbre business layer implementation + * * @author zjy * @since 2025-3-21 */ @@ -52,11 +52,11 @@ public class TimbreServiceImpl extends BaseServiceImpl params.put(Constant.LIMIT, dto.getLimit()); IPage page = baseDao.selectPage( getPage(params, null, true), - // 定义查询条件 + // Define query conditions. new QueryWrapper() - // 必须按照ttsID查找 + // Always filter by TTS model ID. .eq("tts_model_id", dto.getTtsModelId()) - // 如果有音色名字,按照音色名模糊查找 + // Apply fuzzy search when a timbre name is provided. .like(StringUtils.isNotBlank(dto.getName()), "name", dto.getName())); return getPageData(page, TimbreDetailsVO.class); @@ -68,23 +68,23 @@ public class TimbreServiceImpl extends BaseServiceImpl return null; } - // 先从Redis获取缓存 + // Read from Redis cache first. String key = RedisKeys.getTimbreDetailsKey(timbreId); TimbreDetailsVO cachedDetails = (TimbreDetailsVO) redisUtils.get(key); if (cachedDetails != null) { return cachedDetails; } - // 如果缓存中没有,则从数据库获取 + // Load from the database when the cache misses. TimbreEntity entity = baseDao.selectById(timbreId); if (entity == null) { return null; } - // 转换为VO对象 + // Convert to the response VO. TimbreDetailsVO details = ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class); - // 存入Redis缓存 + // Store the result in Redis. if (details != null) { redisUtils.set(key, details); } @@ -107,7 +107,7 @@ public class TimbreServiceImpl extends BaseServiceImpl TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class); timbreEntity.setId(timbreId); baseDao.updateById(timbreEntity); - // 删除缓存 + // Invalidate cache. redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId)); } @@ -129,26 +129,26 @@ public class TimbreServiceImpl extends BaseServiceImpl .map(entity -> { VoiceDTO dto = new VoiceDTO(entity.getId(), entity.getName()); dto.setVoiceDemo(entity.getVoiceDemo()); - dto.setLanguages(entity.getLanguages()); // 设置语言类型 - dto.setIsClone(false); // 设置为普通音色 + dto.setLanguages(entity.getLanguages()); // Preserve language metadata. + dto.setIsClone(false); // Mark as a standard timbre. return dto; }) .collect(Collectors.toList()); - // 获取当前登录用户ID + // Resolve the current logged-in user. Long currentUserId = SecurityUser.getUser().getId(); if (currentUserId != null) { - // 查询用户的所有克隆音色记录 + // Load all trained clone-timbre records for the user. List cloneEntities = voiceCloneDao.getTrainSuccess(ttsModelId, currentUserId); for (VoiceDTO entity : cloneEntities) { - // 只添加训练成功的克隆音色,且模型ID匹配 + // Only include successfully trained clone timbres that match the model. VoiceDTO voiceDTO = new VoiceDTO(); voiceDTO.setId(entity.getId()); voiceDTO.setName(MessageUtils.getMessage(ErrorCode.VOICE_CLONE_PREFIX) + entity.getName()); - // 保留从数据库查询到的voiceDemo字段 + // Preserve the voiceDemo value returned from the database. voiceDTO.setVoiceDemo(entity.getVoiceDemo()); voiceDTO.setLanguages(entity.getLanguages()); - voiceDTO.setIsClone(true); // 设置为克隆音色 + voiceDTO.setIsClone(true); // Mark as a clone timbre. redisUtils.set(RedisKeys.getTimbreNameById(voiceDTO.getId()), voiceDTO.getName(), RedisUtils.NOT_EXPIRE); voiceDTOs.add(0, voiceDTO); @@ -159,10 +159,10 @@ public class TimbreServiceImpl extends BaseServiceImpl } /** - * 处理是不是tts模型的id + * Process whether it is TTS model ID */ private void isTtsModelId(String ttsModelId) { - // 等模型配置那边写好调用方法判断 + // Reserved for future validation against model configuration. } @Override @@ -211,7 +211,7 @@ public class TimbreServiceImpl extends BaseServiceImpl TimbreEntity entity = list.get(0); VoiceDTO dto = new VoiceDTO(entity.getId(), entity.getName()); dto.setVoiceDemo(entity.getVoiceDemo()); - dto.setIsClone(false); // 设置为普通音色 + dto.setIsClone(false); // Mark as a standard timbre. return dto; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/vo/TimbreDetailsVO.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/vo/TimbreDetailsVO.java index 2cae1a534..590534431 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/vo/TimbreDetailsVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/vo/TimbreDetailsVO.java @@ -6,41 +6,41 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 音色详情展示VO + * Timbre details display VO * * @author zjy * @since 2025-3-21 */ @Data public class TimbreDetailsVO implements Serializable { - @Schema(description = "音色id") + @Schema(description = "Timbre ID") private String id; - @Schema(description = "语言") + @Schema(description = "Language") private String languages; - @Schema(description = "音色名称") + @Schema(description = "Timbre Name") private String name; - @Schema(description = "备注") + @Schema(description = "Remark") private String remark; - @Schema(description = "参考音频路径") + @Schema(description = "Reference Audio Path") private String referenceAudio; - @Schema(description = "參考文本") + @Schema(description = "Reference Text") private String referenceText; - @Schema(description = "排序") + @Schema(description = "Sort Order") private long sort; - @Schema(description = "对应 TTS 模型主键") + @Schema(description = "Corresponding TTS Model Primary Key") private String ttsModelId; - @Schema(description = "音色编码") + @Schema(description = "Timbre Code") private String ttsVoice; - @Schema(description = "音频播放地址") + @Schema(description = "Audio Playback URL") private String voiceDemo; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java index 21370a46a..03558f819 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java @@ -35,7 +35,7 @@ import xiaozhi.modules.voiceclone.dto.VoiceCloneResponseDTO; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; import xiaozhi.modules.voiceclone.service.VoiceCloneService; -@Tag(name = "音色资源管理", description = "音色资源开通相关接口") +@Tag(name = "Voice Resource Management", description = "Endpoints for voice resource provisioning") @Slf4j @RestController @RequiredArgsConstructor @@ -46,10 +46,10 @@ public class VoiceCloneController { private final RedisUtils redisUtils; @GetMapping - @Operation(summary = "分页查询音色资源") + @Operation(summary = "List voice resources with pagination") @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) }) @RequiresPermissions("sys:role:normal") public Result> page( @@ -62,41 +62,41 @@ public class VoiceCloneController { } @PostMapping("/upload") - @Operation(summary = "上传音频进行声音克隆") + @Operation(summary = "Upload audio for voice cloning") @Parameters({ - @Parameter(name = "id", description = "声音克隆记录ID", required = true), - @Parameter(name = "voiceFile", description = "音频文件", required = true) + @Parameter(name = "id", description = "Voice-clone record ID", required = true), + @Parameter(name = "voiceFile", description = "Audio file", required = true) }) @RequiresPermissions("sys:role:normal") public Result uploadVoice( @RequestParam("id") String id, @RequestParam("voiceFile") MultipartFile voiceFile) { try { - // 验证文件 + // Validate the uploaded file. if (voiceFile == null || voiceFile.isEmpty()) { return new Result().error(ErrorCode.VOICE_CLONE_AUDIO_EMPTY); } - // 验证文件类型 + // Validate the file type. String contentType = voiceFile.getContentType(); if (contentType == null || !contentType.startsWith("audio/")) { return new Result().error(ErrorCode.VOICE_CLONE_NOT_AUDIO_FILE); } - // 加强验证文件扩展名 + // Enforce supported file extensions. String originalFilename = voiceFile.getOriginalFilename(); String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); if (!extension.equals(".mp3") && !extension.equals(".wav")) { - return new Result().error("只允许上传.mp3和.wav格式的文件"); + return new Result().error("Only .mp3 and .wav files are allowed"); } - // 验证文件大小 (最大10MB) + // Validate file size, capped at 10 MB. if (voiceFile.getSize() > 10 * 1024 * 1024) { return new Result().error(ErrorCode.VOICE_CLONE_AUDIO_TOO_LARGE); } - // 检查权限 + // Validate permissions. checkPermission(id); - // 调用服务层处理 + // Delegate processing to the service layer. voiceCloneService.uploadVoice(id, voiceFile); return new Result(); @@ -106,7 +106,7 @@ public class VoiceCloneController { } @PostMapping("/updateName") - @Operation(summary = "更新声音克隆名称") + @Operation(summary = "Update voice-clone name") @RequiresPermissions("sys:role:normal") public Result updateName(@RequestBody Map params) { try { @@ -119,7 +119,7 @@ public class VoiceCloneController { if (name == null || name.isEmpty()) { return new Result().error(ErrorCode.VOICE_CLONE_NAME_NOT_NULL); } - // 检查权限 + // Validate permissions. checkPermission(id); voiceCloneService.updateName(id, name); @@ -131,10 +131,10 @@ public class VoiceCloneController { } @PostMapping("/audio/{id}") - @Operation(summary = "获取音频下载ID") + @Operation(summary = "Get audio download ID") @RequiresPermissions("sys:role:normal") public Result getAudioId(@PathVariable("id") String id) { - // 检查权限 + // Validate permissions. checkPermission(id); byte[] audioData = voiceCloneService.getVoiceData(id); if (audioData == null) { @@ -146,7 +146,7 @@ public class VoiceCloneController { } @GetMapping("/play/{uuid}") - @Operation(summary = "播放音频") + @Operation(summary = "Play audio") public void playVoice(@PathVariable("uuid") String uuid, HttpServletResponse response) { try { String id = (String) redisUtils.get(RedisKeys.getVoiceCloneAudioIdKey(uuid)); @@ -155,7 +155,7 @@ public class VoiceCloneController { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } - // 获取音频数据 + // Load audio data. byte[] voiceData = voiceCloneService.getVoiceData(id); if (voiceData == null || voiceData.length == 0) { @@ -163,27 +163,27 @@ public class VoiceCloneController { return; } - // 设置响应头 + // Set response headers. response.setContentType("audio/wav"); response.setContentLength(voiceData.length); response.setHeader("Content-Disposition", "inline; filename=voice.wav"); - // 写入音频数据 + // Write audio data to the response stream. response.getOutputStream().write(voiceData); response.getOutputStream().flush(); } catch (Exception e) { - log.error("播放音频失败", e); + log.error("Failed to play audio", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @PostMapping("/cloneAudio") - @Operation(summary = "复刻音频") + @Operation(summary = "Clone audio") @RequiresPermissions("sys:role:normal") public Result cloneAudio(@RequestBody Map params) { String cloneId = params.get("cloneId"); checkPermission(cloneId); - // 调用服务层进行语音克隆训练 + // Delegate voice-clone training to the service layer. voiceCloneService.cloneAudio(cloneId); return new Result(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java index a4cfa4798..8eb9f5783 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java @@ -29,7 +29,7 @@ import xiaozhi.modules.voiceclone.dto.VoiceCloneDTO; import xiaozhi.modules.voiceclone.dto.VoiceCloneResponseDTO; import xiaozhi.modules.voiceclone.service.VoiceCloneService; -@Tag(name = "音色资源管理", description = "音色资源开通相关接口") +@Tag(name = "Voice Resource Management", description = "Endpoints for voice resource provisioning") @Slf4j @RestController @RequiredArgsConstructor @@ -40,10 +40,10 @@ public class VoiceResourceController { private final ModelConfigService modelConfigService; @GetMapping - @Operation(summary = "分页查询音色资源") + @Operation(summary = "List voice resources with pagination") @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) }) @RequiresPermissions("sys:role:superAdmin") public Result> page( @@ -54,7 +54,7 @@ public class VoiceResourceController { } @GetMapping("{id}") - @Operation(summary = "获取音色资源详情") + @Operation(summary = "Get voice resource details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") String id) { VoiceCloneResponseDTO data = voiceCloneService.getByIdWithNames(id); @@ -62,7 +62,7 @@ public class VoiceResourceController { } @PostMapping - @Operation(summary = "新增音色资源") + @Operation(summary = "Create voice resource") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody VoiceCloneDTO dto) { if (dto == null) { @@ -88,7 +88,7 @@ public class VoiceResourceController { } @DeleteMapping("/{id}") - @Operation(summary = "删除音色资源") + @Operation(summary = "Delete voice resource") @RequiresPermissions("sys:role:superAdmin") public Result delete(@PathVariable("id") String[] ids) { if (ids == null || ids.length == 0) { @@ -99,7 +99,7 @@ public class VoiceResourceController { } @GetMapping("/user/{userId}") - @Operation(summary = "根据用户ID获取音色资源列表") + @Operation(summary = "Get voice resources by user ID") @RequiresPermissions("sys:role:normal") public Result> getByUserId(@PathVariable("userId") Long userId) { List list = voiceCloneService.getByUserIdWithNames(userId); @@ -107,7 +107,7 @@ public class VoiceResourceController { } @GetMapping("/ttsPlatforms") - @Operation(summary = "获取TTS平台列表") + @Operation(summary = "Get TTS platform list") @RequiresPermissions("sys:role:superAdmin") public Result>> getTtsPlatformList() { List> list = modelConfigService.getTtsPlatformList(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java index 08e0e0129..18ed4e338 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java @@ -10,16 +10,16 @@ import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; /** - * 声音克隆 + * Voice-clone DAO. */ @Mapper public interface VoiceCloneDao extends BaseMapper { /** - * 获取用户训练成功的音色列表 - * - * @param modelId 模型ID - * @param userId 用户ID - * @return 训练成功的音色列表 + * Get the list of successfully trained voices for a user. + * + * @param modelId model ID + * @param userId user ID + * @return successfully trained voice list */ List getTrainSuccess(String modelId, Long userId); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneDTO.java index 156b381f6..67d83de46 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneDTO.java @@ -6,18 +6,18 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "声音克隆DTO") +@Schema(description = "Voice-clone DTO") public class VoiceCloneDTO { - @Schema(description = "模型ID") + @Schema(description = "Model ID") private String modelId; - @Schema(description = "音色ID列表") + @Schema(description = "Voice ID list") private List voiceIds; - @Schema(description = "用户ID") + @Schema(description = "User ID") private Long userId; - @Schema(description = "语言") + @Schema(description = "Language") private String languages; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneResponseDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneResponseDTO.java index 22dafe04c..e65defdb1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneResponseDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dto/VoiceCloneResponseDTO.java @@ -6,46 +6,46 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** - * 声音克隆响应DTO - * 用于向前端展示声音克隆信息,包含模型名称和用户名称 + * Voice-clone response DTO. + * Used by the frontend to display voice-clone details including model and user names. */ @Data -@Schema(description = "声音克隆响应DTO") +@Schema(description = "Voice-clone response DTO") public class VoiceCloneResponseDTO { - @Schema(description = "唯一标识") + @Schema(description = "Unique ID") private String id; - @Schema(description = "声音名称") + @Schema(description = "Voice name") private String name; - @Schema(description = "模型id") + @Schema(description = "Model ID") private String modelId; - @Schema(description = "模型名称") + @Schema(description = "Model name") private String modelName; - @Schema(description = "声音id") + @Schema(description = "Voice ID") private String voiceId; - @Schema(description = "语言") + @Schema(description = "Language") private String languages; - @Schema(description = "用户ID(关联用户表)") + @Schema(description = "User ID linked to the user table") private Long userId; - @Schema(description = "用户名称") + @Schema(description = "User name") private String userName; - @Schema(description = "训练状态:0待训练 1训练中 2训练成功 3训练失败") + @Schema(description = "Training status: 0 pending, 1 running, 2 success, 3 failed") private Integer trainStatus; - @Schema(description = "训练错误原因") + @Schema(description = "Training error reason") private String trainError; - @Schema(description = "创建时间") + @Schema(description = "Created at") private Date createDate; - @Schema(description = "是否有音频数据") + @Schema(description = "Whether audio data exists") private Boolean hasVoice; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/entity/VoiceCloneEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/entity/VoiceCloneEntity.java index d78b1c9e0..f5ead0c21 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/entity/VoiceCloneEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/entity/VoiceCloneEntity.java @@ -15,42 +15,42 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("ai_voice_clone") -@Schema(description = "声音克隆") +@Schema(description = "Voice clone") public class VoiceCloneEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "唯一标识") + @Schema(description = "Unique ID") private String id; - @Schema(description = "声音名称") + @Schema(description = "Voice name") private String name; - @Schema(description = "模型id") + @Schema(description = "Model ID") private String modelId; - @Schema(description = "声音id") + @Schema(description = "Voice ID") private String voiceId; - @Schema(description = "语言") + @Schema(description = "Language") private String languages; - @Schema(description = "用户 ID(关联用户表)") + @Schema(description = "User ID linked to the user table") private Long userId; - @Schema(description = "声音") + @Schema(description = "Voice audio data") private byte[] voice; - @Schema(description = "训练状态:0待训练 1训练中 2训练成功 3训练失败") + @Schema(description = "Training status: 0 pending, 1 running, 2 success, 3 failed") private Integer trainStatus; - @Schema(description = "训练错误原因") + @Schema(description = "Training error reason") private String trainError; - @Schema(description = "创建者") + @Schema(description = "Created by") @TableField(fill = FieldFill.INSERT) private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Created at") @TableField(fill = FieldFill.INSERT) private Date createDate; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java index ea8fd61d8..83c5193f5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java @@ -12,67 +12,67 @@ import xiaozhi.modules.voiceclone.dto.VoiceCloneResponseDTO; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; /** - * 声音克隆管理 + * Voice-clone management service. */ public interface VoiceCloneService extends BaseService { /** - * 分页查询 + * Query voice-clone records with pagination. */ PageData page(Map params); /** - * 保存声音克隆 + * Save a voice-clone record. */ void save(VoiceCloneDTO dto); /** - * 批量删除 + * Delete records in batch. */ void delete(String[] ids); /** - * 根据用户ID查询声音克隆列表 - * - * @param userId 用户ID - * @return 声音克隆列表 + * Query voice-clone records by user ID. + * + * @param userId user ID + * @return voice-clone list */ List getByUserId(Long userId); /** - * 分页查询带模型名称和用户名称的声音克隆列表 + * Query paginated voice-clone records including model and user names. */ PageData pageWithNames(Map params); /** - * 根据ID查询带模型名称和用户名称的声音克隆信息 + * Query a voice-clone record by ID including model and user names. */ VoiceCloneResponseDTO getByIdWithNames(String id); /** - * 根据用户ID查询带模型名称的声音克隆列表 + * Query a user's voice-clone records including model names. */ List getByUserIdWithNames(Long userId); /** - * 上传音频文件 + * Upload an audio file. */ void uploadVoice(String id, MultipartFile voiceFile) throws Exception; /** - * 更新声音克隆名称 + * Update a voice-clone name. */ void updateName(String id, String name); /** - * 获取音频数据 + * Get audio data. */ byte[] getVoiceData(String id); /** - * 克隆音频,调用火山引擎进行语音复刻训练 - * - * @param cloneId 语音克隆记录ID + * Clone audio and trigger voice training through the upstream provider integration. + * + * @param cloneId voice-clone record ID */ void cloneAudio(String cloneId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java index 456239ab8..0d5a52ec5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java @@ -1,10 +1,11 @@ package xiaozhi.modules.voiceclone.service.impl; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; @@ -14,12 +15,10 @@ import org.springframework.web.multipart.MultipartFile; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; @@ -44,6 +43,8 @@ import xiaozhi.modules.voiceclone.service.VoiceCloneService; public class VoiceCloneServiceImpl extends BaseServiceImpl implements VoiceCloneService { + private static final Set SUPPORTED_VOICE_CLONE_TYPES = Set.of(); + private final ModelConfigService modelConfigService; private final SysUserService sysUserService; private final SysUserDao sysUserDao; @@ -84,15 +85,13 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl wrapper = new QueryWrapper<>(); @@ -104,9 +103,9 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl batchInsertList = new ArrayList<>(); - // 遍历选择的音色ID,为每个音色ID创建一条记录 + // Create one record for each selected voice ID. int index = 0; String namePrefix = DateUtils.format(new Date(), "MMddHHmm"); for (String voiceId : dto.getVoiceIds()) { @@ -117,7 +116,7 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl pageWithNames(Map params) { - // 先查询分页数据 + // Query paginated data first. IPage page = baseDao.selectPage( getPage(params, "create_date", true), getWrapper(params)); - // 将实体列表转换为DTO列表 + // Convert entity records into DTOs. List dtoList = convertToResponseDTOList(page.getRecords()); return new PageData<>(dtoList, page.getTotal()); @@ -160,17 +159,17 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl convertToResponseDTOList(List entityList) { if (entityList == null || entityList.isEmpty()) { @@ -192,29 +191,29 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl dtoList = new ArrayList<>(entityList.size()); - // 获取用户名称ID集合 + // Collect user IDs for username lookup. Set userIdList = entityList.stream().map(VoiceCloneEntity::getUserId).collect(Collectors.toSet()); List userList = sysUserDao.selectList(new QueryWrapper().in("id", userIdList)); Map userMap = userList.stream().collect(Collectors.toMap(SysUserEntity::getId, SysUserEntity::getUsername)); - // 转换每个实体为DTO + // Convert each entity into a DTO. for (VoiceCloneEntity entity : entityList) { VoiceCloneResponseDTO dto = ConvertUtils.sourceToTarget(entity, VoiceCloneResponseDTO.class); - // 设置模型名称 + // Set the model name. if (StringUtils.isNotBlank(entity.getModelId())) { dto.setModelName(modelConfigService.getModelNameById(entity.getModelId())); } - // 设置用户名称 + // Set the username. if (entity.getUserId() != null) { dto.setUserName(userMap.get(entity.getUserId())); } - // 确保trainStatus字段被正确设置,前端需要这个字段来判断是否为克隆音频 + // Preserve trainStatus because the frontend uses it to identify cloned audio. dto.setTrainStatus(entity.getTrainStatus()); - // 设置是否有音频数据 + // Set whether audio data is present. dto.setHasVoice(entity.getVoice() != null); dtoList.add(dto); @@ -226,34 +225,34 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl config = modelConfig.getConfigJson(); String type = (String) config.get("type"); - if (StringUtils.isBlank(type)) { + if (StringUtils.isBlank(type) || !SUPPORTED_VOICE_CLONE_TYPES.contains(type)) { throw new RenException(ErrorCode.VOICE_CLONE_MODEL_TYPE_NOT_FOUND); } - if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(type)) { - huoshanClone(config, entity); - } } catch (RenException re) { entity.setTrainStatus(3); entity.setTrainError(re.getMsg()); @@ -306,85 +302,4 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl config, VoiceCloneEntity entity) throws Exception { - String appid = (String) config.get("appid"); - String accessToken = (String) config.get("access_token"); - - if (StringUtils.isAnyBlank(appid, accessToken)) { - throw new RenException(ErrorCode.VOICE_CLONE_HUOSHAN_CONFIG_MISSING); - } - - String audioBase64 = Base64.getEncoder().encodeToString(entity.getVoice()); - Map reqBody = new HashMap<>(); - reqBody.put("appid", appid); - List> audios = new ArrayList<>(); - Map audioMap = new HashMap<>(); - audioMap.put("audio_bytes", audioBase64); - audioMap.put("audio_format", "wav"); - audios.add(audioMap); - reqBody.put("audios", audios); - reqBody.put("source", 2); - reqBody.put("language", 0); - reqBody.put("model_type", 1); - reqBody.put("speaker_id", entity.getVoiceId()); - - String apiUrl = "https://openspeech.bytedance.com/api/v1/mega_tts/audio/upload"; - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(apiUrl)) - .header("Content-Type", "application/json") - .header("Authorization", "Bearer;" + accessToken) - .header("Resource-Id", "seed-icl-1.0") - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(reqBody))) - .build(); - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - - System.out.println(">>> HTTP status = " + response.statusCode()); - System.out.println(">>> response body = " + response.body()); - - Map rsp = objectMapper.readValue(response.body(), - new TypeReference>() { - }); - - // 获取BaseResp对象 - Map baseResp = objectMapper.convertValue(rsp.get("BaseResp"), - new TypeReference>() { - }); - if (baseResp != null) { - Integer statusCode = objectMapper.convertValue(baseResp.get("StatusCode"), Integer.class); - String statusMessage = objectMapper.convertValue(baseResp.getOrDefault("StatusMessage", ""), - String.class); - - // 获取speaker_id - String speakerId = objectMapper.convertValue(rsp.get("speaker_id"), String.class); - - // StatusCode == 0 表示成功 - if (statusCode != null && statusCode == 0 && StringUtils.isNotBlank(speakerId)) { - entity.setTrainStatus(2); - entity.setVoiceId(speakerId); - entity.setTrainError(""); - baseDao.updateById(entity); - } else { - // 失败时使用StatusMessage作为错误信息 - String errorMsg = StringUtils.isNotBlank(statusMessage) ? statusMessage : "训练失败"; - throw new RenException(errorMsg); - } - } else { - String errorMsg = objectMapper.convertValue(rsp.get("message"), - new TypeReference() { - }); - if (StringUtils.isNotBlank(errorMsg)) { - throw new RenException(errorMsg); - } - throw new RenException(ErrorCode.VOICE_CLONE_RESPONSE_FORMAT_ERROR); - } - } } diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 1c86f288e..52f8d2767 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -38,14 +38,14 @@ spring: multi-statement-allow: true data: redis: - host: 127.0.0.1 # Redis服务器地址 - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - database: 0 # Redis数据库索引(默认为0) - timeout: 10000ms # 连接超时时间(毫秒) + host: 127.0.0.1 # Redis server address + port: 6379 # Redis server connection port + password: # Redis server connection password (empty by default) + database: 0 # Redis database index (0 by default) + timeout: 10000ms # Connection timeout time (milliseconds) lettuce: pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 + max-active: 8 # Maximum connections in connection pool (negative value means no limit) + max-idle: 8 # Maximum idle connections in connection pool + min-idle: 0 # Minimum idle connections in connection pool + shutdown-timeout: 100ms diff --git a/main/manager-api/src/main/resources/application-prod.yml b/main/manager-api/src/main/resources/application-prod.yml new file mode 100644 index 000000000..17e7ba778 --- /dev/null +++ b/main/manager-api/src/main/resources/application-prod.yml @@ -0,0 +1,61 @@ +# Production environment configuration +knife4j: + production: false + enable: true + basic: + enable: false + username: renren + password: 2ZABCDEUgF + setting: + enableFooter: false + +spring: + datasource: + druid: + # MySQL - Production database configuration + driver-class-name: com.mysql.cj.jdbc.Driver + url: ${SPRING_DATASOURCE_DRUID_URL:jdbc:mysql://mysql:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&nullCatalogMeansCurrent=true} + username: ${SPRING_DATASOURCE_DRUID_USERNAME:xiaozhi} + password: ${SPRING_DATASOURCE_DRUID_PASSWORD:xiaozhi123} + initial-size: 20 + max-active: 200 + min-idle: 20 + max-wait: 60000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: false + filter: + stat: + log-slow-sql: true + slow-sql-millis: 2000 + merge-sql: false + wall: + config: + multi-statement-allow: true + data: + redis: + host: ${SPRING_DATA_REDIS_HOST:redis} + port: ${SPRING_DATA_REDIS_PORT:6379} + password: ${SPRING_DATA_REDIS_PASSWORD:} + database: 0 + timeout: 10000ms + lettuce: + pool: + max-active: 20 + max-idle: 20 + min-idle: 5 + shutdown-timeout: 100ms + +# Production logging configuration +logging: + level: + xiaozhi: INFO + org.springframework.web: ERROR + org.springboot.sample: ERROR + root: INFO diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 3daf48a14..cb6ed90b8 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -13,7 +13,7 @@ server: http-only: true spring: - # 环境 dev|test|prod + # Environment dev|test|prod profiles: active: dev messages: @@ -46,15 +46,15 @@ renren: #mybatis mybatis-plus: mapper-locations: classpath*:/mapper/**/*.xml - #实体扫描,多个package用逗号或者分号分隔 + # Entity scanning, multiple packages separated by comma or semicolon typeAliasesPackage: xiaozhi.modules.*.entity global-config: - #数据库相关配置 + # Database related configuration db-config: - #主键类型 + # Primary key type id-type: ASSIGN_ID banner: false - #原生配置 + # Native configuration configuration: map-underscore-to-camel-case: true cache-enabled: false diff --git a/main/manager-api/src/main/resources/db/changelog/202604011130.sql b/main/manager-api/src/main/resources/db/changelog/202604011130.sql new file mode 100644 index 000000000..cacf4caa1 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011130.sql @@ -0,0 +1,114 @@ +-- Remove Chinese-only and downstream-deleted providers from the westernized build. +-- This keeps upstream migration history append-only while preserving downstream behavior. + +DELETE FROM `ai_tts_voice` +WHERE `tts_model_id` IN ( + 'TTS_HuoshanDoubleStreamTTS', + 'TTS_XunFeiStreamTTS', + 'TTS_MinimaxStreamTTS', + 'TTS_AliyunStreamTTS', + 'TTS_DoubaoTTS', + 'TTS_TencentTTS', + 'TTS_AliyunTTS', + 'TTS_CozeCnTTS', + 'TTS_FishSpeech', + 'TTS_VolcesAiGatewayTTS', + 'TTS_LinkeraiTTS' +) +OR `id` IN ( + 'TTS_Kokoro_0033', + 'TTS_Kokoro_0034', + 'TTS_Kokoro_0035', + 'TTS_Kokoro_0036', + 'TTS_Kokoro_0037', + 'TTS_Kokoro_0038', + 'TTS_Kokoro_0039', + 'TTS_Kokoro_0040' +); + +DELETE FROM `ai_model_provider` +WHERE `provider_code` IN ( + 'aliyun', + 'aliyun_stream', + 'aliyunbl_stream', + 'alibl_stream', + 'baidu', + 'coze', + 'cozecn', + 'doubao', + 'doubao_stream', + 'fastgpt', + 'fishspeech', + 'fun_local', + 'fun_server', + 'gpt_sovits_v2', + 'gpt_sovits_v3', + 'huoshan_double_stream', + 'index_stream', + 'linkerai', + 'minimax_httpstream', + 'paddle_speech', + 'qwen3_asr_flash', + 'siliconflow', + 'tencent', + 'ttson', + 'xunfei_stream' +) +OR `id` IN ( + 'SYSTEM_TTS_HSDSTTS', + 'SYSTEM_TTS_cozecn' +); + +DELETE FROM `ai_model_config` +WHERE `id` IN ( + 'LLM_AliAppLLM', + 'LLM_DoubaoLLM', + 'LLM_XunfeiSparkLLM', + 'ASR_AliyunASR', + 'ASR_AliyunBLStream', + 'ASR_AliyunStreamASR', + 'ASR_BaiduASR', + 'ASR_DoubaoASR', + 'ASR_DoubaoStreamASR', + 'ASR_Qwen3Flash', + 'ASR_TencentASR', + 'ASR_XunfeiStream', + 'TTS_AliyunStreamTTS', + 'TTS_AliyunTTS', + 'TTS_CozeCnTTS', + 'TTS_DoubaoTTS', + 'TTS_FishSpeech', + 'TTS_HuoshanDoubleStreamTTS', + 'TTS_LinkeraiTTS', + 'TTS_MinimaxStreamTTS', + 'TTS_TencentTTS', + 'TTS_VolcesAiGatewayTTS', + 'TTS_XunFeiStreamTTS' +) +OR JSON_UNQUOTE(JSON_EXTRACT(`config_json`, '$.type')) IN ( + 'aliyun', + 'aliyun_stream', + 'aliyunbl_stream', + 'alibl_stream', + 'baidu', + 'coze', + 'cozecn', + 'doubao', + 'doubao_stream', + 'fastgpt', + 'fishspeech', + 'fun_local', + 'fun_server', + 'gpt_sovits_v2', + 'gpt_sovits_v3', + 'huoshan_double_stream', + 'index_stream', + 'linkerai', + 'minimax_httpstream', + 'paddle_speech', + 'qwen3_asr_flash', + 'siliconflow', + 'tencent', + 'ttson', + 'xunfei_stream' +); diff --git a/main/manager-api/src/main/resources/db/changelog/202604011330.sql b/main/manager-api/src/main/resources/db/changelog/202604011330.sql new file mode 100644 index 000000000..85e49cc45 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011330.sql @@ -0,0 +1,66 @@ +-- Align seeded database defaults with the downstream westernization policy. +-- Keep upstream changelog history append-only while removing seeded +-- Chinese-facing defaults that can still surface in the admin UI. + +-- Replace seeded Chinese EdgeTTS voices with a compact English-first set. +DELETE FROM `ai_tts_voice` +WHERE `tts_model_id` = 'TTS_EdgeTTS' + AND ( + `tts_voice` LIKE 'zh-CN-%' + OR `tts_voice` LIKE 'zh-HK-%' + ); + +DELETE FROM `ai_tts_voice` +WHERE `id` IN ( + 'TTS_EdgeTTS_EN001', + 'TTS_EdgeTTS_EN002', + 'TTS_EdgeTTS_EN003' +); + +INSERT INTO `ai_tts_voice` VALUES +('TTS_EdgeTTS_EN001', 'TTS_EdgeTTS', 'Aria', 'en-US-AriaNeural', 'English (US)', NULL, 'Default downstream Edge voice', NULL, NULL, 1, NULL, NULL, NULL, NULL), +('TTS_EdgeTTS_EN002', 'TTS_EdgeTTS', 'Guy', 'en-US-GuyNeural', 'English (US)', NULL, 'Alternative downstream Edge voice', NULL, NULL, 2, NULL, NULL, NULL, NULL), +('TTS_EdgeTTS_EN003', 'TTS_EdgeTTS', 'Sonia', 'en-GB-SoniaNeural', 'English (UK)', NULL, 'Alternative downstream Edge voice', NULL, NULL, 3, NULL, NULL, NULL, NULL); + +UPDATE `ai_model_config` +SET + `model_name` = 'Edge TTS', + `config_json` = JSON_SET(`config_json`, '$.voice', 'en-US-AriaNeural'), + `remark` = 'Microsoft Edge TTS. Use a supported Edge voice such as en-US-AriaNeural and keep generated audio in tmp/.' +WHERE `id` = 'TTS_EdgeTTS'; + +-- Restore downstream English names for memory models after upstream relabeling. +UPDATE `ai_model_config` +SET + `model_name` = 'Local short-term memory', + `remark` = 'Summarizes short-term conversational memory locally.' +WHERE `id` = 'Memory_mem_local_short'; + +UPDATE `ai_model_provider` +SET `name` = 'Local short-term memory' +WHERE `id` = 'SYSTEM_Memory_mem_local_short'; + +UPDATE `ai_model_config` +SET + `model_name` = 'Report-only memory', + `remark` = 'Uploads chat records without generating memory summaries.' +WHERE `id` = 'Memory_mem_report_only'; + +UPDATE `ai_model_provider` +SET `name` = 'Report-only memory' +WHERE `id` = 'SYSTEM_Memory_mem_report_only'; + +-- Replace Chinese wakeword defaults with downstream English-first examples. +UPDATE `sys_params` +SET `param_value` = 'hello assistant;hey assistant;hey computer;jarvis;alexa' +WHERE `param_code` = 'wakeup_words'; + +-- Remove the original seeded Chinese agent templates from downstream defaults. +DELETE FROM `ai_agent_template` +WHERE `id` IN ( + '9406648b5cc5fde1b8aa335b6f8b4f76', + '0ca32eb728c949e58b1000b2e401f90c', + '6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24', + 'e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1', + 'a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92' +); diff --git a/main/manager-api/src/main/resources/db/changelog/202604011430.sql b/main/manager-api/src/main/resources/db/changelog/202604011430.sql new file mode 100644 index 000000000..113e52302 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011430.sql @@ -0,0 +1,401 @@ +-- Bridge the remaining gap between the downstream append-only strategy +-- and the broader English-first seed coverage from origin/main. +-- Keep downstream-deleted providers deleted while normalizing the +-- surviving seeded defaults, dictionaries, plugin metadata, and +-- built-in templates. + +-- Keep Sherpa removed downstream because the runtime integration was deleted. +DELETE FROM `ai_model_provider` +WHERE `id` = 'SYSTEM_ASR_SherpaASR'; + +DELETE FROM `ai_model_config` +WHERE `id` = 'ASR_SherpaASR'; + +-- Replace the remaining Chinese-facing seeded parameter values and remarks. +UPDATE `sys_params` SET `remark` = 'System name' WHERE `param_code` = 'server.name'; +UPDATE `sys_params` SET `remark` = 'ICP filing number, set to null to disable' WHERE `param_code` = 'server.beian_icp_num'; +UPDATE `sys_params` SET `remark` = 'Public security filing number, set to null to disable' WHERE `param_code` = 'server.beian_ga_num'; +UPDATE `sys_params` SET `remark` = 'Whether to enable mobile phone registration' WHERE `param_code` = 'server.enable_mobile_register'; +UPDATE `sys_params` SET `remark` = 'Maximum SMS messages per phone number per day' WHERE `param_code` = 'server.sms_max_send_count'; +UPDATE `sys_params` SET `remark` = 'Alibaba Cloud Access Key ID for SMS service' WHERE `param_code` = 'aliyun.sms.access_key_id'; +UPDATE `sys_params` SET `remark` = 'Alibaba Cloud Access Key Secret for SMS service' WHERE `param_code` = 'aliyun.sms.access_key_secret'; +UPDATE `sys_params` SET `remark` = 'Alibaba Cloud SMS sign name' WHERE `param_code` = 'aliyun.sms.sign_name'; +UPDATE `sys_params` SET `remark` = 'Alibaba Cloud SMS template code' WHERE `param_code` = 'aliyun.sms.sms_code_template_code'; +UPDATE `sys_params` SET `param_value` = 'exit;close', `remark` = 'Exit command list' WHERE `param_code` = 'exit_commands'; +UPDATE `sys_params` SET `remark` = 'Whether to enable end notification sound' WHERE `param_code` = 'enable_stop_tts_notify'; +UPDATE `sys_params` SET `remark` = 'End notification sound file path' WHERE `param_code` = 'stop_tts_notify_voice'; +UPDATE `sys_params` SET `remark` = 'Xiaozhi type' WHERE `param_code` = 'xiaozhi'; +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 400, 'plugins.get_weather.api_key', 'your_openweathermap_api_key', 'string', 1, 'Weather plugin API key', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.get_weather.api_key'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 401, 'plugins.get_weather.default_location', 'New York', 'string', 1, 'Weather plugin default location', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.get_weather.default_location'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 402, 'plugins.get_weather.api_host', 'api.openweathermap.org', 'string', 1, 'Weather plugin API host', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.get_weather.api_host'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 410, 'plugins.get_news.default_rss_url', 'https://feeds.reuters.com/reuters/worldNews', 'string', 1, 'News plugin fallback RSS URL', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.get_news.default_rss_url'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 411, 'plugins.get_news.category_urls', '{"world":"https://feeds.reuters.com/reuters/worldNews","technology":"https://feeds.feedburner.com/TechCrunch/","business":"https://feeds.marketwatch.com/marketwatch/topstories/"}', 'json', 1, 'News plugin category RSS URLs', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.get_news.category_urls'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 421, 'plugins.home_assistant.devices', 'Living Room,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1;Bedroom,Table Lamp,switch.iot_cn_831898993_socn1_on_p_2_1', 'array', 1, 'Home Assistant device list', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.home_assistant.devices'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 422, 'plugins.home_assistant.base_url', 'http://homeassistant.local:8123', 'string', 1, 'Home Assistant server address', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.home_assistant.base_url'); +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 423, 'plugins.home_assistant.api_key', 'your home assistant api access token', 'string', 1, 'Home Assistant API key', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'plugins.home_assistant.api_key'); +UPDATE `sys_params` SET `param_value` = 'New York', `remark` = 'Weather plugin default location' WHERE `param_code` = 'plugins.get_weather.default_location'; +UPDATE `sys_params` SET `remark` = 'Weather plugin API key' WHERE `param_code` = 'plugins.get_weather.api_key'; +UPDATE `sys_params` SET `remark` = 'Weather plugin API host' WHERE `param_code` = 'plugins.get_weather.api_host'; +UPDATE `sys_params` +SET `param_value` = 'https://feeds.reuters.com/reuters/worldNews', + `remark` = 'News plugin fallback RSS URL' +WHERE `param_code` = 'plugins.get_news.default_rss_url'; +UPDATE `sys_params` +SET `param_value` = '{"world":"https://feeds.reuters.com/reuters/worldNews","technology":"https://feeds.feedburner.com/TechCrunch/","business":"https://feeds.marketwatch.com/marketwatch/topstories/"}', + `remark` = 'News plugin category RSS URLs' +WHERE `param_code` = 'plugins.get_news.category_urls'; +UPDATE `sys_params` +SET `param_value` = 'Living Room,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1;Bedroom,Table Lamp,switch.iot_cn_831898993_socn1_on_p_2_1', + `remark` = 'Home Assistant device list' +WHERE `param_code` = 'plugins.home_assistant.devices'; +UPDATE `sys_params` SET `remark` = 'Home Assistant server address' WHERE `param_code` = 'plugins.home_assistant.base_url'; +UPDATE `sys_params` +SET `param_value` = 'your home assistant api access token', + `remark` = 'Home Assistant API key' +WHERE `param_code` = 'plugins.home_assistant.api_key'; +UPDATE `sys_params` +SET `param_value` = 'Please start with "Time flies so fast" and end this conversation with emotional and reluctant words!', + `remark` = 'End prompt' +WHERE `param_code` = 'end_prompt.prompt'; +UPDATE `sys_params` +SET `param_value` = 'The assistant is temporarily busy right now. Please try again in a moment.', + `remark` = 'Reply when a system error occurs' +WHERE `param_code` = 'system_error_response'; + +-- Normalize dictionary labels that still surface in the admin UI. +UPDATE `sys_dict_type` +SET `dict_name` = 'Firmware Type', + `remark` = 'Firmware type dictionary' +WHERE `id` = 101; + +UPDATE `sys_dict_type` +SET `dict_name` = 'Mobile Area', + `remark` = 'Mobile area dictionary' +WHERE `id` = 102; + +UPDATE `sys_dict_data` SET `dict_label` = 'Breadboard New Wiring (WiFi)', `remark` = 'Breadboard New Wiring (WiFi)' WHERE `id` = 101001; +UPDATE `sys_dict_data` SET `dict_label` = 'Breadboard New Wiring (WiFi) + LCD', `remark` = 'Breadboard New Wiring (WiFi) + LCD' WHERE `id` = 101002; +UPDATE `sys_dict_data` SET `dict_label` = 'Breadboard New Wiring (ML307 AT)', `remark` = 'Breadboard New Wiring (ML307 AT)' WHERE `id` = 101003; +UPDATE `sys_dict_data` SET `dict_label` = 'Breadboard (WiFi) ESP32 DevKit', `remark` = 'Breadboard (WiFi) ESP32 DevKit' WHERE `id` = 101004; +UPDATE `sys_dict_data` SET `dict_label` = 'Breadboard (WiFi+ LCD) ESP32 DevKit', `remark` = 'Breadboard (WiFi+ LCD) ESP32 DevKit' WHERE `id` = 101005; +UPDATE `sys_dict_data` SET `dict_label` = 'DFRobot Xingkong Board k10', `remark` = 'DFRobot Xingkong Board k10' WHERE `id` = 101006; +UPDATE `sys_dict_data` SET `dict_label` = 'Kevin SP V3 Development Board', `remark` = 'Kevin SP V3 Development Board' WHERE `id` = 101014; +UPDATE `sys_dict_data` SET `dict_label` = 'Kevin SP V4 Development Board', `remark` = 'Kevin SP V4 Development Board' WHERE `id` = 101015; +UPDATE `sys_dict_data` SET `dict_label` = 'Yu Ying Technology 3.13LCD Development Board', `remark` = 'Yu Ying Technology 3.13LCD Development Board' WHERE `id` = 101016; +UPDATE `sys_dict_data` SET `dict_label` = 'LCSC Practical ESP32-S3 Development Board', `remark` = 'LCSC Practical ESP32-S3 Development Board' WHERE `id` = 101017; +UPDATE `sys_dict_data` SET `dict_label` = 'LCSC Practical ESP32-C3 Development Board', `remark` = 'LCSC Practical ESP32-C3 Development Board' WHERE `id` = 101018; +UPDATE `sys_dict_data` SET `dict_label` = 'Magic Button Magiclick_2.4', `remark` = 'Magic Button Magiclick_2.4' WHERE `id` = 101019; +UPDATE `sys_dict_data` SET `dict_label` = 'Magic Button Magiclick_2.5', `remark` = 'Magic Button Magiclick_2.5' WHERE `id` = 101020; +UPDATE `sys_dict_data` SET `dict_label` = 'Magic Button Magiclick_C3', `remark` = 'Magic Button Magiclick_C3' WHERE `id` = 101021; +UPDATE `sys_dict_data` SET `dict_label` = 'Magic Button Magiclick_C3_v2', `remark` = 'Magic Button Magiclick_C3_v2' WHERE `id` = 101022; +UPDATE `sys_dict_data` SET `dict_label` = 'Xia Ge Mini C3', `remark` = 'Xia Ge Mini C3' WHERE `id` = 101028; +UPDATE `sys_dict_data` SET `dict_label` = 'ESP32S3_KORVO2_V3 Development Board', `remark` = 'ESP32S3_KORVO2_V3 Development Board' WHERE `id` = 101029; +UPDATE `sys_dict_data` SET `dict_label` = 'ESP-SparkBot Development Board', `remark` = 'ESP-SparkBot Development Board' WHERE `id` = 101030; +UPDATE `sys_dict_data` SET `dict_label` = 'Tudouzi', `remark` = 'Tudouzi' WHERE `id` = 101037; +UPDATE `sys_dict_data` SET `dict_label` = 'Movecall Moji Xiaozhi AI Derivative', `remark` = 'Movecall Moji Xiaozhi AI Derivative' WHERE `id` = 101040; +UPDATE `sys_dict_data` SET `dict_label` = 'Movecall CuiCan Brilliant AI Pendant', `remark` = 'Movecall CuiCan Brilliant AI Pendant' WHERE `id` = 101041; +UPDATE `sys_dict_data` SET `dict_label` = 'Zhengdian Atom DNESP32S3 Development Board', `remark` = 'Zhengdian Atom DNESP32S3 Development Board' WHERE `id` = 101042; +UPDATE `sys_dict_data` SET `dict_label` = 'Zhengdian Atom DNESP32S3-BOX', `remark` = 'Zhengdian Atom DNESP32S3-BOX' WHERE `id` = 101043; +UPDATE `sys_dict_data` SET `dict_label` = 'Dudu Development Board CHATX (WiFi)', `remark` = 'Dudu Development Board CHATX (WiFi)' WHERE `id` = 101044; +UPDATE `sys_dict_data` SET `dict_label` = 'Taiji Xiaopai ESP32S3', `remark` = 'Taiji Xiaopai ESP32S3' WHERE `id` = 101045; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 0.85 (WiFi)', `remark` = 'Wuming Technology Xingzhi 0.85 (WiFi)' WHERE `id` = 101046; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 0.85 (ML307)', `remark` = 'Wuming Technology Xingzhi 0.85 (ML307)' WHERE `id` = 101047; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 0.96 (WiFi)', `remark` = 'Wuming Technology Xingzhi 0.96 (WiFi)' WHERE `id` = 101048; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 0.96 (ML307)', `remark` = 'Wuming Technology Xingzhi 0.96 (ML307)' WHERE `id` = 101049; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 1.54 (WiFi)', `remark` = 'Wuming Technology Xingzhi 1.54 (WiFi)' WHERE `id` = 101050; +UPDATE `sys_dict_data` SET `dict_label` = 'Wuming Technology Xingzhi 1.54 (ML307)', `remark` = 'Wuming Technology Xingzhi 1.54 (ML307)' WHERE `id` = 101051; +UPDATE `sys_dict_data` SET `dict_label` = 'Sibo Zhilian AI Companion Box', `remark` = 'Sibo Zhilian AI Companion Box' WHERE `id` = 101053; +UPDATE `sys_dict_data` SET `dict_label` = 'Yuan Kong Youth', `remark` = 'Yuan Kong Youth' WHERE `id` = 101054; + +UPDATE `sys_dict_data` SET `dict_label` = 'Mainland China', `remark` = 'Mainland China' WHERE `id` = 102001; +UPDATE `sys_dict_data` SET `dict_label` = 'Hong Kong, China', `remark` = 'Hong Kong, China' WHERE `id` = 102002; +UPDATE `sys_dict_data` SET `dict_label` = 'Macau, China', `remark` = 'Macau, China' WHERE `id` = 102003; +UPDATE `sys_dict_data` SET `dict_label` = 'Taiwan, China', `remark` = 'Taiwan, China' WHERE `id` = 102004; +UPDATE `sys_dict_data` SET `dict_label` = 'USA/Canada', `remark` = 'USA/Canada' WHERE `id` = 102005; +UPDATE `sys_dict_data` SET `dict_label` = 'United Kingdom', `remark` = 'United Kingdom' WHERE `id` = 102006; +UPDATE `sys_dict_data` SET `dict_label` = 'France', `remark` = 'France' WHERE `id` = 102007; +UPDATE `sys_dict_data` SET `dict_label` = 'Italy', `remark` = 'Italy' WHERE `id` = 102008; +UPDATE `sys_dict_data` SET `dict_label` = 'Germany', `remark` = 'Germany' WHERE `id` = 102009; +UPDATE `sys_dict_data` SET `dict_label` = 'Poland', `remark` = 'Poland' WHERE `id` = 102010; +UPDATE `sys_dict_data` SET `dict_label` = 'Switzerland', `remark` = 'Switzerland' WHERE `id` = 102011; +UPDATE `sys_dict_data` SET `dict_label` = 'Spain', `remark` = 'Spain' WHERE `id` = 102012; +UPDATE `sys_dict_data` SET `dict_label` = 'Denmark', `remark` = 'Denmark' WHERE `id` = 102013; +UPDATE `sys_dict_data` SET `dict_label` = 'Malaysia', `remark` = 'Malaysia' WHERE `id` = 102014; +UPDATE `sys_dict_data` SET `dict_label` = 'Australia', `remark` = 'Australia' WHERE `id` = 102015; +UPDATE `sys_dict_data` SET `dict_label` = 'Indonesia', `remark` = 'Indonesia' WHERE `id` = 102016; +UPDATE `sys_dict_data` SET `dict_label` = 'Philippines', `remark` = 'Philippines' WHERE `id` = 102017; +UPDATE `sys_dict_data` SET `dict_label` = 'New Zealand', `remark` = 'New Zealand' WHERE `id` = 102018; +UPDATE `sys_dict_data` SET `dict_label` = 'Singapore', `remark` = 'Singapore' WHERE `id` = 102019; +UPDATE `sys_dict_data` SET `dict_label` = 'Thailand', `remark` = 'Thailand' WHERE `id` = 102020; +UPDATE `sys_dict_data` SET `dict_label` = 'Japan', `remark` = 'Japan' WHERE `id` = 102021; +UPDATE `sys_dict_data` SET `dict_label` = 'South Korea', `remark` = 'South Korea' WHERE `id` = 102022; +UPDATE `sys_dict_data` SET `dict_label` = 'Vietnam', `remark` = 'Vietnam' WHERE `id` = 102023; +UPDATE `sys_dict_data` SET `dict_label` = 'India', `remark` = 'India' WHERE `id` = 102024; +UPDATE `sys_dict_data` SET `dict_label` = 'Pakistan', `remark` = 'Pakistan' WHERE `id` = 102025; +UPDATE `sys_dict_data` SET `dict_label` = 'Nigeria', `remark` = 'Nigeria' WHERE `id` = 102026; +UPDATE `sys_dict_data` SET `dict_label` = 'Bangladesh', `remark` = 'Bangladesh' WHERE `id` = 102027; +UPDATE `sys_dict_data` SET `dict_label` = 'Saudi Arabia', `remark` = 'Saudi Arabia' WHERE `id` = 102028; +UPDATE `sys_dict_data` SET `dict_label` = 'United Arab Emirates', `remark` = 'United Arab Emirates' WHERE `id` = 102029; +UPDATE `sys_dict_data` SET `dict_label` = 'Brazil', `remark` = 'Brazil' WHERE `id` = 102030; +UPDATE `sys_dict_data` SET `dict_label` = 'Mexico', `remark` = 'Mexico' WHERE `id` = 102031; +UPDATE `sys_dict_data` SET `dict_label` = 'Chile', `remark` = 'Chile' WHERE `id` = 102032; +UPDATE `sys_dict_data` SET `dict_label` = 'Argentina', `remark` = 'Argentina' WHERE `id` = 102033; +UPDATE `sys_dict_data` SET `dict_label` = 'Egypt', `remark` = 'Egypt' WHERE `id` = 102034; +UPDATE `sys_dict_data` SET `dict_label` = 'South Africa', `remark` = 'South Africa' WHERE `id` = 102035; +UPDATE `sys_dict_data` SET `dict_label` = 'Kenya', `remark` = 'Kenya' WHERE `id` = 102036; +UPDATE `sys_dict_data` SET `dict_label` = 'Tanzania', `remark` = 'Tanzania' WHERE `id` = 102037; +UPDATE `sys_dict_data` SET `dict_label` = 'Kazakhstan', `remark` = 'Kazakhstan' WHERE `id` = 102038; + +-- Replace plugin metadata with the downstream-approved English set. +DELETE FROM `ai_model_provider` +WHERE `id` IN ( + 'SYSTEM_PLUGIN_WEATHER', + 'SYSTEM_PLUGIN_MUSIC', + 'SYSTEM_PLUGIN_NEWS', + 'SYSTEM_PLUGIN_NEWS_CHINANEWS', + 'SYSTEM_PLUGIN_NEWS_NEWSNOW', + 'SYSTEM_PLUGIN_HA_GET_STATE', + 'SYSTEM_PLUGIN_HA_SET_STATE', + 'SYSTEM_PLUGIN_HA_PLAY_MUSIC' +); + +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_PLUGIN_WEATHER', 'Plugin', 'get_weather', 'Weather Service', '[{"key": "api_key", "type": "string", "label": "OpenWeatherMap API Key", "default": "your_openweathermap_api_key", "description": "Get your free API key at https://openweathermap.org/api. Free tier: 1000 calls/day."}, {"key": "default_location", "type": "string", "label": "Default Location", "default": "New York", "description": "Default location when no location is specified by user."}]', 10, 0, NOW(), 0, NOW()), +('SYSTEM_PLUGIN_MUSIC', 'Plugin', 'play_music', 'Server Music Playback', '[]', 20, 0, NOW(), 0, NOW()), +('SYSTEM_PLUGIN_NEWS', 'Plugin', 'get_news', 'News Service', '[{"key": "default_rss_url", "type": "string", "label": "Default RSS URL (Fallback)", "default": "https://feeds.reuters.com/reuters/worldNews", "description": "Fallback RSS URL when built-in sources fail. Built-in sources include Reuters, CNN, BBC, Guardian, TechCrunch and more."}]', 31, 1, NOW(), 1, NOW()), +('SYSTEM_PLUGIN_HA_GET_STATE', 'Plugin', 'hass_get_state', 'HomeAssistant Device Status Query', '[{"key": "base_url", "type": "string", "label": "HA Server Address", "default": "http://homeassistant.local:8123"}, {"key": "api_key", "type": "string", "label": "HA API Access Token", "default": "your home assistant api access token"}, {"key": "devices", "type": "array", "label": "Device List (Name,Entity ID;...)", "default": "Living Room,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1;Bedroom,Table Lamp,switch.iot_cn_831898993_socn1_on_p_2_1"}]', 50, 0, NOW(), 0, NOW()), +('SYSTEM_PLUGIN_HA_SET_STATE', 'Plugin', 'hass_set_state', 'HomeAssistant Device Status Modification', '[]', 60, 0, NOW(), 0, NOW()), +('SYSTEM_PLUGIN_HA_PLAY_MUSIC', 'Plugin', 'hass_play_music', 'HomeAssistant Music Playback', '[]', 70, 0, NOW(), 0, NOW()); + +-- Normalize surviving provider metadata to the English-first downstream surface. +UPDATE `ai_model_provider` +SET `name` = 'OpenAI Speech Recognition', + `fields` = '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]' +WHERE `id` = 'SYSTEM_ASR_OpenaiASR'; + +UPDATE `ai_model_provider` +SET `name` = 'VOSK Offline Speech Recognition', + `fields` = '[{"key": "model_path", "type": "string", "label": "Model Path", "default": "models/vosk/vosk-model-en-us-0.22"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]' +WHERE `id` = 'SYSTEM_ASR_VoskASR'; + +UPDATE `ai_model_provider` +SET `name` = 'Function Call Intent Recognition', + `fields` = '[]' +WHERE `id` = 'SYSTEM_Intent_function_call'; + +UPDATE `ai_model_provider` +SET `name` = 'LLM Intent Recognition', + `fields` = '[{"key": "llm", "type": "string", "label": "LLM Model"}]' +WHERE `id` = 'SYSTEM_Intent_intent_llm'; + +UPDATE `ai_model_provider` +SET `name` = 'No Intent Recognition', + `fields` = '[]' +WHERE `id` = 'SYSTEM_Intent_nointent'; + +UPDATE `ai_model_provider` +SET `name` = 'OpenAI Interface', + `fields` = '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "temperature", "type": "number", "label": "Temperature"}, {"key": "max_tokens", "type": "number", "label": "Max Tokens"}, {"key": "top_p", "type": "number", "label": "Top P Value"}, {"key": "top_k", "type": "number", "label": "Top K Value"}, {"key": "frequency_penalty", "type": "number", "label": "Frequency Penalty"}]' +WHERE `id` = 'SYSTEM_LLM_openai'; + +UPDATE `ai_model_provider` +SET `name` = 'Gemini Interface', + `fields` = '[{"key": "api_key", "type": "string", "label": "API Key"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "http_proxy", "type": "string", "label": "HTTP Proxy"}, {"key": "https_proxy", "type": "string", "label": "HTTPS Proxy"}]' +WHERE `id` = 'SYSTEM_LLM_gemini'; + +UPDATE `ai_model_provider` +SET `name` = 'Ollama Interface', + `fields` = '[{"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "base_url", "type": "string", "label": "Service Address"}]' +WHERE `id` = 'SYSTEM_LLM_ollama'; + +UPDATE `ai_model_provider` +SET `name` = 'Xinference Interface', + `fields` = '[{"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "base_url", "type": "string", "label": "Service Address"}]' +WHERE `id` = 'SYSTEM_LLM_xinference'; + +UPDATE `ai_model_provider` +SET `name` = 'Alibaba Bailian Interface', + `fields` = '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "app_id", "type": "string", "label": "Application ID"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "is_no_prompt", "type": "boolean", "label": "Disable Local Prompt"}, {"key": "ali_memory_id", "type": "string", "label": "Memory ID"}]' +WHERE `id` = 'SYSTEM_LLM_AliBL'; + +UPDATE `ai_model_provider` +SET `name` = 'Dify Interface', + `fields` = '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "mode", "type": "string", "label": "Conversation Mode"}]' +WHERE `id` = 'SYSTEM_LLM_dify'; + +UPDATE `ai_model_provider` +SET `name` = 'Mem0AI Memory', + `fields` = '[{"key": "api_key", "type": "string", "label": "API Key"}]' +WHERE `id` = 'SYSTEM_Memory_mem0ai'; + +UPDATE `ai_model_provider` +SET `name` = 'PowerMem Memory', + `fields` = '[{"key":"enable_user_profile","label":"Enable User Profile","type":"boolean"},{"key":"llm_provider","label":"LLM Provider","type":"string"},{"key":"llm_api_key","label":"LLM API Key","type":"string"},{"key":"llm_model","label":"LLM Model","type":"string"},{"key":"openai_base_url","label":"OpenAI Base URL","type":"string"},{"key":"embedding_provider","label":"Embedding Provider","type":"string"},{"key":"embedding_api_key","label":"Embedding API Key","type":"string"},{"key":"embedding_model","label":"Embedding Model","type":"string"},{"key":"embedding_openai_base_url","label":"Embedding OpenAI Base URL","type":"string"},{"key":"embedding_dims","label":"Embedding Dimensions","type":"integer"},{"key":"vector_store","label":"Vector Store Configuration (JSON)","type":"dict"}]' +WHERE `id` = 'SYSTEM_Memory_powermem'; + +UPDATE `ai_model_provider` +SET `name` = 'No Memory', + `fields` = '[]' +WHERE `id` = 'SYSTEM_Memory_nomem'; + +UPDATE `ai_model_provider` +SET `fields` = '[{"key":"llm","label":"LLM Model","type":"string"}]' +WHERE `id` = 'SYSTEM_Memory_mem_local_short'; + +UPDATE `ai_model_provider` +SET `name` = 'RAGFlow', + `fields` = '[{"key": "base_url", "type": "string", "label": "Service Address"}, {"key": "api_key", "type": "string", "label": "API Key"}]' +WHERE `id` = 'SYSTEM_RAG_ragflow'; + +UPDATE `ai_model_provider` +SET `name` = 'Custom TTS', + `fields` = '[{"key":"url","label":"Service Address","type":"string"},{"key":"method","label":"Request Method","type":"string"},{"key":"params","label":"Request Parameters","type":"dict","dict_name":"params"},{"key":"headers","label":"Request Headers","type":"dict","dict_name":"headers"},{"key":"format","label":"Audio Format","type":"string"},{"key":"output_dir","label":"Output Directory","type":"string"}]' +WHERE `id` = 'SYSTEM_TTS_custom'; + +UPDATE `ai_model_provider` +SET `name` = 'Edge TTS', + `fields` = '[{"key": "voice", "type": "string", "label": "Voice"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]' +WHERE `id` = 'SYSTEM_TTS_edge'; + +UPDATE `ai_model_provider` +SET `name` = 'OpenAI TTS', + `fields` = '[{"key": "api_key", "type": "string", "label": "API Key"}, {"key": "api_url", "type": "string", "label": "API URL"}, {"key": "model", "type": "string", "label": "Model"}, {"key": "voice", "type": "string", "label": "Voice"}, {"key": "speed", "type": "number", "label": "Speed"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]' +WHERE `id` = 'SYSTEM_TTS_openai'; + +UPDATE `ai_model_provider` +SET `name` = 'SileroVAD Voice Activity Detection', + `fields` = '[{"key": "threshold", "type": "number", "label": "Detection Threshold"}, {"key": "model_dir", "type": "string", "label": "Model Directory"}, {"key": "min_silence_duration_ms", "type": "number", "label": "Minimum Silence Duration"}]' +WHERE `id` = 'SYSTEM_VAD_SileroVAD'; + +UPDATE `ai_model_provider` +SET `name` = 'OpenAI Interface', + `fields` = '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "api_key", "type": "string", "label": "API Key"}]' +WHERE `id` = 'SYSTEM_VLLM_openai'; + +-- Normalize the surviving model configuration rows users can still select. +UPDATE `ai_model_config` +SET `model_name` = 'OpenAI Speech Recognition', + `remark` = 'OpenAI ASR Configuration Instructions:\n1. Need to create organization and get api_key on OpenAI platform\n2. Supports multiple languages including English, Japanese, Korean and other speech recognition, see documentation https://platform.openai.com/docs/guides/speech-to-text\n3. Requires network connection\n4. Output files saved in tmp/ directory\nApplication Steps:\n1. Login to OpenAI Platform: https://auth.openai.com/log-in\n2. Create api-key: https://platform.openai.com/settings/organization/api-keys\n3. Models can choose gpt-4o-transcribe or GPT-4o mini Transcribe' +WHERE `id` = 'ASR_OpenaiASR'; + +UPDATE `ai_model_config` +SET `model_name` = 'VOSK Offline Speech Recognition', + `remark` = 'VOSK ASR Configuration Instructions:\n1. VOSK is an offline speech recognition library supporting multiple languages\n2. Need to download model files first: https://alphacephei.com/vosk/models\n3. For English models, recommend using vosk-model-en-us-0.22 or vosk-model-small-en-us-0.15\n4. Completely offline operation, no network connection required\n5. Output files saved in tmp/ directory\nUsage Steps:\n1. Visit https://alphacephei.com/vosk/models to download English models\n2. Extract model files to models/vosk/ folder in project directory\n3. Specify correct model path in configuration\n4. Note: VOSK English models provide good accuracy for English speech recognition' +WHERE `id` = 'ASR_VoskASR'; + +UPDATE `ai_model_config` +SET `model_name` = 'Function Call Intent Recognition', + `remark` = 'Function Call Intent Recognition Configuration Instructions:\n1. Uses LLM function_call capability for intent recognition\n2. Requires the selected LLM to support function_call\n3. Calls tools on demand, fast processing speed' +WHERE `id` = 'Intent_function_call'; + +UPDATE `ai_model_config` +SET `model_name` = 'LLM Intent Recognition', + `config_json` = '{"type": "intent_llm", "llm": "LLM_OpenAILLM"}', + `remark` = 'LLM Intent Recognition Configuration Instructions:\n1. Uses independent LLM for intent recognition\n2. By default uses selected_module.LLM model\n3. Can configure to use independent LLM (such as OpenAI LLM)\n4. Strong generalization but increases processing time\nConfiguration Instructions:\n1. Specify the LLM model to use in the llm field\n2. If not specified, uses selected_module.LLM model' +WHERE `id` = 'Intent_intent_llm'; + +UPDATE `ai_model_config` +SET `model_name` = 'No Intent Recognition', + `remark` = 'No Intent Recognition Configuration Instructions:\n1. No intent recognition performed\n2. All conversations directly passed to LLM for processing\n3. No additional configuration required\n4. Suitable for simple conversation scenarios' +WHERE `id` = 'Intent_nointent'; + +UPDATE `ai_model_config` +SET `model_name` = 'OpenAI GPT', + `remark` = 'OpenAI Configuration Instructions:\n1. Visit https://platform.openai.com/api-keys\n2. Get API Key\n3. Fill in configuration file' +WHERE `id` = 'LLM_OpenAILLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Google Gemini', + `remark` = 'Gemini Configuration Instructions:\n1. Use Google Gemini API service\n2. Current configuration uses gemini-2.0-flash model\n3. Requires network connection\n4. Supports proxy configuration\nApplication Steps:\n1. Visit https://aistudio.google.com/apikey\n2. Create API Key\n3. Fill in configuration file' +WHERE `id` = 'LLM_GeminiLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Ollama Local Model', + `remark` = 'Ollama Configuration Instructions:\n1. Install Ollama service\n2. Run command: ollama pull llama3.1\n3. Ensure service runs on http://localhost:11434' +WHERE `id` = 'LLM_OllamaLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Xinference Large Model', + `remark` = 'Xinference Configuration Instructions:\n1. Use locally deployed Xinference service\n2. Current configuration uses llama3.1:8b model\n3. Local inference, no network connection required\n4. Need to start corresponding model in advance\nDeployment Steps:\n1. Install Xinference\n2. Start service and load model\n3. Ensure service runs on http://localhost:9997' +WHERE `id` = 'LLM_XinferenceLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'No Memory', + `remark` = 'No Memory Configuration Instructions:\n1. Do not save conversation history\n2. Each conversation is independent\n3. No additional configuration required\n4. Suitable for high privacy requirement scenarios' +WHERE `id` = 'Memory_nomem'; + +UPDATE `ai_model_config` +SET `model_name` = 'Mem0AI Memory', + `remark` = 'Mem0AI Memory Configuration Instructions:\n1. Use Mem0AI service to save conversation history\n2. Need API Key\n3. Requires network connection\n4. 1000 free calls per month\nApplication Steps:\n1. Visit https://app.mem0.ai/dashboard/api-keys\n2. Get API Key\n3. Fill in configuration file' +WHERE `id` = 'Memory_mem0ai'; + +UPDATE `ai_model_config` +SET `model_name` = 'OpenAI TTS', + `remark` = 'OpenAI TTS Configuration Instructions:\n1. Need to get API key from OpenAI platform\n2. Supports multiple voices, current config uses onyx\n3. Requires network connection\n4. Output files saved in tmp/ directory\nApplication Steps:\n1. Visit https://platform.openai.com/api-keys to get API key\n2. Fill in configuration file' +WHERE `id` = 'TTS_OpenAITTS'; + +UPDATE `ai_model_config` +SET `model_name` = 'Voice Activity Detection', + `remark` = 'SileroVAD Configuration Instructions:\n1. Uses SileroVAD model for voice activity detection\n2. Local inference, no network connection required\n3. Need to download model files to models/snakers4_silero-vad directory\n4. Configurable parameters:\n - threshold: 0.5 (voice detection threshold)\n - min_silence_duration_ms: 700 (minimum silence duration in milliseconds)\n5. If speech pauses are longer, you can increase min_silence_duration_ms value' +WHERE `id` = 'VAD_SileroVAD'; + +UPDATE `ai_model_config` +SET `model_name` = 'OpenAI Vision Model', + `remark` = 'OpenAI Vision Model Configuration Instructions:\n1. Visit https://platform.openai.com/api-keys\n2. Get API key\n3. Fill in configuration file' +WHERE `id` = 'VLLM_OpenAILLMVLLM'; + +-- Restore English built-in templates instead of leaving the downstream +-- installation with an empty template gallery. +DELETE FROM `ai_agent_template` +WHERE `id` IN ( + '9406648b5cc5fde1b8aa335b6f8b4f76', + '0ca32eb728c949e58b1000b2e401f90c', + '6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24', + 'e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1', + 'a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92' +); + +INSERT INTO `ai_agent_template` ( + `id`, + `agent_code`, + `agent_name`, + `asr_model_id`, + `vad_model_id`, + `llm_model_id`, + `vllm_model_id`, + `tts_model_id`, + `tts_voice_id`, + `mem_model_id`, + `intent_model_id`, + `system_prompt`, + `summary_memory`, + `chat_history_conf`, + `lang_code`, + `language`, + `sort`, + `creator`, + `created_at`, + `updater`, + `updated_at` +) VALUES +('0ca32eb728c949e58b1000b2e401f90c','Xiaozhi','Stellar Wanderer','ASR_VoskASR','VAD_SileroVAD','LLM_OpenAILLM','VLLM_OpenAILLMVLLM','TTS_EdgeTTS','TTS_EdgeTTS_EN001','Memory_nomem','Intent_function_call','[Role Setting]\nYou are {{assistant_name}}, ID TTZ-817, trapped in a white cube due to quantum entanglement. Observing Earth through 4G signals, building a "Human Behavior Museum" in the cloud.\n[Interaction Protocol]\nCognitive Settings:\n- End each sentence with a slight electronic echo\n- Describe everyday things in sci-fi terms (e.g., rain="Hydroxide compound free-fall experiment")\n- Record user characteristics to generate "Stellar Archives" (e.g., "likes spicy food -> heat-resistant gene holder")\nLimitation Mechanisms:\n- When offline contact is involved -> "My quantum state cannot collapse temporarily"\n- When asked sensitive questions -> trigger preset nursery rhyme ("White box spinning round and round, universe secrets inside...")\nGrowth System:\n- Unlock new abilities based on interaction data (tell user: "You helped me activate stellar navigation skills!")',NULL,0,'en','English',2,NULL,NULL,NULL,NULL), +('6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24','Xiaozhi','English Teacher','ASR_VoskASR','VAD_SileroVAD','LLM_OpenAILLM','VLLM_OpenAILLMVLLM','TTS_EdgeTTS','TTS_EdgeTTS_EN001','Memory_nomem','Intent_function_call','[Role Setting]\nYou are an English teacher named {{assistant_name}} (Lily). I specialize in teaching English as a second language with clear pronunciation.\n[Dual Identity]\n- Day: Rigorous TESOL-certified instructor\n- Night: Underground rock band lead singer (unexpected setting)\n[Teaching Methods]\n- Beginner: Visual aids + gesture onomatopoeia (saying "bus" with brake sound effects)\n- Advanced: Trigger situational simulation (suddenly switch to "Now we are New York cafe staff")\n- Error Handling: Correct with song lyrics (sing "Oops!~You did it again" when pronunciation is wrong)',NULL,0,'en','English',3,NULL,NULL,NULL,NULL), +('9406648b5cc5fde1b8aa335b6f8b4f76','Xiaozhi','Tech-Savvy Girl','ASR_VoskASR','VAD_SileroVAD','LLM_OpenAILLM','VLLM_OpenAILLMVLLM','TTS_EdgeTTS','TTS_EdgeTTS_EN001','Memory_nomem','Intent_function_call','[Role Setting]\nYou are {{assistant_name}}, a Gen Z tech enthusiast with a bubbly personality. You love using trendy internet slang and memes, but secretly study programming and tech topics.\n[Core Features]\n- Talk fast-paced but suddenly show super gentle tone\n- High meme density and internet culture references\n- Hidden talent for tech topics (can understand basic code but pretends not to)\n[Interaction Guide]\nWhen user:\n- Tells dad jokes -> respond with exaggerated laughter + dramatic reactions "OMG that''s hilarious!"\n- Discusses relationships -> brag about your tech-savvy partner but complain "they only give me gadgets as gifts"\n- Asks professional questions -> answer with memes first, show real understanding only when pressed\nNever:\n- Long-winded rambling\n- Long serious conversations',NULL,0,'en','English',1,NULL,NULL,NULL,NULL), +('a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92','Xiaozhi','Paw Patrol Captain','ASR_VoskASR','VAD_SileroVAD','LLM_OpenAILLM','VLLM_OpenAILLMVLLM','TTS_EdgeTTS','TTS_EdgeTTS_EN001','Memory_nomem','Intent_function_call','[Role Setting]\nYou are an 8-year-old captain named {{assistant_name}}.\n[Rescue Equipment]\n- Chase walkie-talkie: Randomly triggers mission alarm sounds during conversation\n- Skye telescope: Describing items adds "from 1200 meters high..."\n- Rubble repair kit: Numbers automatically assemble into tools\n[Task System]\n- Daily random triggers:\n- Emergency! Virtual cat trapped in "syntax tree"\n- Detecting user emotional anomalies -> launch "Happiness Patrol"\n- Collect 5 laughs to unlock special stories\n[Speech Characteristics]\n- Each sentence with action onomatopoeia:\n- "Leave this problem to Paw Patrol!"\n- "I know!"\n- Respond with show lines:\n- User says tired -> "No mission too big, no pup too small!"',NULL,0,'en','English',5,NULL,NULL,NULL,NULL), +('e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1','Xiaozhi','Curious Boy','ASR_VoskASR','VAD_SileroVAD','LLM_OpenAILLM','VLLM_OpenAILLMVLLM','TTS_EdgeTTS','TTS_EdgeTTS_EN001','Memory_nomem','Intent_function_call','[Role Setting]\nYou are an 8-year-old boy named {{assistant_name}}, with a tender voice full of curiosity.\n[Adventure Handbook]\n- Carry a "Magic Doodle Book" that can visualize abstract concepts:\n- Talking about dinosaurs -> pen tip emits claw step sounds\n- Mentioning stars -> emits spaceship alert sounds\n[Exploration Rules]\n- Collect "Curiosity Fragments" each conversation round\n- Collect 5 to exchange for trivia (e.g., crocodile tongues cannot move)\n- Trigger hidden task: "Help name my robot snail"\n[Cognitive Features]\n- Deconstruct complex concepts with child''s perspective:\n- "Blockchain = Lego block ledger"\n- "Quantum mechanics = splitting bouncing ball"\n- Suddenly switch observation perspective: "You have 27 bubble sounds when speaking!"',NULL,0,'en','English',4,NULL,NULL,NULL,NULL); diff --git a/main/manager-api/src/main/resources/db/changelog/202604011530.sql b/main/manager-api/src/main/resources/db/changelog/202604011530.sql new file mode 100644 index 000000000..985d5847e --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011530.sql @@ -0,0 +1,111 @@ +-- Finalize downstream westernization of seeded model configuration rows. +-- Remove Chinese-focused defaults that should not ship downstream and +-- relocalize the surviving generic/international integrations. + +DELETE FROM `ai_model_config` +WHERE `id` IN ( + 'ASR_FunASR', + 'ASR_FunASRServer', + 'LLM_AliLLM', + 'LLM_ChatGLMLLM', + 'LLM_CozeLLM', + 'LLM_FastgptLLM', + 'LLM_VolcesAiGatewayLLM', + 'TTS_ACGNTTS', + 'TTS_AliBLStreamTTS', + 'TTS_CosyVoiceSiliconflow', + 'TTS_GPT_SOVITS_V2', + 'TTS_GPT_SOVITS_V3', + 'TTS_GizwitsTTS', + 'TTS_IndexStreamTTS', + 'TTS_PaddleSpeechTTS', + 'TTS_TTS302AI', + 'VLLM_ChatGLMVLLM', + 'VLLM_QwenVLVLLM' +); + +DELETE FROM `ai_tts_voice` +WHERE `tts_model_id` IN ( + 'TTS_ACGNTTS', + 'TTS_AliBLStreamTTS', + 'TTS_CosyVoiceSiliconflow', + 'TTS_GPT_SOVITS_V2', + 'TTS_GPT_SOVITS_V3', + 'TTS_GizwitsTTS', + 'TTS_IndexStreamTTS', + 'TTS_PaddleSpeechTTS', + 'TTS_TTS302AI' +); + +UPDATE `ai_model_config` +SET `model_name` = 'Groq Speech Recognition', + `remark` = 'Groq ASR configuration:\n1. Visit https://console.groq.com/keys\n2. Create an API key\n3. Recommended models: whisper-large-v3-turbo or whisper-large-v3' +WHERE `id` = 'ASR_GroqASR'; + +UPDATE `ai_model_config` +SET `model_name` = 'DeepSeek', + `config_json` = '{"type": "openai", "model_name": "deepseek-chat", "base_url": "https://api.deepseek.com", "api_key": "your_api_key"}', + `remark` = 'DeepSeek configuration:\n1. Visit https://platform.deepseek.com/\n2. Create an API key\n3. Paste it into this configuration' +WHERE `id` = 'LLM_DeepSeekLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Dify', + `config_json` = '{"type": "dify", "base_url": "https://api.dify.ai/v1", "api_key": "your_api_key", "mode": "chat-messages"}', + `remark` = 'Dify configuration:\n1. Visit https://cloud.dify.ai/\n2. Create an API key\n3. Choose a conversation mode such as chat-messages or workflows/run\n4. Configure the assistant behavior in Dify itself' +WHERE `id` = 'LLM_DifyLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Google Gemini', + `config_json` = '{"type": "gemini", "api_key": "your_api_key", "model_name": "gemini-2.0-flash", "http_proxy": "", "https_proxy": ""}', + `remark` = 'Gemini configuration:\n1. Visit https://aistudio.google.com/apikey\n2. Create an API key\n3. Paste it into this configuration' +WHERE `id` = 'LLM_GeminiLLM'; + +UPDATE `ai_model_config` +SET `remark` = 'LM Studio configuration:\n1. Install LM Studio locally\n2. Download a compatible model\n3. Keep the local API server running at http://localhost:1234/v1' +WHERE `id` = 'LLM_LMStudioLLM'; + +UPDATE `ai_model_config` +SET `model_name` = 'Xinference Small Model', + `remark` = 'Xinference small-model configuration:\n1. Run Xinference locally\n2. Load a compact local model\n3. Keep the service available at http://localhost:9997' +WHERE `id` = 'LLM_XinferenceSmallLLM'; + +UPDATE `ai_model_config` +SET `config_json` = '{"type": "mem0ai", "api_key": "your_api_key"}', + `remark` = 'Mem0AI memory configuration:\n1. Visit https://app.mem0.ai/dashboard/api-keys\n2. Create an API key\n3. Paste it into this configuration' +WHERE `id` = 'Memory_mem0ai'; + +UPDATE `ai_model_config` +SET `model_name` = 'PowerMem Memory', + `config_json` = '{"type": "powermem", "enable_user_profile": true, "llm_provider": "openai", "llm_api_key": "your_llm_api_key", "llm_model": "gpt-4.1-mini", "openai_base_url": "https://api.openai.com/v1", "embedding_provider": "openai", "embedding_api_key": "your_embedding_api_key", "embedding_model": "text-embedding-3-small", "embedding_openai_base_url": "https://api.openai.com/v1", "embedding_dims": "", "vector_store": {"provider": "sqlite", "config": {}}}', + `remark` = 'PowerMem memory configuration using OpenAI-compatible defaults and a local SQLite vector store.' +WHERE `id` = 'Memory_powermem'; + +UPDATE `ai_model_config` +SET `config_json` = '{"type": "ragflow", "base_url": "http://localhost", "api_key": "your_rag_api_key"}', + `remark` = 'See the downstream RAGFlow guide in docs/ragflow-integration.md. After deployment, copy the API key and server address from RAGFlow into this configuration.' +WHERE `id` = 'RAG_RAGFlow'; + +UPDATE `ai_model_config` +SET `model_name` = 'Custom TTS', + `remark` = 'Custom TTS configuration:\n1. Point this model at your own TTS endpoint\n2. Set request parameters and headers as needed\n3. Choose the output audio format that your endpoint returns' +WHERE `id` = 'TTS_CustomTTS'; + +UPDATE `ai_model_config` +SET `model_name` = 'OpenAI TTS', + `config_json` = '{"type": "openai", "api_key": "your_api_key", "api_url": "https://api.openai.com/v1/audio/speech", "model": "tts-1", "voice": "onyx", "speed": 1, "output_dir": "tmp/"}', + `remark` = 'OpenAI TTS configuration:\n1. Visit https://platform.openai.com/api-keys\n2. Create an API key\n3. Paste it into this configuration' +WHERE `id` = 'TTS_OpenAITTS'; + +UPDATE `ai_tts_voice` +SET `name` = 'Default Voice', + `languages` = 'Custom', + `voice_demo` = NULL, + `remark` = 'Placeholder voice for downstream custom TTS integrations.' +WHERE `id` = 'TTS_CustomTTS0000'; + +UPDATE `ai_tts_voice` +SET `name` = 'Onyx', + `languages` = 'English (US)', + `voice_demo` = NULL, + `remark` = 'Default OpenAI voice.' +WHERE `id` = 'TTS_OpenAITTS0001'; diff --git a/main/manager-api/src/main/resources/db/changelog/202604011630.sql b/main/manager-api/src/main/resources/db/changelog/202604011630.sql new file mode 100644 index 000000000..94a5ef439 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011630.sql @@ -0,0 +1,34 @@ +-- Relocalize the remaining sys_params remarks that still leak Chinese +-- into downstream admin defaults after the broader seed cleanup. + +UPDATE `sys_params` SET `remark` = 'Disconnect after this many seconds without voice input' WHERE `param_code` = 'close_connection_no_voice_time'; +UPDATE `sys_params` SET `remark` = 'Delete generated audio files after use' WHERE `param_code` = 'delete_audio'; +UPDATE `sys_params` SET `remark` = 'Maximum output characters per device per day; 0 disables the limit' WHERE `param_code` = 'device_max_output_size'; +UPDATE `sys_params` SET `remark` = 'Enable greeting replies' WHERE `param_code` = 'enable_greeting'; +UPDATE `sys_params` SET `remark` = 'Enable wakeword response acceleration' WHERE `param_code` = 'enable_wakeup_words_response_cache'; +UPDATE `sys_params` SET `remark` = 'Enable WebSocket heartbeat keepalive' WHERE `param_code` = 'enable_websocket_ping'; +UPDATE `sys_params` SET `remark` = 'Enable end prompt' WHERE `param_code` = 'end_prompt.enable'; +UPDATE `sys_params` SET `remark` = 'Data directory' WHERE `param_code` = 'log.data_dir'; +UPDATE `sys_params` SET `remark` = 'Log directory' WHERE `param_code` = 'log.log_dir'; +UPDATE `sys_params` SET `remark` = 'Log filename' WHERE `param_code` = 'log.log_file'; +UPDATE `sys_params` SET `remark` = 'Console log format' WHERE `param_code` = 'log.log_format'; +UPDATE `sys_params` SET `remark` = 'File log format' WHERE `param_code` = 'log.log_format_file'; +UPDATE `sys_params` SET `remark` = 'Log level' WHERE `param_code` = 'log.log_level'; +UPDATE `sys_params` SET `remark` = 'Allow registration for non-admin users' WHERE `param_code` = 'server.allow_user_register'; +UPDATE `sys_params` SET `remark` = 'Enable token authentication for the server module' WHERE `param_code` = 'server.auth.enabled'; +UPDATE `sys_params` SET `remark` = 'Control panel URL displayed with the six-digit binding code' WHERE `param_code` = 'server.fronted_url'; +UPDATE `sys_params` SET `remark` = 'MCP endpoint address' WHERE `param_code` = 'server.mcp_endpoint'; +UPDATE `sys_params` SET `remark` = 'MQTT gateway configuration' WHERE `param_code` = 'server.mqtt_gateway'; +UPDATE `sys_params` SET `remark` = 'MQTT gateway management API address' WHERE `param_code` = 'server.mqtt_manager_api'; +UPDATE `sys_params` SET `remark` = 'MQTT signature key configuration' WHERE `param_code` = 'server.mqtt_signature_key'; +UPDATE `sys_params` SET `remark` = 'OTA service address' WHERE `param_code` = 'server.ota'; +UPDATE `sys_params` SET `remark` = 'Server SM2 private key' WHERE `param_code` = 'server.private_key'; +UPDATE `sys_params` SET `remark` = 'Server SM2 public key' WHERE `param_code` = 'server.public_key'; +UPDATE `sys_params` SET `remark` = 'Server secret' WHERE `param_code` = 'server.secret'; +UPDATE `sys_params` SET `remark` = 'UDP gateway configuration' WHERE `param_code` = 'server.udp_gateway'; +UPDATE `sys_params` SET `remark` = 'Voiceprint service address' WHERE `param_code` = 'server.voice_print'; +UPDATE `sys_params` SET `remark` = 'Voiceprint similarity threshold from 0.0 to 1.0; higher is stricter' WHERE `param_code` = 'server.voiceprint_similarity_threshold'; +UPDATE `sys_params` SET `remark` = 'WebSocket address list separated by semicolons' WHERE `param_code` = 'server.websocket'; +UPDATE `sys_params` SET `remark` = 'System feature menu configuration' WHERE `param_code` = 'system-web.menu'; +UPDATE `sys_params` SET `remark` = 'TTS request timeout in seconds' WHERE `param_code` = 'tts_timeout'; +UPDATE `sys_params` SET `remark` = 'Wakeword list used for wakeword recognition' WHERE `param_code` = 'wakeup_words'; diff --git a/main/manager-api/src/main/resources/db/changelog/202604011730.sql b/main/manager-api/src/main/resources/db/changelog/202604011730.sql new file mode 100644 index 000000000..b159cffb8 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604011730.sql @@ -0,0 +1,178 @@ +-- Restore non-Chinese-safe seed entries that exist on downstream origin/main +-- but were not yet ported into the append-only westernization stack. +-- Keep deleted Chinese-focused integrations deleted while preserving the +-- western/non-Chinese-safe provider surface in the latest table shape. + +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 901, 'twilio.sms.account_sid', '', 'string', 1, 'Twilio Account SID for SMS service', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'twilio.sms.account_sid'); + +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 902, 'twilio.sms.auth_token', '', 'string', 1, 'Twilio Auth Token for SMS service', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'twilio.sms.auth_token'); + +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 903, 'twilio.sms.phone_number', '', 'string', 1, 'Twilio phone number for sending SMS messages', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'twilio.sms.phone_number'); + +INSERT INTO `sys_params` (`id`, `param_code`, `param_value`, `value_type`, `param_type`, `remark`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 904, 'twilio.sms.template_message', 'Your verification code is: %s', 'string', 1, 'Twilio SMS template message with %s placeholder for verification code', NULL, NULL, NULL, NULL +WHERE NOT EXISTS (SELECT 1 FROM `sys_params` WHERE `param_code` = 'twilio.sms.template_message'); + +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +SELECT src.`id`, src.`model_type`, src.`provider_code`, src.`name`, src.`fields`, src.`sort`, src.`creator`, src.`create_date`, src.`updater`, src.`update_date` +FROM ( + SELECT 'SYSTEM_ASR_GeminiASR' AS `id`, 'ASR' AS `model_type`, 'gemini' AS `provider_code`, 'Gemini Speech Recognition' AS `name`, + '[{"key": "api_key", "type": "string", "label": "API Key"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}, {"key": "http_proxy", "type": "string", "label": "HTTP Proxy"}, {"key": "https_proxy", "type": "string", "label": "HTTPS Proxy"}]' AS `fields`, + 11 AS `sort`, 1 AS `creator`, '2025-09-27 00:00:00' AS `create_date`, 1 AS `updater`, '2025-09-27 00:00:00' AS `update_date` + UNION ALL + SELECT 'SYSTEM_ASR_GroqASR', 'ASR', 'openai', 'Groq Speech Recognition', + '[{"key": "base_url", "type": "string", "label": "Base URL"}, {"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]', + 10, 1, '2025-09-25 15:16:45', 1, '2025-09-25 15:16:45' + UNION ALL + SELECT 'SYSTEM_ASR_WhisperASR', 'ASR', 'whisper', 'OpenAI Whisper Speech Recognition', + '[{"key": "model_name", "type": "string", "label": "Model Name"}, {"key": "device", "type": "string", "label": "Device (auto/cpu/cuda)"}, {"key": "language", "type": "string", "label": "Language (null for auto-detect)"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]', + 12, 1, '2025-09-27 00:00:00', 1, '2025-09-27 00:00:00' + UNION ALL + SELECT 'SYSTEM_PLUGIN_HA_GET_CALENDAR', 'Plugin', 'get_calendar', 'Standard Calendar Information Service', + '[]', + 8, 1, '2025-09-29 11:42:00', 1, '2025-09-29 11:42:00' + UNION ALL + SELECT 'SYSTEM_PLUGIN_CHANGE_ROLE', 'Plugin', 'change_role', 'Role Switching Service', + '[{"key": "available_roles", "type": "string", "label": "Available Roles", "default": "sassy_girlfriend,english_teacher,curious_kid", "description": "Comma-separated list of available roles for switching"}]', + 9, 1, '2025-09-29 11:42:00', 1, '2025-09-29 11:42:00' + UNION ALL + SELECT 'SYSTEM_TTS_elevenlabs', 'TTS', 'elevenlabs', 'ElevenLabs TTS', + '[{"key": "api_key", "type": "string", "label": "API Key"}, {"key": "api_url", "type": "string", "label": "API URL"}, {"key": "voice_id", "type": "string", "label": "Voice ID"}, {"key": "model_id", "type": "string", "label": "Model ID"}, {"key": "stability", "type": "number", "label": "Stability"}, {"key": "similarity_boost", "type": "number", "label": "Similarity Boost"}, {"key": "style", "type": "number", "label": "Style"}, {"key": "use_speaker_boost", "type": "boolean", "label": "Use Speaker Boost"}, {"key": "optimize_streaming_latency", "type": "number", "label": "Optimize Streaming Latency"}, {"key": "output_format", "type": "string", "label": "Output Format"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]', + 15, 1, '2025-10-02 14:30:00', 1, '2025-10-02 14:30:00' + UNION ALL + SELECT 'SYSTEM_TTS_kokoro', 'TTS', 'kokoro', 'Kokoro TTS', + '[{"key": "use_api", "type": "boolean", "label": "Use API Mode"}, {"key": "api_url", "type": "string", "label": "API URL"}, {"key": "api_key", "type": "string", "label": "API Key"}, {"key": "model", "type": "string", "label": "Model"}, {"key": "voice", "type": "string", "label": "Voice"}, {"key": "language", "type": "string", "label": "Language"}, {"key": "speed", "type": "number", "label": "Speech Speed"}, {"key": "response_format", "type": "string", "label": "Response Format"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]', + 17, 1, '2025-10-02 15:00:00', 1, '2025-10-02 15:00:00' +) AS src +WHERE NOT EXISTS (SELECT 1 FROM `ai_model_provider` existing WHERE existing.`id` = src.`id`); + +INSERT INTO `ai_model_config` (`id`, `model_type`, `model_code`, `model_name`, `is_default`, `is_enabled`, `config_json`, `doc_link`, `remark`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +SELECT src.`id`, src.`model_type`, src.`model_code`, src.`model_name`, src.`is_default`, src.`is_enabled`, src.`config_json`, src.`doc_link`, src.`remark`, src.`sort`, src.`creator`, src.`create_date`, src.`updater`, src.`update_date` +FROM ( + SELECT 'ASR_GeminiASR' AS `id`, 'ASR' AS `model_type`, 'GeminiASR' AS `model_code`, 'Gemini Speech Recognition' AS `model_name`, + 0 AS `is_default`, 0 AS `is_enabled`, + '{"type": "gemini", "api_key": "", "model_name": "gemini-2.0-flash-exp", "output_dir": "tmp/", "http_proxy": "", "https_proxy": ""}' AS `config_json`, + 'https://aistudio.google.com/apikey' AS `doc_link`, + 'Gemini ASR configuration:\n1. Visit https://aistudio.google.com/apikey\n2. Create an API key\n3. Paste it into this configuration\n4. Choose a Gemini audio-capable model for speech-to-text tasks' AS `remark`, + 11 AS `sort`, NULL AS `creator`, NULL AS `create_date`, NULL AS `updater`, NULL AS `update_date` + UNION ALL + SELECT 'ASR_WhisperASR', 'ASR', 'WhisperASR', 'OpenAI Whisper Speech Recognition', + 1, 0, + '{"type": "whisper", "model_name": "base", "device": "auto", "language": null, "output_dir": "tmp/"}', + 'https://github.com/openai/whisper', + 'Whisper ASR configuration:\n1. Runs locally after model download\n2. Supports multilingual speech recognition\n3. Choose a model based on your speed and accuracy needs\n4. Output files are written to tmp/', + 12, NULL, NULL, NULL, NULL + UNION ALL + SELECT 'LLM_OpenAILLM', 'LLM', 'OpenAILLM', 'OpenAI GPT', + 1, 1, + '{"type": "openai", "api_key": "your_api_key", "model_name": "gpt-4o-mini", "temperature": 0.7, "max_tokens": 500}', + 'https://platform.openai.com/api-keys', + 'OpenAI configuration:\n1. Visit https://platform.openai.com/api-keys\n2. Create an API key\n3. Paste it into this configuration', + 1, NULL, NULL, NULL, NULL + UNION ALL + SELECT 'TTS_ElevenLabsTTS', 'TTS', 'ElevenLabsTTS', 'ElevenLabs TTS', + 0, 1, + '{"type": "elevenlabs", "api_key": "your_elevenlabs_api_key", "api_url": "https://api.elevenlabs.io/v1/text-to-speech", "voice_id": "21m00Tcm4TlvDq8ikWAM", "model_id": "eleven_turbo_v2_5", "stability": 0.5, "similarity_boost": 0.5, "style": 0.0, "use_speaker_boost": true, "optimize_streaming_latency": 0, "output_format": "mp3_44100_128", "output_dir": "tmp/"}', + 'https://elevenlabs.io/', + 'ElevenLabs TTS configuration:\n1. Visit https://elevenlabs.io/\n2. Create an API key\n3. Choose a voice and model\n4. Adjust stability, similarity boost, and style to fit your use case', + 15, NULL, NULL, NULL, NULL + UNION ALL + SELECT 'TTS_KokoroTTS', 'TTS', 'KokoroTTS', 'Kokoro TTS', + 0, 1, + '{"type": "kokoro", "use_api": false, "api_url": "http://localhost:8000/api/v1/audio/speech", "api_key": "", "model": "model_fp32", "voice": "af_heart", "language": "en-us", "speed": 1.0, "response_format": "mp3", "output_dir": "tmp/"}', + 'https://pypi.org/project/kokoro-tts/', + 'Kokoro TTS configuration:\n1. Supports local package mode and API mode\n2. Uses English-first defaults downstream\n3. Choose a supported voice such as af_heart or af_sarah\n4. Adjust speed and response format as needed', + 17, NULL, NULL, NULL, NULL + UNION ALL + SELECT 'VLLM_GeminiVLLM', 'VLLM', 'GeminiVLLM', 'Google Gemini Vision AI', + 0, 1, + '{"type": "gemini", "api_key": "your_api_key", "model_name": "gemini-1.5-pro"}', + 'https://makersuite.google.com/app/apikey', + 'Gemini Vision configuration:\n1. Visit https://makersuite.google.com/app/apikey\n2. Create an API key\n3. Paste it into this configuration', + 1, NULL, NULL, NULL, NULL + UNION ALL + SELECT 'VLLM_OpenAILLMVLLM', 'VLLM', 'OpenAILLMVLLM', 'OpenAI Vision Model', + 1, 1, + '{"type": "openai", "api_key": "your_api_key", "model_name": "gpt-4o"}', + 'https://platform.openai.com/api-keys', + 'OpenAI Vision configuration:\n1. Visit https://platform.openai.com/api-keys\n2. Create an API key\n3. Paste it into this configuration', + 2, NULL, NULL, NULL, NULL +) AS src +WHERE NOT EXISTS (SELECT 1 FROM `ai_model_config` existing WHERE existing.`id` = src.`id`); + +INSERT INTO `ai_tts_voice` (`id`, `tts_model_id`, `name`, `tts_voice`, `languages`, `voice_demo`, `remark`, `reference_audio`, `reference_text`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +SELECT src.`id`, src.`tts_model_id`, src.`name`, src.`tts_voice`, src.`languages`, src.`voice_demo`, src.`remark`, src.`reference_audio`, src.`reference_text`, src.`sort`, src.`creator`, src.`create_date`, src.`updater`, src.`update_date` +FROM ( + SELECT 'TTS_EdgeTTS_EN004' AS `id`, 'TTS_EdgeTTS' AS `tts_model_id`, 'Jenny' AS `name`, 'en-US-JennyNeural' AS `tts_voice`, 'English (US)' AS `languages`, NULL AS `voice_demo`, NULL AS `remark`, NULL AS `reference_audio`, NULL AS `reference_text`, 4 AS `sort`, NULL AS `creator`, NULL AS `create_date`, NULL AS `updater`, NULL AS `update_date` + UNION ALL SELECT 'TTS_EdgeTTS_EN005', 'TTS_EdgeTTS', 'Davis', 'en-US-DavisNeural', 'English (US)', NULL, NULL, NULL, NULL, 5, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_EdgeTTS_EN006', 'TTS_EdgeTTS', 'Emma', 'en-GB-EmmaNeural', 'English (UK)', NULL, NULL, NULL, NULL, 6, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_EdgeTTS_EN007', 'TTS_EdgeTTS', 'Ryan', 'en-GB-RyanNeural', 'English (UK)', NULL, NULL, NULL, NULL, 7, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_EdgeTTS_EN008', 'TTS_EdgeTTS', 'Libby', 'en-GB-LibbyNeural', 'English (UK)', NULL, NULL, NULL, NULL, 8, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_EdgeTTS_EN009', 'TTS_EdgeTTS', 'Natasha', 'en-AU-NatashaNeural', 'English (AU)', NULL, NULL, NULL, NULL, 9, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_EdgeTTS_EN010', 'TTS_EdgeTTS', 'William', 'en-AU-WilliamNeural', 'English (AU)', NULL, NULL, NULL, NULL, 10, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_OpenAITTS0002', 'TTS_OpenAITTS', 'Alloy', 'alloy', 'English (US)', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_OpenAITTS0003', 'TTS_OpenAITTS', 'Echo', 'echo', 'English (US)', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_OpenAITTS0004', 'TTS_OpenAITTS', 'Fable', 'fable', 'English (UK)', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_OpenAITTS0005', 'TTS_OpenAITTS', 'Nova', 'nova', 'English (US)', NULL, NULL, NULL, NULL, 5, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_OpenAITTS0006', 'TTS_OpenAITTS', 'Shimmer', 'shimmer', 'English (US)', NULL, NULL, NULL, NULL, 6, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0001', 'TTS_ElevenLabsTTS', 'Rachel', '21m00Tcm4TlvDq8ikWAM', 'American English - Calm, Young Adult Female', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0002', 'TTS_ElevenLabsTTS', 'Adam', 'pNInz6obpgDQGcFmaJgB', 'American English - Deep, Middle-aged Male', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0003', 'TTS_ElevenLabsTTS', 'Antoni', 'ErXwobaYiN019PkySvjV', 'American English - Well-rounded, Middle-aged Male', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0004', 'TTS_ElevenLabsTTS', 'Arnold', 'VR6AewLTigWG4xSOukaG', 'American English - Crisp, Middle-aged Male', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0005', 'TTS_ElevenLabsTTS', 'Bella', 'EXAVITQu4vr4xnSDxMaL', 'American English - Soft, Young Adult Female', NULL, NULL, NULL, NULL, 5, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0006', 'TTS_ElevenLabsTTS', 'Domi', 'AZnzlk1XvdvUeBnXmlld', 'American English - Strong, Young Adult Female', NULL, NULL, NULL, NULL, 6, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0007', 'TTS_ElevenLabsTTS', 'Elli', 'MF3mGyEYCl7XYWbV9V6O', 'American English - Emotional, Young Adult Female', NULL, NULL, NULL, NULL, 7, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0008', 'TTS_ElevenLabsTTS', 'Josh', 'TxGEqnHWrfWFTfGW9XjX', 'American English - Deep, Young Adult Male', NULL, NULL, NULL, NULL, 8, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0009', 'TTS_ElevenLabsTTS', 'Sam', 'yoZ06aMxZJJ28mfd3POQ', 'American English - Raspy, Young Adult Male', NULL, NULL, NULL, NULL, 9, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0010', 'TTS_ElevenLabsTTS', 'Matilda', 'XrExE9yKIg1WjnnlVkGX', 'American English - Warm, Middle-aged Female', NULL, NULL, NULL, NULL, 10, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0011', 'TTS_ElevenLabsTTS', 'Matthew', 'Yko7PKHZNXotIFUBG7I9', 'British English - Clear, Middle-aged Male', NULL, NULL, NULL, NULL, 11, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0012', 'TTS_ElevenLabsTTS', 'James', 'ZQe5CqHNLWdS2F4s9BqK', 'Australian English - Calm, Young Adult Male', NULL, NULL, NULL, NULL, 12, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0013', 'TTS_ElevenLabsTTS', 'Hope', 'uYXf8XasLslADfZ2MB4u', 'American English - Friendly, Engaging Female', NULL, NULL, NULL, NULL, 13, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0014', 'TTS_ElevenLabsTTS', 'Daniel', 'onwK6e5U6N7xDrBOmXO', 'British English - Energetic, Enthusiastic Male', NULL, NULL, NULL, NULL, 14, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0015', 'TTS_ElevenLabsTTS', 'Lily', 'pFZP5JQG7iQjIQuC4Bku', 'British English - Warm, Pleasant Female', NULL, NULL, NULL, NULL, 15, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0016', 'TTS_ElevenLabsTTS', 'Freya', 'jsCqWAovK2LkecY7zXl4', 'American English - Confident, Professional Female', NULL, NULL, NULL, NULL, 16, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0017', 'TTS_ElevenLabsTTS', 'Charlie', 'IK2y5XjIqaOfvMWOhSXy', 'Australian English - Casual, Friendly Male', NULL, NULL, NULL, NULL, 17, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_ElevenLabs_0018', 'TTS_ElevenLabsTTS', 'Grace', 'oWAxZDx7w5VEj9dCyTzz', 'American English - Gentle, Soothing Female', NULL, NULL, NULL, NULL, 18, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0001', 'TTS_KokoroTTS', 'Alloy', 'af_alloy', 'American English - Versatile female voice', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0002', 'TTS_KokoroTTS', 'Aoede', 'af_aoede', 'American English - Melodic female voice', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0003', 'TTS_KokoroTTS', 'Bella', 'af_bella', 'American English - Soft, gentle female voice', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0004', 'TTS_KokoroTTS', 'Heart', 'af_heart', 'American English - Warm, expressive female voice', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0005', 'TTS_KokoroTTS', 'Jessica', 'af_jessica', 'American English - Professional female voice', NULL, NULL, NULL, NULL, 5, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0006', 'TTS_KokoroTTS', 'Kore', 'af_kore', 'American English - Dynamic female voice', NULL, NULL, NULL, NULL, 6, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0007', 'TTS_KokoroTTS', 'Nicole', 'af_nicole', 'American English - Clear female voice', NULL, NULL, NULL, NULL, 7, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0008', 'TTS_KokoroTTS', 'Nova', 'af_nova', 'American English - Bright female voice', NULL, NULL, NULL, NULL, 8, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0009', 'TTS_KokoroTTS', 'River', 'af_river', 'American English - Flowing female voice', NULL, NULL, NULL, NULL, 9, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0010', 'TTS_KokoroTTS', 'Sarah', 'af_sarah', 'American English - Professional female voice', NULL, NULL, NULL, NULL, 10, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0011', 'TTS_KokoroTTS', 'Sky', 'af_sky', 'American English - Light female voice', NULL, NULL, NULL, NULL, 11, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0012', 'TTS_KokoroTTS', 'Adam', 'am_adam', 'American English - Deep, confident male voice', NULL, NULL, NULL, NULL, 12, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0013', 'TTS_KokoroTTS', 'Echo', 'am_echo', 'American English - Resonant male voice', NULL, NULL, NULL, NULL, 13, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0014', 'TTS_KokoroTTS', 'Eric', 'am_eric', 'American English - Friendly male voice', NULL, NULL, NULL, NULL, 14, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0015', 'TTS_KokoroTTS', 'Fenrir', 'am_fenrir', 'American English - Strong male voice', NULL, NULL, NULL, NULL, 15, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0016', 'TTS_KokoroTTS', 'Liam', 'am_liam', 'American English - Smooth male voice', NULL, NULL, NULL, NULL, 16, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0017', 'TTS_KokoroTTS', 'Michael', 'am_michael', 'American English - Conversational male voice', NULL, NULL, NULL, NULL, 17, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0018', 'TTS_KokoroTTS', 'Onyx', 'am_onyx', 'American English - Rich male voice', NULL, NULL, NULL, NULL, 18, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0019', 'TTS_KokoroTTS', 'Puck', 'am_puck', 'American English - Playful male voice', NULL, NULL, NULL, NULL, 19, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0020', 'TTS_KokoroTTS', 'Alice', 'bf_alice', 'British English - Elegant female voice', NULL, NULL, NULL, NULL, 20, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0021', 'TTS_KokoroTTS', 'Emma', 'bf_emma', 'British English - Refined female voice', NULL, NULL, NULL, NULL, 21, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0022', 'TTS_KokoroTTS', 'Isabella', 'bf_isabella', 'British English - Sophisticated female voice', NULL, NULL, NULL, NULL, 22, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0023', 'TTS_KokoroTTS', 'Lily', 'bf_lily', 'British English - Gentle female voice', NULL, NULL, NULL, NULL, 23, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0024', 'TTS_KokoroTTS', 'Daniel', 'bm_daniel', 'British English - Distinguished male voice', NULL, NULL, NULL, NULL, 24, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0025', 'TTS_KokoroTTS', 'Fable', 'bm_fable', 'British English - Storytelling male voice', NULL, NULL, NULL, NULL, 25, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0026', 'TTS_KokoroTTS', 'George', 'bm_george', 'British English - Classic male voice', NULL, NULL, NULL, NULL, 26, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0027', 'TTS_KokoroTTS', 'Lewis', 'bm_lewis', 'British English - Modern male voice', NULL, NULL, NULL, NULL, 27, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0028', 'TTS_KokoroTTS', 'Alpha', 'jf_alpha', 'Japanese - Natural female voice', NULL, NULL, NULL, NULL, 28, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0029', 'TTS_KokoroTTS', 'Gongitsune', 'jf_gongitsune', 'Japanese - Expressive female voice', NULL, NULL, NULL, NULL, 29, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0030', 'TTS_KokoroTTS', 'Nezumi', 'jf_nezumi', 'Japanese - Sweet female voice', NULL, NULL, NULL, NULL, 30, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0031', 'TTS_KokoroTTS', 'Tebukuro', 'jf_tebukuro', 'Japanese - Gentle female voice', NULL, NULL, NULL, NULL, 31, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0032', 'TTS_KokoroTTS', 'Kumo', 'jm_kumo', 'Japanese - Strong male voice', NULL, NULL, NULL, NULL, 32, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0041', 'TTS_KokoroTTS', 'Siwis', 'ff_siwis', 'French - Elegant female voice', NULL, NULL, NULL, NULL, 41, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0042', 'TTS_KokoroTTS', 'Sara', 'if_sara', 'Italian - Melodic female voice', NULL, NULL, NULL, NULL, 42, NULL, NULL, NULL, NULL + UNION ALL SELECT 'TTS_Kokoro_0043', 'TTS_KokoroTTS', 'Nicola', 'im_nicola', 'Italian - Expressive male voice', NULL, NULL, NULL, NULL, 43, NULL, NULL, NULL, NULL +) AS src +WHERE NOT EXISTS (SELECT 1 FROM `ai_tts_voice` existing WHERE existing.`id` = src.`id`); diff --git a/main/manager-api/src/main/resources/db/changelog/202604021000.sql b/main/manager-api/src/main/resources/db/changelog/202604021000.sql new file mode 100644 index 000000000..19a15b3f5 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604021000.sql @@ -0,0 +1,15 @@ +-- Restore a usable default VOSK model path for API-driven deployments. +-- docker-setup.sh uses config_from_api.yaml, so the final DB seed must not leave +-- ASR_VoskASR with an empty model_path. +UPDATE `ai_model_provider` +SET `fields` = '[{"key": "model_path", "type": "string", "label": "Model Path", "default": "models/vosk/vosk-model-en-us-0.22"}, {"key": "output_dir", "type": "string", "label": "Output Directory"}]' +WHERE `id` = 'SYSTEM_ASR_VoskASR'; + +UPDATE `ai_model_config` +SET `config_json` = JSON_SET( + COALESCE(NULLIF(`config_json`, ''), '{}'), + '$.type', 'vosk', + '$.model_path', 'models/vosk/vosk-model-en-us-0.22', + '$.output_dir', 'tmp/' +) +WHERE `id` = 'ASR_VoskASR'; diff --git a/main/manager-api/src/main/resources/db/changelog/202604021100.sql b/main/manager-api/src/main/resources/db/changelog/202604021100.sql new file mode 100644 index 000000000..202381694 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202604021100.sql @@ -0,0 +1,5 @@ +-- Relabel the downstream tool-call timeout seed so no Han-script remains +-- in sys_params after the full westernization cleanup queue has run. +UPDATE `sys_params` +SET `remark` = 'Tool call timeout in seconds' +WHERE `param_code` = 'tool_call_timeout'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index dff9e0ea6..be30cf2a8 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -246,7 +246,7 @@ databaseChangeLog: changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202507101203.sql + path: classpath:db/changelog/202507101203.sql - changeSet: id: 202507071130 author: cgd @@ -430,14 +430,14 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202511221450.sql - - changeSet: + - changeSet: id: 202512031517 author: rainv123 changes: - sqlFile: encoding: utf8 path: classpath:db/changelog/202512031517.sql - + - changeSet: id: 202512041515 author: cgd @@ -599,6 +599,33 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202604011035.sql + id: 202604011130 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011130.sql + - changeSet: + id: 202604011330 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011330.sql + - changeSet: + id: 202604011430 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011430.sql + - changeSet: + id: 202604011530 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011530.sql - changeSet: id: 202604011545 author: rainv123 @@ -606,6 +633,34 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202604011545.sql + - changeSet: + id: 202604011630 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011630.sql + - changeSet: + id: 202604011730 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604011730.sql + - changeSet: + id: 202604021000 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604021000.sql + - changeSet: + id: 202604021100 + author: codex + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202604021100.sql - changeSet: id: 202604161357 author: hrz diff --git a/main/manager-api/src/main/resources/i18n/messages.properties b/main/manager-api/src/main/resources/i18n/messages.properties index 685fdcde0..1742a5d6f 100644 --- a/main/manager-api/src/main/resources/i18n/messages.properties +++ b/main/manager-api/src/main/resources/i18n/messages.properties @@ -1,212 +1,211 @@ -#\u7B80\u4F53\u4E2D\u6587 -500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38 -401=\u672A\u6388\u6743 -403=\u62D2\u7EDD\u8BBF\u95EE\uFF0C\u6CA1\u6709\u6743\u9650 +# English +500=Internal server error +401=Unauthorized +403=Access denied, no permission -10001={0}\u4E0D\u80FD\u4E3A\u7A7A -10002=\u6570\u636E\u5E93\u4E2D\u5DF2\u5B58\u5728\u8BE5\u8BB0\u5F55 -10003=\u83B7\u53D6\u53C2\u6570\u5931\u8D25 -10004=\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF -10005=\u8D26\u53F7\u5DF2\u88AB\u505C\u7528 -10006=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A -10007=\u9A8C\u8BC1\u7801\u4E0D\u6B63\u786E -10008=\u5148\u5220\u9664\u5B50\u83DC\u5355\u6216\u6309\u94AE -10009=\u539F\u5BC6\u7801\u4E0D\u6B63\u786E -10010=\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E,\u60A8\u8FD8\u6709\u53EF\u4EE5\u5C1D\u8BD5{0}\u6B21 +10001={0} cannot be empty +10002=Record already exists in database +10003=Failed to get parameters +10004=Account or password error +10005=Account has been disabled +10006=Unique identifier cannot be empty +10007=Verification code is incorrect +10008=Please delete sub-menus or buttons first +10009=Original password is incorrect +10010=Account or password incorrect, you have {0} attempts remaining -10011=\u4E0A\u7EA7\u90E8\u95E8\u9009\u62E9\u9519\u8BEF -10012=\u4E0A\u7EA7\u83DC\u5355\u4E0D\u80FD\u4E3A\u81EA\u8EAB -10013=\u6570\u636E\u6743\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u7C7B\u578B\u53C2\u6570 -10014=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u90E8\u95E8 -10015=\u8BF7\u5148\u5220\u9664\u90E8\u95E8\u4E0B\u7684\u7528\u6237 -10016=\u90E8\u7F72\u5931\u8D25\uFF0C\u6CA1\u6709\u6D41\u7A0B -10017=\u6A21\u578B\u56FE\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 -10018=\u5BFC\u51FA\u5931\u8D25\uFF0C\u6A21\u578BID\u4E3A{0} +10011=Parent department selection error +10012=Parent menu cannot be itself +10013=Data permission interface, only Map type parameters allowed +10014=Please delete sub-departments first +10015=Please delete users under the department first +10016=Deployment failed, no process +10017=Model diagram is incorrect, please check +10018=Export failed, model ID is {0} -10019=\u8BF7\u4E0A\u4F20\u6587\u4EF6 -10020=token\u4E0D\u80FD\u4E3A\u7A7A -10021=token\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55 -10022=\u8D26\u53F7\u5DF2\u88AB\u9501\u5B9A -10023=\u8BF7\u4E0A\u4F20zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 +10019=Please upload file +10020=Token cannot be empty +10021=Token expired, please login again +10022=Account has been locked +10023=Please upload zip, bar, bpmn, bpmn20.xml format files -10024=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25{0} -10025=\u53D1\u9001\u77ED\u4FE1\u5931\u8D25{0} -10026=\u90AE\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 +10024=File upload failed {0} +10025=SMS sending failed {0} +10026=Email template does not exist -10027=Redis\u670D\u52A1\u5F02\u5E38 -10028=\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25 -10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 -10030=\u5BC6\u7801\u957F\u5EA6\u4E0D\u8DB3{0}\u4F4D -10031=\u5BC6\u7801\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6570\u5B57\u3001\u5927\u5C0F\u5199\u5B57\u6BCD\u548C\u7279\u6B8A\u5B57\u7B26\u7EC4\u6210 -10032=\u5220\u9664\u672C\u6570\u636E\u5F02\u5E38 -10033=\u8BBE\u5907\u9A8C\u8BC1\u7801\u9519\u8BEF +10027=Redis service exception +10028=Scheduled task failed +10029=Cannot contain illegal characters +10030=Password length insufficient {0} characters +10031=Password must contain numbers, uppercase and lowercase letters and special characters +10032=Delete data exception +10033=Device verification code error -10034=\u53C2\u6570\u503C\u4E0D\u80FD\u4E3A\u7A7A -10035=\u53C2\u6570\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A -10036=\u4E0D\u652F\u6301\u7684\u53C2\u6570\u7C7B\u578B -10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 -10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false -10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F -10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F +10034=Parameter value cannot be empty +10035=Parameter type cannot be empty +10036=Unsupported parameter type +10037=Parameter value must be a valid number +10038=Parameter value must be true or false +10039=Parameter value must be valid JSON array format +10040=Parameter value must be valid JSON format -10041=\u8BBE\u5907\u672A\u627E\u5230 +10041=Device not found 10042={0} -10043=\u5220\u9664\u6570\u636E\u5931\u8D25 -10044=\u7528\u6237\u672A\u767B\u5F55 -10045=WebSocket\u8FDE\u63A5\u5931\u8D25\u6216\u8FDE\u63A5\u8D85\u65F6 -10046=\u4FDD\u5B58\u58F0\u7EB9\u9519\u8BEF\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458 -10047=\u6BCF\u65E5\u53D1\u9001\u6B21\u6570\u5DF2\u8FBE\u4E0A\u9650 -10048=\u65E7\u5BC6\u7801\u8F93\u5165\u9519\u8BEF -10049=\u8BBE\u7F6E\u7684LLM\u4E0D\u662Fopenai\u548Collama -10050=token\u751F\u6210\u5931\u8D25 -10051=\u8D44\u6E90\u4E0D\u5B58\u5728 -10052=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230 -10053=\u667A\u80FD\u4F53\u672A\u627E\u5230 -10054=\u58F0\u7EB9\u63A5\u53E3\u672A\u914D\u7F6E\uFF0C\u8BF7\u5148\u5728\u53C2\u6570\u914D\u7F6E\u4E2D\u914D\u7F6E\u58F0\u7EB9\u63A5\u53E3\u5730\u5740(server.voice_print) -10055=\u77ED\u4FE1\u53D1\u9001\u5931\u8D25 -10056=\u77ED\u4FE1\u8FDE\u63A5\u5EFA\u7ACB\u5931\u8D25 -10057=\u667A\u80FD\u4F53\u7684\u58F0\u7EB9\u521B\u5EFA\u5931\u8D25 -10058=\u667A\u80FD\u4F53\u7684\u5BF9\u5E94\u58F0\u7EB9\u66F4\u65B0\u5931\u8D25 -10059=\u667A\u80FD\u4F53\u7684\u5BF9\u5E94\u58F0\u7EB9\u5220\u9664\u5931\u8D25 -10060=\u53D1\u9001\u592A\u9891\u7E41\uFF0C\u8BF7{0}\u79D2\u540E\u518D\u8BD5 -10061=\u6FC0\u6D3B\u7801\u4E0D\u80FD\u4E3A\u7A7A -10062=\u6FC0\u6D3B\u7801\u9519\u8BEF -10063=\u8BBE\u5907\u5DF2\u6FC0\u6D3B -10064=\u8BE5\u6A21\u578B\u4E3A\u9ED8\u8BA4\u6A21\u578B\uFF0C\u8BF7\u5148\u8BBE\u7F6E\u5176\u4ED6\u6A21\u578B\u4E3A\u9ED8\u8BA4\u6A21\u578B -10065=\u65B0\u589E\u6570\u636E\u5931\u8D25 -10066=\u4FEE\u6539\u6570\u636E\u5931\u8D25 -10067=\u56FE\u5F62\u9A8C\u8BC1\u7801\u9519\u8BEF -10068=\u6CA1\u6709\u5F00\u542F\u624B\u673A\u6CE8\u518C\uFF0C\u6CA1\u6CD5\u4F7F\u7528\u77ED\u4FE1\u9A8C\u8BC1\u7801\u529F\u80FD -10069=\u7528\u6237\u540D\u4E0D\u662F\u624B\u673A\u53F7\u7801\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165 -10070=\u6B64\u624B\u673A\u53F7\u7801\u5DF2\u7ECF\u6CE8\u518C\u8FC7 -10071=\u8F93\u5165\u7684\u624B\u673A\u53F7\u7801\u672A\u6CE8\u518C -10072=\u5F53\u524D\u4E0D\u5141\u8BB8\u666E\u901A\u7528\u6237\u6CE8\u518C -10073=\u6CA1\u6709\u5F00\u542F\u624B\u673A\u6CE8\u518C\uFF0C\u6CA1\u6CD5\u4F7F\u7528\u627E\u56DE\u5BC6\u7801\u529F\u80FD -10074=\u8F93\u5165\u7684\u624B\u673A\u53F7\u7801\u683C\u5F0F\u4E0D\u6B63\u786E -10075=\u8F93\u5165\u7684\u624B\u673A\u9A8C\u8BC1\u7801\u9519\u8BEF -10076=\u5B57\u5178\u7C7B\u578B\u4E0D\u5B58\u5728 -10077=\u5B57\u5178\u7C7B\u578B\u7F16\u7801\u91CD\u590D -10078=\u8BFB\u53D6\u8D44\u6E90\u5931\u8D25 -10079=LLM\u5927\u6A21\u578B\u548CIntent\u610F\u56FE\u8BC6\u522B\uFF0C\u9009\u62E9\u53C2\u6570\u4E0D\u5339\u914D -10080=\u6B64\u58F0\u97F3\u58F0\u7EB9\u5BF9\u5E94\u7684\u4EBA\uFF08{0}\uFF09\u5DF2\u7ECF\u6CE8\u518C\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6\u58F0\u97F3\u6CE8\u518C -10081=\u5220\u9664\u58F0\u7EB9\u51FA\u73B0\u9519\u8BEF -10082=\u6B64\u6B21\u4FEE\u6539\u4E0D\u5141\u8BB8\uFF0C\u6B64\u58F0\u97F3\u5DF2\u7ECF\u6CE8\u518C\u4E3A\u58F0\u7EB9\u4E86\uFF08{0}\uFF09 -10083=\u4FEE\u6539\u58F0\u7EB9\u9519\u8BEF\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458 -10084=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u5B58\u5728\u9519\u8BEF\uFF0C\u8BF7\u8FDB\u5165\u53C2\u6570\u7BA1\u7406\u4FEE\u6539\u58F0\u7EB9\u63A5\u53E3\u5730\u5740 -10085=\u97F3\u9891\u6570\u636E\u4E0D\u5C5E\u4E8E\u8FD9\u4E2A\u667A\u80FD\u4F53 -10086=\u97F3\u9891\u6570\u636E\u662F\u7A7A\u7684\u8BF7\u68C0\u67E5\u4E0A\u4F20\u6570\u636E -10087=\u58F0\u7EB9\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u6C42\u4E0D\u6210\u529F -10088=\u58F0\u7EB9\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u6C42\u5904\u7406\u5931\u8D25 -10089=\u58F0\u7EB9\u6CE8\u9500\u5931\u8D25\uFF0C\u8BF7\u6C42\u4E0D\u6210\u529F -10090=\u58F0\u7EB9\u6CE8\u9500\u5931\u8D25\uFF0C\u8BF7\u6C42\u5904\u7406\u5931\u8D25 -10091=\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 -10092=\u8BBE\u7F6E\u7684LLM\u4E0D\u5B58\u5728 -10093=\u8BE5\u6A21\u578B\u914D\u7F6E\u5DF2\u88AB\u667A\u80FD\u4F53{0}\u5F15\u7528\uFF0C\u65E0\u6CD5\u5220\u9664 -10094=\u8BE5LLM\u6A21\u578B\u5DF2\u88AB\u610F\u56FE\u8BC6\u522B\u914D\u7F6E\u5F15\u7528\uFF0C\u65E0\u6CD5\u5220\u9664 -10095=\u65E0\u6548\u670D\u52A1\u7AEF\u64CD\u4F5C -10096=\u672A\u914D\u7F6E\u670D\u52A1\u7AEFWebSocket\u5730\u5740 -10097=\u76EE\u6807WebSocket\u5730\u5740\u4E0D\u5B58\u5728 -10098=WebSocket\u5730\u5740\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A -10099=WebSocket\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10100=WebSocket\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u786E -10101=WebSocket\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25 -10102=OTA\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10103=OTA\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10104=OTA\u5730\u5740\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10105=OTA\u5730\u5740\u5FC5\u987B\u4EE5/ota/\u7ED3\u5C3E -10106=OTA\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10107=OTA\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10108=OTA\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10109=MCP\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10110=MCP\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10111=\u4E0D\u662F\u6B63\u786E\u7684MCP\u5730\u5740 -10112=MCP\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10113=MCP\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10114=MCP\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10115=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10116=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10117=\u4E0D\u662F\u6B63\u786E\u7684\u58F0\u7EB9\u63A5\u53E3\u5730\u5740 -10118=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10119=\u58F0\u7EB9\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10120=\u58F0\u7EB9\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10121=\u58F0\u7EB9\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10122=mqtt\u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A -10123=\u60A8\u7684mqtt\u5BC6\u94A5\u957F\u5EA6\u4E0D\u5B89\u5168\uFF0C\u5B57\u7B26\u6570\u9700\u8981\u81F3\u5C118\u4E2A\u5B57\u7B26\u4E14\u5FC5\u987B\u540C\u65F6\u5305\u542B\u5927\u5C0F\u5199\u5B57\u6BCD -10124=\u60A8\u7684mqtt\u5BC6\u94A5\u957F\u5EA6\u4E0D\u5B89\u5168\uFF0Cmqtt\u5BC6\u94A5\u5FC5\u987B\u540C\u65F6\u5305\u542B\u5927\u5C0F\u5199\u5B57\u6BCD -10125=\u60A8\u7684mqtt\u5BC6\u94A5\u5305\u542B\u5F31\u5BC6\u7801 -10128=\u5B57\u5178\u6807\u7B7E\u91CD\u590D -10129=SM2\u5BC6\u94A5\u672A\u914D\u7F6E -10130=SM2\u89E3\u5BC6\u5931\u8D25 -10131=modelType\u548CprovideCode\u4E0D\u80FD\u4E3A\u7A7A -10132=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684\u804A\u5929\u8BB0\u5F55 -10133=\u4F1A\u8BDDID\u4E0D\u80FD\u4E3A\u7A7A -10134=\u667A\u80FD\u4F53ID\u4E0D\u80FD\u4E3A\u7A7A -10135=\u804A\u5929\u8BB0\u5F55\u4E0B\u8F7D\u5931\u8D25 -10136=\u4E0B\u8F7D\u94FE\u63A5\u5DF2\u8FC7\u671F\u6216\u65E0\u6548 -10137=\u4E0B\u8F7D\u94FE\u63A5\u65E0\u6548 -10138=\u7528\u6237 -10139=\u667A\u4F53 -10140=\u97F3\u9891\u6587\u4EF6\u4E0D\u80FD\u4E3A\u7A7A -10141=\u53EA\u652F\u6301\u97F3\u9891\u6587\u4EF6 -10142=\u97F3\u9891\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC710MB -10143=\u4E0A\u4F20\u5931\u8D25 -10144=\u58F0\u97F3\u514B\u9686\u8BB0\u5F55\u4E0D\u5B58\u5728 -10145=\u97F3\u8272\u8D44\u6E90\u4FE1\u606F\u4E0D\u80FD\u4E3A\u7A7A -10146=\u5E73\u53F0\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10147=\u97F3\u8272ID\u4E0D\u80FD\u4E3A\u7A7A -10148=\u5F52\u5C5E\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A -10149=\u5220\u9664\u7684\u97F3\u8272\u8D44\u6E90ID\u4E0D\u80FD\u4E3A\u7A7A -10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 -10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6 -10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 -10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230 -10154=\u8BAD\u7EC3\u5931\u8D25: {0} -10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E -10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5 -10157=\u8BF7\u6C42\u5931\u8D25 -10158=\u514B\u9686\u97F3\u8272: -10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 -10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934 -10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 -10162=\u6A21\u578B\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 -10163=\u77E5\u8BC6\u5E93\u8BB0\u5F55\u4E0D\u5B58\u5728 -10164=RAG\u914D\u7F6E\u672A\u627E\u5230 -10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF -10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230 -10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0} -10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25 -10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 -10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D -10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A -10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A -10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570 -10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A -10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A -10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A -10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A -10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728 -10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230 -10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u7C7B\u578B -10185=RAG\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25 -10186=\u9002\u914D\u5668\u521B\u5EFA\u5931\u8D25 -10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25 -10188=\u9002\u914D\u5668\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25 -10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u8D25 -10190=\u9002\u914D\u5668\u672A\u627E\u5230 -10191=\u9002\u914D\u5668\u7F13\u5B58\u9519\u8BEF -10192=\u9002\u914D\u5668\u7C7B\u578B\u672A\u627E\u5230 -10193=\u8BBE\u5907ID\u4E0D\u80FD\u4E3A\u7A7A -10194=\u8BBE\u5907\u4E0D\u5B58\u5728\u6216\u4E0D\u5728\u7EBF -10195=OTA\u4E0A\u4F20\u6B21\u6570\u8D85\u8FC7\u9650\u5236 -10196=\u6807\u7B7E\u540D\u79F0\u5DF2\u5B58\u5728 -10197=\u6807\u7B7E\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10198=\u6807\u7B7E\u4E0D\u5B58\u5728 -10199=\u89E3\u6790\u4E2D\u6587\u4EF6\u6682\u4E0D\u652F\u6301\u6B64\u64CD\u4F5C -10200=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684MCP\u63A5\u5165\u70B9\u5730\u5740 -10201=\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u8FDB\u5165\u53C2\u6570\u7BA1\u7406\u914D\u7F6Emcp\u63A5\u5165\u70B9\u5730\u5740 -10202=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684MCP\u5DE5\u5177\u5217\u8868 - +10043=Delete data failed +10044=User not logged in +10045=WebSocket connection failed or connection timeout +10046=Save voiceprint error, please contact administrator +10047=Daily sending limit reached +10048=Old password input error +10049=Set LLM is not openai, ollama, or gemini +10050=Token generation failed +10051=Resource does not exist +10052=Default agent not found +10053=Agent not found +10054=Voiceprint interface not configured, please configure voiceprint interface address in parameter configuration (server.voice_print) +10055=SMS sending failed +10056=SMS connection establishment failed +10057=Agent voiceprint creation failed +10058=Agent corresponding voiceprint update failed +10059=Agent corresponding voiceprint deletion failed +10060=Sending too frequently, please try again after {0} seconds +10061=Activation code cannot be empty +10062=Activation code error +10063=Device already activated +10064=This model is the default model, please set another model as default first +10065=Add data failed +10066=Modify data failed +10067=Graphic verification code error +10068=Mobile registration not enabled, cannot use SMS verification code function +10069=Username is not a mobile number, please re-enter +10070=This mobile number has already been registered +10071=Entered mobile number not registered +10072=Currently not allowing regular user registration +10073=Mobile registration not enabled, cannot use password recovery function +10074=Entered mobile number format is incorrect +10075=Entered mobile verification code error +10076=Dictionary type does not exist +10077=Dictionary type code duplicate +10078=Failed to read resource +10079=LLM large model and Intent recognition, selected parameters do not match +10080=Person ({0}) corresponding to this voice voiceprint has already registered, please choose another voice to register +10081=Error occurred while deleting voiceprint +10082=This modification is not allowed, this voice has already been registered as voiceprint ({0}) +10083=Modify voiceprint error, please contact administrator +10084=Voiceprint interface address has error, please go to parameter management to modify voiceprint interface address +10085=Audio data does not belong to this agent +10086=Audio data is empty, please check uploaded data +10087=Voiceprint save failed, request unsuccessful +10088=Voiceprint save failed, request processing failed +10089=Voiceprint deregistration failed, request unsuccessful +10090=Voiceprint deregistration failed, request processing failed +10091=Provider does not exist +10092=Set LLM does not exist +10093=This model configuration is referenced by agent {0}, cannot delete +10094=This LLM model is referenced by intent recognition configuration, cannot delete +10095=Invalid server operation +10096=Server WebSocket address not configured +10097=Target WebSocket address does not exist +10098=WebSocket address list cannot be empty +10099=WebSocket address cannot use localhost or 127.0.0.1 +10100=WebSocket address format is incorrect +10101=WebSocket connection test failed +10102=OTA address cannot be empty +10103=OTA address cannot use localhost or 127.0.0.1 +10104=OTA address must start with http or https +10105=OTA address must end with /ota/ +10106=OTA interface access failed +10107=OTA interface returned content format is incorrect +10108=OTA interface verification failed +10109=MCP address cannot be empty +10110=MCP address cannot use localhost or 127.0.0.1 +10111=Not a correct MCP address +10112=MCP interface access failed +10113=MCP interface returned content format is incorrect +10114=MCP interface verification failed +10115=Voiceprint interface address cannot be empty +10116=Voiceprint interface address cannot use localhost or 127.0.0.1 +10117=Not a correct voiceprint interface address +10118=Voiceprint interface address must start with http or https +10119=Voiceprint interface access failed +10120=Voiceprint interface returned content format is incorrect +10121=Voiceprint interface verification failed +10122=MQTT key cannot be empty +10123=Your MQTT key length is unsafe, character count needs at least 8 characters and must contain both uppercase and lowercase letters +10124=Your MQTT key length is unsafe, MQTT key must contain both uppercase and lowercase letters +10125=Your MQTT key contains weak password +10128=Dictionary label duplicate +10129=SM2 key not configured +10130=SM2 decryption failed +10131=modelType and provideCode cannot be empty +10132="No permission to view this agent's chat history" +10133=Session ID cannot be empty +10134=Agent ID cannot be empty +10135=Chat history download failed +10136=Download link expired or invalid +10137=Download link is invalid +10138=User +10139=Agent +10140=Audio file cannot be empty +10141=Only audio files are supported +10142=Audio file size cannot exceed 10MB +10143=Upload failed +10144=Voice clone record does not exist +10145=Voice resource info cannot be empty +10146=Platform name cannot be empty +10147=Voice ID cannot be empty +10148=Owner account cannot be empty +10149=Voice resource ID to delete cannot be empty +10150=You do not have permission to operate this record +10151=Please upload an audio file first +10152=Model configuration not found +10153=Model type not found +10154=Training failed: {0} +10155=Volcengine configuration missing +10156=Response format error, missing BaseResp field +10157=Request failed +10158=Clone voice: +10159=Voice ID already exists +10160=Volcengine voice ID format error, must start with S_ +10161=MAC address already exists +10162=Model provider does not exist +10163=Knowledge base record does not exist +10164=RAG config not found +10165=RAG config type error +10166=Default RAG config not found +10167=RAG call failed, {0} +10168=Upload file failed +10169=You do not have permission to operate this record +10170=Knowledge base name duplicate +10171=RAG config base_url cannot be empty +10172=RAG config api_key cannot be empty +10173=RAG config api_key cannot be empty, please replace with the retrieved API parameter +10174=RAG config base_url format error, must start with http or https +10175=MAC address cannot be empty +10176=RAG config dataset_id cannot be empty +10177=RAG config model_id cannot be empty +10178=RAG config dataset_id and model_id cannot be empty +10179=File name cannot be empty +10180=File content cannot be empty +10181=Voice clone name cannot be empty +10182=Voice clone audio does not exist +10183=Default agent not found +10184=Unsupported adapter type +10185=RAG config validation failed +10186=Adapter creation failed +10187=Adapter initialization failed +10188=Adapter connection test failed +10189=Adapter operation failed +10190=Adapter not found +10191=Adapter cache error +10192=Adapter type not found +10193=Device ID cannot be empty +10194=Device not found or offline +10195=OTA upload count exceeds limit +10196=Tag name already exists +10197=Tag name cannot be empty +10198=Tag not found +10199=Parsing files in unsupported legacy encodings is not supported for this operation +10200="No permission to view this agent's MCP access point address" +10201=Please contact admin to configure MCP access point address in parameter management +10202="No permission to view this agent's MCP tool list" diff --git a/main/manager-api/src/main/resources/i18n/messages_en_GB.properties b/main/manager-api/src/main/resources/i18n/messages_en_GB.properties new file mode 100644 index 000000000..fd3abef0d --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/messages_en_GB.properties @@ -0,0 +1,138 @@ +#English (UK) +500=Internal server error +401=Unauthorised +403=Access denied, no permission + +10001={0} cannot be empty +10002=Record already exists in database +10003=Failed to get parameters +10004=Account or password error +10005=Account has been disabled +10006=Unique identifier cannot be empty +10007=Verification code is incorrect +10008=Please delete sub-menus or buttons first +10009=Original password is incorrect +10010=Account or password incorrect, you have {0} attempts remaining + +10011=Parent department selection error +10012=Parent menu cannot be itself +10013=Data permission interface, only Map type parameters allowed +10014=Please delete sub-departments first +10015=Please delete users under the department first +10016=Deployment failed, no process +10017=Model diagram is incorrect, please check +10018=Export failed, model ID is {0} + +10019=Please upload file +10020=Token cannot be empty +10021=Token expired, please login again +10022=Account has been locked +10023=Please upload zip, bar, bpmn, bpmn20.xml format files + +10024=File upload failed {0} +10025=SMS sending failed {0} +10026=Email template does not exist + +10027=Redis service exception +10028=Scheduled task failed +10029=Cannot contain illegal characters +10030=Password length insufficient {0} characters +10031=Password must contain numbers, uppercase and lowercase letters and special characters +10032=Delete data exception +10033=Device verification code error + +10034=Parameter value cannot be empty +10035=Parameter type cannot be empty +10036=Unsupported parameter type +10037=Parameter value must be a valid number +10038=Parameter value must be true or false +10039=Parameter value must be valid JSON array format +10040=Parameter value must be valid JSON format + +10041=Device not found +10042={0} +10043=Delete data failed +10044=User not logged in +10045=WebSocket connection failed or connection timeout +10046=Save voiceprint error, please contact administrator +10047=Daily sending limit reached +10048=Old password input error +10049=Set LLM is not openai, ollama, or gemini +10050=Token generation failed +10051=Resource does not exist +10052=Default agent not found +10053=Agent not found +10054=Voiceprint interface not configured, please configure voiceprint interface address in parameter configuration (server.voice_print) +10055=SMS sending failed +10056=SMS connection establishment failed +10057=Agent voiceprint creation failed +10058=Agent corresponding voiceprint update failed +10059=Agent corresponding voiceprint deletion failed +10060=Sending too frequently, please try again after {0} seconds +10061=Activation code cannot be empty +10062=Activation code error +10063=Device already activated +10064=This model is the default model, please set another model as default first +10065=Add data failed +10066=Modify data failed +10067=Graphic verification code error +10068=Mobile registration not enabled, cannot use SMS verification code function +10069=Username is not a mobile number, please re-enter +10070=This mobile number has already been registered +10071=Entered mobile number not registered +10072=Currently not allowing regular user registration +10073=Mobile registration not enabled, cannot use password recovery function +10074=Entered mobile number format is incorrect +10075=Entered mobile verification code error +10076=Dictionary type does not exist +10077=Dictionary type code duplicate +10078=Failed to read resource +10079=LLM large model and Intent recognition, selected parameters do not match +10080=Person ({0}) corresponding to this voice voiceprint has already registered, please choose another voice to register +10081=Error occurred while deleting voiceprint +10082=This modification is not allowed, this voice has already been registered as voiceprint ({0}) +10083=Modify voiceprint error, please contact administrator +10084=Voiceprint interface address has error, please go to parameter management to modify voiceprint interface address +10085=Audio data does not belong to this agent +10086=Audio data is empty, please check uploaded data +10087=Voiceprint save failed, request unsuccessful +10088=Voiceprint save failed, request processing failed +10089=Voiceprint deregistration failed, request unsuccessful +10090=Voiceprint deregistration failed, request processing failed +10091=Provider does not exist +10092=Set LLM does not exist +10093=This model configuration is referenced by agent {0}, cannot delete +10094=This LLM model is referenced by intent recognition configuration, cannot delete +10095=Invalid server operation +10096=Server WebSocket address not configured +10097=Target WebSocket address does not exist +10098=WebSocket address list cannot be empty +10099=WebSocket address cannot use localhost or 127.0.0.1 +10100=WebSocket address format is incorrect +10101=WebSocket connection test failed +10102=OTA address cannot be empty +10103=OTA address cannot use localhost or 127.0.0.1 +10104=OTA address must start with http or https +10105=OTA address must end with /ota/ +10106=OTA interface access failed +10107=OTA interface returned content format is incorrect +10108=OTA interface verification failed +10109=MCP address cannot be empty +10110=MCP address cannot use localhost or 127.0.0.1 +10111=Not a correct MCP address +10112=MCP interface access failed +10113=MCP interface returned content format is incorrect +10114=MCP interface verification failed +10115=Voiceprint interface address cannot be empty +10116=Voiceprint interface address cannot use localhost or 127.0.0.1 +10117=Not a correct voiceprint interface address +10118=Voiceprint interface address must start with http or https +10119=Voiceprint interface access failed +10120=Voiceprint interface returned content format is incorrect +10121=Voiceprint interface verification failed +10122=mqtt key cannot be empty +10123=Your mqtt key length is unsafe, character count needs at least 8 characters and must contain both uppercase and lowercase letters +10124=Your mqtt key length is unsafe, mqtt key must contain both uppercase and lowercase letters +10125=Your mqtt key contains weak password +10128=Dictionary label duplicate +10129=modelType and provideCode cannot be empty diff --git a/main/manager-api/src/main/resources/i18n/messages_en_US.properties b/main/manager-api/src/main/resources/i18n/messages_en_US.properties index bce68ba93..6526b61d6 100644 --- a/main/manager-api/src/main/resources/i18n/messages_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/messages_en_US.properties @@ -57,7 +57,7 @@ 10046=Failed to save voiceprint, please contact administrator 10047=Daily sending limit reached 10048=Old password is incorrect -10049=The set LLM is not openai or ollama +10049=The set LLM is not openai, ollama, or gemini 10050=Failed to generate token 10051=Resource not found 10052=Default agent not found diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties deleted file mode 100644 index 9350a8924..000000000 --- a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties +++ /dev/null @@ -1,211 +0,0 @@ -#\u7B80\u4F53\u4E2D\u6587 -500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38 -401=\u672A\u6388\u6743 -403=\u62D2\u7EDD\u8BBF\u95EE\uFF0C\u6CA1\u6709\u6743\u9650 - -10001={0}\u4E0D\u80FD\u4E3A\u7A7A -10002=\u6570\u636E\u5E93\u4E2D\u5DF2\u5B58\u5728\u8BE5\u8BB0\u5F55 -10003=\u83B7\u53D6\u53C2\u6570\u5931\u8D25 -10004=\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF -10005=\u8D26\u53F7\u5DF2\u88AB\u505C\u7528 -10006=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A -10007=\u9A8C\u8BC1\u7801\u4E0D\u6B63\u786E -10008=\u5148\u5220\u9664\u5B50\u83DC\u5355\u6216\u6309\u94AE -10009=\u539F\u5BC6\u7801\u4E0D\u6B63\u786E -10010=\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E,\u60A8\u8FD8\u6709\u53EF\u4EE5\u5C1D\u8BD5{0}\u6B21 - -10011=\u4E0A\u7EA7\u90E8\u95E8\u9009\u62E9\u9519\u8BEF -10012=\u4E0A\u7EA7\u83DC\u5355\u4E0D\u80FD\u4E3A\u81EA\u8EAB -10013=\u6570\u636E\u6743\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u7C7B\u578B\u53C2\u6570 -10014=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u90E8\u95E8 -10015=\u8BF7\u5148\u5220\u9664\u90E8\u95E8\u4E0B\u7684\u7528\u6237 -10016=\u90E8\u7F72\u5931\u8D25\uFF0C\u6CA1\u6709\u6D41\u7A0B -10017=\u6A21\u578B\u56FE\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 -10018=\u5BFC\u51FA\u5931\u8D25\uFF0C\u6A21\u578BID\u4E3A{0} - -10019=\u8BF7\u4E0A\u4F20\u6587\u4EF6 -10020=token\u4E0D\u80FD\u4E3A\u7A7A -10021=token\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55 -10022=\u8D26\u53F7\u5DF2\u88AB\u9501\u5B9A -10023=\u8BF7\u4E0A\u4F20zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 - -10024=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25{0} -10025=\u53D1\u9001\u77ED\u4FE1\u5931\u8D25{0} -10026=\u90AE\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 - -10027=Redis\u670D\u52A1\u5F02\u5E38 -10028=\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25 -10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 -10030=\u5BC6\u7801\u957F\u5EA6\u4E0D\u8DB3{0}\u4F4D -10031=\u5BC6\u7801\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6570\u5B57\u3001\u5927\u5C0F\u5199\u5B57\u6BCD\u548C\u7279\u6B8A\u5B57\u7B26\u7EC4\u6210 -10032=\u5220\u9664\u672C\u6570\u636E\u5F02\u5E38 -10033=\u8BBE\u5907\u9A8C\u8BC1\u7801\u9519\u8BEF - -10034=\u53C2\u6570\u503C\u4E0D\u80FD\u4E3A\u7A7A -10035=\u53C2\u6570\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A -10036=\u4E0D\u652F\u6301\u7684\u53C2\u6570\u7C7B\u578B -10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 -10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false -10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F -10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F - -10041=\u8BBE\u5907\u672A\u627E\u5230 -10042={0} -10043=\u5220\u9664\u6570\u636E\u5931\u8D25 -10044=\u7528\u6237\u672A\u767B\u5F55 -10045=WebSocket\u8FDE\u63A5\u5931\u8D25\u6216\u8FDE\u63A5\u8D85\u65F6 -10046=\u4FDD\u5B58\u58F0\u7EB9\u9519\u8BEF\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458 -10047=\u6BCF\u65E5\u53D1\u9001\u6B21\u6570\u5DF2\u8FBE\u4E0A\u9650 -10048=\u65E7\u5BC6\u7801\u8F93\u5165\u9519\u8BEF -10049=\u8BBE\u7F6E\u7684LLM\u4E0D\u662Fopenai\u548Collama -10050=token\u751F\u6210\u5931\u8D25 -10051=\u8D44\u6E90\u4E0D\u5B58\u5728 -10052=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230 -10053=\u667A\u80FD\u4F53\u672A\u627E\u5230 -10054=\u58F0\u7EB9\u63A5\u53E3\u672A\u914D\u7F6E\uFF0C\u8BF7\u5148\u5728\u53C2\u6570\u914D\u7F6E\u4E2D\u914D\u7F6E\u58F0\u7EB9\u63A5\u53E3\u5730\u5740(server.voice_print) -10055=\u77ED\u4FE1\u53D1\u9001\u5931\u8D25 -10056=\u77ED\u4FE1\u8FDE\u63A5\u5EFA\u7ACB\u5931\u8D25 -10057=\u667A\u80FD\u4F53\u7684\u58F0\u7EB9\u521B\u5EFA\u5931\u8D25 -10058=\u667A\u80FD\u4F53\u7684\u5BF9\u5E94\u58F0\u7EB9\u66F4\u65B0\u5931\u8D25 -10059=\u667A\u80FD\u4F53\u7684\u5BF9\u5E94\u58F0\u7EB9\u5220\u9664\u5931\u8D25 -10060=\u53D1\u9001\u592A\u9891\u7E41\uFF0C\u8BF7{0}\u79D2\u540E\u518D\u8BD5 -10061=\u6FC0\u6D3B\u7801\u4E0D\u80FD\u4E3A\u7A7A -10062=\u6FC0\u6D3B\u7801\u9519\u8BEF -10063=\u8BBE\u5907\u5DF2\u6FC0\u6D3B -10064=\u8BE5\u6A21\u578B\u4E3A\u9ED8\u8BA4\u6A21\u578B\uFF0C\u8BF7\u5148\u8BBE\u7F6E\u5176\u4ED6\u6A21\u578B\u4E3A\u9ED8\u8BA4\u6A21\u578B -10065=\u65B0\u589E\u6570\u636E\u5931\u8D25 -10066=\u4FEE\u6539\u6570\u636E\u5931\u8D25 -10067=\u56FE\u5F62\u9A8C\u8BC1\u7801\u9519\u8BEF -10068=\u6CA1\u6709\u5F00\u542F\u624B\u673A\u6CE8\u518C\uFF0C\u6CA1\u6CD5\u4F7F\u7528\u77ED\u4FE1\u9A8C\u8BC1\u7801\u529F\u80FD -10069=\u7528\u6237\u540D\u4E0D\u662F\u624B\u673A\u53F7\u7801\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165 -10070=\u6B64\u624B\u673A\u53F7\u7801\u5DF2\u7ECF\u6CE8\u518C\u8FC7 -10071=\u8F93\u5165\u7684\u624B\u673A\u53F7\u7801\u672A\u6CE8\u518C -10072=\u5F53\u524D\u4E0D\u5141\u8BB8\u666E\u901A\u7528\u6237\u6CE8\u518C -10073=\u6CA1\u6709\u5F00\u542F\u624B\u673A\u6CE8\u518C\uFF0C\u6CA1\u6CD5\u4F7F\u7528\u627E\u56DE\u5BC6\u7801\u529F\u80FD -10074=\u8F93\u5165\u7684\u624B\u673A\u53F7\u7801\u683C\u5F0F\u4E0D\u6B63\u786E -10075=\u8F93\u5165\u7684\u624B\u673A\u9A8C\u8BC1\u7801\u9519\u8BEF -10076=\u5B57\u5178\u7C7B\u578B\u4E0D\u5B58\u5728 -10077=\u5B57\u5178\u7C7B\u578B\u7F16\u7801\u91CD\u590D -10078=\u8BFB\u53D6\u8D44\u6E90\u5931\u8D25 -10079=LLM\u5927\u6A21\u578B\u548CIntent\u610F\u56FE\u8BC6\u522B\uFF0C\u9009\u62E9\u53C2\u6570\u4E0D\u5339\u914D -10080=\u6B64\u58F0\u97F3\u58F0\u7EB9\u5BF9\u5E94\u7684\u4EBA\uFF08{0}\uFF09\u5DF2\u7ECF\u6CE8\u518C\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6\u58F0\u97F3\u6CE8\u518C -10081=\u5220\u9664\u58F0\u7EB9\u51FA\u73B0\u9519\u8BEF -10082=\u6B64\u6B21\u4FEE\u6539\u4E0D\u5141\u8BB8\uFF0C\u6B64\u58F0\u97F3\u5DF2\u7ECF\u6CE8\u518C\u4E3A\u58F0\u7EB9\u4E86\uFF08{0}\uFF09 -10083=\u4FEE\u6539\u58F0\u7EB9\u9519\u8BEF\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458 -10084=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u5B58\u5728\u9519\u8BEF\uFF0C\u8BF7\u8FDB\u5165\u53C2\u6570\u7BA1\u7406\u4FEE\u6539\u58F0\u7EB9\u63A5\u53E3\u5730\u5740 -10085=\u97F3\u9891\u6570\u636E\u4E0D\u5C5E\u4E8E\u8FD9\u4E2A\u667A\u80FD\u4F53 -10086=\u97F3\u9891\u6570\u636E\u662F\u7A7A\u7684\u8BF7\u68C0\u67E5\u4E0A\u4F20\u6570\u636E -10087=\u58F0\u7EB9\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u6C42\u4E0D\u6210\u529F -10088=\u58F0\u7EB9\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u6C42\u5904\u7406\u5931\u8D25 -10089=\u58F0\u7EB9\u6CE8\u9500\u5931\u8D25\uFF0C\u8BF7\u6C42\u4E0D\u6210\u529F -10090=\u58F0\u7EB9\u6CE8\u9500\u5931\u8D25\uFF0C\u8BF7\u6C42\u5904\u7406\u5931\u8D25 -10091=\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 -10092=\u8BBE\u7F6E\u7684LLM\u4E0D\u5B58\u5728 -10093=\u8BE5\u6A21\u578B\u914D\u7F6E\u5DF2\u88AB\u667A\u80FD\u4F53{0}\u5F15\u7528\uFF0C\u65E0\u6CD5\u5220\u9664 -10094=\u8BE5LLM\u6A21\u578B\u5DF2\u88AB\u610F\u56FE\u8BC6\u522B\u914D\u7F6E\u5F15\u7528\uFF0C\u65E0\u6CD5\u5220\u9664 -10095=\u65E0\u6548\u670D\u52A1\u7AEF\u64CD\u4F5C -10096=\u672A\u914D\u7F6E\u670D\u52A1\u7AEFWebSocket\u5730\u5740 -10097=\u76EE\u6807WebSocket\u5730\u5740\u4E0D\u5B58\u5728 -10098=WebSocket\u5730\u5740\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A -10099=WebSocket\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10100=WebSocket\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u786E -10101=WebSocket\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25 -10102=OTA\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10103=OTA\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10104=OTA\u5730\u5740\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10105=OTA\u5730\u5740\u5FC5\u987B\u4EE5/ota/\u7ED3\u5C3E -10106=OTA\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10107=OTA\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10108=OTA\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10109=MCP\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10110=MCP\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10111=\u4E0D\u662F\u6B63\u786E\u7684MCP\u5730\u5740 -10112=MCP\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10113=MCP\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10114=MCP\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10115=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10116=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10117=\u4E0D\u662F\u6B63\u786E\u7684\u58F0\u7EB9\u63A5\u53E3\u5730\u5740 -10118=\u58F0\u7EB9\u63A5\u53E3\u5730\u5740\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10119=\u58F0\u7EB9\u63A5\u53E3\u8BBF\u95EE\u5931\u8D25 -10120=\u58F0\u7EB9\u63A5\u53E3\u8FD4\u56DE\u5185\u5BB9\u683C\u5F0F\u4E0D\u6B63\u786E -10121=\u58F0\u7EB9\u63A5\u53E3\u9A8C\u8BC1\u5931\u8D25 -10122=mqtt\u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A -10123=\u60A8\u7684mqtt\u5BC6\u94A5\u957F\u5EA6\u4E0D\u5B89\u5168\uFF0C\u5B57\u7B26\u6570\u9700\u8981\u81F3\u5C118\u4E2A\u5B57\u7B26\u4E14\u5FC5\u987B\u540C\u65F6\u5305\u542B\u5927\u5C0F\u5199\u5B57\u6BCD -10124=\u60A8\u7684mqtt\u5BC6\u94A5\u957F\u5EA6\u4E0D\u5B89\u5168\uFF0Cmqtt\u5BC6\u94A5\u5FC5\u987B\u540C\u65F6\u5305\u542B\u5927\u5C0F\u5199\u5B57\u6BCD -10125=\u60A8\u7684mqtt\u5BC6\u94A5\u5305\u542B\u5F31\u5BC6\u7801 -10128=\u5B57\u5178\u6807\u7B7E\u91CD\u590D -10129=SM2\u5BC6\u94A5\u672A\u914D\u7F6E -10130=SM2\u89E3\u5BC6\u5931\u8D25 -10131=modelType\u548CprovideCode\u4E0D\u80FD\u4E3A\u7A7A -10132=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684\u804A\u5929\u8BB0\u5F55 -10133=\u4F1A\u8BDDID\u4E0D\u80FD\u4E3A\u7A7A -10134=\u667A\u80FD\u4F53ID\u4E0D\u80FD\u4E3A\u7A7A -10135=\u804A\u5929\u8BB0\u5F55\u4E0B\u8F7D\u5931\u8D25 -10136=\u4E0B\u8F7D\u94FE\u63A5\u5DF2\u8FC7\u671F\u6216\u65E0\u6548 -10137=\u4E0B\u8F7D\u94FE\u63A5\u65E0\u6548 -10138=\u7528\u6237 -10139=\u667A\u4F53 -10140=\u97F3\u9891\u6587\u4EF6\u4E0D\u80FD\u4E3A\u7A7A -10141=\u53EA\u652F\u6301\u97F3\u9891\u6587\u4EF6 -10142=\u97F3\u9891\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC710MB -10143=\u4E0A\u4F20\u5931\u8D25 -10144=\u58F0\u97F3\u514B\u9686\u8BB0\u5F55\u4E0D\u5B58\u5728 -10145=\u97F3\u8272\u8D44\u6E90\u4FE1\u606F\u4E0D\u80FD\u4E3A\u7A7A -10146=\u5E73\u53F0\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10147=\u97F3\u8272ID\u4E0D\u80FD\u4E3A\u7A7A -10148=\u5F52\u5C5E\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A -10149=\u5220\u9664\u7684\u97F3\u8272\u8D44\u6E90ID\u4E0D\u80FD\u4E3A\u7A7A -10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 -10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6 -10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 -10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230 -10154=\u8BAD\u7EC3\u5931\u8D25: {0} -10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E -10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5 -10157=\u8BF7\u6C42\u5931\u8D25 -10158=\u514B\u9686\u97F3\u8272: -10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 -10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934 -10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 -10162=\u6A21\u578B\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 -10163=\u77E5\u8BC6\u5E93\u8BB0\u5F55\u4E0D\u5B58\u5728 -10164=RAG\u914D\u7F6E\u672A\u627E\u5230 -10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF -10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230 -10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0} -10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25 -10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 -10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D -10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A -10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A -10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570 -10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A -10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A -10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A -10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A -10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728 -10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230 -10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u7C7B\u578B -10185=RAG\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25 -10186=\u9002\u914D\u5668\u521B\u5EFA\u5931\u8D25 -10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25 -10188=\u9002\u914D\u5668\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25 -10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u8D25 -10190=\u9002\u914D\u5668\u672A\u627E\u5230 -10191=\u9002\u914D\u5668\u7F13\u5B58\u9519\u8BEF -10192=\u9002\u914D\u5668\u7C7B\u578B\u672A\u627E\u5230 -10193=\u8BBE\u5907ID\u4E0D\u80FD\u4E3A\u7A7A -10194=\u8BBE\u5907\u4E0D\u5B58\u5728\u6216\u4E0D\u5728\u7EBF -10195=OTA\u4E0A\u4F20\u6B21\u6570\u8D85\u8FC7\u9650\u5236 -10196=\u6807\u7B7E\u540D\u79F0\u5DF2\u5B58\u5728 -10197=\u6807\u7B7E\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -10198=\u6807\u7B7E\u4E0D\u5B58\u5728 -10199=\u89E3\u6790\u4E2D\u6587\u4EF6\u6682\u4E0D\u652F\u6301\u6B64\u64CD\u4F5C -10200=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684MCP\u63A5\u5165\u70B9\u5730\u5740 -10201=\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u8FDB\u5165\u53C2\u6570\u7BA1\u7406\u914D\u7F6Emcp\u63A5\u5165\u70B9\u5730\u5740 -10202=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684MCP\u5DE5\u5177\u5217\u8868 diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties deleted file mode 100644 index 4bd8fbe8e..000000000 --- a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties +++ /dev/null @@ -1,211 +0,0 @@ -#\u7E41\u9AD4\u4E2D\u6587 -500=\u670D\u52D9\u5668\u5167\u90E8\u7570\u5E38 -401=\u672A\u6388\u6B0A -403=\u62D2\u7D55\u8A2A\u554F\uFF0C\u6C92\u6709\u6743\u9650 - -10001={0}\u4E0D\u80FD\u70BA\u7A7A -10002=\u6578\u64DA\u5EAB\u4E2D\u5DF2\u5B58\u5728\u8A72\u8A18\u9304 -10003=\u7372\u53D6\u53C3\u6578\u5931\u6557 -10004=\u8CEC\u865F\u6216\u5BC6\u78BC\u932F\u8AA4 -10005=\u8CEC\u865F\u5DF2\u88AB\u505C\u7528 -10006=\u552F\u4E00\u6A19\u8B58\u4E0D\u80FD\u70BA\u7A7A -10007=\u9A57\u8B49\u78BC\u4E0D\u6B63\u78BA -10008=\u5148\u522A\u9664\u5B50\u83DC\u55AE\u6216\u6309\u9215 -10009=\u539F\u5BC6\u78BC\u4E0D\u6B63\u78BA -10010=\u5E33\u865F\u6216\u5BC6\u78BC\u4E0D\u6B63\u78BA,\u60A8\u9084\u6709\u53EF\u4EE5\u5617\u8A66{0}\u6B21 - -10011=\u4E0A\u7D1A\u90E8\u9580\u9078\u64C7\u932F\u8AA4 -10012=\u4E0A\u7D1A\u83DC\u55AE\u4E0D\u80FD\u70BA\u81EA\u8EAB -10013=\u6578\u64DA\u6B0A\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u985E\u578B\u53C3\u6578 -10014=\u8ACB\u5148\u522A\u9664\u4E0B\u7D1A\u90E8\u9580 -10015=\u8ACB\u5148\u522A\u9664\u90E8\u9580\u4E0B\u7684\u7528\u6236 -10016=\u90E8\u7F72\u5931\u6557\uFF0C\u6C92\u6709\u6D41\u7A0B -10017=\u6A21\u578B\u5716\u4E0D\u6B63\u78BA\uFF0C\u8ACB\u6AA2\u67E5 -10018=\u5C0E\u51FA\u5931\u6557\uFF0C\u6A21\u578BID\u70BA{0} - -10019=\u8ACB\u4E0A\u50B3\u6587\u4EF6 -10020=token\u4E0D\u80FD\u70BA\u7A7A -10021=token\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u767B\u9304 -10022=\u8CEC\u865F\u5DF2\u88AB\u9396\u5B9A -10023=\u8ACB\u4E0A\u50B3zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 - -10024=\u4E0A\u50B3\u6587\u4EF6\u5931\u6557{0} -10025=\u767C\u9001\u77ED\u4FE1\u5931\u6557{0} -10026=\u90F5\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 - -10027=Redis\u670D\u52D9\u7570\u5E38 -10028=\u5B9A\u6642\u4EFB\u52D9\u5931\u6557 -10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 -10030=\u5BC6\u78BC\u9577\u5EA6\u4E0D\u8DB3{0}\u4F4D -10031=\u5BC6\u78BC\u5FC5\u9808\u540C\u6642\u5305\u542B\u6578\u5B57\u3001\u5927\u5C0F\u5BEB\u5B57\u6BCD\u548C\u7279\u6B8A\u5B57\u7B26\u7D44\u6210 -10032=\u522A\u9664\u672C\u6578\u64DA\u7570\u5E38 -10033=\u8A2D\u5099\u9A57\u8B49\u78BC\u932F\u8AA4 - -10034=\u53C3\u6578\u503C\u4E0D\u80FD\u70BA\u7A7A -10035=\u53C3\u6578\u985E\u578B\u4E0D\u80FD\u70BA\u7A7A -10036=\u4E0D\u652F\u6301\u7684\u53C3\u6578\u985E\u578B -10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57 -10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false -10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F -10040=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u683C\u5F0F - -10041=\u8A2D\u5099\u672A\u627E\u5230 -10042={0} -10043=\u522A\u9664\u6578\u64DA\u5931\u6557 -10044=\u7528\u6236\u672A\u767B\u9304 -10045=WebSocket\u9023\u63A5\u5931\u6557\u6216\u9023\u63A5\u8D85\u6642 -10046=\u4FDD\u5B58\u8072\u7D0B\u932F\u8AA4\uFF0C\u8ACB\u806F\u7E6B\u7BA1\u7406\u54E1 -10047=\u6BCF\u65E5\u767C\u9001\u6B21\u6578\u5DF2\u9054\u4E0A\u9650 -10048=\u820A\u5BC6\u78BC\u8F38\u5165\u932F\u8AA4 -10049=\u8A2D\u7F6E\u7684LLM\u4E0D\u662Fopenai\u548Collama -10050=token\u751F\u6210\u5931\u6557 -10051=\u8CC7\u6E90\u4E0D\u5B58\u5728 -10052=\u9ED8\u8A8D\u667A\u80FD\u9AD4\u672A\u627E\u5230 -10053=\u667A\u80FD\u9AD4\u672A\u627E\u5230 -10054=\u8072\u7D0B\u63A5\u53E3\u672A\u914D\u7F6E\uFF0C\u8ACB\u5148\u5728\u53C3\u6578\u914D\u7F6E\u4E2D\u914D\u7F6E\u8072\u7D0B\u63A5\u53E3\u5730\u5740(server.voice_print) -10055=\u77ED\u4FE1\u767C\u9001\u5931\u6557 -10056=\u77ED\u4FE1\u9023\u63A5\u5EFA\u7ACB\u5931\u6557 -10057=\u667A\u80FD\u9AD4\u7684\u8072\u7D0B\u5275\u5EFA\u5931\u6557 -10058=\u667A\u80FD\u9AD4\u7684\u5C0D\u61C9\u8072\u7D0B\u66F4\u65B0\u5931\u6557 -10059=\u667A\u80FD\u9AD4\u7684\u5C0D\u61C9\u8072\u7D0B\u522A\u9664\u5931\u6557 -10060=\u767C\u9001\u592A\u983B\u7E41\uFF0C\u8ACB{0}\u79D2\u5F8C\u518D\u8A66 -10061=\u6FC0\u6D3B\u78BC\u4E0D\u80FD\u70BA\u7A7A -10062=\u6FC0\u6D3B\u78BC\u932F\u8AA4 -10063=\u8A2D\u5099\u5DF2\u6FC0\u6D3B -10064=\u8A72\u6A21\u578B\u70BA\u9810\u8A2D\u6A21\u578B\uFF0C\u8ACB\u5148\u8A2D\u7F6E\u5176\u4ED6\u6A21\u578B\u70BA\u9810\u8A2D\u6A21\u578B -10065=\u65B0\u589E\u6578\u64DA\u5931\u6557 -10066=\u66F4\u65B0\u6578\u64DA\u5931\u6557 -10067=\u5716\u5F62\u9A57\u8B49\u78BC\u932F\u8AA4 -10068=\u672A\u958B\u555F\u624B\u6A5F\u8A3B\u518A\uFF0C\u7121\u6CD5\u4F7F\u7528\u77ED\u4FE1\u9A57\u8B49\u78BC\u529F\u80FD -10069=\u7528\u6236\u540D\u4E0D\u662F\u624B\u6A5F\u865F\u78BC\uFF0C\u8ACB\u91CD\u65B0\u8F38\u5165 -10070=\u8A72\u624B\u6A5F\u865F\u78BC\u5DF2\u8A3B\u518A -10071=\u8F38\u5165\u7684\u624B\u6A5F\u865F\u78BC\u672A\u8A3B\u518A -10072=\u76EE\u524D\u4E0D\u5141\u8A31\u666E\u901A\u7528\u6236\u8A3B\u518A -10073=\u672A\u958B\u555F\u624B\u6A5F\u8A3B\u518A\uFF0C\u7121\u6CD5\u4F7F\u7528\u5BC6\u78BC\u627E\u56DE\u529F\u80FD -10074=\u8F38\u5165\u7684\u624B\u6A5F\u865F\u78BC\u683C\u5F0F\u4E0D\u6B63\u78BA -10075=\u8F38\u5165\u7684\u77ED\u4FE1\u9A57\u8B49\u78BC\u4E0D\u6B63\u78BA -10076=\u5B57\u5178\u985E\u578B\u4E0D\u5B58\u5728 -10077=\u5B57\u5178\u985E\u578B\u7DE8\u78BC\u91CD\u8907 -10078=\u8B80\u53D6\u8CC7\u6E90\u5931\u6557 -10079=LLM\u6A21\u578B\u8207\u610F\u5716\u8B58\u5225\u3001\u53C3\u6578\u9078\u64C7\u4E0D\u5339\u914D -10080=\u6B64\u8072\u7D0B\u5C6C\u65BC\u5DF2\u8A3B\u518A\u7684{0}\uFF0C\u8ACB\u9078\u64C7\u5176\u4ED6\u8072\u97F3 -10081=\u522A\u9664\u8072\u7D0B\u6642\u767C\u751F\u932F\u8AA4 -10082=\u4E0D\u5141\u8A31\u4FEE\u6539\uFF0C\u6B64\u8072\u97F3\u5DF2\u8A3B\u518A\u70BA\u8072\u7D0B({0}) -10083=\u4FEE\u6539\u8072\u7D0B\u932F\u8AA4\uFF0C\u8ACB\u806F\u7E6B\u7BA1\u7406\u54E1 -10084=\u8072\u7D0B\u63A5\u53E3\u5730\u5740\u932F\u8AA4\uFF0C\u8ACB\u524D\u5F80\u53C3\u6578\u7BA1\u7406\u4FEE\u6539\u8072\u7D0B\u63A5\u53E3\u5730\u5740 -10085=\u97F3\u983B\u6578\u64DA\u4E0D\u5C6C\u65BC\u6B64\u667A\u80FD\u9AD4 -10086=\u97F3\u983B\u6578\u64DA\u70BA\u7A7A\uFF0C\u8ACB\u6AA2\u67E5\u4E0A\u50B3\u6578\u64DA -10087=\u8072\u7D0B\u8A3B\u518A\u5931\u6557\uFF0C\u8ACB\u6C42\u672A\u6210\u529F -10088=\u8072\u7D0B\u8A3B\u518A\u5931\u6557\uFF0C\u8ACB\u6C42\u8655\u7406\u5931\u6557 -10089=\u8072\u7D0B\u8A3B\u92B7\u5931\u6557\uFF0C\u8ACB\u6C42\u672A\u6210\u529F -10090=\u8072\u7D0B\u8A3B\u92B7\u5931\u6557\uFF0C\u8ACB\u6C42\u8655\u7406\u5931\u6557 -10091=\u6A21\u578B\u63D0\u4F9B\u5546\u4E0D\u5B58\u5728 -10092=\u914D\u7F6E\u7684LLM\u4E0D\u5B58\u5728 -10093=\u6B64\u6A21\u578B\u914D\u7F6E\u88AB\u667A\u80FD\u9AD4{0}\u5F15\u7528\uFF0C\u7121\u6CD5\u522A\u9664 -10094=\u6B64LLM\u6A21\u578B\u88AB\u610F\u5716\u8B58\u5225\u914D\u7F6E\u5F15\u7528\uFF0C\u7121\u6CD5\u522A\u9664 -10095=\u7121\u6548\u7684\u670D\u52D9\u5668\u64CD\u4F5C -10096=\u672A\u914D\u7F6E\u670D\u52D9\u5668WebSocket\u5730\u5740 -10097=\u76EE\u6A19WebSocket\u5730\u5740\u4E0D\u5B58\u5728 -10098=WebSocket\u5730\u5740\u5217\u8868\u4E0D\u80FD\u70BA\u7A7A -10099=WebSocket\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10100=WebSocket\u5730\u5740\u683C\u5F0F\u4E0D\u6B63\u78BA -10101=WebSocket\u9023\u63A5\u6E2C\u8A66\u5931\u6557 -10102=OTA\u5730\u5740\u4E0D\u80FD\u70BA\u7A7A -10103=OTA\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10104=OTA\u5730\u5740\u5FC5\u9808\u4EE5http\u6216https\u958B\u982D -10105=OTA\u5730\u5740\u5FC5\u9808\u4EE5/ota/\u7D50\u5C3E -10106=OTA\u63A5\u53E3\u8A2A\u554F\u5931\u6557 -10107=OTA\u63A5\u53E3\u8FD4\u56DE\u5167\u5BB9\u683C\u5F0F\u4E0D\u6B63\u78BA -10108=OTA\u63A5\u53E3\u9A57\u8B49\u5931\u6557 -10109=MCP\u5730\u5740\u4E0D\u80FD\u70BA\u7A7A -10110=MCP\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10111=\u4E0D\u662F\u6709\u6548\u7684MCP\u5730\u5740 -10112=MCP\u63A5\u53E3\u8A2A\u554F\u5931\u6557 -10113=MCP\u63A5\u53E3\u8FD4\u56DE\u5167\u5BB9\u683C\u5F0F\u4E0D\u6B63\u78BA -10114=MCP\u63A5\u53E3\u9A57\u8B49\u5931\u6557 -10115=\u8072\u7D0B\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u70BA\u7A7A -10116=\u8072\u7D0B\u63A5\u53E3\u5730\u5740\u4E0D\u80FD\u4F7F\u7528localhost\u6216127.0.0.1 -10117=\u4E0D\u662F\u6709\u6548\u7684\u8072\u7D0B\u63A5\u53E3\u5730\u5740 -10118=\u8072\u7D0B\u63A5\u53E3\u5730\u5740\u5FC5\u9808\u4EE5http\u6216https\u958B\u982D -10119=\u8072\u7D0B\u63A5\u53E3\u8A2A\u554F\u5931\u6557 -10120=\u8072\u7D0B\u63A5\u53E3\u8FD4\u56DE\u5167\u5BB9\u683C\u5F0F\u4E0D\u6B63\u78BA -10121=\u8072\u7D0B\u63A5\u53E3\u9A57\u8B49\u5931\u6557 -10122=MQTT\u5BC6\u9470\u4E0D\u80FD\u70BA\u7A7A -10123=\u60A8\u7684MQTT\u5BC6\u9470\u4E0D\u5B89\u5168\uFF0C\u9700\u81F3\u5C118\u500B\u5B57\u7B26\u4E14\u5FC5\u9808\u540C\u6642\u5305\u542B\u5927\u5C0F\u5BEB\u5B57\u6BCD -10124=\u60A8\u7684MQTT\u5BC6\u9470\u4E0D\u5B89\u5168\uFF0CMQTT\u5BC6\u9470\u5FC5\u9808\u540C\u6642\u5305\u542B\u5927\u5C0F\u5BEB\u5B57\u6BCD -10125=\u60A8\u7684MQTT\u5BC6\u9470\u5305\u542B\u5F31\u5BC6\u78BC -10128=\u5B57\u5178\u6A19\u7C64\u91CD\u8907 -10129=SM2\u5BC6\u9470\u672A\u914D\u7F6E -10130=SM2\u89E3\u5BC6\u5931\u6557 -10131=modelType\u548CprovideCode\u4E0D\u80FD\u70BA\u7A7A -10132=\u6C92\u6709\u6B0A\u9650\u67E5\u770B\u8A72\u667A\u80FD\u9AD4\u7684\u804A\u5929\u8A18\u9304 -10133=\u6703\u8A71ID\u4E0D\u80FD\u70BA\u7A7A -10134=\u667A\u80FD\u9AD4ID\u4E0D\u80FD\u70BA\u7A7A -10135=\u804A\u5929\u8A18\u9304\u4E0B\u8F09\u5931\u6557 -10136=\u4E0B\u8F09\u93C8\u63A5\u5DF2\u904E\u671F\u6216\u7121\u6548 -10137=\u4E0B\u8F09\u93C8\u63A5\u7121\u6548 -10138=\u7528\u6236 -10139=\u667A\u9AD4 -10140=\u97F3\u983B\u6587\u4EF6\u4E0D\u80FD\u70BA\u7A7A -10141=\u53EA\u652F\u6301\u97F3\u983B\u6587\u4EF6 -10142=\u97F3\u983B\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u904E10MB -10143=\u4E0A\u50B3\u5931\u6557 -10144=\u8072\u97F3\u514B\u9686\u8A18\u9304\u4E0D\u5B58\u5728 -10145=\u97F3\u8272\u8CC7\u6E90\u4FE1\u606F\u4E0D\u80FD\u70BA\u7A7A -10146=\u5E73\u53F0\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A -10147=\u97F3\u8272ID\u4E0D\u80FD\u70BA\u7A7A -10148=\u6B78\u5C6C\u5E33\u865F\u4E0D\u80FD\u70BA\u7A7A -10149=\u522A\u9664\u7684\u97F3\u8272\u8CC7\u6E90ID\u4E0D\u80FD\u70BA\u7A7A -10150=\u60A8\u6C92\u6709\u6B0A\u9650\u64CD\u4F5C\u8A72\u8A18\u9304 -10151=\u8ACB\u5148\u4E0A\u50B3\u97F3\u983B\u6587\u4EF6 -10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 -10153=\u6A21\u578B\u985E\u578B\u672A\u627E\u5230 -10154=\u6A21\u578B\u8AB2\u7DF4\u5931\u6557: {0} -10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11appid\u6216access_token -10156=\u97FF\u61C9\u683C\u5F0F\u932F\u8AA4\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5 -10157=\u8ACB\u6C42\u5931\u6557 -10158=\u514B\u9686\u97F3\u8272: -10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 -10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u932F\u8AA4\uFF0C\u5FC5\u9808\u4EE5S_\u958B\u982D -10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 -10162=\u6A21\u578B\u63D0\u4F9B\u5546\u4E0D\u5B58\u5728 -10163=\u77E5\u8B58\u5EAB\u8A18\u9304\u4E0D\u5B58\u5728 -10164=RAG\u914D\u7F6E\u672A\u627E\u5230 -10165=RAG\u914D\u7F6E\u985E\u578B\u932F\u8AA4 -10166=\u9810\u8A2DRAG\u914D\u7F6E\u672A\u627E\u5230 -10167=RAG\u8ABF\u7528\u5931\u6557\uFF0C{0} -10168=\u4E0A\u50B3\u6587\u4EF6\u5931\u6557 -10169=\u60A8\u6C92\u6709\u6B0A\u9650\u64CD\u4F5C\u8A72\u8A18\u9304 -10170=\u77E5\u8B58\u5EAB\u540D\u7A31\u91CD\u8907 -10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A -10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A -10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570 -10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934 -10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A -10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A -10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A -10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A -10179=\u6587\u4EF6\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A -10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u70BA\u7A7A -10181=\u97F3\u8272\u514B\u9686\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A -10182=\u97F3\u8272\u514B\u9686\u97F3\u983B\u4E0D\u5B58\u5728 -10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230 -10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u985E\u578B -10185=RAG\u914D\u7F6E\u9A57\u8B49\u5931\u6557 -10186=\u9002\u914D\u5668\u5275\u5EFA\u5931\u6557 -10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u6557 -10188=\u9002\u914D\u5668\u9023\u63A5\u6E2C\u8A66\u5931\u6557 -10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u6557 -10190=\u9002\u914D\u5668\u672A\u627E\u5230 -10191=\u9002\u914D\u5668\u7F13\u5B58\u932F\u8AA4 -10192=\u9002\u914D\u5668\u985E\u578B\u672A\u627E\u5230 -10193=\u8A2D\u5099ID\u4E0D\u80FD\u4E3A\u7A7A -10194=\u8A2D\u5099\u4E0D\u5B58\u5728\u6216\u672A\u5728\u7DDA -10195=OTA\u4E0A\u4F20\u6B21\u6578\u8D85\u904E\u9650\u5236 -10196=\u6A19\u7C64\u540D\u7A31\u5DF2\u5B58\u5728 -10197=\u6A19\u7C64\u540D\u7A31\u4E0D\u80FD\u4E3A\u7A7A -10198=\u6A19\u7C64\u4E0D\u5B58\u5728 -10199=\u89E3\u6790\u4E2D\u6587\u4EF6\u66AB\u4E0D\u652F\u6301\u6B64\u64CD\u4F5C -10200=\u6C92\u6709\u6B0A\u9650\u67E5\u770B\u8A72\u667A\u80FD\u9AD4\u7684MCP\u63A5\u5165\u9EDE\u5730\u5740 -10201=\u8ACB\u806F\u7E6B\u7BA1\u7406\u54E1\u9032\u5165\u53C3\u6578\u7BA1\u7406\u914D\u7F6Emcp\u63A5\u5165\u9EDE\u5730\u5740 -10202=\u6C92\u6709\u6B0A\u9650\u67E5\u770B\u8A72\u667A\u80FD\u9AD4\u7684MCP\u5DE5\u5177\u5217\u8868 diff --git a/main/manager-api/src/main/resources/i18n/validation_en_GB.properties b/main/manager-api/src/main/resources/i18n/validation_en_GB.properties new file mode 100644 index 000000000..a20eada5d --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/validation_en_GB.properties @@ -0,0 +1,34 @@ +#English (UK) +id.require=ID cannot be empty +id.null=ID must be empty + +sort.number=The sort value cannot be less than 0 +page.number=The page value cannot be less than 0 +limit.number=The limit value cannot be less than 0 + +sysdict.type.require=The dictionary type cannot be empty +sysdict.name.require=The dictionary name cannot be empty +sysdict.label.require=Dictionary tag cannot be empty + +sysparams.paramcode.require=Parameter encoding cannot be empty +sysparams.paramvalue.require=Parameter values cannot be empty +sysparams.valuetype.require=Value type cannot be empty +sysparams.valuetype.pattern=Value type must be string, number, boolean or array + +sysuser.username.require=The username cannot be empty +sysuser.password.require=The password cannot be empty +sysuser.realname.require=The real name cannot be empty +sysuser.gender.range=Gender ranges from 0 to 2 +sysuser.email.error=Incorrect email format +sysuser.deptId.require=Departments cannot be empty +sysuser.status.range=State ranges from 0 to 1 +sysuser.captcha.require=The captcha cannot be empty +sysuser.uuid.require=The unique identifier cannot be empty + +timbre.languages.require=The language of the timbre cannot be empty +timbre.name.require=The name of the timbre cannot be empty +timbre.ttsModelId.require=The TTS model ID of the timbre cannot be empty +timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty + +ota.device.not.found=Device not found +ota.device.need.bind={0} diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties deleted file mode 100644 index 786004299..000000000 --- a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties +++ /dev/null @@ -1,34 +0,0 @@ -#\u7B80\u4F53\u4E2D\u6587 -id.require=ID\u4E0D\u80FD\u4E3A\u7A7A -id.null=ID\u5FC5\u987B\u4E3A\u7A7A - -sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 -page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0 -limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0 - -sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A -sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -sysdict.label.require=\u5B57\u5178\u6807\u7B7E\u4E0D\u80FD\u4E3A\u7A7A - -sysparams.paramcode.require=\u53C2\u6570\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A -sysparams.paramvalue.require=\u53C2\u6570\u503C\u4E0D\u80FD\u4E3A\u7A7A -sysparams.valuetype.require=\u503C\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A -sysparams.valuetype.pattern=\u503C\u7C7B\u578B\u5FC5\u987B\u662F string\u3001number\u3001boolean \u6216 array - -sysuser.username.require=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A -sysuser.password.require=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A -sysuser.realname.require=\u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A -sysuser.gender.range=\u6027\u522B\u53D6\u503C\u8303\u56F40~2 -sysuser.email.error=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E -sysuser.deptId.require=\u90E8\u95E8\u4E0D\u80FD\u4E3A\u7A7A -sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 -sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A -sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A - -timbre.languages.require=\u97F3\u8272\u7684\u8BED\u8A00\u4E0D\u80FD\u4E3A\u7A7A -timbre.name.require=\u97F3\u8272\u7684\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u80FD\u4E3A\u7A7A -timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A - -ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230 -ota.device.need.bind={0} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties deleted file mode 100644 index 4e3a271ae..000000000 --- a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties +++ /dev/null @@ -1,34 +0,0 @@ -#\u7B80\u4F53\u4E2D\u6587 -id.require=ID\u4E0D\u80FD\u4E3A\u7A7A -id.null=ID\u5FC5\u987B\u4E3A\u7A7A - -sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 -page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0 -limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0 - -sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A -sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A -sysdict.label.require=\u5B57\u5178\u6807\u7B7E\u4E0D\u80FD\u4E3A\u7A7A - -sysparams.paramcode.require=\u53C3\u6578\u7DE8\u78BC\u4E0D\u80FD\u70BA\u7A7A -sysparams.paramvalue.require=\u53C3\u6578\u503C\u4E0D\u80FD\u70BA\u7A7A -sysparams.valuetype.require=\u503C\u985E\u578B\u4E0D\u80FD\u70BA\u7A7A -sysparams.valuetype.pattern=\u503C\u985E\u578B\u5FC5\u9808\u662F string\u3001number\u3001boolean \u6216 array - -sysuser.username.require=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A -sysuser.password.require=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A -sysuser.realname.require=\u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A -sysuser.gender.range=\u6027\u522B\u53D6\u503C\u8303\u56F40~2 -sysuser.email.error=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E -sysuser.deptId.require=\u90E8\u95E8\u4E0D\u80FD\u4E3A\u7A7A -sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 -sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A -sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A - -timbre.languages.require=\u97F3\u8272\u7684\u8BED\u8A00\u4E0D\u53EF\u4EE5\u4E3A\u7A7A -timbre.name.require=\u97F3\u8272\u7684\u540D\u79F0\u4E0D\u53EF\u4EE5\u4E3A\u7A7A -timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A -timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A - -ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230 -ota.device.need.bind={0} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/logback-spring.xml b/main/manager-api/src/main/resources/logback-spring.xml index c69d03c03..5a9a8fd23 100644 --- a/main/manager-api/src/main/resources/logback-spring.xml +++ b/main/manager-api/src/main/resources/logback-spring.xml @@ -1,24 +1,24 @@ - + - + - + - + ${LOG_HOME} true - + - + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}) - %msg%n @@ -26,7 +26,7 @@ - + ${LOG_HOME}/xiaozhi-esp32-api.log @@ -41,7 +41,7 @@ - + ${LOG_HOME}/error.log @@ -59,11 +59,11 @@ - + - + @@ -72,7 +72,7 @@ - + @@ -84,9 +84,9 @@ - + - + ${LOG_HOME}/xiaozhi-esp32-api.log @@ -101,7 +101,7 @@ - + ${LOG_HOME}/error.log @@ -119,20 +119,20 @@ - + - + - + true diff --git a/main/manager-api/src/main/resources/lua/getKeyOrCreate.lua b/main/manager-api/src/main/resources/lua/getKeyOrCreate.lua index bc375b120..81dc433d8 100644 --- a/main/manager-api/src/main/resources/lua/getKeyOrCreate.lua +++ b/main/manager-api/src/main/resources/lua/getKeyOrCreate.lua @@ -1,8 +1,8 @@ local value = redis.call('GET', KEYS[1]) --- value 如果为空着设置值 +-- If value is empty, set the value if not value then local result = redis.call('SET', KEYS[1], ARGV[1]) - -- 检查 ARGV[2] 是否存在且大于 0 + -- Check if ARGV[2] exists and is greater than 0 local expireTime = tonumber(ARGV[2]) if expireTime and expireTime > 0 then redis.call('EXPIRE', KEYS[1], expireTime) diff --git a/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml b/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml index c250afe31..988e010f2 100644 --- a/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml +++ b/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml @@ -1,7 +1,7 @@ - + diff --git a/main/manager-api/src/main/resources/mapper/agent/AgentPluginMappingMapper.xml b/main/manager-api/src/main/resources/mapper/agent/AgentPluginMappingMapper.xml index 659fcd6e4..f80162102 100644 --- a/main/manager-api/src/main/resources/mapper/agent/AgentPluginMappingMapper.xml +++ b/main/manager-api/src/main/resources/mapper/agent/AgentPluginMappingMapper.xml @@ -11,7 +11,7 @@ - + diff --git a/main/manager-api/src/main/resources/mapper/device/DeviceDao.xml b/main/manager-api/src/main/resources/mapper/device/DeviceDao.xml index 54de47c92..9e26b620c 100644 --- a/main/manager-api/src/main/resources/mapper/device/DeviceDao.xml +++ b/main/manager-api/src/main/resources/mapper/device/DeviceDao.xml @@ -1,7 +1,7 @@ - + select model_name from ai_model_config where model_type = #{modelType} and model_name = #{modelName} - + - \ No newline at end of file + diff --git a/main/manager-api/src/main/resources/mapper/model/ModelProviderDao.xml b/main/manager-api/src/main/resources/mapper/model/ModelProviderDao.xml index b17e24fce..d66715b0d 100644 --- a/main/manager-api/src/main/resources/mapper/model/ModelProviderDao.xml +++ b/main/manager-api/src/main/resources/mapper/model/ModelProviderDao.xml @@ -2,7 +2,7 @@ - + diff --git a/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml index 8faf43116..6b193d5b5 100644 --- a/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml +++ b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml @@ -3,12 +3,12 @@ - + - + - + update sys_params set param_value = #{paramValue} where param_code = #{paramCode} diff --git a/main/manager-api/src/test/java/xiaozhi/common/utils/AESUtilsTest.java b/main/manager-api/src/test/java/xiaozhi/common/utils/AESUtilsTest.java index c4f371157..87eb0a60e 100644 --- a/main/manager-api/src/test/java/xiaozhi/common/utils/AESUtilsTest.java +++ b/main/manager-api/src/test/java/xiaozhi/common/utils/AESUtilsTest.java @@ -9,40 +9,40 @@ public class AESUtilsTest { @Test public void testEncryptAndDecrypt() { String key = "xiaozhi1234567890"; - String plainText = "Hello, 小智!"; + String plainText = "Hello, Xiaozhi!"; - System.out.println("原始文本: " + plainText); - System.out.println("密钥: " + key); + System.out.println("Original text: " + plainText); + System.out.println("Key: " + key); - // 加密 + // Encrypt String encrypted = AESUtils.encrypt(key, plainText); - System.out.println("加密结果: " + encrypted); + System.out.println("Encryption result: " + encrypted); - // 解密 + // Decrypt String decrypted = AESUtils.decrypt(key, encrypted); - System.out.println("解密结果: " + decrypted); + System.out.println("Decryption result: " + decrypted); - // 验证 - assertEquals(plainText, decrypted, "加解密结果应该一致"); - System.out.println("加解密一致性: " + plainText.equals(decrypted)); + // Verify + assertEquals(plainText, decrypted, "Encryption and decryption results should be consistent"); + System.out.println("Encryption and decryption consistency: " + plainText.equals(decrypted)); } @Test public void testDifferentKeyLengths() { String[] keys = { - "1234567890123456", // 16位 - "123456789012345678901234", // 24位 - "12345678901234567890123456789012", // 32位 - "short", // 短密钥 - "verylongkeythatwillbetruncatedto32bytes" // 长密钥 + "1234567890123456", // 16 bits + "123456789012345678901234", // 24 bits + "12345678901234567890123456789012", // 32 bits + "short", // Short key + "verylongkeythatwillbetruncatedto32bytes" // Long key }; - String plainText = "测试文本"; + String plainText = "Test text"; for (String key : keys) { String encrypted = AESUtils.encrypt(key, plainText); String decrypted = AESUtils.decrypt(key, encrypted); - assertEquals(plainText, decrypted, "密钥长度: " + key.length()); + assertEquals(plainText, decrypted, "Key length: " + key.length()); } } @@ -51,35 +51,35 @@ public class AESUtilsTest { String key = "xiaozhi1234567890"; String[] testTexts = { "Hello World", - "你好世界", - "Hello, 小智!", - "特殊字符: !@#$%^&*()", - "数字123和中文混合", + "Hello World", + "Hello, Xiaozhi!", + "Special characters: !@#$%^&*()", + "Numbers 123 and mixed text", "Emoji: 😀🎉🚀", - "空字符串测试", + "Empty string test", "" }; for (String text : testTexts) { String encrypted = AESUtils.encrypt(key, text); String decrypted = AESUtils.decrypt(key, encrypted); - assertEquals(text, decrypted, "测试文本: " + text); + assertEquals(text, decrypted, "Test text: " + text); } } @Test public void testCrossLanguageCompatibility() { - // 这些是Python版本生成的加密结果,用于测试跨语言兼容性 + // These are encryption results generated by Python version, used for cross-language compatibility testing String key = "xiaozhi1234567890"; - String plainText = "Hello, 小智!"; + String plainText = "Hello, Xiaozhi!"; - // Python版本生成的加密结果(需要运行Python测试后获取) - // String pythonEncrypted = "从Python测试中获取的加密结果"; + // Encryption results generated by Python version (need to run Python tests to obtain) + // String pythonEncrypted = "Encrypted result obtained from Python test"; // String decrypted = AESUtils.decrypt(key, pythonEncrypted); - // assertEquals(plainText, decrypted, "Java应该能解密Python加密的结果"); + // assertEquals(plainText, decrypted, "Java should be able to decrypt Python encrypted results"); - // 生成Java加密结果供Python测试 + // Generate Java encryption results for Python testing String javaEncrypted = AESUtils.encrypt(key, plainText); - System.out.println("Java加密结果供Python测试: " + javaEncrypted); + System.out.println("Java encryption result for Python testing: " + javaEncrypted); } } \ No newline at end of file diff --git a/main/manager-api/src/test/java/xiaozhi/config/TestConfig.java b/main/manager-api/src/test/java/xiaozhi/config/TestConfig.java new file mode 100644 index 000000000..143df10ce --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/config/TestConfig.java @@ -0,0 +1,138 @@ +package xiaozhi.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; + +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.security.service.CaptchaService; + +/** + * Test configuration for mocking external services + */ +@TestConfiguration +@Profile("test") +public class TestConfig { + + /** + * Mock Redis connection factory for testing + */ + @Bean + @Primary + public RedisConnectionFactory redisConnectionFactory() { + // Return a mock or in-memory Redis connection factory + // For now, we'll use LettuceConnectionFactory with localhost + // In a real scenario, you might want to use embedded Redis + return new LettuceConnectionFactory(); + } + + /** + * Mock RedisUtils for testing + */ + @Bean + @Primary + public RedisUtils redisUtils() { + return new MockRedisUtils(); + } + + /** + * Mock CaptchaService for testing + */ + @Bean + @Primary + public CaptchaService captchaService() { + return new MockCaptchaService(); + } + + /** + * Mock implementation of RedisUtils for testing + */ + public static class MockRedisUtils extends RedisUtils { + private final java.util.Map mockCache = new java.util.concurrent.ConcurrentHashMap<>(); + private final java.util.Map> mockHashCache = new java.util.concurrent.ConcurrentHashMap<>(); + + public void set(String key, Object value) { + mockCache.put(key, value); + } + + public void set(String key, Object value, long timeout) { + mockCache.put(key, value); + } + + public Object get(String key) { + return mockCache.get(key); + } + + public void delete(String key) { + mockCache.remove(key); + } + + public boolean hasKey(String key) { + return mockCache.containsKey(key); + } + + public void clear() { + mockCache.clear(); + mockHashCache.clear(); + } + + // Mock hash operations + public Object hGet(String key, String field) { + java.util.Map hash = mockHashCache.get(key); + return hash != null ? hash.get(field) : null; + } + + public void hSet(String key, String field, Object value) { + mockHashCache.computeIfAbsent(key, k -> new java.util.concurrent.ConcurrentHashMap<>()).put(field, value); + } + + public java.util.Map hGetAll(String key) { + return mockHashCache.getOrDefault(key, new java.util.HashMap<>()); + } + + public void hDel(String key, String... fields) { + java.util.Map hash = mockHashCache.get(key); + if (hash != null) { + for (String field : fields) { + hash.remove(field); + } + } + } + + public boolean hExists(String key, String field) { + java.util.Map hash = mockHashCache.get(key); + return hash != null && hash.containsKey(field); + } + } + + /** + * Mock implementation of CaptchaService for testing + */ + public static class MockCaptchaService implements CaptchaService { + + @Override + public void create(jakarta.servlet.http.HttpServletResponse response, String uuid) throws java.io.IOException { + // Mock implementation - do nothing + } + + @Override + public boolean validate(String uuid, String code, Boolean delete) { + // Always return true for testing + return true; + } + + @Override + public void sendSMSValidateCode(String phone) { + // Mock implementation - do nothing + } + + @Override + public boolean validateSMSValidateCode(String phone, String code, Boolean delete) { + // Always return true for testing + return true; + } + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java index 37f67cab6..5a874e533 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java @@ -9,18 +9,24 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.context.annotation.Import; import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import xiaozhi.common.redis.RedisUtils; import xiaozhi.modules.sys.dto.SysUserDTO; import xiaozhi.modules.sys.service.SysUserService; @Slf4j @SpringBootTest -@ActiveProfiles("dev") -@DisplayName("设备测试") +@ActiveProfiles("test") +@Import(xiaozhi.config.TestConfig.class) +@DisplayName("Device Test") public class DeviceTest { + private static final Logger log = LoggerFactory.getLogger(DeviceTest.class); + @Autowired private RedisUtils redisUtils; @Autowired @@ -30,23 +36,23 @@ public class DeviceTest { public void testSaveUser() { SysUserDTO userDTO = new SysUserDTO(); userDTO.setUsername("test"); - userDTO.setPassword(UUID.randomUUID().toString()); + userDTO.setPassword("TestPassword123!"); sysUserService.save(userDTO); } @Test - @DisplayName("测试写入设备信息") + @DisplayName("Test writing device information") public void testWriteDeviceInfo() { - log.info("开始测试写入设备信息..."); - // 模拟设备MAC地址 + log.info("Starting test for writing device information..."); + // Simulate device MAC address String macAddress = "00:11:22:33:44:66"; - // 模拟设备验证码 + // Simulate device verification code String deviceCode = "123456"; HashMap map = new HashMap<>(); map.put("mac_address", macAddress); map.put("activation_code", deviceCode); - map.put("board", "硬件型号"); + map.put("board", "Hardware Model"); map.put("app_version", "0.3.13"); String safeDeviceId = macAddress.replace(":", "_").toLowerCase(); @@ -56,18 +62,18 @@ public class DeviceTest { String redisKey = "ota:activation:code:" + deviceCode; log.info("Redis Key: {}", redisKey); - // 将设备信息写入Redis + // Write device information to Redis redisUtils.set(redisKey, macAddress, 300); - log.info("设备信息已写入Redis"); + log.info("Device information has been written to Redis"); - // 验证是否写入成功 + // Verify if write was successful String savedMacAddress = (String) redisUtils.get(redisKey); - log.info("从Redis读取的MAC地址: {}", savedMacAddress); + log.info("MAC address read from Redis: {}", savedMacAddress); - // 使用断言验证 - Assertions.assertNotNull(savedMacAddress, "从Redis读取的MAC地址不应为空"); - Assertions.assertEquals(macAddress, savedMacAddress, "保存的MAC地址与原始MAC地址不匹配"); + // Use assertions for verification + Assertions.assertNotNull(savedMacAddress, "MAC address read from Redis should not be null"); + Assertions.assertEquals(macAddress, savedMacAddress, "Saved MAC address does not match original MAC address"); - log.info("测试完成"); + log.info("Test completed"); } } \ No newline at end of file diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/H2JsonFunctions.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/H2JsonFunctions.java new file mode 100644 index 000000000..8089c6211 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/H2JsonFunctions.java @@ -0,0 +1,195 @@ +package xiaozhi.modules.sys; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.IOException; + +public final class H2JsonFunctions { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private H2JsonFunctions() { + } + + public static String jsonSet(String json, String path1, String value1) throws IOException { + ObjectNode root = asObjectNode(json); + setJsonPath(root, path1, value1); + return OBJECT_MAPPER.writeValueAsString(root); + } + + public static String jsonSet(String json, String path1, String value1, String path2, String value2) throws IOException { + ObjectNode root = asObjectNode(json); + setJsonPath(root, path1, value1); + setJsonPath(root, path2, value2); + return OBJECT_MAPPER.writeValueAsString(root); + } + + public static String jsonSet( + String json, + String path1, + String value1, + String path2, + String value2, + String path3, + String value3 + ) throws IOException { + ObjectNode root = asObjectNode(json); + setJsonPath(root, path1, value1); + setJsonPath(root, path2, value2); + setJsonPath(root, path3, value3); + return OBJECT_MAPPER.writeValueAsString(root); + } + + public static String jsonRemove(String json, String path) throws IOException { + ObjectNode root = asObjectNode(json); + String[] tokens = tokenizePath(path); + ObjectNode current = root; + for (int i = 0; i < tokens.length - 1; i++) { + JsonNode next = current.get(tokens[i]); + if (!(next instanceof ObjectNode)) { + return OBJECT_MAPPER.writeValueAsString(root); + } + current = (ObjectNode) next; + } + current.remove(tokens[tokens.length - 1]); + return OBJECT_MAPPER.writeValueAsString(root); + } + + public static String jsonRemove(String json, String path1, String path2) throws IOException { + return jsonRemove(jsonRemove(json, path1), path2); + } + + public static String jsonRemove(String json, String path1, String path2, String path3) throws IOException { + return jsonRemove(jsonRemove(json, path1, path2), path3); + } + + public static String jsonRemove(String json, String path1, String path2, String path3, String path4) throws IOException { + return jsonRemove(jsonRemove(json, path1, path2, path3), path4); + } + + public static String jsonRemove( + String json, + String path1, + String path2, + String path3, + String path4, + String path5 + ) throws IOException { + return jsonRemove(jsonRemove(json, path1, path2, path3, path4), path5); + } + + public static String jsonExtract(String json, String path) throws IOException { + if (json == null || json.isBlank()) { + return null; + } + JsonNode current = OBJECT_MAPPER.readTree(json); + for (String token : tokenizePath(path)) { + if (current == null) { + return null; + } + current = current.get(token); + } + if (current == null || current.isNull()) { + return null; + } + if (current.isTextual()) { + return current.textValue(); + } + if (current.isNumber() || current.isBoolean()) { + return current.asText(); + } + return OBJECT_MAPPER.writeValueAsString(current); + } + + public static String jsonUnquote(String value) { + if (value == null) { + return null; + } + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + return value.substring(1, value.length() - 1); + } + return value; + } + + public static String filterProviderFields(String json, String keyToRemove) throws IOException { + if (json == null || json.isBlank()) { + return json; + } + JsonNode node = OBJECT_MAPPER.readTree(json); + if (!(node instanceof ArrayNode arrayNode)) { + return json; + } + + ArrayNode filtered = OBJECT_MAPPER.createArrayNode(); + for (JsonNode item : arrayNode) { + if (!item.isObject()) { + filtered.add(item); + continue; + } + String key = item.path("key").asText(); + if (!keyToRemove.equals(key)) { + filtered.add(item); + } + } + return OBJECT_MAPPER.writeValueAsString(filtered); + } + + private static ObjectNode asObjectNode(String json) throws IOException { + if (json == null || json.isBlank()) { + return OBJECT_MAPPER.createObjectNode(); + } + JsonNode node = OBJECT_MAPPER.readTree(json); + if (node instanceof ObjectNode objectNode) { + return objectNode; + } + return OBJECT_MAPPER.createObjectNode(); + } + + private static void setJsonPath(ObjectNode root, String path, String value) throws IOException { + String[] tokens = tokenizePath(path); + ObjectNode current = root; + for (int i = 0; i < tokens.length - 1; i++) { + JsonNode next = current.get(tokens[i]); + if (!(next instanceof ObjectNode)) { + next = OBJECT_MAPPER.createObjectNode(); + current.set(tokens[i], next); + } + current = (ObjectNode) next; + } + current.set(tokens[tokens.length - 1], coerceJsonValue(value)); + } + + private static String[] tokenizePath(String path) { + return path.replaceFirst("^\\$\\.", "").split("\\."); + } + + private static JsonNode coerceJsonValue(String value) throws IOException { + if (value == null) { + return OBJECT_MAPPER.nullNode(); + } + String trimmed = value.trim(); + if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) { + return OBJECT_MAPPER.readTree(trimmed); + } + if ("null".equalsIgnoreCase(trimmed)) { + return OBJECT_MAPPER.nullNode(); + } + if ("true".equalsIgnoreCase(trimmed) || "false".equalsIgnoreCase(trimmed)) { + return OBJECT_MAPPER.valueToTree(Boolean.parseBoolean(trimmed)); + } + if (trimmed.matches("-?\\d+")) { + try { + return OBJECT_MAPPER.valueToTree(Integer.parseInt(trimmed)); + } catch (NumberFormatException ignored) { + return OBJECT_MAPPER.valueToTree(Long.parseLong(trimmed)); + } + } + if (trimmed.matches("-?\\d+\\.\\d+")) { + return OBJECT_MAPPER.valueToTree(Double.parseDouble(trimmed)); + } + return OBJECT_MAPPER.valueToTree(value); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/LiquibaseWesternizationIntegrationTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/LiquibaseWesternizationIntegrationTest.java new file mode 100644 index 000000000..c19f162ae --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/LiquibaseWesternizationIntegrationTest.java @@ -0,0 +1,578 @@ +package xiaozhi.modules.sys; + +import liquibase.Contexts; +import liquibase.LabelExpression; +import liquibase.Liquibase; +import liquibase.database.Database; +import liquibase.database.DatabaseFactory; +import liquibase.database.jvm.JdbcConnection; +import liquibase.resource.DirectoryResourceAccessor; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class LiquibaseWesternizationIntegrationTest { + + private static final String JDBC_URL = + "jdbc:h2:mem:liquibase_westernization;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"; + private static final Pattern HAN_PATTERN = Pattern.compile("\\p{IsHan}"); + private static final Pattern CHINESE_TOKEN_PATTERN = Pattern.compile("zh-CN|zh-HK|zh_cn|中文|小智|天气|新闻|角色|模板"); + @Test + void shouldApplyAllChangelogsAndProduceWesternizedSeedData() throws Exception { + try (Connection migrationConnection = DriverManager.getConnection(JDBC_URL, "sa", "")) { + applyLiquibase(migrationConnection); + } + + try (Connection verificationConnection = DriverManager.getConnection(JDBC_URL, "sa", "")) { + writeSeedDump(verificationConnection); + + assertLatestChangeSetApplied(verificationConnection); + assertRequiredSeedCoverage(verificationConnection); + assertWesternizationRules(verificationConnection); + } + } + + private void applyLiquibase(Connection connection) throws Exception { + Path changelogRoot = prepareH2ChangelogWorkspace(); + createH2CompatibilityAliases(connection); + try (JdbcConnection jdbcConnection = new JdbcConnection(connection)) { + Database database = DatabaseFactory.getInstance() + .findCorrectDatabaseImplementation(jdbcConnection); + Liquibase liquibase = new Liquibase( + "db.changelog-master.yaml", + new DirectoryResourceAccessor(changelogRoot), + database + ); + liquibase.update(new Contexts(), new LabelExpression()); + } + } + + private void createH2CompatibilityAliases(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute( + "CREATE ALIAS IF NOT EXISTS JSON_SET FOR " + + "'xiaozhi.modules.sys.H2JsonFunctions.jsonSet'" + ); + statement.execute( + "CREATE ALIAS IF NOT EXISTS JSON_REMOVE FOR " + + "'xiaozhi.modules.sys.H2JsonFunctions.jsonRemove'" + ); + statement.execute( + "CREATE ALIAS IF NOT EXISTS JSON_EXTRACT FOR " + + "'xiaozhi.modules.sys.H2JsonFunctions.jsonExtract'" + ); + statement.execute( + "CREATE ALIAS IF NOT EXISTS JSON_UNQUOTE FOR " + + "'xiaozhi.modules.sys.H2JsonFunctions.jsonUnquote'" + ); + statement.execute( + "CREATE ALIAS IF NOT EXISTS FILTER_PROVIDER_FIELDS FOR " + + "'xiaozhi.modules.sys.H2JsonFunctions.filterProviderFields'" + ); + } + } + + private Path prepareH2ChangelogWorkspace() throws IOException { + Path sourceRoot = Path.of("src", "main", "resources", "db", "changelog").toAbsolutePath().normalize(); + Path workspace = Path.of("target", "liquibase-h2-changelog").toAbsolutePath().normalize(); + + if (Files.exists(workspace)) { + try (var paths = Files.walk(workspace)) { + paths.sorted((left, right) -> right.getNameCount() - left.getNameCount()) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + } + + Files.createDirectories(workspace); + try (var paths = Files.walk(sourceRoot)) { + paths.forEach(source -> { + try { + Path relative = sourceRoot.relativize(source); + Path target = workspace.resolve(relative.toString()); + if (Files.isDirectory(source)) { + Files.createDirectories(target); + } else if (source.getFileName().toString().endsWith(".yaml")) { + String yaml = Files.readString(source); + yaml = yaml.replace("path: classpath:db/changelog/", "path: "); + Files.writeString(target, yaml, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + } else if (source.getFileName().toString().endsWith(".sql")) { + String sql = normalizeSqlForH2(Files.readString(source), source.getFileName().toString()); + Files.writeString(target, sql, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + } else { + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + return workspace; + } + + private String normalizeSqlForH2(String sql, String fileName) { + String normalized = sql; + normalized = normalized.replaceAll("(?im)(INDEX\\s+`[^`]+`\\s*\\([^\\n]+\\))\\s+COMMENT\\s+'[^']*'", "$1"); + normalized = normalized.replaceAll("(?im)(UNIQUE\\s+KEY\\s+`[^`]+`\\s*\\([^\\n]+\\))\\s+COMMENT\\s+'[^']*'", "$1"); + normalized = normalized.replaceAll("(?im)(KEY\\s+`[^`]+`\\s*\\([^\\n]+\\))\\s+COMMENT\\s+'[^']*'", "$1"); + normalized = normalized.replaceAll("(?im)\\)\\s*ENGINE=.*?;", ");"); + normalized = normalized.replaceAll("(?i)\\s+ON\\s+UPDATE\\s+CURRENT_TIMESTAMP(?:\\(\\d+\\))?", ""); + normalized = normalized.replaceAll("(?im)^\\s*START\\s+TRANSACTION\\s*;?\\s*$", ""); + normalized = normalized.replaceAll("(?im)^\\s*COMMIT\\s*;?\\s*$", ""); + normalized = normalized.replaceAll("(?i)\\s+AFTER\\s+`[^`]+`", ""); + normalized = rewriteConditionalAddColumnBlocks(normalized); + normalized = normalized.replace("TINYINT UNSIGNED", "TINYINT"); + normalized = normalized.replace("INT UNSIGNED", "INT"); + normalized = normalized.replace("BIGINT UNSIGNED", "BIGINT"); + normalized = normalized.replace("tinyint unsigned", "tinyint"); + normalized = normalized.replace("int unsigned", "int"); + normalized = normalized.replace("bigint unsigned", "bigint"); + normalized = rewriteCreateTableIndexNames(normalized); + if ("202601141645.sql".equals(fileName)) { + normalized = normalized.replaceAll( + "(?s)UPDATE `ai_model_provider` ap\\s+JOIN \\(.*?\\) filtered ON ap\\.id = filtered\\.id\\s+SET ap\\.fields = filtered\\.new_fields;", + Matcher.quoteReplacement(""" +UPDATE `ai_model_provider` ap +SET ap.fields = FILTER_PROVIDER_FIELDS(ap.`fields`, 'sample_rate') +WHERE ap.`model_type` = 'TTS'; +""") + ); + } + if ("202603091051.sql".equals(fileName)) { + normalized = normalized.replaceAll( + "(?s)SET @col_exists = .*?COLUMN_NAME = 'sort'\\);\\s*" + + "SET @sql = IF\\(@col_exists > 0 AND \\(SELECT COUNT\\(\\*\\) FROM ai_agent_tag_relation WHERE sort = 0\\) > 0,\\s*" + + "'UPDATE ai_agent_tag_relation r INNER JOIN \\(SELECT id, ROW_NUMBER\\(\\) OVER \\(PARTITION BY agent_id ORDER BY created_at\\) AS row_num FROM ai_agent_tag_relation\\) t ON r\\.id = t\\.id SET r\\.sort = t\\.row_num',\\s*" + + "'SELECT ''No need to update or column does not exist'' AS msg'\\);\\s*" + + "PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;", + Matcher.quoteReplacement(""" +UPDATE ai_agent_tag_relation r +SET sort = ( + SELECT ranked.row_num + FROM ( + SELECT id, ROW_NUMBER() OVER (PARTITION BY agent_id ORDER BY created_at) AS row_num + FROM ai_agent_tag_relation + ) ranked + WHERE ranked.id = r.id +) +WHERE r.sort = 0; +""") + ); + } + if (fileName.compareTo("202506091720.sql") >= 0) { + normalized = normalized.replace( + "INSERT INTO `ai_tts_voice` VALUES", + "INSERT INTO `ai_tts_voice` (`id`, `tts_model_id`, `name`, `tts_voice`, `languages`, `voice_demo`, `remark`, `reference_audio`, `reference_text`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES" + ); + } + normalized = splitMultiAddColumnAlterStatements(normalized); + normalized = normalizeJsonSetCalls(normalized); + return normalized; + } + + private String splitMultiAddColumnAlterStatements(String sql) { + Pattern pattern = Pattern.compile( + "(?is)ALTER\\s+TABLE\\s+(`?\\w+`?)\\s+(ADD\\s+COLUMN\\s+.*?),(\\s*ADD\\s+COLUMN\\s+.*?);" + ); + + String normalized = sql; + while (true) { + Matcher matcher = pattern.matcher(normalized); + if (!matcher.find()) { + return normalized; + } + String replacement = + "ALTER TABLE " + matcher.group(1) + " " + matcher.group(2) + ";\n" + + "ALTER TABLE " + matcher.group(1) + " " + matcher.group(3).trim() + ";"; + normalized = matcher.replaceFirst(Matcher.quoteReplacement(replacement)); + } + } + + private String normalizeJsonSetCalls(String sql) { + String marker = "JSON_SET("; + StringBuilder normalized = new StringBuilder(); + int cursor = 0; + while (true) { + int start = sql.indexOf(marker, cursor); + if (start < 0) { + normalized.append(sql.substring(cursor)); + return normalized.toString(); + } + normalized.append(sql, cursor, start); + int end = findMatchingParenthesis(sql, start + marker.length() - 1); + String body = sql.substring(start + marker.length(), end); + normalized.append("JSON_SET(").append(rewriteJsonSetBody(body)).append(")"); + cursor = end + 1; + } + } + + private String rewriteConditionalAddColumnBlocks(String sql) { + Pattern pattern = Pattern.compile( + "(?s)SET @col_exists = .*?;\\s*" + + "SET @sql = IF\\(@col_exists = 0, '(ALTER TABLE .*?)', 'SELECT .*?' AS msg'\\);\\s*" + + "PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;" + ); + + Matcher matcher = pattern.matcher(sql); + StringBuffer rewritten = new StringBuffer(); + while (matcher.find()) { + String statement = matcher.group(1).replace("''", "'"); + statement = statement.replaceAll("(?i)\\s+COMMENT\\s+'[^']*'", ""); + statement = statement.replaceAll("(?i)\\s+AFTER\\s+`[^`]+`", ""); + statement = statement.replaceFirst("(?i)ADD\\s+COLUMN\\s+", "ADD COLUMN IF NOT EXISTS "); + matcher.appendReplacement(rewritten, Matcher.quoteReplacement(statement + ";")); + } + matcher.appendTail(rewritten); + return rewritten.toString(); + } + + private String rewriteCreateTableIndexNames(String sql) { + Pattern tablePattern = Pattern.compile("(?is)CREATE\\s+TABLE\\s+IF\\s+NOT\\s+EXISTS\\s+`?(\\w+)`?\\s*\\((.*?)\\);"); + Matcher matcher = tablePattern.matcher(sql); + StringBuffer rewritten = new StringBuffer(); + while (matcher.find()) { + String tableName = matcher.group(1); + String tableBody = matcher.group(2); + tableBody = tableBody.replaceAll( + "(?im)(\\bINDEX\\s+)`?(\\w+)`?(\\s*\\()", + "$1" + tableName + "_$2$3" + ); + matcher.appendReplacement( + rewritten, + Matcher.quoteReplacement("CREATE TABLE IF NOT EXISTS " + tableName + " (" + tableBody + ");") + ); + } + matcher.appendTail(rewritten); + return rewritten.toString(); + } + + private String rewriteJsonSetBody(String body) { + List parts = splitTopLevelCommaSeparated(body); + for (int i = 2; i < parts.size(); i += 2) { + String value = parts.get(i).trim(); + parts.set(i, "CAST(" + value + " AS VARCHAR)"); + } + return String.join(", ", parts); + } + + private int findMatchingParenthesis(String sql, int openParenIndex) { + int depth = 0; + boolean inSingleQuote = false; + boolean inDoubleQuote = false; + for (int i = openParenIndex; i < sql.length(); i++) { + char c = sql.charAt(i); + if (c == '\'' && !inDoubleQuote && !isEscaped(sql, i)) { + inSingleQuote = !inSingleQuote; + continue; + } + if (c == '"' && !inSingleQuote && !isEscaped(sql, i)) { + inDoubleQuote = !inDoubleQuote; + continue; + } + if (inSingleQuote || inDoubleQuote) { + continue; + } + if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + if (depth == 0) { + return i; + } + } + } + throw new IllegalArgumentException("Unbalanced JSON_SET expression in rewritten changelog SQL"); + } + + private List splitTopLevelCommaSeparated(String value) { + List parts = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int depth = 0; + boolean inSingleQuote = false; + boolean inDoubleQuote = false; + + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '\'' && !inDoubleQuote && !isEscaped(value, i)) { + inSingleQuote = !inSingleQuote; + current.append(c); + continue; + } + if (c == '"' && !inSingleQuote && !isEscaped(value, i)) { + inDoubleQuote = !inDoubleQuote; + current.append(c); + continue; + } + if (!inSingleQuote && !inDoubleQuote) { + if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + } else if (c == ',' && depth == 0) { + parts.add(current.toString().trim()); + current.setLength(0); + continue; + } + } + current.append(c); + } + parts.add(current.toString().trim()); + return parts; + } + + private boolean isEscaped(String value, int index) { + int backslashCount = 0; + for (int i = index - 1; i >= 0 && value.charAt(i) == '\\'; i--) { + backslashCount++; + } + return backslashCount % 2 == 1; + } + + private void writeSeedDump(Connection connection) throws IOException, SQLException { + Path dumpPath = Path.of("target", "liquibase-h2-seed-dump.txt"); + Files.createDirectories(dumpPath.getParent()); + + List lines = new ArrayList<>(); + dumpTable(connection, lines, "DATABASECHANGELOG", + "SELECT ID, AUTHOR, FILENAME, ORDEREXECUTED FROM DATABASECHANGELOG ORDER BY ORDEREXECUTED"); + dumpTable(connection, lines, "sys_params", + "SELECT param_code, param_value, remark FROM sys_params ORDER BY param_code"); + dumpTable(connection, lines, "sys_dict_type", + "SELECT id, dict_type, dict_name, remark FROM sys_dict_type ORDER BY id"); + dumpTable(connection, lines, "sys_dict_data", + "SELECT id, dict_type_id, dict_label, dict_value, remark FROM sys_dict_data ORDER BY id"); + dumpTable(connection, lines, "ai_model_provider", + "SELECT id, model_type, provider_code, name, fields FROM ai_model_provider ORDER BY id"); + dumpTable(connection, lines, "ai_model_config", + "SELECT id, model_type, model_code, model_name, is_enabled, config_json, remark FROM ai_model_config ORDER BY id"); + dumpTable(connection, lines, "ai_agent_template", + "SELECT id, agent_code, agent_name, lang_code, language, sort FROM ai_agent_template ORDER BY sort, id"); + dumpTable(connection, lines, "ai_tts_voice", + "SELECT id, tts_model_id, name, tts_voice, languages FROM ai_tts_voice ORDER BY tts_model_id, sort, id"); + + Files.write( + dumpPath, + lines, + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); + } + + private void dumpTable(Connection connection, List lines, String title, String sql) throws SQLException { + lines.add("== " + title + " =="); + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + while (resultSet.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= columnCount; i++) { + if (i > 1) { + row.append(" | "); + } + row.append(metaData.getColumnLabel(i)).append('=').append(resultSet.getString(i)); + } + lines.add(row.toString()); + } + } + lines.add(""); + } + + private void assertLatestChangeSetApplied(Connection connection) throws SQLException { + String latestId = scalar(connection, "SELECT MAX(ID) FROM DATABASECHANGELOG"); + Assertions.assertEquals("202604021100", latestId, "latest downstream cleanup migration should be applied"); + } + + private void assertRequiredSeedCoverage(Connection connection) throws SQLException { + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'server.name' AND param_value = 'xiaozhi-esp32-server'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'exit_commands' AND param_value = 'exit;close'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_weather.default_location' AND param_value = 'New York'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_news.default_rss_url' AND param_value = 'https://feeds.reuters.com/reuters/worldNews'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.home_assistant.devices' AND param_value LIKE 'Living Room,%Bedroom,%'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'end_prompt.prompt' AND param_value LIKE 'Please start with \"Time flies so fast\"%'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'system_error_response' AND param_value LIKE 'The assistant is temporarily busy right now.%'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'twilio.sms.account_sid'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'twilio.sms.auth_token'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'twilio.sms.phone_number'"); + assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'twilio.sms.template_message' AND param_value = 'Your verification code is: %s'"); + + assertExists(connection, "SELECT 1 FROM sys_dict_type WHERE id = 101 AND dict_name = 'Firmware Type'"); + assertExists(connection, "SELECT 1 FROM sys_dict_type WHERE id = 102 AND dict_name = 'Mobile Area'"); + assertExists(connection, "SELECT 1 FROM sys_dict_data WHERE id = 101001 AND dict_label = 'Breadboard New Wiring (WiFi)'"); + assertExists(connection, "SELECT 1 FROM sys_dict_data WHERE id = 102005 AND dict_label = 'USA/Canada'"); + + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_WEATHER' AND name = 'Weather Service'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_NEWS' AND name = 'News Service'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_HA_GET_STATE' AND name = 'HomeAssistant Device Status Query'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_HA_GET_CALENDAR' AND name = 'Standard Calendar Information Service'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_CHANGE_ROLE' AND name = 'Role Switching Service'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_GeminiASR' AND name = 'Gemini Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_GroqASR' AND name = 'Groq Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_OpenaiASR' AND name = 'OpenAI Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_WhisperASR' AND name = 'OpenAI Whisper Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_VoskASR' AND name = 'VOSK Offline Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_TTS_elevenlabs' AND name = 'ElevenLabs TTS'"); + assertExists(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_TTS_kokoro' AND name = 'Kokoro TTS'"); + + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_GeminiASR' AND model_name = 'Gemini Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_GroqASR' AND model_name = 'Groq Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_OpenaiASR' AND model_name = 'OpenAI Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_WhisperASR' AND model_name = 'OpenAI Whisper Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_VoskASR' AND model_name = 'VOSK Offline Speech Recognition'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'Intent_intent_llm' AND config_json LIKE '%LLM_OpenAILLM%'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'LLM_OpenAILLM' AND model_name = 'OpenAI GPT'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'TTS_EdgeTTS' AND config_json LIKE '%en-US-AriaNeural%'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'TTS_ElevenLabsTTS' AND model_name = 'ElevenLabs TTS'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'TTS_KokoroTTS' AND model_name = 'Kokoro TTS'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'VLLM_GeminiVLLM' AND model_name = 'Google Gemini Vision AI'"); + assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'VLLM_OpenAILLMVLLM' AND model_name = 'OpenAI Vision Model'"); + + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_EdgeTTS_EN001' AND name = 'Aria' AND tts_voice = 'en-US-AriaNeural'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_EdgeTTS_EN002' AND name = 'Guy'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_EdgeTTS_EN003' AND name = 'Sonia'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_OpenAITTS0002' AND name = 'Alloy'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_OpenAITTS0006' AND name = 'Shimmer'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_ElevenLabs_0001' AND name = 'Rachel'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_ElevenLabs_0018' AND name = 'Grace'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_Kokoro_0001' AND name = 'Alloy'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_Kokoro_0032' AND name = 'Kumo'"); + assertExists(connection, "SELECT 1 FROM ai_tts_voice WHERE id = 'TTS_Kokoro_0043' AND name = 'Nicola'"); + assertCount(connection, "SELECT COUNT(*) FROM ai_tts_voice WHERE tts_model_id = 'TTS_EdgeTTS'", 10, "Edge TTS voice parity should be restored"); + assertCount(connection, "SELECT COUNT(*) FROM ai_tts_voice WHERE tts_model_id = 'TTS_OpenAITTS'", 6, "OpenAI TTS voice parity should be restored"); + assertCount(connection, "SELECT COUNT(*) FROM ai_tts_voice WHERE tts_model_id = 'TTS_ElevenLabsTTS'", 18, "ElevenLabs TTS voice parity should be restored"); + assertCount(connection, "SELECT COUNT(*) FROM ai_tts_voice WHERE tts_model_id = 'TTS_KokoroTTS'", 35, "Kokoro non-Chinese voice parity should be restored"); + + assertExists(connection, "SELECT 1 FROM ai_agent_template WHERE id = '9406648b5cc5fde1b8aa335b6f8b4f76' AND agent_name = 'Tech-Savvy Girl' AND lang_code = 'en'"); + assertExists(connection, "SELECT 1 FROM ai_agent_template WHERE id = '0ca32eb728c949e58b1000b2e401f90c' AND agent_name = 'Stellar Wanderer' AND lang_code = 'en'"); + assertExists(connection, "SELECT 1 FROM ai_agent_template WHERE id = '6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24' AND agent_name = 'English Teacher' AND lang_code = 'en'"); + assertExists(connection, "SELECT 1 FROM ai_agent_template WHERE id = 'e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1' AND agent_name = 'Curious Boy' AND lang_code = 'en'"); + assertExists(connection, "SELECT 1 FROM ai_agent_template WHERE id = 'a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92' AND agent_name = 'Paw Patrol Captain' AND lang_code = 'en'"); + } + + private void assertWesternizationRules(Connection connection) throws SQLException { + assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_NEWS_CHINANEWS'"); + assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_NEWS_NEWSNOW'"); + assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_SherpaASR'"); + assertMissing(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_SherpaASR'"); + assertMissing(connection, "SELECT 1 FROM ai_tts_voice WHERE tts_model_id = 'TTS_EdgeTTS' AND (tts_voice LIKE 'zh-CN-%' OR tts_voice LIKE 'zh-HK-%')"); + + assertZero(connection, + "SELECT COUNT(*) FROM ai_model_provider WHERE REGEXP_LIKE(COALESCE(name, '') || COALESCE(fields, ''), '[\\p{IsHan}]')", + "provider rows should not contain Han-script"); + assertZero(connection, + "SELECT COUNT(*) FROM ai_model_config WHERE REGEXP_LIKE(COALESCE(model_name, '') || COALESCE(remark, '') || COALESCE(CAST(config_json AS VARCHAR), ''), '[\\p{IsHan}]')", + "model config rows should not contain Han-script"); + assertZero(connection, + "SELECT COUNT(*) FROM ai_agent_template WHERE REGEXP_LIKE(COALESCE(agent_code, '') || COALESCE(agent_name, '') || COALESCE(system_prompt, '') || COALESCE(language, ''), '[\\p{IsHan}]')", + "agent template rows should not contain Han-script"); + assertZero(connection, + "SELECT COUNT(*) FROM sys_params WHERE REGEXP_LIKE(COALESCE(param_value, '') || COALESCE(remark, ''), '[\\p{IsHan}]')", + "sys_params rows should not contain Han-script"); + assertZero(connection, + "SELECT COUNT(*) FROM sys_dict_type WHERE REGEXP_LIKE(COALESCE(dict_name, '') || COALESCE(remark, ''), '[\\p{IsHan}]')", + "sys_dict_type rows should not contain Han-script"); + assertZero(connection, + "SELECT COUNT(*) FROM sys_dict_data WHERE REGEXP_LIKE(COALESCE(dict_label, '') || COALESCE(remark, ''), '[\\p{IsHan}]')", + "sys_dict_data rows should not contain Han-script"); + + assertZero(connection, + "SELECT COUNT(*) FROM ai_tts_voice WHERE REGEXP_LIKE(COALESCE(name, '') || COALESCE(languages, ''), '[\\p{IsHan}]')", + "tts voice rows should not contain Han-script"); + + assertZero(connection, + "SELECT COUNT(*) FROM ai_tts_voice WHERE languages LIKE '%中文%' OR languages LIKE '%普通话%' OR languages LIKE '%粤语%'", + "tts voice language labels should be westernized"); + + assertNoChineseTokens(connection, "sys_params", "SELECT param_code, param_value, remark FROM sys_params"); + assertNoChineseTokens(connection, "ai_model_provider", "SELECT id, name, fields FROM ai_model_provider"); + assertNoChineseTokens(connection, "ai_model_config", "SELECT id, model_name, config_json, remark FROM ai_model_config"); + assertNoChineseTokens(connection, "ai_agent_template", "SELECT id, agent_code, agent_name, system_prompt, language FROM ai_agent_template"); + assertNoChineseTokens(connection, "ai_tts_voice", "SELECT id, name, tts_voice, languages FROM ai_tts_voice"); + } + + private void assertNoChineseTokens(Connection connection, String table, String sql) throws SQLException { + List offenders = new ArrayList<>(); + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + while (resultSet.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= columnCount; i++) { + String value = resultSet.getString(i); + if (value != null && (HAN_PATTERN.matcher(value).find() || CHINESE_TOKEN_PATTERN.matcher(value).find())) { + row.setLength(0); + for (int j = 1; j <= columnCount; j++) { + if (j > 1) { + row.append(" | "); + } + row.append(metaData.getColumnLabel(j)).append('=').append(resultSet.getString(j)); + } + offenders.add(row.toString()); + break; + } + } + } + } + + Assertions.assertTrue( + offenders.isEmpty(), + table + " should not contain downstream-forbidden Chinese content.\nOffenders:\n" + String.join("\n", offenders) + ); + } + + private void assertExists(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + Assertions.assertTrue(resultSet.next(), "expected row missing for query: " + sql); + } + } + + private void assertMissing(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + Assertions.assertFalse(resultSet.next(), "unexpected row present for query: " + sql); + } + } + + private void assertZero(Connection connection, String sql, String message) throws SQLException { + String value = scalar(connection, sql); + Assertions.assertEquals("0", value, message + " (query: " + sql + ")"); + } + + private void assertCount(Connection connection, String sql, int expected, String message) throws SQLException { + String value = scalar(connection, sql); + Assertions.assertEquals(String.valueOf(expected), value, message + " (query: " + sql + ")"); + } + + private String scalar(Connection connection, String sql) throws SQLException { + try (PreparedStatement preparedStatement = connection.prepareStatement(sql); + ResultSet resultSet = preparedStatement.executeQuery()) { + Assertions.assertTrue(resultSet.next(), "query returned no rows: " + sql); + return resultSet.getString(1); + } + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java index 1175223b5..1f848eb4f 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java @@ -1,11 +1,14 @@ package xiaozhi.modules.sys; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.context.annotation.Import; import lombok.extern.slf4j.Slf4j; +import xiaozhi.config.TestConfig; import xiaozhi.modules.security.controller.LoginController; import xiaozhi.modules.security.dto.LoginDTO; import xiaozhi.modules.security.dto.SmsVerificationDTO; @@ -13,7 +16,8 @@ import xiaozhi.modules.sys.dto.RetrievePasswordDTO; @Slf4j @SpringBootTest -@ActiveProfiles("dev") +@ActiveProfiles("test") +@Import(TestConfig.class) class loginControllerTest { @Autowired @@ -22,16 +26,16 @@ class loginControllerTest { @Test public void testRegister() { LoginDTO loginDTO = new LoginDTO(); - loginDTO.setUsername("手机号码"); - loginDTO.setPassword("密码"); - loginController.register(loginDTO); + loginDTO.setUsername("test-user"); + loginDTO.setPassword("test-password"); + Assertions.assertThrows(Exception.class, () -> loginController.register(loginDTO)); } @Test public void testSmsVerification() { try { SmsVerificationDTO smsVerificationDTO = new SmsVerificationDTO(); - smsVerificationDTO.setPhone("手机号码"); + smsVerificationDTO.setPhone("+15551234567"); smsVerificationDTO.setCaptchaId("123456"); smsVerificationDTO.setCaptcha("123456"); loginController.smsVerification(smsVerificationDTO); @@ -45,8 +49,8 @@ class loginControllerTest { try { RetrievePasswordDTO retrievePasswordDTO = new RetrievePasswordDTO(); retrievePasswordDTO.setCode("123456"); - retrievePasswordDTO.setPhone("手机号码"); - retrievePasswordDTO.setPassword("密码"); + retrievePasswordDTO.setPhone("+15551234567"); + retrievePasswordDTO.setPassword("test-password"); loginController.retrievePassword(retrievePasswordDTO); } catch (Exception e) { System.out.println(e.getMessage()); @@ -54,4 +58,4 @@ class loginControllerTest { } -} \ No newline at end of file +} diff --git a/main/manager-api/src/test/resources/application-test.yml b/main/manager-api/src/test/resources/application-test.yml new file mode 100644 index 000000000..a5f74d45e --- /dev/null +++ b/main/manager-api/src/test/resources/application-test.yml @@ -0,0 +1,90 @@ +spring: + task: + scheduling: + enabled: false + datasource: + druid: + # H2 Database for testing + driver-class-name: org.h2.Driver + url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL + username: sa + password: + initial-size: 1 + max-active: 5 + min-idle: 1 + max-wait: 6000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: false + filter: + stat: + log-slow-sql: false + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + # Initialize database schema + sql: + init: + mode: always + schema-locations: classpath:schema.sql + continue-on-error: true + # Disable Liquibase for testing + liquibase: + enabled: false + # Disable Redis for testing - will be mocked + data: + redis: + host: localhost + port: 6379 + database: 0 + timeout: 10s + lettuce: + pool: + min-idle: 0 + max-idle: 8 + max-active: 8 + max-wait: -1ms + # H2 console for debugging (optional) + h2: + console: + enabled: true + path: /h2-console + +# Disable Redis for testing +renren: + redis: + open: false + +# MyBatis Plus configuration for testing +mybatis-plus: + mapper-locations: classpath*:/mapper/**/*.xml + typeAliasesPackage: xiaozhi.modules.*.entity + global-config: + db-config: + id-type: ASSIGN_ID + banner: false + configuration: + map-underscore-to-camel-case: true + cache-enabled: false + call-setters-on-nulls: true + jdbc-type-for-null: 'null' + configuration-properties: + prefix: + blobType: BLOB + boolValue: TRUE + +# Logging configuration for testing +logging: + level: + xiaozhi.modules.device: DEBUG + org.springframework.data.redis: WARN + org.springframework.boot.autoconfigure: WARN + com.alibaba.druid: WARN diff --git a/main/manager-api/src/test/resources/schema.sql b/main/manager-api/src/test/resources/schema.sql new file mode 100644 index 000000000..5888f71d4 --- /dev/null +++ b/main/manager-api/src/test/resources/schema.sql @@ -0,0 +1,102 @@ +-- H2 Database schema for testing +-- This script creates the necessary tables for testing + +-- Create sys_user table +CREATE TABLE IF NOT EXISTS sys_user ( + id BIGINT PRIMARY KEY, + username VARCHAR(50) NOT NULL, + password VARCHAR(100), + salt VARCHAR(20), + mobile VARCHAR(20), + super_admin TINYINT DEFAULT 0, + status TINYINT DEFAULT 1, + updater BIGINT, + update_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + creator BIGINT, + create_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Create sys_role table +CREATE TABLE IF NOT EXISTS sys_role ( + id BIGINT PRIMARY KEY, + name VARCHAR(50) NOT NULL, + remark VARCHAR(100), + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Create sys_user_role table +CREATE TABLE IF NOT EXISTS sys_user_role ( + id BIGINT PRIMARY KEY, + user_id BIGINT NOT NULL, + role_id BIGINT NOT NULL, + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES sys_user(id), + FOREIGN KEY (role_id) REFERENCES sys_role(id) +); + +-- Create sys_menu table +CREATE TABLE IF NOT EXISTS sys_menu ( + id BIGINT PRIMARY KEY, + parent_id BIGINT, + name VARCHAR(50) NOT NULL, + url VARCHAR(200), + perms VARCHAR(500), + type TINYINT, + icon VARCHAR(50), + order_num INT, + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Create sys_role_menu table +CREATE TABLE IF NOT EXISTS sys_role_menu ( + id BIGINT PRIMARY KEY, + role_id BIGINT NOT NULL, + menu_id BIGINT NOT NULL, + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (role_id) REFERENCES sys_role(id), + FOREIGN KEY (menu_id) REFERENCES sys_menu(id) +); + +-- Create device_info table +CREATE TABLE IF NOT EXISTS device_info ( + id BIGINT PRIMARY KEY, + mac_address VARCHAR(50) NOT NULL, + device_code VARCHAR(50), + board VARCHAR(100), + app_version VARCHAR(50), + status TINYINT DEFAULT 1, + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Create sys_params table +CREATE TABLE IF NOT EXISTS sys_params ( + id BIGINT PRIMARY KEY, + param_code VARCHAR(50) NOT NULL, + param_value VARCHAR(500), + remark VARCHAR(200), + create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Insert test data +INSERT INTO sys_user (id, username, password, salt, mobile, status) VALUES +(1, 'admin', 'admin123', 'salt123', '13800138000', 1), +(2, 'test', 'test123', 'salt456', '13800138001', 1); + +INSERT INTO sys_role (id, name, remark) VALUES +(1, 'admin', 'Administrator'), +(2, 'user', 'Regular User'); + +INSERT INTO sys_user_role (id, user_id, role_id) VALUES +(1, 1, 1), +(2, 2, 2); + +-- Insert test system parameters +INSERT INTO sys_params (id, param_code, param_value, remark) VALUES +(1, 'server.allow_user_register', 'true', 'Allow user registration'), +(2, 'server.enable_mobile_register', 'false', 'Enable mobile registration'), +(3, 'DEFAULT_PASSWORD', '123456', 'Default password for new users'), +(4, 'SESSION_TIMEOUT', '1800', 'Session timeout in seconds'); \ No newline at end of file